lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
|---|---|---|---|---|---|---|---|---|---|---|---|
Java
|
apache-2.0
|
adc41eda6f410141028d2e2cbd9022d78cb5e4a9
| 0
|
Esri/arcgis-runtime-samples-java
|
/*
* Copyright 2018 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.samples.featurelayers.time_based_query;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.TimeExtent;
import com.esri.arcgisruntime.mapping.view.MapView;
public class TimeBasedQuerySample extends Application {
private MapView mapView;
@Override
public void start(Stage stage) throws Exception {
try {
// create stack pane and application scene
StackPane stackPane = new StackPane();
Scene scene = new Scene(stackPane);
// size the stage, add a title, and set scene to stage
stage.setTitle("Time Based Query Sample");
stage.setWidth(800);
stage.setHeight(700);
stage.setScene(scene);
stage.show();
// create a map and set it to a map view
mapView = new MapView();
ArcGISMap map = new ArcGISMap(Basemap.createOceans());
mapView.setMap(map);
// create a feature table with the URL of the feature service
String serviceURL = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Hurricanes/MapServer/0";
ServiceFeatureTable serviceFeatureTable = new ServiceFeatureTable(serviceURL);
// define the request mode to manual
serviceFeatureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.MANUAL_CACHE);
// load the table and set the query
serviceFeatureTable.addDoneLoadingListener(() -> {
if (serviceFeatureTable.getLoadStatus() == LoadStatus.LOADED) {
// create query parameters
QueryParameters queryParameters = new QueryParameters();
// set a time extent (beginning of time to September 16th, 2000)
Calendar beg = new Calendar.Builder().setDate(1, 1, 1).build();
Calendar end = new Calendar.Builder().setDate(2000, 9, 16).build();
TimeExtent timeExtent = new TimeExtent(beg, end);
queryParameters.setTimeExtent(timeExtent);
// return all fields
List<String> outputFields = Collections.singletonList("*");
// populate the service with features that fit the time extent, when done zoom to the layer's extent
serviceFeatureTable.populateFromServiceAsync(queryParameters, true, outputFields).addDoneListener(() -> {
mapView.setViewpointGeometryAsync(serviceFeatureTable.getExtent());
});
} else {
new Alert(Alert.AlertType.ERROR, serviceFeatureTable.getLoadError().getMessage()).show();
}
});
// create the feature layer using the service feature table
FeatureLayer featureLayer = new FeatureLayer(serviceFeatureTable);
// add the layer to the map
map.getOperationalLayers().add(featureLayer);
// add the map view to stack pane
stackPane.getChildren().addAll(mapView);
} catch (Exception e) {
// on any error, display stack trace
e.printStackTrace();
}
}
/**
* Stops and releases all resources used in application.
*/
@Override
public void stop() {
// release resources when the application closes
if (mapView != null) {
mapView.dispose();
}
}
/**
* Opens and runs application.
*
* @param args arguments passed to this application
*/
public static void main(String[] args) {
Application.launch(args);
}
}
|
src/main/java/com/esri/samples/featurelayers/time_based_query/TimeBasedQuerySample.java
|
/*
* Copyright 2018 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.samples.featurelayers.time_based_query;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.TimeExtent;
import com.esri.arcgisruntime.mapping.view.MapView;
public class TimeBasedQuerySample extends Application {
private MapView mapView;
@Override
public void start(Stage stage) throws Exception {
try {
// create stack pane and application scene
StackPane stackPane = new StackPane();
Scene scene = new Scene(stackPane);
// size the stage, add a title, and set scene to stage
stage.setTitle("Time Based Query Sample");
stage.setWidth(800);
stage.setHeight(700);
stage.setScene(scene);
stage.show();
// create a map and set it to a map view
mapView = new MapView();
ArcGISMap map = new ArcGISMap(Basemap.createOceans());
mapView.setMap(map);
// create a feature table with the URL of the feature service
String serviceURL = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Hurricanes/MapServer/0";
ServiceFeatureTable serviceFeatureTable = new ServiceFeatureTable(serviceURL);
// define the request mode to manual
serviceFeatureTable.setFeatureRequestMode(ServiceFeatureTable.FeatureRequestMode.MANUAL_CACHE);
// load the table and set the query
serviceFeatureTable.addDoneLoadingListener(() -> {
if (serviceFeatureTable.getLoadStatus() == LoadStatus.LOADED) {
// create query parameters
QueryParameters queryParameters = new QueryParameters();
// set a time extent (beginning of time to September 16th, 2000)
Calendar beg = new Calendar.Builder().setDate(1, 1, 1).build();
Calendar end = new Calendar.Builder().setDate(2000, 9, 16).build();
TimeExtent timeExtent = new TimeExtent(beg, end);
queryParameters.setTimeExtent(timeExtent);
// return all fields
List<String> outputFields = Collections.singletonList("*");
// populate the service with features that fit the time extent, when done zoom to the layer's extent
serviceFeatureTable.populateFromServiceAsync(queryParameters, true, outputFields).addDoneListener(() -> {
mapView.setViewpointGeometryAsync(serviceFeatureTable.getExtent());
});
} else {
new Alert(Alert.AlertType.ERROR, serviceFeatureTable.getLoadError().getMessage()).show();
}
});
// create the feature layer using the service feature table
FeatureLayer featureLayer = new FeatureLayer(serviceFeatureTable);
// add the layer to the map
map.getOperationalLayers().add(featureLayer);
// add the map view to stack pane
stackPane.getChildren().addAll(mapView);
} catch (Exception e) {
// on any error, display stack trace
e.printStackTrace();
}
}
/**
* Stops and releases all resources used in application.
*
* @throws Exception if security manager doesn't allow JVM to exit with
* current status
*/
@Override
public void stop() throws Exception {
// release resources when the application closes
if (mapView != null) {
mapView.dispose();
}
}
/**
* Opens and runs application.
*
* @param args arguments passed to this application
*/
public static void main(String[] args) {
Application.launch(args);
}
}
|
remove stop exception
|
src/main/java/com/esri/samples/featurelayers/time_based_query/TimeBasedQuerySample.java
|
remove stop exception
|
|
Java
|
apache-2.0
|
2cefbcc38f01216a52d274c9793055ec819b8a21
| 0
|
yahoo/pulsar,massakam/pulsar,merlimat/pulsar,yahoo/pulsar,massakam/pulsar,merlimat/pulsar,merlimat/pulsar,massakam/pulsar,merlimat/pulsar,merlimat/pulsar,merlimat/pulsar,yahoo/pulsar,yahoo/pulsar,massakam/pulsar,yahoo/pulsar,massakam/pulsar,yahoo/pulsar,massakam/pulsar
|
/**
* 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.pulsar.functions.instance.stats;
import com.google.common.collect.EvictingQueue;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.Gauge;
import lombok.Getter;
import org.apache.pulsar.common.util.RateLimiter;
import org.apache.pulsar.functions.proto.InstanceCommunication;
import java.util.Arrays;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class SourceStatsManager extends ComponentStatsManager {
public static final String PULSAR_SOURCE_METRICS_PREFIX = "pulsar_source_";
/** Declare metric names **/
public static final String SYSTEM_EXCEPTIONS_TOTAL = "system_exceptions_total";
public static final String SOURCE_EXCEPTIONS_TOTAL = "source_exceptions_total";
public static final String LAST_INVOCATION = "last_invocation";
public static final String RECEIVED_TOTAL = "received_total";
public static final String WRITTEN_TOTAL = "written_total";
public static final String SYSTEM_EXCEPTIONS_TOTAL_1min = "system_exceptions_total_1min";
public static final String SOURCE_EXCEPTIONS_TOTAL_1min = "source_exceptions_total_1min";
public static final String RECEIVED_TOTAL_1min = "received_total_1min";
public static final String WRITTEN_TOTAL_1min = "written_total_1min";
/** Declare Prometheus stats **/
private final Counter statTotalRecordsReceived;
private final Counter statTotalSysExceptions;
private final Counter statTotalSourceExceptions;
private final Counter statTotalWritten;
private final Gauge statlastInvocation;
// windowed metrics
private final Counter statTotalRecordsReceived1min;
private final Counter statTotalSysExceptions1min;
private final Counter statTotalSourceExceptions1min;
private final Counter statTotalWritten1min;
// exceptions
final Gauge sysExceptions;
final Gauge sourceExceptions;
// As an optimization
private final Counter.Child _statTotalRecordsReceived;
private final Counter.Child _statTotalSysExceptions;
private final Counter.Child _statTotalSourceExceptions;
private final Counter.Child _statTotalWritten;
private final Gauge.Child _statlastInvocation;
private Counter.Child _statTotalRecordsReceived1min;
private Counter.Child _statTotalSysExceptions1min;
private Counter.Child _statTotalSourceExceptions1min;
private Counter.Child _statTotalWritten1min;
@Getter
private EvictingQueue<InstanceCommunication.FunctionStatus.ExceptionInformation> latestSystemExceptions = EvictingQueue.create(10);
@Getter
private EvictingQueue<InstanceCommunication.FunctionStatus.ExceptionInformation> latestSourceExceptions = EvictingQueue.create(10);
protected final RateLimiter sysExceptionRateLimiter;
protected final RateLimiter sourceExceptionRateLimiter;
public SourceStatsManager(FunctionCollectorRegistry collectorRegistry, String[] metricsLabels, ScheduledExecutorService
scheduledExecutorService) {
super(collectorRegistry, metricsLabels, scheduledExecutorService);
statTotalRecordsReceived = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + RECEIVED_TOTAL,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + RECEIVED_TOTAL)
.help("Total number of records received from source.")
.labelNames(metricsLabelNames)
.create());
_statTotalRecordsReceived = statTotalRecordsReceived.labels(metricsLabels);
statTotalSysExceptions = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + SYSTEM_EXCEPTIONS_TOTAL,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + SYSTEM_EXCEPTIONS_TOTAL)
.help("Total number of system exceptions.")
.labelNames(metricsLabelNames)
.create());
_statTotalSysExceptions = statTotalSysExceptions.labels(metricsLabels);
statTotalSourceExceptions = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + SOURCE_EXCEPTIONS_TOTAL,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + SOURCE_EXCEPTIONS_TOTAL)
.help("Total number of source exceptions.")
.labelNames(metricsLabelNames)
.create());
_statTotalSourceExceptions = statTotalSourceExceptions.labels(metricsLabels);
statTotalWritten = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + WRITTEN_TOTAL,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + WRITTEN_TOTAL)
.help("Total number of records written to a Pulsar topic.")
.labelNames(metricsLabelNames)
.create());
_statTotalWritten = statTotalWritten.labels(metricsLabels);
statlastInvocation = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + LAST_INVOCATION,
Gauge.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + LAST_INVOCATION)
.help("The timestamp of the last invocation of the source.")
.labelNames(metricsLabelNames)
.create());
_statlastInvocation = statlastInvocation.labels(metricsLabels);
statTotalRecordsReceived1min = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + RECEIVED_TOTAL_1min,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + RECEIVED_TOTAL_1min)
.help("Total number of records received from source in the last 1 minute.")
.labelNames(metricsLabelNames)
.create());
_statTotalRecordsReceived1min = statTotalRecordsReceived1min.labels(metricsLabels);
statTotalSysExceptions1min = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + SYSTEM_EXCEPTIONS_TOTAL_1min,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + SYSTEM_EXCEPTIONS_TOTAL_1min)
.help("Total number of system exceptions in the last 1 minute.")
.labelNames(metricsLabelNames)
.create());
_statTotalSysExceptions1min = statTotalSysExceptions1min.labels(metricsLabels);
statTotalSourceExceptions1min = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + SOURCE_EXCEPTIONS_TOTAL_1min,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + SOURCE_EXCEPTIONS_TOTAL_1min)
.help("Total number of source exceptions in the last 1 minute.")
.labelNames(metricsLabelNames)
.create());
_statTotalSourceExceptions1min = statTotalSourceExceptions1min.labels(metricsLabels);
statTotalWritten1min = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + WRITTEN_TOTAL_1min,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + WRITTEN_TOTAL_1min)
.help("Total number of records written to a Pulsar topic in the last 1 minute.")
.labelNames(metricsLabelNames)
.create());
_statTotalWritten1min = statTotalWritten1min.labels(metricsLabels);
sysExceptions = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + "system_exception",
Gauge.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + "system_exception")
.labelNames(exceptionMetricsLabelNames)
.help("Exception from system code.")
.create());
sourceExceptions = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + "source_exception",
Gauge.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + "source_exception")
.labelNames(exceptionMetricsLabelNames)
.help("Exception from source.")
.create());
sysExceptionRateLimiter = new RateLimiter(scheduledExecutorService, 5, 1, TimeUnit.MINUTES, null);
sourceExceptionRateLimiter = new RateLimiter(scheduledExecutorService, 5, 1, TimeUnit.MINUTES, null);
}
@Override
public void reset() {
statTotalRecordsReceived1min.clear();
_statTotalRecordsReceived1min = statTotalRecordsReceived1min.labels(metricsLabels);
statTotalSysExceptions1min.clear();
_statTotalSysExceptions1min = statTotalSysExceptions1min.labels(metricsLabels);
statTotalSourceExceptions1min.clear();
_statTotalSourceExceptions1min = statTotalSourceExceptions1min.labels(metricsLabels);
statTotalWritten1min.clear();
_statTotalWritten1min = statTotalWritten1min.labels(metricsLabels);
}
@Override
public void incrTotalReceived() {
_statTotalRecordsReceived.inc();
_statTotalRecordsReceived1min.inc();
}
@Override
public void incrTotalProcessedSuccessfully() {
_statTotalWritten.inc();
_statTotalWritten1min.inc();
}
@Override
public void incrSysExceptions(Throwable ex) {
_statTotalSysExceptions.inc();
_statTotalSysExceptions1min.inc();
long ts = System.currentTimeMillis();
InstanceCommunication.FunctionStatus.ExceptionInformation info = getExceptionInfo(ex, ts);
latestSystemExceptions.add(info);
// report exception throw prometheus
if (sysExceptionRateLimiter.tryAcquire()) {
String[] exceptionMetricsLabels = getExceptionMetricsLabels(ex);
sysExceptions.labels(exceptionMetricsLabels).set(1.0);
}
}
@Override
public void incrUserExceptions(Throwable ex) {
incrSysExceptions(ex);
}
@Override
public void incrSourceExceptions(Throwable ex) {
_statTotalSourceExceptions.inc();
_statTotalSourceExceptions1min.inc();
long ts = System.currentTimeMillis();
InstanceCommunication.FunctionStatus.ExceptionInformation info = getExceptionInfo(ex, ts);
latestSourceExceptions.add(info);
// report exception throw prometheus
if (sourceExceptionRateLimiter.tryAcquire()) {
String[] exceptionMetricsLabels = getExceptionMetricsLabels(ex);
sourceExceptions.labels(exceptionMetricsLabels).set(1.0);
}
}
private String[] getExceptionMetricsLabels(Throwable ex) {
String[] exceptionMetricsLabels = Arrays.copyOf(metricsLabels, metricsLabels.length + 1);
exceptionMetricsLabels[exceptionMetricsLabels.length - 1] = ex.getMessage() != null ? ex.getMessage() : "";
return exceptionMetricsLabels;
}
@Override
public void incrSinkExceptions(Throwable ex) {
incrSysExceptions(ex);
}
@Override
public void setLastInvocation(long ts) {
_statlastInvocation.set(ts);
}
@Override
public void processTimeStart() {
//no-op
}
@Override
public void processTimeEnd() {
//no-op
}
@Override
public double getTotalProcessedSuccessfully() {
return _statTotalWritten.get();
}
@Override
public double getTotalRecordsReceived() {
return _statTotalRecordsReceived.get();
}
@Override
public double getTotalSysExceptions() {
return _statTotalSysExceptions.get();
}
@Override
public double getTotalUserExceptions() {
return 0;
}
@Override
public double getLastInvocation() {
return _statlastInvocation.get();
}
@Override
public double getAvgProcessLatency() {
return 0;
}
@Override
public double getTotalProcessedSuccessfully1min() {
return _statTotalWritten1min.get();
}
@Override
public double getTotalRecordsReceived1min() {
return _statTotalRecordsReceived1min.get();
}
@Override
public double getTotalSysExceptions1min() {
return _statTotalSysExceptions1min.get();
}
@Override
public double getTotalUserExceptions1min() {
return 0;
}
@Override
public double getAvgProcessLatency1min() {
return 0;
}
@Override
public EvictingQueue<InstanceCommunication.FunctionStatus.ExceptionInformation> getLatestUserExceptions() {
return EvictingQueue.create(0);
}
@Override
public EvictingQueue<InstanceCommunication.FunctionStatus.ExceptionInformation> getLatestSystemExceptions() {
return latestSystemExceptions;
}
@Override
public EvictingQueue<InstanceCommunication.FunctionStatus.ExceptionInformation> getLatestSourceExceptions() {
return latestSourceExceptions;
}
@Override
public EvictingQueue<InstanceCommunication.FunctionStatus.ExceptionInformation> getLatestSinkExceptions() {
return EvictingQueue.create(0);
}
}
|
pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/stats/SourceStatsManager.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.pulsar.functions.instance.stats;
import com.google.common.collect.EvictingQueue;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import io.prometheus.client.Gauge;
import lombok.Getter;
import org.apache.pulsar.common.util.RateLimiter;
import org.apache.pulsar.functions.proto.InstanceCommunication;
import java.util.Arrays;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class SourceStatsManager extends ComponentStatsManager {
public static final String PULSAR_SOURCE_METRICS_PREFIX = "pulsar_source_";
/** Declare metric names **/
public static final String SYSTEM_EXCEPTIONS_TOTAL = "system_exceptions_total";
public static final String SOURCE_EXCEPTIONS_TOTAL = "source_exceptions_total";
public static final String LAST_INVOCATION = "last_invocation";
public static final String RECEIVED_TOTAL = "received_total";
public static final String WRITTEN_TOTAL = "written_total";
public static final String SYSTEM_EXCEPTIONS_TOTAL_1min = "system_exceptions_total_1min";
public static final String SOURCE_EXCEPTIONS_TOTAL_1min = "source_exceptions_total_1min";
public static final String RECEIVED_TOTAL_1min = "received_total_1min";
public static final String WRITTEN_TOTAL_1min = "written_total_1min";
/** Declare Prometheus stats **/
private final Counter statTotalRecordsReceived;
private final Counter statTotalSysExceptions;
private final Counter statTotalSourceExceptions;
private final Counter statTotalWritten;
private final Gauge statlastInvocation;
// windowed metrics
private final Counter statTotalRecordsReceived1min;
private final Counter statTotalSysExceptions1min;
private final Counter statTotalSourceExceptions1min;
private final Counter statTotalWritten1min;
// exceptions
final Gauge sysExceptions;
final Gauge sourceExceptions;
// As an optimization
private final Counter.Child _statTotalRecordsReceived;
private final Counter.Child _statTotalSysExceptions;
private final Counter.Child _statTotalSourceExceptions;
private final Counter.Child _statTotalWritten;
private final Gauge.Child _statlastInvocation;
private Counter.Child _statTotalRecordsReceived1min;
private Counter.Child _statTotalSysExceptions1min;
private Counter.Child _statTotalSourceExceptions1min;
private Counter.Child _statTotalWritten1min;
@Getter
private EvictingQueue<InstanceCommunication.FunctionStatus.ExceptionInformation> latestSystemExceptions = EvictingQueue.create(10);
@Getter
private EvictingQueue<InstanceCommunication.FunctionStatus.ExceptionInformation> latestSourceExceptions = EvictingQueue.create(10);
protected final RateLimiter sysExceptionRateLimiter;
protected final RateLimiter sourceExceptionRateLimiter;
public SourceStatsManager(FunctionCollectorRegistry collectorRegistry, String[] metricsLabels, ScheduledExecutorService
scheduledExecutorService) {
super(collectorRegistry, metricsLabels, scheduledExecutorService);
statTotalRecordsReceived = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + RECEIVED_TOTAL,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + RECEIVED_TOTAL)
.help("Total number of records received from source.")
.labelNames(metricsLabelNames)
.create());
_statTotalRecordsReceived = statTotalRecordsReceived.labels(metricsLabels);
statTotalSysExceptions = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + SYSTEM_EXCEPTIONS_TOTAL,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + SYSTEM_EXCEPTIONS_TOTAL)
.help("Total number of system exceptions.")
.labelNames(metricsLabelNames)
.create());
_statTotalSysExceptions = statTotalSysExceptions.labels(metricsLabels);
statTotalSourceExceptions = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + SOURCE_EXCEPTIONS_TOTAL,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + SOURCE_EXCEPTIONS_TOTAL)
.help("Total number of source exceptions.")
.labelNames(metricsLabelNames)
.create());
_statTotalSourceExceptions = statTotalSourceExceptions.labels(metricsLabels);
statTotalWritten = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + WRITTEN_TOTAL,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + WRITTEN_TOTAL)
.help("Total number of records written to a Pulsar topic.")
.labelNames(metricsLabelNames)
.create());
_statTotalWritten = statTotalWritten.labels(metricsLabels);
statlastInvocation = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + LAST_INVOCATION,
Gauge.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + LAST_INVOCATION)
.help("The timestamp of the last invocation of the source.")
.labelNames(metricsLabelNames)
.create());
_statlastInvocation = statlastInvocation.labels(metricsLabels);
statTotalRecordsReceived1min = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + RECEIVED_TOTAL_1min,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + RECEIVED_TOTAL_1min)
.help("Total number of records received from source in the last 1 minute.")
.labelNames(metricsLabelNames)
.create());
_statTotalRecordsReceived1min = statTotalRecordsReceived1min.labels(metricsLabels);
statTotalSysExceptions1min = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + SYSTEM_EXCEPTIONS_TOTAL_1min,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + SYSTEM_EXCEPTIONS_TOTAL_1min)
.help("Total number of system exceptions in the last 1 minute.")
.labelNames(metricsLabelNames)
.create());
_statTotalSysExceptions1min = statTotalSysExceptions1min.labels(metricsLabels);
statTotalSourceExceptions1min = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + SOURCE_EXCEPTIONS_TOTAL_1min,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + SOURCE_EXCEPTIONS_TOTAL_1min)
.help("Total number of source exceptions in the last 1 minute.")
.labelNames(metricsLabelNames)
.create());
_statTotalSourceExceptions1min = statTotalSourceExceptions1min.labels(metricsLabels);
statTotalWritten1min = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + WRITTEN_TOTAL_1min,
Counter.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + WRITTEN_TOTAL_1min)
.help("Total number of records written to a Pulsar topic in the last 1 minute.")
.labelNames(metricsLabelNames)
.create());
_statTotalWritten1min = statTotalWritten1min.labels(metricsLabels);
sysExceptions = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + "system_exception",
Gauge.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + "system_exception")
.labelNames(exceptionMetricsLabelNames)
.help("Exception from system code.")
.create());
sourceExceptions = collectorRegistry.registerIfNotExist(
PULSAR_SOURCE_METRICS_PREFIX + "source_exception",
Gauge.build()
.name(PULSAR_SOURCE_METRICS_PREFIX + "source_exception")
.labelNames(exceptionMetricsLabelNames)
.help("Exception from source.")
.create());
sysExceptionRateLimiter = new RateLimiter(scheduledExecutorService, 5, 1, TimeUnit.MINUTES, null);
sourceExceptionRateLimiter = new RateLimiter(scheduledExecutorService, 5, 1, TimeUnit.MINUTES, null);
}
@Override
public void reset() {
statTotalRecordsReceived1min.clear();
_statTotalRecordsReceived1min = statTotalRecordsReceived1min.labels(metricsLabels);
statTotalSysExceptions1min.clear();
_statTotalSysExceptions1min = statTotalSysExceptions1min.labels(metricsLabels);
statTotalSourceExceptions1min.clear();
_statTotalSourceExceptions1min = statTotalSourceExceptions1min.labels(metricsLabels);
statTotalWritten1min.clear();
_statTotalWritten1min = statTotalWritten1min.labels(metricsLabels);
}
@Override
public void incrTotalReceived() {
_statTotalRecordsReceived.inc();
_statTotalRecordsReceived1min.inc();
}
@Override
public void incrTotalProcessedSuccessfully() {
_statTotalWritten.inc();
_statTotalWritten1min.inc();
}
@Override
public void incrSysExceptions(Throwable ex) {
_statTotalSysExceptions.inc();
_statTotalSysExceptions1min.inc();
long ts = System.currentTimeMillis();
InstanceCommunication.FunctionStatus.ExceptionInformation info = getExceptionInfo(ex, ts);
latestSystemExceptions.add(info);
// report exception throw prometheus
if (sysExceptionRateLimiter.tryAcquire()) {
String[] exceptionMetricsLabels = getExceptionMetricsLabels(ex);
sysExceptions.labels(exceptionMetricsLabels).set(1.0);
}
}
@Override
public void incrUserExceptions(Throwable ex) {
incrSysExceptions(ex);
}
@Override
public void incrSourceExceptions(Throwable ex) {
_statTotalSourceExceptions.inc();
_statTotalSourceExceptions1min.inc();
long ts = System.currentTimeMillis();
InstanceCommunication.FunctionStatus.ExceptionInformation info = getExceptionInfo(ex, ts);
latestSourceExceptions.add(info);
// report exception throw prometheus
if (sourceExceptionRateLimiter.tryAcquire()) {
String[] exceptionMetricsLabels = getExceptionMetricsLabels(ex);
sourceExceptions.labels(exceptionMetricsLabels).set(1.0);
}
}
private String[] getExceptionMetricsLabels(Throwable ex) {
String[] exceptionMetricsLabels = Arrays.copyOf(metricsLabels, metricsLabels.length + 1);
exceptionMetricsLabels[exceptionMetricsLabels.length - 1] = ex.getMessage() != null ? ex.getMessage() : "";
return exceptionMetricsLabels;
}
@Override
public void incrSinkExceptions(Throwable ex) {
incrSysExceptions(ex);
}
@Override
public void setLastInvocation(long ts) {
_statlastInvocation.set(ts);
}
@Override
public void processTimeStart() {
//no-op
}
@Override
public void processTimeEnd() {
//no-op
}
@Override
public double getTotalProcessedSuccessfully() {
return _statTotalWritten.get();
}
@Override
public double getTotalRecordsReceived() {
return _statTotalRecordsReceived.get();
}
@Override
public double getTotalSysExceptions() {
return _statTotalSysExceptions.get();
}
@Override
public double getTotalUserExceptions() {
return 0;
}
@Override
public double getLastInvocation() {
return _statlastInvocation.get();
}
@Override
public double getAvgProcessLatency() {
return 0;
}
@Override
public double getTotalProcessedSuccessfully1min() {
return _statTotalWritten1min.get();
}
@Override
public double getTotalRecordsReceived1min() {
return _statTotalRecordsReceived1min.get();
}
@Override
public double getTotalSysExceptions1min() {
return _statTotalSysExceptions1min.get();
}
@Override
public double getTotalUserExceptions1min() {
return 0;
}
@Override
public double getAvgProcessLatency1min() {
return 0;
}
@Override
public EvictingQueue<InstanceCommunication.FunctionStatus.ExceptionInformation> getLatestUserExceptions() {
return EvictingQueue.create(0);
}
@Override
public EvictingQueue<InstanceCommunication.FunctionStatus.ExceptionInformation> getLatestSystemExceptions() {
return EMPTY_QUEUE;
}
@Override
public EvictingQueue<InstanceCommunication.FunctionStatus.ExceptionInformation> getLatestSourceExceptions() {
return EMPTY_QUEUE;
}
@Override
public EvictingQueue<InstanceCommunication.FunctionStatus.ExceptionInformation> getLatestSinkExceptions() {
return EvictingQueue.create(0);
}
}
|
[pulsar-io] fix source stats exposing empty exceptions list (#11478)
### Motivation
`pulsar-admin sources status` always have empty list of `latestSystemExceptions` and `latestSourceExceptions`. With some code digging, it turns out that it always returns `EMPTY_QUEUE`.
|
pulsar-functions/instance/src/main/java/org/apache/pulsar/functions/instance/stats/SourceStatsManager.java
|
[pulsar-io] fix source stats exposing empty exceptions list (#11478)
|
|
Java
|
apache-2.0
|
c95e74e1b92638f7c7a113c0b49737d02885457b
| 0
|
vroyer/elassandra,strapdata/elassandra,vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,strapdata/elassandra,strapdata/elassandra,vroyer/elassandra
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.client.documentation;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.LatchedActionListener;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.client.ESRestHighLevelClientTestCase;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.security.AuthenticateResponse;
import org.elasticsearch.client.security.ChangePasswordRequest;
import org.elasticsearch.client.security.ClearRealmCacheRequest;
import org.elasticsearch.client.security.ClearRealmCacheResponse;
import org.elasticsearch.client.security.ClearRolesCacheRequest;
import org.elasticsearch.client.security.ClearRolesCacheResponse;
import org.elasticsearch.client.security.CreateTokenRequest;
import org.elasticsearch.client.security.CreateTokenResponse;
import org.elasticsearch.client.security.DeletePrivilegesRequest;
import org.elasticsearch.client.security.DeletePrivilegesResponse;
import org.elasticsearch.client.security.DeleteRoleMappingRequest;
import org.elasticsearch.client.security.DeleteRoleMappingResponse;
import org.elasticsearch.client.security.DeleteRoleRequest;
import org.elasticsearch.client.security.DeleteRoleResponse;
import org.elasticsearch.client.security.DeleteUserRequest;
import org.elasticsearch.client.security.DeleteUserResponse;
import org.elasticsearch.client.security.DisableUserRequest;
import org.elasticsearch.client.security.EmptyResponse;
import org.elasticsearch.client.security.EnableUserRequest;
import org.elasticsearch.client.security.ExpressionRoleMapping;
import org.elasticsearch.client.security.GetPrivilegesRequest;
import org.elasticsearch.client.security.GetPrivilegesResponse;
import org.elasticsearch.client.security.GetRoleMappingsRequest;
import org.elasticsearch.client.security.GetRoleMappingsResponse;
import org.elasticsearch.client.security.GetRolesRequest;
import org.elasticsearch.client.security.GetRolesResponse;
import org.elasticsearch.client.security.GetSslCertificatesResponse;
import org.elasticsearch.client.security.HasPrivilegesRequest;
import org.elasticsearch.client.security.HasPrivilegesResponse;
import org.elasticsearch.client.security.InvalidateTokenRequest;
import org.elasticsearch.client.security.InvalidateTokenResponse;
import org.elasticsearch.client.security.PutPrivilegesRequest;
import org.elasticsearch.client.security.PutPrivilegesResponse;
import org.elasticsearch.client.security.PutRoleMappingRequest;
import org.elasticsearch.client.security.PutRoleMappingResponse;
import org.elasticsearch.client.security.PutRoleRequest;
import org.elasticsearch.client.security.PutRoleResponse;
import org.elasticsearch.client.security.PutUserRequest;
import org.elasticsearch.client.security.PutUserResponse;
import org.elasticsearch.client.security.RefreshPolicy;
import org.elasticsearch.client.security.support.CertificateInfo;
import org.elasticsearch.client.security.support.expressiondsl.RoleMapperExpression;
import org.elasticsearch.client.security.support.expressiondsl.expressions.AnyRoleMapperExpression;
import org.elasticsearch.client.security.support.expressiondsl.fields.FieldRoleMapperExpression;
import org.elasticsearch.client.security.user.User;
import org.elasticsearch.client.security.user.privileges.ApplicationPrivilege;
import org.elasticsearch.client.security.user.privileges.ApplicationResourcePrivileges;
import org.elasticsearch.client.security.user.privileges.IndicesPrivileges;
import org.elasticsearch.client.security.user.privileges.Role;
import org.elasticsearch.client.security.user.privileges.UserIndicesPrivileges;
import org.elasticsearch.common.util.set.Sets;
import org.hamcrest.Matchers;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.emptyIterable;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
public class SecurityDocumentationIT extends ESRestHighLevelClientTestCase {
public void testPutUser() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::put-user-password-request
char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
User user = new User("example", Collections.singletonList("superuser"));
PutUserRequest request = PutUserRequest.withPassword(user, password, true, RefreshPolicy.NONE);
//end::put-user-password-request
//tag::put-user-execute
PutUserResponse response = client.security().putUser(request, RequestOptions.DEFAULT);
//end::put-user-execute
//tag::put-user-response
boolean isCreated = response.isCreated(); // <1>
//end::put-user-response
assertTrue(isCreated);
}
{
byte[] salt = new byte[32];
// no need for secure random in a test; it could block and would not be reproducible anyway
random().nextBytes(salt);
char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
User user = new User("example2", Collections.singletonList("superuser"));
//tag::put-user-hash-request
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2withHMACSHA512");
PBEKeySpec keySpec = new PBEKeySpec(password, salt, 10000, 256);
final byte[] pbkdfEncoded = secretKeyFactory.generateSecret(keySpec).getEncoded();
char[] passwordHash = ("{PBKDF2}10000$" + Base64.getEncoder().encodeToString(salt)
+ "$" + Base64.getEncoder().encodeToString(pbkdfEncoded)).toCharArray();
PutUserRequest request = PutUserRequest.withPasswordHash(user, passwordHash, true, RefreshPolicy.NONE);
//end::put-user-hash-request
try {
client.security().putUser(request, RequestOptions.DEFAULT);
} catch (ElasticsearchStatusException e) {
// This is expected to fail as the server will not be using PBKDF2, but that's easiest hasher to support
// in a standard JVM without introducing additional libraries.
assertThat(e.getDetailedMessage(), containsString("PBKDF2"));
}
}
{
User user = new User("example", Arrays.asList("superuser", "another-role"));
//tag::put-user-update-request
PutUserRequest request = PutUserRequest.updateUser(user, true, RefreshPolicy.NONE);
//end::put-user-update-request
// tag::put-user-execute-listener
ActionListener<PutUserResponse> listener = new ActionListener<PutUserResponse>() {
@Override
public void onResponse(PutUserResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-user-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::put-user-execute-async
client.security().putUserAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-user-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteUser() throws Exception {
RestHighLevelClient client = highLevelClient();
addUser(client, "testUser", "testPassword");
{
// tag::delete-user-request
DeleteUserRequest deleteUserRequest = new DeleteUserRequest(
"testUser"); // <1>
// end::delete-user-request
// tag::delete-user-execute
DeleteUserResponse deleteUserResponse = client.security().deleteUser(deleteUserRequest, RequestOptions.DEFAULT);
// end::delete-user-execute
// tag::delete-user-response
boolean found = deleteUserResponse.isAcknowledged(); // <1>
// end::delete-user-response
assertTrue(found);
// check if deleting the already deleted user again will give us a different response
deleteUserResponse = client.security().deleteUser(deleteUserRequest, RequestOptions.DEFAULT);
assertFalse(deleteUserResponse.isAcknowledged());
}
{
DeleteUserRequest deleteUserRequest = new DeleteUserRequest("testUser", RefreshPolicy.IMMEDIATE);
ActionListener<DeleteUserResponse> listener;
//tag::delete-user-execute-listener
listener = new ActionListener<DeleteUserResponse>() {
@Override
public void onResponse(DeleteUserResponse deleteUserResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::delete-user-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
//tag::delete-user-execute-async
client.security().deleteUserAsync(deleteUserRequest, RequestOptions.DEFAULT, listener); // <1>
//end::delete-user-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
private void addUser(RestHighLevelClient client, String userName, String password) throws IOException {
User user = new User(userName, Collections.singletonList(userName));
PutUserRequest request = new PutUserRequest(user, password.toCharArray(), true, RefreshPolicy.NONE);
PutUserResponse response = client.security().putUser(request, RequestOptions.DEFAULT);
assertTrue(response.isCreated());
}
public void testPutRoleMapping() throws Exception {
final RestHighLevelClient client = highLevelClient();
{
// tag::put-role-mapping-execute
final RoleMapperExpression rules = AnyRoleMapperExpression.builder()
.addExpression(FieldRoleMapperExpression.ofUsername("*"))
.addExpression(FieldRoleMapperExpression.ofGroups("cn=admins,dc=example,dc=com"))
.build();
final PutRoleMappingRequest request = new PutRoleMappingRequest("mapping-example", true, Collections.singletonList("superuser"),
rules, null, RefreshPolicy.NONE);
final PutRoleMappingResponse response = client.security().putRoleMapping(request, RequestOptions.DEFAULT);
// end::put-role-mapping-execute
// tag::put-role-mapping-response
boolean isCreated = response.isCreated(); // <1>
// end::put-role-mapping-response
assertTrue(isCreated);
}
{
final RoleMapperExpression rules = AnyRoleMapperExpression.builder()
.addExpression(FieldRoleMapperExpression.ofUsername("*"))
.addExpression(FieldRoleMapperExpression.ofGroups("cn=admins,dc=example,dc=com"))
.build();
final PutRoleMappingRequest request = new PutRoleMappingRequest("mapping-example", true, Collections.singletonList("superuser"),
rules, null, RefreshPolicy.NONE);
// tag::put-role-mapping-execute-listener
ActionListener<PutRoleMappingResponse> listener = new ActionListener<PutRoleMappingResponse>() {
@Override
public void onResponse(PutRoleMappingResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-role-mapping-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::put-role-mapping-execute-async
client.security().putRoleMappingAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-role-mapping-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetRoleMappings() throws Exception {
final RestHighLevelClient client = highLevelClient();
final RoleMapperExpression rules1 = AnyRoleMapperExpression.builder().addExpression(FieldRoleMapperExpression.ofUsername("*"))
.addExpression(FieldRoleMapperExpression.ofGroups("cn=admins,dc=example,dc=com")).build();
final PutRoleMappingRequest putRoleMappingRequest1 = new PutRoleMappingRequest("mapping-example-1", true, Collections.singletonList(
"superuser"), rules1, null, RefreshPolicy.NONE);
final PutRoleMappingResponse putRoleMappingResponse1 = client.security().putRoleMapping(putRoleMappingRequest1,
RequestOptions.DEFAULT);
boolean isCreated1 = putRoleMappingResponse1.isCreated();
assertTrue(isCreated1);
final RoleMapperExpression rules2 = AnyRoleMapperExpression.builder().addExpression(FieldRoleMapperExpression.ofGroups(
"cn=admins,dc=example,dc=com")).build();
final Map<String, Object> metadata2 = new HashMap<>();
metadata2.put("k1", "v1");
final PutRoleMappingRequest putRoleMappingRequest2 = new PutRoleMappingRequest("mapping-example-2", true, Collections.singletonList(
"monitoring"), rules2, metadata2, RefreshPolicy.NONE);
final PutRoleMappingResponse putRoleMappingResponse2 = client.security().putRoleMapping(putRoleMappingRequest2,
RequestOptions.DEFAULT);
boolean isCreated2 = putRoleMappingResponse2.isCreated();
assertTrue(isCreated2);
{
// tag::get-role-mappings-execute
final GetRoleMappingsRequest request = new GetRoleMappingsRequest("mapping-example-1");
final GetRoleMappingsResponse response = client.security().getRoleMappings(request, RequestOptions.DEFAULT);
// end::get-role-mappings-execute
// tag::get-role-mappings-response
List<ExpressionRoleMapping> mappings = response.getMappings();
// end::get-role-mappings-response
assertNotNull(mappings);
assertThat(mappings.size(), is(1));
assertThat(mappings.get(0).isEnabled(), is(true));
assertThat(mappings.get(0).getName(), is("mapping-example-1"));
assertThat(mappings.get(0).getExpression(), equalTo(rules1));
assertThat(mappings.get(0).getMetadata(), equalTo(Collections.emptyMap()));
assertThat(mappings.get(0).getRoles(), contains("superuser"));
}
{
// tag::get-role-mappings-list-execute
final GetRoleMappingsRequest request = new GetRoleMappingsRequest("mapping-example-1", "mapping-example-2");
final GetRoleMappingsResponse response = client.security().getRoleMappings(request, RequestOptions.DEFAULT);
// end::get-role-mappings-list-execute
List<ExpressionRoleMapping> mappings = response.getMappings();
assertNotNull(mappings);
assertThat(mappings.size(), is(2));
for (ExpressionRoleMapping roleMapping : mappings) {
assertThat(roleMapping.isEnabled(), is(true));
assertThat(roleMapping.getName(), isIn(new String[]{"mapping-example-1", "mapping-example-2"}));
if (roleMapping.getName().equals("mapping-example-1")) {
assertThat(roleMapping.getMetadata(), equalTo(Collections.emptyMap()));
assertThat(roleMapping.getExpression(), equalTo(rules1));
assertThat(roleMapping.getRoles(), contains("superuser"));
} else {
assertThat(roleMapping.getMetadata(), equalTo(metadata2));
assertThat(roleMapping.getExpression(), equalTo(rules2));
assertThat(roleMapping.getRoles(), contains("monitoring"));
}
}
}
{
// tag::get-role-mappings-all-execute
final GetRoleMappingsRequest request = new GetRoleMappingsRequest();
final GetRoleMappingsResponse response = client.security().getRoleMappings(request, RequestOptions.DEFAULT);
// end::get-role-mappings-all-execute
List<ExpressionRoleMapping> mappings = response.getMappings();
assertNotNull(mappings);
assertThat(mappings.size(), is(2));
for (ExpressionRoleMapping roleMapping : mappings) {
assertThat(roleMapping.isEnabled(), is(true));
assertThat(roleMapping.getName(), isIn(new String[]{"mapping-example-1", "mapping-example-2"}));
if (roleMapping.getName().equals("mapping-example-1")) {
assertThat(roleMapping.getMetadata(), equalTo(Collections.emptyMap()));
assertThat(roleMapping.getExpression(), equalTo(rules1));
assertThat(roleMapping.getRoles(), contains("superuser"));
} else {
assertThat(roleMapping.getMetadata(), equalTo(metadata2));
assertThat(roleMapping.getExpression(), equalTo(rules2));
assertThat(roleMapping.getRoles(), contains("monitoring"));
}
}
}
{
final GetRoleMappingsRequest request = new GetRoleMappingsRequest();
// tag::get-role-mappings-execute-listener
ActionListener<GetRoleMappingsResponse> listener = new ActionListener<GetRoleMappingsResponse>() {
@Override
public void onResponse(GetRoleMappingsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-role-mappings-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-role-mappings-execute-async
client.security().getRoleMappingsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-role-mappings-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testEnableUser() throws Exception {
RestHighLevelClient client = highLevelClient();
char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
User enable_user = new User("enable_user", Collections.singletonList("superuser"));
PutUserRequest putUserRequest = new PutUserRequest(enable_user, password, true, RefreshPolicy.IMMEDIATE);
PutUserResponse putUserResponse = client.security().putUser(putUserRequest, RequestOptions.DEFAULT);
assertTrue(putUserResponse.isCreated());
{
//tag::enable-user-execute
EnableUserRequest request = new EnableUserRequest("enable_user", RefreshPolicy.NONE);
EmptyResponse response = client.security().enableUser(request, RequestOptions.DEFAULT);
//end::enable-user-execute
assertNotNull(response);
}
{
//tag::enable-user-execute-listener
EnableUserRequest request = new EnableUserRequest("enable_user", RefreshPolicy.NONE);
ActionListener<EmptyResponse> listener = new ActionListener<EmptyResponse>() {
@Override
public void onResponse(EmptyResponse setUserEnabledResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::enable-user-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::enable-user-execute-async
client.security().enableUserAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::enable-user-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDisableUser() throws Exception {
RestHighLevelClient client = highLevelClient();
char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
User disable_user = new User("disable_user", Collections.singletonList("superuser"));
PutUserRequest putUserRequest = new PutUserRequest(disable_user, password, true, RefreshPolicy.IMMEDIATE);
PutUserResponse putUserResponse = client.security().putUser(putUserRequest, RequestOptions.DEFAULT);
assertTrue(putUserResponse.isCreated());
{
//tag::disable-user-execute
DisableUserRequest request = new DisableUserRequest("disable_user", RefreshPolicy.NONE);
EmptyResponse response = client.security().disableUser(request, RequestOptions.DEFAULT);
//end::disable-user-execute
assertNotNull(response);
}
{
//tag::disable-user-execute-listener
DisableUserRequest request = new DisableUserRequest("disable_user", RefreshPolicy.NONE);
ActionListener<EmptyResponse> listener = new ActionListener<EmptyResponse>() {
@Override
public void onResponse(EmptyResponse setUserEnabledResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::disable-user-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::disable-user-execute-async
client.security().disableUserAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::disable-user-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetRoles() throws Exception {
final RestHighLevelClient client = highLevelClient();
addRole("my_role");
addRole("my_role2");
addRole("my_role3");
{
//tag::get-roles-request
GetRolesRequest request = new GetRolesRequest("my_role");
//end::get-roles-request
//tag::get-roles-execute
GetRolesResponse response = client.security().getRoles(request, RequestOptions.DEFAULT);
//end::get-roles-execute
//tag::get-roles-response
List<Role> roles = response.getRoles();
//end::get-roles-response
assertNotNull(response);
assertThat(roles.size(), equalTo(1));
assertThat(roles.get(0).getName(), equalTo("my_role"));
assertThat(roles.get(0).getClusterPrivileges().contains("all"), equalTo(true));
}
{
//tag::get-roles-list-request
GetRolesRequest request = new GetRolesRequest("my_role", "my_role2");
GetRolesResponse response = client.security().getRoles(request, RequestOptions.DEFAULT);
//end::get-roles-list-request
List<Role> roles = response.getRoles();
assertNotNull(response);
assertThat(roles.size(), equalTo(2));
assertThat(roles.get(0).getClusterPrivileges().contains("all"), equalTo(true));
assertThat(roles.get(1).getClusterPrivileges().contains("all"), equalTo(true));
}
{
//tag::get-roles-all-request
GetRolesRequest request = new GetRolesRequest();
GetRolesResponse response = client.security().getRoles(request, RequestOptions.DEFAULT);
//end::get-roles-all-request
List<Role> roles = response.getRoles();
assertNotNull(response);
// 21 system roles plus the three we created
assertThat(roles.size(), equalTo(24));
}
{
GetRolesRequest request = new GetRolesRequest("my_role");
ActionListener<GetRolesResponse> listener;
//tag::get-roles-execute-listener
listener = new ActionListener<GetRolesResponse>() {
@Override
public void onResponse(GetRolesResponse getRolesResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::get-roles-execute-listener
assertNotNull(listener);
// Replace the empty listener by a blocking listener in test
final PlainActionFuture<GetRolesResponse> future = new PlainActionFuture<>();
listener = future;
//tag::get-roles-execute-async
client.security().getRolesAsync(request, RequestOptions.DEFAULT, listener); // <1>
//end::get-roles-execute-async
final GetRolesResponse response = future.get(30, TimeUnit.SECONDS);
assertNotNull(response);
assertThat(response.getRoles().size(), equalTo(1));
assertThat(response.getRoles().get(0).getName(), equalTo("my_role"));
assertThat(response.getRoles().get(0).getClusterPrivileges().contains("all"), equalTo(true));
}
}
public void testAuthenticate() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::authenticate-execute
AuthenticateResponse response = client.security().authenticate(RequestOptions.DEFAULT);
//end::authenticate-execute
//tag::authenticate-response
User user = response.getUser(); // <1>
boolean enabled = response.enabled(); // <2>
final String authenticationRealmName = response.getAuthenticationRealm().getName(); // <3>
final String authenticationRealmType = response.getAuthenticationRealm().getType(); // <4>
final String lookupRealmName = response.getLookupRealm().getName(); // <5>
final String lookupRealmType = response.getLookupRealm().getType(); // <6>
//end::authenticate-response
assertThat(user.getUsername(), is("test_user"));
assertThat(user.getRoles(), contains(new String[]{"superuser"}));
assertThat(user.getFullName(), nullValue());
assertThat(user.getEmail(), nullValue());
assertThat(user.getMetadata().isEmpty(), is(true));
assertThat(enabled, is(true));
assertThat(authenticationRealmName, is("default_file"));
assertThat(authenticationRealmType, is("file"));
assertThat(lookupRealmName, is("default_file"));
assertThat(lookupRealmType, is("file"));
}
{
// tag::authenticate-execute-listener
ActionListener<AuthenticateResponse> listener = new ActionListener<AuthenticateResponse>() {
@Override
public void onResponse(AuthenticateResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::authenticate-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::authenticate-execute-async
client.security().authenticateAsync(RequestOptions.DEFAULT, listener); // <1>
// end::authenticate-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testHasPrivileges() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::has-privileges-request
HasPrivilegesRequest request = new HasPrivilegesRequest(
Sets.newHashSet("monitor", "manage"),
Sets.newHashSet(
IndicesPrivileges.builder().indices("logstash-2018-10-05").privileges("read", "write").build(),
IndicesPrivileges.builder().indices("logstash-2018-*").privileges("read").build()
),
null
);
//end::has-privileges-request
//tag::has-privileges-execute
HasPrivilegesResponse response = client.security().hasPrivileges(request, RequestOptions.DEFAULT);
//end::has-privileges-execute
//tag::has-privileges-response
boolean hasMonitor = response.hasClusterPrivilege("monitor"); // <1>
boolean hasWrite = response.hasIndexPrivilege("logstash-2018-10-05", "write"); // <2>
boolean hasRead = response.hasIndexPrivilege("logstash-2018-*", "read"); // <3>
//end::has-privileges-response
assertThat(response.getUsername(), is("test_user"));
assertThat(response.hasAllRequested(), is(true));
assertThat(hasMonitor, is(true));
assertThat(hasWrite, is(true));
assertThat(hasRead, is(true));
assertThat(response.getApplicationPrivileges().entrySet(), emptyIterable());
}
{
HasPrivilegesRequest request = new HasPrivilegesRequest(Collections.singleton("monitor"), null, null);
// tag::has-privileges-execute-listener
ActionListener<HasPrivilegesResponse> listener = new ActionListener<HasPrivilegesResponse>() {
@Override
public void onResponse(HasPrivilegesResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::has-privileges-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::has-privileges-execute-async
client.security().hasPrivilegesAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::has-privileges-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testClearRealmCache() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::clear-realm-cache-request
ClearRealmCacheRequest request = new ClearRealmCacheRequest(Collections.emptyList(), Collections.emptyList());
//end::clear-realm-cache-request
//tag::clear-realm-cache-execute
ClearRealmCacheResponse response = client.security().clearRealmCache(request, RequestOptions.DEFAULT);
//end::clear-realm-cache-execute
assertNotNull(response);
assertThat(response.getNodes(), not(empty()));
//tag::clear-realm-cache-response
List<ClearRealmCacheResponse.Node> nodes = response.getNodes(); // <1>
//end::clear-realm-cache-response
}
{
//tag::clear-realm-cache-execute-listener
ClearRealmCacheRequest request = new ClearRealmCacheRequest(Collections.emptyList(), Collections.emptyList());
ActionListener<ClearRealmCacheResponse> listener = new ActionListener<ClearRealmCacheResponse>() {
@Override
public void onResponse(ClearRealmCacheResponse clearRealmCacheResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::clear-realm-cache-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::clear-realm-cache-execute-async
client.security().clearRealmCacheAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::clear-realm-cache-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testClearRolesCache() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::clear-roles-cache-request
ClearRolesCacheRequest request = new ClearRolesCacheRequest("my_role");
//end::clear-roles-cache-request
//tag::clear-roles-cache-execute
ClearRolesCacheResponse response = client.security().clearRolesCache(request, RequestOptions.DEFAULT);
//end::clear-roles-cache-execute
assertNotNull(response);
assertThat(response.getNodes(), not(empty()));
//tag::clear-roles-cache-response
List<ClearRolesCacheResponse.Node> nodes = response.getNodes(); // <1>
//end::clear-roles-cache-response
}
{
//tag::clear-roles-cache-execute-listener
ClearRolesCacheRequest request = new ClearRolesCacheRequest("my_role");
ActionListener<ClearRolesCacheResponse> listener = new ActionListener<ClearRolesCacheResponse>() {
@Override
public void onResponse(ClearRolesCacheResponse clearRolesCacheResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::clear-roles-cache-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::clear-roles-cache-execute-async
client.security().clearRolesCacheAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::clear-roles-cache-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetSslCertificates() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::get-certificates-execute
GetSslCertificatesResponse response = client.security().getSslCertificates(RequestOptions.DEFAULT);
//end::get-certificates-execute
assertNotNull(response);
//tag::get-certificates-response
List<CertificateInfo> certificates = response.getCertificates(); // <1>
//end::get-certificates-response
assertThat(certificates.size(), Matchers.equalTo(9));
final Iterator<CertificateInfo> it = certificates.iterator();
CertificateInfo c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=testnode-client-profile"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=Elasticsearch Test Node, OU=elasticsearch, O=org"));
assertThat(c.getPath(), Matchers.equalTo("testnode.crt"));
assertThat(c.getFormat(), Matchers.equalTo("PEM"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=OpenLDAP, OU=Elasticsearch, O=Elastic, L=Mountain View, ST=CA, C=US"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=Elasticsearch Test Node, OU=elasticsearch, O=org"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=Elasticsearch Test Client, OU=elasticsearch, O=org"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=ad-ELASTICSEARCHAD-CA, DC=ad, DC=test, DC=elasticsearch, DC=com"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=Elasticsearch Test Node"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=samba4"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=Elasticsearch Test Node"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
}
{
// tag::get-certificates-execute-listener
ActionListener<GetSslCertificatesResponse> listener = new ActionListener<GetSslCertificatesResponse>() {
@Override
public void onResponse(GetSslCertificatesResponse getSslCertificatesResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-certificates-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-certificates-execute-async
client.security().getSslCertificatesAsync(RequestOptions.DEFAULT, listener); // <1>
// end::get-certificates-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testChangePassword() throws Exception {
RestHighLevelClient client = highLevelClient();
char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
char[] newPassword = new char[]{'n', 'e', 'w', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
User user = new User("change_password_user", Collections.singletonList("superuser"), Collections.emptyMap(), null, null);
PutUserRequest putUserRequest = new PutUserRequest(user, password, true, RefreshPolicy.NONE);
PutUserResponse putUserResponse = client.security().putUser(putUserRequest, RequestOptions.DEFAULT);
assertTrue(putUserResponse.isCreated());
{
//tag::change-password-execute
ChangePasswordRequest request = new ChangePasswordRequest("change_password_user", newPassword, RefreshPolicy.NONE);
EmptyResponse response = client.security().changePassword(request, RequestOptions.DEFAULT);
//end::change-password-execute
assertNotNull(response);
}
{
//tag::change-password-execute-listener
ChangePasswordRequest request = new ChangePasswordRequest("change_password_user", password, RefreshPolicy.NONE);
ActionListener<EmptyResponse> listener = new ActionListener<EmptyResponse>() {
@Override
public void onResponse(EmptyResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::change-password-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
//tag::change-password-execute-async
client.security().changePasswordAsync(request, RequestOptions.DEFAULT, listener); // <1>
//end::change-password-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteRoleMapping() throws Exception {
final RestHighLevelClient client = highLevelClient();
{
// Create role mappings
final RoleMapperExpression rules = FieldRoleMapperExpression.ofUsername("*");
final PutRoleMappingRequest request = new PutRoleMappingRequest("mapping-example", true, Collections.singletonList("superuser"),
rules, null, RefreshPolicy.NONE);
final PutRoleMappingResponse response = client.security().putRoleMapping(request, RequestOptions.DEFAULT);
boolean isCreated = response.isCreated();
assertTrue(isCreated);
}
{
// tag::delete-role-mapping-execute
final DeleteRoleMappingRequest request = new DeleteRoleMappingRequest("mapping-example", RefreshPolicy.NONE);
final DeleteRoleMappingResponse response = client.security().deleteRoleMapping(request, RequestOptions.DEFAULT);
// end::delete-role-mapping-execute
// tag::delete-role-mapping-response
boolean isFound = response.isFound(); // <1>
// end::delete-role-mapping-response
assertTrue(isFound);
}
{
final DeleteRoleMappingRequest request = new DeleteRoleMappingRequest("mapping-example", RefreshPolicy.NONE);
// tag::delete-role-mapping-execute-listener
ActionListener<DeleteRoleMappingResponse> listener = new ActionListener<DeleteRoleMappingResponse>() {
@Override
public void onResponse(DeleteRoleMappingResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-role-mapping-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::delete-role-mapping-execute-async
client.security().deleteRoleMappingAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::delete-role-mapping-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteRole() throws Exception {
RestHighLevelClient client = highLevelClient();
addRole("testrole");
{
// tag::delete-role-request
DeleteRoleRequest deleteRoleRequest = new DeleteRoleRequest(
"testrole"); // <1>
// end::delete-role-request
// tag::delete-role-execute
DeleteRoleResponse deleteRoleResponse = client.security().deleteRole(deleteRoleRequest, RequestOptions.DEFAULT);
// end::delete-role-execute
// tag::delete-role-response
boolean found = deleteRoleResponse.isFound(); // <1>
// end::delete-role-response
assertTrue(found);
// check if deleting the already deleted role again will give us a different response
deleteRoleResponse = client.security().deleteRole(deleteRoleRequest, RequestOptions.DEFAULT);
assertFalse(deleteRoleResponse.isFound());
}
{
DeleteRoleRequest deleteRoleRequest = new DeleteRoleRequest("testrole");
ActionListener<DeleteRoleResponse> listener;
//tag::delete-role-execute-listener
listener = new ActionListener<DeleteRoleResponse>() {
@Override
public void onResponse(DeleteRoleResponse deleteRoleResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::delete-role-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
//tag::delete-role-execute-async
client.security().deleteRoleAsync(deleteRoleRequest, RequestOptions.DEFAULT, listener); // <1>
//end::delete-role-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testPutRole() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// tag::put-role-request
final Role role = Role.builder()
.name("testPutRole")
.clusterPrivileges(randomSubsetOf(1, Role.ClusterPrivilegeName.ALL_ARRAY))
.build();
final PutRoleRequest request = new PutRoleRequest(role, RefreshPolicy.NONE);
// end::put-role-request
// tag::put-role-execute
final PutRoleResponse response = client.security().putRole(request, RequestOptions.DEFAULT);
// end::put-role-execute
// tag::put-role-response
boolean isCreated = response.isCreated(); // <1>
// end::put-role-response
assertTrue(isCreated);
}
{
final Role role = Role.builder()
.name("testPutRole")
.clusterPrivileges(randomSubsetOf(1, Role.ClusterPrivilegeName.ALL_ARRAY))
.build();
final PutRoleRequest request = new PutRoleRequest(role, RefreshPolicy.NONE);
// tag::put-role-execute-listener
ActionListener<PutRoleResponse> listener = new ActionListener<PutRoleResponse>() {
@Override
public void onResponse(PutRoleResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-role-execute-listener
// Avoid unused variable warning
assertNotNull(listener);
// Replace the empty listener by a blocking listener in test
final PlainActionFuture<PutRoleResponse> future = new PlainActionFuture<>();
listener = future;
// tag::put-role-execute-async
client.security().putRoleAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-role-execute-async
assertNotNull(future.get(30, TimeUnit.SECONDS));
assertThat(future.get().isCreated(), is(false)); // false because it has already been created by the sync variant
}
}
private void addRole(String roleName) throws IOException {
final Role role = Role.builder()
.name(roleName)
.clusterPrivileges("all")
.build();
final PutRoleRequest request = new PutRoleRequest(role, RefreshPolicy.IMMEDIATE);
highLevelClient().security().putRole(request, RequestOptions.DEFAULT);
}
public void testCreateToken() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// Setup user
User token_user = new User("token_user", Collections.singletonList("kibana_user"));
PutUserRequest putUserRequest = new PutUserRequest(token_user, "password".toCharArray(), true, RefreshPolicy.IMMEDIATE);
PutUserResponse putUserResponse = client.security().putUser(putUserRequest, RequestOptions.DEFAULT);
assertTrue(putUserResponse.isCreated());
}
{
// tag::create-token-password-request
final char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
CreateTokenRequest createTokenRequest = CreateTokenRequest.passwordGrant("token_user", password);
// end::create-token-password-request
// tag::create-token-execute
CreateTokenResponse createTokenResponse = client.security().createToken(createTokenRequest, RequestOptions.DEFAULT);
// end::create-token-execute
// tag::create-token-response
String accessToken = createTokenResponse.getAccessToken(); // <1>
String refreshToken = createTokenResponse.getRefreshToken(); // <2>
// end::create-token-response
assertNotNull(accessToken);
assertNotNull(refreshToken);
assertNotNull(createTokenResponse.getExpiresIn());
// tag::create-token-refresh-request
createTokenRequest = CreateTokenRequest.refreshTokenGrant(refreshToken);
// end::create-token-refresh-request
CreateTokenResponse refreshResponse = client.security().createToken(createTokenRequest, RequestOptions.DEFAULT);
assertNotNull(refreshResponse.getAccessToken());
assertNotNull(refreshResponse.getRefreshToken());
}
{
// tag::create-token-client-credentials-request
CreateTokenRequest createTokenRequest = CreateTokenRequest.clientCredentialsGrant();
// end::create-token-client-credentials-request
ActionListener<CreateTokenResponse> listener;
//tag::create-token-execute-listener
listener = new ActionListener<CreateTokenResponse>() {
@Override
public void onResponse(CreateTokenResponse createTokenResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::create-token-execute-listener
// Avoid unused variable warning
assertNotNull(listener);
// Replace the empty listener by a blocking listener in test
final PlainActionFuture<CreateTokenResponse> future = new PlainActionFuture<>();
listener = future;
//tag::create-token-execute-async
client.security().createTokenAsync(createTokenRequest, RequestOptions.DEFAULT, listener); // <1>
//end::create-token-execute-async
assertNotNull(future.get(30, TimeUnit.SECONDS));
assertNotNull(future.get().getAccessToken());
// "client-credentials" grants aren't refreshable
assertNull(future.get().getRefreshToken());
}
}
public void testInvalidateToken() throws Exception {
RestHighLevelClient client = highLevelClient();
String accessToken;
String refreshToken;
{
// Setup user
final char[] password = "password".toCharArray();
User invalidate_token_user = new User("invalidate_token", Collections.singletonList("kibana_user"));
PutUserRequest putUserRequest = new PutUserRequest(invalidate_token_user, password, true, RefreshPolicy.IMMEDIATE);
PutUserResponse putUserResponse = client.security().putUser(putUserRequest, RequestOptions.DEFAULT);
assertTrue(putUserResponse.isCreated());
// Create tokens
final CreateTokenRequest createTokenRequest = CreateTokenRequest.passwordGrant("invalidate_token", password);
final CreateTokenResponse tokenResponse = client.security().createToken(createTokenRequest, RequestOptions.DEFAULT);
accessToken = tokenResponse.getAccessToken();
refreshToken = tokenResponse.getRefreshToken();
}
{
// tag::invalidate-access-token-request
InvalidateTokenRequest invalidateTokenRequest = InvalidateTokenRequest.accessToken(accessToken);
// end::invalidate-access-token-request
// tag::invalidate-token-execute
InvalidateTokenResponse invalidateTokenResponse =
client.security().invalidateToken(invalidateTokenRequest, RequestOptions.DEFAULT);
// end::invalidate-token-execute
// tag::invalidate-token-response
boolean isCreated = invalidateTokenResponse.isCreated();
// end::invalidate-token-response
assertTrue(isCreated);
}
{
// tag::invalidate-refresh-token-request
InvalidateTokenRequest invalidateTokenRequest = InvalidateTokenRequest.refreshToken(refreshToken);
// end::invalidate-refresh-token-request
ActionListener<InvalidateTokenResponse> listener;
//tag::invalidate-token-execute-listener
listener = new ActionListener<InvalidateTokenResponse>() {
@Override
public void onResponse(InvalidateTokenResponse invalidateTokenResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::invalidate-token-execute-listener
// Avoid unused variable warning
assertNotNull(listener);
// Replace the empty listener by a blocking listener in test
final PlainActionFuture<InvalidateTokenResponse> future = new PlainActionFuture<>();
listener = future;
//tag::invalidate-token-execute-async
client.security().invalidateTokenAsync(invalidateTokenRequest, RequestOptions.DEFAULT, listener); // <1>
//end::invalidate-token-execute-async
final InvalidateTokenResponse response = future.get(30, TimeUnit.SECONDS);
assertNotNull(response);
assertTrue(response.isCreated());// technically, this should be false, but the API is broken
// See https://github.com/elastic/elasticsearch/issues/35115
}
}
public void testGetPrivileges() throws Exception {
final RestHighLevelClient client = highLevelClient();
final ApplicationPrivilege readTestappPrivilege =
new ApplicationPrivilege("testapp", "read", Arrays.asList("action:login", "data:read/*"), null);
final Map<String, Object> metadata = new HashMap<>();
metadata.put("key1", "value1");
final ApplicationPrivilege writeTestappPrivilege =
new ApplicationPrivilege("testapp", "write", Arrays.asList("action:login", "data:write/*"), metadata);
final ApplicationPrivilege allTestappPrivilege =
new ApplicationPrivilege("testapp", "all", Arrays.asList("action:login", "data:write/*", "manage:*"), null);
final Map<String, Object> metadata2 = new HashMap<>();
metadata2.put("key2", "value2");
final ApplicationPrivilege readTestapp2Privilege =
new ApplicationPrivilege("testapp2", "read", Arrays.asList("action:login", "data:read/*"), metadata2);
final ApplicationPrivilege writeTestapp2Privilege =
new ApplicationPrivilege("testapp2", "write", Arrays.asList("action:login", "data:write/*"), null);
final ApplicationPrivilege allTestapp2Privilege =
new ApplicationPrivilege("testapp2", "all", Arrays.asList("action:login", "data:write/*", "manage:*"), null);
{
List<ApplicationPrivilege> applicationPrivileges = new ArrayList<>();
applicationPrivileges.add(readTestappPrivilege);
applicationPrivileges.add(writeTestappPrivilege);
applicationPrivileges.add(allTestappPrivilege);
applicationPrivileges.add(readTestapp2Privilege);
applicationPrivileges.add(writeTestapp2Privilege);
applicationPrivileges.add(allTestapp2Privilege);
PutPrivilegesRequest putPrivilegesRequest = new PutPrivilegesRequest(applicationPrivileges, RefreshPolicy.IMMEDIATE);
PutPrivilegesResponse putPrivilegesResponse = client.security().putPrivileges(putPrivilegesRequest, RequestOptions.DEFAULT);
assertNotNull(putPrivilegesResponse);
assertThat(putPrivilegesResponse.wasCreated("testapp", "write"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp", "read"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp", "all"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp2", "all"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp2", "write"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp2", "read"), is(true));
}
{
//tag::get-privileges-request
GetPrivilegesRequest request = new GetPrivilegesRequest("testapp", "write");
//end::get-privileges-request
//tag::get-privileges-execute
GetPrivilegesResponse response = client.security().getPrivileges(request, RequestOptions.DEFAULT);
//end::get-privileges-execute
assertNotNull(response);
assertThat(response.getPrivileges().size(), equalTo(1));
assertThat(response.getPrivileges().contains(writeTestappPrivilege), equalTo(true));
}
{
//tag::get-all-application-privileges-request
GetPrivilegesRequest request = GetPrivilegesRequest.getApplicationPrivileges("testapp");
//end::get-all-application-privileges-request
GetPrivilegesResponse response = client.security().getPrivileges(request, RequestOptions.DEFAULT);
assertNotNull(response);
assertThat(response.getPrivileges().size(), equalTo(3));
final GetPrivilegesResponse exptectedResponse =
new GetPrivilegesResponse(Arrays.asList(readTestappPrivilege, writeTestappPrivilege, allTestappPrivilege));
assertThat(response, equalTo(exptectedResponse));
//tag::get-privileges-response
Set<ApplicationPrivilege> privileges = response.getPrivileges();
//end::get-privileges-response
for (ApplicationPrivilege privilege : privileges) {
assertThat(privilege.getApplication(), equalTo("testapp"));
if (privilege.getName().equals("read")) {
assertThat(privilege.getActions(), containsInAnyOrder("action:login", "data:read/*"));
assertThat(privilege.getMetadata().isEmpty(), equalTo(true));
} else if (privilege.getName().equals("write")) {
assertThat(privilege.getActions(), containsInAnyOrder("action:login", "data:write/*"));
assertThat(privilege.getMetadata().isEmpty(), equalTo(false));
assertThat(privilege.getMetadata().get("key1"), equalTo("value1"));
} else if (privilege.getName().equals("all")) {
assertThat(privilege.getActions(), containsInAnyOrder("action:login", "data:write/*", "manage:*"));
assertThat(privilege.getMetadata().isEmpty(), equalTo(true));
}
}
}
{
//tag::get-all-privileges-request
GetPrivilegesRequest request = GetPrivilegesRequest.getAllPrivileges();
//end::get-all-privileges-request
GetPrivilegesResponse response = client.security().getPrivileges(request, RequestOptions.DEFAULT);
assertNotNull(response);
assertThat(response.getPrivileges().size(), equalTo(6));
final GetPrivilegesResponse exptectedResponse =
new GetPrivilegesResponse(Arrays.asList(readTestappPrivilege, writeTestappPrivilege, allTestappPrivilege,
readTestapp2Privilege, writeTestapp2Privilege, allTestapp2Privilege));
assertThat(response, equalTo(exptectedResponse));
}
{
GetPrivilegesRequest request = new GetPrivilegesRequest("testapp", "read");
//tag::get-privileges-execute-listener
ActionListener<GetPrivilegesResponse> listener = new ActionListener<GetPrivilegesResponse>() {
@Override
public void onResponse(GetPrivilegesResponse getPrivilegesResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::get-privileges-execute-listener
// Avoid unused variable warning
assertNotNull(listener);
// Replace the empty listener by a blocking listener in test
final PlainActionFuture<GetPrivilegesResponse> future = new PlainActionFuture<>();
listener = future;
//tag::get-privileges-execute-async
client.security().getPrivilegesAsync(request, RequestOptions.DEFAULT, listener); // <1>
//end::get-privileges-execute-async
final GetPrivilegesResponse response = future.get(30, TimeUnit.SECONDS);
assertNotNull(response);
assertThat(response.getPrivileges().size(), equalTo(1));
assertThat(response.getPrivileges().contains(readTestappPrivilege), equalTo(true));
}
}
public void testPutPrivileges() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// tag::put-privileges-request
final List<ApplicationPrivilege> privileges = new ArrayList<>();
privileges.add(ApplicationPrivilege.builder()
.application("app01")
.privilege("all")
.actions(Sets.newHashSet("action:login"))
.metadata(Collections.singletonMap("k1", "v1"))
.build());
privileges.add(ApplicationPrivilege.builder()
.application("app01")
.privilege("write")
.actions(Sets.newHashSet("action:write"))
.build());
final PutPrivilegesRequest putPrivilegesRequest = new PutPrivilegesRequest(privileges, RefreshPolicy.IMMEDIATE);
// end::put-privileges-request
// tag::put-privileges-execute
final PutPrivilegesResponse putPrivilegesResponse = client.security().putPrivileges(putPrivilegesRequest,
RequestOptions.DEFAULT);
// end::put-privileges-execute
final String applicationName = "app01";
final String privilegeName = "all";
// tag::put-privileges-response
final boolean status = putPrivilegesResponse.wasCreated(applicationName, privilegeName); // <1>
// end::put-privileges-response
assertThat(status, is(true));
}
{
final List<ApplicationPrivilege> privileges = new ArrayList<>();
privileges.add(ApplicationPrivilege.builder()
.application("app01")
.privilege("all")
.actions(Sets.newHashSet("action:login"))
.metadata(Collections.singletonMap("k1", "v1"))
.build());
final PutPrivilegesRequest putPrivilegesRequest = new PutPrivilegesRequest(privileges, RefreshPolicy.IMMEDIATE);
// tag::put-privileges-execute-listener
ActionListener<PutPrivilegesResponse> listener = new ActionListener<PutPrivilegesResponse>() {
@Override
public void onResponse(PutPrivilegesResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-privileges-execute-listener
// Avoid unused variable warning
assertNotNull(listener);
// Replace the empty listener by a blocking listener in test
final PlainActionFuture<PutPrivilegesResponse> future = new PlainActionFuture<>();
listener = future;
//tag::put-privileges-execute-async
client.security().putPrivilegesAsync(putPrivilegesRequest, RequestOptions.DEFAULT, listener); // <1>
//end::put-privileges-execute-async
assertNotNull(future.get(30, TimeUnit.SECONDS));
assertThat(future.get().wasCreated("app01", "all"), is(false));
}
}
public void testDeletePrivilege() throws Exception {
RestHighLevelClient client = highLevelClient();
{
List<ApplicationPrivilege> applicationPrivileges = new ArrayList<>();
applicationPrivileges.add(ApplicationPrivilege.builder()
.application("testapp")
.privilege("read")
.actions("action:login", "data:read/*")
.build());
applicationPrivileges.add(ApplicationPrivilege.builder()
.application("testapp")
.privilege("write")
.actions("action:login", "data:write/*")
.build());
applicationPrivileges.add(ApplicationPrivilege.builder()
.application("testapp")
.privilege("all")
.actions("action:login", "data:write/*")
.build());
PutPrivilegesRequest putPrivilegesRequest = new PutPrivilegesRequest(applicationPrivileges, RefreshPolicy.IMMEDIATE);
PutPrivilegesResponse putPrivilegesResponse = client.security().putPrivileges(putPrivilegesRequest, RequestOptions.DEFAULT);
assertNotNull(putPrivilegesResponse);
assertThat(putPrivilegesResponse.wasCreated("testapp", "write"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp", "read"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp", "all"), is(true));
}
{
// tag::delete-privileges-request
DeletePrivilegesRequest request = new DeletePrivilegesRequest(
"testapp", // <1>
"read", "write"); // <2>
// end::delete-privileges-request
// tag::delete-privileges-execute
DeletePrivilegesResponse response = client.security().deletePrivileges(request, RequestOptions.DEFAULT);
// end::delete-privileges-execute
// tag::delete-privileges-response
String application = response.getApplication(); // <1>
boolean found = response.isFound("read"); // <2>
// end::delete-privileges-response
assertThat(application, equalTo("testapp"));
assertTrue(response.isFound("write"));
assertTrue(found);
// check if deleting the already deleted privileges again will give us a different response
response = client.security().deletePrivileges(request, RequestOptions.DEFAULT);
assertFalse(response.isFound("write"));
}
{
DeletePrivilegesRequest deletePrivilegesRequest = new DeletePrivilegesRequest("testapp", "all");
ActionListener<DeletePrivilegesResponse> listener;
//tag::delete-privileges-execute-listener
listener = new ActionListener<DeletePrivilegesResponse>() {
@Override
public void onResponse(DeletePrivilegesResponse deletePrivilegesResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::delete-privileges-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
//tag::delete-privileges-execute-async
client.security().deletePrivilegesAsync(deletePrivilegesRequest, RequestOptions.DEFAULT, listener); // <1>
//end::delete-privileges-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
}
|
client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SecurityDocumentationIT.java
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.client.documentation;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.LatchedActionListener;
import org.elasticsearch.action.support.PlainActionFuture;
import org.elasticsearch.client.ESRestHighLevelClientTestCase;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.security.AuthenticateResponse;
import org.elasticsearch.client.security.ChangePasswordRequest;
import org.elasticsearch.client.security.ClearRealmCacheRequest;
import org.elasticsearch.client.security.ClearRealmCacheResponse;
import org.elasticsearch.client.security.ClearRolesCacheRequest;
import org.elasticsearch.client.security.ClearRolesCacheResponse;
import org.elasticsearch.client.security.CreateTokenRequest;
import org.elasticsearch.client.security.CreateTokenResponse;
import org.elasticsearch.client.security.DeletePrivilegesRequest;
import org.elasticsearch.client.security.DeletePrivilegesResponse;
import org.elasticsearch.client.security.DeleteRoleMappingRequest;
import org.elasticsearch.client.security.DeleteRoleMappingResponse;
import org.elasticsearch.client.security.DeleteRoleRequest;
import org.elasticsearch.client.security.DeleteRoleResponse;
import org.elasticsearch.client.security.DeleteUserRequest;
import org.elasticsearch.client.security.DeleteUserResponse;
import org.elasticsearch.client.security.DisableUserRequest;
import org.elasticsearch.client.security.EmptyResponse;
import org.elasticsearch.client.security.EnableUserRequest;
import org.elasticsearch.client.security.ExpressionRoleMapping;
import org.elasticsearch.client.security.GetPrivilegesRequest;
import org.elasticsearch.client.security.GetPrivilegesResponse;
import org.elasticsearch.client.security.GetRoleMappingsRequest;
import org.elasticsearch.client.security.GetRoleMappingsResponse;
import org.elasticsearch.client.security.GetRolesRequest;
import org.elasticsearch.client.security.GetRolesResponse;
import org.elasticsearch.client.security.GetSslCertificatesResponse;
import org.elasticsearch.client.security.HasPrivilegesRequest;
import org.elasticsearch.client.security.HasPrivilegesResponse;
import org.elasticsearch.client.security.InvalidateTokenRequest;
import org.elasticsearch.client.security.InvalidateTokenResponse;
import org.elasticsearch.client.security.PutPrivilegesRequest;
import org.elasticsearch.client.security.PutPrivilegesResponse;
import org.elasticsearch.client.security.PutRoleMappingRequest;
import org.elasticsearch.client.security.PutRoleMappingResponse;
import org.elasticsearch.client.security.PutRoleRequest;
import org.elasticsearch.client.security.PutRoleResponse;
import org.elasticsearch.client.security.PutUserRequest;
import org.elasticsearch.client.security.PutUserResponse;
import org.elasticsearch.client.security.RefreshPolicy;
import org.elasticsearch.client.security.support.CertificateInfo;
import org.elasticsearch.client.security.support.expressiondsl.RoleMapperExpression;
import org.elasticsearch.client.security.support.expressiondsl.expressions.AnyRoleMapperExpression;
import org.elasticsearch.client.security.support.expressiondsl.fields.FieldRoleMapperExpression;
import org.elasticsearch.client.security.user.User;
import org.elasticsearch.client.security.user.privileges.Role;
import org.elasticsearch.client.security.user.privileges.ApplicationPrivilege;
import org.elasticsearch.client.security.user.privileges.IndicesPrivileges;
import org.elasticsearch.common.util.set.Sets;
import org.hamcrest.Matchers;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.emptyIterable;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
public class SecurityDocumentationIT extends ESRestHighLevelClientTestCase {
public void testPutUser() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::put-user-password-request
char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
User user = new User("example", Collections.singletonList("superuser"));
PutUserRequest request = PutUserRequest.withPassword(user, password, true, RefreshPolicy.NONE);
//end::put-user-password-request
//tag::put-user-execute
PutUserResponse response = client.security().putUser(request, RequestOptions.DEFAULT);
//end::put-user-execute
//tag::put-user-response
boolean isCreated = response.isCreated(); // <1>
//end::put-user-response
assertTrue(isCreated);
}
{
byte[] salt = new byte[32];
SecureRandom.getInstanceStrong().nextBytes(salt);
char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
User user = new User("example2", Collections.singletonList("superuser"));
//tag::put-user-hash-request
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2withHMACSHA512");
PBEKeySpec keySpec = new PBEKeySpec(password, salt, 10000, 256);
final byte[] pbkdfEncoded = secretKeyFactory.generateSecret(keySpec).getEncoded();
char[] passwordHash = ("{PBKDF2}10000$" + Base64.getEncoder().encodeToString(salt)
+ "$" + Base64.getEncoder().encodeToString(pbkdfEncoded)).toCharArray();
PutUserRequest request = PutUserRequest.withPasswordHash(user, passwordHash, true, RefreshPolicy.NONE);
//end::put-user-hash-request
try {
client.security().putUser(request, RequestOptions.DEFAULT);
} catch (ElasticsearchStatusException e) {
// This is expected to fail as the server will not be using PBKDF2, but that's easiest hasher to support
// in a standard JVM without introducing additional libraries.
assertThat(e.getDetailedMessage(), containsString("PBKDF2"));
}
}
{
User user = new User("example", Arrays.asList("superuser", "another-role"));
//tag::put-user-update-request
PutUserRequest request = PutUserRequest.updateUser(user, true, RefreshPolicy.NONE);
//end::put-user-update-request
// tag::put-user-execute-listener
ActionListener<PutUserResponse> listener = new ActionListener<PutUserResponse>() {
@Override
public void onResponse(PutUserResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-user-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::put-user-execute-async
client.security().putUserAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-user-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteUser() throws Exception {
RestHighLevelClient client = highLevelClient();
addUser(client, "testUser", "testPassword");
{
// tag::delete-user-request
DeleteUserRequest deleteUserRequest = new DeleteUserRequest(
"testUser"); // <1>
// end::delete-user-request
// tag::delete-user-execute
DeleteUserResponse deleteUserResponse = client.security().deleteUser(deleteUserRequest, RequestOptions.DEFAULT);
// end::delete-user-execute
// tag::delete-user-response
boolean found = deleteUserResponse.isAcknowledged(); // <1>
// end::delete-user-response
assertTrue(found);
// check if deleting the already deleted user again will give us a different response
deleteUserResponse = client.security().deleteUser(deleteUserRequest, RequestOptions.DEFAULT);
assertFalse(deleteUserResponse.isAcknowledged());
}
{
DeleteUserRequest deleteUserRequest = new DeleteUserRequest("testUser", RefreshPolicy.IMMEDIATE);
ActionListener<DeleteUserResponse> listener;
//tag::delete-user-execute-listener
listener = new ActionListener<DeleteUserResponse>() {
@Override
public void onResponse(DeleteUserResponse deleteUserResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::delete-user-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
//tag::delete-user-execute-async
client.security().deleteUserAsync(deleteUserRequest, RequestOptions.DEFAULT, listener); // <1>
//end::delete-user-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
private void addUser(RestHighLevelClient client, String userName, String password) throws IOException {
User user = new User(userName, Collections.singletonList(userName));
PutUserRequest request = new PutUserRequest(user, password.toCharArray(), true, RefreshPolicy.NONE);
PutUserResponse response = client.security().putUser(request, RequestOptions.DEFAULT);
assertTrue(response.isCreated());
}
public void testPutRoleMapping() throws Exception {
final RestHighLevelClient client = highLevelClient();
{
// tag::put-role-mapping-execute
final RoleMapperExpression rules = AnyRoleMapperExpression.builder()
.addExpression(FieldRoleMapperExpression.ofUsername("*"))
.addExpression(FieldRoleMapperExpression.ofGroups("cn=admins,dc=example,dc=com"))
.build();
final PutRoleMappingRequest request = new PutRoleMappingRequest("mapping-example", true, Collections.singletonList("superuser"),
rules, null, RefreshPolicy.NONE);
final PutRoleMappingResponse response = client.security().putRoleMapping(request, RequestOptions.DEFAULT);
// end::put-role-mapping-execute
// tag::put-role-mapping-response
boolean isCreated = response.isCreated(); // <1>
// end::put-role-mapping-response
assertTrue(isCreated);
}
{
final RoleMapperExpression rules = AnyRoleMapperExpression.builder()
.addExpression(FieldRoleMapperExpression.ofUsername("*"))
.addExpression(FieldRoleMapperExpression.ofGroups("cn=admins,dc=example,dc=com"))
.build();
final PutRoleMappingRequest request = new PutRoleMappingRequest("mapping-example", true, Collections.singletonList("superuser"),
rules, null, RefreshPolicy.NONE);
// tag::put-role-mapping-execute-listener
ActionListener<PutRoleMappingResponse> listener = new ActionListener<PutRoleMappingResponse>() {
@Override
public void onResponse(PutRoleMappingResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-role-mapping-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::put-role-mapping-execute-async
client.security().putRoleMappingAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-role-mapping-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetRoleMappings() throws Exception {
final RestHighLevelClient client = highLevelClient();
final RoleMapperExpression rules1 = AnyRoleMapperExpression.builder().addExpression(FieldRoleMapperExpression.ofUsername("*"))
.addExpression(FieldRoleMapperExpression.ofGroups("cn=admins,dc=example,dc=com")).build();
final PutRoleMappingRequest putRoleMappingRequest1 = new PutRoleMappingRequest("mapping-example-1", true, Collections.singletonList(
"superuser"), rules1, null, RefreshPolicy.NONE);
final PutRoleMappingResponse putRoleMappingResponse1 = client.security().putRoleMapping(putRoleMappingRequest1,
RequestOptions.DEFAULT);
boolean isCreated1 = putRoleMappingResponse1.isCreated();
assertTrue(isCreated1);
final RoleMapperExpression rules2 = AnyRoleMapperExpression.builder().addExpression(FieldRoleMapperExpression.ofGroups(
"cn=admins,dc=example,dc=com")).build();
final Map<String, Object> metadata2 = new HashMap<>();
metadata2.put("k1", "v1");
final PutRoleMappingRequest putRoleMappingRequest2 = new PutRoleMappingRequest("mapping-example-2", true, Collections.singletonList(
"monitoring"), rules2, metadata2, RefreshPolicy.NONE);
final PutRoleMappingResponse putRoleMappingResponse2 = client.security().putRoleMapping(putRoleMappingRequest2,
RequestOptions.DEFAULT);
boolean isCreated2 = putRoleMappingResponse2.isCreated();
assertTrue(isCreated2);
{
// tag::get-role-mappings-execute
final GetRoleMappingsRequest request = new GetRoleMappingsRequest("mapping-example-1");
final GetRoleMappingsResponse response = client.security().getRoleMappings(request, RequestOptions.DEFAULT);
// end::get-role-mappings-execute
// tag::get-role-mappings-response
List<ExpressionRoleMapping> mappings = response.getMappings();
// end::get-role-mappings-response
assertNotNull(mappings);
assertThat(mappings.size(), is(1));
assertThat(mappings.get(0).isEnabled(), is(true));
assertThat(mappings.get(0).getName(), is("mapping-example-1"));
assertThat(mappings.get(0).getExpression(), equalTo(rules1));
assertThat(mappings.get(0).getMetadata(), equalTo(Collections.emptyMap()));
assertThat(mappings.get(0).getRoles(), contains("superuser"));
}
{
// tag::get-role-mappings-list-execute
final GetRoleMappingsRequest request = new GetRoleMappingsRequest("mapping-example-1", "mapping-example-2");
final GetRoleMappingsResponse response = client.security().getRoleMappings(request, RequestOptions.DEFAULT);
// end::get-role-mappings-list-execute
List<ExpressionRoleMapping> mappings = response.getMappings();
assertNotNull(mappings);
assertThat(mappings.size(), is(2));
for (ExpressionRoleMapping roleMapping : mappings) {
assertThat(roleMapping.isEnabled(), is(true));
assertThat(roleMapping.getName(), isIn(new String[]{"mapping-example-1", "mapping-example-2"}));
if (roleMapping.getName().equals("mapping-example-1")) {
assertThat(roleMapping.getMetadata(), equalTo(Collections.emptyMap()));
assertThat(roleMapping.getExpression(), equalTo(rules1));
assertThat(roleMapping.getRoles(), contains("superuser"));
} else {
assertThat(roleMapping.getMetadata(), equalTo(metadata2));
assertThat(roleMapping.getExpression(), equalTo(rules2));
assertThat(roleMapping.getRoles(), contains("monitoring"));
}
}
}
{
// tag::get-role-mappings-all-execute
final GetRoleMappingsRequest request = new GetRoleMappingsRequest();
final GetRoleMappingsResponse response = client.security().getRoleMappings(request, RequestOptions.DEFAULT);
// end::get-role-mappings-all-execute
List<ExpressionRoleMapping> mappings = response.getMappings();
assertNotNull(mappings);
assertThat(mappings.size(), is(2));
for (ExpressionRoleMapping roleMapping : mappings) {
assertThat(roleMapping.isEnabled(), is(true));
assertThat(roleMapping.getName(), isIn(new String[]{"mapping-example-1", "mapping-example-2"}));
if (roleMapping.getName().equals("mapping-example-1")) {
assertThat(roleMapping.getMetadata(), equalTo(Collections.emptyMap()));
assertThat(roleMapping.getExpression(), equalTo(rules1));
assertThat(roleMapping.getRoles(), contains("superuser"));
} else {
assertThat(roleMapping.getMetadata(), equalTo(metadata2));
assertThat(roleMapping.getExpression(), equalTo(rules2));
assertThat(roleMapping.getRoles(), contains("monitoring"));
}
}
}
{
final GetRoleMappingsRequest request = new GetRoleMappingsRequest();
// tag::get-role-mappings-execute-listener
ActionListener<GetRoleMappingsResponse> listener = new ActionListener<GetRoleMappingsResponse>() {
@Override
public void onResponse(GetRoleMappingsResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-role-mappings-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-role-mappings-execute-async
client.security().getRoleMappingsAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::get-role-mappings-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testEnableUser() throws Exception {
RestHighLevelClient client = highLevelClient();
char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
User enable_user = new User("enable_user", Collections.singletonList("superuser"));
PutUserRequest putUserRequest = new PutUserRequest(enable_user, password, true, RefreshPolicy.IMMEDIATE);
PutUserResponse putUserResponse = client.security().putUser(putUserRequest, RequestOptions.DEFAULT);
assertTrue(putUserResponse.isCreated());
{
//tag::enable-user-execute
EnableUserRequest request = new EnableUserRequest("enable_user", RefreshPolicy.NONE);
EmptyResponse response = client.security().enableUser(request, RequestOptions.DEFAULT);
//end::enable-user-execute
assertNotNull(response);
}
{
//tag::enable-user-execute-listener
EnableUserRequest request = new EnableUserRequest("enable_user", RefreshPolicy.NONE);
ActionListener<EmptyResponse> listener = new ActionListener<EmptyResponse>() {
@Override
public void onResponse(EmptyResponse setUserEnabledResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::enable-user-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::enable-user-execute-async
client.security().enableUserAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::enable-user-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDisableUser() throws Exception {
RestHighLevelClient client = highLevelClient();
char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
User disable_user = new User("disable_user", Collections.singletonList("superuser"));
PutUserRequest putUserRequest = new PutUserRequest(disable_user, password, true, RefreshPolicy.IMMEDIATE);
PutUserResponse putUserResponse = client.security().putUser(putUserRequest, RequestOptions.DEFAULT);
assertTrue(putUserResponse.isCreated());
{
//tag::disable-user-execute
DisableUserRequest request = new DisableUserRequest("disable_user", RefreshPolicy.NONE);
EmptyResponse response = client.security().disableUser(request, RequestOptions.DEFAULT);
//end::disable-user-execute
assertNotNull(response);
}
{
//tag::disable-user-execute-listener
DisableUserRequest request = new DisableUserRequest("disable_user", RefreshPolicy.NONE);
ActionListener<EmptyResponse> listener = new ActionListener<EmptyResponse>() {
@Override
public void onResponse(EmptyResponse setUserEnabledResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::disable-user-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::disable-user-execute-async
client.security().disableUserAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::disable-user-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetRoles() throws Exception {
final RestHighLevelClient client = highLevelClient();
addRole("my_role");
addRole("my_role2");
addRole("my_role3");
{
//tag::get-roles-request
GetRolesRequest request = new GetRolesRequest("my_role");
//end::get-roles-request
//tag::get-roles-execute
GetRolesResponse response = client.security().getRoles(request, RequestOptions.DEFAULT);
//end::get-roles-execute
//tag::get-roles-response
List<Role> roles = response.getRoles();
//end::get-roles-response
assertNotNull(response);
assertThat(roles.size(), equalTo(1));
assertThat(roles.get(0).getName(), equalTo("my_role"));
assertThat(roles.get(0).getClusterPrivileges().contains("all"), equalTo(true));
}
{
//tag::get-roles-list-request
GetRolesRequest request = new GetRolesRequest("my_role", "my_role2");
GetRolesResponse response = client.security().getRoles(request, RequestOptions.DEFAULT);
//end::get-roles-list-request
List<Role> roles = response.getRoles();
assertNotNull(response);
assertThat(roles.size(), equalTo(2));
assertThat(roles.get(0).getClusterPrivileges().contains("all"), equalTo(true));
assertThat(roles.get(1).getClusterPrivileges().contains("all"), equalTo(true));
}
{
//tag::get-roles-all-request
GetRolesRequest request = new GetRolesRequest();
GetRolesResponse response = client.security().getRoles(request, RequestOptions.DEFAULT);
//end::get-roles-all-request
List<Role> roles = response.getRoles();
assertNotNull(response);
// 21 system roles plus the three we created
assertThat(roles.size(), equalTo(24));
}
{
GetRolesRequest request = new GetRolesRequest("my_role");
ActionListener<GetRolesResponse> listener;
//tag::get-roles-execute-listener
listener = new ActionListener<GetRolesResponse>() {
@Override
public void onResponse(GetRolesResponse getRolesResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::get-roles-execute-listener
assertNotNull(listener);
// Replace the empty listener by a blocking listener in test
final PlainActionFuture<GetRolesResponse> future = new PlainActionFuture<>();
listener = future;
//tag::get-roles-execute-async
client.security().getRolesAsync(request, RequestOptions.DEFAULT, listener); // <1>
//end::get-roles-execute-async
final GetRolesResponse response = future.get(30, TimeUnit.SECONDS);
assertNotNull(response);
assertThat(response.getRoles().size(), equalTo(1));
assertThat(response.getRoles().get(0).getName(), equalTo("my_role"));
assertThat(response.getRoles().get(0).getClusterPrivileges().contains("all"), equalTo(true));
}
}
public void testAuthenticate() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::authenticate-execute
AuthenticateResponse response = client.security().authenticate(RequestOptions.DEFAULT);
//end::authenticate-execute
//tag::authenticate-response
User user = response.getUser(); // <1>
boolean enabled = response.enabled(); // <2>
final String authenticationRealmName = response.getAuthenticationRealm().getName(); // <3>
final String authenticationRealmType = response.getAuthenticationRealm().getType(); // <4>
final String lookupRealmName = response.getLookupRealm().getName(); // <5>
final String lookupRealmType = response.getLookupRealm().getType(); // <6>
//end::authenticate-response
assertThat(user.getUsername(), is("test_user"));
assertThat(user.getRoles(), contains(new String[]{"superuser"}));
assertThat(user.getFullName(), nullValue());
assertThat(user.getEmail(), nullValue());
assertThat(user.getMetadata().isEmpty(), is(true));
assertThat(enabled, is(true));
assertThat(authenticationRealmName, is("default_file"));
assertThat(authenticationRealmType, is("file"));
assertThat(lookupRealmName, is("default_file"));
assertThat(lookupRealmType, is("file"));
}
{
// tag::authenticate-execute-listener
ActionListener<AuthenticateResponse> listener = new ActionListener<AuthenticateResponse>() {
@Override
public void onResponse(AuthenticateResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::authenticate-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::authenticate-execute-async
client.security().authenticateAsync(RequestOptions.DEFAULT, listener); // <1>
// end::authenticate-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testHasPrivileges() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::has-privileges-request
HasPrivilegesRequest request = new HasPrivilegesRequest(
Sets.newHashSet("monitor", "manage"),
Sets.newHashSet(
IndicesPrivileges.builder().indices("logstash-2018-10-05").privileges("read", "write").build(),
IndicesPrivileges.builder().indices("logstash-2018-*").privileges("read").build()
),
null
);
//end::has-privileges-request
//tag::has-privileges-execute
HasPrivilegesResponse response = client.security().hasPrivileges(request, RequestOptions.DEFAULT);
//end::has-privileges-execute
//tag::has-privileges-response
boolean hasMonitor = response.hasClusterPrivilege("monitor"); // <1>
boolean hasWrite = response.hasIndexPrivilege("logstash-2018-10-05", "write"); // <2>
boolean hasRead = response.hasIndexPrivilege("logstash-2018-*", "read"); // <3>
//end::has-privileges-response
assertThat(response.getUsername(), is("test_user"));
assertThat(response.hasAllRequested(), is(true));
assertThat(hasMonitor, is(true));
assertThat(hasWrite, is(true));
assertThat(hasRead, is(true));
assertThat(response.getApplicationPrivileges().entrySet(), emptyIterable());
}
{
HasPrivilegesRequest request = new HasPrivilegesRequest(Collections.singleton("monitor"), null, null);
// tag::has-privileges-execute-listener
ActionListener<HasPrivilegesResponse> listener = new ActionListener<HasPrivilegesResponse>() {
@Override
public void onResponse(HasPrivilegesResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::has-privileges-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::has-privileges-execute-async
client.security().hasPrivilegesAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::has-privileges-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testClearRealmCache() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::clear-realm-cache-request
ClearRealmCacheRequest request = new ClearRealmCacheRequest(Collections.emptyList(), Collections.emptyList());
//end::clear-realm-cache-request
//tag::clear-realm-cache-execute
ClearRealmCacheResponse response = client.security().clearRealmCache(request, RequestOptions.DEFAULT);
//end::clear-realm-cache-execute
assertNotNull(response);
assertThat(response.getNodes(), not(empty()));
//tag::clear-realm-cache-response
List<ClearRealmCacheResponse.Node> nodes = response.getNodes(); // <1>
//end::clear-realm-cache-response
}
{
//tag::clear-realm-cache-execute-listener
ClearRealmCacheRequest request = new ClearRealmCacheRequest(Collections.emptyList(), Collections.emptyList());
ActionListener<ClearRealmCacheResponse> listener = new ActionListener<ClearRealmCacheResponse>() {
@Override
public void onResponse(ClearRealmCacheResponse clearRealmCacheResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::clear-realm-cache-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::clear-realm-cache-execute-async
client.security().clearRealmCacheAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::clear-realm-cache-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testClearRolesCache() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::clear-roles-cache-request
ClearRolesCacheRequest request = new ClearRolesCacheRequest("my_role");
//end::clear-roles-cache-request
//tag::clear-roles-cache-execute
ClearRolesCacheResponse response = client.security().clearRolesCache(request, RequestOptions.DEFAULT);
//end::clear-roles-cache-execute
assertNotNull(response);
assertThat(response.getNodes(), not(empty()));
//tag::clear-roles-cache-response
List<ClearRolesCacheResponse.Node> nodes = response.getNodes(); // <1>
//end::clear-roles-cache-response
}
{
//tag::clear-roles-cache-execute-listener
ClearRolesCacheRequest request = new ClearRolesCacheRequest("my_role");
ActionListener<ClearRolesCacheResponse> listener = new ActionListener<ClearRolesCacheResponse>() {
@Override
public void onResponse(ClearRolesCacheResponse clearRolesCacheResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::clear-roles-cache-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::clear-roles-cache-execute-async
client.security().clearRolesCacheAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::clear-roles-cache-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testGetSslCertificates() throws Exception {
RestHighLevelClient client = highLevelClient();
{
//tag::get-certificates-execute
GetSslCertificatesResponse response = client.security().getSslCertificates(RequestOptions.DEFAULT);
//end::get-certificates-execute
assertNotNull(response);
//tag::get-certificates-response
List<CertificateInfo> certificates = response.getCertificates(); // <1>
//end::get-certificates-response
assertThat(certificates.size(), Matchers.equalTo(9));
final Iterator<CertificateInfo> it = certificates.iterator();
CertificateInfo c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=testnode-client-profile"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=Elasticsearch Test Node, OU=elasticsearch, O=org"));
assertThat(c.getPath(), Matchers.equalTo("testnode.crt"));
assertThat(c.getFormat(), Matchers.equalTo("PEM"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=OpenLDAP, OU=Elasticsearch, O=Elastic, L=Mountain View, ST=CA, C=US"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=Elasticsearch Test Node, OU=elasticsearch, O=org"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=Elasticsearch Test Client, OU=elasticsearch, O=org"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=ad-ELASTICSEARCHAD-CA, DC=ad, DC=test, DC=elasticsearch, DC=com"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=Elasticsearch Test Node"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=samba4"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
c = it.next();
assertThat(c.getSubjectDn(), Matchers.equalTo("CN=Elasticsearch Test Node"));
assertThat(c.getPath(), Matchers.equalTo("testnode.jks"));
assertThat(c.getFormat(), Matchers.equalTo("jks"));
}
{
// tag::get-certificates-execute-listener
ActionListener<GetSslCertificatesResponse> listener = new ActionListener<GetSslCertificatesResponse>() {
@Override
public void onResponse(GetSslCertificatesResponse getSslCertificatesResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::get-certificates-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::get-certificates-execute-async
client.security().getSslCertificatesAsync(RequestOptions.DEFAULT, listener); // <1>
// end::get-certificates-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testChangePassword() throws Exception {
RestHighLevelClient client = highLevelClient();
char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
char[] newPassword = new char[]{'n', 'e', 'w', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
User user = new User("change_password_user", Collections.singletonList("superuser"), Collections.emptyMap(), null, null);
PutUserRequest putUserRequest = new PutUserRequest(user, password, true, RefreshPolicy.NONE);
PutUserResponse putUserResponse = client.security().putUser(putUserRequest, RequestOptions.DEFAULT);
assertTrue(putUserResponse.isCreated());
{
//tag::change-password-execute
ChangePasswordRequest request = new ChangePasswordRequest("change_password_user", newPassword, RefreshPolicy.NONE);
EmptyResponse response = client.security().changePassword(request, RequestOptions.DEFAULT);
//end::change-password-execute
assertNotNull(response);
}
{
//tag::change-password-execute-listener
ChangePasswordRequest request = new ChangePasswordRequest("change_password_user", password, RefreshPolicy.NONE);
ActionListener<EmptyResponse> listener = new ActionListener<EmptyResponse>() {
@Override
public void onResponse(EmptyResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::change-password-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
//tag::change-password-execute-async
client.security().changePasswordAsync(request, RequestOptions.DEFAULT, listener); // <1>
//end::change-password-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteRoleMapping() throws Exception {
final RestHighLevelClient client = highLevelClient();
{
// Create role mappings
final RoleMapperExpression rules = FieldRoleMapperExpression.ofUsername("*");
final PutRoleMappingRequest request = new PutRoleMappingRequest("mapping-example", true, Collections.singletonList("superuser"),
rules, null, RefreshPolicy.NONE);
final PutRoleMappingResponse response = client.security().putRoleMapping(request, RequestOptions.DEFAULT);
boolean isCreated = response.isCreated();
assertTrue(isCreated);
}
{
// tag::delete-role-mapping-execute
final DeleteRoleMappingRequest request = new DeleteRoleMappingRequest("mapping-example", RefreshPolicy.NONE);
final DeleteRoleMappingResponse response = client.security().deleteRoleMapping(request, RequestOptions.DEFAULT);
// end::delete-role-mapping-execute
// tag::delete-role-mapping-response
boolean isFound = response.isFound(); // <1>
// end::delete-role-mapping-response
assertTrue(isFound);
}
{
final DeleteRoleMappingRequest request = new DeleteRoleMappingRequest("mapping-example", RefreshPolicy.NONE);
// tag::delete-role-mapping-execute-listener
ActionListener<DeleteRoleMappingResponse> listener = new ActionListener<DeleteRoleMappingResponse>() {
@Override
public void onResponse(DeleteRoleMappingResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::delete-role-mapping-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
// tag::delete-role-mapping-execute-async
client.security().deleteRoleMappingAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::delete-role-mapping-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testDeleteRole() throws Exception {
RestHighLevelClient client = highLevelClient();
addRole("testrole");
{
// tag::delete-role-request
DeleteRoleRequest deleteRoleRequest = new DeleteRoleRequest(
"testrole"); // <1>
// end::delete-role-request
// tag::delete-role-execute
DeleteRoleResponse deleteRoleResponse = client.security().deleteRole(deleteRoleRequest, RequestOptions.DEFAULT);
// end::delete-role-execute
// tag::delete-role-response
boolean found = deleteRoleResponse.isFound(); // <1>
// end::delete-role-response
assertTrue(found);
// check if deleting the already deleted role again will give us a different response
deleteRoleResponse = client.security().deleteRole(deleteRoleRequest, RequestOptions.DEFAULT);
assertFalse(deleteRoleResponse.isFound());
}
{
DeleteRoleRequest deleteRoleRequest = new DeleteRoleRequest("testrole");
ActionListener<DeleteRoleResponse> listener;
//tag::delete-role-execute-listener
listener = new ActionListener<DeleteRoleResponse>() {
@Override
public void onResponse(DeleteRoleResponse deleteRoleResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::delete-role-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
//tag::delete-role-execute-async
client.security().deleteRoleAsync(deleteRoleRequest, RequestOptions.DEFAULT, listener); // <1>
//end::delete-role-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
public void testPutRole() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// tag::put-role-request
final Role role = Role.builder()
.name("testPutRole")
.clusterPrivileges(randomSubsetOf(1, Role.ClusterPrivilegeName.ALL_ARRAY))
.build();
final PutRoleRequest request = new PutRoleRequest(role, RefreshPolicy.NONE);
// end::put-role-request
// tag::put-role-execute
final PutRoleResponse response = client.security().putRole(request, RequestOptions.DEFAULT);
// end::put-role-execute
// tag::put-role-response
boolean isCreated = response.isCreated(); // <1>
// end::put-role-response
assertTrue(isCreated);
}
{
final Role role = Role.builder()
.name("testPutRole")
.clusterPrivileges(randomSubsetOf(1, Role.ClusterPrivilegeName.ALL_ARRAY))
.build();
final PutRoleRequest request = new PutRoleRequest(role, RefreshPolicy.NONE);
// tag::put-role-execute-listener
ActionListener<PutRoleResponse> listener = new ActionListener<PutRoleResponse>() {
@Override
public void onResponse(PutRoleResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-role-execute-listener
// Avoid unused variable warning
assertNotNull(listener);
// Replace the empty listener by a blocking listener in test
final PlainActionFuture<PutRoleResponse> future = new PlainActionFuture<>();
listener = future;
// tag::put-role-execute-async
client.security().putRoleAsync(request, RequestOptions.DEFAULT, listener); // <1>
// end::put-role-execute-async
assertNotNull(future.get(30, TimeUnit.SECONDS));
assertThat(future.get().isCreated(), is(false)); // false because it has already been created by the sync variant
}
}
private void addRole(String roleName) throws IOException {
final Role role = Role.builder()
.name(roleName)
.clusterPrivileges("all")
.build();
final PutRoleRequest request = new PutRoleRequest(role, RefreshPolicy.IMMEDIATE);
highLevelClient().security().putRole(request, RequestOptions.DEFAULT);
}
public void testCreateToken() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// Setup user
User token_user = new User("token_user", Collections.singletonList("kibana_user"));
PutUserRequest putUserRequest = new PutUserRequest(token_user, "password".toCharArray(), true, RefreshPolicy.IMMEDIATE);
PutUserResponse putUserResponse = client.security().putUser(putUserRequest, RequestOptions.DEFAULT);
assertTrue(putUserResponse.isCreated());
}
{
// tag::create-token-password-request
final char[] password = new char[]{'p', 'a', 's', 's', 'w', 'o', 'r', 'd'};
CreateTokenRequest createTokenRequest = CreateTokenRequest.passwordGrant("token_user", password);
// end::create-token-password-request
// tag::create-token-execute
CreateTokenResponse createTokenResponse = client.security().createToken(createTokenRequest, RequestOptions.DEFAULT);
// end::create-token-execute
// tag::create-token-response
String accessToken = createTokenResponse.getAccessToken(); // <1>
String refreshToken = createTokenResponse.getRefreshToken(); // <2>
// end::create-token-response
assertNotNull(accessToken);
assertNotNull(refreshToken);
assertNotNull(createTokenResponse.getExpiresIn());
// tag::create-token-refresh-request
createTokenRequest = CreateTokenRequest.refreshTokenGrant(refreshToken);
// end::create-token-refresh-request
CreateTokenResponse refreshResponse = client.security().createToken(createTokenRequest, RequestOptions.DEFAULT);
assertNotNull(refreshResponse.getAccessToken());
assertNotNull(refreshResponse.getRefreshToken());
}
{
// tag::create-token-client-credentials-request
CreateTokenRequest createTokenRequest = CreateTokenRequest.clientCredentialsGrant();
// end::create-token-client-credentials-request
ActionListener<CreateTokenResponse> listener;
//tag::create-token-execute-listener
listener = new ActionListener<CreateTokenResponse>() {
@Override
public void onResponse(CreateTokenResponse createTokenResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::create-token-execute-listener
// Avoid unused variable warning
assertNotNull(listener);
// Replace the empty listener by a blocking listener in test
final PlainActionFuture<CreateTokenResponse> future = new PlainActionFuture<>();
listener = future;
//tag::create-token-execute-async
client.security().createTokenAsync(createTokenRequest, RequestOptions.DEFAULT, listener); // <1>
//end::create-token-execute-async
assertNotNull(future.get(30, TimeUnit.SECONDS));
assertNotNull(future.get().getAccessToken());
// "client-credentials" grants aren't refreshable
assertNull(future.get().getRefreshToken());
}
}
public void testInvalidateToken() throws Exception {
RestHighLevelClient client = highLevelClient();
String accessToken;
String refreshToken;
{
// Setup user
final char[] password = "password".toCharArray();
User invalidate_token_user = new User("invalidate_token", Collections.singletonList("kibana_user"));
PutUserRequest putUserRequest = new PutUserRequest(invalidate_token_user, password, true, RefreshPolicy.IMMEDIATE);
PutUserResponse putUserResponse = client.security().putUser(putUserRequest, RequestOptions.DEFAULT);
assertTrue(putUserResponse.isCreated());
// Create tokens
final CreateTokenRequest createTokenRequest = CreateTokenRequest.passwordGrant("invalidate_token", password);
final CreateTokenResponse tokenResponse = client.security().createToken(createTokenRequest, RequestOptions.DEFAULT);
accessToken = tokenResponse.getAccessToken();
refreshToken = tokenResponse.getRefreshToken();
}
{
// tag::invalidate-access-token-request
InvalidateTokenRequest invalidateTokenRequest = InvalidateTokenRequest.accessToken(accessToken);
// end::invalidate-access-token-request
// tag::invalidate-token-execute
InvalidateTokenResponse invalidateTokenResponse =
client.security().invalidateToken(invalidateTokenRequest, RequestOptions.DEFAULT);
// end::invalidate-token-execute
// tag::invalidate-token-response
boolean isCreated = invalidateTokenResponse.isCreated();
// end::invalidate-token-response
assertTrue(isCreated);
}
{
// tag::invalidate-refresh-token-request
InvalidateTokenRequest invalidateTokenRequest = InvalidateTokenRequest.refreshToken(refreshToken);
// end::invalidate-refresh-token-request
ActionListener<InvalidateTokenResponse> listener;
//tag::invalidate-token-execute-listener
listener = new ActionListener<InvalidateTokenResponse>() {
@Override
public void onResponse(InvalidateTokenResponse invalidateTokenResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::invalidate-token-execute-listener
// Avoid unused variable warning
assertNotNull(listener);
// Replace the empty listener by a blocking listener in test
final PlainActionFuture<InvalidateTokenResponse> future = new PlainActionFuture<>();
listener = future;
//tag::invalidate-token-execute-async
client.security().invalidateTokenAsync(invalidateTokenRequest, RequestOptions.DEFAULT, listener); // <1>
//end::invalidate-token-execute-async
final InvalidateTokenResponse response = future.get(30, TimeUnit.SECONDS);
assertNotNull(response);
assertTrue(response.isCreated());// technically, this should be false, but the API is broken
// See https://github.com/elastic/elasticsearch/issues/35115
}
}
public void testGetPrivileges() throws Exception {
final RestHighLevelClient client = highLevelClient();
final ApplicationPrivilege readTestappPrivilege =
new ApplicationPrivilege("testapp", "read", Arrays.asList("action:login", "data:read/*"), null);
final Map<String, Object> metadata = new HashMap<>();
metadata.put("key1", "value1");
final ApplicationPrivilege writeTestappPrivilege =
new ApplicationPrivilege("testapp", "write", Arrays.asList("action:login", "data:write/*"), metadata);
final ApplicationPrivilege allTestappPrivilege =
new ApplicationPrivilege("testapp", "all", Arrays.asList("action:login", "data:write/*", "manage:*"), null);
final Map<String, Object> metadata2 = new HashMap<>();
metadata2.put("key2", "value2");
final ApplicationPrivilege readTestapp2Privilege =
new ApplicationPrivilege("testapp2", "read", Arrays.asList("action:login", "data:read/*"), metadata2);
final ApplicationPrivilege writeTestapp2Privilege =
new ApplicationPrivilege("testapp2", "write", Arrays.asList("action:login", "data:write/*"), null);
final ApplicationPrivilege allTestapp2Privilege =
new ApplicationPrivilege("testapp2", "all", Arrays.asList("action:login", "data:write/*", "manage:*"), null);
{
List<ApplicationPrivilege> applicationPrivileges = new ArrayList<>();
applicationPrivileges.add(readTestappPrivilege);
applicationPrivileges.add(writeTestappPrivilege);
applicationPrivileges.add(allTestappPrivilege);
applicationPrivileges.add(readTestapp2Privilege);
applicationPrivileges.add(writeTestapp2Privilege);
applicationPrivileges.add(allTestapp2Privilege);
PutPrivilegesRequest putPrivilegesRequest = new PutPrivilegesRequest(applicationPrivileges, RefreshPolicy.IMMEDIATE);
PutPrivilegesResponse putPrivilegesResponse = client.security().putPrivileges(putPrivilegesRequest, RequestOptions.DEFAULT);
assertNotNull(putPrivilegesResponse);
assertThat(putPrivilegesResponse.wasCreated("testapp", "write"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp", "read"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp", "all"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp2", "all"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp2", "write"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp2", "read"), is(true));
}
{
//tag::get-privileges-request
GetPrivilegesRequest request = new GetPrivilegesRequest("testapp", "write");
//end::get-privileges-request
//tag::get-privileges-execute
GetPrivilegesResponse response = client.security().getPrivileges(request, RequestOptions.DEFAULT);
//end::get-privileges-execute
assertNotNull(response);
assertThat(response.getPrivileges().size(), equalTo(1));
assertThat(response.getPrivileges().contains(writeTestappPrivilege), equalTo(true));
}
{
//tag::get-all-application-privileges-request
GetPrivilegesRequest request = GetPrivilegesRequest.getApplicationPrivileges("testapp");
//end::get-all-application-privileges-request
GetPrivilegesResponse response = client.security().getPrivileges(request, RequestOptions.DEFAULT);
assertNotNull(response);
assertThat(response.getPrivileges().size(), equalTo(3));
final GetPrivilegesResponse exptectedResponse =
new GetPrivilegesResponse(Arrays.asList(readTestappPrivilege, writeTestappPrivilege, allTestappPrivilege));
assertThat(response, equalTo(exptectedResponse));
//tag::get-privileges-response
Set<ApplicationPrivilege> privileges = response.getPrivileges();
//end::get-privileges-response
for (ApplicationPrivilege privilege : privileges) {
assertThat(privilege.getApplication(), equalTo("testapp"));
if (privilege.getName().equals("read")) {
assertThat(privilege.getActions(), containsInAnyOrder("action:login", "data:read/*"));
assertThat(privilege.getMetadata().isEmpty(), equalTo(true));
} else if (privilege.getName().equals("write")) {
assertThat(privilege.getActions(), containsInAnyOrder("action:login", "data:write/*"));
assertThat(privilege.getMetadata().isEmpty(), equalTo(false));
assertThat(privilege.getMetadata().get("key1"), equalTo("value1"));
} else if (privilege.getName().equals("all")) {
assertThat(privilege.getActions(), containsInAnyOrder("action:login", "data:write/*", "manage:*"));
assertThat(privilege.getMetadata().isEmpty(), equalTo(true));
}
}
}
{
//tag::get-all-privileges-request
GetPrivilegesRequest request = GetPrivilegesRequest.getAllPrivileges();
//end::get-all-privileges-request
GetPrivilegesResponse response = client.security().getPrivileges(request, RequestOptions.DEFAULT);
assertNotNull(response);
assertThat(response.getPrivileges().size(), equalTo(6));
final GetPrivilegesResponse exptectedResponse =
new GetPrivilegesResponse(Arrays.asList(readTestappPrivilege, writeTestappPrivilege, allTestappPrivilege,
readTestapp2Privilege, writeTestapp2Privilege, allTestapp2Privilege));
assertThat(response, equalTo(exptectedResponse));
}
{
GetPrivilegesRequest request = new GetPrivilegesRequest("testapp", "read");
//tag::get-privileges-execute-listener
ActionListener<GetPrivilegesResponse> listener = new ActionListener<GetPrivilegesResponse>() {
@Override
public void onResponse(GetPrivilegesResponse getPrivilegesResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::get-privileges-execute-listener
// Avoid unused variable warning
assertNotNull(listener);
// Replace the empty listener by a blocking listener in test
final PlainActionFuture<GetPrivilegesResponse> future = new PlainActionFuture<>();
listener = future;
//tag::get-privileges-execute-async
client.security().getPrivilegesAsync(request, RequestOptions.DEFAULT, listener); // <1>
//end::get-privileges-execute-async
final GetPrivilegesResponse response = future.get(30, TimeUnit.SECONDS);
assertNotNull(response);
assertThat(response.getPrivileges().size(), equalTo(1));
assertThat(response.getPrivileges().contains(readTestappPrivilege), equalTo(true));
}
}
public void testPutPrivileges() throws Exception {
RestHighLevelClient client = highLevelClient();
{
// tag::put-privileges-request
final List<ApplicationPrivilege> privileges = new ArrayList<>();
privileges.add(ApplicationPrivilege.builder()
.application("app01")
.privilege("all")
.actions(Sets.newHashSet("action:login"))
.metadata(Collections.singletonMap("k1", "v1"))
.build());
privileges.add(ApplicationPrivilege.builder()
.application("app01")
.privilege("write")
.actions(Sets.newHashSet("action:write"))
.build());
final PutPrivilegesRequest putPrivilegesRequest = new PutPrivilegesRequest(privileges, RefreshPolicy.IMMEDIATE);
// end::put-privileges-request
// tag::put-privileges-execute
final PutPrivilegesResponse putPrivilegesResponse = client.security().putPrivileges(putPrivilegesRequest,
RequestOptions.DEFAULT);
// end::put-privileges-execute
final String applicationName = "app01";
final String privilegeName = "all";
// tag::put-privileges-response
final boolean status = putPrivilegesResponse.wasCreated(applicationName, privilegeName); // <1>
// end::put-privileges-response
assertThat(status, is(true));
}
{
final List<ApplicationPrivilege> privileges = new ArrayList<>();
privileges.add(ApplicationPrivilege.builder()
.application("app01")
.privilege("all")
.actions(Sets.newHashSet("action:login"))
.metadata(Collections.singletonMap("k1", "v1"))
.build());
final PutPrivilegesRequest putPrivilegesRequest = new PutPrivilegesRequest(privileges, RefreshPolicy.IMMEDIATE);
// tag::put-privileges-execute-listener
ActionListener<PutPrivilegesResponse> listener = new ActionListener<PutPrivilegesResponse>() {
@Override
public void onResponse(PutPrivilegesResponse response) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
// end::put-privileges-execute-listener
// Avoid unused variable warning
assertNotNull(listener);
// Replace the empty listener by a blocking listener in test
final PlainActionFuture<PutPrivilegesResponse> future = new PlainActionFuture<>();
listener = future;
//tag::put-privileges-execute-async
client.security().putPrivilegesAsync(putPrivilegesRequest, RequestOptions.DEFAULT, listener); // <1>
//end::put-privileges-execute-async
assertNotNull(future.get(30, TimeUnit.SECONDS));
assertThat(future.get().wasCreated("app01", "all"), is(false));
}
}
public void testDeletePrivilege() throws Exception {
RestHighLevelClient client = highLevelClient();
{
List<ApplicationPrivilege> applicationPrivileges = new ArrayList<>();
applicationPrivileges.add(ApplicationPrivilege.builder()
.application("testapp")
.privilege("read")
.actions("action:login", "data:read/*")
.build());
applicationPrivileges.add(ApplicationPrivilege.builder()
.application("testapp")
.privilege("write")
.actions("action:login", "data:write/*")
.build());
applicationPrivileges.add(ApplicationPrivilege.builder()
.application("testapp")
.privilege("all")
.actions("action:login", "data:write/*")
.build());
PutPrivilegesRequest putPrivilegesRequest = new PutPrivilegesRequest(applicationPrivileges, RefreshPolicy.IMMEDIATE);
PutPrivilegesResponse putPrivilegesResponse = client.security().putPrivileges(putPrivilegesRequest, RequestOptions.DEFAULT);
assertNotNull(putPrivilegesResponse);
assertThat(putPrivilegesResponse.wasCreated("testapp", "write"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp", "read"), is(true));
assertThat(putPrivilegesResponse.wasCreated("testapp", "all"), is(true));
}
{
// tag::delete-privileges-request
DeletePrivilegesRequest request = new DeletePrivilegesRequest(
"testapp", // <1>
"read", "write"); // <2>
// end::delete-privileges-request
// tag::delete-privileges-execute
DeletePrivilegesResponse response = client.security().deletePrivileges(request, RequestOptions.DEFAULT);
// end::delete-privileges-execute
// tag::delete-privileges-response
String application = response.getApplication(); // <1>
boolean found = response.isFound("read"); // <2>
// end::delete-privileges-response
assertThat(application, equalTo("testapp"));
assertTrue(response.isFound("write"));
assertTrue(found);
// check if deleting the already deleted privileges again will give us a different response
response = client.security().deletePrivileges(request, RequestOptions.DEFAULT);
assertFalse(response.isFound("write"));
}
{
DeletePrivilegesRequest deletePrivilegesRequest = new DeletePrivilegesRequest("testapp", "all");
ActionListener<DeletePrivilegesResponse> listener;
//tag::delete-privileges-execute-listener
listener = new ActionListener<DeletePrivilegesResponse>() {
@Override
public void onResponse(DeletePrivilegesResponse deletePrivilegesResponse) {
// <1>
}
@Override
public void onFailure(Exception e) {
// <2>
}
};
//end::delete-privileges-execute-listener
// Replace the empty listener by a blocking listener in test
final CountDownLatch latch = new CountDownLatch(1);
listener = new LatchedActionListener<>(listener, latch);
//tag::delete-privileges-execute-async
client.security().deletePrivilegesAsync(deletePrivilegesRequest, RequestOptions.DEFAULT, listener); // <1>
//end::delete-privileges-execute-async
assertTrue(latch.await(30L, TimeUnit.SECONDS));
}
}
}
|
Avoid blocking non-reproducible randomness in test (#36561)
The security documentation test uses
SecureRandom#getStrongInstance. This defaults to
securerandom.strongAlgorithms=NativePRNGBlocking:SUN,DRBG:SUN which
means a blocking implementation that reads from /dev/random. This means
that this test can stall if the entropy on the machine is
exhausted. Anyway, it also means that the randomness is
non-reproducible, a thing that we try to avoid in tests. This commit
switches to a boring randomness source to avoid the blocking, and to
keep the test reproducible.
|
client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SecurityDocumentationIT.java
|
Avoid blocking non-reproducible randomness in test (#36561)
|
|
Java
|
apache-2.0
|
b90515f4b5f125bb74470892eb5f9a4c0f00467b
| 0
|
eayun/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine
|
package org.ovirt.engine.core.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* This class stores the local configuration (understanding local as the
* configuration of the local machine, as opposed to the global configuration
* stored in the database) of the engine loaded from the file specified by the
* <code>ENGINE_VARS</code> environment variable.
*/
public class LocalConfig {
// The log:
private static final Logger log = Logger.getLogger(LocalConfig.class);
private static final String SENSITIVE_KEYS = "SENSITIVE_KEYS";
// Compile regular expressions:
private static final Pattern EMPTY_LINE = Pattern.compile("^\\s*(#.*)?$");
private static final Pattern KEY_VALUE_EXPRESSION = Pattern.compile("^\\s*(\\w+)=(.*)$");
// The properties object storing the current values of the parameters:
private Map<String, String> values = new HashMap<String, String>();
/**
* Use configuration from map.
* @param values map.
*/
protected void setConfig(Map<String, String> values) {
this.values = values;
dumpConfig();
}
/**
* Use configuration from files.
* @param defaultsPath path to file containing the defaults.
* @param varsPath path to file and directory of file.d.
*/
protected void loadConfig(String defaultsPath, String varsPath) {
// This is the list of configuration files that will be loaded and
// merged (the initial size is 2 because usually we will have only two
// configuration files to merge, the defaults and the variables):
List<File> configFiles = new ArrayList<File>(2);
if (!StringUtils.isEmpty(defaultsPath)) {
File defaultsFile = new File(defaultsPath);
configFiles.add(defaultsFile);
}
if (!StringUtils.isEmpty(varsPath)) {
File varsFile = new File(varsPath);
configFiles.add(varsFile);
// Locate the override values directory and add the .conf files inside
// to the list, sorted alphabetically:
File[] varsFiles = new File(varsPath + ".d").listFiles(
new FilenameFilter() {
@Override
public boolean accept(File parent, String name) {
return name.endsWith(".conf");
}
}
);
if (varsFiles != null) {
Arrays.sort(
varsFiles,
new Comparator<File>() {
@Override
public int compare (File leftFile, File rightFile) {
String leftName = leftFile.getName();
String rightName = rightFile.getName();
return leftName.compareTo(rightName);
}
}
);
for (File file : varsFiles) {
configFiles.add(file);
}
}
}
// Load the configuration files in the order they are in the list:
for (File configFile : configFiles) {
try {
loadProperties(configFile);
}
catch (IOException exception) {
String message = "Can't load configuration file.";
log.error(message, exception);
throw new IllegalStateException(message, exception);
}
}
dumpConfig();
}
/**
* Dump all configuration to the log.
* this should probably be DEBUG, but as it will usually happen only once,
* during the startup, is not that a roblem to use INFO.
*/
private void dumpConfig() {
if (log.isInfoEnabled()) {
Set<String> keys = values.keySet();
List<String> list = new ArrayList<String>(keys.size());
List<String> sensitiveKeys = Arrays.asList(getSensitiveKeys());
list.addAll(keys);
Collections.sort(list);
for (String key : list) {
String value = "***";
if (!sensitiveKeys.contains(key)) {
value = values.get(key);
}
log.info("Value of property \"" + key + "\" is \"" + value + "\".");
}
}
}
/**
* Load the contents of the properties file located by the given environment
* variable or file.
*
* @param file the file that will be used to load the properties if the given
* environment variable doesn't have a value
*/
private void loadProperties(File file) throws IOException {
// Do nothing if the file doesn't exist or isn't readable:
if (!file.canRead()) {
log.info("The file \"" + file.getAbsolutePath() + "\" doesn't exist or isn't readable. Will return an empty set of properties.");
return;
}
// Load the file:
int index = 0;
try (
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")))
) {
String line = null;
while ((line = reader.readLine()) != null) {
index++;
loadLine(line);
}
log.info("Loaded file \"" + file.getAbsolutePath() + "\".");
}
catch (Exception e) {
String msg = String.format(
"Can't load file '%s' line %d: %s",
file.getAbsolutePath(),
index,
e
);
log.error(msg, e);
throw new RuntimeException(msg, e);
}
}
/**
* Expand string using current variables.
*
* @return Expanded string.
* @param value String.
*/
public String expandString(String value) {
StringBuilder ret = new StringBuilder();
boolean escape = false;
boolean inQuotes = false;
int index = 0;
while (index < value.length()) {
char c = value.charAt(index++);
if (escape) {
escape = false;
ret.append(c);
}
else {
switch(c) {
case '\\':
escape = true;
break;
case '$':
if (value.charAt(index++) != '{') {
throw new RuntimeException("Malformed variable assignement");
}
int i = value.indexOf('}', index);
if (i == -1) {
throw new RuntimeException("Malformed variable assignement");
}
String name = value.substring(index, i);
index = i+1;
String v = values.get(name);
if (v != null) {
ret.append(v);
}
else {
v = System.getProperty(name);
if (v != null) {
ret.append(v);
}
}
break;
case '"':
inQuotes = !inQuotes;
break;
case ' ':
case '#':
if (inQuotes) {
ret.append(c);
}
else {
index = value.length();
}
break;
default:
ret.append(c);
break;
}
}
}
return ret.toString();
}
/**
* Load the contents of a line from a properties file, expanding
* references to variables.
*
* @param line the line from the properties file
*/
private void loadLine(String line) throws IOException {
Matcher blankMatch = EMPTY_LINE.matcher(line);
if (!blankMatch.find()) {
Matcher keyValueMatch = KEY_VALUE_EXPRESSION.matcher(line);
if (!keyValueMatch.find()) {
throw new RuntimeException("Invalid line");
}
values.put(
keyValueMatch.group(1),
expandString(keyValueMatch.group(2))
);
}
}
/**
* Get all properties.
*
* @return map of all properties.
*/
public Map<String, String> getProperties() {
return values;
}
/**
* Get the value of a property given its name.
*
* @param key the name of the property
* @param allowMissing return null if missing
* @return the value of the property as contained in the configuration file
* @throws java.lang.IllegalStateException if the property doesn't have a
* value
*/
public String getProperty(String key, boolean allowMissing) {
String value = values.get(key);
if (value == null && !allowMissing) {
// Loudly alert in the log and throw an exception:
String message = "The property \"" + key + "\" doesn't have a value.";
log.error(message);
throw new IllegalArgumentException(message);
// Or maybe kill ourselves, as a missing configuration parameter is
// a serious error:
// System.exit(1)
}
return value;
}
/**
* Get the value of a property given its name.
*
* @param key the name of the property
* @return the value of the property as contained in the configuration file
* @throws java.lang.IllegalStateException if the property doesn't have a
* value
*/
public String getProperty(String key) {
return getProperty(key, false);
}
// Accepted values for boolean properties (please keep them sorted as we use
// a binary search to check if a given property matches one of these
// values):
private static final String[] TRUE_VALUES = { "1", "t", "true", "y", "yes" };
private static final String[] FALSE_VALUES = { "0", "f", "false", "n", "no" };
/**
* Get the value of a boolean property given its name. It will take the text
* of the property and return <true> if it is <code>true</code> if the text
* of the property is <code>true</code>, <code>t</code>, <code>yes</code>,
* <code>y</code> or <code>1</code> (ignoring case).
*
* @param key the name of the property
* @param defaultValue default value to return, null do not allow.
* @return the boolean value of the property
* @throws java.lang.IllegalArgumentException if the properties doesn't have
* a value or if the value is not a valid boolean
*/
public boolean getBoolean(String key, Boolean defaultValue) {
boolean ret;
// Get the text of the property and convert it to lowercase:
String value = getProperty(key, defaultValue != null);
if (value == null) {
ret = defaultValue.booleanValue();
}
else {
value = value.trim().toLowerCase();
// Check if it is one of the true values:
if (Arrays.binarySearch(TRUE_VALUES, value) >= 0) {
ret = true;
}
// Check if it is one of the false values:
else if (Arrays.binarySearch(FALSE_VALUES, value) >= 0) {
ret = false;
}
else {
// No luck, will alert in the log that the text is not valid and throw
// an exception:
String message = "The value \"" + value + "\" for property \"" + key + "\" is not a valid boolean.";
log.error(message);
throw new IllegalArgumentException(message);
}
}
return ret;
}
/**
* Get the value of a boolean property given its name. It will take the text
* of the property and return <true> if it is <code>true</code> if the text
* of the property is <code>true</code>, <code>t</code>, <code>yes</code>,
* <code>y</code> or <code>1</code> (ignoring case).
*
* @param key the name of the property
* @param defaultValue default value to return, null do not allow.
* @return the boolean value of the property
* @throws java.lang.IllegalArgumentException if the properties doesn't have
* a value or if the value is not a valid boolean
*/
public boolean getBoolean(String key) {
return getBoolean(key, null);
}
/**
* Get the value of an integer property given its name. If the text of the
* value can't be converted to an integer a message will be sent to the log
* and an exception thrown.
*
* @param key the name of the property
* @param defaultValue default value to return, null do not allow.
* @return the integer value of the property
* @throws java.lang.IllegalArgumentException if the property doesn't have a
* value or the value is not a valid integer
*/
public int getInteger(String key, Integer defaultValue) {
int ret;
String value = getProperty(key, defaultValue != null);
if (value == null) {
ret = defaultValue.intValue();
}
else {
try {
ret = Integer.parseInt(value);
}
catch (NumberFormatException exception) {
String message = "The value \"" + value + "\" for property \"" + key + "\" is not a valid integer.";
log.error(message, exception);
throw new IllegalArgumentException(message, exception);
}
}
return ret;
}
/**
* Get the value of an integer property given its name. If the text of the
* value can't be converted to an integer a message will be sent to the log
* and an exception thrown.
*
* @param key the name of the property
* @return the integer value of the property
* @throws java.lang.IllegalArgumentException if the property doesn't have a
* value or the value is not a valid integer
*/
public int getInteger(String key) {
return getInteger(key, null);
}
/**
* Get the value of an long property given its name. If the text of the
* value can't be converted to an long a message will be sent to the log
* and an exception thrown.
*
* @param key the name of the property
* @param defaultValue default value to return, null do not allow.
* @return the long value of the property
* @throws java.lang.IllegalArgumentException if the property doesn't have a
* value or the value is not a valid long
*/
public long getLong(String key, Long defaultValue) {
long ret;
String value = getProperty(key, defaultValue != null);
if (value == null) {
ret = defaultValue.intValue();
}
else {
try {
ret = Long.parseLong(value);
}
catch (NumberFormatException exception) {
String message = "The value \"" + value + "\" for property \"" + key + "\" is not a valid long integer.";
log.error(message, exception);
throw new IllegalArgumentException(message, exception);
}
}
return ret;
}
/**
* Get the value of an long property given its name. If the text of the
* value can't be converted to an long a message will be sent to the log
* and an exception thrown.
*
* @param key the name of the property
* @return the long value of the property
* @throws java.lang.IllegalArgumentException if the property doesn't have a
* value or the value is not a valid long
*/
public long getLong(String key) {
return getLong(key, null);
}
/**
* Get the value of a property corresponding to a file or directory name.
*
* @param key the name of the property
* @return the file object corresponding to the value of the property
*/
public File getFile(String key) {
String value = getProperty(key);
return new File(value);
}
public String[] getSensitiveKeys() {
String sensitiveKeys = values.get(SENSITIVE_KEYS);
if (sensitiveKeys == null) {
return new String[] {};
}
else {
return sensitiveKeys.split(",");
}
}
}
|
backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/LocalConfig.java
|
package org.ovirt.engine.core.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* This class stores the local configuration (understanding local as the
* configuration of the local machine, as opposed to the global configuration
* stored in the database) of the engine loaded from the file specified by the
* <code>ENGINE_VARS</code> environment variable.
*/
public class LocalConfig {
// The log:
private static final Logger log = Logger.getLogger(LocalConfig.class);
private static final String SENSITIVE_KEYS = "SENSITIVE_KEYS";
// Compile regular expressions:
private static final Pattern EMPTY_LINE = Pattern.compile("^\\s*(#.*)?$");
private static final Pattern KEY_VALUE_EXPRESSION = Pattern.compile("^\\s*(\\w+)=(.*)$");
// The properties object storing the current values of the parameters:
private Map<String, String> values = new HashMap<String, String>();
/**
* Use configuration from map.
* @param values map.
*/
protected void setConfig(Map<String, String> values) {
this.values = values;
dumpConfig();
}
/**
* Use configuration from files.
* @param defaultsPath path to file containing the defaults.
* @param varsPath path to file and directory of file.d.
*/
protected void loadConfig(String defaultsPath, String varsPath) {
// This is the list of configuration files that will be loaded and
// merged (the initial size is 2 because usually we will have only two
// configuration files to merge, the defaults and the variables):
List<File> configFiles = new ArrayList<File>(2);
if (!StringUtils.isEmpty(defaultsPath)) {
File defaultsFile = new File(defaultsPath);
configFiles.add(defaultsFile);
}
if (!StringUtils.isEmpty(varsPath)) {
File varsFile = new File(varsPath);
configFiles.add(varsFile);
// Locate the override values directory and add the .conf files inside
// to the list, sorted alphabetically:
File[] varsFiles = new File(varsPath + ".d").listFiles(
new FilenameFilter() {
@Override
public boolean accept(File parent, String name) {
return name.endsWith(".conf");
}
}
);
if (varsFiles != null) {
Arrays.sort(
varsFiles,
new Comparator<File>() {
@Override
public int compare (File leftFile, File rightFile) {
String leftName = leftFile.getName();
String rightName = rightFile.getName();
return leftName.compareTo(rightName);
}
}
);
for (File file : varsFiles) {
configFiles.add(file);
}
}
}
// Load the configuration files in the order they are in the list:
for (File configFile : configFiles) {
try {
loadProperties(configFile);
}
catch (IOException exception) {
String message = "Can't load configuration file.";
log.error(message, exception);
throw new IllegalStateException(message, exception);
}
}
dumpConfig();
}
/**
* Dump all configuration to the log.
* this should probably be DEBUG, but as it will usually happen only once,
* during the startup, is not that a roblem to use INFO.
*/
private void dumpConfig() {
if (log.isInfoEnabled()) {
Set<String> keys = values.keySet();
List<String> list = new ArrayList<String>(keys.size());
List<String> sensitiveKeys = Arrays.asList(getSensitiveKeys());
list.addAll(keys);
Collections.sort(list);
for (String key : list) {
String value = "***";
if (!sensitiveKeys.contains(key)) {
value = values.get(key);
}
log.info("Value of property \"" + key + "\" is \"" + value + "\".");
}
}
}
/**
* Load the contents of the properties file located by the given environment
* variable or file.
*
* @param file the file that will be used to load the properties if the given
* environment variable doesn't have a value
*/
private void loadProperties(File file) throws IOException {
// Do nothing if the file doesn't exist or isn't readable:
if (!file.canRead()) {
log.warn("The file \"" + file.getAbsolutePath() + "\" doesn't exist or isn't readable. Will return an empty set of properties.");
return;
}
// Load the file:
int index = 0;
try (
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")))
) {
String line = null;
while ((line = reader.readLine()) != null) {
index++;
loadLine(line);
}
log.info("Loaded file \"" + file.getAbsolutePath() + "\".");
}
catch (Exception e) {
String msg = String.format(
"Can't load file '%s' line %d: %s",
file.getAbsolutePath(),
index,
e
);
log.error(msg, e);
throw new RuntimeException(msg, e);
}
}
/**
* Expand string using current variables.
*
* @return Expanded string.
* @param value String.
*/
public String expandString(String value) {
StringBuilder ret = new StringBuilder();
boolean escape = false;
boolean inQuotes = false;
int index = 0;
while (index < value.length()) {
char c = value.charAt(index++);
if (escape) {
escape = false;
ret.append(c);
}
else {
switch(c) {
case '\\':
escape = true;
break;
case '$':
if (value.charAt(index++) != '{') {
throw new RuntimeException("Malformed variable assignement");
}
int i = value.indexOf('}', index);
if (i == -1) {
throw new RuntimeException("Malformed variable assignement");
}
String name = value.substring(index, i);
index = i+1;
String v = values.get(name);
if (v != null) {
ret.append(v);
}
else {
v = System.getProperty(name);
if (v != null) {
ret.append(v);
}
}
break;
case '"':
inQuotes = !inQuotes;
break;
case ' ':
case '#':
if (inQuotes) {
ret.append(c);
}
else {
index = value.length();
}
break;
default:
ret.append(c);
break;
}
}
}
return ret.toString();
}
/**
* Load the contents of a line from a properties file, expanding
* references to variables.
*
* @param line the line from the properties file
*/
private void loadLine(String line) throws IOException {
Matcher blankMatch = EMPTY_LINE.matcher(line);
if (!blankMatch.find()) {
Matcher keyValueMatch = KEY_VALUE_EXPRESSION.matcher(line);
if (!keyValueMatch.find()) {
throw new RuntimeException("Invalid line");
}
values.put(
keyValueMatch.group(1),
expandString(keyValueMatch.group(2))
);
}
}
/**
* Get all properties.
*
* @return map of all properties.
*/
public Map<String, String> getProperties() {
return values;
}
/**
* Get the value of a property given its name.
*
* @param key the name of the property
* @param allowMissing return null if missing
* @return the value of the property as contained in the configuration file
* @throws java.lang.IllegalStateException if the property doesn't have a
* value
*/
public String getProperty(String key, boolean allowMissing) {
String value = values.get(key);
if (value == null && !allowMissing) {
// Loudly alert in the log and throw an exception:
String message = "The property \"" + key + "\" doesn't have a value.";
log.error(message);
throw new IllegalArgumentException(message);
// Or maybe kill ourselves, as a missing configuration parameter is
// a serious error:
// System.exit(1)
}
return value;
}
/**
* Get the value of a property given its name.
*
* @param key the name of the property
* @return the value of the property as contained in the configuration file
* @throws java.lang.IllegalStateException if the property doesn't have a
* value
*/
public String getProperty(String key) {
return getProperty(key, false);
}
// Accepted values for boolean properties (please keep them sorted as we use
// a binary search to check if a given property matches one of these
// values):
private static final String[] TRUE_VALUES = { "1", "t", "true", "y", "yes" };
private static final String[] FALSE_VALUES = { "0", "f", "false", "n", "no" };
/**
* Get the value of a boolean property given its name. It will take the text
* of the property and return <true> if it is <code>true</code> if the text
* of the property is <code>true</code>, <code>t</code>, <code>yes</code>,
* <code>y</code> or <code>1</code> (ignoring case).
*
* @param key the name of the property
* @param defaultValue default value to return, null do not allow.
* @return the boolean value of the property
* @throws java.lang.IllegalArgumentException if the properties doesn't have
* a value or if the value is not a valid boolean
*/
public boolean getBoolean(String key, Boolean defaultValue) {
boolean ret;
// Get the text of the property and convert it to lowercase:
String value = getProperty(key, defaultValue != null);
if (value == null) {
ret = defaultValue.booleanValue();
}
else {
value = value.trim().toLowerCase();
// Check if it is one of the true values:
if (Arrays.binarySearch(TRUE_VALUES, value) >= 0) {
ret = true;
}
// Check if it is one of the false values:
else if (Arrays.binarySearch(FALSE_VALUES, value) >= 0) {
ret = false;
}
else {
// No luck, will alert in the log that the text is not valid and throw
// an exception:
String message = "The value \"" + value + "\" for property \"" + key + "\" is not a valid boolean.";
log.error(message);
throw new IllegalArgumentException(message);
}
}
return ret;
}
/**
* Get the value of a boolean property given its name. It will take the text
* of the property and return <true> if it is <code>true</code> if the text
* of the property is <code>true</code>, <code>t</code>, <code>yes</code>,
* <code>y</code> or <code>1</code> (ignoring case).
*
* @param key the name of the property
* @param defaultValue default value to return, null do not allow.
* @return the boolean value of the property
* @throws java.lang.IllegalArgumentException if the properties doesn't have
* a value or if the value is not a valid boolean
*/
public boolean getBoolean(String key) {
return getBoolean(key, null);
}
/**
* Get the value of an integer property given its name. If the text of the
* value can't be converted to an integer a message will be sent to the log
* and an exception thrown.
*
* @param key the name of the property
* @param defaultValue default value to return, null do not allow.
* @return the integer value of the property
* @throws java.lang.IllegalArgumentException if the property doesn't have a
* value or the value is not a valid integer
*/
public int getInteger(String key, Integer defaultValue) {
int ret;
String value = getProperty(key, defaultValue != null);
if (value == null) {
ret = defaultValue.intValue();
}
else {
try {
ret = Integer.parseInt(value);
}
catch (NumberFormatException exception) {
String message = "The value \"" + value + "\" for property \"" + key + "\" is not a valid integer.";
log.error(message, exception);
throw new IllegalArgumentException(message, exception);
}
}
return ret;
}
/**
* Get the value of an integer property given its name. If the text of the
* value can't be converted to an integer a message will be sent to the log
* and an exception thrown.
*
* @param key the name of the property
* @return the integer value of the property
* @throws java.lang.IllegalArgumentException if the property doesn't have a
* value or the value is not a valid integer
*/
public int getInteger(String key) {
return getInteger(key, null);
}
/**
* Get the value of an long property given its name. If the text of the
* value can't be converted to an long a message will be sent to the log
* and an exception thrown.
*
* @param key the name of the property
* @param defaultValue default value to return, null do not allow.
* @return the long value of the property
* @throws java.lang.IllegalArgumentException if the property doesn't have a
* value or the value is not a valid long
*/
public long getLong(String key, Long defaultValue) {
long ret;
String value = getProperty(key, defaultValue != null);
if (value == null) {
ret = defaultValue.intValue();
}
else {
try {
ret = Long.parseLong(value);
}
catch (NumberFormatException exception) {
String message = "The value \"" + value + "\" for property \"" + key + "\" is not a valid long integer.";
log.error(message, exception);
throw new IllegalArgumentException(message, exception);
}
}
return ret;
}
/**
* Get the value of an long property given its name. If the text of the
* value can't be converted to an long a message will be sent to the log
* and an exception thrown.
*
* @param key the name of the property
* @return the long value of the property
* @throws java.lang.IllegalArgumentException if the property doesn't have a
* value or the value is not a valid long
*/
public long getLong(String key) {
return getLong(key, null);
}
/**
* Get the value of a property corresponding to a file or directory name.
*
* @param key the name of the property
* @return the file object corresponding to the value of the property
*/
public File getFile(String key) {
String value = getProperty(key);
return new File(value);
}
public String[] getSensitiveKeys() {
String sensitiveKeys = values.get(SENSITIVE_KEYS);
if (sensitiveKeys == null) {
return new String[] {};
}
else {
return sensitiveKeys.split(",");
}
}
}
|
utils: LocalConfig: reduce message severity if file is missing
it is valid to have purely default without any configuration.
Bug-Url: https://bugzilla.redhat.com/show_bug.cgi?id=1020675
Change-Id: If597acaf41049392a24d59549034af9e09c7616e
Signed-off-by: Alon Bar-Lev <2e3ceb4d37adc6ae3ccc00d3646e0e0a036ace03@redhat.com>
|
backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/LocalConfig.java
|
utils: LocalConfig: reduce message severity if file is missing
|
|
Java
|
apache-2.0
|
0d02b953390fd629c39e5c63eaa2b53ea841d493
| 0
|
dcordero/BigNerdRanch-Android
|
package com.bignerdranch.android.criminalintent;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class CrimeListFragment extends Fragment {
private static final String SAVED_SUBTITLE_VISIBLE = "subtitle_visible";
private RecyclerView mRecyclerView;
private CrimeAdapter mCrimeAdapter;
private boolean mSubtitleVisible;
private Callbacks mCallbacks;
public interface Callbacks {
void onCrimeSelected(Crime crime);
}
@Override public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
@Override public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_SUBTITLE_VISIBLE, mSubtitleVisible);
}
@Override public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
if (savedInstanceState != null) {
mSubtitleVisible = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE);
}
}
@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem menuItem = menu.findItem(R.id.menu_item_show_subtitle);
if (mSubtitleVisible) {
menuItem.setTitle(R.string.hide_subtitle);
}
else {
menuItem.setTitle(R.string.show_subtitle);
}
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new_crime:
Crime crime = new Crime();
CrimeLab.get(getActivity()).addCrime(crime);
Intent intent = CrimePagerActivity.newIntent(getActivity(), crime.getId());
startActivity(intent);
return true;
case R.id.menu_item_show_subtitle:
mSubtitleVisible = !mSubtitleVisible;
getActivity().invalidateOptionsMenu();
updateSubtitle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override public void onResume() {
super.onResume();
updateUI();
}
@Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime>crimes = crimeLab.getCrimes();
if (mCrimeAdapter == null) {
mCrimeAdapter = new CrimeAdapter(crimes);
mRecyclerView.setAdapter(mCrimeAdapter);
}
else {
mCrimeAdapter.setCrimes(crimes);
mCrimeAdapter.notifyDataSetChanged();
}
updateSubtitle();
}
void updateSubtitle() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
int crimeCount = crimeLab.getCrimes().size();
String subtitle = getResources().getQuantityString(R.plurals.subtitle_plural, crimeCount, crimeCount);
if (!mSubtitleVisible) {
subtitle = null;
}
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar().setSubtitle(subtitle);
}
// RecyclerView: ViewHolder
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Crime mCrime;
private CheckBox mSolvedCheckBox;
private TextView mTitleTextView;
private TextView mDateTextView;
public CrimeHolder(View itemView) {
super (itemView);
itemView.setOnClickListener(this);
mSolvedCheckBox = (CheckBox) itemView.findViewById(R.id.list_item_crime_solved_check_box);
mTitleTextView = (TextView) itemView.findViewById(R.id.list_item_crime_title_text_view);
mDateTextView = (TextView) itemView.findViewById(R.id.list_item_crime_date_text_view);
}
public void bindCrime(Crime crime) {
mCrime = crime;
mSolvedCheckBox.setChecked(crime.isSolved());
mTitleTextView.setText(crime.getTitle());
mDateTextView.setText(crime.getDate().toString());
}
@Override
public void onClick(View v) {
Intent intent = CrimePagerActivity.newIntent(getActivity(), mCrime.getId());
startActivity(intent);
}
}
// RecyclerView: Adapter
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
@Override public CrimeHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_item_crime, viewGroup, false);
return new CrimeHolder(view);
}
@Override public void onBindViewHolder(CrimeHolder crimeHolder, int position) {
crimeHolder.bindCrime(mCrimes.get(position));
}
@Override public int getItemCount() {
return mCrimes.size();
}
public void setCrimes(List<Crime> crimes) {
mCrimes = crimes;
}
}
}
|
CriminalIntent/app/src/main/java/com/bignerdranch/android/criminalintent/CrimeListFragment.java
|
package com.bignerdranch.android.criminalintent;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class CrimeListFragment extends Fragment {
private static final String SAVED_SUBTITLE_VISIBLE = "subtitle_visible";
private RecyclerView mRecyclerView;
private CrimeAdapter mCrimeAdapter;
private boolean mSubtitleVisible;
@Override public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_SUBTITLE_VISIBLE, mSubtitleVisible);
}
@Override public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
if (savedInstanceState != null) {
mSubtitleVisible = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE);
}
}
@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem menuItem = menu.findItem(R.id.menu_item_show_subtitle);
if (mSubtitleVisible) {
menuItem.setTitle(R.string.hide_subtitle);
}
else {
menuItem.setTitle(R.string.show_subtitle);
}
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new_crime:
Crime crime = new Crime();
CrimeLab.get(getActivity()).addCrime(crime);
Intent intent = CrimePagerActivity.newIntent(getActivity(), crime.getId());
startActivity(intent);
return true;
case R.id.menu_item_show_subtitle:
mSubtitleVisible = !mSubtitleVisible;
getActivity().invalidateOptionsMenu();
updateSubtitle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override public void onResume() {
super.onResume();
updateUI();
}
@Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime>crimes = crimeLab.getCrimes();
if (mCrimeAdapter == null) {
mCrimeAdapter = new CrimeAdapter(crimes);
mRecyclerView.setAdapter(mCrimeAdapter);
}
else {
mCrimeAdapter.setCrimes(crimes);
mCrimeAdapter.notifyDataSetChanged();
}
updateSubtitle();
}
void updateSubtitle() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
int crimeCount = crimeLab.getCrimes().size();
String subtitle = getResources().getQuantityString(R.plurals.subtitle_plural, crimeCount, crimeCount);
if (!mSubtitleVisible) {
subtitle = null;
}
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.getSupportActionBar().setSubtitle(subtitle);
}
// RecyclerView: ViewHolder
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Crime mCrime;
private CheckBox mSolvedCheckBox;
private TextView mTitleTextView;
private TextView mDateTextView;
public CrimeHolder(View itemView) {
super (itemView);
itemView.setOnClickListener(this);
mSolvedCheckBox = (CheckBox) itemView.findViewById(R.id.list_item_crime_solved_check_box);
mTitleTextView = (TextView) itemView.findViewById(R.id.list_item_crime_title_text_view);
mDateTextView = (TextView) itemView.findViewById(R.id.list_item_crime_date_text_view);
}
public void bindCrime(Crime crime) {
mCrime = crime;
mSolvedCheckBox.setChecked(crime.isSolved());
mTitleTextView.setText(crime.getTitle());
mDateTextView.setText(crime.getDate().toString());
}
@Override
public void onClick(View v) {
Intent intent = CrimePagerActivity.newIntent(getActivity(), mCrime.getId());
startActivity(intent);
}
}
// RecyclerView: Adapter
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
@Override public CrimeHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_item_crime, viewGroup, false);
return new CrimeHolder(view);
}
@Override public void onBindViewHolder(CrimeHolder crimeHolder, int position) {
crimeHolder.bindCrime(mCrimes.get(position));
}
@Override public int getItemCount() {
return mCrimes.size();
}
public void setCrimes(List<Crime> crimes) {
mCrimes = crimes;
}
}
}
|
Define callback to communicate back from fragment to hosting activity
|
CriminalIntent/app/src/main/java/com/bignerdranch/android/criminalintent/CrimeListFragment.java
|
Define callback to communicate back from fragment to hosting activity
|
|
Java
|
apache-2.0
|
7bfbdd3aa00b58bc3a6abd934c2c17461d85b44e
| 0
|
HubSpot/Baragon,HubSpot/Baragon,HubSpot/Baragon
|
package com.hubspot.baragon.service.edgecache.cloudflare.client;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.hubspot.baragon.service.BaragonServiceModule;
import com.hubspot.baragon.service.config.EdgeCacheConfiguration;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareDnsRecord;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareListDnsRecordsResponse;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareListZonesResponse;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflarePurgeRequest;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareResponse;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareResultInfo;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareZone;
import com.hubspot.horizon.HttpRequest.Method;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.Response;
@Singleton
public class CloudflareClient {
private static final Logger LOG = LoggerFactory.getLogger(CloudflareClient.class);
private static final int MAX_ZONES_PER_PAGE = 50;
private static final int MAX_DNS_RECORDS_PER_PAGE = 100;
private final AsyncHttpClient httpClient;
private final ObjectMapper objectMapper;
private final String apiBase;
private final String apiEmail;
private final String apiKey;
// <ZoneId, CloudflareZone>
private final Supplier<ConcurrentMap<String, CloudflareZone>> zoneCache;
// <ZoneId, <DnsName, CloudflareDnsRecord>>
private final LoadingCache<String, Map<String, CloudflareDnsRecord>> dnsRecordCache;
@Inject
public CloudflareClient(EdgeCacheConfiguration edgeCacheConfiguration,
@Named(BaragonServiceModule.BARAGON_SERVICE_HTTP_CLIENT) AsyncHttpClient httpClient,
ObjectMapper objectMapper) {
this.httpClient = httpClient;
this.objectMapper = objectMapper;
Map<String, String> integrationSettings = edgeCacheConfiguration.getIntegrationSettings();
this.apiBase = integrationSettings.get("apiBase");
this.apiEmail = integrationSettings.get("apiEmail");
this.apiKey = integrationSettings.get("apiKey");
this.zoneCache = Suppliers.memoizeWithExpiration(() -> {
try {
return retrieveAllZones().stream().collect(Collectors.toConcurrentMap(
CloudflareZone::getName,
Function.identity(),
(name1, name2) -> {
LOG.debug("Duplicate name found", name1);
return name1;
}
));
} catch (CloudflareClientException e) {
LOG.error("Unable to refresh Cloudflare zone cache", e);
return new ConcurrentHashMap<>();
}
}, 10, TimeUnit.MINUTES);
this.dnsRecordCache = CacheBuilder.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(new CacheLoader<String, Map<String, CloudflareDnsRecord>>() {
@Override
public Map<String, CloudflareDnsRecord> load(String zoneId) throws Exception {
return retrieveDnsRecords(zoneId).stream().collect(Collectors.toConcurrentMap(
CloudflareDnsRecord::getName,
Function.identity(),
(name1, name2) -> {
LOG.debug("Duplicate name found", name1);
return name1;
}
));
}
});
}
public boolean purgeEdgeCache(String zoneId, List<String> cacheTags) throws CloudflareClientException {
CloudflarePurgeRequest purgeRequest = new CloudflarePurgeRequest(Collections.emptyList(), cacheTags);
Response response = requestWith(Method.DELETE, String.format("zones/%s/purge_cache", zoneId), purgeRequest);
return isSuccess(response);
}
private Response requestWith(Method method, String path, Object body) throws CloudflareClientException {
return request(method, path, Optional.of(body), Optional.absent(), Optional.absent(), Optional.absent(), Optional.absent());
}
private Response request(Method method, String path, Optional<Object> body, Optional<Integer> page, Optional<Integer> perPage, Optional<String> order, Optional<String> direction) throws CloudflareClientException {
BoundRequestBuilder builder;
switch (method) {
case DELETE:
builder = httpClient.prepareDelete(apiBase + path);
break;
case GET:
default:
builder = httpClient.prepareGet(apiBase + path);
}
builder
.addHeader("X-Auth-Email", apiEmail)
.addHeader("X-Auth-Key", apiKey);
if (body.isPresent()) {
try {
builder.setBody(objectMapper.writeValueAsString(body.get()));
} catch (JsonProcessingException e) {
throw new CloudflareClientException("Unable to serialize body while preparing to send API request", e);
}
}
page.asSet().forEach(p -> builder.addQueryParameter("page", page.get().toString()));
perPage.asSet().forEach(p -> builder.addQueryParameter("per_page", perPage.get().toString()));
order.asSet().forEach(o -> builder.addQueryParameter("order", order.get()));
direction.asSet().forEach(d -> builder.addQueryParameter("direction", direction.get()));
try {
return builder.execute().get();
} catch (Exception e) {
throw new CloudflareClientException("Unexpected error during Cloudflare API call", e);
}
}
private boolean isSuccess(Response response) {
return response.getStatusCode() >= 200 && response.getStatusCode() < 300;
}
public CloudflareZone getZone(String name) throws CloudflareClientException {
return zoneCache.get().get(name);
}
public List<CloudflareZone> retrieveAllZones() throws CloudflareClientException {
CloudflareListZonesResponse cloudflareResponse = listZonesPaged(1);
List<CloudflareZone> zones = new ArrayList<>();
zones.addAll(cloudflareResponse.getResult());
CloudflareResultInfo paginationInfo = cloudflareResponse.getResultInfo();
for (int i = 2; i <= paginationInfo.getTotalPages(); i++) {
CloudflareListZonesResponse cloudflarePageResponse = listZonesPaged(i);
zones.addAll(cloudflarePageResponse.getResult());
}
return zones;
}
private CloudflareListZonesResponse listZonesPaged(Integer page) throws CloudflareClientException {
Response response = pagedRequest(Method.GET, "zones", page, MAX_ZONES_PER_PAGE);
if (!isSuccess(response)) {
try {
CloudflareResponse parsedResponse = objectMapper.readValue(response.getResponseBody(), CloudflareListZonesResponse.class);
throw new CloudflareClientException("Failed to get zones, " + parsedResponse);
} catch (IOException e) {
throw new CloudflareClientException("Failed to get zones; unable to parse error response");
}
}
try {
return objectMapper.readValue(response.getResponseBody(), CloudflareListZonesResponse.class);
} catch (IOException e) {
throw new CloudflareClientException("Unable to parse Cloudflare List Zones response", e);
}
}
public CloudflareDnsRecord getDnsRecord(String zoneId, String name) throws CloudflareClientException {
try {
return dnsRecordCache.get(zoneId).get(name);
} catch (ExecutionException e) {
throw new CloudflareClientException(e.getMessage(), e.getCause());
}
}
public Set<CloudflareDnsRecord> retrieveDnsRecords(String zoneId) throws CloudflareClientException {
CloudflareListDnsRecordsResponse cloudflareResponse = listDnsRecordsPaged(zoneId, 1);
Set<CloudflareDnsRecord> dnsRecords = cloudflareResponse.getResult();
CloudflareResultInfo paginationInfo = cloudflareResponse.getResultInfo();
for (int i = 2; i <= paginationInfo.getTotalPages(); i++) {
CloudflareListDnsRecordsResponse cloudflarePageResponse = listDnsRecordsPaged(zoneId, i);
dnsRecords.addAll(cloudflarePageResponse.getResult());
}
return dnsRecords;
}
private CloudflareListDnsRecordsResponse listDnsRecordsPaged(String zoneId, Integer page) throws CloudflareClientException {
Response response = pagedRequest(Method.GET, String.format("zones/%s/dns_records", zoneId), page, MAX_DNS_RECORDS_PER_PAGE);
if (!isSuccess(response)) {
try {
CloudflareResponse parsedResponse = objectMapper.readValue(response.getResponseBody(), CloudflareListDnsRecordsResponse.class);
throw new CloudflareClientException("Failed to get DNS records, " + parsedResponse);
} catch (IOException e) {
throw new CloudflareClientException("Failed to get DNS records; unable to parse error response");
}
}
try {
return objectMapper.readValue(response.getResponseBody(), CloudflareListDnsRecordsResponse.class);
} catch (IOException e) {
throw new CloudflareClientException("Unable to parse Cloudflare List DNS Records response", e);
}
}
private Response pagedRequest(Method method, String path, Integer page, Integer perPage) throws CloudflareClientException {
return request(method, path, Optional.absent(), Optional.of(page), Optional.of(perPage), Optional.absent(), Optional.absent());
}
}
|
BaragonService/src/main/java/com/hubspot/baragon/service/edgecache/cloudflare/client/CloudflareClient.java
|
package com.hubspot.baragon.service.edgecache.cloudflare.client;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.hubspot.baragon.service.BaragonServiceModule;
import com.hubspot.baragon.service.config.EdgeCacheConfiguration;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareDnsRecord;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareListDnsRecordsResponse;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareListZonesResponse;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflarePurgeRequest;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareResponse;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareResultInfo;
import com.hubspot.baragon.service.edgecache.cloudflare.client.models.CloudflareZone;
import com.hubspot.horizon.HttpRequest.Method;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.Response;
@Singleton
public class CloudflareClient {
private static final Logger LOG = LoggerFactory.getLogger(CloudflareClient.class);
private static final int MAX_ZONES_PER_PAGE = 50;
private static final int MAX_DNS_RECORDS_PER_PAGE = 100;
private final AsyncHttpClient httpClient;
private final ObjectMapper objectMapper;
private final String apiBase;
private final String apiEmail;
private final String apiKey;
// <ZoneId, CloudflareZone>
private final Supplier<ConcurrentMap<String, CloudflareZone>> zoneCache;
// <ZoneId, <DnsName, CloudflareDnsRecord>>
private final LoadingCache<String, Map<String, CloudflareDnsRecord>> dnsRecordCache;
@Inject
public CloudflareClient(EdgeCacheConfiguration edgeCacheConfiguration,
@Named(BaragonServiceModule.BARAGON_SERVICE_HTTP_CLIENT) AsyncHttpClient httpClient,
ObjectMapper objectMapper) {
this.httpClient = httpClient;
this.objectMapper = objectMapper;
Map<String, String> integrationSettings = edgeCacheConfiguration.getIntegrationSettings();
this.apiBase = integrationSettings.get("apiBase");
this.apiEmail = integrationSettings.get("apiEmail");
this.apiKey = integrationSettings.get("apiKey");
this.zoneCache = Suppliers.memoizeWithExpiration(() -> {
try {
return retrieveAllZones().stream().collect(Collectors.toConcurrentMap(
CloudflareZone::getName, Function.identity()
));
} catch (CloudflareClientException e) {
LOG.error("Unable to refresh Cloudflare zone cache", e);
return new ConcurrentHashMap<>();
}
}, 10, TimeUnit.MINUTES);
this.dnsRecordCache = CacheBuilder.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(new CacheLoader<String, Map<String, CloudflareDnsRecord>>() {
@Override
public Map<String, CloudflareDnsRecord> load(String zoneId) throws Exception {
return retrieveDnsRecords(zoneId).stream().collect(Collectors.toConcurrentMap(
CloudflareDnsRecord::getName, Function.identity()
));
}
});
}
public boolean purgeEdgeCache(String zoneId, List<String> cacheTags) throws CloudflareClientException {
CloudflarePurgeRequest purgeRequest = new CloudflarePurgeRequest(Collections.emptyList(), cacheTags);
Response response = requestWith(Method.DELETE, String.format("zones/%s/purge_cache", zoneId), purgeRequest);
return isSuccess(response);
}
private Response requestWith(Method method, String path, Object body) throws CloudflareClientException {
return request(method, path, Optional.of(body), Optional.absent(), Optional.absent(), Optional.absent(), Optional.absent());
}
private Response request(Method method, String path, Optional<Object> body, Optional<Integer> page, Optional<Integer> perPage, Optional<String> order, Optional<String> direction) throws CloudflareClientException {
BoundRequestBuilder builder;
switch (method) {
case DELETE:
builder = httpClient.prepareDelete(apiBase + path);
break;
case GET:
default:
builder = httpClient.prepareGet(apiBase + path);
}
builder
.addHeader("X-Auth-Email", apiEmail)
.addHeader("X-Auth-Key", apiKey);
if (body.isPresent()) {
try {
builder.setBody(objectMapper.writeValueAsString(body.get()));
} catch (JsonProcessingException e) {
throw new CloudflareClientException("Unable to serialize body while preparing to send API request", e);
}
}
page.asSet().forEach(p -> builder.addQueryParameter("page", page.get().toString()));
perPage.asSet().forEach(p -> builder.addQueryParameter("per_page", perPage.get().toString()));
order.asSet().forEach(o -> builder.addQueryParameter("order", order.get()));
direction.asSet().forEach(d -> builder.addQueryParameter("direction", direction.get()));
try {
return builder.execute().get();
} catch (Exception e) {
throw new CloudflareClientException("Unexpected error during Cloudflare API call", e);
}
}
private boolean isSuccess(Response response) {
return response.getStatusCode() >= 200 && response.getStatusCode() < 300;
}
public CloudflareZone getZone(String name) throws CloudflareClientException {
return zoneCache.get().get(name);
}
public List<CloudflareZone> retrieveAllZones() throws CloudflareClientException {
CloudflareListZonesResponse cloudflareResponse = listZonesPaged(1);
List<CloudflareZone> zones = new ArrayList<>();
zones.addAll(cloudflareResponse.getResult());
CloudflareResultInfo paginationInfo = cloudflareResponse.getResultInfo();
for (int i = 2; i <= paginationInfo.getTotalPages(); i++) {
CloudflareListZonesResponse cloudflarePageResponse = listZonesPaged(i);
zones.addAll(cloudflarePageResponse.getResult());
}
return zones;
}
private CloudflareListZonesResponse listZonesPaged(Integer page) throws CloudflareClientException {
Response response = pagedRequest(Method.GET, "zones", page, MAX_ZONES_PER_PAGE);
if (!isSuccess(response)) {
try {
CloudflareResponse parsedResponse = objectMapper.readValue(response.getResponseBody(), CloudflareListZonesResponse.class);
throw new CloudflareClientException("Failed to get zones, " + parsedResponse);
} catch (IOException e) {
throw new CloudflareClientException("Failed to get zones; unable to parse error response");
}
}
try {
return objectMapper.readValue(response.getResponseBody(), CloudflareListZonesResponse.class);
} catch (IOException e) {
throw new CloudflareClientException("Unable to parse Cloudflare List Zones response", e);
}
}
public CloudflareDnsRecord getDnsRecord(String zoneId, String name) throws CloudflareClientException {
try {
return dnsRecordCache.get(zoneId).get(name);
} catch (ExecutionException e) {
throw new CloudflareClientException(e.getMessage(), e.getCause());
}
}
public Set<CloudflareDnsRecord> retrieveDnsRecords(String zoneId) throws CloudflareClientException {
CloudflareListDnsRecordsResponse cloudflareResponse = listDnsRecordsPaged(zoneId, 1);
Set<CloudflareDnsRecord> dnsRecords = cloudflareResponse.getResult();
CloudflareResultInfo paginationInfo = cloudflareResponse.getResultInfo();
for (int i = 2; i <= paginationInfo.getTotalPages(); i++) {
CloudflareListDnsRecordsResponse cloudflarePageResponse = listDnsRecordsPaged(zoneId, i);
dnsRecords.addAll(cloudflarePageResponse.getResult());
}
return dnsRecords;
}
private CloudflareListDnsRecordsResponse listDnsRecordsPaged(String zoneId, Integer page) throws CloudflareClientException {
Response response = pagedRequest(Method.GET, String.format("zones/%s/dns_records", zoneId), page, MAX_DNS_RECORDS_PER_PAGE);
if (!isSuccess(response)) {
try {
CloudflareResponse parsedResponse = objectMapper.readValue(response.getResponseBody(), CloudflareListDnsRecordsResponse.class);
throw new CloudflareClientException("Failed to get DNS records, " + parsedResponse);
} catch (IOException e) {
throw new CloudflareClientException("Failed to get DNS records; unable to parse error response");
}
}
try {
return objectMapper.readValue(response.getResponseBody(), CloudflareListDnsRecordsResponse.class);
} catch (IOException e) {
throw new CloudflareClientException("Unable to parse Cloudflare List DNS Records response", e);
}
}
private Response pagedRequest(Method method, String path, Integer page, Integer perPage) throws CloudflareClientException {
return request(method, path, Optional.absent(), Optional.of(page), Optional.of(perPage), Optional.absent(), Optional.absent());
}
}
|
Ignore duplicate names in cloudflare dns zone cache
|
BaragonService/src/main/java/com/hubspot/baragon/service/edgecache/cloudflare/client/CloudflareClient.java
|
Ignore duplicate names in cloudflare dns zone cache
|
|
Java
|
bsd-3-clause
|
76c2b024511b9463e05f64cdad7eb616576e461b
| 0
|
sirixdb/sirix,sirixdb/sirix,sirixdb/sirix,sirixdb/sirix
|
package org.sirix.xquery.compiler.expression;
import org.brackit.xquery.QueryContext;
import org.brackit.xquery.QueryException;
import org.brackit.xquery.Tuple;
import org.brackit.xquery.array.DArray;
import org.brackit.xquery.atomic.QNm;
import org.brackit.xquery.util.path.Path;
import org.brackit.xquery.xdm.Expr;
import org.brackit.xquery.xdm.Item;
import org.brackit.xquery.xdm.Sequence;
import org.sirix.api.json.JsonNodeReadOnlyTrx;
import org.sirix.index.IndexDef;
import org.sirix.xquery.SirixQueryContext;
import org.sirix.xquery.json.JsonDBCollection;
import org.sirix.xquery.json.JsonItemFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toSet;
public final class IndexExpr implements Expr {
private final String databaseName;
private final String resourceName;
private final Integer revision;
private final Map<IndexDef, List<Path<QNm>>> indexDefsToPaths;
public IndexExpr(final Map<String, Object> properties) {
requireNonNull(properties);
databaseName = (String) properties.get("databaseName");
resourceName = (String) properties.get("resourceName");
revision = (Integer) properties.get("revision");
indexDefsToPaths = (Map<IndexDef, List<Path<QNm>>>) properties.get("indexDefs");
}
@Override
public Sequence evaluate(QueryContext ctx, Tuple tuple) throws QueryException {
final var jsonItemStore = ((SirixQueryContext) ctx).getJsonItemStore();
final JsonDBCollection jsonCollection = jsonItemStore.lookup(databaseName);
final var database = jsonCollection.getDatabase();
final var manager = database.openResourceManager(resourceName);
final var indexController = revision == -1
? manager.getRtxIndexController(manager.getMostRecentRevisionNumber())
: manager.getRtxIndexController(revision);
final JsonNodeReadOnlyTrx rtx =
revision == -1 ? manager.beginNodeReadOnlyTrx() : manager.beginNodeReadOnlyTrx(revision);
final var nodeKeys = new ArrayList<Long>();
for (final Map.Entry<IndexDef, List<Path<QNm>>> entrySet : indexDefsToPaths.entrySet()) {
final var pathStrings = entrySet.getValue().stream().map(Path::toString).collect(toSet());
final var nodeReferencesIterator = indexController.openPathIndex(rtx.getPageTrx(),
entrySet.getKey(),
indexController.createPathFilter(pathStrings,
rtx));
nodeReferencesIterator.forEachRemaining(currentNodeReferences -> nodeKeys.addAll(currentNodeReferences.getNodeKeys()));
}
final var sequence = new ArrayList<Sequence>();
final var jsonItemFactory = new JsonItemFactory();
nodeKeys.forEach(nodeKey -> {
rtx.moveTo(nodeKey).trx().moveToFirstChild();
sequence.add(jsonItemFactory.getSequence(rtx, jsonCollection));
});
if (sequence.size() == 0) {
return null;
}
return new DArray(sequence.toArray(new Sequence[] {}));
}
@Override
public Item evaluateToItem(QueryContext ctx, Tuple tuple) throws QueryException {
final var res = evaluate(ctx, tuple);
if (res instanceof Item) {
return (Item) res;
}
return null;
}
@Override
public boolean isUpdating() {
return false;
}
@Override
public boolean isVacuous() {
return false;
}
}
|
bundles/sirix-xquery/src/main/java/org/sirix/xquery/compiler/expression/IndexExpr.java
|
package org.sirix.xquery.compiler.expression;
import org.brackit.xquery.QueryContext;
import org.brackit.xquery.QueryException;
import org.brackit.xquery.Tuple;
import org.brackit.xquery.array.DArray;
import org.brackit.xquery.atomic.QNm;
import org.brackit.xquery.util.path.Path;
import org.brackit.xquery.xdm.Expr;
import org.brackit.xquery.xdm.Item;
import org.brackit.xquery.xdm.Sequence;
import org.sirix.api.json.JsonNodeReadOnlyTrx;
import org.sirix.index.IndexDef;
import org.sirix.xquery.SirixQueryContext;
import org.sirix.xquery.json.JsonDBCollection;
import org.sirix.xquery.json.JsonItemFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toSet;
public final class IndexExpr implements Expr {
private final String databaseName;
private final String resourceName;
private final Integer revision;
private final Map<IndexDef, List<Path<QNm>>> indexDefsToPaths;
public IndexExpr(final Map<String, Object> properties) {
requireNonNull(properties);
databaseName = (String) properties.get("databaseName");
resourceName = (String) properties.get("resourceName");
revision = (Integer) properties.get("revision");
indexDefsToPaths = (Map<IndexDef, List<Path<QNm>>>) properties.get("indexDefs");
}
@Override
public Sequence evaluate(QueryContext ctx, Tuple tuple) throws QueryException {
final var jsonItemStore = ((SirixQueryContext) ctx).getJsonItemStore();
final JsonDBCollection jsonCollection = jsonItemStore.lookup(databaseName);
final var database = jsonCollection.getDatabase();
final var manager = database.openResourceManager(resourceName);
final var indexController = revision == -1
? manager.getRtxIndexController(manager.getMostRecentRevisionNumber())
: manager.getRtxIndexController(revision);
final JsonNodeReadOnlyTrx rtx =
revision == -1 ? manager.beginNodeReadOnlyTrx() : manager.beginNodeReadOnlyTrx(revision);
final var nodeKeys = new ArrayList<Long>();
for (final Map.Entry<IndexDef, List<Path<QNm>>> entrySet : indexDefsToPaths.entrySet()) {
final var pathStrings = entrySet.getValue().stream().map(Path::toString).collect(toSet());
final var nodeReferencesIterator = indexController.openPathIndex(rtx.getPageTrx(),
entrySet.getKey(),
indexController.createPathFilter(pathStrings,
rtx));
nodeReferencesIterator.forEachRemaining(currentNodeReferences -> nodeKeys.addAll(currentNodeReferences.getNodeKeys()));
}
final var sequence = new ArrayList<Sequence>();
final var jsonItemFactory = new JsonItemFactory();
nodeKeys.forEach(nodeKey -> {
rtx.moveTo(nodeKey).trx().moveToFirstChild();
sequence.add(jsonItemFactory.getSequence(rtx, jsonCollection));
});
if (sequence.size() == 0) {
return null;
}
return new DArray(sequence.toArray(new Sequence[] {}));
}
@Override
public Item evaluateToItem(QueryContext ctx, Tuple tuple) throws QueryException {
return null;
}
@Override
public boolean isUpdating() {
return false;
}
@Override
public boolean isVacuous() {
return false;
}
}
|
Add IndexExpr in SirixTranslator.
|
bundles/sirix-xquery/src/main/java/org/sirix/xquery/compiler/expression/IndexExpr.java
|
Add IndexExpr in SirixTranslator.
|
|
Java
|
bsd-3-clause
|
b9bd5b727649cbe12b10c7c9c9a9798f1d5381fe
| 0
|
crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl
|
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content.browser;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.SurfaceTexture;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.TextureView.SurfaceTextureListener;
import android.widget.FrameLayout;
import org.chromium.base.CalledByNative;
import org.chromium.base.JNINamespace;
import org.chromium.ui.base.WindowAndroid;
/***
* This view is used by a ContentView to render its content.
* Call {@link #setCurrentContentViewCore(ContentViewCore)} with the contentViewCore that should be
* managing the view.
* Note that only one ContentViewCore can be shown at a time.
*/
@JNINamespace("content")
public class ContentViewRenderView extends FrameLayout {
// The native side of this object.
private long mNativeContentViewRenderView;
private SurfaceHolder.Callback mSurfaceCallback;
private final SurfaceView mSurfaceView;
protected ContentViewCore mContentViewCore;
// Enum for the type of compositing surface:
// SURFACE_VIEW - Use SurfaceView as compositing surface which
// has a bit performance advantage
// TEXTURE_VIEW - Use TextureView as compositing surface which
// supports animation on the View
public enum CompositingSurfaceType { SURFACE_VIEW, TEXTURE_VIEW };
// The stuff for TextureView usage. It is not a good practice to mix 2 different
// implementations into one single class. However, for the sake of reducing the
// effort of rebasing maintanence in future, here we avoid heavily changes in
// this class.
private TextureView mTextureView;
private Surface mSurface;
private CompositingSurfaceType mCompositingSurfaceType;
private ContentReadbackHandler mContentReadbackHandler;
// The listener which will be triggered when below two conditions become valid.
// 1. The view has been initialized and ready to draw content to the screen.
// 2. The compositor finished compositing and the OpenGL buffers has been swapped.
// Which means the view has been updated with visually non-empty content.
// This listener will be triggered only once after registered.
private FirstRenderedFrameListener mFirstRenderedFrameListener;
private boolean mFirstFrameReceived;
public interface FirstRenderedFrameListener{
public void onFirstFrameReceived();
}
// Initialize the TextureView for rendering ContentView and configure the callback
// listeners.
private void initTextureView(Context context) {
mTextureView = new TextureView(context);
mTextureView.setBackgroundColor(Color.WHITE);
mTextureView.setSurfaceTextureListener(new SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture,
int width, int height) {
assert mNativeContentViewRenderView != 0;
mSurface = new Surface(surfaceTexture);
nativeSurfaceCreated(mNativeContentViewRenderView);
// Force to trigger the compositor to start working.
onSurfaceTextureSizeChanged(surfaceTexture, width, height);
onReadyToRender();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture,
int width, int height) {
assert mNativeContentViewRenderView != 0 && mSurface != null;
assert surfaceTexture == mTextureView.getSurfaceTexture();
assert mSurface != null;
// Here we hard-code the pixel format since the native part requires
// the format parameter to decide if the compositing surface should be
// replaced with a new one when the format is changed.
//
// If TextureView is used, the surface won't be possible to changed,
// so that the format is also not changed. There is no special reason
// to use RGBA_8888 value since the native part won't use its real
// value to do something for drawing.
//
// TODO(hmin): Figure out how to get pixel format from SurfaceTexture.
int format = PixelFormat.RGBA_8888;
nativeSurfaceChanged(mNativeContentViewRenderView,
format, width, height, mSurface);
if (mContentViewCore != null) {
mContentViewCore.onPhysicalBackingSizeChanged(
width, height);
}
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
assert mNativeContentViewRenderView != 0;
nativeSurfaceDestroyed(mNativeContentViewRenderView);
// Release the underlying surface to make it invalid.
mSurface.release();
mSurface = null;
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
// Do nothing since the SurfaceTexture won't be updated via updateTexImage().
}
});
}
public ContentViewRenderView(Context context) {
this(context, CompositingSurfaceType.SURFACE_VIEW);
}
/**
* Constructs a new ContentViewRenderView.
* This should be called and the {@link ContentViewRenderView} should be added to the view
* hierarchy before the first draw to avoid a black flash that is seen every time a
* {@link SurfaceView} is added.
* @param context The context used to create this.
* @param surfaceType TextureView is used as compositing target surface,
* otherwise SurfaceView is used.
*/
public ContentViewRenderView(Context context, CompositingSurfaceType surfaceType) {
super(context);
mCompositingSurfaceType = surfaceType;
if (surfaceType == CompositingSurfaceType.TEXTURE_VIEW) {
initTextureView(context);
addView(mTextureView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
// Avoid compiler warning.
mSurfaceView = null;
mSurfaceCallback = null;
return;
}
mSurfaceView = createSurfaceView(getContext());
mSurfaceView.setZOrderMediaOverlay(true);
setSurfaceViewBackgroundColor(Color.WHITE);
addView(mSurfaceView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
mSurfaceView.setVisibility(GONE);
}
/**
* Initialization that requires native libraries should be done here.
* Native code should add/remove the layers to be rendered through the ContentViewLayerRenderer.
* @param rootWindow The {@link WindowAndroid} this render view should be linked to.
*/
public void onNativeLibraryLoaded(WindowAndroid rootWindow) {
assert rootWindow != null;
mNativeContentViewRenderView = nativeInit(rootWindow.getNativePointer());
assert mNativeContentViewRenderView != 0;
mContentReadbackHandler = new ContentReadbackHandler() {
@Override
protected boolean readyForReadback() {
return mNativeContentViewRenderView != 0 && mContentViewCore != null;
}
};
mContentReadbackHandler.initNativeContentReadbackHandler();
if (mCompositingSurfaceType == CompositingSurfaceType.TEXTURE_VIEW)
return;
assert !mSurfaceView.getHolder().getSurface().isValid() :
"Surface created before native library loaded.";
mSurfaceCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
assert mNativeContentViewRenderView != 0;
nativeSurfaceChanged(mNativeContentViewRenderView,
format, width, height, holder.getSurface());
if (mContentViewCore != null) {
mContentViewCore.onPhysicalBackingSizeChanged(
width, height);
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
assert mNativeContentViewRenderView != 0;
nativeSurfaceCreated(mNativeContentViewRenderView);
onReadyToRender();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
assert mNativeContentViewRenderView != 0;
nativeSurfaceDestroyed(mNativeContentViewRenderView);
}
};
mSurfaceView.getHolder().addCallback(mSurfaceCallback);
mSurfaceView.setVisibility(VISIBLE);
}
/**
* @return The content readback handler.
*/
public ContentReadbackHandler getContentReadbackHandler() {
return mContentReadbackHandler;
}
/**
* Sets the background color of the surface view. This method is necessary because the
* background color of ContentViewRenderView itself is covered by the background of
* SurfaceView.
* @param color The color of the background.
*/
public void setSurfaceViewBackgroundColor(int color) {
if (mSurfaceView != null) {
mSurfaceView.setBackgroundColor(color);
}
}
/**
* Should be called when the ContentViewRenderView is not needed anymore so its associated
* native resource can be freed.
*/
public void destroy() {
mContentReadbackHandler.destroy();
mContentReadbackHandler = null;
if (mCompositingSurfaceType == CompositingSurfaceType.TEXTURE_VIEW) {
mTextureView.setSurfaceTextureListener(null);
if (mSurface != null) {
mSurface.release();
mSurface = null;
}
} else {
mSurfaceView.getHolder().removeCallback(mSurfaceCallback);
}
nativeDestroy(mNativeContentViewRenderView);
mNativeContentViewRenderView = 0;
}
public void setCurrentContentViewCore(ContentViewCore contentViewCore) {
assert mNativeContentViewRenderView != 0;
mContentViewCore = contentViewCore;
if (mContentViewCore != null) {
mContentViewCore.onPhysicalBackingSizeChanged(getWidth(), getHeight());
nativeSetCurrentContentViewCore(mNativeContentViewRenderView,
mContentViewCore.getNativeContentViewCore());
} else {
nativeSetCurrentContentViewCore(mNativeContentViewRenderView, 0);
}
}
/**
* Trigger a redraw of the compositor. This is only needed if the UI changes something that
* does not trigger a redraw itself by updating the layer tree.
*/
public void setNeedsComposite() {
if (mNativeContentViewRenderView == 0) return;
nativeSetNeedsComposite(mNativeContentViewRenderView);
}
/**
* This method should be subclassed to provide actions to be performed once the view is ready to
* render.
*/
protected void onReadyToRender() {
}
/**
* This method could be subclassed optionally to provide a custom SurfaceView object to
* this ContentViewRenderView.
* @param context The context used to create the SurfaceView object.
* @return The created SurfaceView object.
*/
protected SurfaceView createSurfaceView(Context context) {
return new SurfaceView(context);
}
public void registerFirstRenderedFrameListener(FirstRenderedFrameListener listener) {
mFirstRenderedFrameListener = listener;
if (mFirstFrameReceived && mFirstRenderedFrameListener != null) {
mFirstRenderedFrameListener.onFirstFrameReceived();
}
}
/**
* @return whether the surface view is initialized and ready to render.
*/
public boolean isInitialized() {
return mSurfaceView.getHolder().getSurface() != null || mSurface != null;
}
/**
* Enter or leave overlay video mode.
* @param enabled Whether overlay mode is enabled.
*/
public void setOverlayVideoMode(boolean enabled) {
if (mCompositingSurfaceType == CompositingSurfaceType.TEXTURE_VIEW) {
nativeSetOverlayVideoMode(mNativeContentViewRenderView, enabled);
return;
}
int format = enabled ? PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE;
mSurfaceView.getHolder().setFormat(format);
nativeSetOverlayVideoMode(mNativeContentViewRenderView, enabled);
}
/**
* Set the native layer tree helper for this {@link ContentViewRenderView}.
* @param layerTreeBuildHelperNativePtr Native pointer to the layer tree build helper.
*/
public void setLayerTreeBuildHelper(long layerTreeBuildHelperNativePtr) {
nativeSetLayerTreeBuildHelper(mNativeContentViewRenderView, layerTreeBuildHelperNativePtr);
}
@CalledByNative
protected void onCompositorLayout() {
}
@CalledByNative
private void onSwapBuffersCompleted() {
if (!mFirstFrameReceived && mContentViewCore != null &&
mContentViewCore.isReady()) {
mFirstFrameReceived = true;
if (mFirstRenderedFrameListener != null) {
mFirstRenderedFrameListener.onFirstFrameReceived();
}
}
// Ignore if TextureView is used.
if (mCompositingSurfaceType == CompositingSurfaceType.TEXTURE_VIEW) return;
if (mSurfaceView.getBackground() != null) {
post(new Runnable() {
@Override public void run() {
mSurfaceView.setBackgroundResource(0);
}
});
}
}
/**
* @return Native pointer for the UI resource provider taken from the compositor.
*/
public long getUIResourceProvider() {
return nativeGetUIResourceProvider(mNativeContentViewRenderView);
}
private native long nativeInit(long rootWindowNativePointer);
private native long nativeGetUIResourceProvider(long nativeContentViewRenderView);
private native void nativeDestroy(long nativeContentViewRenderView);
private native void nativeSetCurrentContentViewCore(long nativeContentViewRenderView,
long nativeContentViewCore);
private native void nativeSetLayerTreeBuildHelper(long nativeContentViewRenderView,
long buildHelperNativePtr);
private native void nativeSurfaceCreated(long nativeContentViewRenderView);
private native void nativeSurfaceDestroyed(long nativeContentViewRenderView);
private native void nativeSurfaceChanged(long nativeContentViewRenderView,
int format, int width, int height, Surface surface);
private native void nativeSetOverlayVideoMode(long nativeContentViewRenderView,
boolean enabled);
private native void nativeSetNeedsComposite(long nativeContentViewRenderView);
}
|
content/public/android/java/src/org/chromium/content/browser/ContentViewRenderView.java
|
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.content.browser;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.SurfaceTexture;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.TextureView.SurfaceTextureListener;
import android.widget.FrameLayout;
import org.chromium.base.CalledByNative;
import org.chromium.base.JNINamespace;
import org.chromium.ui.base.WindowAndroid;
/***
* This view is used by a ContentView to render its content.
* Call {@link #setCurrentContentViewCore(ContentViewCore)} with the contentViewCore that should be
* managing the view.
* Note that only one ContentViewCore can be shown at a time.
*/
@JNINamespace("content")
public class ContentViewRenderView extends FrameLayout {
// The native side of this object.
private long mNativeContentViewRenderView;
private SurfaceHolder.Callback mSurfaceCallback;
private final SurfaceView mSurfaceView;
protected ContentViewCore mContentViewCore;
// Enum for the type of compositing surface:
// SURFACE_VIEW - Use SurfaceView as compositing surface which
// has a bit performance advantage
// TEXTURE_VIEW - Use TextureView as compositing surface which
// supports animation on the View
public enum CompositingSurfaceType { SURFACE_VIEW, TEXTURE_VIEW };
// The stuff for TextureView usage. It is not a good practice to mix 2 different
// implementations into one single class. However, for the sake of reducing the
// effort of rebasing maintanence in future, here we avoid heavily changes in
// this class.
private TextureView mTextureView;
private Surface mSurface;
private CompositingSurfaceType mCompositingSurfaceType;
private ContentReadbackHandler mContentReadbackHandler;
// The listener which will be triggered when below two conditions become valid.
// 1. The view has been initialized and ready to draw content to the screen.
// 2. The compositor finished compositing and the OpenGL buffers has been swapped.
// Which means the view has been updated with visually non-empty content.
// This listener will be triggered only once after registered.
private FirstRenderedFrameListener mFirstRenderedFrameListener;
private boolean mFirstFrameReceived;
public interface FirstRenderedFrameListener{
public void onFirstFrameReceived();
}
// Initialize the TextureView for rendering ContentView and configure the callback
// listeners.
private void initTextureView(Context context) {
mTextureView = new TextureView(context);
mTextureView.setBackgroundColor(Color.WHITE);
mTextureView.setSurfaceTextureListener(new SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture,
int width, int height) {
assert mNativeContentViewRenderView != 0;
mSurface = new Surface(surfaceTexture);
nativeSurfaceCreated(mNativeContentViewRenderView);
// Force to trigger the compositor to start working.
onSurfaceTextureSizeChanged(surfaceTexture, width, height);
onReadyToRender();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture,
int width, int height) {
assert mNativeContentViewRenderView != 0 && mSurface != null;
assert surfaceTexture == mTextureView.getSurfaceTexture();
assert mSurface != null;
// Here we hard-code the pixel format since the native part requires
// the format parameter to decide if the compositing surface should be
// replaced with a new one when the format is changed.
//
// If TextureView is used, the surface won't be possible to changed,
// so that the format is also not changed. There is no special reason
// to use RGBA_8888 value since the native part won't use its real
// value to do something for drawing.
//
// TODO(hmin): Figure out how to get pixel format from SurfaceTexture.
int format = PixelFormat.RGBA_8888;
nativeSurfaceChanged(mNativeContentViewRenderView,
format, width, height, mSurface);
if (mContentViewCore != null) {
mContentViewCore.onPhysicalBackingSizeChanged(
width, height);
}
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
assert mNativeContentViewRenderView != 0;
nativeSurfaceDestroyed(mNativeContentViewRenderView);
// Release the underlying surface to make it invalid.
mSurface.release();
mSurface = null;
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
// Do nothing since the SurfaceTexture won't be updated via updateTexImage().
}
});
}
public ContentViewRenderView(Context context) {
this(context, CompositingSurfaceType.SURFACE_VIEW);
}
/**
* Constructs a new ContentViewRenderView.
* This should be called and the {@link ContentViewRenderView} should be added to the view
* hierarchy before the first draw to avoid a black flash that is seen every time a
* {@link SurfaceView} is added.
* @param context The context used to create this.
* @param surfaceType TextureView is used as compositing target surface,
* otherwise SurfaceView is used.
*/
public ContentViewRenderView(Context context, CompositingSurfaceType surfaceType) {
super(context);
mCompositingSurfaceType = surfaceType;
if (surfaceType == CompositingSurfaceType.TEXTURE_VIEW) {
initTextureView(context);
addView(mTextureView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
// Avoid compiler warning.
mSurfaceView = null;
mSurfaceCallback = null;
return;
}
mSurfaceView = createSurfaceView(getContext());
mSurfaceView.setZOrderMediaOverlay(true);
setSurfaceViewBackgroundColor(Color.WHITE);
addView(mSurfaceView,
new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
mSurfaceView.setVisibility(GONE);
}
/**
* Initialization that requires native libraries should be done here.
* Native code should add/remove the layers to be rendered through the ContentViewLayerRenderer.
* @param rootWindow The {@link WindowAndroid} this render view should be linked to.
*/
public void onNativeLibraryLoaded(WindowAndroid rootWindow) {
assert !mSurfaceView.getHolder().getSurface().isValid() :
"Surface created before native library loaded.";
assert rootWindow != null;
mNativeContentViewRenderView = nativeInit(rootWindow.getNativePointer());
assert mNativeContentViewRenderView != 0;
mSurfaceCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
assert mNativeContentViewRenderView != 0;
nativeSurfaceChanged(mNativeContentViewRenderView,
format, width, height, holder.getSurface());
if (mContentViewCore != null) {
mContentViewCore.onPhysicalBackingSizeChanged(
width, height);
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
assert mNativeContentViewRenderView != 0;
nativeSurfaceCreated(mNativeContentViewRenderView);
onReadyToRender();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
assert mNativeContentViewRenderView != 0;
nativeSurfaceDestroyed(mNativeContentViewRenderView);
}
};
mSurfaceView.getHolder().addCallback(mSurfaceCallback);
mSurfaceView.setVisibility(VISIBLE);
mContentReadbackHandler = new ContentReadbackHandler() {
@Override
protected boolean readyForReadback() {
return mNativeContentViewRenderView != 0 && mContentViewCore != null;
}
};
mContentReadbackHandler.initNativeContentReadbackHandler();
}
/**
* @return The content readback handler.
*/
public ContentReadbackHandler getContentReadbackHandler() {
return mContentReadbackHandler;
}
/**
* Sets the background color of the surface view. This method is necessary because the
* background color of ContentViewRenderView itself is covered by the background of
* SurfaceView.
* @param color The color of the background.
*/
public void setSurfaceViewBackgroundColor(int color) {
if (mSurfaceView != null) {
mSurfaceView.setBackgroundColor(color);
}
}
/**
* Should be called when the ContentViewRenderView is not needed anymore so its associated
* native resource can be freed.
*/
public void destroy() {
mContentReadbackHandler.destroy();
mContentReadbackHandler = null;
if (mCompositingSurfaceType == CompositingSurfaceType.TEXTURE_VIEW) {
mTextureView.setSurfaceTextureListener(null);
if (mSurface != null) {
mSurface.release();
mSurface = null;
}
} else {
mSurfaceView.getHolder().removeCallback(mSurfaceCallback);
}
nativeDestroy(mNativeContentViewRenderView);
mNativeContentViewRenderView = 0;
}
public void setCurrentContentViewCore(ContentViewCore contentViewCore) {
assert mNativeContentViewRenderView != 0;
mContentViewCore = contentViewCore;
if (mContentViewCore != null) {
mContentViewCore.onPhysicalBackingSizeChanged(getWidth(), getHeight());
nativeSetCurrentContentViewCore(mNativeContentViewRenderView,
mContentViewCore.getNativeContentViewCore());
} else {
nativeSetCurrentContentViewCore(mNativeContentViewRenderView, 0);
}
}
/**
* Trigger a redraw of the compositor. This is only needed if the UI changes something that
* does not trigger a redraw itself by updating the layer tree.
*/
public void setNeedsComposite() {
if (mNativeContentViewRenderView == 0) return;
nativeSetNeedsComposite(mNativeContentViewRenderView);
}
/**
* This method should be subclassed to provide actions to be performed once the view is ready to
* render.
*/
protected void onReadyToRender() {
}
/**
* This method could be subclassed optionally to provide a custom SurfaceView object to
* this ContentViewRenderView.
* @param context The context used to create the SurfaceView object.
* @return The created SurfaceView object.
*/
protected SurfaceView createSurfaceView(Context context) {
return new SurfaceView(context);
}
public void registerFirstRenderedFrameListener(FirstRenderedFrameListener listener) {
mFirstRenderedFrameListener = listener;
if (mFirstFrameReceived && mFirstRenderedFrameListener != null) {
mFirstRenderedFrameListener.onFirstFrameReceived();
}
}
/**
* @return whether the surface view is initialized and ready to render.
*/
public boolean isInitialized() {
return mSurfaceView.getHolder().getSurface() != null || mSurface != null;
}
/**
* Enter or leave overlay video mode.
* @param enabled Whether overlay mode is enabled.
*/
public void setOverlayVideoMode(boolean enabled) {
if (mCompositingSurfaceType == CompositingSurfaceType.TEXTURE_VIEW) {
nativeSetOverlayVideoMode(mNativeContentViewRenderView, enabled);
return;
}
int format = enabled ? PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE;
mSurfaceView.getHolder().setFormat(format);
nativeSetOverlayVideoMode(mNativeContentViewRenderView, enabled);
}
/**
* Set the native layer tree helper for this {@link ContentViewRenderView}.
* @param layerTreeBuildHelperNativePtr Native pointer to the layer tree build helper.
*/
public void setLayerTreeBuildHelper(long layerTreeBuildHelperNativePtr) {
nativeSetLayerTreeBuildHelper(mNativeContentViewRenderView, layerTreeBuildHelperNativePtr);
}
@CalledByNative
protected void onCompositorLayout() {
}
@CalledByNative
private void onSwapBuffersCompleted() {
if (!mFirstFrameReceived && mContentViewCore != null &&
mContentViewCore.isReady()) {
mFirstFrameReceived = true;
if (mFirstRenderedFrameListener != null) {
mFirstRenderedFrameListener.onFirstFrameReceived();
}
}
// Ignore if TextureView is used.
if (mCompositingSurfaceType == CompositingSurfaceType.TEXTURE_VIEW) return;
if (mSurfaceView.getBackground() != null) {
post(new Runnable() {
@Override public void run() {
mSurfaceView.setBackgroundResource(0);
}
});
}
}
/**
* @return Native pointer for the UI resource provider taken from the compositor.
*/
public long getUIResourceProvider() {
return nativeGetUIResourceProvider(mNativeContentViewRenderView);
}
private native long nativeInit(long rootWindowNativePointer);
private native long nativeGetUIResourceProvider(long nativeContentViewRenderView);
private native void nativeDestroy(long nativeContentViewRenderView);
private native void nativeSetCurrentContentViewCore(long nativeContentViewRenderView,
long nativeContentViewCore);
private native void nativeSetLayerTreeBuildHelper(long nativeContentViewRenderView,
long buildHelperNativePtr);
private native void nativeSurfaceCreated(long nativeContentViewRenderView);
private native void nativeSurfaceDestroyed(long nativeContentViewRenderView);
private native void nativeSurfaceChanged(long nativeContentViewRenderView,
int format, int width, int height, Surface surface);
private native void nativeSetOverlayVideoMode(long nativeContentViewRenderView,
boolean enabled);
private native void nativeSetNeedsComposite(long nativeContentViewRenderView);
}
|
[Android] Only initialize ContentReadbackHandler in onNativeLibraryLoaded for TextureView.
Let's bail out after ContentReadbackHandler initialization in the case of
TextureView.
BUG=https://crosswalk-project.org/jira/browse/XWALK-1887
Reworked with M38.
|
content/public/android/java/src/org/chromium/content/browser/ContentViewRenderView.java
|
[Android] Only initialize ContentReadbackHandler in onNativeLibraryLoaded for TextureView.
|
|
Java
|
bsd-3-clause
|
17a8a62b0c9f1162e54ccfab79521d171e45830d
| 0
|
ojacobson/dryad-repo,jimallman/dryad-repo,mdiggory/dryad-repo,mdiggory/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,mdiggory/dryad-repo,mdiggory/dryad-repo,mdiggory/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo
|
/*
* CollectionViewer.java
*
* Version: $Revision: 1.21 $
*
* Date: $Date: 2006/07/27 18:24:34 $
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.xmlui.aspect.submission;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.authorize.AuthorizeException;
import org.dspace.authorize.AuthorizeManager;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.core.Constants;
import org.dspace.eperson.Group;
import org.xml.sax.SAXException;
/**
* Add a single link to the display item page that allows
* the user to submit a new item to this collection.
*
* @author Scott Phillips
*/
public class CollectionViewer extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings */
protected static final Message T_title =
message("xmlui.Submission.SelectCollection.title");
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
return "0";
return HashUtil.hash(dso.getHandle());
}
catch (SQLException sqle)
{
// Ignore all errors and just return that the component is not
// cachable.
return "0";
}
}
/**
* Generate the cache validity object.
*
* The validity object will include the collection being viewed and
* all recently submitted items. This does not include the community / collection
* hierarch, when this changes they will not be reflected in the cache.
*/
public SourceValidity getValidity()
{
if (this.validity == null)
{
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
return null;
if (!(dso instanceof Collection))
return null;
Collection collection = (Collection) dso;
DSpaceValidity validity = new DSpaceValidity();
// Add the actual collection;
validity.add(collection);
// Add the eperson viewing the collection
validity.add(eperson);
// Include any groups they are a member of
Group[] groups = Group.allMemberGroups(context, eperson);
for (Group group : groups)
{
validity.add(group);
}
this.validity = validity.complete();
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
/**
* Add a single link to the view item page that allows the user
* to submit to the collection.
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Collection))
return;
// Set up the major variables
Collection collection = (Collection) dso;
// Only add the submit link if the user has the ability to add items.
if (AuthorizeManager.authorizeActionBoolean(context, collection, Constants.ADD))
{
Division home = body.addDivision("collection-home","primary repository collection");
Division viewer = home.addDivision("collection-view","secondary");
String submitURL = contextPath + "/handle/" + collection.getHandle() + "/submit";
viewer.addPara().addXref(submitURL,"Submit a new item to this collection");
}
}
/**
* Recycle
*/
public void recycle()
{
this.validity = null;
super.recycle();
}
}
|
dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/CollectionViewer.java
|
/*
* CollectionViewer.java
*
* Version: $Revision: 1.21 $
*
* Date: $Date: 2006/07/27 18:24:34 $
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.xmlui.aspect.submission;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import org.apache.cocoon.caching.CacheableProcessingComponent;
import org.apache.cocoon.util.HashUtil;
import org.apache.excalibur.source.SourceValidity;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.DSpaceValidity;
import org.dspace.app.xmlui.utils.HandleUtil;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.DSpaceObject;
import org.dspace.eperson.Group;
import org.xml.sax.SAXException;
/**
* Add a single link to the display item page that allows
* the user to submit a new item to this collection.
*
* @author Scott Phillips
*/
public class CollectionViewer extends AbstractDSpaceTransformer implements CacheableProcessingComponent
{
/** Language Strings */
protected static final Message T_title =
message("xmlui.Submission.SelectCollection.title");
/** Cached validity object */
private SourceValidity validity;
/**
* Generate the unique caching key.
* This key must be unique inside the space of this component.
*/
public Serializable getKey()
{
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
return "0";
return HashUtil.hash(dso.getHandle());
}
catch (SQLException sqle)
{
// Ignore all errors and just return that the component is not
// cachable.
return "0";
}
}
/**
* Generate the cache validity object.
*
* The validity object will include the collection being viewed and
* all recently submitted items. This does not include the community / collection
* hierarch, when this changes they will not be reflected in the cache.
*/
public SourceValidity getValidity()
{
if (this.validity == null)
{
try
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (dso == null)
return null;
if (!(dso instanceof Collection))
return null;
Collection collection = (Collection) dso;
DSpaceValidity validity = new DSpaceValidity();
// Add the actual collection;
validity.add(collection);
// Add the eperson viewing the collection
validity.add(eperson);
// Include any groups they are a member of
Group[] groups = Group.allMemberGroups(context, eperson);
for (Group group : groups)
{
validity.add(group);
}
this.validity = validity.complete();
}
catch (Exception e)
{
// Just ignore all errors and return an invalid cache.
}
}
return this.validity;
}
/**
* Add a single link to the view item page that allows the user
* to submit to the collection.
*/
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
if (!(dso instanceof Collection))
return;
// Set up the major variables
Collection collection = (Collection) dso;
Division home = body.addDivision("collection-home","primary repository collection");
Division viewer = home.addDivision("collection-view","secondary");
String submitURL = contextPath + "/handle/" + collection.getHandle() + "/submit";
viewer.addPara().addXref(submitURL,"Submit a new item to this collection");
}
/**
* Recycle
*/
public void recycle()
{
this.validity = null;
super.recycle();
}
}
|
(Scott Phillips) SF#1897647 - For a logged in user the submit button is allways displayed
git-svn-id: 80a01abba97d47db4f6b7aa893d54fe8b6cbeff5@2746 9c30dcfa-912a-0410-8fc2-9e0234be79fd
|
dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/CollectionViewer.java
|
(Scott Phillips) SF#1897647 - For a logged in user the submit button is allways displayed
|
|
Java
|
bsd-3-clause
|
5bccc3cd8d1601f7d2af3c1c6724400526886e9a
| 0
|
ConnCollege/cas,ConnCollege/cas,ConnCollege/cas
|
/*
* Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license
* distributed with this file and available online at
* http://www.uportal.org/license.html
*/
package org.jasig.cas.audit.spi;
import org.aspectj.lang.JoinPoint;
import com.github.inspektr.common.spi.PrincipalResolver;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.ticket.ServiceTicket;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.util.AopUtils;
import javax.validation.constraints.NotNull;
/**
* PrincipalResolver that can retrieve the username from either the Ticket or from the Credentials.
*
* @author Scott Battaglia
* @version $Revision: 1.1 $ $Date: 2005/08/19 18:27:17 $
* @since 3.1.2
*
*/
public class TicketOrCredentialPrincipalResolver implements PrincipalResolver {
@NotNull
protected TicketRegistry ticketRegistry;
public void setTicketRegistry(final TicketRegistry ticketRegistry) {
this.ticketRegistry = ticketRegistry;
}
public String resolveFrom(final JoinPoint joinPoint, final Object retVal) {
return resolveFromInternal(AopUtils.unWrapJoinPoint(joinPoint));
}
public String resolveFrom(final JoinPoint joinPoint, final Exception retVal) {
return resolveFromInternal(AopUtils.unWrapJoinPoint(joinPoint));
}
public String resolve() {
return UNKNOWN_USER;
}
protected String resolveFromInternal(final JoinPoint joinPoint) {
final Object arg1 = joinPoint.getArgs()[0];
if (arg1 instanceof Credentials) {
return arg1.toString();
} else if (arg1 instanceof String) {
final Ticket ticket = this.ticketRegistry.getTicket((String) arg1);
if (ticket instanceof ServiceTicket) {
final ServiceTicket serviceTicket = (ServiceTicket) ticket;
return serviceTicket.getGrantingTicket().getAuthentication().getPrincipal().getId();
} else if (ticket instanceof TicketGrantingTicket) {
final TicketGrantingTicket tgt = (TicketGrantingTicket) ticket;
return tgt.getAuthentication().getPrincipal().getId();
}
}
return UNKNOWN_USER;
}
}
|
cas-server-core/src/main/java/org/jasig/cas/audit/spi/TicketOrCredentialPrincipalResolver.java
|
/*
* Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license
* distributed with this file and available online at
* http://www.uportal.org/license.html
*/
package org.jasig.cas.audit.spi;
import org.aspectj.lang.JoinPoint;
import com.github.inspektr.common.spi.PrincipalResolver;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.ticket.ServiceTicket;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.util.AopUtils;
import javax.validation.constraints.NotNull;
/**
* PrincipalResolver that can retrieve the username from either the Ticket or from the Credentials.
*
* @author Scott Battaglia
* @version $Revision: 1.1 $ $Date: 2005/08/19 18:27:17 $
* @since 3.1.2
*
*/
public class TicketOrCredentialPrincipalResolver implements PrincipalResolver {
@NotNull
protected TicketRegistry ticketRegistry;
public void setTicketRegistry(final TicketRegistry ticketRegistry) {
this.ticketRegistry = ticketRegistry;
}
public String resolveFrom(final JoinPoint joinPoint, final Object retval) {
return resolveFromInternal(AopUtils.unWrapJoinPoint(joinPoint));
}
public String resolveFrom(final JoinPoint joinPoint, Exception retval) {
return resolveFromInternal(AopUtils.unWrapJoinPoint(joinPoint));
}
public String resolve() {
return UNKNOWN_USER;
}
protected String resolveFromInternal(final JoinPoint joinPoint) {
final Object arg1 = joinPoint.getArgs()[0];
if (arg1 instanceof Credentials) {
return arg1.toString();
} else if (arg1 instanceof String) {
final Ticket ticket = this.ticketRegistry.getTicket((String) arg1);
if (ticket instanceof ServiceTicket) {
final ServiceTicket serviceTicket = (ServiceTicket) ticket;
return serviceTicket.getGrantingTicket().getAuthentication().getPrincipal().getId();
} else if (ticket instanceof TicketGrantingTicket) {
final TicketGrantingTicket tgt = (TicketGrantingTicket) ticket;
return tgt.getAuthentication().getPrincipal().getId();
}
}
return UNKNOWN_USER;
}
}
|
NOJIRA
added missing final
|
cas-server-core/src/main/java/org/jasig/cas/audit/spi/TicketOrCredentialPrincipalResolver.java
|
NOJIRA
|
|
Java
|
mit
|
58ff4c7253a8a1683a48e5ee087de59836e3c51f
| 0
|
MEiDIK/SlimAdapter,MEiDIK/SlimAdapter
|
package net.idik.lib.slimadapter.ex.loadmore;
import android.view.View;
/**
* Created by linshuaibin on 22/05/2017.
*/
public abstract class LoadMoreViewCreator {
private SlimMoreLoader loader;
public void attachLoader(SlimMoreLoader loader) {
this.loader = loader;
}
protected void reload() {
loader.loadMore();
}
protected abstract View createLoadingView();
protected abstract View createNoMoreView();
protected abstract View createPullToLoadMoreView();
protected abstract View createErrorView();
}
|
slimadapter/src/main/java/net/idik/lib/slimadapter/ex/loadmore/LoadMoreViewCreator.java
|
package net.idik.lib.slimadapter.ex.loadmore;
import android.view.View;
/**
* Created by linshuaibin on 22/05/2017.
*/
public abstract class LoadMoreViewCreator {
private SlimMoreLoader loader;
public void attachLoader(SlimMoreLoader loader) {
this.loader = loader;
}
protected void reload() {
loader.loadMore();
}
abstract View createLoadingView();
abstract View createNoMoreView();
abstract View createPullToLoadMoreView();
abstract View createErrorView();
}
|
Update LoadMoreViewCreator.java
#fix unnable to custom LoadMoreView
|
slimadapter/src/main/java/net/idik/lib/slimadapter/ex/loadmore/LoadMoreViewCreator.java
|
Update LoadMoreViewCreator.java
|
|
Java
|
mit
|
93abae93b6485afb6a22caeb802980abae84af7b
| 0
|
ponzao/mira
|
package org.ponzao;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
private static class Node implements Comparable<Node> {
private final char c;
private final int column;
private final int row;
private Double cost;
private Double estimatedDistance;
private Node parent;
public Node(final char c, final int row, final int column) {
this.c = c;
this.column = column;
this.row = row;
}
@Override
public String toString() {
return "" + this.c;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
public boolean isBlocked() {
return c == '#';
}
public void setParent(Node parent) {
this.parent = parent;
}
public Node getParent() {
return parent;
}
public void setCost(Double cost) {
this.cost = cost;
}
public Double getCost() {
return cost;
}
public void setEstimatedDistance(Double estimatedDistance) {
this.estimatedDistance = estimatedDistance;
}
public Double calculateDistance(final Node other) {
return Math.sqrt(Math.pow(other.column - this.column, 2)
+ Math.pow(other.row - this.row, 2));
}
public Double getEstimatedDistance() {
return estimatedDistance;
}
@Override
public int compareTo(Node o) {
final Double thisSum = estimatedDistance + cost;
final Double thatSum = o.estimatedDistance + o.cost;
return thisSum < thatSum ? -1 : thisSum > thatSum ? 1 : 0;
}
}
private static class Grid {
private final Node grid[][];
private Node start;
private Node goal;
private final int rows;
private final int columns;
private static final Double DIAGONAL_COST = Math.sqrt(2);
private static final Double NORMAL_COST = 1.0;
public Grid(final char[][] charGrid) {
this.rows = charGrid.length;
this.columns = charGrid[0].length;
this.grid = new Node[rows][columns];
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < columns; ++column) {
final Node node = new Node(charGrid[row][column], row,
column);
if (charGrid[row][column] == 'S')
this.start = node;
else if (charGrid[row][column] == 'G')
this.goal = node;
this.grid[row][column] = node;
}
}
}
public Node getStart() {
return start;
}
public Node getGoal() {
return goal;
}
private boolean isInGrid(final int row, final int column) {
return 0 <= row && 0 <= column && column < columns && row < rows;
}
// TODO Honestly, wtf :D
public List<Node> accessibleNeighbors(final Node node) {
final List<Node> result = new ArrayList<Node>();
final int origRow = node.getRow();
final int origColumn = node.getColumn();
for (int row = origRow - 1; row <= origRow + 1; ++row) {
for (int column = origColumn - 1; column <= origColumn + 1; ++column) {
if (!(row == origRow && column == origColumn)
&& isInGrid(row, column)
&& !grid[row][column].isBlocked()) {
final Node current = grid[row][column];
if (row != origRow && column != origColumn) {
if (current.getCost() == null) {
current.setCost(DIAGONAL_COST + node.getCost());
} else if (current.getCost() != null
&& (DIAGONAL_COST + node.getCost()) < current
.getCost()) {
current.setCost(DIAGONAL_COST + node.getCost());
} else {
continue;
}
} else {
if (current.getCost() == null) {
current.setCost(NORMAL_COST + node.getCost());
} else if ((NORMAL_COST + node.getCost()) < current
.getCost()) {
current.setCost(NORMAL_COST + node.getCost());
} else {
continue;
}
}
if (current.getEstimatedDistance() == null) {
current.setEstimatedDistance(current
.calculateDistance(goal));
}
current.setParent(node);
result.add(current);
}
}
}
return result;
}
@Override
public String toString() {
String s = "";
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < columns; ++column) {
s = s + this.grid[row][column];
}
s = s + "\n";
}
return s;
}
}
public static void main(String args[]) {
final Grid grid = new Grid(new char[][] {
{ '.', '.', '.', '.', '.', '.', '.' },
{ '#', '#', '.', '#', '.', '.', '.' },
{ 'S', '#', '.', '#', '.', '.', '.' },
{ '.', '#', '.', '#', '.', '.', '.' },
{ '.', '.', '.', '#', '.', '.', 'G' }, });
showRoute(findRouteToGoal(grid));
}
private static void showRoute(final Node goal) {
System.out.println("Route from goal to start, indexed from 1.");
Node current = goal;
while (current != null) {
System.out.println("Column: " + (current.getColumn() + 1)
+ ", Row: " + (1 + current.getRow()));
current = current.getParent();
}
}
private static Node findRouteToGoal(final Grid grid) {
final List<Node> open = new ArrayList<Node>();
final Node start = grid.getStart();
final Node goal = grid.getGoal();
start.setCost(0.0);
open.add(start);
open.addAll(grid.accessibleNeighbors(start));
open.remove(start);
Collections.sort(open);
while (true) {
final Node bestNode = open.get(0);
open.addAll(grid.accessibleNeighbors(bestNode));
if (open.contains(goal)) {
return goal;
}
open.remove(bestNode);
Collections.sort(open);
}
}
}
|
src/main/java/org/ponzao/Main.java
|
package org.ponzao;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
private static class Node implements Comparable<Node> {
private final char c;
private final int column;
private final int row;
private Double cost;
private Double estimatedDistance;
private Node parent;
public Node(final char c, final int row, final int column) {
this.c = c;
this.column = column;
this.row = row;
}
@Override
public String toString() {
return "" + this.c;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
public boolean isBlocked() {
return c == '#';
}
public void setParent(Node parent) {
this.parent = parent;
}
public Node getParent() {
return parent;
}
public void setCost(Double cost) {
this.cost = cost;
}
public Double getCost() {
return cost;
}
public void setEstimatedDistance(Double estimatedDistance) {
this.estimatedDistance = estimatedDistance;
}
public Double calculateDistance(final Node other) {
return Math.sqrt(Math.pow(other.column - this.column, 2)
+ Math.pow(other.row - this.row, 2));
}
public Double getEstimatedDistance() {
return estimatedDistance;
}
@Override
public int compareTo(Node o) {
final Double thisSum = estimatedDistance + cost;
final Double thatSum = o.estimatedDistance + o.cost;
return thisSum < thatSum ? -1 : thisSum > thatSum ? 1 : 0;
}
}
private static class Grid {
private final Node grid[][];
private Node start;
private Node goal;
private final int rows;
private final int columns;
private static final Double DIAGONAL_COST = Math.sqrt(2);
private static final Double NORMAL_COST = 1.0;
public Grid(final char[][] charGrid) {
this.rows = charGrid.length;
this.columns = charGrid[0].length;
this.grid = new Node[rows][columns];
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < columns; ++column) {
final Node node = new Node(charGrid[row][column], row,
column);
if (charGrid[row][column] == 'S')
this.start = node;
else if (charGrid[row][column] == 'G')
this.goal = node;
this.grid[row][column] = node;
}
}
}
public Node getStart() {
return start;
}
public Node getGoal() {
return goal;
}
private boolean isInGrid(final int row, final int column) {
return 0 <= row && 0 <= column && column < columns && row < rows;
}
// TODO Honestly, wtf :D
public List<Node> accessibleNeighbors(final Node node) {
final List<Node> result = new ArrayList<Node>();
final int origRow = node.getRow();
final int origColumn = node.getColumn();
for (int row = origRow - 1; row <= origRow + 1; ++row) {
for (int column = origColumn - 1; column <= origColumn + 1; ++column) {
if (!(row == origRow && column == origColumn)
&& isInGrid(row, column)
&& !grid[row][column].isBlocked()) {
final Node current = grid[row][column];
if (row != origRow && column != origColumn) {
if (current.getCost() == null) {
current.setCost(DIAGONAL_COST + node.getCost());
} else if (current.getCost() != null
&& (DIAGONAL_COST + node.getCost()) < current
.getCost()) {
current.setCost(DIAGONAL_COST + node.getCost());
} else {
continue;
}
} else {
if (current.getCost() == null) {
current.setCost(NORMAL_COST + node.getCost());
} else if ((NORMAL_COST + node.getCost()) < current
.getCost()) {
current.setCost(NORMAL_COST + node.getCost());
} else {
continue;
}
}
if (current.getEstimatedDistance() == null) {
current.setEstimatedDistance(current
.calculateDistance(goal));
}
current.setParent(node);
result.add(current);
}
}
}
return result;
}
@Override
public String toString() {
String s = "";
for (int row = 0; row < rows; ++row) {
for (int column = 0; column < columns; ++column) {
s = s + this.grid[row][column];
}
s = s + "\n";
}
return s;
}
}
public static void main(String args[]) {
final Grid grid = new Grid(new char[][] {
{ '.', '.', '.', '.', '.', '.', '.' },
{ '#', '#', '.', '#', '.', '.', '.' },
{ 'S', '#', '.', '#', '.', '.', '.' },
{ '.', '#', '.', '#', '.', '.', '.' },
{ '.', '.', '.', '#', '.', '.', 'G' }, });
showRoute(findRouteToGoal(grid));
}
private static void showRoute(final Node goal) {
System.out.println("Route from goal to start, indexed from 1.");
Node current = goal;
while (current != null) {
System.out.println("Column: " + (current.getColumn() + 1)
+ ", Row: " + (1 + current.getRow()));
current = current.getParent();
}
}
private static Node findRouteToGoal(final Grid grid) {
final List<Node> open = new ArrayList<Node>();
final Node start = grid.getStart();
final Node goal = grid.getGoal();
start.setCost(0.0);
open.add(start);
final List<Node> closed = new ArrayList<Node>();
open.addAll(grid.accessibleNeighbors(start));
open.remove(start);
Collections.sort(open);
closed.add(start);
while (true) {
final Node bestNode = open.get(0);
open.addAll(grid.accessibleNeighbors(bestNode));
if (open.contains(goal)) {
return goal;
}
open.remove(bestNode);
Collections.sort(open);
closed.add(bestNode);
}
}
}
|
Removed unnecessary Collection for removed nodes.
|
src/main/java/org/ponzao/Main.java
|
Removed unnecessary Collection for removed nodes.
|
|
Java
|
mit
|
7dc9be324710aaaeb1ab2d2e620705a798ae4cac
| 0
|
saptarshidebnath/processrunner,saptarshidebnath/processrunner
|
package com.saptarshidebnath.processrunner.lib.process;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.saptarshidebnath.processrunner.lib.exception.ProcessConfigurationException;
import com.saptarshidebnath.processrunner.lib.exception.ProcessException;
import com.saptarshidebnath.processrunner.lib.output.Output;
import com.saptarshidebnath.processrunner.lib.utilities.Constants;
import org.apache.commons.lang3.SystemUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.StringStartsWith.startsWith;
/** Created by saptarshi on 12/22/2016. */
public class ProcessRunnerImplFactoryTest {
private final Gson gson;
private final int arryPosition;
{
this.gson = new GsonBuilder().setPrettyPrinting().create();
if (SystemUtils.IS_OS_WINDOWS) {
this.arryPosition = 1;
} else {
this.arryPosition = 0;
}
}
@Before
public void setUp() throws Exception {}
@After
public void tearDown() throws Exception {}
@Test
public void startProcess() throws ProcessException {
final int response =
ProcessRunnerFactory.startProcess(getDefaultInterpreter(), getInterPreterVersion());
assertThat("Validating process runner for simple process : ", response, is(0));
}
@Test(expected = ProcessException.class)
public void startProcessWithWrongParmeters() throws ProcessException {
ProcessRunnerFactory.startProcess("", getInterPreterVersion());
}
@Test(expected = ProcessException.class)
public void getProcessWithLessParamsWrongParamets() throws ProcessException {
final ProcessRunner processRunner =
ProcessRunnerFactory.startProcess(
getDefaultInterpreter(), "", Constants.DEFAULT_CURRENT_DIR);
processRunner.getJsonLogDump().delete();
}
@Test(expected = ProcessException.class)
public void getProcessMoreParamWrongParamets() throws ProcessException, IOException {
final File tempFile = File.createTempFile("temp-file-name", ".json");
tempFile.deleteOnExit();
final ProcessRunner processRunner =
ProcessRunnerFactory.startProcess(
"", getInterPreterVersion(), Constants.DEFAULT_CURRENT_DIR, tempFile, false);
}
@Test
public void startProcessWithProcessConfig()
throws ProcessException, IOException, ProcessConfigurationException {
final File tempFile = File.createTempFile("temp", ".json");
tempFile.deleteOnExit();
final ProcessConfiguration configuration =
new ProcessConfiguration(
getDefaultInterpreter(),
getInterPreterVersion(),
Constants.DEFAULT_CURRENT_DIR,
tempFile,
true);
final Integer response = ProcessRunnerFactory.startProcess(configuration);
assertThat("Validating process return code : ", response, is(0));
}
@Test
public void startThreadedProcessWithProcessConfig()
throws ProcessException, IOException, ProcessConfigurationException, ExecutionException,
InterruptedException {
final File tempFile = File.createTempFile("temp", ".json");
tempFile.deleteOnExit();
final ProcessConfiguration configuration =
new ProcessConfiguration(
getDefaultInterpreter(),
getInterPreterVersion(),
Constants.DEFAULT_CURRENT_DIR,
tempFile,
true);
final Future<Integer> response = ProcessRunnerFactory.startProcess(configuration, true);
assertThat("Validating process return code : ", response.get(), is(0));
}
@Test(expected = ProcessException.class)
public void startProcessWithProcessConfigWithWrongParams()
throws ProcessException, IOException, ProcessConfigurationException {
final File tempFile = File.createTempFile("temp", ".json");
tempFile.setReadOnly();
tempFile.deleteOnExit();
final ProcessConfiguration configuration =
new ProcessConfiguration(
getDefaultInterpreter(),
getInterPreterVersion(),
Constants.DEFAULT_CURRENT_DIR,
tempFile,
true);
ProcessRunnerFactory.startProcess(configuration);
}
@Test(expected = ProcessException.class)
public void startThreadedProcessWithProcessConfigWithWrongParams()
throws ProcessException, IOException, ProcessConfigurationException {
final File tempFile = File.createTempFile("temp", ".json");
tempFile.setReadOnly();
tempFile.deleteOnExit();
final ProcessConfiguration configuration =
new ProcessConfiguration(
getDefaultInterpreter(),
getInterPreterVersion(),
Constants.DEFAULT_CURRENT_DIR,
tempFile,
true);
ProcessRunnerFactory.startProcess(configuration, true);
}
@Test
public void getProcessLessDetailed() throws IOException, ProcessException, InterruptedException {
final ProcessRunner processRunner =
ProcessRunnerFactory.startProcess(
getDefaultInterpreter(), getInterPreterVersion(), Constants.DEFAULT_CURRENT_DIR);
final int response = processRunner.run();
assertThat("Validating process return code : ", response, is(0));
final File jsonLogDump = processRunner.getJsonLogDump();
assertThat("Validating if JSON log dump is created : ", jsonLogDump.exists(), is(true));
final String jsonLogAsString =
new Scanner(jsonLogDump, Charset.defaultCharset().name()).useDelimiter("\\Z").next();
final Type listTypeOuputArray = new TypeToken<List<Output>>() {}.getType();
final List<Output> output = this.gson.fromJson(jsonLogAsString, listTypeOuputArray);
assertThat("Is the jsonLogAsString a valid json : ", isJSONValid(jsonLogAsString), is(true));
assertThat("Validating json log record number : ", output.size(), is(getVersionPutputSize()));
assertThat(
"Validating json log content : ",
output.get(this.arryPosition).getOutputText(),
startsWith(getInitialVersionComments()));
jsonLogDump.delete();
}
private boolean isJSONValid(final String jsonInString) {
try {
this.gson.fromJson(jsonInString, Object.class);
return true;
} catch (final com.google.gson.JsonSyntaxException ex) {
return false;
}
}
private String getInterPreterVersion() {
String message = "--version";
if (SystemUtils.IS_OS_WINDOWS) {
message = "ver";
}
return message;
}
private int getVersionPutputSize() {
int response = 6;
if (SystemUtils.IS_OS_WINDOWS) {
response = 2;
}
return response;
}
private String getDefaultInterpreter() {
String message = "bash";
if (SystemUtils.IS_OS_WINDOWS) {
message = "cmd.exe /c";
}
return message;
}
private String getInitialVersionComments() {
String message = "GNU bash, version";
if (SystemUtils.IS_OS_WINDOWS) {
message = "Microsoft Windows [Version";
}
return message;
}
@Test
public void getProcessMoreDetailed() throws IOException, ProcessException, InterruptedException {
final ProcessRunner processRunner =
ProcessRunnerFactory.startProcess(
getDefaultInterpreter(),
getInterPreterVersion(),
Constants.DEFAULT_CURRENT_DIR,
File.createTempFile("temp-file-name", ".json"),
false);
final int response = processRunner.run();
assertThat("Validating process return code : ", response, is(0));
final File jsonLogDump = processRunner.getJsonLogDump();
assertThat("Validating if JSON log dump is created : ", jsonLogDump.exists(), is(true));
final String jsonLogAsString =
new Scanner(jsonLogDump, Charset.defaultCharset().name()).useDelimiter("\\Z").next();
final Type listTypeOuputArray = new TypeToken<List<Output>>() {}.getType();
final List<Output> output = this.gson.fromJson(jsonLogAsString, listTypeOuputArray);
assertThat("Is the jsonLogAsString a valid json : ", isJSONValid(jsonLogAsString), is(true));
assertThat("Validating json log record number : ", output.size(), is(getVersionPutputSize()));
assertThat(
"Validating json log content : ",
output.get(this.arryPosition).getOutputText(),
startsWith(getInitialVersionComments()));
//TODO
jsonLogDump.delete();
}
@Test
public void testSaveSysOutAndSaveSysError()
throws IOException, ProcessException, InterruptedException {
final File tempFile = File.createTempFile("temp-file-name", ".json");
tempFile.deleteOnExit();
ProcessRunner processRunner = null;
if (SystemUtils.IS_OS_WINDOWS) {
processRunner =
ProcessRunnerFactory.startProcess(
"cmd /c",
"test.bat",
new File(
Constants.DEFAULT_CURRENT_DIR.getAbsolutePath()
+ File.separator
+ "src"
+ File.separator
+ "test"
+ File.separator
+ "scripts"
+ File.separator
+ "batch"),
tempFile,
true);
} else if (SystemUtils.IS_OS_LINUX) {
processRunner =
ProcessRunnerFactory.startProcess(
"bash",
"test.sh",
new File(
Constants.DEFAULT_CURRENT_DIR.getAbsolutePath()
+ File.separator
+ "src"
+ File.separator
+ "test"
+ File.separator
+ "scripts"
+ File.separator
+ "shell"),
tempFile,
true);
}
final int response = processRunner.run();
final File sysout = processRunner.saveSysOut(File.createTempFile("temp-file-sysout", ".json"));
sysout.deleteOnExit();
final File syserr = processRunner.saveSysOut(File.createTempFile("temp-file-syserr", ".json"));
final File jsonLogDump = processRunner.getJsonLogDump();
jsonLogDump.deleteOnExit();
syserr.deleteOnExit();
assertThat("Validating process return code : ", response, is(0));
assertThat("Validating if JSON log dump is created : ", jsonLogDump.exists(), is(true));
final String jsonLogAsString =
new Scanner(jsonLogDump, Charset.defaultCharset().name()).useDelimiter("\\Z").next();
final Type listTypeOuputArray = new TypeToken<List<Output>>() {}.getType();
final List<Output> output = this.gson.fromJson(jsonLogAsString, listTypeOuputArray);
assertThat("Is the jsonLogAsString a valid json : ", isJSONValid(jsonLogAsString), is(true));
assertThat("Validating json log record number : ", output.size(), is(greaterThan(0)));
assertThat(
"Validating number of input on SYSERR : ", getFileLineNumber(syserr), is(greaterThan(0)));
assertThat(
"Validating number of input on SYSOUT : ", getFileLineNumber(sysout), is(greaterThan(0)));
}
private int getFileLineNumber(final File fileToCountLineNumber) throws IOException {
final LineNumberReader lnr = new LineNumberReader(new FileReader(fileToCountLineNumber));
lnr.skip(Long.MAX_VALUE);
final int lineNumber = lnr.getLineNumber() + 1; //Add 1 because line index starts at 0
lnr.close();
return lineNumber;
}
}
|
src/test/java/com/saptarshidebnath/processrunner/lib/process/ProcessRunnerImplFactoryTest.java
|
package com.saptarshidebnath.processrunner.lib.process;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.saptarshidebnath.processrunner.lib.exception.ProcessConfigurationException;
import com.saptarshidebnath.processrunner.lib.exception.ProcessException;
import com.saptarshidebnath.processrunner.lib.output.Output;
import com.saptarshidebnath.processrunner.lib.utilities.Constants;
import org.apache.commons.lang3.SystemUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.StringStartsWith.startsWith;
/** Created by saptarshi on 12/22/2016. */
public class ProcessRunnerImplFactoryTest {
private final Gson gson;
private final int arryPosition;
{
this.gson = new GsonBuilder().setPrettyPrinting().create();
if (SystemUtils.IS_OS_WINDOWS) {
this.arryPosition = 1;
} else {
this.arryPosition = 0;
}
}
@Before
public void setUp() throws Exception {}
@After
public void tearDown() throws Exception {}
@Test
public void startProcess() throws ProcessException {
final int response =
ProcessRunnerFactory.startProcess(getDefaultInterpreter(), getInterPreterVersion());
assertThat("Validating process runner for simple process : ", response, is(0));
}
@Test(expected = ProcessException.class)
public void startProcessWithWrongParmeters() throws ProcessException {
ProcessRunnerFactory.startProcess("", getInterPreterVersion());
}
@Test(expected = ProcessException.class)
public void getProcessWithLessParamsWrongParamets() throws ProcessException {
final ProcessRunner processRunner =
ProcessRunnerFactory.startProcess(
getDefaultInterpreter(), "", Constants.DEFAULT_CURRENT_DIR);
processRunner.getJsonLogDump().delete();
}
@Test(expected = ProcessException.class)
public void getProcessMoreParamWrongParamets() throws ProcessException, IOException {
final File tempFile = File.createTempFile("temp-file-name", ".json");
tempFile.deleteOnExit();
final ProcessRunner processRunner =
ProcessRunnerFactory.startProcess(
"", getInterPreterVersion(), Constants.DEFAULT_CURRENT_DIR, tempFile, false);
}
@Test
public void startProcessWithProcessConfig()
throws ProcessException, IOException, ProcessConfigurationException {
final File tempFile = File.createTempFile("temp", ".json");
tempFile.deleteOnExit();
final ProcessConfiguration configuration =
new ProcessConfiguration(
getDefaultInterpreter(),
getInterPreterVersion(),
Constants.DEFAULT_CURRENT_DIR,
tempFile,
true);
final Integer response = ProcessRunnerFactory.startProcess(configuration);
assertThat("Validating process return code : ", response, is(0));
}
@Test
public void startThreadedProcessWithProcessConfig()
throws ProcessException, IOException, ProcessConfigurationException, ExecutionException,
InterruptedException {
final File tempFile = File.createTempFile("temp", ".json");
tempFile.deleteOnExit();
final ProcessConfiguration configuration =
new ProcessConfiguration(
getDefaultInterpreter(),
getInterPreterVersion(),
Constants.DEFAULT_CURRENT_DIR,
tempFile,
true);
final Future<Integer> response = ProcessRunnerFactory.startProcess(configuration, true);
assertThat("Validating process return code : ", response.get(), is(0));
}
@Test(expected = ProcessException.class)
public void startProcessWithProcessConfigWithWrongParams()
throws ProcessException, IOException, ProcessConfigurationException {
final File tempFile = File.createTempFile("temp", ".json");
tempFile.setReadOnly();
tempFile.deleteOnExit();
final ProcessConfiguration configuration =
new ProcessConfiguration(
getDefaultInterpreter(),
getInterPreterVersion(),
Constants.DEFAULT_CURRENT_DIR,
tempFile,
true);
ProcessRunnerFactory.startProcess(configuration);
}
@Test(expected = ProcessException.class)
public void startThreadedProcessWithProcessConfigWithWrongParams()
throws ProcessException, IOException, ProcessConfigurationException {
final File tempFile = File.createTempFile("temp", ".json");
tempFile.setReadOnly();
tempFile.deleteOnExit();
final ProcessConfiguration configuration =
new ProcessConfiguration(
getDefaultInterpreter(),
getInterPreterVersion(),
Constants.DEFAULT_CURRENT_DIR,
tempFile,
true);
ProcessRunnerFactory.startProcess(configuration, true);
}
@Test
public void getProcessLessDetailed() throws IOException, ProcessException, InterruptedException {
final ProcessRunner processRunner =
ProcessRunnerFactory.startProcess(
getDefaultInterpreter(), getInterPreterVersion(), Constants.DEFAULT_CURRENT_DIR);
final int response = processRunner.run();
assertThat("Validating process return code : ", response, is(0));
final File jsonLogDump = processRunner.getJsonLogDump();
assertThat("Validating if JSON log dump is created : ", jsonLogDump.exists(), is(true));
final String jsonLogAsString =
new Scanner(jsonLogDump, Charset.defaultCharset().name()).useDelimiter("\\Z").next();
final Type listTypeOuputArray = new TypeToken<List<Output>>() {}.getType();
final List<Output> output = this.gson.fromJson(jsonLogAsString, listTypeOuputArray);
assertThat("Is the jsonLogAsString a valid json : ", isJSONValid(jsonLogAsString), is(true));
assertThat("Validating json log record number : ", output.size(), is(getVersionPutputSize()));
assertThat(
"Validating json log content : ",
output.get(this.arryPosition).getOutputText(),
startsWith(getInitialVersionComments()));
jsonLogDump.delete();
}
private boolean isJSONValid(final String jsonInString) {
try {
this.gson.fromJson(jsonInString, Object.class);
return true;
} catch (final com.google.gson.JsonSyntaxException ex) {
return false;
}
}
private String getInterPreterVersion() {
String message = "--version";
if (SystemUtils.IS_OS_WINDOWS) {
message = "ver";
}
return message;
}
private int getVersionPutputSize() {
int response = 6;
if (SystemUtils.IS_OS_WINDOWS) {
response = 2;
}
return response;
}
private String getDefaultInterpreter() {
String message = "bash";
if (SystemUtils.IS_OS_WINDOWS) {
message = "cmd.exe /c";
}
return message;
}
private String getInitialVersionComments() {
String message = "GNU bash, version";
if (SystemUtils.IS_OS_WINDOWS) {
message = "Microsoft Windows [Version";
}
return message;
}
@Test
public void getProcessMoreDetailed() throws IOException, ProcessException, InterruptedException {
final ProcessRunner processRunner =
ProcessRunnerFactory.startProcess(
getDefaultInterpreter(),
getInterPreterVersion(),
Constants.DEFAULT_CURRENT_DIR,
File.createTempFile("temp-file-name", ".json"),
false);
final int response = processRunner.run();
assertThat("Validating process return code : ", response, is(0));
final File jsonLogDump = processRunner.getJsonLogDump();
assertThat("Validating if JSON log dump is created : ", jsonLogDump.exists(), is(true));
final String jsonLogAsString =
new Scanner(jsonLogDump, Charset.defaultCharset().name()).useDelimiter("\\Z").next();
final Type listTypeOuputArray = new TypeToken<List<Output>>() {}.getType();
final List<Output> output = this.gson.fromJson(jsonLogAsString, listTypeOuputArray);
assertThat("Is the jsonLogAsString a valid json : ", isJSONValid(jsonLogAsString), is(true));
assertThat("Validating json log record number : ", output.size(), is(getVersionPutputSize()));
assertThat(
"Validating json log content : ",
output.get(this.arryPosition).getOutputText(),
startsWith(getInitialVersionComments()));
//TODO
jsonLogDump.delete();
}
@Test
public void te() throws IOException, ProcessException, InterruptedException {
final File tempFile = File.createTempFile("temp-file-name", ".json");
tempFile.deleteOnExit();
ProcessRunner processRunner = null;
if (SystemUtils.IS_OS_WINDOWS) {
processRunner =
ProcessRunnerFactory.startProcess(
"cmd /c",
"test.bat",
new File(
Constants.DEFAULT_CURRENT_DIR.getAbsolutePath()
+ File.separator
+ "src"
+ File.separator
+ "test"
+ File.separator
+ "scripts"
+ File.separator
+ "batch"),
tempFile,
true);
} else if (SystemUtils.IS_OS_LINUX) {
processRunner =
ProcessRunnerFactory.startProcess(
"bash",
"test.sh",
new File(
Constants.DEFAULT_CURRENT_DIR.getAbsolutePath()
+ File.separator
+ "src"
+ File.separator
+ "test"
+ File.separator
+ "scripts"
+ File.separator
+ "shell"),
tempFile,
true);
}
final int response = processRunner.run();
final File sysout = processRunner.saveSysOut(File.createTempFile("temp-file-sysout", ".json"));
sysout.deleteOnExit();
final File syserr = processRunner.saveSysOut(File.createTempFile("temp-file-syserr", ".json"));
final File jsonLogDump = processRunner.getJsonLogDump();
jsonLogDump.deleteOnExit();
syserr.deleteOnExit();
assertThat("Validating process return code : ", response, is(0));
assertThat("Validating if JSON log dump is created : ", jsonLogDump.exists(), is(true));
final String jsonLogAsString =
new Scanner(jsonLogDump, Charset.defaultCharset().name()).useDelimiter("\\Z").next();
final Type listTypeOuputArray = new TypeToken<List<Output>>() {}.getType();
final List<Output> output = this.gson.fromJson(jsonLogAsString, listTypeOuputArray);
assertThat("Is the jsonLogAsString a valid json : ", isJSONValid(jsonLogAsString), is(true));
assertThat("Validating json log record number : ", output.size(), is(greaterThan(0)));
assertThat(
"Validating number of input on SYSERR : ", getFileLineNumber(syserr), is(greaterThan(0)));
assertThat(
"Validating number of input on SYSOUT : ", getFileLineNumber(sysout), is(greaterThan(0)));
}
private int getFileLineNumber(final File fileToCountLineNumber) throws IOException {
final LineNumberReader lnr = new LineNumberReader(new FileReader(fileToCountLineNumber));
lnr.skip(Long.MAX_VALUE);
final int lineNumber = lnr.getLineNumber() + 1; //Add 1 because line index starts at 0
lnr.close();
return lineNumber;
}
}
|
Updated method name
|
src/test/java/com/saptarshidebnath/processrunner/lib/process/ProcessRunnerImplFactoryTest.java
|
Updated method name
|
|
Java
|
mit
|
fb9c6c53d1ce5e4d501ec76e103b6f9ac42c024f
| 0
|
datasift/datasift-java,datasift/datasift-java
|
package com.datasift.client.managedsource.sources;
import com.datasift.client.DataSiftConfig;
import com.datasift.client.managedsource.ManagedDataSourceType;
/**
* @author Courtney Robinson <courtney.robinson@datasift.com>
*/
public class Instagram extends BaseSource<Instagram> {
public Instagram(DataSiftConfig config) {
super(config, ManagedDataSourceType.INSTAGRAM);
}
/**
* set to true, if you want to receive like interactions.
*
* @return this
*/
public Instagram enableLikes(boolean enabled) {
return setParametersField("likes", enabled);
}
/**
* set to true, if you want to receive comment interactions.
*
* @return this
*/
public Instagram enableComments(boolean enabled) {
return setParametersField("comments", enabled);
}
/**
* Adds a managed instagram source by user
*
* @param userId the ID of the user
* @return this
*/
public Instagram byUser(String userId) {
addResource(Type.USER, userId, -1, -1, -1, false, null);
return this;
}
/**
* Adds a resource by tag
*
* @param tag the tag, e.g cat
* @param exactMatch true when a tag must be an exact match or false when the tag should match the instragram tag
* search behaviour
* @return this
*/
public Instagram byTag(String tag, boolean exactMatch) {
addResource(Type.TAG, tag, -1, -1, -1, exactMatch, null);
return this;
}
public Instagram byArea(float longitude, float lattitude) {
return byArea(longitude, lattitude);
}
/**
* Adds a resource a given area
*
* @param longitude the longitude value of the coordinates to use
* @param latitude the latitude value of the coordinate to use
* @param distance an optional distance which marks the radius around the given area,
* defaults to 1000 and must be between 1 and 5000 metres
* @return this
*/
public Instagram byArea(float longitude, float latitude, int distance) {
addResource(Type.AREA, null, longitude, latitude, distance, false, null);
return this;
}
public Instagram byLocation(float longitude, float latitude) {
return byLocation(longitude, latitude, 0);
}
/**
* Adds a resource a given location
*
* @param longitude the longitude value of the coordinates to use
* @param latitude the latitude value of the coordinate to use
* @param distance an optional distance which marks the radius around the given area,
* defaults to 1000 and must be between 1 and 5000 metres
* @return this
* @see #byArea(float, float, int)
*/
public Instagram byLocation(float longitude, float latitude, int distance) {
addResource(Type.LOCATION, null, longitude, latitude, distance, false, null);
return this;
}
/**
* The same as {@link #byLocation(float, float, int)} but instead of using coordinates a foursquare location ID
* is provided
*
* @param fourSquareLocation a valid foursquare location ID e.g. 5XfVJe
* @return this
*/
public Instagram byFoursquareLocation(String fourSquareLocation) {
throw new Exception('Instagram has deprecated foursquare support since 20th April 2016');
}
/**
* Adds a resource that is filtered based on popularity
*
* @return this
*/
public Instagram byPopularity() {
addResource(Type.POPULAR, null, -1, -1, -1, false, null);
return this;
}
/**
* Adds a resource object to the request of the given type, which is always required
*
* @param type the type of resource, all other params are optional dependent upon what this value is
* @return this
*/
protected Instagram addResource(Type type, String value, float longitude, float lattitude, int distance,
boolean exactMatch, String fourSquareLocation) {
ResourceParams parameterSet = newResourceParams();
switch (type) {
case USER:
if (value == null) {
throw new IllegalArgumentException("If type is user then value is required");
}
parameterSet.set("type", "user");
parameterSet.set("value", value);
break;
case TAG:
if (value == null) {
throw new IllegalArgumentException("If type is user then value is required");
}
parameterSet.set("type", "tag");
parameterSet.set("value", value);
parameterSet.set("extact_match", exactMatch);
break;
case AREA:
case LOCATION:
if (value == null || distance > 5000) {
throw new IllegalArgumentException("If provided distance must be between 1 and 5000 metres or < 0" +
" to be ignored");
}
if (type == Type.LOCATION) {
parameterSet.set("type", "location");
if (fourSquareLocation != null) {
parameterSet.set("foursq", fourSquareLocation);
}
} else {
parameterSet.set("type", "area");
}
if (fourSquareLocation == null) {
parameterSet.set("lat", lattitude);
parameterSet.set("lng", longitude);
if (distance > 0) {
parameterSet.set("distance", lattitude);
}
}
break;
case POPULAR:
parameterSet.set("type", "popular");
break;
}
return this;
}
/**
* Adds an OAuth token to the managed source
*
* @param oAuthAccessToken an oauth2 token
* @param name a human friendly name for this auth token
* @param expires identity resource expiry date/time as a UTC timestamp, i.e. when the token expires
* @return this
*/
public Instagram addOAutToken(String oAuthAccessToken, long expires, String name) {
if (oAuthAccessToken == null || oAuthAccessToken.isEmpty()) {
throw new IllegalArgumentException("A valid OAuth and refresh token is required");
}
AuthParams parameterSet = newAuthParams(name, expires);
parameterSet.set("value", oAuthAccessToken);
return this;
}
public static enum Type {
USER, TAG, AREA, LOCATION, POPULAR
}
}
|
src/main/java/com/datasift/client/managedsource/sources/Instagram.java
|
package com.datasift.client.managedsource.sources;
import com.datasift.client.DataSiftConfig;
import com.datasift.client.managedsource.ManagedDataSourceType;
/**
* @author Courtney Robinson <courtney.robinson@datasift.com>
*/
public class Instagram extends BaseSource<Instagram> {
public Instagram(DataSiftConfig config) {
super(config, ManagedDataSourceType.INSTAGRAM);
}
/**
* set to true, if you want to receive like interactions.
*
* @return this
*/
public Instagram enableLikes(boolean enabled) {
return setParametersField("likes", enabled);
}
/**
* set to true, if you want to receive comment interactions.
*
* @return this
*/
public Instagram enableComments(boolean enabled) {
return setParametersField("comments", enabled);
}
/**
* Adds a managed instagram source by user
*
* @param userId the ID of the user
* @return this
*/
public Instagram byUser(String userId) {
addResource(Type.USER, userId, -1, -1, -1, false, null);
return this;
}
/**
* Adds a resource by tag
*
* @param tag the tag, e.g cat
* @param exactMatch true when a tag must be an exact match or false when the tag should match the instragram tag
* search behaviour
* @return this
*/
public Instagram byTag(String tag, boolean exactMatch) {
addResource(Type.TAG, tag, -1, -1, -1, exactMatch, null);
return this;
}
public Instagram byArea(float longitude, float lattitude) {
return byArea(longitude, lattitude);
}
/**
* Adds a resource a given area
*
* @param longitude the longitude value of the coordinates to use
* @param latitude the latitude value of the coordinate to use
* @param distance an optional distance which marks the radius around the given area,
* defaults to 1000 and must be between 1 and 5000 metres
* @return this
*/
public Instagram byArea(float longitude, float latitude, int distance) {
addResource(Type.AREA, null, longitude, latitude, distance, false, null);
return this;
}
public Instagram byLocation(float longitude, float latitude) {
return byLocation(longitude, latitude, 0);
}
/**
* Adds a resource a given location
*
* @param longitude the longitude value of the coordinates to use
* @param latitude the latitude value of the coordinate to use
* @param distance an optional distance which marks the radius around the given area,
* defaults to 1000 and must be between 1 and 5000 metres
* @return this
* @see #byArea(float, float, int)
*/
public Instagram byLocation(float longitude, float latitude, int distance) {
addResource(Type.LOCATION, null, longitude, latitude, distance, false, null);
return this;
}
/**
* The same as {@link #byLocation(float, float, int)} but instead of using coordinates a foursquare location ID
* is provided
*
* @param fourSquareLocation a valid foursquare location ID e.g. 5XfVJe
* @return this
*/
public Instagram byFoursquareLocation(String fourSquareLocation) {
addResource(Type.LOCATION, null, -1, -1, -1, false, fourSquareLocation);
return this;
}
/**
* Adds a resource that is filtered based on popularity
*
* @return this
*/
public Instagram byPopularity() {
addResource(Type.POPULAR, null, -1, -1, -1, false, null);
return this;
}
/**
* Adds a resource object to the request of the given type, which is always required
*
* @param type the type of resource, all other params are optional dependent upon what this value is
* @return this
*/
protected Instagram addResource(Type type, String value, float longitude, float lattitude, int distance,
boolean exactMatch, String fourSquareLocation) {
ResourceParams parameterSet = newResourceParams();
switch (type) {
case USER:
if (value == null) {
throw new IllegalArgumentException("If type is user then value is required");
}
parameterSet.set("type", "user");
parameterSet.set("value", value);
break;
case TAG:
if (value == null) {
throw new IllegalArgumentException("If type is user then value is required");
}
parameterSet.set("type", "tag");
parameterSet.set("value", value);
parameterSet.set("extact_match", exactMatch);
break;
case AREA:
case LOCATION:
if (value == null || distance > 5000) {
throw new IllegalArgumentException("If provided distance must be between 1 and 5000 metres or < 0" +
" to be ignored");
}
if (type == Type.LOCATION) {
parameterSet.set("type", "location");
if (fourSquareLocation != null) {
parameterSet.set("foursq", fourSquareLocation);
}
} else {
parameterSet.set("type", "area");
}
if (fourSquareLocation == null) {
parameterSet.set("lat", lattitude);
parameterSet.set("lng", longitude);
if (distance > 0) {
parameterSet.set("distance", lattitude);
}
}
break;
case POPULAR:
parameterSet.set("type", "popular");
break;
}
return this;
}
/**
* Adds an OAuth token to the managed source
*
* @param oAuthAccessToken an oauth2 token
* @param name a human friendly name for this auth token
* @param expires identity resource expiry date/time as a UTC timestamp, i.e. when the token expires
* @return this
*/
public Instagram addOAutToken(String oAuthAccessToken, long expires, String name) {
if (oAuthAccessToken == null || oAuthAccessToken.isEmpty()) {
throw new IllegalArgumentException("A valid OAuth and refresh token is required");
}
AuthParams parameterSet = newAuthParams(name, expires);
parameterSet.set("value", oAuthAccessToken);
return this;
}
public static enum Type {
USER, TAG, AREA, LOCATION, POPULAR
}
}
|
Addresses FTD-523 Removed Foursquare since Instagram dropped support since 20/04/16
|
src/main/java/com/datasift/client/managedsource/sources/Instagram.java
|
Addresses FTD-523 Removed Foursquare since Instagram dropped support since 20/04/16
|
|
Java
|
mit
|
72d1fc74ae8ea9e09438ed3a16cce5678a889737
| 0
|
Querz/NBT
|
package net.querz.nbt;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class Tag<T> implements Comparable<Tag<T>>, Cloneable {
/**
* The maximum depth of the NBT structure.
* */
public static final int MAX_DEPTH = 512;
private static final Map<String, String> ESCAPE_CHARACTERS;
static {
final Map<String, String> temp = new HashMap<>();
temp.put("\\", "\\\\\\\\");
temp.put("\n", "\\\\n");
temp.put("\t", "\\\\t");
temp.put("\r", "\\\\r");
temp.put("\"", "\\\\\"");
ESCAPE_CHARACTERS = Collections.unmodifiableMap(temp);
}
private static final Pattern ESCAPE_PATTERN = Pattern.compile("[\\\\\n\t\r\"]");
private static final Pattern NON_QUOTE_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-+]+");
private T value;
/**
* Initializes this Tag with a {@code null} value.
*/
public Tag() {
this(null);
}
/**
* Initializes this Tag with some value. If the value is {@code null}, it will call
* this Tag's implementation of {@link Tag#getEmptyValue()} to set as the default value.
* @param value The value to be set for this Tag.
* */
public Tag(T value) {
//the value of a tag can never be null
this.value = value == null ? getEmptyValue() : value;
}
/**
* @return This Tag's ID, usually used for serialization and deserialization.
* */
public byte getID() {
return TagFactory.idFromClass(getClass());
}
/**
* @return A default value for this Tag.
* */
protected abstract T getEmptyValue();
/**
* @return The value of this Tag.
* */
protected T getValue() {
return value;
}
/**
* Sets the value for this Tag directly.
* @param value The value to be set.
* */
protected void setValue(T value) {
this.value = value;
}
/**
* Calls {@link Tag#serialize(DataOutputStream, String, int)} with an empty name.
* @see Tag#serialize(DataOutputStream, String, int)
* @param dos The DataOutputStream to write to
* @param depth The current depth of the structure
* @throws IOException If something went wrong during serialization
* */
public final void serialize(DataOutputStream dos, int depth) throws IOException {
serialize(dos, "", depth);
}
/**
* Serializes this Tag starting at the gives depth.
* @param dos The DataOutputStream to write to.
* @param name The name of this Tag, if this is the root Tag.
* @param depth The current depth of the structure.
* @throws IOException If something went wrong during serialization.
* @exception NullPointerException If {@code dos} or {@code name} is {@code null}.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public final void serialize(DataOutputStream dos, String name, int depth) throws IOException {
dos.writeByte(getID());
if (getID() != 0) {
dos.writeUTF(name);
}
serializeValue(dos, depth);
}
/**
* Deserializes this Tag starting at the given depth.
* The name of the root Tag is ignored.
* @param dis The DataInputStream to read from.
* @param depth The current depth of the structure.
* @throws IOException If something went wrong during deserialization.
* @exception NullPointerException If {@code dis} is {@code null}.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* @return The deserialized NBT structure.
* */
public static Tag<?> deserialize(DataInputStream dis, int depth) throws IOException {
int id = dis.readByte() & 0xFF;
Tag<?> tag = TagFactory.fromID(id);
if (id != 0) {
dis.readUTF();
tag.deserializeValue(dis, depth);
}
return tag;
}
/**
* Serializes only the value of this Tag.
* @param dos The DataOutputStream to write to.
* @param depth The current depth of the structure.
* @throws IOException If something went wrong during serialization.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public abstract void serializeValue(DataOutputStream dos, int depth) throws IOException;
/**
* Deserializes only the value of this Tag.
* @param dis The DataInputStream to read from.
* @param depth The current depth of the structure.
* @throws IOException If something went wrong during deserialization.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public abstract void deserializeValue(DataInputStream dis, int depth) throws IOException;
/**
* Calls {@link Tag#toString(int)} with an initial depth of {@code 0}.
* @see Tag#toString(int)
* */
@Override
public String toString() {
return toString(0);
}
/**
* Creates a string representation of this Tag in a valid JSON format.
* @param depth The current depth of the structure.
* @return The string representation of this Tag.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public String toString(int depth) {
return "{\"type\":\""+ getClass().getSimpleName() + "\"," +
"\"value\":" + valueToString(depth) + "}";
}
/**
* Returns a JSON representation of the value of this Tag.
* @param depth The current depth of the structure.
* @return The string representation of the value of this Tag.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public abstract String valueToString(int depth);
/**
* Calls {@link Tag#toTagString(int)} with an initial depth of {@code 0}.
* @see Tag#toTagString(int)
* @return The JSON-like string representation of this Tag.
* */
public String toTagString() {
return toTagString(0);
}
/**
* Returns a JSON-like representation of the value of this Tag, usually used for Minecraft commands.
* @param depth The current depth of the structure.
* @return The JSON-like string representation of this Tag.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public String toTagString(int depth) {
return valueToTagString(depth);
}
/**
* Returns a JSON-like representation of the value of this Tag.
* @param depth The current depth of the structure.
* @return The JSON-like string representation of the value of this Tag.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public abstract String valueToTagString(int depth);
/**
* Returns whether this Tag and some other Tag are equal.
* They are equal if {@code other} is not {@code null} and they are of the same class.
* Custom Tag implementations should overwrite this but check the result
* of this {@code super}-method while comparing.
* @param other The Tag to compare to.
* @return {@code true} if they are equal based on the conditions mentioned above.
* */
@Override
public boolean equals(Object other) {
return other != null && getClass() == other.getClass();
}
/**
* Calculates the hash code of this Tag. Tags which are equal according to {@link Tag#equals(Object)}
* must return an equal hash code.
* @return The hash code of this Tag.
* */
@Override
public int hashCode() {
return value.hashCode();
}
/**
* Creates a clone of this Tag.
* @return A clone of this Tag.
* */
@SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException")
public abstract Tag<T> clone();
/**
* A utility method to check if some value is {@code null}.
* @param <V> Any type that should be checked for being {@code null}
* @param v The value to check.
* @return {@code v}, if it's not {@code null}.
* @exception NullPointerException If {@code v} is {@code null}.
* */
protected <V> V checkNull(V v) {
if (v == null) {
throw new NullPointerException(getClass().getSimpleName() + " does not allow setting null");
}
return v;
}
/**
* Increments {@code depth} by {@code 1}.
* @param depth The value to increment.
* @return The incremented value.
* @exception MaxDepthReachedException If {@code depth} is {@code >=} {@link Tag#MAX_DEPTH}.
* @exception IllegalArgumentException If {@code depth} is {@code <} {@code 0}
* */
protected int incrementDepth(int depth) {
if (depth >= MAX_DEPTH) {
throw new MaxDepthReachedException("reached maximum depth (" + Tag.MAX_DEPTH + ") of NBT structure");
}
if (depth < 0) {
throw new IllegalArgumentException("initial depth cannot be negative");
}
return ++depth;
}
/**
* Escapes a string to fit into a JSON-like string representation for Minecraft
* or to create the JSON string representation of a Tag returned from {@link Tag#toString()}
* @param s The string to be escaped.
* @param lenient {@code true} if it should force double quotes ({@code "}) at the start and
* the end of the string.
* @return The escaped string.
* */
protected static String escapeString(String s, boolean lenient) {
StringBuffer sb = new StringBuffer();
Matcher m = ESCAPE_PATTERN.matcher(s);
while (m.find()) {
m.appendReplacement(sb, ESCAPE_CHARACTERS.get(m.group()));
}
m.appendTail(sb);
m = NON_QUOTE_PATTERN.matcher(s);
if (!lenient || !m.matches()) {
sb.insert(0, "\"").append("\"");
}
return sb.toString();
}
}
|
src/main/java/net/querz/nbt/Tag.java
|
package net.querz.nbt;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class Tag<T> implements Comparable<Tag<T>>, Cloneable {
/**
* The maximum depth of the NBT structure.
* */
public static final int MAX_DEPTH = 512;
private static final Map<String, String> ESCAPE_CHARACTERS = new HashMap<String, String>() {{
put("\\", "\\\\\\\\");
put("\n", "\\\\n");
put("\t", "\\\\t");
put("\r", "\\\\r");
put("\"", "\\\\\"");
}};
private static final Pattern ESCAPE_PATTERN = Pattern.compile("[\\\\\n\t\r\"]");
private static final Pattern NON_QUOTE_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-+]+");
private T value;
/**
* Initializes this Tag with a {@code null} value.
*/
public Tag() {
this(null);
}
/**
* Initializes this Tag with some value. If the value is {@code null}, it will call
* this Tag's implementation of {@link Tag#getEmptyValue()} to set as the default value.
* @param value The value to be set for this Tag.
* */
public Tag(T value) {
//the value of a tag can never be null
this.value = value == null ? getEmptyValue() : value;
}
/**
* @return This Tag's ID, usually used for serialization and deserialization.
* */
public byte getID() {
return TagFactory.idFromClass(getClass());
}
/**
* @return A default value for this Tag.
* */
protected abstract T getEmptyValue();
/**
* @return The value of this Tag.
* */
protected T getValue() {
return value;
}
/**
* Sets the value for this Tag directly.
* @param value The value to be set.
* */
protected void setValue(T value) {
this.value = value;
}
/**
* Calls {@link Tag#serialize(DataOutputStream, String, int)} with an empty name.
* @see Tag#serialize(DataOutputStream, String, int)
* @param dos The DataOutputStream to write to
* @param depth The current depth of the structure
* @throws IOException If something went wrong during serialization
* */
public final void serialize(DataOutputStream dos, int depth) throws IOException {
serialize(dos, "", depth);
}
/**
* Serializes this Tag starting at the gives depth.
* @param dos The DataOutputStream to write to.
* @param name The name of this Tag, if this is the root Tag.
* @param depth The current depth of the structure.
* @throws IOException If something went wrong during serialization.
* @exception NullPointerException If {@code dos} or {@code name} is {@code null}.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public final void serialize(DataOutputStream dos, String name, int depth) throws IOException {
dos.writeByte(getID());
if (getID() != 0) {
dos.writeUTF(name);
}
serializeValue(dos, depth);
}
/**
* Deserializes this Tag starting at the given depth.
* The name of the root Tag is ignored.
* @param dis The DataInputStream to read from.
* @param depth The current depth of the structure.
* @throws IOException If something went wrong during deserialization.
* @exception NullPointerException If {@code dis} is {@code null}.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* @return The deserialized NBT structure.
* */
public static Tag<?> deserialize(DataInputStream dis, int depth) throws IOException {
int id = dis.readByte() & 0xFF;
Tag<?> tag = TagFactory.fromID(id);
if (id != 0) {
dis.readUTF();
tag.deserializeValue(dis, depth);
}
return tag;
}
/**
* Serializes only the value of this Tag.
* @param dos The DataOutputStream to write to.
* @param depth The current depth of the structure.
* @throws IOException If something went wrong during serialization.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public abstract void serializeValue(DataOutputStream dos, int depth) throws IOException;
/**
* Deserializes only the value of this Tag.
* @param dis The DataInputStream to read from.
* @param depth The current depth of the structure.
* @throws IOException If something went wrong during deserialization.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public abstract void deserializeValue(DataInputStream dis, int depth) throws IOException;
/**
* Calls {@link Tag#toString(int)} with an initial depth of {@code 0}.
* @see Tag#toString(int)
* */
@Override
public String toString() {
return toString(0);
}
/**
* Creates a string representation of this Tag in a valid JSON format.
* @param depth The current depth of the structure.
* @return The string representation of this Tag.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public String toString(int depth) {
return "{\"type\":\""+ getClass().getSimpleName() + "\"," +
"\"value\":" + valueToString(depth) + "}";
}
/**
* Returns a JSON representation of the value of this Tag.
* @param depth The current depth of the structure.
* @return The string representation of the value of this Tag.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public abstract String valueToString(int depth);
/**
* Calls {@link Tag#toTagString(int)} with an initial depth of {@code 0}.
* @see Tag#toTagString(int)
* @return The JSON-like string representation of this Tag.
* */
public String toTagString() {
return toTagString(0);
}
/**
* Returns a JSON-like representation of the value of this Tag, usually used for Minecraft commands.
* @param depth The current depth of the structure.
* @return The JSON-like string representation of this Tag.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public String toTagString(int depth) {
return valueToTagString(depth);
}
/**
* Returns a JSON-like representation of the value of this Tag.
* @param depth The current depth of the structure.
* @return The JSON-like string representation of the value of this Tag.
* @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#MAX_DEPTH}.
* */
public abstract String valueToTagString(int depth);
/**
* Returns whether this Tag and some other Tag are equal.
* They are equal if {@code other} is not {@code null} and they are of the same class.
* Custom Tag implementations should overwrite this but check the result
* of this {@code super}-method while comparing.
* @param other The Tag to compare to.
* @return {@code true} if they are equal based on the conditions mentioned above.
* */
@Override
public boolean equals(Object other) {
return other != null && getClass() == other.getClass();
}
/**
* Calculates the hash code of this Tag. Tags which are equal according to {@link Tag#equals(Object)}
* must return an equal hash code.
* @return The hash code of this Tag.
* */
@Override
public int hashCode() {
return value.hashCode();
}
/**
* Creates a clone of this Tag.
* @return A clone of this Tag.
* */
@SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException")
public abstract Tag<T> clone();
/**
* A utility method to check if some value is {@code null}.
* @param <V> Any type that should be checked for being {@code null}
* @param v The value to check.
* @return {@code v}, if it's not {@code null}.
* @exception NullPointerException If {@code v} is {@code null}.
* */
protected <V> V checkNull(V v) {
if (v == null) {
throw new NullPointerException(getClass().getSimpleName() + " does not allow setting null");
}
return v;
}
/**
* Increments {@code depth} by {@code 1}.
* @param depth The value to increment.
* @return The incremented value.
* @exception MaxDepthReachedException If {@code depth} is {@code >=} {@link Tag#MAX_DEPTH}.
* @exception IllegalArgumentException If {@code depth} is {@code <} {@code 0}
* */
protected int incrementDepth(int depth) {
if (depth >= MAX_DEPTH) {
throw new MaxDepthReachedException("reached maximum depth (" + Tag.MAX_DEPTH + ") of NBT structure");
}
if (depth < 0) {
throw new IllegalArgumentException("initial depth cannot be negative");
}
return ++depth;
}
/**
* Escapes a string to fit into a JSON-like string representation for Minecraft
* or to create the JSON string representation of a Tag returned from {@link Tag#toString()}
* @param s The string to be escaped.
* @param lenient {@code true} if it should force double quotes ({@code "}) at the start and
* the end of the string.
* @return The escaped string.
* */
protected static String escapeString(String s, boolean lenient) {
StringBuffer sb = new StringBuffer();
Matcher m = ESCAPE_PATTERN.matcher(s);
while (m.find()) {
m.appendReplacement(sb, ESCAPE_CHARACTERS.get(m.group()));
}
m.appendTail(sb);
m = NON_QUOTE_PATTERN.matcher(s);
if (!lenient || !m.matches()) {
sb.insert(0, "\"").append("\"");
}
return sb.toString();
}
}
|
Replaced anonymous Map subclass for constant
|
src/main/java/net/querz/nbt/Tag.java
|
Replaced anonymous Map subclass for constant
|
|
Java
|
mit
|
15a666b08f6ee1e9fe55f25a7b5190ea55a6e868
| 0
|
ReneMuetti/RFTools,McJty/RFTools,Adaptivity/RFTools,Elecs-Mods/RFTools
|
package com.mcjty.rftools.blocks.dimlets;
import com.mcjty.container.InventoryHelper;
import com.mcjty.entity.GenericTileEntity;
import com.mcjty.rftools.dimension.DimensionDescriptor;
import com.mcjty.rftools.dimension.RfToolsDimensionManager;
import com.mcjty.rftools.items.ModItems;
import com.mcjty.rftools.items.dimlets.DimletEntry;
import com.mcjty.rftools.items.dimlets.DimletType;
import com.mcjty.rftools.items.dimlets.KnownDimletConfiguration;
import com.mcjty.rftools.network.Argument;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagIntArray;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.EnumChatFormatting;
import net.minecraftforge.common.util.Constants;
import java.util.*;
public class DimensionEnscriberTileEntity extends GenericTileEntity implements ISidedInventory {
public static final String CMD_STORE = "store";
public static final String CMD_EXTRACT = "extract";
public static final String CMD_SETNAME = "setName";
private boolean tabSlotHasChanged = false;
private InventoryHelper inventoryHelper = new InventoryHelper(this, DimensionEnscriberContainer.factory, DimensionEnscriberContainer.SIZE_DIMLETS+1);
@Override
public int[] getAccessibleSlotsFromSide(int side) {
return DimensionEnscriberContainer.factory.getAccessibleSlots();
}
@Override
public boolean canInsertItem(int index, ItemStack item, int side) {
return DimensionEnscriberContainer.factory.isInputSlot(index);
}
@Override
public boolean canExtractItem(int index, ItemStack item, int side) {
return DimensionEnscriberContainer.factory.isOutputSlot(index);
}
@Override
public int getSizeInventory() {
return inventoryHelper.getStacks().length;
}
@Override
public ItemStack getStackInSlot(int index) {
return inventoryHelper.getStacks()[index];
}
@Override
public ItemStack decrStackSize(int index, int amount) {
return inventoryHelper.decrStackSize(index, amount);
}
@Override
public ItemStack getStackInSlotOnClosing(int index) {
return null;
}
@Override
public void setInventorySlotContents(int index, ItemStack stack) {
inventoryHelper.setInventorySlotContents(getInventoryStackLimit(), index, stack);
}
@Override
public String getInventoryName() {
return "Enscriber Inventory";
}
@Override
public boolean hasCustomInventoryName() {
return false;
}
@Override
public int getInventoryStackLimit() {
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
return true;
}
@Override
public void openInventory() {
}
@Override
public void closeInventory() {
}
@Override
public boolean isItemValidForSlot(int index, ItemStack stack) {
return true;
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
super.readFromNBT(tagCompound);
}
@Override
public void readRestorableFromNBT(NBTTagCompound tagCompound) {
super.readRestorableFromNBT(tagCompound);
readBufferFromNBT(tagCompound);
}
private void readBufferFromNBT(NBTTagCompound tagCompound) {
NBTTagList bufferTagList = tagCompound.getTagList("Items", Constants.NBT.TAG_COMPOUND);
for (int i = 0 ; i < bufferTagList.tagCount() ; i++) {
NBTTagCompound nbtTagCompound = bufferTagList.getCompoundTagAt(i);
inventoryHelper.getStacks()[i] = ItemStack.loadItemStackFromNBT(nbtTagCompound);
}
}
@Override
public void writeToNBT(NBTTagCompound tagCompound) {
super.writeToNBT(tagCompound);
}
@Override
public void writeRestorableToNBT(NBTTagCompound tagCompound) {
super.writeRestorableToNBT(tagCompound);
writeBufferToNBT(tagCompound);
}
private void writeBufferToNBT(NBTTagCompound tagCompound) {
NBTTagList bufferTagList = new NBTTagList();
for (int i = 0 ; i < inventoryHelper.getStacks().length ; i++) {
ItemStack stack = inventoryHelper.getStacks()[i];
NBTTagCompound nbtTagCompound = new NBTTagCompound();
if (stack != null) {
stack.writeToNBT(nbtTagCompound);
}
bufferTagList.appendTag(nbtTagCompound);
}
tagCompound.setTag("Items", bufferTagList);
}
private void storeDimlets() {
DimensionDescriptor descriptor = convertToDimensionDescriptor();
ItemStack realizedTab = createRealizedTab(descriptor);
inventoryHelper.getStacks()[DimensionEnscriberContainer.SLOT_TAB] = realizedTab;
markDirty();
}
/**
* Create a realized dimension tab by taking a map of ids per type and storing
* that in the NBT of the realized dimension tab.
* @param dimletsByType
* @return
*/
private ItemStack createRealizedTab(DimensionDescriptor descriptor) {
ItemStack realizedTab = new ItemStack(ModItems.realizedDimensionTab, 1, 0);
NBTTagCompound tagCompound = new NBTTagCompound();
descriptor.writeToNBT(tagCompound);
// Check if the dimension already exists and if so set the progress to 100%.
RfToolsDimensionManager manager = RfToolsDimensionManager.getDimensionManager(worldObj);
Integer id = manager.getDimensionID(descriptor);
if (id != null) {
// The dimension was already created.
tagCompound.setInteger("ticksLeft", 0);
tagCompound.setInteger("id", id);
}
realizedTab.setTagCompound(tagCompound);
return realizedTab;
}
/**
* Convert the dimlets in the inventory to a dimension descriptor.
* @return
*/
private DimensionDescriptor convertToDimensionDescriptor() {
Map<DimletType,List<Integer>> dimletsByType = new HashMap<DimletType, List<Integer>>();
for (DimletType type : DimletType.values()) {
dimletsByType.put(type, new ArrayList<Integer>());
}
for (int i = 0 ; i < DimensionEnscriberContainer.SIZE_DIMLETS ; i++) {
ItemStack stack = inventoryHelper.getStacks()[i + DimensionEnscriberContainer.SLOT_DIMLETS];
if (stack != null && stack.stackSize > 0) {
int dimletId = stack.getItemDamage();
DimletEntry entry = KnownDimletConfiguration.idToDimlet.get(dimletId);
dimletsByType.get(entry.getType()).add(dimletId);
}
inventoryHelper.getStacks()[i + DimensionEnscriberContainer.SLOT_DIMLETS] = null;
}
return new DimensionDescriptor(dimletsByType);
}
private void extractDimlets() {
ItemStack realizedTab = inventoryHelper.getStacks()[DimensionEnscriberContainer.SLOT_TAB];
NBTTagCompound tagCompound = realizedTab.getTagCompound();
if (tagCompound != null) {
int idx = DimensionEnscriberContainer.SLOT_DIMLETS;
String descriptionString = tagCompound.getString("descriptionString");
if (!descriptionString.trim().isEmpty()) {
String[] opcodes = descriptionString.split(",");
for (String oc : opcodes) {
Integer id = Integer.parseInt(oc.substring(1));
inventoryHelper.getStacks()[idx++] = new ItemStack(ModItems.knownDimlet, 1, id);
}
}
}
inventoryHelper.getStacks()[DimensionEnscriberContainer.SLOT_TAB] = new ItemStack(ModItems.emptyDimensionTab);
markDirty();
}
private void setName(String name) {
ItemStack realizedTab = inventoryHelper.getStacks()[DimensionEnscriberContainer.SLOT_TAB];
if (realizedTab != null) {
NBTTagCompound tagCompound = realizedTab.getTagCompound();
if (tagCompound == null) {
tagCompound = new NBTTagCompound();
realizedTab.setTagCompound(tagCompound);
}
tagCompound.setString("name", name);
markDirty();
}
}
@Override
public void onSlotChanged(int index, ItemStack stack) {
if (worldObj.isRemote && index == DimensionEnscriberContainer.SLOT_TAB) {
tabSlotHasChanged = true;
}
}
public boolean hasTabSlotChangedAndClear() {
boolean rc = tabSlotHasChanged;
tabSlotHasChanged = false;
return rc;
}
@Override
public boolean execute(String command, Map<String, Argument> args) {
boolean rc = super.execute(command, args);
if (rc) {
return true;
}
if (CMD_STORE.equals(command)) {
storeDimlets();
setName(args.get("name").getString());
return true;
} else if (CMD_EXTRACT.equals(command)) {
extractDimlets();
return true;
} else if (CMD_SETNAME.equals(command)) {
setName(args.get("name").getString());
return true;
}
return false;
}
}
|
src/main/java/com/mcjty/rftools/blocks/dimlets/DimensionEnscriberTileEntity.java
|
package com.mcjty.rftools.blocks.dimlets;
import com.mcjty.container.InventoryHelper;
import com.mcjty.entity.GenericTileEntity;
import com.mcjty.rftools.dimension.DimensionDescriptor;
import com.mcjty.rftools.dimension.RfToolsDimensionManager;
import com.mcjty.rftools.items.ModItems;
import com.mcjty.rftools.items.dimlets.DimletEntry;
import com.mcjty.rftools.items.dimlets.DimletType;
import com.mcjty.rftools.items.dimlets.KnownDimletConfiguration;
import com.mcjty.rftools.network.Argument;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagIntArray;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.EnumChatFormatting;
import net.minecraftforge.common.util.Constants;
import java.util.*;
public class DimensionEnscriberTileEntity extends GenericTileEntity implements ISidedInventory {
public static final String CMD_STORE = "store";
public static final String CMD_EXTRACT = "extract";
public static final String CMD_SETNAME = "setName";
private boolean tabSlotHasChanged = false;
private InventoryHelper inventoryHelper = new InventoryHelper(this, DimensionEnscriberContainer.factory, DimensionEnscriberContainer.SIZE_DIMLETS+1);
@Override
public int[] getAccessibleSlotsFromSide(int side) {
return DimensionEnscriberContainer.factory.getAccessibleSlots();
}
@Override
public boolean canInsertItem(int index, ItemStack item, int side) {
return DimensionEnscriberContainer.factory.isInputSlot(index);
}
@Override
public boolean canExtractItem(int index, ItemStack item, int side) {
return DimensionEnscriberContainer.factory.isOutputSlot(index);
}
@Override
public int getSizeInventory() {
return inventoryHelper.getStacks().length;
}
@Override
public ItemStack getStackInSlot(int index) {
return inventoryHelper.getStacks()[index];
}
@Override
public ItemStack decrStackSize(int index, int amount) {
return inventoryHelper.decrStackSize(index, amount);
}
@Override
public ItemStack getStackInSlotOnClosing(int index) {
return null;
}
@Override
public void setInventorySlotContents(int index, ItemStack stack) {
inventoryHelper.setInventorySlotContents(getInventoryStackLimit(), index, stack);
}
@Override
public String getInventoryName() {
return "Enscriber Inventory";
}
@Override
public boolean hasCustomInventoryName() {
return false;
}
@Override
public int getInventoryStackLimit() {
return 1;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
return true;
}
@Override
public void openInventory() {
}
@Override
public void closeInventory() {
}
@Override
public boolean isItemValidForSlot(int index, ItemStack stack) {
return true;
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
super.readFromNBT(tagCompound);
}
@Override
public void readRestorableFromNBT(NBTTagCompound tagCompound) {
super.readRestorableFromNBT(tagCompound);
readBufferFromNBT(tagCompound);
}
private void readBufferFromNBT(NBTTagCompound tagCompound) {
NBTTagList bufferTagList = tagCompound.getTagList("Items", Constants.NBT.TAG_COMPOUND);
for (int i = 0 ; i < bufferTagList.tagCount() ; i++) {
NBTTagCompound nbtTagCompound = bufferTagList.getCompoundTagAt(i);
inventoryHelper.getStacks()[i] = ItemStack.loadItemStackFromNBT(nbtTagCompound);
}
}
@Override
public void writeToNBT(NBTTagCompound tagCompound) {
super.writeToNBT(tagCompound);
}
@Override
public void writeRestorableToNBT(NBTTagCompound tagCompound) {
super.writeRestorableToNBT(tagCompound);
writeBufferToNBT(tagCompound);
}
private void writeBufferToNBT(NBTTagCompound tagCompound) {
NBTTagList bufferTagList = new NBTTagList();
for (int i = 0 ; i < inventoryHelper.getStacks().length ; i++) {
ItemStack stack = inventoryHelper.getStacks()[i];
NBTTagCompound nbtTagCompound = new NBTTagCompound();
if (stack != null) {
stack.writeToNBT(nbtTagCompound);
}
bufferTagList.appendTag(nbtTagCompound);
}
tagCompound.setTag("Items", bufferTagList);
}
private void storeDimlets() {
DimensionDescriptor descriptor = convertToDimensionDescriptor();
ItemStack realizedTab = createRealizedTab(descriptor);
inventoryHelper.getStacks()[DimensionEnscriberContainer.SLOT_TAB] = realizedTab;
markDirty();
}
/**
* Create a realized dimension tab by taking a map of ids per type and storing
* that in the NBT of the realized dimension tab.
* @param dimletsByType
* @return
*/
private ItemStack createRealizedTab(DimensionDescriptor descriptor) {
ItemStack realizedTab = new ItemStack(ModItems.realizedDimensionTab, 1, 0);
NBTTagCompound tagCompound = new NBTTagCompound();
descriptor.writeToNBT(tagCompound);
// Check if the dimension already exists and if so set the progress to 100%.
RfToolsDimensionManager manager = RfToolsDimensionManager.getDimensionManager(worldObj);
Integer id = manager.getDimensionID(descriptor);
if (id != null) {
// The dimension was already created.
tagCompound.setInteger("ticksLeft", 0);
tagCompound.setInteger("id", id);
}
realizedTab.setTagCompound(tagCompound);
return realizedTab;
}
/**
* Convert the dimlets in the inventory to a dimension descriptor.
* @return
*/
private DimensionDescriptor convertToDimensionDescriptor() {
Map<DimletType,List<Integer>> dimletsByType = new HashMap<DimletType, List<Integer>>();
for (DimletType type : DimletType.values()) {
dimletsByType.put(type, new ArrayList<Integer>());
}
for (int i = 0 ; i < DimensionEnscriberContainer.SIZE_DIMLETS ; i++) {
ItemStack stack = inventoryHelper.getStacks()[i + DimensionEnscriberContainer.SLOT_DIMLETS];
if (stack != null && stack.stackSize > 0) {
int dimletId = stack.getItemDamage();
DimletEntry entry = KnownDimletConfiguration.idToDimlet.get(dimletId);
dimletsByType.get(entry.getType()).add(dimletId);
}
inventoryHelper.getStacks()[i + DimensionEnscriberContainer.SLOT_DIMLETS] = null;
}
return new DimensionDescriptor(dimletsByType);
}
private void extractDimlets() {
ItemStack realizedTab = inventoryHelper.getStacks()[DimensionEnscriberContainer.SLOT_TAB];
NBTTagCompound tagCompound = realizedTab.getTagCompound();
if (tagCompound != null) {
int idx = DimensionEnscriberContainer.SLOT_DIMLETS;
String descriptionString = tagCompound.getString("descriptionString");
String[] opcodes = descriptionString.split(",");
for (String oc : opcodes) {
Integer id = Integer.parseInt(oc.substring(1));
inventoryHelper.getStacks()[idx++] = new ItemStack(ModItems.knownDimlet, 1, id);
}
}
inventoryHelper.getStacks()[DimensionEnscriberContainer.SLOT_TAB] = new ItemStack(ModItems.emptyDimensionTab);
markDirty();
}
private void setName(String name) {
ItemStack realizedTab = inventoryHelper.getStacks()[DimensionEnscriberContainer.SLOT_TAB];
if (realizedTab != null) {
NBTTagCompound tagCompound = realizedTab.getTagCompound();
if (tagCompound == null) {
tagCompound = new NBTTagCompound();
realizedTab.setTagCompound(tagCompound);
}
tagCompound.setString("name", name);
markDirty();
}
}
@Override
public void onSlotChanged(int index, ItemStack stack) {
if (worldObj.isRemote && index == DimensionEnscriberContainer.SLOT_TAB) {
tabSlotHasChanged = true;
}
}
public boolean hasTabSlotChangedAndClear() {
boolean rc = tabSlotHasChanged;
tabSlotHasChanged = false;
return rc;
}
@Override
public boolean execute(String command, Map<String, Argument> args) {
boolean rc = super.execute(command, args);
if (rc) {
return true;
}
if (CMD_STORE.equals(command)) {
storeDimlets();
setName(args.get("name").getString());
return true;
} else if (CMD_EXTRACT.equals(command)) {
extractDimlets();
return true;
} else if (CMD_SETNAME.equals(command)) {
setName(args.get("name").getString());
return true;
}
return false;
}
}
|
Fixed a crash when trying to extract an empty realized item tab
|
src/main/java/com/mcjty/rftools/blocks/dimlets/DimensionEnscriberTileEntity.java
|
Fixed a crash when trying to extract an empty realized item tab
|
|
Java
|
mit
|
261b77845ec8c7d41391b8fdaf68a598a86220b3
| 0
|
jenkinsci/plugin-compat-tester,jenkinsci/plugin-compat-tester
|
package org.jenkins.tools.test.maven;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import org.jenkins.tools.test.exception.PomExecutionException;
import org.jenkins.tools.test.util.ExecutedTestNamesSolver;
/**
* Runs external Maven executable.
*/
public class ExternalMavenRunner implements MavenRunner {
private static final String DISABLE_DOWNLOAD_LOGS = "-ntp";
@CheckForNull
private File mvn;
private Set<String> executedTests;
/**
* Constructor.
*
* @param mvn Path to Maven. If {@code null}, a default Maven executable from
* {@code PATH} will be used
*/
public ExternalMavenRunner(@CheckForNull File mvn) {
this.mvn = mvn;
this.executedTests = new HashSet<>();
}
public Set<String> getExecutedTests() {
return Collections.unmodifiableSet(executedTests);
}
@Override
public void run(Config config, File baseDirectory, File buildLogFile, String... goals)
throws PomExecutionException {
List<String> cmd = new ArrayList<>();
cmd.add(mvn != null ? mvn.getAbsolutePath() : "mvn");
cmd.add("--show-version");
cmd.add("--batch-mode");
cmd.add(DISABLE_DOWNLOAD_LOGS);
if (config.userSettingsFile != null) {
cmd.add("--settings=" + config.userSettingsFile);
}
for (Map.Entry<String, String> entry : config.userProperties.entrySet()) {
cmd.add("--define=" + entry);
}
cmd.addAll(Arrays.asList(goals));
System.out.println("running " + cmd + " in " + baseDirectory + " >> " + buildLogFile);
try {
Process p = new ProcessBuilder(cmd).directory(baseDirectory).redirectErrorStream(true).start();
List<String> succeededPluginArtifactIds = new ArrayList<>();
try (InputStream is = p.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()));
FileOutputStream os = new FileOutputStream(buildLogFile, true);
PrintWriter w = new PrintWriter(new OutputStreamWriter(os, Charset.defaultCharset()))) {
String completed = null;
Pattern pattern = Pattern.compile("\\[INFO\\] --- (.+):.+:.+ [(].+[)] @ .+ ---");
String line;
boolean testPhase = false;
while ((line = r.readLine()) != null) {
System.out.println(line);
w.println(line);
if(line.contains("T E S T S")) {
testPhase = true;
}
Matcher m = pattern.matcher(line);
if (m.matches()) {
if (completed != null) {
succeededPluginArtifactIds.add(completed);
}
completed = m.group(1);
} else if (line.equals("[INFO] BUILD SUCCESS") && completed != null) {
succeededPluginArtifactIds.add(completed);
} else if (testPhase && line.startsWith("[INFO] Running") && !line.contains("InjectedTest")) {
this.executedTests.add(line.split("Running")[1].trim());
}
}
w.flush();
System.out.println("succeeded artifactIds: " + succeededPluginArtifactIds);
System.out.println("executed classname tests: " + getExecutedTests());
}
if (p.waitFor() != 0) {
throw new PomExecutionException(cmd + " failed in " + baseDirectory, succeededPluginArtifactIds,
/* TODO */Collections.emptyList(), Collections.emptyList(),
new ExecutedTestNamesSolver().solve(getTypes(config), getExecutedTests(), baseDirectory));
}
} catch (PomExecutionException x) {
x.printStackTrace();
throw x;
} catch (Exception x) {
x.printStackTrace();
throw new PomExecutionException(x);
}
}
private Set<String> getTypes(Config config) {
Set<String> result = new HashSet<>();
if (config == null || config.userProperties == null || !config.userProperties.containsKey("types")) {
result.add("surefire");
return result;
}
String types = config.userProperties.get("types");
for (String type : types.split(",")) {
result.add(type);
}
return result;
}
}
|
plugins-compat-tester/src/main/java/org/jenkins/tools/test/maven/ExternalMavenRunner.java
|
package org.jenkins.tools.test.maven;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import org.jenkins.tools.test.exception.PomExecutionException;
import org.jenkins.tools.test.util.ExecutedTestNamesSolver;
/**
* Runs external Maven executable.
*/
public class ExternalMavenRunner implements MavenRunner {
private static final String DISABLE_DOWNLOAD_LOGS = "-ntp;
@CheckForNull
private File mvn;
private Set<String> executedTests;
/**
* Constructor.
*
* @param mvn Path to Maven. If {@code null}, a default Maven executable from
* {@code PATH} will be used
*/
public ExternalMavenRunner(@CheckForNull File mvn) {
this.mvn = mvn;
this.executedTests = new HashSet<>();
}
public Set<String> getExecutedTests() {
return Collections.unmodifiableSet(executedTests);
}
@Override
public void run(Config config, File baseDirectory, File buildLogFile, String... goals)
throws PomExecutionException {
List<String> cmd = new ArrayList<>();
cmd.add(mvn != null ? mvn.getAbsolutePath() : "mvn");
cmd.add("--show-version");
cmd.add("--batch-mode");
cmd.add(DISABLE_DOWNLOAD_LOGS);
if (config.userSettingsFile != null) {
cmd.add("--settings=" + config.userSettingsFile);
}
for (Map.Entry<String, String> entry : config.userProperties.entrySet()) {
cmd.add("--define=" + entry);
}
cmd.addAll(Arrays.asList(goals));
System.out.println("running " + cmd + " in " + baseDirectory + " >> " + buildLogFile);
try {
Process p = new ProcessBuilder(cmd).directory(baseDirectory).redirectErrorStream(true).start();
List<String> succeededPluginArtifactIds = new ArrayList<>();
try (InputStream is = p.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()));
FileOutputStream os = new FileOutputStream(buildLogFile, true);
PrintWriter w = new PrintWriter(new OutputStreamWriter(os, Charset.defaultCharset()))) {
String completed = null;
Pattern pattern = Pattern.compile("\\[INFO\\] --- (.+):.+:.+ [(].+[)] @ .+ ---");
String line;
boolean testPhase = false;
while ((line = r.readLine()) != null) {
System.out.println(line);
w.println(line);
if(line.contains("T E S T S")) {
testPhase = true;
}
Matcher m = pattern.matcher(line);
if (m.matches()) {
if (completed != null) {
succeededPluginArtifactIds.add(completed);
}
completed = m.group(1);
} else if (line.equals("[INFO] BUILD SUCCESS") && completed != null) {
succeededPluginArtifactIds.add(completed);
} else if (testPhase && line.startsWith("[INFO] Running") && !line.contains("InjectedTest")) {
this.executedTests.add(line.split("Running")[1].trim());
}
}
w.flush();
System.out.println("succeeded artifactIds: " + succeededPluginArtifactIds);
System.out.println("executed classname tests: " + getExecutedTests());
}
if (p.waitFor() != 0) {
throw new PomExecutionException(cmd + " failed in " + baseDirectory, succeededPluginArtifactIds,
/* TODO */Collections.emptyList(), Collections.emptyList(),
new ExecutedTestNamesSolver().solve(getTypes(config), getExecutedTests(), baseDirectory));
}
} catch (PomExecutionException x) {
x.printStackTrace();
throw x;
} catch (Exception x) {
x.printStackTrace();
throw new PomExecutionException(x);
}
}
private Set<String> getTypes(Config config) {
Set<String> result = new HashSet<>();
if (config == null || config.userProperties == null || !config.userProperties.containsKey("types")) {
result.add("surefire");
return result;
}
String types = config.userProperties.get("types");
for (String type : types.split(",")) {
result.add(type);
}
return result;
}
}
|
Update plugins-compat-tester/src/main/java/org/jenkins/tools/test/maven/ExternalMavenRunner.java
Co-authored-by: Jesse Glick <f03f7b035106bba3da9b565be6f0115dc0d88f87@cloudbees.com>
|
plugins-compat-tester/src/main/java/org/jenkins/tools/test/maven/ExternalMavenRunner.java
|
Update plugins-compat-tester/src/main/java/org/jenkins/tools/test/maven/ExternalMavenRunner.java
|
|
Java
|
mit
|
0c7b71339f17ddfd23173ffde9c9a7a7ba0b5c10
| 0
|
venkatramanm/swf-all,venkatramanm/swf-all,venkatramanm/swf-all
|
package com.venky.swf.controller;
import com.venky.core.util.Bucket;
import com.venky.core.util.ObjectHolder;
import com.venky.extension.Registry;
import com.venky.swf.controller.annotations.RequireLogin;
import com.venky.swf.db.Database;
import com.venky.swf.db.model.cache.CacheVersion;
import com.venky.swf.path.Path;
import com.venky.swf.sql.Select;
import com.venky.swf.views.BytesView;
import com.venky.swf.views.View;
import java.util.Arrays;
import java.util.List;
public class CacheVersionsController extends ModelController<CacheVersion> {
public CacheVersionsController(Path path) {
super(path);
}
public CacheVersion getLastVersion(){
List<CacheVersion> versionList = new Select().from(CacheVersion.class).orderBy("VERSION_NUMBER DESC").execute(1);
CacheVersion version = null;
if (!versionList.isEmpty()){
version = versionList.get(0);
}else {
version = Database.getTable(CacheVersion.class).newRecord();
version.setVersionNumber(new Bucket(1));
version.save();
}
return version;
}
@RequireLogin(false)
public View last(){
CacheVersion version = getLastVersion();
if (getReturnIntegrationAdaptor() == null){
return back();
}else {
return getReturnIntegrationAdaptor().createResponse(getPath(),version, Arrays.asList("VERSION_NUMBER","UPDATED_AT"));
}
}
public View increment(){
CacheVersion version = getLastVersion();
version.getVersionNumber().increment();
version.save();
Registry.instance().callExtensions(Controller.CLEAR_CACHED_RESULT_EXTENSION, CacheOperation.CLEAR,getPath(),new ObjectHolder<>(null));
if (getReturnIntegrationAdaptor() == null){
return back();
}else {
return getReturnIntegrationAdaptor().createResponse(getPath(),version);
}
}
}
|
swf/src/main/java/com/venky/swf/controller/CacheVersionsController.java
|
package com.venky.swf.controller;
import com.venky.core.util.Bucket;
import com.venky.core.util.ObjectHolder;
import com.venky.extension.Registry;
import com.venky.swf.controller.annotations.RequireLogin;
import com.venky.swf.db.Database;
import com.venky.swf.db.model.cache.CacheVersion;
import com.venky.swf.path.Path;
import com.venky.swf.sql.Select;
import com.venky.swf.views.BytesView;
import com.venky.swf.views.View;
import java.util.Arrays;
import java.util.List;
public class CacheVersionsController extends ModelController<CacheVersion> {
public CacheVersionsController(Path path) {
super(path);
}
public CacheVersion getLastVersion(){
List<CacheVersion> versionList = new Select().from(CacheVersion.class).orderBy("VERSION_NUMBER DESC").execute(1);
CacheVersion version = null;
if (!versionList.isEmpty()){
version = versionList.get(0);
}else {
version = Database.getTable(CacheVersion.class).newRecord();
version.setVersionNumber(new Bucket(1));
version.save();
}
return version;
}
@RequireLogin(false)
public View last(){
CacheVersion version = getLastVersion();
if (getReturnIntegrationAdaptor() == null){
return back();
}else {
return getReturnIntegrationAdaptor().createResponse(getPath(),version, Arrays.asList("VERSION_NUMBER","UPDATED_AT"));
}
}
public View increment(){
CacheVersion version = getLastVersion();
version.getVersionNumber().increment();
version.save();
Registry.instance().callExtensions(Controller.CLEAR_CACHED_RESULT_EXTENSION,getPath(),new ObjectHolder<>(null));
if (getReturnIntegrationAdaptor() == null){
return back();
}else {
return getReturnIntegrationAdaptor().createResponse(getPath(),version);
}
}
}
|
Cache Version clearing cdn
|
swf/src/main/java/com/venky/swf/controller/CacheVersionsController.java
|
Cache Version clearing cdn
|
|
Java
|
mit
|
939f64ce5cfd37d7815df4f2a28b200ba6c2e400
| 0
|
kaltsimon/Chasing-Pictures-front-end,kaltsimon/Chasing-Pictures-front-end,ChasingPictures/front-end,kaltsimon/Chasing-Pictures-front-end,ChasingPictures/front-end,ChasingPictures/front-end
|
package de.fu_berlin.cdv.chasingpictures.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import de.fu_berlin.cdv.chasingpictures.Maps;
import de.fu_berlin.cdv.chasingpictures.PictureDownloader;
import de.fu_berlin.cdv.chasingpictures.R;
import de.fu_berlin.cdv.chasingpictures.api.Picture;
import de.fu_berlin.cdv.chasingpictures.api.PictureRequest;
import de.fu_berlin.cdv.chasingpictures.api.Place;
/**
* Display a slideshow of all the pictures for a place.
*
* @author Simon Kalt
*/
public class Slideshow extends Activity {
protected List<Picture> mPictures;
private ProgressBar mProgressBar;
private ViewGroup mContainerView;
private RelativeLayout currentImageLayout;
private Handler mHandler;
private Place mPlace;
/**
* A background task for animating the transition between images.
*/
private class SlideshowTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
for(int i = 0; i < mPictures.size(); i++) {
final int finalI = i;
mHandler.post(new Runnable() {
@Override
public void run() {
setNewPicture(finalI);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
}
/**
* A background task for downloading the given pictures
* and, when finished, starting the slideshow.
*/
private class SlideshowPictureDownloader extends PictureDownloader {
public SlideshowPictureDownloader(File targetDirectory) {
super(targetDirectory);
}
@Override
protected void onProgressUpdate(Progress... values) {
if (values.length > 0)
mProgressBar.setProgress(values[0].getCurrent());
}
@Override
protected void onPostExecute(Void aVoid) {
hideProgressBar();
new SlideshowTask().executeOnExecutor(THREAD_POOL_EXECUTOR);
}
}
/**
* A background task for requesting all the available pictures for the current place.
*/
private class PictureRequestTask extends AsyncTask<PictureRequest, Void, List<Picture>> {
private final PictureDownloader downloader;
public PictureRequestTask(PictureDownloader downloader) {
this.downloader = downloader;
}
@Override
protected List<Picture> doInBackground(PictureRequest... params) {
// FIXME: Check for null, if yes, display error and exit
return params[0].sendRequest().getBody().getPlaces().get(0).getPictures();
}
@Override
protected void onPostExecute(List<Picture> pictures) {
mPictures = pictures;
mProgressBar.setMax(mPictures.size());
downloader.execute(mPictures.toArray(new Picture[mPictures.size()]));
}
}
/**
* Creates an {@link Intent} for a slideshow using the given place.
*
* @param context The current context
* @param place A place for which to show the slideshow
* @return An intent to be used with {@link #startActivity(Intent)}.
*/
public static Intent createIntent(Context context, Place place) {
Intent intent = new Intent(context, Slideshow.class);
intent.putExtra(Maps.EXTRA_PLACE, place);
return intent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slideshow);
mContainerView = (ViewGroup) findViewById(R.id.slideshowLayout);
mProgressBar = (ProgressBar) findViewById(R.id.slideshowProgressBar);
mHandler = new Handler();
mPlace = (Place) getIntent().getSerializableExtra(Maps.EXTRA_PLACE);
if (mPlace == null) {
Toast.makeText(
this,
"Did not receive a place",
Toast.LENGTH_SHORT
).show();
finish();
}
PictureDownloader downloader = new SlideshowPictureDownloader(getCacheDir());
PictureRequestTask pictureRequestTask = new PictureRequestTask(downloader);
pictureRequestTask.execute(new PictureRequest(this, mPlace));
}
/**
* Replace the currently displayed picture with the one with the given index.
* @param index Index of the picture in the {@link #mPictures} list
*/
private void setNewPicture(int index) {
RelativeLayout relativeLayout = (RelativeLayout) LayoutInflater.from(this).inflate(
R.layout.slideshow_image,
mContainerView,
false
);
ImageView newImageView = (ImageView) relativeLayout.getChildAt(0);
newImageView.setImageBitmap(getBitmapForIndex(index));
if (currentImageLayout != null) {
currentImageLayout.setVisibility(View.INVISIBLE);
mContainerView.removeView(currentImageLayout);
}
currentImageLayout = relativeLayout;
mContainerView.addView(relativeLayout, 0);
}
private void hideProgressBar() {
mProgressBar.setVisibility(View.GONE);
}
private Bitmap getBitmapForIndex(int idx) {
String file = mPictures.get(idx).getCachedFile().getPath();
return BitmapFactory.decodeFile(file);
}
}
|
ChasingPictures/app/src/main/java/de/fu_berlin/cdv/chasingpictures/activity/Slideshow.java
|
package de.fu_berlin.cdv.chasingpictures.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import de.fu_berlin.cdv.chasingpictures.Maps;
import de.fu_berlin.cdv.chasingpictures.PictureDownloader;
import de.fu_berlin.cdv.chasingpictures.R;
import de.fu_berlin.cdv.chasingpictures.api.Picture;
import de.fu_berlin.cdv.chasingpictures.api.PictureRequest;
import de.fu_berlin.cdv.chasingpictures.api.Place;
/**
* Display a slideshow of all the pictures for a place.
*
* @author Simon Kalt
*/
public class Slideshow extends Activity {
protected List<Picture> mPictures;
private ProgressBar mProgressBar;
private ViewGroup mContainerView;
private RelativeLayout currentImageLayout;
private Handler mHandler;
private Place mPlace;
/**
* A background task for animating the transition between images.
*/
private class SlideshowTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
for(int i = 0; i < mPictures.size(); i++) {
final int finalI = i;
mHandler.post(new Runnable() {
@Override
public void run() {
setNewPicture(finalI);
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
}
/**
* A background task for downloading the given pictures
* and, when finished, starting the slideshow.
*/
private class SlideshowPictureDownloader extends PictureDownloader {
public SlideshowPictureDownloader(File targetDirectory) {
super(targetDirectory);
}
@Override
protected void onProgressUpdate(Progress... values) {
if (values.length > 0)
mProgressBar.setProgress(values[0].getCurrent());
}
@Override
protected void onPostExecute(Void aVoid) {
hideProgressBar();
new SlideshowTask().executeOnExecutor(THREAD_POOL_EXECUTOR);
}
}
private class PictureRequestTask extends AsyncTask<PictureRequest, Void, List<Picture>> {
private final PictureDownloader downloader;
public PictureRequestTask(PictureDownloader downloader) {
this.downloader = downloader;
}
@Override
protected List<Picture> doInBackground(PictureRequest... params) {
// FIXME: Check for null, if yes, display error and exit
return params[0].sendRequest().getBody().getPlaces().get(0).getPictures();
}
@Override
protected void onPostExecute(List<Picture> pictures) {
mPictures = pictures;
mProgressBar.setMax(mPictures.size());
downloader.execute(mPictures.toArray(new Picture[mPictures.size()]));
}
}
/**
* Creates an {@link Intent} for a slideshow using the given place.
*
* @param context The current context
* @param place A place for which to show the slideshow
* @return An intent to be used with {@link #startActivity(Intent)}.
*/
public static Intent createIntent(Context context, Place place) {
Intent intent = new Intent(context, Slideshow.class);
intent.putExtra(Maps.EXTRA_PLACE, place);
return intent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slideshow);
mContainerView = (ViewGroup) findViewById(R.id.slideshowLayout);
mProgressBar = (ProgressBar) findViewById(R.id.slideshowProgressBar);
mHandler = new Handler();
mPlace = (Place) getIntent().getSerializableExtra(Maps.EXTRA_PLACE);
if (mPlace == null) {
Toast.makeText(
this,
"Did not receive a place",
Toast.LENGTH_SHORT
).show();
finish();
}
PictureDownloader downloader = new SlideshowPictureDownloader(getCacheDir());
PictureRequestTask pictureRequestTask = new PictureRequestTask(downloader);
pictureRequestTask.execute(new PictureRequest(this, mPlace));
}
/**
* Replace the currently displayed picture with the one with the given index.
* @param index Index of the picture in the {@link #mPictures} list
*/
private void setNewPicture(int index) {
RelativeLayout relativeLayout = (RelativeLayout) LayoutInflater.from(this).inflate(
R.layout.slideshow_image,
mContainerView,
false
);
ImageView newImageView = (ImageView) relativeLayout.getChildAt(0);
newImageView.setImageBitmap(getBitmapForIndex(index));
if (currentImageLayout != null) {
currentImageLayout.setVisibility(View.INVISIBLE);
mContainerView.removeView(currentImageLayout);
}
currentImageLayout = relativeLayout;
mContainerView.addView(relativeLayout, 0);
}
private void hideProgressBar() {
mProgressBar.setVisibility(View.GONE);
}
private Bitmap getBitmapForIndex(int idx) {
String file = mPictures.get(idx).getCachedFile().getPath();
return BitmapFactory.decodeFile(file);
}
}
|
Documentation
|
ChasingPictures/app/src/main/java/de/fu_berlin/cdv/chasingpictures/activity/Slideshow.java
|
Documentation
|
|
Java
|
epl-1.0
|
dd15242e039f6a3e263eb68bcc074a7277baed89
| 0
|
ModelWriter/Tarski,ModelWriter/Tarski,ModelWriter/Tarski,ModelWriter/WP3,ModelWriter/WP3,ModelWriter/WP3
|
/*******************************************************************************
* Copyright (c) 2015 UNIT Information Technologies R&D Ltd 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
*
* Contributors: Ferhat Erata - initial API and implementation H. Emre Kirmizi - initial API and
* implementation Serhat Celik - initial API and implementation U. Anil Ozturk - initial API and
* implementation
*******************************************************************************/
package eu.modelwriter.marker.command;
import java.util.UUID;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.PlatformUI;
import eu.modelwriter.marker.MarkerActivator;
import eu.modelwriter.marker.internal.AnnotationFactory;
import eu.modelwriter.marker.internal.MarkElementUtilities;
import eu.modelwriter.marker.internal.MarkerFactory;
public class MarkAllHandler extends AbstractHandler {
IEditorPart editor;
IFile file;
ISelection selection;
private void createMarkers() {
this.editor =
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
this.file = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.getActiveEditor().getEditorInput().getAdapter(IFile.class);
this.selection =
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
ITextSelection textSelection = (ITextSelection) this.selection;
if (MarkerFactory.findMarkerWithAbsolutePosition(this.file, textSelection.getOffset(),
textSelection.getOffset() + textSelection.getLength()) != null) {
MessageDialog dialog = new MessageDialog(MarkerActivator.getShell(), "Mark Information", null,
"In these area, there is already a marker", MessageDialog.WARNING, new String[] {"OK"},
0);
dialog.open();
} else {
String content = MarkerFactory.getCurrentEditorContent();
int index = 0;
int offset = 0;
int length = textSelection.getLength();
String id = UUID.randomUUID().toString();
String leader_id = UUID.randomUUID().toString();
if (length != 0) {
while ((offset =
content.toLowerCase().indexOf(textSelection.getText().toLowerCase(), index)) != -1) {
TextSelection nextSelection =
new TextSelection(MarkerFactory.getDocument(), offset, length);
if (MarkerFactory.findMarkerWithAbsolutePosition(this.file, offset,
offset + length) == null) {
IMarker mymarker = MarkerFactory.createMarker(this.file, nextSelection);
MarkElementUtilities.setGroupId(mymarker, id);
if (textSelection.getOffset() == offset) {
MarkElementUtilities.setLeaderId(mymarker, leader_id);
}
AnnotationFactory.addAnnotation(mymarker, this.editor,
AnnotationFactory.ANNOTATION_MARKING);
}
index = offset + length;
}
MessageDialog dialog = new MessageDialog(MarkerActivator.getShell(),
"Mark Information will be provided by this wizard.", null,
"\"" + textSelection.getText() + "\" has been selected to be marked",
MessageDialog.INFORMATION, new String[] {"OK"}, 0);
dialog.open();
} else {
MessageDialog dialog = new MessageDialog(MarkerActivator.getShell(),
"Mark Information will be provided by this wizard.", null,
"Please select a valid information", MessageDialog.INFORMATION, new String[] {"OK"}, 0);
dialog.open();
}
}
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
this.createMarkers();
this.refresh();
return null;
}
private void refresh() {
MarkerFactory.refreshProjectExp();
}
}
|
Source/eu.modelwriter.marker.command/src/eu/modelwriter/marker/command/MarkAllHandler.java
|
/*******************************************************************************
* Copyright (c) 2015 UNIT Information Technologies R&D Ltd
* 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
*
* Contributors:
* Ferhat Erata - initial API and implementation
* H. Emre Kirmizi - initial API and implementation
* Serhat Celik - initial API and implementation
* U. Anil Ozturk - initial API and implementation
*******************************************************************************/
package eu.modelwriter.marker.command;
import java.util.UUID;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.ui.PlatformUI;
import eu.modelwriter.marker.MarkerActivator;
import eu.modelwriter.marker.internal.AnnotationFactory;
import eu.modelwriter.marker.internal.MarkElementUtilities;
import eu.modelwriter.marker.internal.MarkerFactory;
public class MarkAllHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
ISelection iselection =
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
IFile file = MarkerActivator.getEditor().getEditorInput().getAdapter(IFile.class);
if (iselection instanceof ITreeSelection) {
/* Mark action may will be */
} else if (iselection instanceof ITextSelection) {
ITextSelection selection = (ITextSelection) iselection;
if (MarkerFactory.findMarkerWithAbsolutePosition(file, selection.getOffset(),
selection.getOffset() + selection.getLength()) != null) {
MessageDialog dialog = new MessageDialog(MarkerActivator.getShell(), "Mark Information",
null, "In these area, there is already a marker", MessageDialog.WARNING,
new String[] {"OK"}, 0);
dialog.open();
return null;
} else {
String content = MarkerFactory.getCurrentEditorContent();
int index = 0;
int offset = 0;
int length = selection.getLength();
String id = UUID.randomUUID().toString();
String leader_id = UUID.randomUUID().toString();
if (length != 0) {
while ((offset =
content.toLowerCase().indexOf(selection.getText().toLowerCase(), index)) != -1) {
TextSelection nextSelection =
new TextSelection(MarkerFactory.getDocument(), offset, length);
if (MarkerFactory.findMarkerWithAbsolutePosition(file, offset,
offset + length) == null) {
IMarker mymarker = MarkerFactory.createMarker(file, nextSelection);
MarkElementUtilities.setGroupId(mymarker, id);
if (selection.getOffset() == offset) {
MarkElementUtilities.setLeaderId(mymarker, leader_id);
}
AnnotationFactory.addAnnotation(mymarker, MarkerActivator.getEditor(),
AnnotationFactory.ANNOTATION_MARKING);
}
index = offset + length;
}
MessageDialog dialog = new MessageDialog(MarkerActivator.getShell(),
"Mark Information will be provided by this wizard.", null,
"\"" + selection.getText() + "\" has been seleceted to be marked",
MessageDialog.INFORMATION, new String[] {"OK"}, 0);
dialog.open();
} else {
MessageDialog dialog = new MessageDialog(MarkerActivator.getShell(),
"Mark Information will be provided by this wizard.", null,
"Please select a valid information", MessageDialog.INFORMATION, new String[] {"OK"},
0);
dialog.open();
}
}
}
MarkerFactory.refreshProjectExp();
return null;
}
}
|
Mark All Handler class has been updated to code re-factoring.
|
Source/eu.modelwriter.marker.command/src/eu/modelwriter/marker/command/MarkAllHandler.java
|
Mark All Handler class has been updated to code re-factoring.
|
|
Java
|
epl-1.0
|
61637592ca65455ebf57b138e58479481a5b2e0a
| 0
|
smeup/asup,smeup/asup,smeup/asup
|
/**
* Copyright (c) 2012, 2016 Sme.UP 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
*
*
* Contributors:
* Mattia Rocchi - Initial API and implementation
*/
package org.smeup.sys.il.esam.jdbc;
import java.sql.SQLException;
import org.smeup.sys.db.core.QConnection;
import org.smeup.sys.il.data.QData;
import org.smeup.sys.il.data.QDataContext;
import org.smeup.sys.il.data.QIndicator;
import org.smeup.sys.il.data.QRecord;
import org.smeup.sys.il.data.QString;
import org.smeup.sys.il.esam.AccessMode;
import org.smeup.sys.il.esam.OperationDirection;
import org.smeup.sys.il.esam.OperationRead;
import org.smeup.sys.il.esam.OperationSet;
import org.smeup.sys.il.esam.QIndex;
import org.smeup.sys.il.esam.QKSDataSet;
public class JDBCKeySequencedDataSetImpl<R extends QRecord> extends JDBCDataSetImpl<R> implements QKSDataSet<R> {
protected JDBCKeySequencedDataSetImpl(QConnection databaseConnection, QString tableName, QIndex index, R record, AccessMode accessMode, boolean userOpen, JDBCInfoStruct infoStruct,
QDataContext dataContext) {
super(databaseConnection, tableName, index, record, accessMode, userOpen, infoStruct, dataContext);
}
@Override
public boolean chain(Object keyField) {
return chain(keyField, null, null, null);
}
@Override
public boolean chain(Object keyField, QIndicator notFound) {
return chain(keyField, notFound, null, null);
}
@Override
public boolean chain(Object keyField, QIndicator notFound, Boolean lock) {
return chain(keyField, notFound, null, lock);
}
@Override
public boolean chain(Object keyField, QIndicator notFound, QIndicator error, Boolean lock) {
Object[] keyList = { keyField };
return chain(keyList, notFound, error, lock);
}
@Override
public boolean chain(Object[] keyList) {
return chain(keyList, null, null, null);
}
@Override
public boolean chain(Object[] keyList, Boolean lock) {
return chain(keyList, null, null, lock);
}
@Override
public boolean chain(Object[] keyList, QIndicator notFound) {
return chain(keyList, notFound, null, null);
}
@Override
public boolean chain(Object[] keyList, QIndicator notFound, Boolean lock) {
return chain(keyList, notFound, null, lock);
}
@Override
public boolean chain(Object[] keyList, QIndicator notFound, QIndicator error) {
return chain(keyList, notFound, error, null);
}
@Override
public boolean chain(Object[] keyList, QIndicator notFound, QIndicator error, Boolean lock) {
try {
prepareAccess(OperationSet.CHAIN, keyList, OperationRead.CHAIN, keyList, false);
readNext();
} catch (SQLException e) {
handleSQLException(e);
}
if (notFound != null)
notFound.eval(!isFound());
if (error != null)
error.eval(onError());
return isFound();
}
@Override
public boolean chain(QData keyField) {
return chain(keyField, null, null, null);
}
@Override
public boolean chain(QData keyField, Boolean lock) {
return chain(keyField, null, null, lock);
}
@Override
public boolean chain(QData keyField, QIndicator notFound) {
return chain(keyField, notFound, null, null);
}
@Override
public boolean chain(QData keyField, QIndicator notFound, Boolean lock) {
return chain(keyField, notFound, null, lock);
}
@Override
public boolean chain(QData keyField, QIndicator notFound, QIndicator error) {
return chain(keyField, notFound, error, null);
}
@Override
public boolean chain(QData keyField, QIndicator notFound, QIndicator error, Boolean lock) {
Object[] keyList = { keyField };
return chain(keyList, notFound, error, lock);
}
@Override
public void delete(Object[] keyList, QIndicator notFound) {
deleteRecord(keyList, notFound, null);
}
@Override
public void delete(Object[] keyList, QIndicator notFound, QIndicator error) {
deleteRecord(keyList, notFound, error);
}
@Override
public boolean reade(Object[] keyList, Boolean lock) {
return reade(keyList, null, null, null);
}
@Override
public boolean reade(Object keyField) {
return reade(keyField, null, null, null);
}
@Override
public boolean reade(Object keyField, QIndicator endOfData) {
return reade(keyField, endOfData, null, null);
}
@Override
public boolean reade(Object keyField, Boolean lock) {
return reade(keyField, null, null, lock);
}
@Override
public boolean reade(Object keyField, QIndicator endOfData, Boolean lock) {
return reade(keyField, endOfData, null, lock);
}
@Override
public boolean reade(Object keyField, QIndicator endOfData, QIndicator error, Boolean lock) {
Object[] keyList = { keyField };
return reade(keyList, endOfData, error, lock);
}
@Override
public boolean reade(Object[] keyList) {
return reade(keyList, null, null, null);
}
@Override
public boolean reade(Object[] keyList, QIndicator endOfData) {
return reade(keyList, endOfData, null, null);
}
@Override
public boolean reade(Object[] keyList, QIndicator endOfData, Boolean lock) {
return reade(keyList, endOfData, null, lock);
}
@Override
public boolean reade(Object[] keyList, QIndicator endOfData, QIndicator error, Boolean lock) {
try {
if (rebuildNeeded(OperationDirection.FORWARD)) {
Object[] keySet = null;
if (isBeforeFirst())
keySet = this.currentKeySet;
else
keySet = buildKeySet();
prepareAccess(this.currentOpSet, keySet, OperationRead.READ_EQUAL, keyList, false);
}
readNext();
} catch (SQLException e) {
handleSQLException(e);
}
if (endOfData != null)
endOfData.eval(isEndOfData());
if (error != null)
error.eval(onError());
return isFound();
}
@Override
public boolean reade(QData keyField) {
return reade(keyField, null, null, null);
}
@Override
public boolean reade(QData keyField, QIndicator endOfData) {
return reade(keyField, endOfData, null, null);
}
@Override
public boolean reade(QData keyField, Boolean lock) {
return reade(keyField, null, null, lock);
}
@Override
public boolean reade(QData keyField, QIndicator endOfData, Boolean lock) {
return reade(keyField, endOfData, null, lock);
}
@Override
public boolean reade(QData keyField, QIndicator endOfData, QIndicator error, Boolean lock) {
Object[] keyList = { keyField };
return reade(keyList, endOfData, error, lock);
}
@Override
public boolean readpe(Object keyField) {
return readpe(keyField, null, null, null);
}
@Override
public boolean readpe(Object keyField, Boolean lock) {
return readpe(keyField, null, null, lock);
}
@Override
public boolean readpe(Object keyField, QIndicator beginningOfData) {
return readpe(keyField, beginningOfData, null, null);
}
@Override
public boolean readpe(Object keyField, QIndicator beginningOfData, Boolean lock) {
return readpe(keyField, beginningOfData, null, lock);
}
@Override
public boolean readpe(Object keyField, QIndicator beginningOfData, QIndicator error, Boolean lock) {
Object[] keyList = { keyField };
return readpe(keyList, beginningOfData, error, lock);
}
@Override
public boolean readpe(Object[] keyList) {
return readpe(keyList, null, null, null);
}
@Override
public boolean readpe(Object[] keyList, Boolean lock) {
return readpe(keyList, null, null, lock);
}
@Override
public boolean readpe(Object[] keyList, QIndicator beginningOfData) {
return readpe(keyList, beginningOfData, null, null);
}
@Override
public boolean readpe(Object[] keyList, QIndicator beginningOfData, Boolean lock) {
return readpe(keyList, beginningOfData, null, lock);
}
@Override
public boolean readpe(Object[] keyList, QIndicator beginningOfData, QIndicator error, Boolean lock) {
try {
if (rebuildNeeded(OperationDirection.BACKWARD)) {
Object[] keySet = null;
if (isBeforeFirst())
keySet = this.currentKeySet;
else
keySet = buildKeySet();
prepareAccess(this.currentOpSet, keySet, OperationRead.READ_PRIOR_EQUAL, keyList, false);
}
readNext();
} catch (SQLException e) {
handleSQLException(e);
}
if (beginningOfData != null)
beginningOfData.eval(isEndOfData());
if (error != null)
error.eval(onError());
return isFound();
}
@Override
public boolean readpe(QData keyField) {
return readpe(keyField, null, null, null);
}
@Override
public boolean readpe(QData keyField, Boolean lock) {
return readpe(keyField, null, null, lock);
}
@Override
public boolean readpe(QData keyField, QIndicator beginningOfData) {
return readpe(keyField, beginningOfData, null, null);
}
@Override
public boolean readpe(QData keyField, QIndicator beginningOfData, Boolean lock) {
return readpe(keyField, beginningOfData, null, lock);
}
@Override
public boolean readpe(QData keyField, QIndicator beginningOfData, QIndicator error, Boolean lock) {
Object[] keyList = { keyField };
return readpe(keyList, beginningOfData, error, lock);
}
@Override
public void setgt(Object keyField) {
setgt(keyField, null, null);
}
@Override
public void setgt(Object keyField, QIndicator found) {
setgt(keyField, found, null);
}
@Override
public void setgt(Object keyField, QIndicator found, QIndicator error) {
Object[] keyList = { keyField };
setgt(keyList, found, error);
}
@Override
public void setgt(Object[] keyList) {
setgt(keyList, null, null);
}
@Override
public void setgt(Object[] keyList, QIndicator found) {
setgt(keyList, found, null);
}
@Override
public void setgt(Object[] keyList, QIndicator found, QIndicator error) {
setKeySet(OperationSet.SET_GREATER_THAN, keyList);
if (found != null || error != null)
try {
if (rebuildNeeded(OperationDirection.FORWARD)) {
Object[] keySet = null;
if (isBeforeFirst())
keySet = this.currentKeySet;
else
keySet = buildKeySet();
prepareAccess(this.currentOpSet, keySet, OperationRead.READ, keyList, false);
}
readForSetll();
} catch (SQLException e) {
handleSQLException(e);
}
if (found != null)
found.eval(isFound());
if (error != null)
error.eval(onError());
}
@Override
public void setgt(QData keyField) {
setgt(keyField, null, null);
}
@Override
public void setgt(QData keyField, QIndicator found) {
setgt(keyField, found, null);
}
@Override
public void setgt(QData keyField, QIndicator found, QIndicator error) {
Object[] keyList = { keyField };
setgt(keyList, found, error);
}
@Override
public void setll(Object keyField) {
setll(keyField, null, null, null);
}
@Override
public void setll(Object keyField, QIndicator found) {
setll(keyField, found, null, null);
}
@Override
public void setll(Object keyField, QIndicator found, QIndicator equal) {
setll(keyField, found, equal, null);
}
@Override
public void setll(Object keyField, QIndicator found, QIndicator equal, QIndicator error) {
Object[] keyList = { keyField };
setll(keyList, found, equal, error);
}
@Override
public void setll(Object[] keyList) {
setll(keyList, null, null, null);
}
@Override
public void setll(Object[] keyList, QIndicator found) {
setll(keyList, found, null, null);
}
@Override
public void setll(Object[] keyList, QIndicator found, QIndicator equal) {
setll(keyList, found, equal, null);
}
@Override
public void setll(Object[] keyList, QIndicator found, QIndicator equal, QIndicator error) {
setKeySet(OperationSet.SET_LOWER_LIMIT, keyList);
if (found != null || equal != null)
try {
if (rebuildNeeded(OperationDirection.FORWARD)) {
Object[] keySet = null;
if (isBeforeFirst())
keySet = this.currentKeySet;
else
keySet = buildKeySet();
prepareAccess(this.currentOpSet, keySet, OperationRead.READ_EQUAL, keyList, false);
}
readForSetll();
} catch (SQLException e) {
handleSQLException(e);
}
if (found != null)
found.eval(isFound());
if (equal != null)
equal.eval(isEqual());
if (error != null)
error.eval(onError());
}
@Override
public void setll(QData keyField) {
setll(keyField, null, null, null);
}
@Override
public void setll(QData keyField, QIndicator found) {
setll(keyField, found, null, null);
}
@Override
public void setll(QData keyField, QIndicator found, QIndicator equal) {
setll(keyField, found, equal, null);
}
@Override
public void setll(QData keyField, QIndicator found, QIndicator equal, QIndicator error) {
Object[] keyList = { keyField };
setll(keyList, found, equal, error);
}
@Override
public void delete(QData keyField, QIndicator notFound) {
Object[] keyList = { keyField };
delete(keyList, notFound);
}
@Override
public void delete(QData keyField, QIndicator notFound, QIndicator error) {
Object[] keyList = { keyField };
delete(keyList, notFound, error);
}
}
|
org.smeup.sys.il.esam.jdbc/src/org/smeup/sys/il/esam/jdbc/JDBCKeySequencedDataSetImpl.java
|
/**
* Copyright (c) 2012, 2016 Sme.UP 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
*
*
* Contributors:
* Mattia Rocchi - Initial API and implementation
*/
package org.smeup.sys.il.esam.jdbc;
import java.sql.SQLException;
import org.smeup.sys.db.core.QConnection;
import org.smeup.sys.il.data.QData;
import org.smeup.sys.il.data.QDataContext;
import org.smeup.sys.il.data.QIndicator;
import org.smeup.sys.il.data.QRecord;
import org.smeup.sys.il.data.QString;
import org.smeup.sys.il.esam.AccessMode;
import org.smeup.sys.il.esam.OperationDirection;
import org.smeup.sys.il.esam.OperationRead;
import org.smeup.sys.il.esam.OperationSet;
import org.smeup.sys.il.esam.QIndex;
import org.smeup.sys.il.esam.QKSDataSet;
public class JDBCKeySequencedDataSetImpl<R extends QRecord> extends JDBCDataSetImpl<R> implements QKSDataSet<R> {
protected JDBCKeySequencedDataSetImpl(QConnection databaseConnection, QString tableName, QIndex index, R record, AccessMode accessMode, boolean userOpen, JDBCInfoStruct infoStruct,
QDataContext dataContext) {
super(databaseConnection, tableName, index, record, accessMode, userOpen, infoStruct, dataContext);
}
@Override
public boolean chain(Object keyField) {
return chain(keyField, null, null, null);
}
@Override
public boolean chain(Object keyField, QIndicator notFound) {
return chain(keyField, notFound, null, null);
}
@Override
public boolean chain(Object keyField, QIndicator notFound, Boolean lock) {
return chain(keyField, notFound, null, lock);
}
@Override
public boolean chain(Object keyField, QIndicator notFound, QIndicator error, Boolean lock) {
Object[] keyList = { keyField };
return chain(keyList, notFound, error, lock);
}
@Override
public boolean chain(Object[] keyList) {
return chain(keyList, null, null, null);
}
@Override
public boolean chain(Object[] keyList, Boolean lock) {
return chain(keyList, null, null, lock);
}
@Override
public boolean chain(Object[] keyList, QIndicator notFound) {
return chain(keyList, notFound, null, null);
}
@Override
public boolean chain(Object[] keyList, QIndicator notFound, Boolean lock) {
return chain(keyList, notFound, null, lock);
}
@Override
public boolean chain(Object[] keyList, QIndicator notFound, QIndicator error) {
return chain(keyList, notFound, error, null);
}
@Override
public boolean chain(Object[] keyList, QIndicator notFound, QIndicator error, Boolean lock) {
try {
prepareAccess(OperationSet.CHAIN, keyList, OperationRead.CHAIN, keyList, false);
readNext();
} catch (SQLException e) {
handleSQLException(e);
}
if (notFound != null)
notFound.eval(!isFound());
if (error != null)
error.eval(onError());
return isFound();
}
@Override
public boolean chain(QData keyField) {
return chain(keyField, null, null, null);
}
@Override
public boolean chain(QData keyField, Boolean lock) {
return chain(keyField, null, null, lock);
}
@Override
public boolean chain(QData keyField, QIndicator notFound) {
return chain(keyField, notFound, null, null);
}
@Override
public boolean chain(QData keyField, QIndicator notFound, Boolean lock) {
return chain(keyField, notFound, null, lock);
}
@Override
public boolean chain(QData keyField, QIndicator notFound, QIndicator error) {
return chain(keyField, notFound, error, null);
}
@Override
public boolean chain(QData keyField, QIndicator notFound, QIndicator error, Boolean lock) {
Object[] keyList = { keyField };
return chain(keyList, notFound, error, lock);
}
@Override
public void delete(Object[] keyList, QIndicator notFound) {
deleteRecord(keyList, notFound, null);
}
@Override
public void delete(Object[] keyList, QIndicator notFound, QIndicator error) {
deleteRecord(keyList, notFound, error);
}
@Override
public boolean reade(Object[] keyList, Boolean lock) {
return reade(keyList, null, null, null);
}
@Override
public boolean reade(Object keyField) {
return reade(keyField, null, null, null);
}
@Override
public boolean reade(Object keyField, QIndicator endOfData) {
return reade(keyField, endOfData, null, null);
}
@Override
public boolean reade(Object keyField, Boolean lock) {
return reade(keyField, null, null, lock);
}
@Override
public boolean reade(Object keyField, QIndicator endOfData, Boolean lock) {
return reade(keyField, endOfData, null, lock);
}
@Override
public boolean reade(Object keyField, QIndicator endOfData, QIndicator error, Boolean lock) {
Object[] keyList = { keyField };
return reade(keyList, endOfData, error, lock);
}
@Override
public boolean reade(Object[] keyList) {
return reade(keyList, null, null, null);
}
@Override
public boolean reade(Object[] keyList, QIndicator endOfData) {
return reade(keyList, endOfData, null, null);
}
@Override
public boolean reade(Object[] keyList, QIndicator endOfData, Boolean lock) {
return reade(keyList, endOfData, null, lock);
}
@Override
public boolean reade(Object[] keyList, QIndicator endOfData, QIndicator error, Boolean lock) {
try {
if (rebuildNeeded(OperationDirection.FORWARD)) {
Object[] keySet = null;
if (isBeforeFirst())
keySet = this.currentKeySet;
else
keySet = buildKeySet();
prepareAccess(this.currentOpSet, keySet, OperationRead.READ_EQUAL, keyList, false);
}
readNext();
} catch (SQLException e) {
handleSQLException(e);
}
if (endOfData != null)
endOfData.eval(isEndOfData());
if (error != null)
error.eval(onError());
return isFound();
}
@Override
public boolean reade(QData keyField) {
return reade(keyField, null, null, null);
}
@Override
public boolean reade(QData keyField, QIndicator endOfData) {
return reade(keyField, endOfData, null, null);
}
@Override
public boolean reade(QData keyField, Boolean lock) {
return reade(keyField, null, null, lock);
}
@Override
public boolean reade(QData keyField, QIndicator endOfData, Boolean lock) {
return reade(keyField, endOfData, null, lock);
}
@Override
public boolean reade(QData keyField, QIndicator endOfData, QIndicator error, Boolean lock) {
Object[] keyList = { keyField };
return reade(keyList, endOfData, error, lock);
}
@Override
public boolean readpe(Object keyField) {
return readpe(keyField, null, null, null);
}
@Override
public boolean readpe(Object keyField, Boolean lock) {
return readpe(keyField, null, null, lock);
}
@Override
public boolean readpe(Object keyField, QIndicator beginningOfData) {
return readpe(keyField, beginningOfData, null, null);
}
@Override
public boolean readpe(Object keyField, QIndicator beginningOfData, Boolean lock) {
return readpe(keyField, beginningOfData, null, lock);
}
@Override
public boolean readpe(Object keyField, QIndicator beginningOfData, QIndicator error, Boolean lock) {
Object[] keyList = { keyField };
return readpe(keyList, beginningOfData, error, lock);
}
@Override
public boolean readpe(Object[] keyList) {
return readpe(keyList, null, null, null);
}
@Override
public boolean readpe(Object[] keyList, Boolean lock) {
return readpe(keyList, null, null, lock);
}
@Override
public boolean readpe(Object[] keyList, QIndicator beginningOfData) {
return readpe(keyList, beginningOfData, null, null);
}
@Override
public boolean readpe(Object[] keyList, QIndicator beginningOfData, Boolean lock) {
return readpe(keyList, beginningOfData, null, lock);
}
@Override
public boolean readpe(Object[] keyList, QIndicator beginningOfData, QIndicator error, Boolean lock) {
try {
if (rebuildNeeded(OperationDirection.BACKWARD)) {
Object[] keySet = null;
if (isBeforeFirst())
keySet = this.currentKeySet;
else
keySet = buildKeySet();
prepareAccess(this.currentOpSet, keySet, OperationRead.READ_PRIOR_EQUAL, keyList, false);
}
readNext();
} catch (SQLException e) {
handleSQLException(e);
}
if (beginningOfData != null)
beginningOfData.eval(isEndOfData());
if (error != null)
error.eval(onError());
return isFound();
}
@Override
public boolean readpe(QData keyField) {
return readpe(keyField, null, null, null);
}
@Override
public boolean readpe(QData keyField, Boolean lock) {
return readpe(keyField, null, null, lock);
}
@Override
public boolean readpe(QData keyField, QIndicator beginningOfData) {
return readpe(keyField, beginningOfData, null, null);
}
@Override
public boolean readpe(QData keyField, QIndicator beginningOfData, Boolean lock) {
return readpe(keyField, beginningOfData, null, lock);
}
@Override
public boolean readpe(QData keyField, QIndicator beginningOfData, QIndicator error, Boolean lock) {
Object[] keyList = { keyField };
return readpe(keyList, beginningOfData, error, lock);
}
@Override
public void setgt(Object keyField) {
setgt(keyField, null, null);
}
@Override
public void setgt(Object keyField, QIndicator found) {
setgt(keyField, found, null);
}
@Override
public void setgt(Object keyField, QIndicator found, QIndicator error) {
Object[] keyList = { keyField };
setgt(keyList, found, error);
}
@Override
public void setgt(Object[] keyList) {
setgt(keyList, null, null);
}
@Override
public void setgt(Object[] keyList, QIndicator found) {
setgt(keyList, found, null);
}
@Override
public void setgt(Object[] keyList, QIndicator found, QIndicator error) {
setKeySet(OperationSet.SET_GREATER_THAN, keyList);
if (found != null)
found.eval(isFound());
if (error != null)
error.eval(onError());
}
@Override
public void setgt(QData keyField) {
setgt(keyField, null, null);
}
@Override
public void setgt(QData keyField, QIndicator found) {
setgt(keyField, found, null);
}
@Override
public void setgt(QData keyField, QIndicator found, QIndicator error) {
Object[] keyList = { keyField };
setgt(keyList, found, error);
}
@Override
public void setll(Object keyField) {
setll(keyField, null, null, null);
}
@Override
public void setll(Object keyField, QIndicator found) {
setll(keyField, found, null, null);
}
@Override
public void setll(Object keyField, QIndicator found, QIndicator equal) {
setll(keyField, found, equal, null);
}
@Override
public void setll(Object keyField, QIndicator found, QIndicator equal, QIndicator error) {
Object[] keyList = { keyField };
setll(keyList, found, equal, error);
}
@Override
public void setll(Object[] keyList) {
setll(keyList, null, null, null);
}
@Override
public void setll(Object[] keyList, QIndicator found) {
setll(keyList, found, null, null);
}
@Override
public void setll(Object[] keyList, QIndicator found, QIndicator equal) {
setll(keyList, found, equal, null);
}
@Override
public void setll(Object[] keyList, QIndicator found, QIndicator equal, QIndicator error) {
setKeySet(OperationSet.SET_LOWER_LIMIT, keyList);
if (found != null || equal != null)
try {
if (rebuildNeeded(OperationDirection.FORWARD)) {
Object[] keySet = null;
if (isBeforeFirst())
keySet = this.currentKeySet;
else
keySet = buildKeySet();
prepareAccess(this.currentOpSet, keySet, OperationRead.READ_EQUAL, keyList, false);
}
readForSetll();
} catch (SQLException e) {
handleSQLException(e);
}
if (found != null)
found.eval(isFound());
if (equal != null)
equal.eval(isEqual());
if (error != null)
error.eval(onError());
}
@Override
public void setll(QData keyField) {
setll(keyField, null, null, null);
}
@Override
public void setll(QData keyField, QIndicator found) {
setll(keyField, found, null, null);
}
@Override
public void setll(QData keyField, QIndicator found, QIndicator equal) {
setll(keyField, found, equal, null);
}
@Override
public void setll(QData keyField, QIndicator found, QIndicator equal, QIndicator error) {
Object[] keyList = { keyField };
setll(keyList, found, equal, error);
}
@Override
public void delete(QData keyField, QIndicator notFound) {
Object[] keyList = { keyField };
delete(keyList, notFound);
}
@Override
public void delete(QData keyField, QIndicator notFound, QIndicator error) {
Object[] keyList = { keyField };
delete(keyList, notFound, error);
}
}
|
Implementazione setgt con indicatore
|
org.smeup.sys.il.esam.jdbc/src/org/smeup/sys/il/esam/jdbc/JDBCKeySequencedDataSetImpl.java
|
Implementazione setgt con indicatore
|
|
Java
|
agpl-3.0
|
c064a2ca403072e19d9aadf7f8e19802365c47f1
| 0
|
datamatica-pl/traccar-api,datamatica-pl/traccar-api
|
/*
* Copyright (C) 2016 Datamatica (dev@datamatica.pl)
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.datamatica.traccar.api.providers;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import pl.datamatica.traccar.model.ApplicationSettings;
public class ApplicationSettingsProvider{
private final EntityManager em;
public ApplicationSettingsProvider(EntityManager em) {
this.em = em;
}
public ApplicationSettings get() {
TypedQuery<ApplicationSettings> tq = em.createQuery("Select x from ApplicationSettings x",
ApplicationSettings.class);
tq.setMaxResults(1);
List<ApplicationSettings> result = tq.getResultList();
return result.isEmpty() ? new ApplicationSettings() : tq.getSingleResult();
}
}
|
src/main/java/pl/datamatica/traccar/api/providers/ApplicationSettingsProvider.java
|
/*
* Copyright (C) 2016 Datamatica (dev@datamatica.pl)
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.datamatica.traccar.api.providers;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import pl.datamatica.traccar.model.ApplicationSettings;
public class ApplicationSettingsProvider{
private final EntityManager em;
public ApplicationSettingsProvider(EntityManager em) {
this.em = em;
}
public ApplicationSettings get() {
TypedQuery<ApplicationSettings> tq = em.createQuery("Select x from ApplicationSettings x",
ApplicationSettings.class);
tq.setMaxResults(1);
return tq.getSingleResult();
}
}
|
https://datamatica.atlassian.net/browse/AUTO-846
|
src/main/java/pl/datamatica/traccar/api/providers/ApplicationSettingsProvider.java
|
https://datamatica.atlassian.net/browse/AUTO-846
|
|
Java
|
agpl-3.0
|
4fe677b473acd55e73c400e0c3f2d492bc64549a
| 0
|
quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,quikkian-ua-devops/kfs,kuali/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,kuali/kfs,kkronenb/kfs,ua-eas/kfs,bhutchinson/kfs,smith750/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,quikkian-ua-devops/kfs,kuali/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,smith750/kfs,bhutchinson/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,ua-eas/kfs,UniversityOfHawaii/kfs,smith750/kfs,bhutchinson/kfs
|
/*
* Copyright 2010 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kfs.module.endow.batch.service.impl;
import static org.kuali.kfs.sys.fixture.UserNameFixture.kfs;
import java.util.Calendar;
import org.kuali.kfs.module.endow.batch.service.RollFrequencyDatesService;
import org.kuali.kfs.module.endow.document.service.FrequencyDatesService;
import org.kuali.kfs.module.endow.document.service.KEMService;
import org.kuali.kfs.module.endow.fixture.RollFrequencyCodeFixture;
import org.kuali.kfs.sys.ConfigureContext;
import org.kuali.kfs.sys.context.KualiTestBase;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.context.TestUtils;
@ConfigureContext(session = kfs)
public class RollFrequencyDatesServiceImplTest extends KualiTestBase {
protected RollFrequencyDatesServiceImpl rollFrequencyDatesService;
protected FrequencyDatesService frequencyDatesService;
protected KEMService kemService;
/**
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
// Initialize service objects.
frequencyDatesService = SpringContext.getBean(FrequencyDatesService.class);
rollFrequencyDatesService = (RollFrequencyDatesServiceImpl) TestUtils.getUnproxiedService("mockRollFrequencyDatesService");
kemService = SpringContext.getBean(KEMService.class);
super.setUp();
}
/**
*
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception {
frequencyDatesService = null;
rollFrequencyDatesService = null;
kemService = null;
super.tearDown();
}
public void testCalculateNextDueDate_InvalidFrequency() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.INVALID_FREQUENCY_CODE;
Calendar cal = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
assertNull(frequencyCode + " must be invalid", frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(cal.getTimeInMillis())));
}
/**
* checks the next due date for daily code
*/
public void testCalculateNextDueDate_Daily() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.DAILY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalendar = RollFrequencyCodeFixture.DAILY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next daily date is incorect.", new java.sql.Date(expectedCalendar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* checks the next due date for weekly code
*/
public void testCalculateNextDueDate_Weekly() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.WEEKLY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalendar = RollFrequencyCodeFixture.WEEKLY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next weekly date is incorect.", new java.sql.Date(expectedCalendar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* checks the next due date for semi-monthly code
*/
public void testCalculateNextDueDate_SemiMonthly() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.SEMI_MONTHLY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalendar = RollFrequencyCodeFixture.SEMI_MONTHLY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next semi-monthly date is incorect.", new java.sql.Date(expectedCalendar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* checks the next due date for monthly code
*/
public void testCalculateNextDueDate_Monthly() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.MONTHLY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalendar = RollFrequencyCodeFixture.MONTHLY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next monthly date is incorect.", new java.sql.Date(expectedCalendar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* checks the next due date for quarterly code
*/
public void testCalculateNextDueDate_Quarterly() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.QUARTERLY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalendar = RollFrequencyCodeFixture.QUARTERLY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next quarterly date is incorect.", new java.sql.Date(expectedCalendar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* checks the next due date for semi-annual code
*/
public void testCalculateNextDueDate_SemiAnnually() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.SEMI_ANNUALLY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalendar = RollFrequencyCodeFixture.SEMI_ANNUALLY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next semi-annual date is incorect.", new java.sql.Date(expectedCalendar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* checks the next due date for annual code
*/
public void testCalculateNextDueDate_Annually() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.ANNUALLY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalendar = RollFrequencyCodeFixture.ANNUALLY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next annual date is incorect.", new java.sql.Date(expectedCalendar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* tests RollFrequencyDatesService#updateSecurityIncomeNextPayDates
*/
public void testRollFrequencyDatesService_updateSecurityIncomeNextPayDates() {
assertTrue("updateSecurityIncomeNextPayDates() failed.", rollFrequencyDatesService.updateSecurityIncomeNextPayDates());
}
/**
* tests RollFrequencyDatesService#updateTicklerNextDueDates
*/
public void testRollFrequencyDatesService_updateTicklerNextDueDates() {
assertTrue("updateTicklerNextDueDates() failed.", rollFrequencyDatesService.updateTicklerNextDueDates());
}
/**
* tests RollFrequencyDatesService#updateFeeMethodProcessDates
*/
public void testRollFrequencyDatesService_updateFeeMethodProcessDates() {
assertTrue("updateFeeMethodProcessDates failed.", rollFrequencyDatesService.updateFeeMethodProcessDates());
}
/**
* tests RollFrequencyDatesService#updateRecurringCashTransferProcessDates
*/
public void testRollFrequencyDatesService_updateRecurringCashTransferProcessDates() {
assertTrue("updateRecurringCashTransferProcessDates failed.", rollFrequencyDatesService.updateRecurringCashTransferProcessDates());
}
/**
* tests RollFrequencyDatesService#updateCashSweepModelNextDueDates
*/
public void testRollFrequencyDatesService_updateCashSweepModelNextDueDates() {
assertTrue("updateCashSweepModelNextDueDates() failed.", rollFrequencyDatesService.updateCashSweepModelNextDueDates());
}
/**
* tests RollFrequencyDatesService#updateAutomatedCashInvestmentModelNextDueDates
*/
public void testRollFrequencyDatesService_updateAutomatedCashInvestmentModelNextDueDates() {
assertTrue("updateAutomatedCashInvestmentModelNextDueDates failed.", rollFrequencyDatesService.updateAutomatedCashInvestmentModelNextDueDates());
}
}
|
test/unit/src/org/kuali/kfs/module/endow/batch/service/impl/RollFrequencyDatesServiceImplTest.java
|
/*
* Copyright 2010 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kfs.module.endow.batch.service.impl;
import static org.kuali.kfs.sys.fixture.UserNameFixture.kfs;
import java.util.Calendar;
import org.kuali.kfs.module.endow.batch.service.RollFrequencyDatesService;
import org.kuali.kfs.module.endow.document.service.FrequencyDatesService;
import org.kuali.kfs.module.endow.document.service.KEMService;
import org.kuali.kfs.module.endow.fixture.RollFrequencyCodeFixture;
import org.kuali.kfs.sys.ConfigureContext;
import org.kuali.kfs.sys.context.KualiTestBase;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.context.TestUtils;
@ConfigureContext(session = kfs)
public class RollFrequencyDatesServiceImplTest extends KualiTestBase {
protected RollFrequencyDatesServiceImpl rollFrequencyDatesService;
protected FrequencyDatesService frequencyDatesService;
protected KEMService kemService;
/**
* @see junit.framework.TestCase#setUp()
*/
@Override
protected void setUp() throws Exception {
// Initialize service objects.
frequencyDatesService = SpringContext.getBean(FrequencyDatesService.class);
rollFrequencyDatesService = (RollFrequencyDatesServiceImpl) TestUtils.getUnproxiedService("mockRollFrequencyDatesService");
kemService = SpringContext.getBean(KEMService.class);
super.setUp();
}
/**
*
* @see junit.framework.TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception {
frequencyDatesService = null;
rollFrequencyDatesService = null;
kemService = null;
super.tearDown();
}
public void testCalculateNextDueDate_InvalidFrequency() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.INVALID_FREQUENCY_CODE;
Calendar cal = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
assertNull(frequencyCode + " must be invalid", frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(cal.getTimeInMillis())));
}
/**
* checks the next due date for daily code
*/
public void testCalculateNextDueDate_Daily() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.DAILY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalednar = RollFrequencyCodeFixture.DAILY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next daily date is incorect.", new java.sql.Date(expectedCalednar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* checks the next due date for weekly code
*/
public void testCalculateNextDueDate_Weekly() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.WEEKLY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalednar = RollFrequencyCodeFixture.WEEKLY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next weekly date is incorect.", new java.sql.Date(expectedCalednar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* checks the next due date for semi-monthly code
*/
public void testCalculateNextDueDate_SemiMonthly() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.SEMI_MONTHLY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalednar = RollFrequencyCodeFixture.SEMI_MONTHLY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next semi-monthly date is incorect.", new java.sql.Date(expectedCalednar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* checks the next due date for monthly code
*/
public void testCalculateNextDueDate_Monthly() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.MONTHLY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalednar = RollFrequencyCodeFixture.MONTHLY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next monthly date is incorect.", new java.sql.Date(expectedCalednar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* checks the next due date for quarterly code
*/
public void testCalculateNextDueDate_Quarterly() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.QUARTERLY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalednar = RollFrequencyCodeFixture.QUARTERLY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next quarterly date is incorect.", new java.sql.Date(expectedCalednar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* checks the next due date for semi-annual code
*/
public void testCalculateNextDueDate_SemiAnnually() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.SEMI_ANNUALLY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalednar = RollFrequencyCodeFixture.SEMI_ANNUALLY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next semi-annual date is incorect.", new java.sql.Date(expectedCalednar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* checks the next due date for annual code
*/
public void testCalculateNextDueDate_Annually() {
RollFrequencyCodeFixture rollFrequencyCodeFixture = RollFrequencyCodeFixture.ANNUALLY_TARGET_DATE;
Calendar targetCalendar = rollFrequencyCodeFixture.getCalendar();
String frequencyCode = rollFrequencyCodeFixture.getFrequencyCode();
Calendar expectedCalednar = RollFrequencyCodeFixture.ANNUALLY_EXPECTED_DATE.getCalendar();
assertEquals("The calculation of the next annual date is incorect.", new java.sql.Date(expectedCalednar.getTimeInMillis()), frequencyDatesService.calculateNextDueDate(frequencyCode, new java.sql.Date(targetCalendar.getTimeInMillis())));
}
/**
* tests RollFrequencyDatesService#updateSecurityIncomeNextPayDates
*/
public void testRollFrequencyDatesService_updateSecurityIncomeNextPayDates() {
assertTrue("updateSecurityIncomeNextPayDates() failed.", rollFrequencyDatesService.updateSecurityIncomeNextPayDates());
}
/**
* tests RollFrequencyDatesService#updateTicklerNextDueDates
*/
public void testRollFrequencyDatesService_updateTicklerNextDueDates() {
assertTrue("updateTicklerNextDueDates() faild.", rollFrequencyDatesService.updateTicklerNextDueDates());
}
/**
* tests RollFrequencyDatesService#updateFeeMethodProcessDates
*/
public void testRollFrequencyDatesService_updateFeeMethodProcessDates() {
assertTrue("updateFeeMethodProcessDates faild.", rollFrequencyDatesService.updateFeeMethodProcessDates());
}
/**
* tests RollFrequencyDatesService#updateRecurringCashTransferProcessDates
*/
public void testRollFrequencyDatesService_updateRecurringCashTransferProcessDates() {
assertTrue("updateRecurringCashTransferProcessDates faild.", rollFrequencyDatesService.updateRecurringCashTransferProcessDates());
}
/**
* tests RollFrequencyDatesService#updateCashSweepModelNextDueDates
*/
public void testRollFrequencyDatesService_updateCashSweepModelNextDueDates() {
assertTrue("updateCashSweepModelNextDueDates() faild.", rollFrequencyDatesService.updateCashSweepModelNextDueDates());
}
/**
* tests RollFrequencyDatesService#updateAutomatedCashInvestmentModelNextDueDates
*/
public void testRollFrequencyDatesService_updateAutomatedCashInvestmentModelNextDueDates() {
assertTrue("updateAutomatedCashInvestmentModelNextDueDates faild.", rollFrequencyDatesService.updateAutomatedCashInvestmentModelNextDueDates());
}
}
|
Typo fixing.
|
test/unit/src/org/kuali/kfs/module/endow/batch/service/impl/RollFrequencyDatesServiceImplTest.java
|
Typo fixing.
|
|
Java
|
lgpl-2.1
|
5867359854178954d21b57afc117d1863907cf5a
| 0
|
viktorbahr/jaer,SensorsINI/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,viktorbahr/jaer,SensorsINI/jaer
|
package net.sf.jaer.util.avioutput;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.beans.PropertyChangeEvent;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.TreeMap;
import javax.swing.BoxLayout;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.awt.GLCanvas;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.glu.GLUquadric;
import eu.seebetter.ini.chips.davis.HotPixelFilter;
import eu.visualize.ini.convnet.DvsSubsamplerToFrame;
import eu.visualize.ini.convnet.TargetLabeler;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.eventprocessing.filter.BackgroundActivityFilter;
import net.sf.jaer.eventprocessing.tracking.EinsteinClusterTracker;
import net.sf.jaer.eventprocessing.tracking.EinsteinClusterTracker.Cluster;
import net.sf.jaer.graphics.AEFrameChipRenderer;
import net.sf.jaer.graphics.ChipCanvas;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.ImageDisplay;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
/**
* Writes out AVI movie with DVS time or event slices as AVI frame images with
* desired output resolution
*
* @author Tobi Delbruck, Federico Corradi
*/
@Description("Writes out AVI movie with DVS constant-number-of-event slices as AVI frame images with desired output resolution")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class DvsSliceTargetAviWriter extends AbstractAviWriter
implements FrameAnnotater {
private static final int currentTargetTypeID = 0;
private static final int CURSOR_SIZE_CHIP_PIXELS = 3;
private DvsSubsamplerToFrame dvsSubsampler = null;
private int dimx, dimy, grayScale;
private int hotpixelColumn = getInt("hotpixelColumn", 0);
private int dvsMinEvents = getInt("dvsMinEvents", 10000);
private JFrame frame = null;
public ImageDisplay display;
private boolean showOutput;
private volatile boolean newFrameAvailable = false;
private int endOfFrameTimestamp=0, lastTimestamp=0;
protected boolean writeDvsSliceImageOnApsFrame = getBoolean("writeDvsSliceImageOnApsFrame", false);
protected boolean doPositiveLabel = getBoolean("doPositiveLabel", true);
private boolean rendererPropertyChangeListenerAdded=false;
private AEFrameChipRenderer renderer=null;
private HashMap<String, String> mapDataFilenameToTargetFilename = new HashMap();
private String lastFileName = getString("lastFileName", DEFAULT_FILENAME);
private String lastDataFilename = null;
private TreeMap<Integer, SimultaneouTargetLocations> targetLocations = new TreeMap();
private TargetLocation targetLocation = null;
private GLUquadric mouseQuad = null;
private int minSampleTimestamp = Integer.MAX_VALUE, maxSampleTimestamp = Integer.MIN_VALUE;
private int targetRadius = getInt("targetRadius", 10);
// file statistics
private long firstInputStreamTimestamp = 0, lastInputStreamTimestamp = 0, inputStreamDuration = 0;
private long filePositionEvents = 0, fileLengthEvents = 0;
private int filePositionTimestamp = 0;
private boolean warnSave = true;
private final int N_FRACTIONS = 1000;
private boolean[] labeledFractions = new boolean[N_FRACTIONS]; //to annotate graphically what has been labeled so far in event stream
private boolean[] targetPresentInFractions = new
boolean[N_FRACTIONS]; // to annotate graphically what has beenlabeled so far in event stream
private ArrayList<TargetLocation> currentTargets = new ArrayList(10); // currently valid targets
private ArrayList<DvsSubsamplerToFrame> currentdvsSubsampler = new ArrayList(10);
//private ArrayList<DvsSubsamplerToFrame> currentdvsSubsampler = new ArrayList(10); // currently valid subsampler
private ChipCanvas chipCanvas;
private GLCanvas glCanvas;
private int minTargetPointIntervalUs = getInt("minTargetPointIntervalUs", 10000);
private int maxTimeLastTargetLocationValidUs = getInt("maxTimeLastTargetLocationValidUs", 100000);
private int random_shift_x = 0;//Minx + (int)(Math.random() * ((Maxx - Minx) + 1));
private int random_shift_y = 0;//Miny + (int)(Math.random() * ((Maxy - Miny) + 1));
// Include Einstein Tracker
private EinsteinClusterTracker trackCluster=new EinsteinClusterTracker(chip);
private final BackgroundActivityFilter backgroundActivityFilter;
private final HotPixelFilter hotPixelFilter;
private final TargetLabeler targetLabelerFilter;
private java.util.List<Cluster> clusters = new LinkedList<Cluster>();
private int nextUpdateTimeUs = 0;
public DvsSliceTargetAviWriter(AEChip chip) {
super(chip);
dimx = getInt("dimx", 36);
dimy = getInt("dimy", 36);
grayScale = getInt("grayScale", 100);
showOutput = getBoolean("showOutput", true);
trackCluster.setEnclosed(true, this);
FilterChain filterChain=new FilterChain(chip);
backgroundActivityFilter = new BackgroundActivityFilter(chip);
hotPixelFilter = new HotPixelFilter(chip);
targetLabelerFilter = new TargetLabeler(chip);
filterChain.add(trackCluster);
filterChain.add(backgroundActivityFilter);
filterChain.add(hotPixelFilter);
filterChain.add(targetLabelerFilter);
setEnclosedFilterChain(filterChain);
DEFAULT_FILENAME = "DvsTargetAvi.avi";
setPropertyTooltip("grayScale", "1/grayScale is the amount by which each DVS event is added to time slice 2D gray-level histogram");
setPropertyTooltip("dimx", "width of AVI frame");
setPropertyTooltip("dimy", "height of AVI frame");
setPropertyTooltip("hotpixelColumn", "Do not consider spikes from this column");
setPropertyTooltip("loadLocations", "loads locations from a file");
setPropertyTooltip("showOutput", "shows output in JFrame/ImageDisplay");
setPropertyTooltip("dvsMinEvents", "minimum number of events to run net on DVS timeslice (only if writeDvsSliceImageOnApsFrame is false)");
setPropertyTooltip("writeDvsSliceImageOnApsFrame", "<html>write DVS slice image for each APS frame end event (dvsMinEvents ignored).<br>The frame is written at the end of frame APS event.<br><b>Warning: to capture all frames, ensure that playback time slices are slow enough that all frames are rendered</b>");
setPropertyTooltip("minTargetPointIntervalUs", "minimum interval between target positions in the database in us");
setPropertyTooltip("maxTimeLastTargetLocationValidUs", "this time after last sample, the data is shown as not yet been labeled. This time specifies how long a specified target location is valid after its last specified location.");
setPropertyTooltip("doPositiveLabel", "<html>send positive target to slicer or negative targets.");
Arrays.fill(labeledFractions, false);
Arrays.fill(targetPresentInFractions, false);
try {
byte[] bytes = getPrefs().getByteArray("TargetLabeler.hashmap", null);
if (bytes != null) {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
mapDataFilenameToTargetFilename = (HashMap<String,String>) in.readObject();
in.close();
log.info("loaded mapDataFilenameToTargetFilename: " + mapDataFilenameToTargetFilename.size() + " entries");
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
private TargetLocation lastNewTargetLocation = null;
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
// frameExtractor.filterPacket(in); // extracts frames with nornalization (brightness, contrast) and sends to apsNet on each frame in PropertyChangeListener
// send DVS timeslice to convnet
getEnclosedFilterChain().filterPacket(in);
super.filterPacket(in);
//EventPacket temp = getEnclosedFilterChain().filterPacket(in);
if(!rendererPropertyChangeListenerAdded){
rendererPropertyChangeListenerAdded=true;
renderer=(AEFrameChipRenderer)chip.getRenderer();
renderer.getSupport().addPropertyChangeListener(this);
}
final int sizeX = chip.getSizeX();
final int sizeY = chip.getSizeY();
checkSubsampler();
//checkSubsamplers();
clusters = trackCluster.getClusters();
int radius;
//add tracked clusters to lists of current targets
int counter = 0;
for (Cluster c : clusters) {
radius = (int) c.getRadius();
targetLocation = new TargetLocation(targetLabelerFilter.getCurrentFrameNumber(), c.getLastEventTimestamp(),
new Point((int) c.getLocation().x, (int) c.getLocation().y),
0, //only faces for the moment
radius,
radius); // read target location
currentTargets.add(targetLocation);
markDataHasTarget(targetLocation.timestamp);
}
//System.out.println(String.format("we have n: %d cluster",counter));
TargetLocation newTargetLocation = null;
lastNewTargetLocation = newTargetLocation;
for (BasicEvent e : in) {
if (e.isSpecial() || e.isFilteredOut()) {
continue;
}
PolarityEvent p = (PolarityEvent) e;
if (((long) e.timestamp - (long) lastTimestamp) >= minTargetPointIntervalUs) {
// show the nearest TargetLocation if at least minTargetPointIntervalUs has passed by,
// or "No target" if the location was previously
Map.Entry<Integer, SimultaneouTargetLocations> mostRecentTargetsBeforeThisEvent = targetLocations.lowerEntry(e.timestamp);
if (mostRecentTargetsBeforeThisEvent != null) {
for (TargetLocation t : mostRecentTargetsBeforeThisEvent.getValue()) {
if ((t == null) || ((t != null) && ((e.timestamp - t.timestamp) > maxTimeLastTargetLocationValidUs))) {
targetLocation = null;
} else {
if (targetLocation != t) {
targetLocation = t;
currentTargets.add(targetLocation);
markDataHasTarget(targetLocation.timestamp);
}
}
}
lastTimestamp = e.timestamp;
// find next saved target location that is just before this time (lowerEntry)
lastNewTargetLocation = newTargetLocation;
}
}
if (e.timestamp < lastTimestamp) {
lastTimestamp = e.timestamp;
}
//prune list of current targets to their valid lifetime, and remove leftover targets in the future
ArrayList<TargetLocation> removeList = new ArrayList();
for (TargetLocation t : currentTargets) {
if (((t.timestamp + maxTimeLastTargetLocationValidUs) < in.getLastTimestamp()) || (t.timestamp > in.getLastTimestamp())) {
removeList.add(t);
}
}
currentTargets.removeAll(removeList);
// TO DO multiple targets per time..
// it should produce one dvsSubampler image per target
double x_max;
double x_min;
double y_max;
double y_min;
counter = -1 ;
int numlocx = trackCluster.getMaxNumClusters();
int curretlocx = 0;
int currentnumtargets = currentTargets.size();
int[] location_x;
location_x = new int[currentnumtargets];
for(int i =0; i<currentnumtargets; i++){
location_x[i] = -1;
}
for (TargetLocation t : currentTargets) {
counter++;
if (t.location != null) {
//add this event into the dvsSubsampler if it is an event that is part of the tracked patch (target)
if( location_x[counter] == -1 ){
location_x[counter] = (int) t.location.getX();
curretlocx = counter;
}else{
for(int i =0; i<currentnumtargets; i++){
if(location_x[i] == (int) t.location.getX() ){
curretlocx = i;
}
}
}
//currentlocx is the current target id...
//NB!! one spike can be part of multiple targets
//System.out.println(curretlocx)
x_max = t.location.getX() + (t.dimx/2.0);
x_min = t.location.getX() - (t.dimx/2.0);
y_max = t.location.getY() + (t.dimy/2.0);
y_min = t.location.getY() - (t.dimy/2.0);
if( (p.x < x_max) && (p.x > x_min) && (p.y < y_max) && (p.y > y_min)){
// re-scale p to subsampler window and split it between targets
int newx = (int) (((((p.getX() - t.location.getX())/(t.dimx+2))*dimx) + (dimx/2.0)) ); //shift by the counter for different targets
newx = (newx/currentnumtargets)*(curretlocx+1); //automatically resize based on the number of target presents.. requires long life time of targets
int newy = (int) (((((p.getY() - t.location.getY())/(t.dimy+2))*dimy) + (dimy/2.0)) );
// for (DvsSubsamplerToFrame thissub : currentdvsSubsampler) {
//thissub.addEventInNewCoordinates(p, newx, newy);
dvsSubsampler.addEventInNewCoordinates(p, newx, newy);
if ((writeDvsSliceImageOnApsFrame && newFrameAvailable && (e.timestamp>=endOfFrameTimestamp))
|| ((!writeDvsSliceImageOnApsFrame && (dvsSubsampler.getAccumulatedEventCount() > dvsMinEvents))
&& !chip.getAeViewer().isPaused())) {
if(writeDvsSliceImageOnApsFrame) {
newFrameAvailable=false;
}
maybeShowOutput(dvsSubsampler);
if (aviOutputStream != null) {
BufferedImage bi = toImage(dvsSubsampler);
try {
writeTimecode(e.timestamp);
aviOutputStream.writeFrame(bi);
incrementFramecountAndMaybeCloseOutput();
} catch (IOException ex) {
log.warning(ex.toString());
ex.printStackTrace();
setFilterEnabled(false);
}
}
dvsSubsampler.clear();
// }
}
}
}
}
}
//System.out.println(counter);
if(writeDvsSliceImageOnApsFrame && ((lastTimestamp-endOfFrameTimestamp)>1000000)){
log.warning("last frame event was received more than 1s ago; maybe you need to enable Display Frames in the User Control Panel?");
}
return in;
}
/**
* @return the minTargetPointIntervalUs
*/
public int getMinTargetPointIntervalUs() {
return minTargetPointIntervalUs;
}
/**
* @param minTargetPointIntervalUs the minTargetPointIntervalUs to set
*/
public void setMinTargetPointIntervalUs(int minTargetPointIntervalUs) {
this.minTargetPointIntervalUs = minTargetPointIntervalUs;
putInt("minTargetPointIntervalUs", minTargetPointIntervalUs);
}
@Override
public void annotate(GLAutoDrawable drawable) {
if (dvsSubsampler == null) {
return;
}
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .8f);
MultilineAnnotationTextRenderer.setScale(.3f);
String s = String.format("mostOffCount=%d\n mostOnCount=%d",dvsSubsampler.getMostOffCount(), dvsSubsampler.getMostOnCount());
MultilineAnnotationTextRenderer.renderMultilineString(s);
GL2 gl = drawable.getGL().getGL2();
chipCanvas = chip.getCanvas();
if (chipCanvas == null) {
return;
}
glCanvas = (GLCanvas) chipCanvas.getCanvas();
if (glCanvas == null) {
return;
}
if (isSelected()) {
Point mp = glCanvas.getMousePosition();
Point p = chipCanvas.getPixelFromPoint(mp);
if (p == null) {
return;
}
checkBlend(gl);
float[] compArray = new float[4];
gl.glColor3fv(targetTypeColors[currentTargetTypeID % targetTypeColors.length].getColorComponents(compArray), 0);
gl.glLineWidth(3f);
gl.glPushMatrix();
gl.glTranslatef(p.x, p.y, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glEnd();
gl.glTranslatef(.5f, -.5f, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glEnd();
// if (quad == null) {
// quad = glu.gluNewQuadric();
// }
// glu.gluQuadricDrawStyle(quad, GLU.GLU_FILL);
// glu.gluDisk(quad, 0, 3, 32, 1);
gl.glPopMatrix();
}
for (TargetLocation t : currentTargets) {
if (t.location != null) {
t.draw(drawable, gl);
}
}
trackCluster.annotate(drawable);
}
@Override
public synchronized void doStartRecordingAndSaveAVIAs() {
String[] s = {"dimx=" + dimx, "dimy=" + dimy, "grayScale=" + grayScale, "dvsMinEvents=" + dvsMinEvents, "format=" + format.toString(), "compressionQuality=" + compressionQuality};
setAdditionalComments(s);
super.doStartRecordingAndSaveAVIAs(); //To change body of generated methods, choose Tools | Templates.
}
private void checkSubsampler() {
if ((dvsSubsampler == null) || ((dimx * dimy) != dvsSubsampler.getnPixels())) {
if ((aviOutputStream != null) && (dvsSubsampler != null)) {
log.info("closing existing output file because output resolution has changed");
doCloseFile();
}
dvsSubsampler = new DvsSubsamplerToFrame(dimx, dimy, grayScale);
}
}
private BufferedImage toImage(DvsSubsamplerToFrame subSampler) {
BufferedImage bi = new BufferedImage(dimx, dimy, BufferedImage.TYPE_INT_BGR);
int[] bd = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData();
for (int y = 0; y < dimy; y++) {
for (int x = 0; x < dimx; x++) {
int b = (int) (255 * subSampler.getValueAtPixel(x, y));
int g = b;
int r = b;
int idx=((dimy - y - 1) * dimx) + x;
if(idx>=bd.length){
throw new RuntimeException(String.format("index %d out of bounds for x=%d y=%d",idx,x,y));
}
bd[idx] = (b << 16) | (g << 8) | r | 0xFF000000;
}
}
return bi;
}
synchronized public void maybeShowOutput(DvsSubsamplerToFrame subSampler) {
if (!showOutput) {
return;
}
if (frame == null) {
String windowName = "DVS target slice";
frame = new JFrame(windowName);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
display = ImageDisplay.createOpenGLCanvas();
display.setBorderSpacePixels(10);
display.setImageSize(dimx, dimy);
display.setSize(200, 200);
panel.add(display);
frame.getContentPane().add(panel);
frame.pack();
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowOutput(false);
}
});
}
if (!frame.isVisible()) {
frame.setVisible(true);
}
if ((display.getWidth() != dimx) || (display.getHeight() != dimy)) {
display.setImageSize(dimx, dimy);
}
for (int x = 0; x < dimx; x++) {
for (int y = 0; y < dimy; y++) {
display.setPixmapGray(x, y, subSampler.getValueAtPixel(x, y));
}
}
display.repaint();
}
/**
* @return the dvsMinEvents
*/
public int getDvsMinEvents() {
return dvsMinEvents;
}
/**
* @param dvsMinEvents the dvsMinEvents to set
*/
public void setDvsMinEvents(int dvsMinEvents) {
this.dvsMinEvents = dvsMinEvents;
putInt("dvsMinEvents", dvsMinEvents);
}
/**
* @return the hotpixelCoumn
*/
public int getHotpixelCoumn() {
return hotpixelColumn;
}
/**
* @param dimx the dimx to set
*/
public void setHotpixelColumn(int hotpixelColumn) {
this.hotpixelColumn = hotpixelColumn;
putInt("hotpixelColumn", hotpixelColumn);
}
/**
* @return the dimx
*/
public int getDimx() {
return dimx;
}
/**
* @param dimx the dimx to set
*/
synchronized public void setDimx(int dimx) {
this.dimx = dimx;
putInt("dimx", dimx);
}
/**
* @return the dimy
*/
public int getDimy() {
return dimy;
}
/**
* @param dimy the dimy to set
*/
synchronized public void setDimy(int dimy) {
this.dimy = dimy;
putInt("dimy", dimy);
}
/**
* @return the showOutput
*/
public boolean isShowOutput() {
return showOutput;
}
/**
* @param showOutput the showOutput to set
*/
public void setShowOutput(boolean showOutput) {
boolean old = this.showOutput;
this.showOutput = showOutput;
putBoolean("showOutput", showOutput);
getSupport().firePropertyChange("showOutput", old, showOutput);
}
/**
* @return the maxTimeLastTargetLocationValidUs
*/
public int getMaxTimeLastTargetLocationValidUs() {
return maxTimeLastTargetLocationValidUs;
}
/**
* @param maxTimeLastTargetLocationValidUs the
* maxTimeLastTargetLocationValidUs to set
*/
public void setMaxTimeLastTargetLocationValidUs(int maxTimeLastTargetLocationValidUs) {
if (maxTimeLastTargetLocationValidUs < minTargetPointIntervalUs) {
maxTimeLastTargetLocationValidUs = minTargetPointIntervalUs;
}
this.maxTimeLastTargetLocationValidUs = maxTimeLastTargetLocationValidUs;
putInt("maxTimeLastTargetLocationValidUs", maxTimeLastTargetLocationValidUs);
}
/**
* @return the grayScale
*/
public int getGrayScale() {
return grayScale;
}
private int getFractionOfFileDuration(int timestamp) {
if (inputStreamDuration == 0) {
return 0;
}
return (int) Math.floor((N_FRACTIONS * ((float) (timestamp - firstInputStreamTimestamp))) / inputStreamDuration);
}
private void markDataHasTarget(int timestamp) {
if (inputStreamDuration == 0) {
return;
}
int frac = getFractionOfFileDuration(timestamp);
if ((frac < 0) || (frac >= labeledFractions.length)) {
log.warning("fraction " + frac + " is out of range " + labeledFractions.length + ", something is wrong");
return;
}
labeledFractions[frac] = true;
targetPresentInFractions[frac] = true;
}
/**
* @param grayScale the grayScale to set
*/
public void setGrayScale(int grayScale) {
if (grayScale < 1) {
grayScale = 1;
}
this.grayScale = grayScale;
putInt("grayScale", grayScale);
if (dvsSubsampler != null) {
dvsSubsampler.setColorScale(grayScale);
}
}
synchronized public void doLoadLocations() {
lastFileName = mapDataFilenameToTargetFilename.get(lastDataFilename);
if (lastFileName == null) {
lastFileName = DEFAULT_FILENAME;
}
if ((lastFileName != null) && lastFileName.equals(DEFAULT_FILENAME)) {
File f = chip.getAeViewer().getRecentFiles().getMostRecentFile();
if (f == null) {
lastFileName = DEFAULT_FILENAME;
} else {
lastFileName = f.getPath();
}
}
JFileChooser c = new JFileChooser(lastFileName);
c.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
}
@Override
public String getDescription() {
return "Text target label files";
}
});
c.setMultiSelectionEnabled(false);
c.setSelectedFile(new File(lastFileName));
ChipCanvas chipCanvas = chip.getCanvas();
GLCanvas glCanvas = (GLCanvas) chipCanvas.getCanvas();
int ret = c.showOpenDialog(glCanvas);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
lastFileName = c.getSelectedFile().toString();
putString("lastFileName", lastFileName);
loadLocations(new File(lastFileName));
}
/**
* Loads last locations. Note that this is a lengthy operation
*/
synchronized public void loadLastLocations() {
if (lastFileName == null) {
return;
}
File f = new File(lastFileName);
if (!f.exists() || !f.isFile()) {
return;
}
loadLocations(f);
}
synchronized private void loadLocations(File f) {
log.info("loading " + f);
try {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
targetLocations.clear();
minSampleTimestamp = Integer.MAX_VALUE;
maxSampleTimestamp = Integer.MIN_VALUE;
try {
BufferedReader reader = new BufferedReader(new FileReader(f));
String s = reader.readLine();
StringBuilder sb = new StringBuilder();
while ((s != null) && s.startsWith("#")) {
sb.append(s + "\n");
s = reader.readLine();
}
log.info("header lines on " + f.getAbsolutePath() + "are\n" + sb.toString());
while (s != null) {
Scanner scanner = new Scanner(s);
try {
int frame = scanner.nextInt();
int ts = scanner.nextInt();
int x = scanner.nextInt();
int y = scanner.nextInt();
int targetTypeID = 0;
int targetdimx = targetRadius;
int targetdimy = targetRadius;
try {
targetTypeID = scanner.nextInt();
try {
// added target dimensions compatibility
targetdimx = scanner.nextInt();
targetdimy = scanner.nextInt();
}catch (NoSuchElementException e) {
// older type file with only single target and no targetClassID and no x,y dimensions
}
} catch (NoSuchElementException e) {
// older type file with only single target
}
targetLocation = new TargetLocation(frame, ts,
new Point(x, y),
targetTypeID,
targetdimx,
targetdimy); // read target location
} catch (NoSuchElementException ex2) {
throw new IOException(("couldn't parse file " + f) == null ? "null" : f.toString() + ", got InputMismatchException on line: " + s);
}
if ((targetLocation.location.x == -1) && (targetLocation.location.y == -1)) {
targetLocation.location = null;
}
addSample(targetLocation.timestamp, targetLocation);
markDataHasTarget(targetLocation.timestamp);
if (targetLocation != null) {
if (targetLocation.timestamp > maxSampleTimestamp) {
maxSampleTimestamp = targetLocation.timestamp;
}
if (targetLocation.timestamp < minSampleTimestamp) {
minSampleTimestamp = targetLocation.timestamp;
}
}
s = reader.readLine();
}
log.info("done loading " + f);
if (lastDataFilename != null) {
mapDataFilenameToTargetFilename.put(lastDataFilename, f.getPath());
}
} catch (FileNotFoundException ex) {
ChipCanvas chipCanvas = chip.getCanvas();
GLCanvas glCanvas = (GLCanvas) chipCanvas.getCanvas();
JOptionPane.showMessageDialog(glCanvas, ("couldn't find file " + f) == null ? "null" : f.toString() + ": got exception " + ex.toString(), "Couldn't load locations",
JOptionPane.WARNING_MESSAGE, null);
} catch (IOException ex) {
ChipCanvas chipCanvas = chip.getCanvas();
GLCanvas glCanvas = (GLCanvas) chipCanvas.getCanvas();
JOptionPane.showMessageDialog(glCanvas, ("IOException with file " + f) == null ? "null" : f.toString() + ": got exception " + ex.toString(), "Couldn't load locations",
JOptionPane.WARNING_MESSAGE, null);
}
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
/**
* List of targets simultaneously present at a particular timestamp
*/
private class SimultaneouTargetLocations extends ArrayList<TargetLocation> {
}
/**
* @return the targetLocation
*/
public TargetLocation getTargetLocation() {
return targetLocation;
}
private void addSample(int timestamp, TargetLocation newTargetLocation) {
SimultaneouTargetLocations s = targetLocations.get(timestamp);
if (s == null) {
s = new SimultaneouTargetLocations();
targetLocations.put(timestamp, s);
}
s.add(newTargetLocation);
}
/**
* @return the writeDvsSliceImageOnApsFrame
*/
public boolean isWriteDvsSliceImageOnApsFrame() {
return writeDvsSliceImageOnApsFrame;
}
/**
* @return the doPositiveLabel
*/
public boolean isDoPositiveLabel() {
return doPositiveLabel;
}
/**
* @param writeDvsSliceImageOnApsFrame the writeDvsSliceImageOnApsFrame to
* set
*/
public void setDoPositiveLabel(boolean doPositiveLabel) {
this.doPositiveLabel = doPositiveLabel;
if(doPositiveLabel){
random_shift_x = 0;//Minx + (int)(Math.random() * ((Maxx - Minx) + 1));
random_shift_y = 0;//Minx + (int)(Math.random() * ((Maxx - Minx) + 1));
}else{
random_shift_x = 0;//dimx + (int)(Math.random() * (((2.0*dimx) - dimx) + 1));
random_shift_y = 0;//dimy + (int)(Math.random() * (((2.0*dimy) - dimy) + 1));
}
putBoolean("doPositiveLabel", doPositiveLabel);
}
/**
* @param writeDvsSliceImageOnApsFrame the writeDvsSliceImageOnApsFrame to
* set
*/
public void setWriteDvsSliceImageOnApsFrame(boolean writeDvsSliceImageOnApsFrame) {
this.writeDvsSliceImageOnApsFrame = writeDvsSliceImageOnApsFrame;
putBoolean("writeDvsSliceImageOnApsFrame", writeDvsSliceImageOnApsFrame);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ((evt.getPropertyName() == AEFrameChipRenderer.EVENT_NEW_FRAME_AVAILBLE)) {
AEFrameChipRenderer renderer=(AEFrameChipRenderer)evt.getNewValue();
endOfFrameTimestamp=renderer.getTimestampFrameEnd();
newFrameAvailable = true;
} else if (isCloseOnRewind() && (evt.getPropertyName() == AEInputStream.EVENT_REWIND)) {
doCloseFile();
}
}
private final Color[] targetTypeColors = {Color.BLUE, Color.CYAN, Color.GREEN, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED};
class TargetLocation {
int timestamp;
int frameNumber;
Point location; // center of target location
int targetClassID; // class of target, i.e. car, person
int dimx; // dimension of target x
int dimy; // y
public TargetLocation(int frameNumber, int timestamp, Point location, int targetTypeID, int dimx, int dimy) {
this.frameNumber = frameNumber;
this.timestamp = timestamp;
this.location = location != null ? new Point(location) : null;
this.targetClassID = targetTypeID;
this.dimx = dimx;
this.dimy = dimy;
}
private void draw(GLAutoDrawable drawable, GL2 gl) {
GLU glu = new GLU();
gl.glPushMatrix();
gl.glTranslatef(location.x, location.y, 0f);
float[] compArray = new float[4];
gl.glColor3fv(targetTypeColors[targetClassID % targetTypeColors.length].getColorComponents(compArray), 0);
if (mouseQuad == null) {
mouseQuad = glu.gluNewQuadric();
}
glu.gluQuadricDrawStyle(mouseQuad, GLU.GLU_LINE);
glu.gluDisk(mouseQuad, dimx/2, (dimy/2) +1, 32, 1);
//System.out.println(String.format("(%d,%d,%d,%d)", dimx/2, (dimy/2) + 1, 32, 1));
gl.glPopMatrix();
}
@Override
public String toString() {
return String.format("TargetLocation frameNumber=%d timestamp=%d location=%s", frameNumber, timestamp, location == null ?
"null" : location.toString());
}
}
}
|
src/net/sf/jaer/util/avioutput/DvsSliceTargetAviWriter.java
|
package net.sf.jaer.util.avioutput;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.beans.PropertyChangeEvent;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.TreeMap;
import javax.swing.BoxLayout;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.awt.GLCanvas;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.glu.GLUquadric;
import eu.seebetter.ini.chips.davis.HotPixelFilter;
import eu.visualize.ini.convnet.DvsSubsamplerToFrame;
import eu.visualize.ini.convnet.TargetLabeler;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.eventprocessing.filter.BackgroundActivityFilter;
import net.sf.jaer.eventprocessing.tracking.EinsteinClusterTracker;
import net.sf.jaer.eventprocessing.tracking.EinsteinClusterTracker.Cluster;
import net.sf.jaer.graphics.AEFrameChipRenderer;
import net.sf.jaer.graphics.ChipCanvas;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.ImageDisplay;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
/**
* Writes out AVI movie with DVS time or event slices as AVI frame images with
* desired output resolution
*
* @author Tobi Delbruck
*/
@Description("Writes out AVI movie with DVS constant-number-of-event slices as AVI frame images with desired output resolution")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class DvsSliceTargetAviWriter extends AbstractAviWriter
implements FrameAnnotater {
private static final int currentTargetTypeID = 0;
private static final int CURSOR_SIZE_CHIP_PIXELS = 3;
private DvsSubsamplerToFrame dvsSubsampler = null;
private int dimx, dimy, grayScale;
private int hotpixelColumn = getInt("hotpixelColumn", 0);
private int dvsMinEvents = getInt("dvsMinEvents", 10000);
private JFrame frame = null;
public ImageDisplay display;
private boolean showOutput;
private volatile boolean newFrameAvailable = false;
private int endOfFrameTimestamp=0, lastTimestamp=0;
protected boolean writeDvsSliceImageOnApsFrame = getBoolean("writeDvsSliceImageOnApsFrame", false);
protected boolean doPositiveLabel = getBoolean("doPositiveLabel", true);
private boolean rendererPropertyChangeListenerAdded=false;
private AEFrameChipRenderer renderer=null;
private HashMap<String, String> mapDataFilenameToTargetFilename = new HashMap();
private String lastFileName = getString("lastFileName", DEFAULT_FILENAME);
private String lastDataFilename = null;
private TreeMap<Integer, SimultaneouTargetLocations> targetLocations = new TreeMap();
private TargetLocation targetLocation = null;
private GLUquadric mouseQuad = null;
private int minSampleTimestamp = Integer.MAX_VALUE, maxSampleTimestamp = Integer.MIN_VALUE;
private int targetRadius = getInt("targetRadius", 10);
// file statistics
private long firstInputStreamTimestamp = 0, lastInputStreamTimestamp = 0, inputStreamDuration = 0;
private long filePositionEvents = 0, fileLengthEvents = 0;
private int filePositionTimestamp = 0;
private boolean warnSave = true;
private final int N_FRACTIONS = 1000;
private boolean[] labeledFractions = new boolean[N_FRACTIONS]; //to annotate graphically what has been labeled so far in event stream
private boolean[] targetPresentInFractions = new
boolean[N_FRACTIONS]; // to annotate graphically what has beenlabeled so far in event stream
private ArrayList<TargetLocation> currentTargets = new ArrayList(10); // currently valid targets
private java.util.List<DvsSubsamplerToFrame> currentdvsSubsampler = new LinkedList<DvsSubsamplerToFrame>();
//private ArrayList<DvsSubsamplerToFrame> currentdvsSubsampler = new ArrayList(10); // currently valid subsampler
private ChipCanvas chipCanvas;
private GLCanvas glCanvas;
private int minTargetPointIntervalUs = getInt("minTargetPointIntervalUs", 10000);
private int maxTimeLastTargetLocationValidUs = getInt("maxTimeLastTargetLocationValidUs", 100000);
private int random_shift_x = 0;//Minx + (int)(Math.random() * ((Maxx - Minx) + 1));
private int random_shift_y = 0;//Miny + (int)(Math.random() * ((Maxy - Miny) + 1));
// Include Einstein Tracker
private EinsteinClusterTracker trackCluster=new EinsteinClusterTracker(chip);
private final BackgroundActivityFilter backgroundActivityFilter;
private final HotPixelFilter hotPixelFilter;
private final TargetLabeler targetLabelerFilter;
private java.util.List<Cluster> clusters = new LinkedList<Cluster>();
private int nextUpdateTimeUs = 0;
public DvsSliceTargetAviWriter(AEChip chip) {
super(chip);
dimx = getInt("dimx", 36);
dimy = getInt("dimy", 36);
grayScale = getInt("grayScale", 100);
showOutput = getBoolean("showOutput", true);
trackCluster.setEnclosed(true, this);
FilterChain filterChain=new FilterChain(chip);
backgroundActivityFilter = new BackgroundActivityFilter(chip);
hotPixelFilter = new HotPixelFilter(chip);
targetLabelerFilter = new TargetLabeler(chip);
filterChain.add(trackCluster);
filterChain.add(backgroundActivityFilter);
filterChain.add(hotPixelFilter);
filterChain.add(targetLabelerFilter);
setEnclosedFilterChain(filterChain);
DEFAULT_FILENAME = "DvsTargetAvi.avi";
setPropertyTooltip("grayScale", "1/grayScale is the amount by which each DVS event is added to time slice 2D gray-level histogram");
setPropertyTooltip("dimx", "width of AVI frame");
setPropertyTooltip("dimy", "height of AVI frame");
setPropertyTooltip("hotpixelColumn", "Do not consider spikes from this column");
setPropertyTooltip("loadLocations", "loads locations from a file");
setPropertyTooltip("showOutput", "shows output in JFrame/ImageDisplay");
setPropertyTooltip("dvsMinEvents", "minimum number of events to run net on DVS timeslice (only if writeDvsSliceImageOnApsFrame is false)");
setPropertyTooltip("writeDvsSliceImageOnApsFrame", "<html>write DVS slice image for each APS frame end event (dvsMinEvents ignored).<br>The frame is written at the end of frame APS event.<br><b>Warning: to capture all frames, ensure that playback time slices are slow enough that all frames are rendered</b>");
setPropertyTooltip("minTargetPointIntervalUs", "minimum interval between target positions in the database in us");
setPropertyTooltip("maxTimeLastTargetLocationValidUs", "this time after last sample, the data is shown as not yet been labeled. This time specifies how long a specified target location is valid after its last specified location.");
setPropertyTooltip("doPositiveLabel", "<html>send positive target to slicer or negative targets.");
Arrays.fill(labeledFractions, false);
Arrays.fill(targetPresentInFractions, false);
try {
byte[] bytes = getPrefs().getByteArray("TargetLabeler.hashmap", null);
if (bytes != null) {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
mapDataFilenameToTargetFilename = (HashMap<String,String>) in.readObject();
in.close();
log.info("loaded mapDataFilenameToTargetFilename: " + mapDataFilenameToTargetFilename.size() + " entries");
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
private TargetLocation lastNewTargetLocation = null;
@Override
synchronized public EventPacket<?> filterPacket(EventPacket<?> in) {
// frameExtractor.filterPacket(in); // extracts frames with nornalization (brightness, contrast) and sends to apsNet on each frame in PropertyChangeListener
// send DVS timeslice to convnet
getEnclosedFilterChain().filterPacket(in);
super.filterPacket(in);
//EventPacket temp = getEnclosedFilterChain().filterPacket(in);
if(!rendererPropertyChangeListenerAdded){
rendererPropertyChangeListenerAdded=true;
renderer=(AEFrameChipRenderer)chip.getRenderer();
renderer.getSupport().addPropertyChangeListener(this);
}
final int sizeX = chip.getSizeX();
final int sizeY = chip.getSizeY();
checkSubsampler();
clusters = trackCluster.getClusters();
//for (Cluster c : clusters) {
// c.updateClusterList(in,in.timestamp);
//}
int tmp_cluster_x,tmp_cluster_y,radius;
//add tracked clusters to lists of current targets
int counter = 0;
for (Cluster c : clusters) {
//targetLocation = null;
c.getLocation();
radius = (int) c.getRadius();
targetLocation = new TargetLocation(targetLabelerFilter.getCurrentFrameNumber(), c.getLastEventTimestamp(),
new Point((int) c.getLocation().x, (int) c.getLocation().y),
0, //only faces for the moment
radius,
radius); // read target location
currentTargets.add(targetLocation);
markDataHasTarget(targetLocation.timestamp);
//currentTargets.add(targetLocation);
}
TargetLocation newTargetLocation = null;
lastNewTargetLocation = newTargetLocation;
for (BasicEvent e : in) {
if (e.isSpecial() || e.isFilteredOut()) {
continue;
}
PolarityEvent p = (PolarityEvent) e;
if (((long) e.timestamp - (long) lastTimestamp) >= minTargetPointIntervalUs) {
// show the nearest TargetLocation if at least minTargetPointIntervalUs has passed by,
// or "No target" if the location was previously
Map.Entry<Integer, SimultaneouTargetLocations> mostRecentTargetsBeforeThisEvent = targetLocations.lowerEntry(e.timestamp);
if (mostRecentTargetsBeforeThisEvent != null) {
for (TargetLocation t : mostRecentTargetsBeforeThisEvent.getValue()) {
if ((t == null) || ((t != null) && ((e.timestamp - t.timestamp) > maxTimeLastTargetLocationValidUs))) {
targetLocation = null;
} else {
if (targetLocation != t) {
targetLocation = t;
currentTargets.add(targetLocation);
markDataHasTarget(targetLocation.timestamp);
}
}
}
lastTimestamp = e.timestamp;
// find next saved target location that is just before this time (lowerEntry)
//TargetLocation newTargetLocation = null;
lastNewTargetLocation = newTargetLocation;
}
}
if (e.timestamp < lastTimestamp) {
lastTimestamp = e.timestamp;
}
//prune list of current targets to their valid lifetime, and remove leftover targets in the future
ArrayList<TargetLocation> removeList = new ArrayList();
for (TargetLocation t : currentTargets) {
if (((t.timestamp + maxTimeLastTargetLocationValidUs) < in.getLastTimestamp()) || (t.timestamp > in.getLastTimestamp())) {
removeList.add(t);
}
}
currentTargets.removeAll(removeList);
// TO DO multiple targets per time..
// it should produce one dvsSubampler image per target
double x_max;
double x_min;
double y_max;
double y_min;
for (TargetLocation t : currentTargets) {
if (t.location != null) {
//add this event into the dvsSubsampler if it is an event that is part of the tracked patch (target)
x_max = t.location.getX() + (t.dimx/2.0);
x_min = t.location.getX() - (t.dimx/2.0);
y_max = t.location.getY() + (t.dimy/2.0);
y_min = t.location.getY() - (t.dimy/2.0);
if( (p.x < x_max) && (p.x > x_min) && (p.y < y_max) && (p.y > y_min)){
// re-scale p to x_min,x_max=y_min,y_max
int newx = (int) (((((p.getX() - t.location.getX())/(t.dimx+2))*dimx) + (dimx/2.0)) ) ;
int newy = (int) (((((p.getY() - t.location.getY())/(t.dimy+2))*dimy) + (dimy/2.0)) ) ;
for (DvsSubsamplerToFrame thissub : currentdvsSubsampler) {
//thissub.addEventInNewCoordinates(p, newx, newy);
dvsSubsampler.addEventInNewCoordinates(p, newx, newy);
if ((writeDvsSliceImageOnApsFrame && newFrameAvailable && (e.timestamp>=endOfFrameTimestamp))
|| ((!writeDvsSliceImageOnApsFrame && (dvsSubsampler.getAccumulatedEventCount() > dvsMinEvents))
&& !chip.getAeViewer().isPaused())) {
if(writeDvsSliceImageOnApsFrame) {
newFrameAvailable=false;
}
maybeShowOutput(dvsSubsampler);
if (aviOutputStream != null) {
BufferedImage bi = toImage(dvsSubsampler);
try {
writeTimecode(e.timestamp);
aviOutputStream.writeFrame(bi);
incrementFramecountAndMaybeCloseOutput();
} catch (IOException ex) {
log.warning(ex.toString());
ex.printStackTrace();
setFilterEnabled(false);
}
}
dvsSubsampler.clear();
}
}
}
}
}
}
//System.out.println(counter);
if(writeDvsSliceImageOnApsFrame && ((lastTimestamp-endOfFrameTimestamp)>1000000)){
log.warning("last frame event was received more than 1s ago; maybe you need to enable Display Frames in the User Control Panel?");
}
return in;
}
/**
* @return the minTargetPointIntervalUs
*/
public int getMinTargetPointIntervalUs() {
return minTargetPointIntervalUs;
}
/**
* @param minTargetPointIntervalUs the minTargetPointIntervalUs to set
*/
public void setMinTargetPointIntervalUs(int minTargetPointIntervalUs) {
this.minTargetPointIntervalUs = minTargetPointIntervalUs;
putInt("minTargetPointIntervalUs", minTargetPointIntervalUs);
}
@Override
public void annotate(GLAutoDrawable drawable) {
if (dvsSubsampler == null) {
return;
}
MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .8f);
MultilineAnnotationTextRenderer.setScale(.3f);
String s = String.format("mostOffCount=%d\n mostOnCount=%d",dvsSubsampler.getMostOffCount(), dvsSubsampler.getMostOnCount());
MultilineAnnotationTextRenderer.renderMultilineString(s);
GL2 gl = drawable.getGL().getGL2();
chipCanvas = chip.getCanvas();
if (chipCanvas == null) {
return;
}
glCanvas = (GLCanvas) chipCanvas.getCanvas();
if (glCanvas == null) {
return;
}
if (isSelected()) {
Point mp = glCanvas.getMousePosition();
Point p = chipCanvas.getPixelFromPoint(mp);
if (p == null) {
return;
}
checkBlend(gl);
float[] compArray = new float[4];
gl.glColor3fv(targetTypeColors[currentTargetTypeID % targetTypeColors.length].getColorComponents(compArray), 0);
gl.glLineWidth(3f);
gl.glPushMatrix();
gl.glTranslatef(p.x, p.y, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glEnd();
gl.glTranslatef(.5f, -.5f, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glEnd();
// if (quad == null) {
// quad = glu.gluNewQuadric();
// }
// glu.gluQuadricDrawStyle(quad, GLU.GLU_FILL);
// glu.gluDisk(quad, 0, 3, 32, 1);
gl.glPopMatrix();
}
for (TargetLocation t : currentTargets) {
if (t.location != null) {
t.draw(drawable, gl);
}
}
trackCluster.annotate(drawable);
}
@Override
public synchronized void doStartRecordingAndSaveAVIAs() {
String[] s = {"dimx=" + dimx, "dimy=" + dimy, "grayScale=" + grayScale, "dvsMinEvents=" + dvsMinEvents, "format=" + format.toString(), "compressionQuality=" + compressionQuality};
setAdditionalComments(s);
super.doStartRecordingAndSaveAVIAs(); //To change body of generated methods, choose Tools | Templates.
}
private void checkSubsampler() {
if ((dvsSubsampler == null) || ((dimx * dimy) != dvsSubsampler.getnPixels())) {
if ((aviOutputStream != null) && (dvsSubsampler != null)) {
log.info("closing existing output file because output resolution has changed");
doCloseFile();
}
dvsSubsampler = new DvsSubsamplerToFrame(dimx, dimy, grayScale);
}
}
private BufferedImage toImage(DvsSubsamplerToFrame subSampler) {
BufferedImage bi = new BufferedImage(dimx, dimy, BufferedImage.TYPE_INT_BGR);
int[] bd = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData();
for (int y = 0; y < dimy; y++) {
for (int x = 0; x < dimx; x++) {
int b = (int) (255 * subSampler.getValueAtPixel(x, y));
int g = b;
int r = b;
int idx=((dimy - y - 1) * dimx) + x;
if(idx>=bd.length){
throw new RuntimeException(String.format("index %d out of bounds for x=%d y=%d",idx,x,y));
}
bd[idx] = (b << 16) | (g << 8) | r | 0xFF000000;
}
}
return bi;
}
synchronized public void maybeShowOutput(DvsSubsamplerToFrame subSampler) {
if (!showOutput) {
return;
}
if (frame == null) {
String windowName = "DVS target slice";
frame = new JFrame(windowName);
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
frame.setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
display = ImageDisplay.createOpenGLCanvas();
display.setBorderSpacePixels(10);
display.setImageSize(dimx, dimy);
display.setSize(200, 200);
panel.add(display);
frame.getContentPane().add(panel);
frame.pack();
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowOutput(false);
}
});
}
if (!frame.isVisible()) {
frame.setVisible(true);
}
if ((display.getWidth() != dimx) || (display.getHeight() != dimy)) {
display.setImageSize(dimx, dimy);
}
for (int x = 0; x < dimx; x++) {
for (int y = 0; y < dimy; y++) {
display.setPixmapGray(x, y, subSampler.getValueAtPixel(x, y));
}
}
display.repaint();
}
/**
* @return the dvsMinEvents
*/
public int getDvsMinEvents() {
return dvsMinEvents;
}
/**
* @param dvsMinEvents the dvsMinEvents to set
*/
public void setDvsMinEvents(int dvsMinEvents) {
this.dvsMinEvents = dvsMinEvents;
putInt("dvsMinEvents", dvsMinEvents);
}
/**
* @return the hotpixelCoumn
*/
public int getHotpixelCoumn() {
return hotpixelColumn;
}
/**
* @param dimx the dimx to set
*/
public void setHotpixelColumn(int hotpixelColumn) {
this.hotpixelColumn = hotpixelColumn;
putInt("hotpixelColumn", hotpixelColumn);
}
/**
* @return the dimx
*/
public int getDimx() {
return dimx;
}
/**
* @param dimx the dimx to set
*/
synchronized public void setDimx(int dimx) {
this.dimx = dimx;
putInt("dimx", dimx);
}
/**
* @return the dimy
*/
public int getDimy() {
return dimy;
}
/**
* @param dimy the dimy to set
*/
synchronized public void setDimy(int dimy) {
this.dimy = dimy;
putInt("dimy", dimy);
}
/**
* @return the showOutput
*/
public boolean isShowOutput() {
return showOutput;
}
/**
* @param showOutput the showOutput to set
*/
public void setShowOutput(boolean showOutput) {
boolean old = this.showOutput;
this.showOutput = showOutput;
putBoolean("showOutput", showOutput);
getSupport().firePropertyChange("showOutput", old, showOutput);
}
/**
* @return the maxTimeLastTargetLocationValidUs
*/
public int getMaxTimeLastTargetLocationValidUs() {
return maxTimeLastTargetLocationValidUs;
}
/**
* @param maxTimeLastTargetLocationValidUs the
* maxTimeLastTargetLocationValidUs to set
*/
public void setMaxTimeLastTargetLocationValidUs(int maxTimeLastTargetLocationValidUs) {
if (maxTimeLastTargetLocationValidUs < minTargetPointIntervalUs) {
maxTimeLastTargetLocationValidUs = minTargetPointIntervalUs;
}
this.maxTimeLastTargetLocationValidUs = maxTimeLastTargetLocationValidUs;
putInt("maxTimeLastTargetLocationValidUs", maxTimeLastTargetLocationValidUs);
}
/**
* @return the grayScale
*/
public int getGrayScale() {
return grayScale;
}
private int getFractionOfFileDuration(int timestamp) {
if (inputStreamDuration == 0) {
return 0;
}
return (int) Math.floor((N_FRACTIONS * ((float) (timestamp - firstInputStreamTimestamp))) / inputStreamDuration);
}
private void markDataHasTarget(int timestamp) {
if (inputStreamDuration == 0) {
return;
}
int frac = getFractionOfFileDuration(timestamp);
if ((frac < 0) || (frac >= labeledFractions.length)) {
log.warning("fraction " + frac + " is out of range " + labeledFractions.length + ", something is wrong");
return;
}
labeledFractions[frac] = true;
targetPresentInFractions[frac] = true;
}
/**
* @param grayScale the grayScale to set
*/
public void setGrayScale(int grayScale) {
if (grayScale < 1) {
grayScale = 1;
}
this.grayScale = grayScale;
putInt("grayScale", grayScale);
if (dvsSubsampler != null) {
dvsSubsampler.setColorScale(grayScale);
}
}
synchronized public void doLoadLocations() {
lastFileName = mapDataFilenameToTargetFilename.get(lastDataFilename);
if (lastFileName == null) {
lastFileName = DEFAULT_FILENAME;
}
if ((lastFileName != null) && lastFileName.equals(DEFAULT_FILENAME)) {
File f = chip.getAeViewer().getRecentFiles().getMostRecentFile();
if (f == null) {
lastFileName = DEFAULT_FILENAME;
} else {
lastFileName = f.getPath();
}
}
JFileChooser c = new JFileChooser(lastFileName);
c.setFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
}
@Override
public String getDescription() {
return "Text target label files";
}
});
c.setMultiSelectionEnabled(false);
c.setSelectedFile(new File(lastFileName));
ChipCanvas chipCanvas = chip.getCanvas();
GLCanvas glCanvas = (GLCanvas) chipCanvas.getCanvas();
int ret = c.showOpenDialog(glCanvas);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
lastFileName = c.getSelectedFile().toString();
putString("lastFileName", lastFileName);
loadLocations(new File(lastFileName));
}
/**
* Loads last locations. Note that this is a lengthy operation
*/
synchronized public void loadLastLocations() {
if (lastFileName == null) {
return;
}
File f = new File(lastFileName);
if (!f.exists() || !f.isFile()) {
return;
}
loadLocations(f);
}
synchronized private void loadLocations(File f) {
log.info("loading " + f);
try {
setCursor(new Cursor(Cursor.WAIT_CURSOR));
targetLocations.clear();
minSampleTimestamp = Integer.MAX_VALUE;
maxSampleTimestamp = Integer.MIN_VALUE;
try {
BufferedReader reader = new BufferedReader(new FileReader(f));
String s = reader.readLine();
StringBuilder sb = new StringBuilder();
while ((s != null) && s.startsWith("#")) {
sb.append(s + "\n");
s = reader.readLine();
}
log.info("header lines on " + f.getAbsolutePath() + "are\n" + sb.toString());
while (s != null) {
Scanner scanner = new Scanner(s);
try {
int frame = scanner.nextInt();
int ts = scanner.nextInt();
int x = scanner.nextInt();
int y = scanner.nextInt();
int targetTypeID = 0;
int targetdimx = targetRadius;
int targetdimy = targetRadius;
try {
targetTypeID = scanner.nextInt();
try {
// added target dimensions compatibility
targetdimx = scanner.nextInt();
targetdimy = scanner.nextInt();
}catch (NoSuchElementException e) {
// older type file with only single target and no targetClassID and no x,y dimensions
}
} catch (NoSuchElementException e) {
// older type file with only single target
}
targetLocation = new TargetLocation(frame, ts,
new Point(x, y),
targetTypeID,
targetdimx,
targetdimy); // read target location
} catch (NoSuchElementException ex2) {
throw new IOException(("couldn't parse file " + f) == null ? "null" : f.toString() + ", got InputMismatchException on line: " + s);
}
if ((targetLocation.location.x == -1) && (targetLocation.location.y == -1)) {
targetLocation.location = null;
}
addSample(targetLocation.timestamp, targetLocation);
markDataHasTarget(targetLocation.timestamp);
if (targetLocation != null) {
if (targetLocation.timestamp > maxSampleTimestamp) {
maxSampleTimestamp = targetLocation.timestamp;
}
if (targetLocation.timestamp < minSampleTimestamp) {
minSampleTimestamp = targetLocation.timestamp;
}
}
s = reader.readLine();
}
log.info("done loading " + f);
if (lastDataFilename != null) {
mapDataFilenameToTargetFilename.put(lastDataFilename, f.getPath());
}
} catch (FileNotFoundException ex) {
ChipCanvas chipCanvas = chip.getCanvas();
GLCanvas glCanvas = (GLCanvas) chipCanvas.getCanvas();
JOptionPane.showMessageDialog(glCanvas, ("couldn't find file " + f) == null ? "null" : f.toString() + ": got exception " + ex.toString(), "Couldn't load locations",
JOptionPane.WARNING_MESSAGE, null);
} catch (IOException ex) {
ChipCanvas chipCanvas = chip.getCanvas();
GLCanvas glCanvas = (GLCanvas) chipCanvas.getCanvas();
JOptionPane.showMessageDialog(glCanvas, ("IOException with file " + f) == null ? "null" : f.toString() + ": got exception " + ex.toString(), "Couldn't load locations",
JOptionPane.WARNING_MESSAGE, null);
}
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
/**
* List of targets simultaneously present at a particular timestamp
*/
private class SimultaneouTargetLocations extends ArrayList<TargetLocation> {
}
/**
* @return the targetLocation
*/
public TargetLocation getTargetLocation() {
return targetLocation;
}
private void addSample(int timestamp, TargetLocation newTargetLocation) {
SimultaneouTargetLocations s = targetLocations.get(timestamp);
if (s == null) {
s = new SimultaneouTargetLocations();
targetLocations.put(timestamp, s);
}
s.add(newTargetLocation);
}
/**
* @return the writeDvsSliceImageOnApsFrame
*/
public boolean isWriteDvsSliceImageOnApsFrame() {
return writeDvsSliceImageOnApsFrame;
}
/**
* @return the doPositiveLabel
*/
public boolean isDoPositiveLabel() {
return doPositiveLabel;
}
/**
* @param writeDvsSliceImageOnApsFrame the writeDvsSliceImageOnApsFrame to
* set
*/
public void setDoPositiveLabel(boolean doPositiveLabel) {
this.doPositiveLabel = doPositiveLabel;
if(doPositiveLabel){
random_shift_x = 0;//Minx + (int)(Math.random() * ((Maxx - Minx) + 1));
random_shift_y = 0;//Minx + (int)(Math.random() * ((Maxx - Minx) + 1));
}else{
random_shift_x = dimx + (int)(Math.random() * (((2.0*dimx) - dimx) + 1));
random_shift_y = dimy + (int)(Math.random() * (((2.0*dimy) - dimy) + 1));
}
putBoolean("doPositiveLabel", doPositiveLabel);
}
/**
* @param writeDvsSliceImageOnApsFrame the writeDvsSliceImageOnApsFrame to
* set
*/
public void setWriteDvsSliceImageOnApsFrame(boolean writeDvsSliceImageOnApsFrame) {
this.writeDvsSliceImageOnApsFrame = writeDvsSliceImageOnApsFrame;
putBoolean("writeDvsSliceImageOnApsFrame", writeDvsSliceImageOnApsFrame);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ((evt.getPropertyName() == AEFrameChipRenderer.EVENT_NEW_FRAME_AVAILBLE)) {
AEFrameChipRenderer renderer=(AEFrameChipRenderer)evt.getNewValue();
endOfFrameTimestamp=renderer.getTimestampFrameEnd();
newFrameAvailable = true;
} else if (isCloseOnRewind() && (evt.getPropertyName() == AEInputStream.EVENT_REWIND)) {
doCloseFile();
}
}
private final Color[] targetTypeColors = {Color.BLUE, Color.CYAN, Color.GREEN, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED};
class TargetLocation {
int timestamp;
int frameNumber;
Point location; // center of target location
int targetClassID; // class of target, i.e. car, person
int dimx; // dimension of target x
int dimy; // y
public TargetLocation(int frameNumber, int timestamp, Point location, int targetTypeID, int dimx, int dimy) {
this.frameNumber = frameNumber;
this.timestamp = timestamp;
this.location = location != null ? new Point(location) : null;
this.targetClassID = targetTypeID;
this.dimx = dimx;
this.dimy = dimy;
}
private void draw(GLAutoDrawable drawable, GL2 gl) {
GLU glu = new GLU();
gl.glPushMatrix();
gl.glTranslatef(location.x, location.y, 0f);
float[] compArray = new float[4];
gl.glColor3fv(targetTypeColors[targetClassID % targetTypeColors.length].getColorComponents(compArray), 0);
if (mouseQuad == null) {
mouseQuad = glu.gluNewQuadric();
}
glu.gluQuadricDrawStyle(mouseQuad, GLU.GLU_LINE);
glu.gluDisk(mouseQuad, dimx/2, (dimy/2) +1, 32, 1);
//System.out.println(String.format("(%d,%d,%d,%d)", dimx/2, (dimy/2) + 1, 32, 1));
gl.glPopMatrix();
}
@Override
public String toString() {
return String.format("TargetLocation frameNumber=%d timestamp=%d location=%s", frameNumber, timestamp, location == null ?
"null" : location.toString());
}
}
}
|
jAER: Slicer AVI Writer with target tracker for region of interests
git-svn-id: fe6b3b33f0410f5f719dcd9e0c58b92353e7a5d3@7313 b7f4320f-462c-0410-a916-d9f35bb82d52
|
src/net/sf/jaer/util/avioutput/DvsSliceTargetAviWriter.java
|
jAER: Slicer AVI Writer with target tracker for region of interests
|
|
Java
|
lgpl-2.1
|
7385f24da4e17b07f4010ed48518753110d6efd0
| 0
|
xph906/SootNew,mbenz89/soot,xph906/SootNew,anddann/soot,mbenz89/soot,anddann/soot,plast-lab/soot,mbenz89/soot,cfallin/soot,plast-lab/soot,cfallin/soot,cfallin/soot,xph906/SootNew,xph906/SootNew,cfallin/soot,anddann/soot,plast-lab/soot,anddann/soot,mbenz89/soot
|
/* Soot - a J*va Optimization Framework
* Copyright (C) 2003 Jennifer Lhotak
*
* 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.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package ca.mcgill.sable.soot.launching;
import org.eclipse.ui.*;
import org.eclipse.jface.dialogs.*;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.viewers.*;
import org.eclipse.jface.action.*;
import org.eclipse.core.runtime.*;
import java.lang.reflect.InvocationTargetException;
import ca.mcgill.sable.soot.*;
import org.eclipse.swt.widgets.*;
import java.util.*;
/**
* Main Soot Launcher. Handles running Soot directly (or as a
* process)
*/
public class SootLauncher implements IWorkbenchWindowActionDelegate {
private IWorkbenchPart part;
protected IWorkbenchWindow window;
private ISelection selection;
private IStructuredSelection structured;
protected String platform_location;
protected String external_jars_location;
public SootClasspath sootClasspath = new SootClasspath();
public SootSelection sootSelection;
//private IFolder sootOutputFolder;
private SootCommandList sootCommandList;
private String outputLocation;
private SootDefaultCommands sdc;
private SootOutputFilesHandler fileHandler;
private DavaHandler davaHandler;
public void run(IAction action) {
setSootSelection(new SootSelection(structured));
getSootSelection().initialize();
setFileHandler(new SootOutputFilesHandler(window));
getFileHandler().resetSootOutputFolder(getSootSelection().getProject());
//System.out.println("starting SootLauncher");
setDavaHandler(new DavaHandler());
getDavaHandler().setSootOutputFolder(getFileHandler().getSootOutputFolder());
getDavaHandler().handleBefore();
initPaths();
initCommandList();
}
private void initCommandList() {
setSootCommandList(new SootCommandList());
}
protected void runSootDirectly(){
runSootDirectly("soot.Main");
}
private void sendSootOutputEvent(String toSend){
SootOutputEvent send = new SootOutputEvent(this, ISootOutputEventConstants.SOOT_NEW_TEXT_EVENT);
send.setTextToAppend(toSend);
final SootOutputEvent sendFinal = send;
Display.getCurrent().asyncExec(new Runnable(){
public void run() {
SootPlugin.getDefault().fireSootOutputEvent(sendFinal);
};
});
}
protected void runSootDirectly(String mainClass) {
int length = getSootCommandList().getList().size();
//Object [] temp = getSootCommandList().getList().toArray();
String temp [] = new String [length];
getSootCommandList().getList().toArray(temp);
sendSootOutputEvent(mainClass);
sendSootOutputEvent(" ");
final String [] cmdAsArray = temp;
for (int i = 0; i < temp.length; i++) {
//System.out.println(temp[i]);
sendSootOutputEvent(temp[i]);
sendSootOutputEvent(" ");
}
sendSootOutputEvent("\n");
//System.out.println("about to make list be array of strings");
//final String [] cmdAsArray = (String []) temp;
IRunnableWithProgress op;
try {
newProcessStarting();
op = new SootRunner(temp, Display.getCurrent(), mainClass);
ModalContext.run(op, true, new NullProgressMonitor(), Display.getCurrent());
}
catch (InvocationTargetException e1) {
// handle exception
System.out.println("InvocationTargetException: "+e1.getMessage());
}
catch (InterruptedException e2) {
// handle cancelation
System.out.println("InterruptedException: "+e2.getMessage());
//op.getProc().destroy();
}
}
protected void runSootAsProcess(String cmd) {
SootProcessRunner op;
try {
newProcessStarting();
op = new SootProcessRunner(Display.getCurrent(), cmd, sootClasspath);
if (window == null) {
window = SootPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow();
}
new ProgressMonitorDialog(window.getShell()).run(true, true, op);
}
catch (InvocationTargetException e1) {
// handle exception
}
catch (InterruptedException e2) {
// handle cancelation
System.out.println(e2.getMessage());
//op.getProc().destroy();
}
}
private void newProcessStarting() {
SootOutputEvent clear_event = new SootOutputEvent(this, ISootOutputEventConstants.SOOT_CLEAR_EVENT);
SootPlugin.getDefault().fireSootOutputEvent(clear_event);
SootOutputEvent se = new SootOutputEvent(this, ISootOutputEventConstants.SOOT_NEW_TEXT_EVENT);
se.setTextToAppend("Starting ...");
SootPlugin.getDefault().fireSootOutputEvent(se);
}
private String[] formCmdLine(String cmd) {
StringTokenizer st = new StringTokenizer(cmd);
int count = st.countTokens();
String[] cmdLine = new String[count];
count = 0;
while(st.hasMoreTokens()) {
cmdLine[count++] = st.nextToken();
//System.out.println(cmdLine[count-1]);
}
return cmdLine;
}
private void initPaths() {
sootClasspath.initialize();
// platform location
//platform_location = Platform.getLocation().toOSString();
platform_location = getSootSelection().getJavaProject().getProject().getLocation().toOSString();
System.out.println("platform_location: "+platform_location);
platform_location = platform_location.substring(0, platform_location.lastIndexOf(System.getProperty("file.separator")));
System.out.println("platform_location: "+platform_location);
// external jars location - may need to change don't think I use this anymore
external_jars_location = Platform.getLocation().removeLastSegments(2).toOSString();
setOutputLocation(platform_location+getFileHandler().getSootOutputFolder().getFullPath().toOSString());
}
public void runFinish() {
getFileHandler().refreshFolder();
//for updating markers
SootPlugin.getDefault().getManager().updateSootRanFlag();
//getDavaHandler().handleAfter();
//getFileHandler().handleFilesChanged();
}
public IStructuredSelection getStructured() {
return structured;
}
private void setStructured(IStructuredSelection struct) {
structured = struct;
}
public void init(IWorkbenchWindow window) {
this.window = window;
}
public void dispose() {
}
public void selectionChanged(IAction action, ISelection selection) {
this.selection = selection;
if (selection instanceof IStructuredSelection){
setStructured((IStructuredSelection)selection);
}
}
/**
* Returns the sootClasspath.
* @return SootClasspath
*/
public SootClasspath getSootClasspath() {
return sootClasspath;
}
/**
* Sets the sootClasspath.
* @param sootClasspath The sootClasspath to set
*/
public void setSootClasspath(SootClasspath sootClasspath) {
this.sootClasspath = sootClasspath;
}
/**
* Returns the sootSelection.
* @return SootSelection
*/
public SootSelection getSootSelection() {
return sootSelection;
}
/**
* Sets the sootSelection.
* @param sootSelection The sootSelection to set
*/
public void setSootSelection(SootSelection sootSelection) {
this.sootSelection = sootSelection;
}
/**
* Returns the window.
* @return IWorkbenchWindow
*/
public IWorkbenchWindow getWindow() {
return window;
}
/**
* Returns the sootCommandList.
* @return SootCommandList
*/
public SootCommandList getSootCommandList() {
return sootCommandList;
}
/**
* Sets the sootCommandList.
* @param sootCommandList The sootCommandList to set
*/
public void setSootCommandList(SootCommandList sootCommandList) {
this.sootCommandList = sootCommandList;
}
/**
* Returns the output_location.
* @return String
*/
public String getOutputLocation() {
return outputLocation;
}
/**
* Sets the output_location.
* @param output_location The output_location to set
*/
public void setOutputLocation(String outputLocation) {
this.outputLocation = outputLocation;
}
/**
* Returns the sdc.
* @return SootDefaultCommands
*/
public SootDefaultCommands getSdc() {
return sdc;
}
/**
* Sets the sdc.
* @param sdc The sdc to set
*/
public void setSdc(SootDefaultCommands sdc) {
this.sdc = sdc;
}
/**
* Returns the fileHandler.
* @return SootOutputFilesHandler
*/
public SootOutputFilesHandler getFileHandler() {
return fileHandler;
}
/**
* Sets the fileHandler.
* @param fileHandler The fileHandler to set
*/
public void setFileHandler(SootOutputFilesHandler fileHandler) {
this.fileHandler = fileHandler;
}
/**
* @return
*/
public DavaHandler getDavaHandler() {
return davaHandler;
}
/**
* @param handler
*/
public void setDavaHandler(DavaHandler handler) {
davaHandler = handler;
}
}
|
eclipse/ca.mcgill.sable.soot/src/ca/mcgill/sable/soot/launching/SootLauncher.java
|
/* Soot - a J*va Optimization Framework
* Copyright (C) 2003 Jennifer Lhotak
*
* 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.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package ca.mcgill.sable.soot.launching;
import org.eclipse.ui.*;
import org.eclipse.jface.dialogs.*;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.viewers.*;
import org.eclipse.jface.action.*;
import org.eclipse.core.runtime.*;
import java.lang.reflect.InvocationTargetException;
import ca.mcgill.sable.soot.*;
import org.eclipse.swt.widgets.*;
import java.util.*;
/**
* Main Soot Launcher. Handles running Soot directly (or as a
* process)
*/
public class SootLauncher implements IWorkbenchWindowActionDelegate {
private IWorkbenchPart part;
protected IWorkbenchWindow window;
private ISelection selection;
private IStructuredSelection structured;
protected String platform_location;
protected String external_jars_location;
public SootClasspath sootClasspath = new SootClasspath();
public SootSelection sootSelection;
//private IFolder sootOutputFolder;
private SootCommandList sootCommandList;
private String outputLocation;
private SootDefaultCommands sdc;
private SootOutputFilesHandler fileHandler;
private DavaHandler davaHandler;
public void run(IAction action) {
setSootSelection(new SootSelection(structured));
getSootSelection().initialize();
setFileHandler(new SootOutputFilesHandler(window));
getFileHandler().resetSootOutputFolder(getSootSelection().getProject());
//System.out.println("starting SootLauncher");
setDavaHandler(new DavaHandler());
getDavaHandler().setSootOutputFolder(getFileHandler().getSootOutputFolder());
getDavaHandler().handleBefore();
initPaths();
initCommandList();
}
private void initCommandList() {
setSootCommandList(new SootCommandList());
}
protected void runSootDirectly(){
runSootDirectly("soot.Main");
}
private void sendSootOutputEvent(String toSend){
SootOutputEvent send = new SootOutputEvent(this, ISootOutputEventConstants.SOOT_NEW_TEXT_EVENT);
send.setTextToAppend(toSend);
final SootOutputEvent sendFinal = send;
Display.getCurrent().asyncExec(new Runnable(){
public void run() {
SootPlugin.getDefault().fireSootOutputEvent(sendFinal);
};
});
}
protected void runSootDirectly(String mainClass) {
int length = getSootCommandList().getList().size();
//Object [] temp = getSootCommandList().getList().toArray();
String temp [] = new String [length];
getSootCommandList().getList().toArray(temp);
sendSootOutputEvent(mainClass);
sendSootOutputEvent(" ");
final String [] cmdAsArray = temp;
for (int i = 0; i < temp.length; i++) {
//System.out.println(temp[i]);
sendSootOutputEvent(temp[i]);
sendSootOutputEvent(" ");
}
sendSootOutputEvent("\n");
//System.out.println("about to make list be array of strings");
//final String [] cmdAsArray = (String []) temp;
IRunnableWithProgress op;
try {
newProcessStarting();
op = new SootRunner(temp, Display.getCurrent(), mainClass);
ModalContext.run(op, true, new NullProgressMonitor(), Display.getCurrent());
}
catch (InvocationTargetException e1) {
// handle exception
System.out.println("InvocationTargetException: "+e1.getMessage());
}
catch (InterruptedException e2) {
// handle cancelation
System.out.println("InterruptedException: "+e2.getMessage());
//op.getProc().destroy();
}
}
protected void runSootAsProcess(String cmd) {
SootProcessRunner op;
try {
newProcessStarting();
op = new SootProcessRunner(Display.getCurrent(), cmd, sootClasspath);
if (window == null) {
window = SootPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow();
}
new ProgressMonitorDialog(window.getShell()).run(true, true, op);
}
catch (InvocationTargetException e1) {
// handle exception
}
catch (InterruptedException e2) {
// handle cancelation
System.out.println(e2.getMessage());
//op.getProc().destroy();
}
}
private void newProcessStarting() {
SootOutputEvent clear_event = new SootOutputEvent(this, ISootOutputEventConstants.SOOT_CLEAR_EVENT);
SootPlugin.getDefault().fireSootOutputEvent(clear_event);
SootOutputEvent se = new SootOutputEvent(this, ISootOutputEventConstants.SOOT_NEW_TEXT_EVENT);
se.setTextToAppend("Starting ...");
SootPlugin.getDefault().fireSootOutputEvent(se);
}
private String[] formCmdLine(String cmd) {
StringTokenizer st = new StringTokenizer(cmd);
int count = st.countTokens();
String[] cmdLine = new String[count];
count = 0;
while(st.hasMoreTokens()) {
cmdLine[count++] = st.nextToken();
//System.out.println(cmdLine[count-1]);
}
return cmdLine;
}
private void initPaths() {
sootClasspath.initialize();
// platform location
platform_location = Platform.getLocation().toOSString();
// external jars location - may need to change don't think I use this anymore
external_jars_location = Platform.getLocation().removeLastSegments(2).toOSString();
setOutputLocation(platform_location+getFileHandler().getSootOutputFolder().getFullPath().toOSString());
}
public void runFinish() {
getFileHandler().refreshFolder();
//for updating markers
SootPlugin.getDefault().getManager().updateSootRanFlag();
//getDavaHandler().handleAfter();
//getFileHandler().handleFilesChanged();
}
public IStructuredSelection getStructured() {
return structured;
}
private void setStructured(IStructuredSelection struct) {
structured = struct;
}
public void init(IWorkbenchWindow window) {
this.window = window;
}
public void dispose() {
}
public void selectionChanged(IAction action, ISelection selection) {
this.selection = selection;
if (selection instanceof IStructuredSelection){
setStructured((IStructuredSelection)selection);
}
}
/**
* Returns the sootClasspath.
* @return SootClasspath
*/
public SootClasspath getSootClasspath() {
return sootClasspath;
}
/**
* Sets the sootClasspath.
* @param sootClasspath The sootClasspath to set
*/
public void setSootClasspath(SootClasspath sootClasspath) {
this.sootClasspath = sootClasspath;
}
/**
* Returns the sootSelection.
* @return SootSelection
*/
public SootSelection getSootSelection() {
return sootSelection;
}
/**
* Sets the sootSelection.
* @param sootSelection The sootSelection to set
*/
public void setSootSelection(SootSelection sootSelection) {
this.sootSelection = sootSelection;
}
/**
* Returns the window.
* @return IWorkbenchWindow
*/
public IWorkbenchWindow getWindow() {
return window;
}
/**
* Returns the sootCommandList.
* @return SootCommandList
*/
public SootCommandList getSootCommandList() {
return sootCommandList;
}
/**
* Sets the sootCommandList.
* @param sootCommandList The sootCommandList to set
*/
public void setSootCommandList(SootCommandList sootCommandList) {
this.sootCommandList = sootCommandList;
}
/**
* Returns the output_location.
* @return String
*/
public String getOutputLocation() {
return outputLocation;
}
/**
* Sets the output_location.
* @param output_location The output_location to set
*/
public void setOutputLocation(String outputLocation) {
this.outputLocation = outputLocation;
}
/**
* Returns the sdc.
* @return SootDefaultCommands
*/
public SootDefaultCommands getSdc() {
return sdc;
}
/**
* Sets the sdc.
* @param sdc The sdc to set
*/
public void setSdc(SootDefaultCommands sdc) {
this.sdc = sdc;
}
/**
* Returns the fileHandler.
* @return SootOutputFilesHandler
*/
public SootOutputFilesHandler getFileHandler() {
return fileHandler;
}
/**
* Sets the fileHandler.
* @param fileHandler The fileHandler to set
*/
public void setFileHandler(SootOutputFilesHandler fileHandler) {
this.fileHandler = fileHandler;
}
/**
* @return
*/
public DavaHandler getDavaHandler() {
return davaHandler;
}
/**
* @param handler
*/
public void setDavaHandler(DavaHandler handler) {
davaHandler = handler;
}
}
|
- fixed problem of getting workspace location when there are multiple workspaces
|
eclipse/ca.mcgill.sable.soot/src/ca/mcgill/sable/soot/launching/SootLauncher.java
|
- fixed problem of getting workspace location when there are multiple workspaces
|
|
Java
|
lgpl-2.1
|
de331721936883cb90a2cef4642b801d513449b2
| 0
|
Arabidopsis-Information-Portal/intermine,tomck/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,elsiklab/intermine,zebrafishmine/intermine,justincc/intermine,kimrutherford/intermine,JoeCarlson/intermine,joshkh/intermine,drhee/toxoMine,tomck/intermine,zebrafishmine/intermine,JoeCarlson/intermine,JoeCarlson/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,drhee/toxoMine,tomck/intermine,tomck/intermine,justincc/intermine,drhee/toxoMine,joshkh/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,zebrafishmine/intermine,elsiklab/intermine,kimrutherford/intermine,justincc/intermine,justincc/intermine,zebrafishmine/intermine,kimrutherford/intermine,joshkh/intermine,tomck/intermine,drhee/toxoMine,joshkh/intermine,justincc/intermine,joshkh/intermine,drhee/toxoMine,JoeCarlson/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,zebrafishmine/intermine,drhee/toxoMine,elsiklab/intermine,kimrutherford/intermine,JoeCarlson/intermine,justincc/intermine,joshkh/intermine,elsiklab/intermine,justincc/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,joshkh/intermine,tomck/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,elsiklab/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,elsiklab/intermine,tomck/intermine,kimrutherford/intermine,justincc/intermine,zebrafishmine/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,zebrafishmine/intermine,drhee/toxoMine,elsiklab/intermine,JoeCarlson/intermine
|
package org.flymine.dataconversion;
/*
* Copyright (C) 2002-2004 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.io.FileReader;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.HashSet;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import org.intermine.InterMineException;
import org.intermine.xml.full.Attribute;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.Reference;
import org.intermine.xml.full.ReferenceList;
import org.intermine.xml.full.ItemHelper;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreFactory;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.ObjectStoreWriterFactory;
import org.intermine.dataconversion.ItemReader;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.dataconversion.DataTranslator;
import org.intermine.dataconversion.FieldNameAndValue;
import org.intermine.dataconversion.ItemPrefetchDescriptor;
import org.intermine.dataconversion.ItemPrefetchConstraintDynamic;
import org.intermine.dataconversion.ObjectStoreItemPathFollowingImpl;
import org.intermine.dataconversion.ObjectStoreItemReader;
import org.intermine.dataconversion.ObjectStoreItemWriter;
import org.intermine.util.XmlUtil;
import org.apache.log4j.Logger;
/**
* Convert Ensembl data in fulldata Item format conforming to a source OWL definition
* to fulldata Item format conforming to InterMine OWL definition.
*
* @author Wenyan Ji
* @author Richard Smith
* @author Andrew Varley
* @author Mark Woodbridge
*/
public class EnsemblHumanDataTranslator extends DataTranslator
{
protected static final Logger LOG = Logger.getLogger(EnsemblHumanDataTranslator.class);
private Item ensemblDb;
private Reference ensemblRef;
private Item emblDb;
private Reference emblRef;
private Item tremblDb;
private Reference tremblRef;
private Item swissprotDb;
private Reference swissprotRef;
private Item flybaseDb;
private Reference flybaseRef;
private Item refSeqDb;
private Reference refSeqRef;
private Item hugoDb;
private Reference hugoRef;
private Item genbankDb;
private Reference genbankRef;
private Item gdbDb;
private Reference gdbRef;
private Item unistsDb;
private Reference unistsRef;
private Map supercontigs = new HashMap();
private Map scLocs = new HashMap();
private String orgAbbrev;
private Item organism;
private Reference orgRef;
private Map proteins = new HashMap();
private Map proteinIds = new HashMap();
private Set proteinSynonyms = new HashSet();
private Map chr2Contig = new HashMap();
private Map sc2Contig = new HashMap();
private Map clone2Contig = new HashMap();
private Set chrSet = new HashSet();
private Set scSet = new HashSet();
private Set contigSet = new HashSet();
private Set cloneSet = new HashSet();
private Map seqIdMap = new HashMap();
/**
* @see DataTranslator#DataTranslator
*/
public EnsemblHumanDataTranslator(ItemReader srcItemReader, OntModel model, String ns,
String orgAbbrev) {
super(srcItemReader, model, ns);
this.orgAbbrev = orgAbbrev;
}
/**
* @see DataTranslator#translate
*/
public void translate(ItemWriter tgtItemWriter)
throws ObjectStoreException, InterMineException {
tgtItemWriter.store(ItemHelper.convert(getOrganism()));
tgtItemWriter.store(ItemHelper.convert(getEnsemblDb()));
tgtItemWriter.store(ItemHelper.convert(getEmblDb()));
tgtItemWriter.store(ItemHelper.convert(getTremblDb()));
tgtItemWriter.store(ItemHelper.convert(getSwissprotDb()));
tgtItemWriter.store(ItemHelper.convert(getHugoDb()));
tgtItemWriter.store(ItemHelper.convert(getRefSeqDb()));
tgtItemWriter.store(ItemHelper.convert(getGenbankDb()));
tgtItemWriter.store(ItemHelper.convert(getGdbDb()));
tgtItemWriter.store(ItemHelper.convert(getUnistsDb()));
super.translate(tgtItemWriter);
Iterator i = proteins.values().iterator();
while (i.hasNext()) {
tgtItemWriter.store(ItemHelper.convert((Item) i.next()));
}
i = proteinSynonyms.iterator();
while (i.hasNext()) {
tgtItemWriter.store(ItemHelper.convert((Item) i.next()));
}
if (flybaseDb != null) {
tgtItemWriter.store(ItemHelper.convert(flybaseDb));
}
}
/**
* @see DataTranslator#translateItem
*/
protected Collection translateItem(Item srcItem)
throws ObjectStoreException, InterMineException {
Collection result = new HashSet();
String srcNs = XmlUtil.getNamespaceFromURI(srcItem.getClassName());
String className = XmlUtil.getFragmentFromURI(srcItem.getClassName());
Collection translated = super.translateItem(srcItem);
if (translated != null) {
for (Iterator i = translated.iterator(); i.hasNext();) {
boolean storeTgtItem = true;
Item tgtItem = (Item) i.next();
if ("karyotype".equals(className)) {
tgtItem.addReference(getOrgRef());
Item location = createLocation(srcItem, tgtItem, true);
location.addAttribute(new Attribute("strand", "0"));
result.add(location);
} else if ("exon".equals(className)) {
tgtItem.addReference(getOrgRef());
Item stableId = getStableId("exon", srcItem.getIdentifier(), srcNs);
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", "identifier");
}
addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false);
Item location = createLocation(srcItem, tgtItem, true);
result.add(location);
} else if ("gene".equals(className)) {
tgtItem.addReference(getOrgRef());
addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false);
Item location = createLocation(srcItem, tgtItem, true);
result.add(location);
Item anaResult = createAnalysisResult(srcItem, tgtItem);
result.add(anaResult);
List comments = getCommentIds(srcItem.getIdentifier(), srcNs);
if (!comments.isEmpty()) {
tgtItem.addCollection(new ReferenceList("comments", comments));
}
// gene name should be its stable id (or identifier if none)
Item stableId = null;
stableId = getStableId("gene", srcItem.getIdentifier(), srcNs);
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", "identifier");
} else {
tgtItem.addAttribute(new Attribute("identifier", srcItem.getIdentifier()));
}
// display_xref is gene name (?)
//promoteField(tgtItem, srcItem, "name", "display_xref", "display_label");
result.addAll(setGeneSynonyms(srcItem, tgtItem, srcNs));
// if no organismDbId set to be same as identifier
if (!tgtItem.hasAttribute("organismDbId")) {
tgtItem.addAttribute(new Attribute("organismDbId",
tgtItem.getAttribute("identifier").getValue()));
}
} else if ("transcript".equals(className)) {
tgtItem.addReference(getOrgRef());
Item geneRelation = createItem(tgtNs + "SimpleRelation", "");
addReferencedItem(tgtItem, geneRelation, "objects", true, "subject", false);
moveField(srcItem, geneRelation, "gene", "object");
result.add(geneRelation);
// if no identifier set the identifier as name (primary key)
if (!tgtItem.hasAttribute("identifier")) {
Item stableId = getStableId("transcript", srcItem.getIdentifier(), srcNs);
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", "identifier");
} else {
tgtItem.addAttribute(new Attribute("identifier",
srcItem.getIdentifier()));
}
}
Item location = createLocation(srcItem, tgtItem, true);
result.add(location);
} else if ("translation".equals(className)) {
Item protein = getProteinByPrimaryAccession(srcItem, srcNs);
//transcript translation subject object?
if (srcItem.hasReference("transcript")) {
String transcriptId = srcItem.getReference("transcript").getRefId();
Item transRelation = createItem(tgtNs + "SimpleRelation", "");
transRelation.addReference(new Reference("subject", transcriptId));
addReferencedItem(protein, transRelation, "subjects", true,
"object", false);
result.add(transRelation);
}
storeTgtItem = false;
// stable_ids become syonyms, need ensembl Database as source
} else if (className.endsWith("_stable_id")) {
if (className.endsWith("translation_stable_id")) {
storeTgtItem = false;
} else {
tgtItem.addReference(getEnsemblRef());
tgtItem.addAttribute(new Attribute("type", "accession"));
}
// } else if ("prediction_transcript".equals(className)) {
// tgtItem.addReference(getOrgRef());
// result.add(createLocation(srcItem, tgtItem, true));
} else if ("repeat_feature".equals(className)) {
tgtItem.addReference(getOrgRef());
result.add(createAnalysisResult(srcItem, tgtItem));
result.add(createLocation(srcItem, tgtItem, true));
promoteField(tgtItem, srcItem, "consensus", "repeat_consensus",
"repeat_consensus");
promoteField(tgtItem, srcItem, "type", "repeat_consensus", "repeat_class");
promoteField(tgtItem, srcItem, "identifier", "repeat_consensus", "repeat_name");
} else if ("marker".equals(className)) {
Set locations = createLocations(srcItem, tgtItem, srcNs);
List locationIds = new ArrayList();
for (Iterator j = locations.iterator(); j.hasNext(); ) {
Item location = (Item) j.next();
locationIds.add(location.getIdentifier());
result.add(location);
}
//tgtItem.addCollection(new ReferenceList("locations", locationIds));
setNameAttribute(srcItem, tgtItem);
//setSynonym
} else if ("marker_synonym".equals(className)) {
tgtItem.addAttribute(new Attribute("type", "accession"));
if (srcItem.hasAttribute("source")) {
String source = srcItem.getAttribute("source").getValue();
if (source.equals("genbank")) {
tgtItem.addReference(getGenbankRef());
} else if (source.equals("gdb")) {
tgtItem.addReference(getGdbRef());
} else if (source.equals("unists")) {
tgtItem.addReference(getUnistsRef());
} else {
tgtItem.addReference(getEnsemblRef());
}
} else {
tgtItem.addReference(getEnsemblRef());
}
}
if (storeTgtItem) {
result.add(tgtItem);
}
}
// assembly maps to null but want to create location on a supercontig
} else if ("assembly".equals(className)) {
Item location = createAssemblyLocation(srcItem);
result.add(location);
// seq_region map to null, become Chromosome, Supercontig, Clone and Contig respectively
} else if ("seq_region".equals(className)) {
Item seq = getSeqItem(srcItem.getIdentifier());
result.add(seq);
//simple_feature map to null, become TRNA/CpGIsland depending on analysis_id(logic_name)
} else if ("simple_feature".equals(className)) {
Item simpleFeature = createSimpleFeature(srcItem);
result.add(simpleFeature);
result.add(createLocation(srcItem, simpleFeature, true));
result.add(createAnalysisResult(srcItem, simpleFeature));
}
return result;
}
/**
* Translate a "located" Item into an Item and a location
* @param srcItem the source Item
* @param tgtItem the target Item (after translation)
* @param srcItemIsChild true if srcItem should be subject of Location
* @throws ObjectStoreException when anything goes wrong.
* @return the location item
*/
protected Item createLocation(Item srcItem, Item tgtItem, boolean srcItemIsChild)
throws ObjectStoreException {
String namespace = XmlUtil.getNamespaceFromURI(tgtItem.getClassName());
Item location = createItem(namespace + "Location", "");
Item seq = new Item();
moveField(srcItem, location, "seq_region_start", "start");
moveField(srcItem, location, "seq_region_end", "end");
location.addAttribute(new Attribute("startIsPartial", "false"));
location.addAttribute(new Attribute("endIsPartial", "false"));
if (srcItem.hasAttribute("seq_region_strand")) {
moveField(srcItem, location, "seq_region_strand", "strand");
}
if (srcItem.hasAttribute("phase")) {
moveField(srcItem, location, "phase", "phase");
}
if (srcItem.hasAttribute("end_phase")) {
moveField(srcItem, location, "end_phase", "endPhase");
}
if (srcItem.hasAttribute("ori")) {
moveField(srcItem, location, "ori", "strand");
}
if (srcItem.hasReference("seq_region")) {
String refId = srcItem.getReference("seq_region").getRefId();
seq = (Item) getSeqItem(refId);
}
if (srcItemIsChild) {
addReferencedItem(tgtItem, location, "objects", true, "subject", false);
location.addReference(new Reference("object", seq.getIdentifier()));
//moveField(srcItem, location, "seq_region", "object");
} else {
addReferencedItem(tgtItem, location, "subjects", true, "object", false);
location.addReference(new Reference("subject", seq.getIdentifier()));
//moveField(srcItem, location, "seq_region", "subject");
}
return location;
}
/**
* @param srcItem ensembl:marker
* @param tgtItem flymine:Marker
* @param srcNs source namespace
* @throws ObjectStoreException when anything goes wrong.
* @return set of locations
*/
protected Set createLocations(Item srcItem, Item tgtItem, String srcNs)
throws ObjectStoreException {
Set result = new HashSet();
Set constraints = new HashSet();
String value = srcItem.getIdentifier();
constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
srcNs + "marker_feature", false));
constraints.add(new FieldNameAndValue("marker", value, true));
Item location = new Item();
for (Iterator i = srcItemReader.getItemsByDescription(constraints).iterator();
i.hasNext(); ) {
Item feature = ItemHelper.convert((org.intermine.model.fulldata.Item) i.next());
location = createLocation(feature, tgtItem, true);
result.add(location);
}
return result;
}
/**
* @param srcItem ensembl:marker
* @param tgtItem flymine:Marker
* @throws ObjectStoreException when anything goes wrong.
*/
protected void setNameAttribute(Item srcItem, Item tgtItem) throws ObjectStoreException {
if (srcItem.hasReference("display_marker_synonym")) {
Item synonym = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("display_marker_synonym").getRefId()));
if (synonym.hasAttribute("name")) {
String name = synonym.getAttribute("name").getValue();
tgtItem.addAttribute(new Attribute("name", name));
}
}
}
/**
* @param srcItem = assembly
* @return location item which reflects the relations between chromosome and contig,
* supercontig and contig, clone and contig
* @throws ObjectStoreException when anything goes wrong.
*/
protected Item createAssemblyLocation(Item srcItem) throws ObjectStoreException {
int start, end, asmStart, cmpStart, asmEnd, cmpEnd, contigLength;
String ori, contigId, bioEntityId;
contigId = srcItem.getReference("cmp_seq_region").getRefId();
bioEntityId = srcItem.getReference("asm_seq_region").getRefId();
Item contig = ItemHelper.convert(srcItemReader.getItemById(contigId));
Item bioEntity = ItemHelper.convert(srcItemReader.getItemById(bioEntityId));
contigLength = Integer.parseInt(contig.getAttribute("length").getValue());
asmStart = Integer.parseInt(srcItem.getAttribute("asm_start").getValue());
cmpStart = Integer.parseInt(srcItem.getAttribute("cmp_start").getValue());
asmEnd = Integer.parseInt(srcItem.getAttribute("asm_end").getValue());
cmpEnd = Integer.parseInt(srcItem.getAttribute("cmp_end").getValue());
ori = srcItem.getAttribute("ori").getValue();
if (ori.equals("1")) {
start = asmStart - cmpStart + 1;
end = start + contigLength - 1;
} else {
if (cmpEnd == contigLength) {
start = asmStart;
end = start + contigLength - 1;
} else {
start = asmStart - (contigLength - cmpEnd);
end = start + contigLength - 1;
}
}
Item location = createItem(tgtNs + "Location", "");
location.addAttribute(new Attribute("start", Integer.toString(start)));
location.addAttribute(new Attribute("end", Integer.toString(end)));
location.addAttribute(new Attribute("startIsPartial", "false"));
location.addAttribute(new Attribute("endIsPartial", "false"));
location.addAttribute(new Attribute("strand", srcItem.getAttribute("ori").getValue()));
Item seq = new Item();
seq = (Item) getSeqItem(contigId);
location.addReference(new Reference("subject", seq.getIdentifier()));
seq = (Item) getSeqItem(bioEntityId);
location.addReference(new Reference("object", seq.getIdentifier()));
return location;
}
/**
* @param refId = refId for the seq_region
* @return seq item it could be chromosome, supercontig, clone or contig
* @throws ObjectStoreException when anything goes wrong.
*/
protected Item getSeqItem(String refId) throws ObjectStoreException {
Item seq = new Item();
Item seqRegion = ItemHelper.convert(srcItemReader.getItemById(refId));
if (seqIdMap.containsKey(refId)) {
seq = (Item) seqIdMap.get(refId);
} else {
String property = null;
if (seqRegion.hasReference("coord_system")) {
Item coord = ItemHelper.convert(srcItemReader.getItemById(
seqRegion.getReference("coord_system").getRefId()));
if (coord.hasAttribute("name")) {
property = coord.getAttribute("name").getValue();
}
}
if (property != null && property != "") {
String s = (property.substring(0, 1)).toUpperCase().concat(property.substring(1));
seq = createItem(tgtNs + s, "");
if (seqRegion.hasAttribute("name")) {
seq.addAttribute(new Attribute("identifier",
seqRegion.getAttribute("name").getValue()));
}
if (seqRegion.hasAttribute("length")) {
seq.addAttribute(new Attribute("length",
seqRegion.getAttribute("length").getValue()));
}
seqIdMap.put(refId, seq);
}
}
return seq;
}
/**
* Create an AnalysisResult pointed to by tgtItem evidence reference. Move srcItem
* analysis reference and score to new AnalysisResult.
* @param srcItem item in src namespace to move fields from
* @param tgtItem item that will reference AnalysisResult
* @throws ObjectStoreException when anything goes wrong.
* @return new AnalysisResult item
*/
protected Item createAnalysisResult(Item srcItem, Item tgtItem) throws ObjectStoreException {
Item result = createItem(tgtNs + "ComputationalResult", "");
if (srcItem.hasAttribute("analysis")) {
moveField(srcItem, result, "analysis", "analysis");
}
if (srcItem.hasAttribute("score")) {
moveField(srcItem, result, "score", "score"); //gene
}
result.addReference(getEnsemblRef());
ReferenceList evidence = new ReferenceList("evidence", Arrays.asList(new Object[]
{result.getIdentifier(), getEnsemblDb().getIdentifier()}));
tgtItem.addCollection(evidence);
return result;
}
/**
* Create a simpleFeature item depends on the logic_name attribute in analysis
* will become TRNA, or CpGIsland
* @param srcItem ensembl: simple_feature
* @return new simpleFeature item
* @throws ObjectStoreException when anything goes wrong.
*/
protected Item createSimpleFeature(Item srcItem) throws ObjectStoreException {
Item simpleFeature = new Item();
if (srcItem.hasReference("analysis")) {
Item analysis = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("analysis").getRefId()));
if (analysis.hasAttribute("logic_name")) {
String name = analysis.getAttribute("logic_name").getValue();
if (name.equals("tRNAscan")) {
simpleFeature = createItem(tgtNs + "TRNA", "");
} else if (name.equals("CpG")) {
simpleFeature = createItem(tgtNs + "CpGIsland", "");
} else if (name.equals("Eponine")) {
simpleFeature = createItem(tgtNs + "TranscriptionStartSite", "");
} else if (name.equals("FirstEF")) {
//5 primer exon and promoter including coding and noncoding
}
simpleFeature.addReference(getOrgRef());
}
}
return simpleFeature;
}
/**
* @param String id = translation id
* @param String srcNs sourceNamespace
* @return String chosenProteinId
* throws ObjectStoreExceptions if anything goes wrong
*/
private String getChosenProteinId(String id, String srcNs) throws ObjectStoreException {
String chosenId = (String) proteinIds.get(id);
if (chosenId == null) {
Item translation = ItemHelper.convert(srcItemReader.getItemById(id));
chosenId = getProteinByPrimaryAccession(translation, srcNs).getIdentifier();
proteinIds.put(id, chosenId);
}
return chosenId;
}
/**
* @param Item srcItem = e:translation
* @param String srcNs sourceNamespace
* @return Item for :Protein
* @throws ObjectStoreExceptions if anything goes wrong
*/
private Item getProteinByPrimaryAccession(Item srcItem, String srcNs)
throws ObjectStoreException {
Item protein = createItem(tgtNs + "Protein", "");
Set synonyms = new HashSet();
String value = srcItem.getIdentifier();
String swissProtId = null;
String tremblId = null;
String emblId = null;
if (srcItem.hasReference("transcript")) {
Item transcript = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("transcript").getRefId()));
if (transcript.hasReference("display_xref")) {
Item xref = ItemHelper.convert(srcItemReader.getItemById(
transcript.getReference("display_xref").getRefId()));
String accession = null;
String dbname = null;
if (xref != null) {
accession = xref.getAttribute("dbprimary_acc").getValue();
Item externalDb = ItemHelper.convert(srcItemReader
.getItemById(xref.getReference("external_db").getRefId()));
if (externalDb != null) {
dbname = externalDb.getAttribute("db_name").getValue();
}
}
//LOG.error("processing: " + accession + ", " + dbname);
if (accession != null && !accession.equals("")
&& dbname != null && !dbname.equals("")) {
if (dbname.equals("Uniprot/SWISSPROT")) { //Uniprot/SWISSPROT
swissProtId = accession;
Item synonym = createItem(tgtNs + "Synonym", "");
addReferencedItem(protein, synonym, "synonyms", true, "subject", false);
synonym.addAttribute(new Attribute("value", accession));
synonym.addAttribute(new Attribute("type", "accession"));
synonym.addReference(getSwissprotRef());
synonyms.add(synonym);
} else if (dbname.equals("Uniprot/SPTREMBL")) { // Uniprot/SPTREMBL
tremblId = accession;
Item synonym = createItem(tgtNs + "Synonym", "");
addReferencedItem(protein, synonym, "synonyms", true, "subject", false);
synonym.addAttribute(new Attribute("value", accession));
synonym.addAttribute(new Attribute("type", "accession"));
synonym.addReference(getTremblRef());
synonyms.add(synonym);
} else if (dbname.equals("protein_id")) {
emblId = accession;
Item synonym = createItem(tgtNs + "Synonym", "");
addReferencedItem(protein, synonym, "synonyms", true, "subject", false);
synonym.addAttribute(new Attribute("value", accession));
synonym.addAttribute(new Attribute("type", "accession"));
synonym.addReference(getEmblRef());
synonyms.add(synonym);
} else if (dbname.equals("prediction_SPTREMBL")) {
emblId = accession;
Item synonym = createItem(tgtNs + "Synonym", "");
addReferencedItem(protein, synonym, "synonyms", true, "subject", false);
synonym.addAttribute(new Attribute("value", accession));
synonym.addAttribute(new Attribute("type", "accession"));
synonym.addReference(getEmblRef());
synonyms.add(synonym);
}
}
}
}
String primaryAcc = srcItem.getIdentifier();
if (swissProtId != null) {
primaryAcc = swissProtId;
} else if (tremblId != null) {
primaryAcc = tremblId;
} else if (emblId != null) {
primaryAcc = emblId;
} else {
// there was no protein accession so use ensembl stable id
Item stableId = getStableId("translation", srcItem.getIdentifier(), srcNs);
if (stableId != null) {
primaryAcc = stableId.getAttribute("stable_id").getValue();
}
}
protein.addAttribute(new Attribute("primaryAccession", primaryAcc));
Item chosenProtein = (Item) proteins.get(primaryAcc);
if (chosenProtein == null) {
// set up additional references/collections
protein.addReference(getOrgRef());
if (srcItem.hasAttribute("seq_start")) {
protein.addAttribute(new Attribute("translationStart",
srcItem.getAttribute("seq_start").getValue()));
}
if (srcItem.hasAttribute("seq_end")) {
protein.addAttribute(new Attribute("translationEnd",
srcItem.getAttribute("seq_end").getValue()));
}
if (srcItem.hasReference("start_exon")) {
protein.addReference(new Reference("startExon",
srcItem.getReference("start_exon").getRefId()));
}
if (srcItem.hasReference("end_exon")) {
protein.addReference(new Reference("endExon",
srcItem.getReference("end_exon").getRefId()));
}
proteins.put(primaryAcc, protein);
proteinSynonyms.addAll(synonyms);
chosenProtein = protein;
}
proteinIds.put(srcItem.getIdentifier(), chosenProtein.getIdentifier());
return chosenProtein;
}
/**
* Find external database accession numbers in ensembl to set as Synonyms
* @param srcItem it in source format ensembl:gene
* @param tgtItem translate item flymine:Gene
* @param srcNs namespace of source model
* @return a set of Synonyms
* @throws ObjectStoreException if problem retrieving items
*/
protected Set setGeneSynonyms(Item srcItem, Item tgtItem, String srcNs)
throws ObjectStoreException {
// additional gene information is in xref table only accessible via translation
Set synonyms = new HashSet();
if (srcItem.hasReference("display_xref")) {
Item xref = ItemHelper.convert(srcItemReader
.getItemById(srcItem.getReference("display_xref").getRefId()));
String accession = null;
String dbname = null;
if (xref.hasAttribute("dbprimary_acc")) {
accession = xref.getAttribute("dbprimary_acc").getValue();
}
if (xref.hasReference("external_db")) {
Item externalDb = ItemHelper.convert(srcItemReader
.getItemById(xref.getReference("external_db").getRefId()));
if (externalDb != null) {
dbname = externalDb.getAttribute("db_name").getValue();
}
}
if (accession != null && !accession.equals("")
&& dbname != null && !dbname.equals("")) {
if (dbname.equals("HUGO") || dbname.equals("RefSeq")) { //?HUGO RefSeq
Item synonym = createItem(tgtNs + "Synonym", "");
addReferencedItem(tgtItem, synonym, "synonyms", true, "subject", false);
synonym.addAttribute(new Attribute("value", accession));
if (dbname.equals("HUGO")) {
synonym.addAttribute(new Attribute("type", "accession"));
synonym.addReference(getHugoRef());
tgtItem.addAttribute(new Attribute("name", accession));
} else {
synonym.addAttribute(new Attribute("type", "accession"));
synonym.addReference(getRefSeqRef());
tgtItem.addAttribute(new Attribute("name", accession));
}
synonyms.add(synonym);
}
}
}
return synonyms;
}
/**
* Find stable_id for various ensembl type
* @param ensemblType could be gene, exon, transcript or translation
* it should be part of name before _stable_id
* @param identifier srcItem identifier, srcItem could be gene, exon, transcript/translation
* @param srcNs namespace of source model
* @return a set of Synonyms
* @throws ObjectStoreException if problem retrieving items
*/
private Item getStableId(String ensemblType, String identifier, String srcNs) throws
ObjectStoreException {
//String value = identifier.substring(identifier.indexOf("_") + 1);
String value = identifier;
Set constraints = new HashSet();
constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
srcNs + ensemblType + "_stable_id", false));
constraints.add(new FieldNameAndValue(ensemblType, value, true));
Iterator stableIds = srcItemReader.getItemsByDescription(constraints).iterator();
if (stableIds.hasNext()) {
return ItemHelper.convert((org.intermine.model.fulldata.Item) stableIds.next());
} else {
return null;
}
}
/**
* change description class to comments
* @param identifier ensembl:gene srcItem identifier
* @param tgtItem translate item flymine:Gene
* @param srcNs namespace of source model
* @return a list of commentIds
* @throws ObjectStoreException if problem retrieving items
*/
private List getCommentIds(String identifier, String srcNs) throws
ObjectStoreException {
String value = identifier;
Set constraints = new HashSet();
constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
srcNs + "gene_description", false));
constraints.add(new FieldNameAndValue("gene", value, true));
List commentIds = new ArrayList();
for (Iterator i = srcItemReader.getItemsByDescription(constraints).iterator();
i.hasNext(); ) {
Item comment = ItemHelper.convert((org.intermine.model.fulldata.Item) i.next());
commentIds.add((String) comment.getIdentifier());
}
return commentIds;
}
/**
* set database object
* @return db item
*/
private Item getEnsemblDb() {
if (ensemblDb == null) {
ensemblDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "ensembl");
Attribute url = new Attribute("url", "http://www.ensembl.org");
ensemblDb.addAttribute(title);
ensemblDb.addAttribute(url);
}
return ensemblDb;
}
private Reference getEnsemblRef() {
if (ensemblRef == null) {
ensemblRef = new Reference("source", getEnsemblDb().getIdentifier());
}
return ensemblRef;
}
/**
* set database object
* @return db item
*/
private Item getEmblDb() {
if (emblDb == null) {
emblDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "embl");
Attribute url = new Attribute("url", "http://www.ebi.ac.uk/embl");
emblDb.addAttribute(title);
emblDb.addAttribute(url);
}
return emblDb;
}
/**
* @return db reference
*/
private Reference getEmblRef() {
if (emblRef == null) {
emblRef = new Reference("source", getEmblDb().getIdentifier());
}
return emblRef;
}
/**
* set database object
* @return db item
*/
private Item getSwissprotDb() {
if (swissprotDb == null) {
swissprotDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "Swiss-Prot");
Attribute url = new Attribute("url", "http://ca.expasy.org/sprot/");
swissprotDb.addAttribute(title);
swissprotDb.addAttribute(url);
}
return swissprotDb;
}
/**
* @return db reference
*/
private Reference getSwissprotRef() {
if (swissprotRef == null) {
swissprotRef = new Reference("source", getSwissprotDb().getIdentifier());
}
return swissprotRef;
}
/**
* set database object
* @return db item
*/
private Item getTremblDb() {
if (tremblDb == null) {
tremblDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "TrEMBL");
Attribute url = new Attribute("url", "http://ca.expasy.org/sprot/");
tremblDb.addAttribute(title);
tremblDb.addAttribute(url);
}
return tremblDb;
}
/**
* @return db reference
*/
private Reference getTremblRef() {
if (tremblRef == null) {
tremblRef = new Reference("source", getTremblDb().getIdentifier());
}
return tremblRef;
}
/**
* set database object
* @return db item
*/
private Item getFlyBaseDb() {
if (flybaseDb == null) {
flybaseDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "FlyBase");
Attribute url = new Attribute("url", "http://www.flybase.org");
flybaseDb.addAttribute(title);
flybaseDb.addAttribute(url);
}
return flybaseDb;
}
/**
* @return db reference
*/
private Reference getFlyBaseRef() {
if (flybaseRef == null) {
flybaseRef = new Reference("source", getFlyBaseDb().getIdentifier());
}
return flybaseRef;
}
/**
* @return db reference
*/
private Reference getRefSeqRef() {
if (refSeqRef == null) {
refSeqRef = new Reference("source", getRefSeqDb().getIdentifier());
}
return refSeqRef;
}
/**
* set database object
* @return db item
*/
private Item getRefSeqDb() {
if (refSeqDb == null) {
refSeqDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "RefSeq");
Attribute url = new Attribute("url", "http://www.ncbi.nlm.nih.gov/RefSeq/");
refSeqDb.addAttribute(title);
refSeqDb.addAttribute(url);
}
return refSeqDb;
}
/**
* @return db reference
*/
private Reference getHugoRef() {
if (hugoRef == null) {
hugoRef = new Reference("source", getHugoDb().getIdentifier());
}
return hugoRef;
}
/**
* set database object
* @return db item
*/
private Item getHugoDb() {
if (hugoDb == null) {
hugoDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "HUGO");
Attribute url = new Attribute("url", "http://www.hugo-international.org/hugo");
hugoDb.addAttribute(title);
hugoDb.addAttribute(url);
}
return hugoDb;
}
/**
* @return db reference
*/
private Reference getGenbankRef() {
if (genbankRef == null) {
genbankRef = new Reference("source", getGenbankDb().getIdentifier());
}
return genbankRef;
}
/**
* set database object
* @return db item
*/
private Item getGenbankDb() {
if (genbankDb == null) {
genbankDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "genbank");
Attribute url = new Attribute("url", "http://www.ncbi.nlm.nih.gov/");
genbankDb.addAttribute(title);
genbankDb.addAttribute(url);
}
return genbankDb;
}
/**
* @return db reference
*/
private Reference getGdbRef() {
if (gdbRef == null) {
gdbRef = new Reference("source", getGdbDb().getIdentifier());
}
return gdbRef;
}
/**
* set database object
* @return db item
*/
private Item getGdbDb() {
if (gdbDb == null) {
gdbDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "gdb");
Attribute url = new Attribute("url", "http://gdbwww.gdb.org/");
gdbDb.addAttribute(title);
gdbDb.addAttribute(url);
}
return gdbDb;
}
/**
* @return db reference
*/
private Reference getUnistsRef() {
if (unistsRef == null) {
unistsRef = new Reference("source", getUnistsDb().getIdentifier());
}
return unistsRef;
}
/**
* set database object
* @return db item
*/
private Item getUnistsDb() {
if (unistsDb == null) {
unistsDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "unists");
Attribute url = new Attribute("url",
"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=unists");
unistsDb.addAttribute(title);
unistsDb.addAttribute(url);
}
return unistsDb;
}
/**
* @return organism item, for homo_sapiens, abbreviation is HS
*/
private Item getOrganism() {
if (organism == null) {
organism = createItem(tgtNs + "Organism", "");
Attribute a1 = new Attribute("abbreviation", orgAbbrev);
organism.addAttribute(a1);
}
return organism;
}
/**
* @return organism reference
*/
private Reference getOrgRef() {
if (orgRef == null) {
orgRef = new Reference("organism", getOrganism().getIdentifier());
}
return orgRef;
}
/**
* Main method
* @param args command line arguments
* @throws Exception if something goes wrong
*/
public static void main (String[] args) throws Exception {
String srcOsName = args[0];
String tgtOswName = args[1];
String modelName = args[2];
String format = args[3];
String namespace = args[4];
String orgAbbrev = args[5];
String identifier = ObjectStoreItemPathFollowingImpl.IDENTIFIER;
String classname = ObjectStoreItemPathFollowingImpl.CLASSNAME;
Map paths = new HashMap();
//karyotype
ItemPrefetchDescriptor desc = new ItemPrefetchDescriptor("karyotype.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
paths.put("http://www.flymine.org/model/ensembl-human#karyotype",
Collections.singleton(desc));
//exon
Set descSet = new HashSet();
desc = new ItemPrefetchDescriptor("exon <- exon_stable_id.exon");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "exon"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#exon_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("exon.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
ItemPrefetchDescriptor desc1 = new ItemPrefetchDescriptor(
"exon.seq_region <- seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc1.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#seq_region", false));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#exon", descSet);
//gene
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("gene <- gene_stable_id.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "gene"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#gene_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.analysis");
desc.addConstraint(new ItemPrefetchConstraintDynamic("analysis", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor("gene.seq_region <- seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc1.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#seq_region", false));
desc.addPath(desc1);
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene <- gene_description.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "gene"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#gene_description", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.display_xref");
desc.addConstraint(new ItemPrefetchConstraintDynamic("display_xref", identifier));
desc1 = new ItemPrefetchDescriptor("gene.display_xref <- xref.external_db");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("external_db", identifier));
desc1.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#xref", false));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#gene", descSet);
//transcript
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("transcript <- transcript_stable_id.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "transcript"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#transcript_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("transcript.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic("gene", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("transcript.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor(
"transcript.seq_region <- seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc1.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#seq_region", false));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#transcript", descSet);
//translation
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("translation <- translation_stable_id.translation");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "translation"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#translation_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("translation.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic("transcript", identifier));
descSet.add(desc);
desc1 = new ItemPrefetchDescriptor("(translation.transcript).display_xref");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("display_xref", identifier));
desc1.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#transcript", false));
ItemPrefetchDescriptor desc2 = new ItemPrefetchDescriptor(
"transcript.display_xref <- xref.external_db");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("external_db", identifier));
desc2.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#xref", false));
desc1.addPath(desc2);
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#translation", descSet);
//simple_feature
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("simple_feature.analysis");
desc.addConstraint(new ItemPrefetchConstraintDynamic("analysis", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("simple_feature.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor(
"simple_feature.seq_region <- seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc1.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#seq_region", false));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#simple_feature", descSet);
//repeat_feature
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("repeat_feature.repeat_consensus");
desc.addConstraint(new ItemPrefetchConstraintDynamic("repeat_consensus", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("repeat_feature.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc1 = new ItemPrefetchDescriptor(
"repeat_feature.seq_region <- seq_region.coord_system");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc1.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#seq_region", false));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#repeat_feature", descSet);
//marker
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("marker.display_marker_synonym");
desc.addConstraint(new ItemPrefetchConstraintDynamic("display_marker_synonym", identifier));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("marker <- marker_feature.marker");
desc.addConstraint(new ItemPrefetchConstraintDynamic(identifier, "marker"));
desc.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#marker_feature", false));
desc1 = new ItemPrefetchDescriptor("marker_feature.seq_region");
desc1.addConstraint(new ItemPrefetchConstraintDynamic("seq_region", identifier));
desc2 = new ItemPrefetchDescriptor(
"marker_feature.seq_region <- seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc2.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#seq_region", false));
desc1.addPath(desc2);
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#marker",
Collections.singleton(desc));
//assembly
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("assembly.asm_seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("asm_seq_region", identifier));
desc2 = new ItemPrefetchDescriptor(
"assembly.asm_seq_region <- seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc2.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#seq_region", false));
desc.addPath(desc2);
descSet.add(desc);
desc = new ItemPrefetchDescriptor("assembly.cmp_seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic("cmp_seq_region",
identifier));
desc2 = new ItemPrefetchDescriptor(
"assembly.cmp_seq_region <- seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
desc2.addConstraint(new FieldNameAndValue(classname,
"http://www.flymine.org/model/ensembl-human#seq_region", false));
desc.addPath(desc2);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#assembly", descSet);
//seq_region
desc = new ItemPrefetchDescriptor("seq_region.coord_system");
desc.addConstraint(new ItemPrefetchConstraintDynamic("coord_system", identifier));
paths.put("http://www.flymine.org/model/ensembl-human#seq_region",
Collections.singleton(desc));
ObjectStore osSrc = ObjectStoreFactory.getObjectStore(srcOsName);
ItemReader srcItemReader = new ObjectStoreItemReader(osSrc, paths);
ObjectStoreWriter oswTgt = ObjectStoreWriterFactory.getObjectStoreWriter(tgtOswName);
ItemWriter tgtItemWriter = new ObjectStoreItemWriter(oswTgt);
OntModel model = ModelFactory.createOntologyModel();
model.read(new FileReader(new File(modelName)), null, format);
DataTranslator dt = new EnsemblHumanDataTranslator(srcItemReader, model, namespace,
orgAbbrev);
model = null;
dt.translate(tgtItemWriter);
tgtItemWriter.close();
}
}
|
flymine/model/ensembl-human/src/java/org/flymine/dataconversion/EnsemblHumanDataTranslator.java
|
package org.flymine.dataconversion;
/*
* Copyright (C) 2002-2004 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.io.FileReader;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.HashSet;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import org.intermine.InterMineException;
import org.intermine.xml.full.Attribute;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.Reference;
import org.intermine.xml.full.ReferenceList;
import org.intermine.xml.full.ItemHelper;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreFactory;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.ObjectStoreWriterFactory;
import org.intermine.dataconversion.ItemReader;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.dataconversion.DataTranslator;
import org.intermine.dataconversion.FieldNameAndValue;
import org.intermine.dataconversion.ItemPrefetchDescriptor;
import org.intermine.dataconversion.ItemPrefetchConstraintDynamic;
import org.intermine.dataconversion.ObjectStoreItemPathFollowingImpl;
import org.intermine.dataconversion.ObjectStoreItemReader;
import org.intermine.dataconversion.ObjectStoreItemWriter;
import org.intermine.util.XmlUtil;
import org.apache.log4j.Logger;
/**
* Convert Ensembl data in fulldata Item format conforming to a source OWL definition
* to fulldata Item format conforming to InterMine OWL definition.
*
* @author Wenyan Ji
* @author Richard Smith
* @author Andrew Varley
* @author Mark Woodbridge
*/
public class EnsemblHumanDataTranslator extends DataTranslator
{
protected static final Logger LOG = Logger.getLogger(EnsemblHumanDataTranslator.class);
private Item ensemblDb;
private Reference ensemblRef;
private Item emblDb;
private Reference emblRef;
private Item tremblDb;
private Reference tremblRef;
private Item swissprotDb;
private Reference swissprotRef;
private Item flybaseDb;
private Reference flybaseRef;
private Map supercontigs = new HashMap();
private Map scLocs = new HashMap();
private Map exons = new HashMap();
private Map flybaseIds = new HashMap();
private String orgAbbrev;
private Item organism;
private Reference orgRef;
private Map proteins = new HashMap();
private Map proteinIds = new HashMap();
private Set proteinSynonyms = new HashSet();
private Map chr2Contig = new HashMap();
private Map sc2Contig = new HashMap();
private Map clone2Contig = new HashMap();
private Set chrSet = new HashSet();
private Set scSet = new HashSet();
private Set contigSet = new HashSet();
private Set cloneSet = new HashSet();
private Map seqIdMap = new HashMap();
/**
* @see DataTranslator#DataTranslator
*/
public EnsemblHumanDataTranslator(ItemReader srcItemReader, OntModel model, String ns,
String orgAbbrev) {
super(srcItemReader, model, ns);
this.orgAbbrev = orgAbbrev;
}
/**
* @see DataTranslator#translate
*/
public void translate(ItemWriter tgtItemWriter)
throws ObjectStoreException, InterMineException {
tgtItemWriter.store(ItemHelper.convert(getOrganism()));
tgtItemWriter.store(ItemHelper.convert(getEnsemblDb()));
tgtItemWriter.store(ItemHelper.convert(getEmblDb()));
tgtItemWriter.store(ItemHelper.convert(getTremblDb()));
tgtItemWriter.store(ItemHelper.convert(getSwissprotDb()));
super.translate(tgtItemWriter);
Iterator i = exons.values().iterator();
while (i.hasNext()) {
tgtItemWriter.store(ItemHelper.convert((Item) i.next()));
}
i = proteins.values().iterator();
while (i.hasNext()) {
tgtItemWriter.store(ItemHelper.convert((Item) i.next()));
}
i = proteinSynonyms.iterator();
while (i.hasNext()) {
tgtItemWriter.store(ItemHelper.convert((Item) i.next()));
}
if (flybaseDb != null) {
tgtItemWriter.store(ItemHelper.convert(flybaseDb));
}
}
/**
* @see DataTranslator#translateItem
*/
protected Collection translateItem(Item srcItem)
throws ObjectStoreException, InterMineException {
Collection result = new HashSet();
String srcNs = XmlUtil.getNamespaceFromURI(srcItem.getClassName());
String className = XmlUtil.getFragmentFromURI(srcItem.getClassName());
Collection translated = super.translateItem(srcItem);
if (translated != null) {
for (Iterator i = translated.iterator(); i.hasNext();) {
boolean storeTgtItem = true;
Item tgtItem = (Item) i.next();
if ("karyotype".equals(className)) {
tgtItem.addReference(getOrgRef());
Item location = createLocation(srcItem, tgtItem, true);
location.addAttribute(new Attribute("strand", "0"));
result.add(location);
} else if ("exon".equals(className)) {
tgtItem.addReference(getOrgRef());
Item stableId = getStableId("exon", srcItem.getIdentifier(), srcNs);
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", "identifier");
}
addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false);
Item location = createLocation(srcItem, tgtItem, true);
result.add(location);
} else if ("gene".equals(className)) {
tgtItem.addReference(getOrgRef());
addReferencedItem(tgtItem, getEnsemblDb(), "evidence", true, "", false);
Item location = createLocation(srcItem, tgtItem, true);
result.add(location);
Item anaResult = createAnalysisResult(srcItem, tgtItem);
result.add(anaResult);
List comments = getCommentIds(srcItem.getIdentifier(), srcNs);
if (!comments.isEmpty()) {
tgtItem.addCollection(new ReferenceList("comments", comments));
}
// gene name should be its stable id (or identifier if none)
Item stableId = null;
stableId = getStableId("gene", srcItem.getIdentifier(), srcNs);
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", "identifier");
} else {
tgtItem.addAttribute(new Attribute("identifier", srcItem.getIdentifier()));
}
// display_xref is gene name (?)
//promoteField(tgtItem, srcItem, "name", "display_xref", "display_label");
result.addAll(setGeneSynonyms(srcItem, tgtItem, srcNs));
// if no organismDbId set to be same as identifier
if (!tgtItem.hasAttribute("organismDbId")) {
tgtItem.addAttribute(new Attribute("organismDbId",
tgtItem.getAttribute("identifier").getValue()));
}
} else if ("transcript".equals(className)) {
tgtItem.addReference(getOrgRef());
Item geneRelation = createItem(tgtNs + "SimpleRelation", "");
addReferencedItem(tgtItem, geneRelation, "objects", true, "subject", false);
moveField(srcItem, geneRelation, "gene", "object");
result.add(geneRelation);
// if no identifier set the identifier as name (primary key)
if (!tgtItem.hasAttribute("identifier")) {
Item stableId = getStableId("transcript", srcItem.getIdentifier(), srcNs);
if (stableId != null) {
moveField(stableId, tgtItem, "stable_id", "identifier");
} else {
tgtItem.addAttribute(new Attribute("identifier",
srcItem.getIdentifier()));
}
}
} else if ("translation".equals(className)) {
Item protein = getProteinByPrimaryAccession(srcItem, srcNs);
//transcript translation subject object?
if (srcItem.hasReference("transcript")) {
String transcriptId = srcItem.getReference("transcript").getRefId();
Item transRelation = createItem(tgtNs + "SimpleRelation", "");
transRelation.addReference(new Reference("subject", transcriptId));
addReferencedItem(protein, transRelation, "subjects", true,
"object", false);
result.add(transRelation);
}
storeTgtItem = false;
// stable_ids become syonyms, need ensembl Database as source
} else if (className.endsWith("_stable_id")) {
if (className.endsWith("translation_stable_id")) {
storeTgtItem = false;
} else {
tgtItem.addReference(getEnsemblRef());
tgtItem.addAttribute(new Attribute("type", "accession"));
}
} else if ("simple_feature".equals(className)) {
tgtItem.addReference(getOrgRef());
tgtItem.addAttribute(new Attribute("identifier", srcItem.getIdentifier()));
result.add(createAnalysisResult(srcItem, tgtItem));
result.add(createLocation(srcItem, tgtItem, true));
// } else if ("prediction_transcript".equals(className)) {
// tgtItem.addReference(getOrgRef());
// result.add(createLocation(srcItem, tgtItem, true));
} else if ("repeat_feature".equals(className)) {
tgtItem.addReference(getOrgRef());
result.add(createAnalysisResult(srcItem, tgtItem));
result.add(createLocation(srcItem, tgtItem, true));
promoteField(tgtItem, srcItem, "consensus", "repeat_consensus",
"repeat_consensus");
promoteField(tgtItem, srcItem, "type", "repeat_consensus", "repeat_class");
promoteField(tgtItem, srcItem, "identifier", "repeat_consensus", "repeat_name");
}
if (storeTgtItem) {
result.add(tgtItem);
}
}
// assembly maps to null but want to create location on a supercontig
} else if ("assembly".equals(className)) {
Item location = createAssemblyLocation(srcItem);
result.add(location);
// seq_region map to null, become Chromosome, Supercontig, Clone and Contig respectively
} else if ("seq_region".equals(className)) {
Item seq = getSeqItem(srcItem.getIdentifier());
result.add(seq);
}
return result;
}
/**
* Translate a "located" Item into an Item and a location
* @param srcItem the source Item
* @param tgtItem the target Item (after translation)
* @param srcItemIsChild true if srcItem should be subject of Location
* @return the location item
*/
protected Item createLocation(Item srcItem, Item tgtItem, boolean srcItemIsChild) throws ObjectStoreException {
String namespace = XmlUtil.getNamespaceFromURI(tgtItem.getClassName());
Item location = createItem(namespace + "Location", "");
Item seq = new Item();
moveField(srcItem, location, "seq_region_start", "start");
moveField(srcItem, location, "seq_region_end", "end");
location.addAttribute(new Attribute("startIsPartial", "false"));
location.addAttribute(new Attribute("endIsPartial", "false"));
if (srcItem.hasAttribute("seq_region_strand")) {
moveField(srcItem, location, "seq_region_strand", "strand");
}
if (srcItem.hasAttribute("phase")) {
moveField(srcItem, location, "phase", "phase");
}
if (srcItem.hasAttribute("end_phase")) {
moveField(srcItem, location, "end_phase", "endPhase");
}
if (srcItem.hasAttribute("ori")) {
moveField(srcItem, location, "ori", "strand");
}
if (srcItem.hasReference("seq_region")) {
String refId = srcItem.getReference("seq_region").getRefId();
seq = (Item) getSeqItem(refId);
}
if (srcItemIsChild) {
addReferencedItem(tgtItem, location, "objects", true, "subject", false);
location.addReference(new Reference("object", seq.getIdentifier()));
//moveField(srcItem, location, "seq_region", "object");
} else {
addReferencedItem(tgtItem, location, "subjects", true, "object", false);
location.addReference(new Reference("subject", seq.getIdentifier()));
//moveField(srcItem, location, "seq_region", "subject");
}
return location;
}
/**
* @param srcItem = assembly
* @return location item which reflects the relations between chromosome and contig,
* supercontig and contig, clone and contig
*/
protected Item createAssemblyLocation(Item srcItem)
throws ObjectStoreException{
int start, end, asmStart, cmpStart, asmEnd, cmpEnd, contigLength;
String ori, contigId, bioEntityId;
contigId = srcItem.getReference("cmp_seq_region").getRefId();
bioEntityId = srcItem.getReference("asm_seq_region").getRefId();
Item contig = ItemHelper.convert(srcItemReader.getItemById(contigId));
Item bioEntity = ItemHelper.convert(srcItemReader.getItemById(bioEntityId));
contigLength = Integer.parseInt(contig.getAttribute("length").getValue());
asmStart = Integer.parseInt(srcItem.getAttribute("asm_start").getValue());
cmpStart = Integer.parseInt(srcItem.getAttribute("cmp_start").getValue());
asmEnd = Integer.parseInt(srcItem.getAttribute("asm_end").getValue());
cmpEnd = Integer.parseInt(srcItem.getAttribute("cmp_end").getValue());
ori = srcItem.getAttribute("ori").getValue();
if (ori.equals("1")) {
start = asmStart - cmpStart + 1;
end = start + contigLength;
} else {
if (cmpEnd == contigLength) {
start = asmStart;
end = start + contigLength - 1;
} else {
start = asmStart - (contigLength - cmpEnd);
end = start + contigLength - 1;
}
}
Item location = createItem(tgtNs + "Location", "");
location.addAttribute(new Attribute("start", Integer.toString(start)));
location.addAttribute(new Attribute("end", Integer.toString(end)));
location.addAttribute(new Attribute("startIsPartial", "false"));
location.addAttribute(new Attribute("endIsPartial", "false"));
location.addAttribute(new Attribute("strand", srcItem.getAttribute("ori").getValue()));
Item seq = new Item();
seq = (Item) getSeqItem(contigId);
location.addReference(new Reference("subject", seq.getIdentifier()));
seq = (Item) getSeqItem(bioEntityId);
location.addReference(new Reference("object", seq.getIdentifier()));
return location;
}
/**
* @param refId = refId for the seq_region
* @return seq item it could be chromosome, supercontig, clone or contig
*/
protected Item getSeqItem(String refId)
throws ObjectStoreException {
Item seq = new Item();
Item seqRegion = ItemHelper.convert(srcItemReader.getItemById(refId));
if (seqIdMap.containsKey(refId)) {
seq = (Item) seqIdMap.get(refId);
} else {
String property = null;
if (seqRegion.hasReference("coord_system")) {
Item coord = ItemHelper.convert(srcItemReader.getItemById(
seqRegion.getReference("coord_system").getRefId()));
property = coord.getAttribute("name").getValue();
}
if (property != null && property != "") {
String s = (property.substring(0, 1)).toUpperCase().concat(property.substring(1));
seq = createItem(tgtNs + s, "");
seq.addAttribute(new Attribute("identifier",
seqRegion.getAttribute("name").getValue()));
seq.addAttribute(new Attribute("length",
seqRegion.getAttribute("length").getValue()));
seqIdMap.put(refId, seq);
}
}
return seq;
}
/**
* Create an AnalysisResult pointed to by tgtItem evidence reference. Move srcItem
* analysis reference and score to new AnalysisResult.
* @param srcItem item in src namespace to move fields from
* @param tgtItem item that will reference AnalysisResult
* @return new AnalysisResult item
*/
protected Item createAnalysisResult(Item srcItem, Item tgtItem)
throws ObjectStoreException{
Item result = createItem(tgtNs + "ComputationalResult", "");
if (srcItem.hasAttribute("analysis")) {
moveField(srcItem, result, "analysis", "analysis");
}
if (srcItem.hasAttribute("score")) {
moveField(srcItem, result, "score", "score"); //gene
}
result.addReference(getEnsemblRef());
ReferenceList evidence = new ReferenceList("evidence", Arrays.asList(new Object[]
{result.getIdentifier(), getEnsemblDb().getIdentifier()}));
tgtItem.addCollection(evidence);
return result;
}
/**
* @param String id = translation id
* @param String srcNs sourceNamespace
* @return String chosenProteinId
* throws exceptions if anything goes wrong
*/
private String getChosenProteinId(String id, String srcNs) throws ObjectStoreException {
String chosenId = (String) proteinIds.get(id);
if (chosenId == null) {
Item translation = ItemHelper.convert(srcItemReader.getItemById(id));
chosenId = getProteinByPrimaryAccession(translation, srcNs).getIdentifier();
proteinIds.put(id, chosenId);
}
return chosenId;
}
/**
* @param Item srcItem = e:translation
* @param String srcNs sourceNamespace
* @return Item for :Protein
* @throws exceptions if anything goes wrong
*/
private Item getProteinByPrimaryAccession(Item srcItem, String srcNs)
throws ObjectStoreException {
Item protein = createItem(tgtNs + "Protein", "");
Set synonyms = new HashSet();
String value = srcItem.getIdentifier();
String swissProtId = null;
String tremblId = null;
String emblId = null;
if (srcItem.hasReference("transcript")) {
Item transcript = ItemHelper.convert(srcItemReader.getItemById(
srcItem.getReference("transcript").getRefId()));
if (transcript.hasReference("display_xref")) {
Item xref = ItemHelper.convert(srcItemReader.getItemById(
transcript.getReference("display_xref").getRefId()));
String accession = null;
String dbname = null;
if (xref != null) {
accession = xref.getAttribute("dbprimary_acc").getValue();
Item externalDb = ItemHelper.convert(srcItemReader
.getItemById(xref.getReference("external_db").getRefId()));
if (externalDb != null) {
dbname = externalDb.getAttribute("db_name").getValue();
}
}
//LOG.error("processing: " + accession + ", " + dbname);
if (accession != null && !accession.equals("")
&& dbname != null && !dbname.equals("")) {
if (dbname.equals("Uniprot/SWISSPROT")) { //Uniprot/SWISSPROT
swissProtId = accession;
Item synonym = createItem(tgtNs + "Synonym", "");
addReferencedItem(protein, synonym, "synonyms", true, "subject", false);
synonym.addAttribute(new Attribute("value", accession));
synonym.addAttribute(new Attribute("type", "accession"));
synonym.addReference(getSwissprotRef());
synonyms.add(synonym);
} else if (dbname.equals("Uniprot/SPTREMBL")) { // Uniprot/SPTREMBL
tremblId = accession;
Item synonym = createItem(tgtNs + "Synonym", "");
addReferencedItem(protein, synonym, "synonyms", true, "subject", false);
synonym.addAttribute(new Attribute("value", accession));
synonym.addAttribute(new Attribute("type", "accession"));
synonym.addReference(getTremblRef());
synonyms.add(synonym);
} else if (dbname.equals("protein_id")) {
emblId = accession;
Item synonym = createItem(tgtNs + "Synonym", "");
addReferencedItem(protein, synonym, "synonyms", true, "subject", false);
synonym.addAttribute(new Attribute("value", accession));
synonym.addAttribute(new Attribute("type", "accession"));
synonym.addReference(getEmblRef());
synonyms.add(synonym);
} else if (dbname.equals("prediction_SPTREMBL")) {
emblId = accession;
Item synonym = createItem(tgtNs + "Synonym", "");
addReferencedItem(protein, synonym, "synonyms", true, "subject", false);
synonym.addAttribute(new Attribute("value", accession));
synonym.addAttribute(new Attribute("type", "accession"));
synonym.addReference(getEmblRef());
synonyms.add(synonym);
}
}
}
}
String primaryAcc = srcItem.getIdentifier();
if (swissProtId != null) {
primaryAcc = swissProtId;
} else if (tremblId != null) {
primaryAcc = tremblId;
} else if (emblId != null) {
primaryAcc = emblId;
} else {
// there was no protein accession so use ensembl stable id
Item stableId = getStableId("translation", srcItem.getIdentifier(), srcNs);
if (stableId != null) {
primaryAcc = stableId.getAttribute("stable_id").getValue();
}
}
protein.addAttribute(new Attribute("primaryAccession", primaryAcc));
Item chosenProtein = (Item) proteins.get(primaryAcc);
if (chosenProtein == null) {
// set up additional references/collections
protein.addReference(getOrgRef());
if (srcItem.hasAttribute("seq_start")) {
protein.addAttribute(new Attribute("translationStart",
srcItem.getAttribute("seq_start").getValue()));
}
if (srcItem.hasAttribute("seq_end")) {
protein.addAttribute(new Attribute("translationEnd",
srcItem.getAttribute("seq_end").getValue()));
}
if (srcItem.hasReference("start_exon")) {
protein.addReference(new Reference("startExon",
srcItem.getReference("start_exon").getRefId()));
}
if (srcItem.hasReference("end_exon")) {
protein.addReference(new Reference("endExon",
srcItem.getReference("end_exon").getRefId()));
}
proteins.put(primaryAcc, protein);
proteinSynonyms.addAll(synonyms);
chosenProtein = protein;
}
proteinIds.put(srcItem.getIdentifier(), chosenProtein.getIdentifier());
return chosenProtein;
}
/**
* Find external database accession numbers in ensembl to set as Synonyms
* @param srcItem it in source format ensembl:gene
* @param tgtItem translate item flymine:Gene
* @param srcNs namespace of source model
* @return a set of Synonyms
* @throws ObjectStoreException if problem retrieving items
*/
protected Set setGeneSynonyms(Item srcItem, Item tgtItem, String srcNs)
throws ObjectStoreException {
// additional gene information is in xref table only accessible via translation
Set synonyms = new HashSet();
if (srcItem.hasReference("display_xref")) {
Item xref = ItemHelper.convert(srcItemReader
.getItemById(srcItem.getReference("display_xref").getRefId()));
String accession = null;
String dbname = null;
if (xref.hasAttribute("dbprimary_acc")) {
accession = xref.getAttribute("dbprimary_acc").getValue();
}
if (xref.hasReference("external_db")) {
Item externalDb = ItemHelper.convert(srcItemReader
.getItemById(xref.getReference("external_db").getRefId()));
if (externalDb != null) {
dbname = externalDb.getAttribute("db_name").getValue();
}
}
if (accession != null && !accession.equals("")
&& dbname != null && !dbname.equals("")) {
if (dbname.equals("flybase_gene") || dbname.equals("flybase_symbol")) { //?
Item synonym = createItem(tgtNs + "Synonym", "");
addReferencedItem(tgtItem, synonym, "synonyms", true, "subject", false);
synonym.addAttribute(new Attribute("value", accession));
if (dbname.equals("flybase_symbol")) {
synonym.addAttribute(new Attribute("type", "name"));
tgtItem.addAttribute(new Attribute("name", accession));
} else { // flybase_gene
synonym.addAttribute(new Attribute("type", "accession"));
// temporary fix to deal with broken FlyBase identfiers in ensembl
String value = accession;
Set idSet = (Set) flybaseIds.get(accession);
if (idSet == null) {
idSet = new HashSet();
} else {
value += "_flymine_" + idSet.size();
}
idSet.add(value);
flybaseIds.put(accession, idSet);
tgtItem.addAttribute(new Attribute("organismDbId", value));
}
synonym.addReference(getFlyBaseRef());
synonyms.add(synonym);
}
}
}
return synonyms;
}
/**
* Find stable_id for various ensembl type
* @param ensemblType could be gene, exon, transcript or translation
* it should be part of name before _stable_id
* @param identifier srcItem identifier, srcItem could be gene, exon, transcript/translation
* @param srcNs namespace of source model
* @return a set of Synonyms
* @throws ObjectStoreException if problem retrieving items
*/
private Item getStableId(String ensemblType, String identifier, String srcNs) throws
ObjectStoreException {
//String value = identifier.substring(identifier.indexOf("_") + 1);
String value = identifier;
Set constraints = new HashSet();
constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
srcNs + ensemblType + "_stable_id", false));
constraints.add(new FieldNameAndValue(ensemblType, value, true));
Iterator stableIds = srcItemReader.getItemsByDescription(constraints).iterator();
if (stableIds.hasNext()) {
return ItemHelper.convert((org.intermine.model.fulldata.Item) stableIds.next());
} else {
return null;
}
}
/**
* change description class to comments
* @param identifier ensembl:gene srcItem identifier
* @param tgtItem translate item flymine:Gene
* @param srcNs namespace of source model
* @return a list of commentIds
* @throws ObjectStoreException if problem retrieving items
*/
private List getCommentIds(String identifier, String srcNs) throws
ObjectStoreException {
String value = identifier;
Set constraints = new HashSet();
constraints.add(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
srcNs + "gene_description", false));
constraints.add(new FieldNameAndValue("gene", value, true));
List commentIds = new ArrayList();
for (Iterator i = srcItemReader.getItemsByDescription(constraints).iterator();
i.hasNext(); ) {
Item comment = ItemHelper.convert((org.intermine.model.fulldata.Item) i.next());
commentIds.add((String) comment.getIdentifier());
}
return commentIds;
}
/**
* set database object
* @return db item
*/
private Item getEnsemblDb() {
if (ensemblDb == null) {
ensemblDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "ensembl");
Attribute url = new Attribute("url", "http://www.ensembl.org");
ensemblDb.addAttribute(title);
ensemblDb.addAttribute(url);
}
return ensemblDb;
}
private Reference getEnsemblRef() {
if (ensemblRef == null) {
ensemblRef = new Reference("source", getEnsemblDb().getIdentifier());
}
return ensemblRef;
}
/**
* set database object
* @return db item
*/
private Item getEmblDb() {
if (emblDb == null) {
emblDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "embl");
Attribute url = new Attribute("url", "http://www.ebi.ac.uk/embl");
emblDb.addAttribute(title);
emblDb.addAttribute(url);
}
return emblDb;
}
/**
* @return db reference
*/
private Reference getEmblRef() {
if (emblRef == null) {
emblRef = new Reference("source", getEmblDb().getIdentifier());
}
return emblRef;
}
/**
* set database object
* @return db item
*/
private Item getSwissprotDb() {
if (swissprotDb == null) {
swissprotDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "Swiss-Prot");
Attribute url = new Attribute("url", "http://ca.expasy.org/sprot/");
swissprotDb.addAttribute(title);
swissprotDb.addAttribute(url);
}
return swissprotDb;
}
/**
* @return db reference
*/
private Reference getSwissprotRef() {
if (swissprotRef == null) {
swissprotRef = new Reference("source", getSwissprotDb().getIdentifier());
}
return swissprotRef;
}
/**
* set database object
* @return db item
*/
private Item getTremblDb() {
if (tremblDb == null) {
tremblDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "TrEMBL");
Attribute url = new Attribute("url", "http://ca.expasy.org/sprot/");
tremblDb.addAttribute(title);
tremblDb.addAttribute(url);
}
return tremblDb;
}
/**
* @return db reference
*/
private Reference getTremblRef() {
if (tremblRef == null) {
tremblRef = new Reference("source", getTremblDb().getIdentifier());
}
return tremblRef;
}
/**
* set database object
* @return db item
*/
private Item getFlyBaseDb() {
if (flybaseDb == null) {
flybaseDb = createItem(tgtNs + "Database", "");
Attribute title = new Attribute("title", "FlyBase");
Attribute url = new Attribute("url", "http://www.flybase.org");
flybaseDb.addAttribute(title);
flybaseDb.addAttribute(url);
}
return flybaseDb;
}
/**
* @return db reference
*/
private Reference getFlyBaseRef() {
if (flybaseRef == null) {
flybaseRef = new Reference("source", getFlyBaseDb().getIdentifier());
}
return flybaseRef;
}
/**
* @return organism item, for homo_sapiens, abbreviation is HS
*/
private Item getOrganism() {
if (organism == null) {
organism = createItem(tgtNs + "Organism", "");
Attribute a1 = new Attribute("abbreviation", orgAbbrev);
organism.addAttribute(a1);
}
return organism;
}
/**
* @return organism reference
*/
private Reference getOrgRef() {
if (orgRef == null) {
orgRef = new Reference("organism", getOrganism().getIdentifier());
}
return orgRef;
}
/**
* Main method
* @param args command line arguments
* @throws Exception if something goes wrong
*/
public static void main (String[] args) throws Exception {
String srcOsName = args[0];
String tgtOswName = args[1];
String modelName = args[2];
String format = args[3];
String namespace = args[4];
String orgAbbrev = args[5];
Map paths = new HashMap();
//karyotype
ItemPrefetchDescriptor desc = new ItemPrefetchDescriptor("karyotype.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "seq_region"));
paths.put("http://www.flymine.org/model/ensembl-human#karyotype",
Collections.singleton(desc));
//exon
Set descSet = new HashSet();
desc = new ItemPrefetchDescriptor("exon <- exon_stable_id.exon");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "exon"));
desc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
"http://www.flymine.org/model/ensembl-human#exon_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("exon.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "seq_region"));
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#exon", descSet);
//gene
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("gene <- gene_stable_id.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "gene"));
desc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
"http://www.flymine.org/model/ensembl-human#gene_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.analysis");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "analysis"));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "seq_region"));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene <- gene_description.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "gene"));
desc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
"http://www.flymine.org/model/ensembl-human#gene_description", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("gene.display_xref");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "display_xref"));
ItemPrefetchDescriptor desc1 = new ItemPrefetchDescriptor(
"gene.display_xref <- xref.external_db");
desc1.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "external_db"));
desc1.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
"http://www.flymine.org/model/ensembl-human#xref", false));
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#gene", descSet);
//transcript
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("transcript <- transcript_stable_id.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "transcript"));
desc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
"http://www.flymine.org/model/ensembl-human#transcript_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("transcript.gene");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "gene"));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("transcript.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "seq_region"));
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#transcript", descSet);
//translation
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("translation <- translation_stable_id.translation");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "translation"));
desc.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
"http://www.flymine.org/model/ensembl-human#translation_stable_id", false));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("translation.transcript");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "transcript"));
descSet.add(desc);
desc1 = new ItemPrefetchDescriptor("(translation.transcript).display_xref");
desc1.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "display_xref"));
desc1.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
"http://www.flymine.org/model/ensembl-human#transcript", false));
ItemPrefetchDescriptor desc2 = new ItemPrefetchDescriptor(
"transcript.display_xref <- xref.external_db");
desc2.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "external_db"));
desc2.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
"http://www.flymine.org/model/ensembl-human#xref", false));
desc1.addPath(desc2);
desc.addPath(desc1);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#translation", descSet);
//simple_feature seq_region analysis
//repeat_feature
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("repeat_feature.repeat_consensus");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "repeat_consensus"));
descSet.add(desc);
desc = new ItemPrefetchDescriptor("repeat_feature.seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "seq_region"));
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#repeat_feature", descSet);
//assembly
descSet = new HashSet();
desc = new ItemPrefetchDescriptor("assembly.asm_seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "asm_seq_region"));
desc2 = new ItemPrefetchDescriptor(
"assembly.asm_seq_region <- seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "coord_system"));
desc2.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
"http://www.flymine.org/model/ensembl-human#coord_system", false));
desc.addPath(desc2);
descSet.add(desc);
desc = new ItemPrefetchDescriptor("assembly.cmp_seq_region");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "cmp_seq_region"));
desc2 = new ItemPrefetchDescriptor(
"assembly.cmp_seq_region <- seq_region.coord_system");
desc2.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "coord_system"));
desc2.addConstraint(new FieldNameAndValue(ObjectStoreItemPathFollowingImpl.CLASSNAME,
"http://www.flymine.org/model/ensembl-human#coord_system", false));
desc.addPath(desc2);
descSet.add(desc);
paths.put("http://www.flymine.org/model/ensembl-human#assembly", descSet);
//seq_region
desc = new ItemPrefetchDescriptor("seq_region.coord_system");
desc.addConstraint(new ItemPrefetchConstraintDynamic(
ObjectStoreItemPathFollowingImpl.IDENTIFIER, "coord_system"));
paths.put("http://www.flymine.org/model/ensembl-human#seq_region",
Collections.singleton(desc));
ObjectStore osSrc = ObjectStoreFactory.getObjectStore(srcOsName);
ItemReader srcItemReader = new ObjectStoreItemReader(osSrc, paths);
ObjectStoreWriter oswTgt = ObjectStoreWriterFactory.getObjectStoreWriter(tgtOswName);
ItemWriter tgtItemWriter = new ObjectStoreItemWriter(oswTgt);
OntModel model = ModelFactory.createOntologyModel();
model.read(new FileReader(new File(modelName)), null, format);
DataTranslator dt = new EnsemblHumanDataTranslator(srcItemReader, model, namespace,
orgAbbrev);
model = null;
dt.translate(tgtItemWriter);
tgtItemWriter.close();
}
}
|
added marker, marker_feature
|
flymine/model/ensembl-human/src/java/org/flymine/dataconversion/EnsemblHumanDataTranslator.java
|
added marker, marker_feature
|
|
Java
|
lgpl-2.1
|
07cd920f07c37234e3fd7d4fa5a867fc3493c3fa
| 0
|
zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform
|
/*
* Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the
* @author tags. See the copyright.txt file in the distribution for a full
* listing of individual contributors.
*
* This 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 software 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.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
* site: http://www.fsf.org.
*/
package org.zanata.webtrans.client.editor.table;
import org.zanata.common.ContentState;
import org.zanata.webtrans.client.events.EditTransUnitEvent;
import org.zanata.webtrans.client.events.TextChangeEvent;
import org.zanata.webtrans.client.events.TextChangeEventHandler;
import org.zanata.webtrans.shared.model.TransUnit;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import net.customware.gwt.presenter.client.EventBus;
import com.google.gwt.gen2.table.client.CellEditor;
import com.google.gwt.gen2.table.client.InlineCellEditor.InlineCellEditorImages;
import com.google.gwt.gen2.table.override.client.HTMLTable;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
public class InlineTargetCellEditor implements CellEditor<TransUnit>
{
/**
* An {@link ImageBundle} that provides images for
* {@link InlineTargetCellEditor}.
*/
public static interface TargetCellEditorImages extends InlineCellEditorImages
{
}
/**
* Default style name.
*/
public static final String DEFAULT_STYLENAME = "gwt-TargetCellEditor";
/**
* The click listener used to clone.
*/
private ClickHandler cloneHandler = new ClickHandler()
{
public void onClick(ClickEvent event)
{
textArea.setText(cellValue.getSource());
textArea.setFocus(true);
autoSize();
Log.info("InlineTargetCellEditor.java: Clone action.");
}
};
/**
* The click listener used to clone and save.
*/
private ClickHandler cloneAndSaveHandler = new ClickHandler()
{
public void onClick(ClickEvent event)
{
cloneHandler.onClick(null);
acceptHandler.onClick(null);
Log.info("InlineTargetCellEditor.java: Clone-and-save action (The last clone action is called by this action).");
}
};
/**
* The click listener used to cancel.
*/
private ClickHandler cancelHandler = new ClickHandler()
{
public void onClick(ClickEvent event)
{
cancelEdit();
}
};
private final CheckBox toggleFuzzy;
/**
* The click listener used to accept.
*/
private ClickHandler acceptHandler = new ClickHandler()
{
public void onClick(ClickEvent event)
{
acceptEdit();
gotoNextRow(curRow);
}
};
/**
* The current {@link CellEditor.Callback}.
*/
private Callback<TransUnit> curCallback = null;
private CancelCallback<TransUnit> cancelCallback = null;
private EditRowCallback editRowCallback = null;
/**
* The current {@link CellEditor.CellEditInfo}.
*/
private CellEditInfo curCellEditInfo = null;
/**
* The main grid used for layout.
*/
private FlowPanel layoutTable;
private Widget cellViewWidget;
private TransUnit cellValue;
private final TextArea textArea;
private boolean isFocused = false;
// private Image stateImage;
private int curRow;
private int curCol;
private HTMLTable table;
/*
* The minimum height of the target editor
*/
// private static final int MIN_HEIGHT = 48;
/**
* Construct a new {@link InlineTargetCellEditor}.
*
* @param content the {@link Widget} used to edit
*/
public InlineTargetCellEditor(final NavigationMessages messages, CancelCallback<TransUnit> callback, EditRowCallback tranValueCallback, final EventBus eventBus)
{
this(messages, GWT.<TargetCellEditorImages> create(TargetCellEditorImages.class), callback, tranValueCallback, eventBus);
}
/**
* Construct a new {@link InlineTargetCellEditor} with the specified images.
*
* @param content the {@link Widget} used to edit
* @param images the images to use for the accept/cancel buttons
*/
public InlineTargetCellEditor(final NavigationMessages messages, TargetCellEditorImages images, CancelCallback<TransUnit> callback, EditRowCallback rowCallback, final EventBus eventBus)
{
// Wrap contents in a table
layoutTable = new FlowPanel();
cancelCallback = callback;
editRowCallback = rowCallback;
// textArea = new AutoSizeTextArea(3, 1);
textArea = new TextArea();
textArea.setStyleName("TableEditorContent-Edit");
textArea.addBlurHandler(new BlurHandler()
{
@Override
public void onBlur(BlurEvent event)
{
isFocused = false;
}
});
textArea.addFocusHandler(new FocusHandler()
{
@Override
public void onFocus(FocusEvent event)
{
isFocused = true;
}
});
textArea.addKeyUpHandler(new KeyUpHandler()
{
@Override
public void onKeyUp(KeyUpEvent event)
{
eventBus.fireEvent(new EditTransUnitEvent());
int keyCode = event.getNativeKeyCode();
// NB: if you change these, please change NavigationConsts too!
if (event.isControlKeyDown() && keyCode == KeyCodes.KEY_ENTER)
{
acceptEdit();
gotoNextRow(curRow);
}
else if (keyCode == KeyCodes.KEY_ESCAPE)
{
cancelEdit();
}
// else if (event.isControlKeyDown() && event.isShiftKeyDown() &&
// event.getNativeKeyCode() == KeyCodes.KEY_PAGEDOWN)
// { // was alt-e
// handleNextState(ContentState.NeedReview);
// }
// else if (event.isControlKeyDown() && event.isShiftKeyDown() &&
// event.getNativeKeyCode() == KeyCodes.KEY_PAGEUP)
// { // was alt-m
// handlePrevState(ContentState.NeedReview);
// // } else if(event.isControlKeyDown() && event.getNativeKeyCode()
// // == KeyCodes.KEY_PAGEDOWN) { // bad in Firefox
// }
else if (event.isAltKeyDown() && event.isDownArrow())
{
handleNext();
// } else if(event.isControlKeyDown() && event.getNativeKeyCode()
// == KeyCodes.KEY_PAGEUP) { // bad in Firefox
}
else if (event.isAltKeyDown() && event.isUpArrow())
{
handlePrev();
}
else if (event.isAltKeyDown() && keyCode == KeyCodes.KEY_PAGEDOWN)
{ // alt-pagedown
handleNextState();
}
else if (event.isAltKeyDown() && keyCode == KeyCodes.KEY_PAGEUP)
{ // alt-pageup
handlePrevState();
}
else if (event.isAltKeyDown() && keyCode == 78)
{
// alt-n to toggle fuzzy check box
if (toggleFuzzy.getValue())
toggleFuzzy.setValue(false);
else
toggleFuzzy.setValue(true);
}
else if ((!event.isAltKeyDown()) && (!event.isControlKeyDown()) && ((keyCode > 46 && keyCode < 58) || (keyCode > 64 && keyCode < 91)))
{
// Remove fuzzy state for fuzzy entry when typing a-z or 0-9
toggleFuzzyBox();
}
autoSize();
// these shortcuts disabled because they conflict with basic text editing:
// else if (event.isControlKeyDown() && event.getNativeKeyCode() == KeyCodes.KEY_HOME)
// { // ctrl-home
// cloneHandler.onClick(null);
// }
// else if (event.isControlKeyDown() && event.getNativeKeyCode() == KeyCodes.KEY_END)
// { // ctrl-end
// cloneAndSaveHandler.onClick(null);
// }
}
});
/********
* textArea.addTextChangeEventHandler(new TextChangeEventHandler() {
*
* @Override public void onTextChange(TextChangeEvent event) {
* Log.debug("TextChangeEvent"); toggleFuzzyBox(); } });
*********/
layoutTable.add(textArea);
HorizontalPanel operationsPanel = new HorizontalPanel();
operationsPanel.addStyleName("float-right-div");
operationsPanel.setSpacing(4);
layoutTable.add(operationsPanel);
// icon as the current state of the unit
// stateImage = new Image(resources.newUnit());
// operationsPanel.add(stateImage);
// Add content widget
toggleFuzzy = new CheckBox(messages.fuzzy());
operationsPanel.add(toggleFuzzy);
PushButton cloneButton = new PushButton(new Image(), cloneHandler);
cloneButton.setText(messages.editClone());
cloneButton.setTitle(messages.editCloneShortcut());
operationsPanel.add(cloneButton);
PushButton cloneAndSaveButton = new PushButton(new Image(), cloneAndSaveHandler);
cloneAndSaveButton.setText(messages.editCloneAndSave());
cloneAndSaveButton.setTitle(messages.editCloneAndSaveShortcut());
operationsPanel.add(cloneAndSaveButton);
PushButton cancelButton = new PushButton(images.cellEditorCancel().createImage(), cancelHandler);
cancelButton.setText(messages.editCancel());
cancelButton.setTitle(messages.editCancelShortcut());
operationsPanel.add(cancelButton);
PushButton acceptButton = new PushButton(images.cellEditorAccept().createImage(), acceptHandler);
acceptButton.setText(messages.editSave());
acceptButton.setTitle(messages.editSaveShortcut());
operationsPanel.add(acceptButton);
}
private void gotoNextRow(int row)
{
editRowCallback.gotoNextRow(row);
}
private void gotoPrevRow(int row)
{
editRowCallback.gotoPrevRow(row);
}
private void gotoNextFuzzy(int row)
{
editRowCallback.gotoNextFuzzy(row);
}
private void gotoPrevFuzzy(int row)
{
editRowCallback.gotoPrevFuzzy(row);
}
private void restoreView()
{
if (curCellEditInfo != null && cellViewWidget != null)
{
curCellEditInfo.getTable().setWidget(curRow, curCol, cellViewWidget);
cellViewWidget.getParent().setHeight(cellViewWidget.getOffsetHeight() + "px");
}
}
private boolean isDirty()
{
if (cellValue == null)
return false;
return !textArea.getText().equals(cellValue.getTarget());
}
public boolean isEditing()
{
return cellValue != null;
}
public boolean isFocused()
{
return isFocused;
}
public void setText(String text)
{
if (isEditing())
{
textArea.setText(text);
}
}
public void editCell(CellEditInfo cellEditInfo, TransUnit cellValue, Callback<TransUnit> callback)
{
// don't allow edits of two cells at once
if (isDirty())
{
callback.onCancel(cellEditInfo);
return;
}
if (isEditing())
{
if (cellEditInfo.getCellIndex() == curCol && cellEditInfo.getRowIndex() == curRow)
{
return;
}
restoreView();
}
Log.debug("starting edit of cell");
// Save the current values
curCallback = callback;
curCellEditInfo = cellEditInfo;
// Get the info about the cell
table = curCellEditInfo.getTable();
curRow = curCellEditInfo.getRowIndex();
curCol = curCellEditInfo.getCellIndex();
cellViewWidget = table.getWidget(curRow, curCol);
// int height = table.getWidget(curRow, curCol - 1).getOffsetHeight();
// int realHeight = height > MIN_HEIGHT ? height : MIN_HEIGHT;
//Disable it for autosize
// textArea.setHeight(realHeight + "px");
int width = table.getWidget(curRow, 0).getOffsetWidth() - 10;
// layoutTable.setHeight(realHeight + "px");
textArea.setWidth(width + "px");
table.setWidget(curRow, curCol, layoutTable);
textArea.setText(cellValue.getTarget());
autoSize();
this.cellValue = cellValue;
textArea.setFocus(true);
DOM.scrollIntoView(table.getCellFormatter().getElement(curRow, curCol));
toggleFuzzy.setValue(cellValue.getStatus() == ContentState.NeedReview);
// refreshStateImage();
}
// private void refreshStateImage()
// {
// if (cellValue.getStatus() == ContentState.New)
// stateImage.setUrl(resources.newUnit().getURL());
// else if (cellValue.getStatus() == ContentState.NeedReview)
// stateImage.setUrl(resources.fuzzyUnit().getURL());
// else if (cellValue.getStatus() == ContentState.Approved)
// stateImage.setUrl(resources.approvedUnit().getURL());
// }
/**
* Accept the contents of the cell editor as the new cell value.
*/
protected void acceptEdit()
{
// Check if we are ready to accept
if (!onAccept())
{
return;
}
cellValue.setTarget(textArea.getText());
if (cellValue.getTarget().isEmpty())
cellValue.setStatus(ContentState.New);
else
cellValue.setStatus(toggleFuzzy.getValue() ? ContentState.NeedReview : ContentState.Approved);
restoreView();
// Send the new cell value to the callback
curCallback.onComplete(curCellEditInfo, cellValue);
clearSelection();
}
public void clearSelection()
{
curCallback = null;
curCellEditInfo = null;
cellViewWidget = null;
cellValue = null;
}
/**
* Cancel the cell edit.
*/
protected void cancelEdit()
{
// Fire the event
if (!onCancel())
{
return;
}
restoreView();
// Call the callback
if (curCallback != null)
{
// curCallback.onCancel(curCellEditInfo);
cancelCallback.onCancel(cellValue);
}
clearSelection();
}
/**
* Called before an accept takes place.
*
* @return true to allow the accept, false to prevent it
*/
protected boolean onAccept()
{
return true;
}
/**
* Called before a cancel takes place.
*
* @return true to allow the cancel, false to prevent it
*/
protected boolean onCancel()
{
return true;
}
public void handleNext()
{
gotoNextRow(curRow);
}
public void handlePrev()
{
gotoPrevRow(curRow);
}
public void handleNextState()
{
gotoNextFuzzy(curRow);
}
public void handlePrevState()
{
gotoPrevFuzzy(curRow);
}
public void setTextAreaSize()
{
autoSize();
}
public void toggleFuzzyBox()
{
if (toggleFuzzy.getValue())
toggleFuzzy.setValue(false);
}
public void autoSize()
{
int initLines = 3;
int growLines = 1;
Log.debug("autosize TextArea");
int rows = textArea.getVisibleLines();
while (rows > initLines)
{
textArea.setVisibleLines(--rows);
}
while (textArea.getElement().getScrollHeight() > textArea.getElement().getClientHeight())
{
textArea.setVisibleLines(textArea.getVisibleLines() + growLines);
}
}
}
|
server/zanata-war/src/main/java/org/zanata/webtrans/client/editor/table/InlineTargetCellEditor.java
|
/*
* Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the
* @author tags. See the copyright.txt file in the distribution for a full
* listing of individual contributors.
*
* This 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 software 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.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
* site: http://www.fsf.org.
*/
package org.zanata.webtrans.client.editor.table;
import org.zanata.common.ContentState;
import org.zanata.webtrans.client.events.EditTransUnitEvent;
import org.zanata.webtrans.client.events.TextChangeEvent;
import org.zanata.webtrans.client.events.TextChangeEventHandler;
import org.zanata.webtrans.shared.model.TransUnit;
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import net.customware.gwt.presenter.client.EventBus;
import com.google.gwt.gen2.table.client.CellEditor;
import com.google.gwt.gen2.table.client.InlineCellEditor.InlineCellEditorImages;
import com.google.gwt.gen2.table.override.client.HTMLTable;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
public class InlineTargetCellEditor implements CellEditor<TransUnit>
{
/**
* An {@link ImageBundle} that provides images for
* {@link InlineTargetCellEditor}.
*/
public static interface TargetCellEditorImages extends InlineCellEditorImages
{
}
/**
* Default style name.
*/
public static final String DEFAULT_STYLENAME = "gwt-TargetCellEditor";
/**
* The click listener used to clone.
*/
private ClickHandler cloneHandler = new ClickHandler()
{
public void onClick(ClickEvent event)
{
textArea.setText(cellValue.getSource());
textArea.setFocus(true);
autoSize();
Log.info("InlineTargetCellEditor.java: Clone action.");
}
};
/**
* The click listener used to clone and save.
*/
private ClickHandler cloneAndSaveHandler = new ClickHandler()
{
public void onClick(ClickEvent event)
{
cloneHandler.onClick(null);
acceptHandler.onClick(null);
Log.info("InlineTargetCellEditor.java: Clone-and-save action (The last clone action is called by this action).");
}
};
/**
* The click listener used to cancel.
*/
private ClickHandler cancelHandler = new ClickHandler()
{
public void onClick(ClickEvent event)
{
cancelEdit();
}
};
private final CheckBox toggleFuzzy;
/**
* The click listener used to accept.
*/
private ClickHandler acceptHandler = new ClickHandler()
{
public void onClick(ClickEvent event)
{
acceptEdit();
gotoNextRow(curRow);
}
};
/**
* The current {@link CellEditor.Callback}.
*/
private Callback<TransUnit> curCallback = null;
private CancelCallback<TransUnit> cancelCallback = null;
private EditRowCallback editRowCallback = null;
/**
* The current {@link CellEditor.CellEditInfo}.
*/
private CellEditInfo curCellEditInfo = null;
/**
* The main grid used for layout.
*/
private FlowPanel layoutTable;
private Widget cellViewWidget;
private TransUnit cellValue;
private final TextArea textArea;
private boolean isFocused = false;
// private Image stateImage;
private int curRow;
private int curCol;
private HTMLTable table;
/*
* The minimum height of the target editor
*/
// private static final int MIN_HEIGHT = 48;
/**
* Construct a new {@link InlineTargetCellEditor}.
*
* @param content the {@link Widget} used to edit
*/
public InlineTargetCellEditor(final NavigationMessages messages, CancelCallback<TransUnit> callback, EditRowCallback tranValueCallback, final EventBus eventBus)
{
this(messages, GWT.<TargetCellEditorImages> create(TargetCellEditorImages.class), callback, tranValueCallback, eventBus);
}
/**
* Construct a new {@link InlineTargetCellEditor} with the specified images.
*
* @param content the {@link Widget} used to edit
* @param images the images to use for the accept/cancel buttons
*/
public InlineTargetCellEditor(final NavigationMessages messages, TargetCellEditorImages images, CancelCallback<TransUnit> callback, EditRowCallback rowCallback, final EventBus eventBus)
{
// Wrap contents in a table
layoutTable = new FlowPanel();
cancelCallback = callback;
editRowCallback = rowCallback;
// textArea = new AutoSizeTextArea(3, 1);
textArea = new TextArea();
textArea.setStyleName("TableEditorContent-Edit");
textArea.addBlurHandler(new BlurHandler()
{
@Override
public void onBlur(BlurEvent event)
{
isFocused = false;
}
});
textArea.addFocusHandler(new FocusHandler()
{
@Override
public void onFocus(FocusEvent event)
{
isFocused = true;
}
});
textArea.addKeyUpHandler(new KeyUpHandler()
{
@Override
public void onKeyUp(KeyUpEvent event)
{
eventBus.fireEvent(new EditTransUnitEvent());
// NB: if you change these, please change NavigationConsts too!
if (event.isControlKeyDown() && event.getNativeKeyCode() == KeyCodes.KEY_ENTER)
{
acceptEdit();
gotoNextRow(curRow);
}
else if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE)
{
cancelEdit();
}
// else if (event.isControlKeyDown() && event.isShiftKeyDown() &&
// event.getNativeKeyCode() == KeyCodes.KEY_PAGEDOWN)
// { // was alt-e
// handleNextState(ContentState.NeedReview);
// }
// else if (event.isControlKeyDown() && event.isShiftKeyDown() &&
// event.getNativeKeyCode() == KeyCodes.KEY_PAGEUP)
// { // was alt-m
// handlePrevState(ContentState.NeedReview);
// // } else if(event.isControlKeyDown() && event.getNativeKeyCode()
// // == KeyCodes.KEY_PAGEDOWN) { // bad in Firefox
// }
else if (event.isAltKeyDown() && event.isDownArrow())
{
handleNext();
// } else if(event.isControlKeyDown() && event.getNativeKeyCode()
// == KeyCodes.KEY_PAGEUP) { // bad in Firefox
}
else if (event.isAltKeyDown() && event.isUpArrow())
{
handlePrev();
}
else if (event.isAltKeyDown() && event.getNativeKeyCode() == KeyCodes.KEY_PAGEDOWN)
{ // alt-pagedown
handleNextState();
}
else if (event.isAltKeyDown() && event.getNativeKeyCode() == KeyCodes.KEY_PAGEUP)
{ // alt-pageup
handlePrevState();
}
else if (event.isAltKeyDown() && event.getNativeKeyCode() == 78)
{
if (toggleFuzzy.getValue())
toggleFuzzy.setValue(false);
else
toggleFuzzy.setValue(true);
}
else if (!event.isAnyModifierKeyDown())
{
// Remove fuzzy state for fuzzy entry when start typing
toggleFuzzyBox();
}
autoSize();
// these shortcuts disabled because they conflict with basic text editing:
// else if (event.isControlKeyDown() && event.getNativeKeyCode() == KeyCodes.KEY_HOME)
// { // ctrl-home
// cloneHandler.onClick(null);
// }
// else if (event.isControlKeyDown() && event.getNativeKeyCode() == KeyCodes.KEY_END)
// { // ctrl-end
// cloneAndSaveHandler.onClick(null);
// }
}
});
/********
* textArea.addTextChangeEventHandler(new TextChangeEventHandler() {
*
* @Override public void onTextChange(TextChangeEvent event) {
* Log.debug("TextChangeEvent"); toggleFuzzyBox(); } });
*********/
layoutTable.add(textArea);
HorizontalPanel operationsPanel = new HorizontalPanel();
operationsPanel.addStyleName("float-right-div");
operationsPanel.setSpacing(4);
layoutTable.add(operationsPanel);
// icon as the current state of the unit
// stateImage = new Image(resources.newUnit());
// operationsPanel.add(stateImage);
// Add content widget
toggleFuzzy = new CheckBox(messages.fuzzy());
operationsPanel.add(toggleFuzzy);
PushButton cloneButton = new PushButton(new Image(), cloneHandler);
cloneButton.setText(messages.editClone());
cloneButton.setTitle(messages.editCloneShortcut());
operationsPanel.add(cloneButton);
PushButton cloneAndSaveButton = new PushButton(new Image(), cloneAndSaveHandler);
cloneAndSaveButton.setText(messages.editCloneAndSave());
cloneAndSaveButton.setTitle(messages.editCloneAndSaveShortcut());
operationsPanel.add(cloneAndSaveButton);
PushButton cancelButton = new PushButton(images.cellEditorCancel().createImage(), cancelHandler);
cancelButton.setText(messages.editCancel());
cancelButton.setTitle(messages.editCancelShortcut());
operationsPanel.add(cancelButton);
PushButton acceptButton = new PushButton(images.cellEditorAccept().createImage(), acceptHandler);
acceptButton.setText(messages.editSave());
acceptButton.setTitle(messages.editSaveShortcut());
operationsPanel.add(acceptButton);
}
private void gotoNextRow(int row)
{
editRowCallback.gotoNextRow(row);
}
private void gotoPrevRow(int row)
{
editRowCallback.gotoPrevRow(row);
}
private void gotoNextFuzzy(int row)
{
editRowCallback.gotoNextFuzzy(row);
}
private void gotoPrevFuzzy(int row)
{
editRowCallback.gotoPrevFuzzy(row);
}
private void restoreView()
{
if (curCellEditInfo != null && cellViewWidget != null)
{
curCellEditInfo.getTable().setWidget(curRow, curCol, cellViewWidget);
cellViewWidget.getParent().setHeight(cellViewWidget.getOffsetHeight() + "px");
}
}
private boolean isDirty()
{
if (cellValue == null)
return false;
return !textArea.getText().equals(cellValue.getTarget());
}
public boolean isEditing()
{
return cellValue != null;
}
public boolean isFocused()
{
return isFocused;
}
public void setText(String text)
{
if (isEditing())
{
textArea.setText(text);
}
}
public void editCell(CellEditInfo cellEditInfo, TransUnit cellValue, Callback<TransUnit> callback)
{
// don't allow edits of two cells at once
if (isDirty())
{
callback.onCancel(cellEditInfo);
return;
}
if (isEditing())
{
if (cellEditInfo.getCellIndex() == curCol && cellEditInfo.getRowIndex() == curRow)
{
return;
}
restoreView();
}
Log.debug("starting edit of cell");
// Save the current values
curCallback = callback;
curCellEditInfo = cellEditInfo;
// Get the info about the cell
table = curCellEditInfo.getTable();
curRow = curCellEditInfo.getRowIndex();
curCol = curCellEditInfo.getCellIndex();
cellViewWidget = table.getWidget(curRow, curCol);
// int height = table.getWidget(curRow, curCol - 1).getOffsetHeight();
// int realHeight = height > MIN_HEIGHT ? height : MIN_HEIGHT;
//Disable it for autosize
// textArea.setHeight(realHeight + "px");
int width = table.getWidget(curRow, 0).getOffsetWidth() - 10;
// layoutTable.setHeight(realHeight + "px");
textArea.setWidth(width + "px");
table.setWidget(curRow, curCol, layoutTable);
textArea.setText(cellValue.getTarget());
autoSize();
this.cellValue = cellValue;
textArea.setFocus(true);
DOM.scrollIntoView(table.getCellFormatter().getElement(curRow, curCol));
toggleFuzzy.setValue(cellValue.getStatus() == ContentState.NeedReview);
// refreshStateImage();
}
// private void refreshStateImage()
// {
// if (cellValue.getStatus() == ContentState.New)
// stateImage.setUrl(resources.newUnit().getURL());
// else if (cellValue.getStatus() == ContentState.NeedReview)
// stateImage.setUrl(resources.fuzzyUnit().getURL());
// else if (cellValue.getStatus() == ContentState.Approved)
// stateImage.setUrl(resources.approvedUnit().getURL());
// }
/**
* Accept the contents of the cell editor as the new cell value.
*/
protected void acceptEdit()
{
// Check if we are ready to accept
if (!onAccept())
{
return;
}
cellValue.setTarget(textArea.getText());
if (cellValue.getTarget().isEmpty())
cellValue.setStatus(ContentState.New);
else
cellValue.setStatus(toggleFuzzy.getValue() ? ContentState.NeedReview : ContentState.Approved);
restoreView();
// Send the new cell value to the callback
curCallback.onComplete(curCellEditInfo, cellValue);
clearSelection();
}
public void clearSelection()
{
curCallback = null;
curCellEditInfo = null;
cellViewWidget = null;
cellValue = null;
}
/**
* Cancel the cell edit.
*/
protected void cancelEdit()
{
// Fire the event
if (!onCancel())
{
return;
}
restoreView();
// Call the callback
if (curCallback != null)
{
// curCallback.onCancel(curCellEditInfo);
cancelCallback.onCancel(cellValue);
}
clearSelection();
}
/**
* Called before an accept takes place.
*
* @return true to allow the accept, false to prevent it
*/
protected boolean onAccept()
{
return true;
}
/**
* Called before a cancel takes place.
*
* @return true to allow the cancel, false to prevent it
*/
protected boolean onCancel()
{
return true;
}
public void handleNext()
{
gotoNextRow(curRow);
}
public void handlePrev()
{
gotoPrevRow(curRow);
}
public void handleNextState()
{
gotoNextFuzzy(curRow);
}
public void handlePrevState()
{
gotoPrevFuzzy(curRow);
}
public void setTextAreaSize()
{
autoSize();
}
public void toggleFuzzyBox()
{
if (toggleFuzzy.getValue())
toggleFuzzy.setValue(false);
}
public void autoSize()
{
int initLines = 3;
int growLines = 1;
Log.debug("autosize TextArea");
int rows = textArea.getVisibleLines();
while (rows > initLines)
{
textArea.setVisibleLines(--rows);
}
while (textArea.getElement().getScrollHeight() > textArea.getElement().getClientHeight())
{
textArea.setVisibleLines(textArea.getVisibleLines() + growLines);
}
}
}
|
remove fuzzy state when typing a-z or 0-9 when not press Altkey and ControlKey
|
server/zanata-war/src/main/java/org/zanata/webtrans/client/editor/table/InlineTargetCellEditor.java
|
remove fuzzy state when typing a-z or 0-9 when not press Altkey and ControlKey
|
|
Java
|
apache-2.0
|
8a56ae7aa97c153cfda805046e1160940a71e5af
| 0
|
troyhen/dsp
|
/* Copyright 2015 Troy D. Heninger
*
* 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.dsp;
import java.io.IOException;
import java.io.File;
import java.lang.reflect.*; // Field, Method, Modifier
import java.sql.*;
import java.text.*; // DateFormat
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
/**
* This class is the default class that all DSP pages extend. When a page
* is written to extend another class then an object of this class still
* be created as the page object. Functions of this class are treated special
* in the DSP parser. Any arguments passed to functions which do not start
* with an underscore '_', will be converted to the proper type automatically.
* Functions that accept multiple arguments accept Object arrays. These functions
* call allow any number of arguments and the DSP parser will send all arguments
* as elements of the array.
*/
public abstract class DspPage extends HttpServlet implements HttpJspPage
{
private static final long serialVersionUID = 6527415972891184043L;
/** The empty string */
public static final String EMPTY = "";
/** The word NULL */
public static final String NULL = "NULL";
/** The word "day", used in dateAdd(), dateSub(), instantAdd(), and instantSub() */
public static final String DAY = "day";
/** The word "days", used in dateAdd(), dateSub(), instantAdd(), and instantSub() */
public static final String DAYS = "days";
public static final String MONTH = "month";
public static final String MONTHS = "months";
public static final String LONG = "long";
public static final String SHORT = "short";
public static final String YEAR = "year";
public static final String YEARS = "years";
/** The words 'sql' and 'mil', used in date(), time(), and instant() */
public static final String SQL = "sql";
public static final String MIL = "mil";
public static final String ACCESS = "access";
public static final String HTML = "html";
public static final String DOMAIN = "domain";
public static final String LINKS = "links";
public static final String SPACE = "space";
public static final int SQL_STMT = 0;
public static final int ARRAY_STMT = 1;
public static final int DIR_STMT = 2;
public static final int SCAN_STMT = 3;
static final boolean DEBUG_MODE = false;
// static final boolean TRACE_MODE = false;
static final Calendar cal = Calendar.getInstance();
static final DateFormat dform = DateFormat.getDateInstance(DateFormat.SHORT);
static final DateFormat dateAmer = new SimpleDateFormat("MM/dd/yyyy");
static final DateFormat datelong = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
static final DateFormat instantAmer = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
static final DateFormat instantAccessForm = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
static final DateFormat instantlong = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm:ss.SSSS a");
static final DateFormat timelong = new SimpleDateFormat("hh:mm:ss.SSSS a");
static final DateFormat timeshort = new SimpleDateFormat("hh:mm:ss a");
static final DateFormat timeshort2 = new SimpleDateFormat("hh:mm a");
static final DateFormat timeshort3 = new SimpleDateFormat("hh:mma");
static final DateFormat timeshort4 = new SimpleDateFormat("hh:mm:ssa");
static final DateFormat timeshort5 = new SimpleDateFormat("HH:mm:ss");
static final DateFormat timeshort6 = new SimpleDateFormat("HH:mm");
static final DateFormat zonedate = new SimpleDateFormat("yyyyMMdd");
static final DateFormat zoneinstant = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
static final DateFormat zonetime = new SimpleDateFormat("HHmmss");
static final DecimalFormat tens = new DecimalFormat("#,##0.#");
static final DecimalFormat percent = new DecimalFormat("#,##0.#%");
private static String[] types = {"<a", "</a", ".com", ".net", ".org", ".edu", ".gov", ".mil",};
protected DspProp prop;
/**
* Integer absolute value. Returns the absolute value of <b>arg</b>.
*/
public static int abs(int arg)
{
return arg < 0 ? -arg : arg;
} // abs()
/**
* Integer addition. Returns the summation of all arguments. Each argument
* is converted to an <b>int</b> type. An empty or null array <b>arg</b> evalutes to 0.
* Any null arguments are ignored.
*/
public static int add(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("add(" + psize + " args)");
int result = 0;
for (int ix = 0, end = psize; ix < end; ix++)
{
try {
result += _int(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // add()
/**
* Add anchor tags around text that looks like a hyperlink or an email addresses.
* Called from html().
* @see html()
*/
private static StringBuilder addAnchors(StringBuilder buf)
{
char c;
boolean inTag = false, mailto = false;
for (int ix = 0, end = buf.length(); ix < end; ix++)
{
c = buf.charAt(ix);
if (c == '<' && !inTag)
{
inTag = true;
if (ix + 2 < end && Character.toLowerCase(buf.charAt(ix + 1)) == 'a'
&& buf.charAt(ix + 2) <= ' ') return buf; // done if any anchor tags found
}
if (c == '>' && inTag) inTag = false;
if (c == '.' && !inTag)
{
int iz = ix + 1;
mailto = false;
for (; iz < end; iz++)
{
c = buf.charAt(iz);
if (c <= ' ' || c == '"' || c == '\'' || c == ';' || c == ','
|| c == '<' || c == '>' || c > 126)
{
break;
}
if (iz == ix + 1 && c == '&') break;
if (c == '@') mailto = true;
}
String url = buf.substring(ix, iz).toLowerCase();
if (url.startsWith(".exe") || url.startsWith(".doc")
|| url.startsWith(".htm") || url.startsWith(".txt")
|| url.startsWith(".dll") || url.startsWith(".zip")
|| url.startsWith(".gif") || url.startsWith(".jpg")
|| url.startsWith("..."))
{
ix += 2;
continue; // these are only files
}
// if (!(url.startsWith("com") || url.startsWith("org") || url.startsWith("net")
// || url.startsWith("mil") || url.startsWith("gov"))) continue; // only these allowed
c = buf.charAt(iz - 1);
while (c == '.')
{
iz--; // ignore ending periods
if (iz <= ix) break;
c = buf.charAt(iz - 1);
}
if (iz <= ix + 1) continue; // too short
int iy = ix - 1;
for (; iy > 0; iy--)
{
c = buf.charAt(iy);
if (c <= ' ' || c == '"' || c == '\'' || c == ';' || c == ','
|| c == '<' || c == '>' || c > 126)
{
iy++;
break;
}
if (c == '@') mailto = true;
}
if (iz < iy + 4 || iy < 0) continue; // too short
int ij = iy;
for (; ij < iz; ij++)
{
c = buf.charAt(ij);
if (c != '-' && c != '+' && c != '.' && c != 'e' && c != 'E'
&& c != '$' && (c < '0' || c > '9')) break;
}
if (ij >= iz) continue; // ignore floating point numbers
url = buf.substring(iy, iz);
// weed out things that can't be a URL
String lower = url.toLowerCase();
if (!mailto && lower.indexOf(".com") < 0 && lower.indexOf(".net") < 0
&& lower.indexOf("www") < 0 && lower.indexOf(".edu") < 0
&& lower.indexOf(".gov") < 0 && lower.indexOf(".org") < 0
&& lower.indexOf(".web") < 0 && lower.indexOf(".htm") < 0) continue;
//System.out.println("ix = " + ix + ", iy = " + iy + ", iz = " + iz + ", end = " + end
// + "\n\t'" + url + "'");
buf.insert(iz, "</a>");
if (mailto)
{
buf.insert(iy, "<a href=\"mailto:" + url + "\">");
}
else
{
if (url.toLowerCase().startsWith("http"))
{
buf.insert(iy, "<a href=\"" + url + "\">");
}
else
{
buf.insert(iy, "<a href=\"http://" + url + "\">");
}
}
int inc = buf.length() - end;
end += inc;
ix = iz + inc - 1;
}
}
return buf;
} // addAnchors()
/**
* Logical And. Calculates the logical <b>and</b> of all arguments.
* Each argument is converted to a boolean as it is used. An empty or null
* array arg evaluates to 0. Note, this function cannot do short-circut
* evalation, as Java dose when you use the || operator.
* @see or()
*/
public static boolean and(Object[] args)
{
if (args == null || args.length == 0) return false;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("and(" + psize + " args)");
boolean result = true;
for (int ix = 0, end = psize; result && ix < end; ix++)
{
try {
result &= _boolean(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // and()
static final String base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* Decode a Base64 String. This decodes a String that has been encoded with Base64
* encoding, as defined in RFC 1521.
*/
public static String base64Decode(String data)
{
String result = null;
if (data != null)
{
int len = data.length();
byte[] buf = new byte[len * 3 / 4];
int bits = 0, accum = 0, iy = 0;
boolean trunc = false;
for (int ix = 0; ix < len; ix++)
{
char c = data.charAt(ix);
if (c == '=')
{
trunc = true; // ignore the last 8 bits because the input had a non multiple of 6 bits
break; // If I hit '=' then I know I'm done
}
if (c >= 'A' && c <= 'Z')
{
accum = (accum << 6) | (c - 'A');
}
else
if (c >= 'a' && c <= 'z')
{
accum = (accum << 6) | (c - 'a' + 26);
}
else
if (c >= '0' && c <= '9')
{
accum = (accum << 6) | (c - '0' + 52);
}
else if (c == '+')
{
accum = (accum << 6) | 62;
}
else if (c == '/')
{
accum = (accum << 6) | 63;
}
else continue; // ignore all other characters; don't increment bits
bits += 6;
if (bits >= 24)
{
buf[iy++] = (byte)(accum >>> 16);
buf[iy++] = (byte)(accum >>> 8);
buf[iy++] = (byte)accum;
bits = 0;
accum = 0;
}
}
if (bits > 0)
{
int bitsOver = bits;
while (bitsOver < 24)
{
accum <<= 6;
bitsOver += 6;
}
if (trunc) bits -= 8; // ignore the last byte since it will be 0
while (bits > 0)
{
buf[iy++] = (byte)(accum >>> 16);
accum <<= 8;
bits -= 8;
}
}
try { result = new String(buf, 0, iy, "UTF-8"); } catch (java.io.UnsupportedEncodingException e) {}
}
if (DEBUG_MODE) ThreadState.logln("base64Decode(" + data + ") -> " + result);
return result;
} // base64Decode()
/**
* Encode a Base64 String. This encodes a String using Base64 encoding, as defined in
* RFC 1521.
*/
public static String base64Encode(String data)
{
String result;
if (data == null) result = null;
else
{
byte[] utf8 = null;
try { utf8 = data.getBytes("UTF-8"); } catch (java.io.UnsupportedEncodingException e) {}
int len = utf8.length;
StringBuilder buf = new StringBuilder(len * 5 / 3);
int bits = 0, accum = 0, line = 0;
for (int ix = 0; ix < len; ix++)
{
accum = (accum << 8) | (utf8[ix] & 0xff); // always positive
bits += 8;
if (bits >= 24)
{
buf.append(base64Chars.charAt(accum >>> 18));
buf.append(base64Chars.charAt((accum >>> 12) & 0x3f));
buf.append(base64Chars.charAt((accum >>> 6) & 0x3f));
buf.append(base64Chars.charAt(accum & 0x3f));
bits = 0;
accum = 0;
line += 4;
if (line >= 76)
{
buf.append("\r\n");
line = 0;
}
}
}
if (bits > 0)
{
int bitsOver = bits;
while (bitsOver < 24)
{
accum <<= 8;
bitsOver += 8;
}
buf.append(base64Chars.charAt(accum >>> 18));
bits -= 6;
buf.append(base64Chars.charAt((accum >>> 12) & 0x3f));
bits -= 6;
if (bits > 0)
{
buf.append(base64Chars.charAt((accum >>> 6) & 0x3f));
}
else
{
buf.append('=');
}
buf.append('=');
}
result = buf.toString();
}
if (DEBUG_MODE) ThreadState.logln("base64Encode(" + data + ") -> " + result);
return result;
} // base64Encode()
/**
* Bit-wise And. Calculates the bit-wise <b>and</b> of all arguments.
* Each argument is converted to an int as it is used. An empty or null
* array evaluates to 0.
*/
public static int bitAnd(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
int result = -1;
for (int ix = 0, end = psize; ix < end; ix++)
{
try {
result &= _int(args[ix]);
} catch (NullPointerException e) {
}
}
if (DEBUG_MODE) ThreadState.logln("bitAnd(" + psize + " args) -> " + result);
return result;
} // bitAnd()
/**
* Bit-wise Or. Calculates the bit-wise <b>or</b> of all arguments.
* Each argument is converted to an int as it is used. An empty or null
* array <b>arg</b> evaluates to 0.
*/
public static int bitOr(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
int result = 0;
for (int ix = 0, end = psize; ix < end; ix++)
{
try {
result |= _int(args[ix]);
} catch (NullPointerException e) {
}
}
if (DEBUG_MODE) ThreadState.logln("bitOr(" + psize + " args) -> " + result);
return result;
} // bitOr()
/**
* Bit-wise Exclusive-Or. Calculates the bit-wise <b>exclusive or</b> of all arguments.
* Each argument is converted to an int as it is used. An empty or null
* array <b>arg</b> evaluates to 0.
*/
public static int bitXor(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
int result = 0;
for (int ix = 0, end = psize; ix < end; ix++)
{
try {
result ^= _int(args[ix]);
} catch (NullPointerException e) {
}
}
if (DEBUG_MODE) ThreadState.logln("bitXor(" + psize + " args) -> " + result);
return result;
} // bitXor()
/**
* Concatenates Strings. This simply concatenates the arguments and returns the String.
* Each argument is converted to a String as it is used. Null arguments convert to the empty
* String "". An empty or null array <b>arg</b> evaluates to the empty string "".
*/
public static String concat(Object[] args)
{
StringBuilder result = new StringBuilder();
int psize = 0;
if (args != null)
{
psize = args.length;
for (int ix = 0; ix < psize; ix++)
{
String s = _String(args[ix]);
if (s != null)
{
// s = replace(s, "<br>", "\r\n");
result.append(s);
}
}
}
if (DEBUG_MODE) ThreadState.logln("concat(" + psize + " args) -> " + result);
return result.toString();
} // concat()
/**
* Date Conversion and Extraction. This multipurpose function can convert a Date object
* to a String in several formats, or can extract parts of the date. This function only
* accepts one or two arg elements. If two, the first is the requested function
* to perform, and the second is converted to java.sql.Date. If one, the request is assumed
* to be "short". The following are the types of functions performed based on the request:
* <table><tr><td>Request (arg1)</td><td>Returned</td><td>Type</td><td>Example</td></tr>
* <tr><td>short</td><td>Short Date</td><td>String</td><td>2000-11-20</td></tr>
* <tr><td>long</td><td>Long Date</td><td>String</td><td>Monday, November 20, 2000</td></tr>
* <tr><td>sql</td><td>SQL Date</td><td>String</td><td>{d '2000-11-20'}</td></tr>
* <tr><td>year</td><td>Year</td><td>Integer</td><td>2000</td></tr>
* <tr><td>month</td><td>Month</td><td>Integer</td><td>11</td></tr>
* <tr><td>day</td><td>Day of Month</td><td>Integer</td><td>20</td></tr></table>
* @deprecated
*/
public static Object date(Object[] args) throws IllegalArgumentException
{
int psize = args.length;
if (!(psize == 1 || psize == 2))
throw new IllegalArgumentException("date() can only accept 1 or 2 arguments");
String type = null;
Date date;
if (psize == 2)
{
type = _String(args[0]);
date = _Date(args[1]);
}
else date = _Date(args[0]);
Object result;
if (psize == 1 || SHORT.equalsIgnoreCase(type)) result = dateShort(date);
else
if (LONG.equalsIgnoreCase(type)) result = dateLong(date);
else
if (SQL.equalsIgnoreCase(type)) result = dateSql(date);
else
if (YEAR.equalsIgnoreCase(type)) result = new Integer(dateYear(date));
else
if (MONTH.equalsIgnoreCase(type)) result = new Integer(dateMonth(date));
else
if (DAY.equalsIgnoreCase(type)) result = new Integer(dateDay(date));
else
throw new IllegalArgumentException("date(" + type + ", " + date + ") error, unknown date type");
if (DEBUG_MODE) ThreadState.logln("date(" + psize + " args) -> " + result);
return result;
} // date()
/**
* Add date units to a Date. This function adds years, months, weeks, or days to a Date.
* This function accepts either two or three arg elements. The first element
* is converted to a java.sql.Date. The second is converted to an int. The last
* if present is converted to a String and specifies the type of addition to perform.
* If only two elements are sent the type is assumed to be "days". Here are
* the allowed addition requests: year, years, month, months, week, weeks, day, or days.
*/
public static Date dateAdd(Object[] args) throws IllegalArgumentException
{
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("dateAdd(" + psize + " args)");
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("dateAdd() can only accept 2 or 3 arguments");
Date date = _Date(args[0]);
int value = _int(args[1]);
String str = "days";
if (psize == 3)
{
str = _String(args[2]);
}
int type = 'd';
if (str.length() > 0) type = Character.toLowerCase(str.charAt(0));
Calendar c = Calendar.getInstance();
c.setTime(date);
switch (type)
{
case 'd':
c.add(Calendar.DATE, value);
break;
case 'm':
c.add(Calendar.MONTH, value);
break;
case 'w':
c.add(Calendar.WEEK_OF_YEAR, value);
break;
case 'y':
c.add(Calendar.YEAR, value);
break;
default:
throw new IllegalArgumentException("Unknown value type: " + str);
}
return new Date(c.getTime().getTime());
} // dateAdd()
/**
* Returns the date in the American standar format MM/DD/YYYY
*/
public static String dateAmerican(Date date)
{
String result;
if (date == null) result = null;
else result = dateAmer.format(date);
if (DEBUG_MODE) ThreadState.logln("dateAmerican(" + date + ") -> " + result);
return result;
} // dateAmerican()
/**
* Return the day of the month of the Date.
*/
public static int dateDay(Date date)
{
int result;
if (date == null) result = 0;
else
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
result = cal.get(Calendar.DAY_OF_MONTH);
}
if (DEBUG_MODE) ThreadState.logln("dateDay(" + date + ") -> " + result);
return result;
} // dateDay()
/**
* Returns the difference between the two dates as a String.
*/
public static String dateDiff(Date date1, Date date2)
{
return msecDiff(date1.getTime(), date2.getTime());
} // dateDiff()
/**
* Return the Date as a String in long format.
*/
public static String dateLong(Date date)
{
String result;
if (date == null) result = null;
else result = datelong.format(date);
if (DEBUG_MODE) ThreadState.logln("dateLong(" + date + ") -> " + result);
return result;
} // dateLong()
/**
* Return the month of the Date, as a number 1-12.
*/
public static int dateMonth(Date date)
{
int result;
if (date == null) result = 0;
else
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
result = cal.get(Calendar.MONTH) + 1;
}
if (DEBUG_MODE) ThreadState.logln("dateMonth(" + date + ") -> " + result);
return result;
} // dateMonth()
/**
* Return the Date as a String in short format.
*/
public static String dateShort(Date date)
{
String result;
if (date == null) result = null;
else result = date.toString();
if (DEBUG_MODE) ThreadState.logln("dateShort(" + date + ") -> " + result);
return result;
} // dateShort()
/**
* Return the Date as a String formated for use in an SQL statement.
*/
public static String dateSql(Date date)
{
String result;
if (date == null) result = NULL;
else result = "{d '" + date + "'}";
if (DEBUG_MODE) ThreadState.logln("dateSql(" + date + ") -> " + result);
return result;
} // dateSql()
/**
* Subtract date units from a Date. This function subtracts years, months, weeks, or days from a Date.
* This function accepts either two or three arg elements. The first element
* is converted to a java.sql.Date. The second is the value converted to an int. The last
* if present is converted to a String and specifies the type of subtraction to perform.
* If only two elements are sent the type is assumed to be "days". Here are
* the allowed subtraction requests: year, years, month, months, week, weeks, day, or days.
*/
public static Date dateSub(Object[] args) throws IllegalArgumentException
{
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("dateSub(" + psize + " args)");
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("dateSub() can only accept 2 or 3 arguments");
int value = _int(args[1]);
args[1] = new Integer(-value);
return dateAdd(args);
} // dateSub()
/**
* Return the year of the Date.
*/
public static int dateYear(Date date)
{
int result;
if (date == null) result = 0;
else
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
result = cal.get(Calendar.YEAR);
}
if (DEBUG_MODE) ThreadState.logln("dateYear(" + date + ")");
return result;
} // dateYear()
/**
* Returns an integer that has it's bits scrambled. If the same resulting value is again sent
* through this function the original value will be returned.
*/
public static int descramble(int value, String key)
{
byte[] shifts = new byte[32];
for (int ix = 0; ix < 32; ix++)
{
shifts[ix] = (byte)ix;
}
int hash = key.hashCode();
Random rand = new Random((long)hash << 32 | hash);
for (int ix = 0; ix < 32; ix++)
{
byte temp = shifts[ix];
int r = (int)(rand.nextFloat() * 32);
shifts[ix] = shifts[r];
shifts[r] = temp;
}
//System.out.println("descramble [");
//for (int ix = 0; ix < 32; ix++)
//{
// if (ix > 0) System.out.print(", ");
// System.out.print(shifts[ix]);
//}
//System.out.println("]");
int result = 0;
for (int ix = 0; ix < 32; ix++)
{
int shift = shifts[ix];
result |= ((value >>> shift) & 1) << ix;
}
result ^= hash;
//System.out.println("value " + Integer.toHexString(value) + ", hash " + Integer.toHexString(value) + ", result " + Integer.toHexString(result));
if (DEBUG_MODE) ThreadState.logln("descramble(" + value + ", " + key + ") -> " + result);
return result;
} // descramble()
/**
* Integer division. Returns the first argument divided by each of the reast. Each argument
* is converted to an <b>int</b> type. An empty or null array <b>arg</b> evalutes to 0.
* Any null arguments are ignored.
*/
public static int div(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("div(" + psize + " args)");
int result = 1;
try {
result = _int(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1, end = psize; ix < end; ix++)
{
try {
result /= _int(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // div()
/**
* Integer division with round-off. This works the similar to div(), except that
* when the resulting fractional part is 1/2 or greater the next higher integer (or lower
* in case of a negative result) is returned. Also, this only works with two arguments.
* @see div(Object[])
* @see divRoundUp(int, int)
*/
public static int divRoundOff(int i1, int i2) throws IllegalArgumentException
{
int result;
if (i2 == 0) throw new IllegalArgumentException("Cannot divide by 0.");
if ((i1 >= 0 && i2 > 0) || (i1 < 0 && i2 < 0)) result = (i1 + (i2 >> 1)) / i2;
else result = (i1 + (i2 >> 1)) / i2;
return result;
} // divRoundOff()
/**
* Integer division with round-up. This works the similar to div(), except that
* when their would be any remainder the next higher integer (or lower
* in case of a negative result) is returned. Also, this only works with two arguments.
* @see div(Object[])
* @see divRoundOff(int, int)
*/
public static int divRoundUp(int i1, int i2) throws IllegalArgumentException
{
int result;
if (i2 == 0) throw new IllegalArgumentException("Cannot divide by 0.");
if ((i1 >= 0 && i2 > 0) || (i1 < 0 && i2 < 0)) result = (i1 + i2 - 1) / i2;
else result = (i1 + i2 - 1) / i2;
return result;
} // divRoundUp()
// public void doGet(HttpServletRequest request, HttpServletResponse response)
// throws ServletException, IOException
// {
// _jspService(request, response);
// } // doGet()
// public void doPost(HttpServletRequest request, HttpServletResponse response)
// throws ServletException, IOException
// {
// _jspService(request, response);
// } // doPost()
/**
* Returns true if arg1 and arg2 are equals, false otherwise. Arg2 is converted to
* the same time as arg1, if the types to not match. If arg2 can't be converted the
* result is false. Case is ignored when comparing Strings.
*/
public boolean eq(Object arg1, Object arg2) //throws Exception
{
boolean result = false;
if (arg1 == null && arg2 == null) result = true;
else
if (arg1 != null && arg2 != null)
{
try {
if (arg1 instanceof String && ((String)arg1).equalsIgnoreCase(_String(arg2))) result = true;
else
if (arg1 instanceof Date && arg1.equals(_Date(arg2))) result = true;
else
if (arg1 instanceof Time && arg1.equals(_Time(arg2))) result = true;
else
if (arg1 instanceof Boolean && arg1.equals(_Boolean(arg2))) result = true;
else
if (arg1 instanceof Double && arg1.equals(_Double(arg2))) result = true;
else
if (arg1 instanceof Integer && arg1.equals(_Integer(arg2))) result = true;
else
if (arg1 instanceof Number && _Double(arg1).equals(_Double(arg2))) result = true;
else
if (_String(arg1).equalsIgnoreCase(_String(arg2))) result = true;
} catch (Exception e) {
}
}
if (DEBUG_MODE) ThreadState.logln("eq(" + arg1 + ", " + arg2 + ") -> " + result);
return result;
} // eq()
/**
* Make object ready for use in an SQL where clause. Outputs an '=' if value is set
* or 'is' if not, then converts the value to an Integer and outputs the value.
* @see quote(String)
*/
public static String eqInteger(Object value)
{
return (value == null || (value instanceof String && ((String)value).length() == 0)
? "is " : "= ") + sqlInteger(value);
} // eqInteger()
/**
* Make String ready for use in an SQL where clause. Outputs an '=' if value is set
* or 'is' if not, then quotes and outputs the value.
* @see quote(String)
*/
public static String eqQuote(String value)
{
return (value == null || value.length() == 0 ? " is " : " = ") + quote(value);
} // eqQuote()
/**
* Make object ready for use in an SQL where clause. Outputs an '=' if value is set
* or 'is' if not, then quotes and outputs the value.
* @see quote(String)
*/
public static String eqSql(Object value)
{
if (value == null || value instanceof String) return eqQuote((String)value);
if (value instanceof Object[] || value instanceof String[]
|| value instanceof Number[] || value instanceof Collection) return " in " + sql(value);
return " = " + sql(value);
} // eqSql()
/**
* Execute a statement. The first word specifies the type of statement: "array", "dir", "scan", or "sql".
* If none of those are found the statement is assumed to be of type "sql". The db option to switch
* databases is allowed at the beginning of sql statements.
*/
public DspStatement execute(String typeStr, Object obj) throws DspException
{
int type = SQL_STMT;
if (typeStr != null && typeStr.length() > 0)
{
if (typeStr.equals("scan"))
{
type = SCAN_STMT;
}
else
if (typeStr.equals("array"))
{
type = ARRAY_STMT;
}
else
if (typeStr.equals("dir"))
{
type = DIR_STMT;
}
else
if (!typeStr.equals("sql")) throw new IllegalArgumentException("Invalid statement type: " + typeStr);
}
return execute("_t999", type, obj);
} // execute()
/**
* Execute a statement. Used by DspDo, DspIf, DspSql, and DspWhile.
*/
protected DspStatement execute(String name, int type, Object obj)
throws DspException
{
DspStatement state = makeStatement(name, type);
state.execute(obj);
return state;
} // execute()
/**
* Execute a statement and return the first column of the first row if statement produces
* a result set. Otherwise, return the number of rows modified. The first word specifies
* the type of statement: "array", "dir", "scan", or "sql". If none of those are found the
* statement is assumed to be of type "sql". The db option to switch databases is allowed
* at the beginning of sql statements.
*/
public Object executeGet1st(String typeStr, Object obj) throws DspException
{
int type = SQL_STMT;
if (typeStr != null && typeStr.length() > 0)
{
if (typeStr.equals("scan"))
{
type = SCAN_STMT;
}
else
if (typeStr.equals("array"))
{
type = ARRAY_STMT;
}
else
if (typeStr.equals("dir"))
{
type = DIR_STMT;
}
else
if (!typeStr.equals("sql")) throw new IllegalArgumentException("Invalid statement type: " + typeStr);
}
return executeGet1st("_t998", type, obj);
} // executeGet1st()
/**
* Execute a statement and return the first column of the first row if statement produces
* a result set. Otherwise, return the number of rows modified. Used by DspSet and DspDefault.
*/
protected Object executeGet1st(String name, int type, Object obj)
throws DspException
{
DspStatement state = makeStatement(name, type);
try {
state.execute(obj);
if (state.hasResults())
{
state.next();
return state.getObject(1);
}
int result = state.getResult();
if (result == 0 || result == Integer.MIN_VALUE) return null;
return new Integer(result);
} finally {
state.close();
}
} // executeGet1st()
/**
* Real number absolute value. Returns the absolute value of <b>arg</b>.
*/
public static double fabs(double arg)
{
return arg < 0.0 ? -arg : arg;
} // fabs()
/**
* Real numebr addition. Returns the summation of all arguments. Each argument
* is converted to an <b>int</b> type. An empty or null array <b>arg</b> evalutes to 0.
* Any null arguments are ignored.
*/
public static double fadd(Object[] args)
{
if (args == null || args.length == 0) return 0.0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("fadd(" + psize + " args)");
double result = 0.0;
for (int ix = 0, end = psize; ix < end; ix++)
{
try {
result += _double(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // fadd()
/**
* Real number division. Returns the first argument divided by each of the reast. Each argument
* is converted to an <b>int</b> type. An empty or null array <b>arg</b> evalutes to 0.
* Any null arguments are ignored.
*/
public static double fdiv(Object[] args)
{
if (args == null || args.length == 0) return 0.0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("fdiv(" + psize + " args)");
double result = 1.0;
try {
result = _double(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1, end = psize; ix < end; ix++)
{
try {
result /= _double(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // div()
/**
* Returns the maximum (most positive) of the double arguments.
* Any null arguments are ignored.
*/
public static double fmax(Object[] args)
{
int psize;
if (args == null || ((psize = args.length) == 0)) return 0.0;
double result = 0.0;
try {
result = _double(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1; ix < psize; ix++)
{
try {
double temp = _double(args[ix]);
if (temp > result) result = temp;
} catch (NullPointerException e) {
}
}
return result;
} // fmax()
/**
* Returns the minimum (most negative) of the double arguments.
* Any null arguments are ignored.
*/
public static double fmin(Object[] args)
{
int psize;
if (args == null || ((psize = args.length) == 0)) return 0.0;
double result = 0.0;
try {
result = _double(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1; ix < psize; ix++)
{
try {
double temp = _double(args[ix]);
if (temp < result) result = temp;
} catch (NullPointerException e) {
}
}
return result;
} // fmin()
/**
* Real number multiplication. Returns the product of all arguments. Each argument
* is converted to an <b>int</b> type. An empty or null array <b>arg</b> evalutes to 0.
* Any null arguments are ignored.
*/
public static double fmul(Object[] args)
{
if (args == null || args.length == 0) return 0.0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("fmul(" + psize + " args)");
double result = 1.0;
try {
result = _double(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1, end = psize; ix < end; ix++)
{
try {
result *= _double(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // fmul()
/**
* Real number negation. Returns the negative of the argument.
*/
public static double fneg(double arg)
{
double result = -arg;
if (DEBUG_MODE) ThreadState.logln("fneg(" + arg + ") => " + result);
return result;
} // fneg()
/**
* Formats the value as a percentage, and returns the String.
*/
public static String formatPercent(double value)
{
return percent.format(value);
} // formatPercent()
/**
* Formats raw phone numbers both with and without area codes as follows:
* (aaa) eee-nnnn or eee-nnnn
*/
public static String formatPhone(String phone)
{
String phoneOrig = phone;
if (phone == null || phone.length() == 0) return phone;
phone = stripNonNumerics(phone.trim());
if (phone.length() == 0) return phone;
String prefix = "";
char c;
while ((c = phone.charAt(0)) == '0' || c == '1') {
prefix += c;
phone = phone.substring(1);
if (phone.length() == 0) break;
}
if (prefix.length() > 0) prefix += ' ';
int len = phone.length();
if (len == 7) return prefix + phone.substring(0, 3) + '-' + phone.substring(3);
if (len == 10) return prefix + '(' + phone.substring(0, 3) + ") " + phone.substring(3, 6)
+ '-' + phone.substring(6);
return phoneOrig;
} // formatPhone()
/**
* Convert from HTML to Unicode text. This function converts many of the encoded HTML
* characters to normal Unicode text. Example: &lt; to <. This is the opposite
* of showHtml().
* @see showHtml(String)
*/
public static String fromHtml(String text)
{
int ixz;
if (text == null || (ixz = text.length()) == 0) return text;
StringBuilder buf = new StringBuilder(ixz);
String rep = null;
for (int ix = 0; ix < ixz; ix++)
{
char c = text.charAt(ix);
if (c == '&');
{
String sub = text.substring(ix + 1).toLowerCase();
if (sub.startsWith("lt;"))
{
c = '<';
ix += 3;
}
else
if (sub.startsWith("gt;"))
{
c = '>';
ix += 3;
}
else
if (sub.startsWith("amp;"))
{
c = '&';
ix += 4;
}
else
if (sub.startsWith("nbsp;"))
{
c = ' ';
ix += 5;
}
else
if (sub.startsWith("semi;"))
{
c = ';';
ix += 5;
}
else
if (sub.startsWith("#"))
{
char c2 = 0;
for (int iy = ix + 1; iy < ixz; iy++)
{
char c1 = text.charAt(iy);
if (c1 >= '0' && c1 <= '9')
{
c2 = (char)(c2 * 10 + c1);
continue;
}
if (c1 == ';')
{
c = c2;
ix = iy;
}
break;
}
} else if (c == '<' && ix + 3 <= ixz && Character.toLowerCase(text.charAt(ix + 1)) == 'b'
&& Character.toLowerCase(text.charAt(ix + 2)) == 'r' && text.charAt(ix + 3) == '>') {
c = '\n';
}
}
if (rep != null)
{
buf.append(rep);
rep = null;
}
else buf.append(c);
}
return buf.toString();
} // fromHtml()
/**
* Real number subtraction. Each argument is subtracted from the first. If no arguments
* are submitted then the result is 0.
* Any null arguments are ignored.
*/
public static double fsub(Object[] args)
{
if (args == null || args.length == 0) return 0.0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("fsub(" + psize + " args)");
double result = 0.0;
try {
result = _double(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1, end = psize; ix < end; ix++)
{
try {
result -= _double(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // fsub()
/**
* Returns the sign of the argument as a real number: -1.0 if negative, 0.0 if 0.0, and
* 1.0 if positive.
*/
public static double fsgn(double arg)
{
if (arg < 0.0) return -1.0;
else
if (arg > 0.0) return 1.0;
else return 0.0;
} // fsgn()
/**
* Returns true if arg1 >= arg2, false otherwise.
*/
public static boolean ge(double arg1, double arg2)
{
return arg1 >= arg2;
} // ge()
/**
* Returns a new object instance.
*/
public static Object getBean(String className) throws DspException
{
try {
return Class.forName(className).newInstance();
} catch (Exception e) {
throw new DspException("Couldn't get bean " + className, e);
}
} // getBean()
/**
* Returns the value of the named member of the object. If the object is a DspObject
* get() is called. Otherwise, it uses reflection to look up and get the field.
*/
public static Object getMember(Object obj, String member) throws DspException
{
try {
return ((DspObject)obj).get(member);
} catch (ClassCastException e) {
Class<?> c = obj.getClass();
try {
Field f = c.getField(member);
// if (Modifier.isPublic(f.getModifiers())
// {
return f.get(obj);
// }
} catch (NoSuchFieldException e1) {
throw new DspException("Could not find field '" + member + '\'', e1);
} catch (IllegalAccessException e1) {
throw new DspException("Could not access field '" + member + '\'', e1);
}
}
} // getMember()
/**
* Returns the result of calling a named method of the object, passing args as the arguments
* of the function. If the object is a DspObject run() is called. Otherwise, it uses
* reflection to look up and call the method.
*/
public static Object getMember(Object obj, String member, Object[] args) throws DspException
{
// try {
// return ((DspObject) obj).run(member, args);
// } catch (ClassCastException e) {
Class<?> c = obj.getClass();
Class<?>[] types = null;
int len;
if (args != null && (len = args.length) > 0)
{
types = new Class[len];
for (int ix = 0; ix < len; ix++)
{
if (args[ix] != null)
{
types[ix] = args[ix].getClass();
}
}
}
try {
int close = 0;
Method[] meths = c.getMethods();
Method found = null;
//int choice = -1;
for (int ix = 0, ixz = meths.length; ix < ixz; ix++)
{
Method meth = meths[ix];
if (Modifier.isPublic(meth.getModifiers()) && meth.getName().equals(member))
{
Class<?>[] pTypes = meth.getParameterTypes();
if ((pTypes.length == 0 && args == null) || (args != null && pTypes.length == args.length))
{
int close1 = 1;
if (args != null)
{
for (int iy = 0, iyz = pTypes.length; iy < iyz; iy++)
{
if (pTypes[iy] == types[iy])
{
close1 += 2;
//ThreadState.logln(ix + " - " + pTypes[iy]);
}
else
if (pTypes[iy].isAssignableFrom(types[iy])) close1++;
} // for iy
} // if args
if (close1 > close)
{
//ThreadState.logln(ix + " got " + close1 + " points");
found = meth;
// choice = ix;
close = close1;
}
} // if name matches
} // for
}
if (found == null)
{
throw new DspException("Could not find method " + member + " in " + obj);
}
else
{
//ThreadState.logln("Choice " + choice);
return found.invoke(obj, args);
}
// } catch (NoSuchMethodException e1) {
// throw new DspException("Could not find method " + member + " in " + obj, e1);
} catch (IllegalAccessException e1) {
throw new DspException("Could not invoke method " + member + " in " + obj, e1);
} catch (InvocationTargetException e1) {
throw new DspException("Exception in method " + member + " in " + obj, e1.getTargetException());
} catch (Throwable e1) {
throw new DspException("Exception in method " + member + " in " + obj, e1);
}
// }
} // getMember(args)
/**
* Returns an instantiation of a tag extenion object.
*/
public static Tag getTag(DspObject temp, String prefix, String action, String className) throws DspException
{
Tag tag = (Tag)temp.get('_' + prefix + '_' + action);
if (tag == null)
{
try {
tag = (Tag)Class.forName(className).newInstance();
} catch (Exception e) {
throw new DspException("Could not create " + className);
}
}
return tag;
} // getTag()
// abstract public long getId();
/**
* Returns the prop object belonging to this group or pages.
*/
public DspProp getProp() { return prop; }
/**
* Returns true if arg1 > arg2.
*/
public static boolean gt(double arg1, double arg2)
{
boolean result = arg1 > arg2;
if (DEBUG_MODE) ThreadState.logln("gt(" + arg1 + ", " + arg2 + ") => " + result);
return result;
} // gt()
/**
* Converts the String to HTML format. It looks for certain characters and converts them
* to the proper HTML tags. If the String already contains HTML tags, these will be left
* intact. You will probably use this function heavily, unless you store HTML directly in
* your database. The following table lists the conversions that take place within this function:
* <table>
* <tr><td>From</td><td>To</td><td>Conditions and Comments</td></tr>
* <tr><td>\r, \n, or \r\n</td><td><br></td><td> </td></tr>
* <tr><td>\t</td><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td> </td></tr>
* <tr><td><space><space>...</td><td>&nbsp;...<space></td><td><space> means a space character</td></tr>
* <tr><td>&</td><td>&amp;</td><td> </td></tr>
* <tr><td>;</td><td>&semi;</td><td> </td></td>
* <tr><td>*</td><td><ul><li></td><td>Unordered list; must begin a line</td></tr>
* <tr><td>**...</td><td><ul><ul>...<li></td><td>Higher level lists; must begin a line</td></tr>
* <tr><td>#</td><td><ol><li></td><td>Ordered list; must begin a line</td></tr>
* <tr><td>##...</td><td><ol><ol>...<li></td><td>Higher level lists; must begin a line</td></tr>
* <tr><td>^</td><td><blockquote></td><td>Indented block; must begin a line</td></tr>
* <tr><td>^^...</td><td><blockquote><br><blockquote>...</td><td>Higher level indents; must begin a line</td></tr>
* <tr><td>(c) or (C)</td><td>&copy;</td><td>©</td></tr>
* <tr><td>(r) or (R)</td><td>&reg;</td><td>®</td></tr>
* <tr><td>(tm) or (TM)</td><td><small><sub>TM</small></sub></td><td><small><sup>TM</small></sup></td></tr>
* <tr><td>(sm) or (SM)</td><td><small><sub>SM</small></sub></td><td><small><sup>SM</small></sup></td></tr>
* <tr><td>{</td><td>&#123;</td><td>To prevent DSP from parsing published pages</td></tr>
* <tr><td>}</td><td>&#125;</td><td>same as above</td></tr>
* </table>
*/
public static String html(String text)
{
String org = text;
String result;
if (text == null || isHtml(text)) result = text;
else
{
int ix;
StringBuilder buf = new StringBuilder(text);
buf.ensureCapacity(text.length() * 5 / 4);
addAnchors(buf);
htmlCharsBuf(buf);
text = buf.toString();
int end = text.length();
buf.setLength(0);
int level0 = 0, level = 0, tab0 = 0, tab = 0;
char c1 = '\n', c;
boolean bar = false;
for (ix = 0; ix <= end; ix++)
{
c = c1;
c1 = ix < end ? text.charAt(ix) : (char)-1;
String app = null;
switch (c)
{
case '\r':
if (c1 == '\n')
{
c = c1;
c1 = ++ix < end ? text.charAt(ix) : (char)-1;
}
case '\n':
level = tab = 0;
if (c1 == '^')
{
while (c1 == '^')
{
c = c1;
c1 = ++ix < end ? text.charAt(ix) : (char)-1;
tab++;
}
}
if (c1 == '|')
{
bar = true;
while (c1 == '|')
{
c = c1;
c1 = ++ix < end ? text.charAt(ix) : (char)-1;
tab++;
}
}
if (c1 == '*')
{
while (c1 == '*')
{
c = c1;
c1 = ++ix < end ? text.charAt(ix) : (char)-1;
level++;
}
}
else
if (c1 == '#')
{
while (c1 == '#')
{
c = c1;
c1 = ++ix < end ? text.charAt(ix) : (char)-1;
level--;
}
}
//System.out.println("level " + level0 + " -> " + level);
//System.out.println("tab " + tab0 + " -> " + tab);
while (level0 > level && level0 > 0)
{
if (app != null) buf.append(app);
app = "</ul>";
level0--;
}
while (level0 < level && level0 < 0)
{
if (app != null) buf.append(app);
app = "</ol>";
level0++;
}
boolean br = ix > 0;
while (tab0 > tab)
{
br = false;
if (app != null) buf.append(app);
app = "</blockquote>";
tab0--;
}
while (tab0 < tab)
{
br = false;
if (app != null) buf.append(app);
if (bar) app = "<blockquote dir=ltr style=\"PADDING-RIGHT: 0px; PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #000000 2px solid; MARGIN-RIGHT: 0px\">";
else app = "<blockquote>";
tab0++;
}
bar = false;
while (level0 < level)
{
if (app != null) buf.append(app);
app = "<ul>";
level0++;
}
while (level0 > level)
{
if (app != null) buf.append(app);
app = "<ol>";
level0--;
}
if (level != 0)
{
if (app != null) buf.append(app);
app = "<li>";
}
else if (br)
{
if (app != null) buf.append(app);
app = "<br>";
}
break;
case '\t':
app = " ";
break;
case ' ':
if (c1 == ' ') app = " ";
break;
}
if (app != null) buf.append(app);
else if (c > 0) buf.append(c);
}
while (level0 != 0)
{
if (level0 < 0)
{
buf.append("</ol>");
level0++;
}
else
{
buf.append("</ul>");
level0--;
}
}
result = buf.toString();
}
if (DEBUG_MODE) ThreadState.logln("html(" + org + ") -> " + result);
return result;
} // html()
/**
* Converts the String to HTML format. It looks for certain characters and converts them
* to the proper HTML tags. If the String already contains HTML tags, these will be left
* intact. You will probably use this function heavily, unless you store HTML directly in
* your database. The following table lists the conversions that take place within this function:
* <table>
* <tr><td>From</td><td>To</td><td>Conditions and Comments</td></tr>
* <tr><td>(c) or (C)</td><td>&copy;</td><td>©</td></tr>
* <tr><td>(r) or (R)</td><td>&reg;</td><td>®</td></tr>
* <tr><td>(tm) or (TM)</td><td><small><sub>TM</small></sub></td><td><small><sup>TM</small></sup></td></tr>
* <tr><td>(sm) or (SM)</td><td><small><sub>SM</small></sub></td><td><small><sup>SM</small></sup></td></tr>
* <tr><td>{</td><td>&#123;</td><td>To prevent DSP from parsing published pages</td></tr>
* <tr><td>}</td><td>&#125;</td><td>same as above</td></tr>
* </table>
*/
public static String htmlChars(CharSequence text)
{
StringBuilder buf = new StringBuilder(text);
buf.ensureCapacity(text.length() * 5 / 4);
htmlCharsBuf(buf);
String result = buf.toString();
if (DEBUG_MODE) ThreadState.logln("htmlChars(" + text + ") -> " + result);
return result;
} // htmlChars()
private static void htmlCharsBuf(StringBuilder buf)
{
replaceBuf(buf, "(TM)", "<small><small><sup>TM</sup></small></small>");
replaceBuf(buf, "(tm)", "<small><small><sup>TM</sup></small></small>");
replaceBuf(buf, "(SM)", "<small><small><sup>SM</sup></small></small>");
replaceBuf(buf, "(sm)", "<small><small><sup>SM</sup></small></small>");
replaceBuf(buf, "(R)", "®");
replaceBuf(buf, "(r)", "®");
replaceBuf(buf, "(C)", "©");
replaceBuf(buf, "(c)", "©");
if (buf != null)
{
for (int ix = 0, ixz = buf.length(); ix < ixz; ix++)
{
char c = buf.charAt(ix);
if (c > 0x7f || c == '{' || c == '}')
{
String str = "&#" + (int)c + ';';
buf.replace(ix, ix + 1, str);
ix += str.length() - 1;
}
}
}
if (DEBUG_MODE) ThreadState.logln("htmlCharsBuf()");
} // htmlCharsBuf()
/**
* Join a sequence into a single string, separated by sep.
* Items that are null are skipped.
* @param list list of items
* @param sep separator
* @return joined string
*/
public static CharSequence join(Collection<?> list, String sep) {
StringBuilder result = new StringBuilder();
for (Object item : list) {
if (item != null) {
if (result.length() > 0) result.append(sep);
result.append(item);
}
}
return result;
}
/**
* Join a sequence into a single string, separated by sep.
* Items that are null are skipped.
* @param list list of items
* @param sep separator
* @return joined string
*/
public static CharSequence join(Object[] list, String sep) {
StringBuilder result = new StringBuilder();
for (Object item : list) {
if (item != null) {
if (result.length() > 0) result.append(sep);
result.append(item);
}
}
return result;
}
/**
* Binary multiplexer, If the first argument evaluates to true then the second argument
* is returned. If false, the third argument is return, or null if there was no third argument.
*/
public static Object iff(Object[] args) throws IllegalArgumentException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("iff() can only accept 2 or 3 parameters");
Object param = args[0];
// ThreadState.log("iff(" + args + ") -> ");
if (_boolean(param))
{
if (DEBUG_MODE) ThreadState.logln(args[1]);
return args[1];
}
else
if (psize == 3)
{
if (DEBUG_MODE) ThreadState.logln(args[2]);
return args[2];
}
else
{
if (DEBUG_MODE) ThreadState.logln("null");
return null;
}
} // iff()
/**
* Return the first index of a substring within the String. This function returns the index of
* the second element as a String if found within the first as a String. If not found then -1 is returned.
* If three elements are sent, it is starting index for the search.
* @see lastIndexOf(Object[])
*/
public static int indexOf(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("indexOf() can only accept 2 or 3 arguments");
String data = _String(args[0]);
String find = _String(args[1]);
int result;
if (data == null || find == null) result = -1;
else
{
int index = 0;
if (psize > 2)
{
index = _int(args[2]);
}
result = data.indexOf(find, index);
}
if (DEBUG_MODE) ThreadState.logln("indexOf(" + args + ") -> " + result);
return result;
} // indexOf()
/**
* Format Timestamp in various ways. This multipurpose function can convert a Timestamp object
* to a String in several formats. This function only
* accepts one or two arg elements. If two, the first is the requested function
* to perform, and the second is converted to java.sql.Time. If one, the request is assumed
* to be "short". The following are the types of functions performed based on the request:
* <table><tr><td>Request (arg1)</td><td>Returned</td><td>Type</td><td>Example</td></tr>
* <tr><td>short</td><td>Short Timestamp</td><td>String</td><td>2000-11-20 12:13 PM</td></tr>
* <tr><td>long</td><td>Long Timestamp</td><td>String</td><td>Monday, November 20, 2000 12:13:52.239 PM MST</td></tr>
* <tr><td>sql</td><td>SQL Timestamp</td><td>String</td><td>{ts '2000-11-20 12:13:52.239 PM MST'}</td></tr>
* <tr><td>access</td><td>MS Access Timestamp</td><td>String</td><td>#2000-11-20 12:13:56 PM#</td></tr></table>
* @deprecated
*/
public static Object instant(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 1 || psize == 2))
throw new IllegalArgumentException("instant() can only accept 1 or 2 arguments");
String type = null;
Timestamp date;
if (psize == 2)
{
type = _String(args[0]);
date = _Instant(args[1]);
}
else date = _Instant(args[0]);
String result;
if (psize == 1
|| SHORT.equalsIgnoreCase(type)) result = instantShort(date);
else
if (LONG.equalsIgnoreCase(type)) result = instantLong(date);
else
if (SQL.equalsIgnoreCase(type)) result = instantSql(date);
else
if (ACCESS.equalsIgnoreCase(type)) result = instantAccess(date);
else throw new IllegalArgumentException("instant(" + type + ", " + date + ") error, unknown instant function");
if (DEBUG_MODE) ThreadState.logln("instant(" + args + ") -> " + result);
return result;
} // instant()
/**
* Convert Timestamp to an MS Access SQL String. Converts the Timestamp to a String for use
* in an SQL statement when using Microsoft Access(tm). This is needed because MS Access,
* using the JDBC-ODBC bridge, doesn't support the standard JDBC Timestamp format.
*/
public static String instantAccess(Timestamp date)
{
String result;
if (date == null) result = NULL;
else result = '#' + instantAccessForm.format(date) + '#';
if (DEBUG_MODE) ThreadState.logln("instantAccess(" + date + ") -> " + result);
return result;
} // instantAccess()
/**
* Add units of time to a Timestamp. Adds years, months, weeks, days, hours,
* minutes, seconds, milliseconds from Time. It accepts 2 or three members of args. The first
* is convert to Time. The second is the value to be added. The third, if present, is
* the units String: years, months, weeks, days, hours, mins, secs, msecs. If no third member
* is present, the units are assumed to be milliseconds.
*/
public static Timestamp instantAdd(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("instantAdd() can only accept 2 or 3 arguments");
Timestamp date = _Instant(args[0]);
int value = _int(args[1]);
String str = "msec";
if (psize == 3)
{
str = _String(args[2]);
}
int type = 'i';
if (str.length() > 0) type = Character.toLowerCase(str.charAt(0));
if (str.length() > 1 && type == 'm')
{
int t2 = Character.toLowerCase(str.charAt(1));
if (t2 == 's') type = 'i';
else
if (t2 == 'i') type = 'n';
}
Calendar c = Calendar.getInstance();
c.setTime(date);
switch (type)
{
case 'i':
c.add(Calendar.MILLISECOND, value);
break;
case 's':
c.add(Calendar.SECOND, value);
break;
case 'n':
c.add(Calendar.MINUTE, value);
break;
case 'h':
c.add(Calendar.HOUR, value);
break;
case 'd':
c.add(Calendar.DATE, value);
break;
case 'm':
c.add(Calendar.MONTH, value);
break;
case 'w':
c.add(Calendar.WEEK_OF_YEAR, value);
break;
case 'y':
c.add(Calendar.YEAR, value);
break;
default:
throw new IllegalArgumentException("Unknown value type: " + str);
}
Timestamp result = new Timestamp(c.getTime().getTime());
if (DEBUG_MODE) ThreadState.logln("instantAdd(" + args + ") -> " + result);
return result;
} // instantAdd()
/**
* Returns the date and time in the American standar format MM/DD/YYYY HH:MM AM|PM
*/
public static String instantAmerican(Date date)
{
String result;
if (date == null) result = null;
else result = instantAmer.format(date);
if (DEBUG_MODE) ThreadState.logln("instantAmerican(" + date + ") -> " + result);
return result;
} // instantAmerican()
/**
* Returns a String with the computed difference between two Timestamps.
*/
public static String instantDiff(Timestamp time1, Timestamp time2)
{
return msecDiff(time1.getTime(), time2.getTime());
} // instantDiff()
/**
* Convert Instant to long String. Converts the Timestamp to a long formatted String.
*/
public static String instantLong(Timestamp date)
{
String result;
if (date == null) result = null;
else result = instantlong.format(date);
if (DEBUG_MODE) ThreadState.logln("instantLong(" + date + ") -> " + result);
return result;
} // instantLong()
/**
* Convert Instant to short String. Converts the Timestamp to a short formatted String.
*/
public static String instantShort(Timestamp date)
{
String result;
if (date == null) result = null;
else result = date.toString();
if (DEBUG_MODE) ThreadState.logln("instantShort(" + date + ") -> " + result);
return result;
} // instantShort()
/**
* Convert Timestamp to an SQL String. Converts the Timestamp to a String for use
* in an SQL statement.
*/
public static String instantSql(Timestamp date)
{
String result;
if (date == null) result = NULL;
else result = "{ts '" + date + "'}";
if (DEBUG_MODE) ThreadState.logln("instantSql(" + date + ") -> " + result);
return result;
} // instantSql()
/**
* Subtract units of time from a Timestamp. Subtracts years, months, weeks, days, hours,
* minutes, seconds, milliseconds from Time. It accepts 2 or three members of args. The first
* is convert to Time. The second is the value to be subtracted. The third, if present, is
* the units String: years, months, weeks, days, hours, mins, secs, msecs. If no third member
* is present, the units are assumed to be milliseconds.
*/
public static Timestamp instantSub(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("instantSub() can only accept 2 or 3 arguments");
args[1] = new Integer(-_int(args[1]));
Timestamp result = instantAdd(args);
if (DEBUG_MODE) ThreadState.logln("instantSub(" + args + ") -> " + result);
return result;
} // instantSub()
/**
* Returns true if the object is a java.sql.Date or can be converted to one.
*/
public static boolean isDate(Object obj)
{
boolean result = false;
try {
result = _Date(obj) != null;
} catch (Exception e) {
}
if (DEBUG_MODE) ThreadState.logln("isDate(" + obj + ") -> " + result);
return result;
} // isDate()
/**
* Returns true if the object is a real number or can be converted to one.
*/
public static boolean isFloat(Object obj)
{
boolean result = false;
try {
result = _Float(obj) != null;
} catch (Exception e) {
}
if (DEBUG_MODE) ThreadState.logln("isFloat(" + obj + ") -> " + result);
return result;
} // isFloat()
/**
* Returns true if the String begins and ends with HTML tags.
*/
public static boolean isHtml(String text)
{
boolean result = false;
if (text != null)
{
String temp = text.trim();
int end = temp.length();
if (end >= 3 && temp.charAt(0) == '<'
&& temp.charAt(end - 1) == '>') result = true;
}
if (DEBUG_MODE) ThreadState.logln("isHtml(" + text + ") -> " + result);
return result;
} // isHtml()
/**
* Returns true if the object is a java.sql.Timestamp or can be converted to one.
*/
public static boolean isInstant(Object obj)
{
boolean result = false;
try {
result = _Instant(obj) != null;
} catch (Exception e) {
}
if (DEBUG_MODE) ThreadState.logln("isInstant(" + obj + ") -> " + result);
return result;
} // isInstant()
/**
* Returns true if the object is a integral number or can be converted to one.
*/
public static boolean isInt(Object obj)
{
boolean result = false;
try {
result = _Integer(obj) != null;
} catch (Exception e) {
}
if (DEBUG_MODE) ThreadState.logln("isInt(" + obj + ") -> " + result);
return result;
} // isInt()
/**
* Same as isInt(Object)
*/
public static boolean isInteger(Object obj)
{
return isInt(obj);
} // isInteger()
/**
* Returns true if the object is a null.
*/
public static boolean isNull(Object obj)
{
boolean result = (obj == null) || (obj instanceof DspNull);
if (DEBUG_MODE) ThreadState.logln("isNull(" + obj + ") -> " + result);
return result;
} // isNull()
/**
* Returns true if obj is not null or if obj is a String returns true if it is not empty.
*/
public static boolean isSet(Object obj)
{
if (obj == null) return false;
String str = _String(obj);
return str.length() > 0;
} // isSet()
/**
* Returns true if the object is a java.sql.Time or can be converted to one.
*/
public static boolean isTime(Object obj)
{
boolean result = false;
try {
result = _Time(obj) != null;
} catch (Exception e) {
}
if (DEBUG_MODE) ThreadState.logln("isTime(" + obj + ") -> " + result);
return result;
} // isTime()
public void jspInit() {}
public void jspDestroy() {}
/**
* Return the last index of a substring within the String. This function returns the index of
* the second element as a String if found within the first as a String. If not found then -1 is returned.
* If three elements are sent, it is starting index for the search.
* @see indexOf(Object[])
*/
public static int lastIndexOf(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("lastIndexOf() can only accept 2 or 3 arguments");
String data = _String(args[0]);
String find = _String(args[1]);
int result;
if (data == null || find == null) result = -1;
else
{
int index = data.length();
if (psize > 2)
{
index = _int(args[2]);
}
result = data.lastIndexOf(find, index);
}
if (DEBUG_MODE) ThreadState.logln("lastIndexOf(" + args + ") -> " + result);
return result;
} // lastIndexOf()
/**
* Returns true if the first argument is less than or equal to the second, comparison
* is done with real numbers.
*/
public static boolean le(double arg1, double arg2)
{
boolean result = arg1 <= arg2;
if (DEBUG_MODE) ThreadState.logln("le(" + arg1 + ", " + arg2 + ") => " + result);
return result;
} // le()
/**
* Return the length of the String.
*/
public static int length(CharSequence data)
{
int result;
if (data == null) result = 0;
else
{
result = data.length();
}
if (DEBUG_MODE) ThreadState.logln("length(" + data + ") -> " + result);
return result;
} // length()
/**
* Truncate the String to lim characters, from the left.
* @see rlimit()
*/
public static String limit(String data, int lim)
{
String result = null;
if (lim > 0)
{
result = data;
if (data != null && data.length() > lim)
{
result = data.substring(0, lim);
}
}
if (DEBUG_MODE) ThreadState.logln("limit(" + data + ", " + lim + ") -> " + result);
return result;
} // limit()
/**
* Convert String to lower case.
*/
public static String lowerCase(String arg)
{
String result;
if (arg == null) result = null;
else result = arg.toLowerCase();
if (DEBUG_MODE) ThreadState.logln("lowerCase(" + arg + ") -> " + arg);
return result;
} // lowerCase()
/**
* Returns true if the first argument is less than the second, compared as real numbers.
*/
public static boolean lt(double arg1, double arg2)
{
boolean result = arg1 < arg2;
if (DEBUG_MODE) ThreadState.logln("lt(" + arg1 + ", " + arg2 + ") => " + result);
return result;
} // lt()
private DspStatement makeStatement(String name, int type)
throws DspException, IllegalArgumentException
{
DspStatement state;
boolean debug = false, trace = false;
try { debug = _boolean(ThreadState.getOpen().get(DspObject.DEBUG)); } catch (NumberFormatException e) {}
try { trace = _boolean(ThreadState.getOpen().get(DspObject.TRACE)); } catch (NumberFormatException e) {}
switch (type)
{
case ARRAY_STMT:
state = new DspStatementArray(name, debug, trace);
break;
case DIR_STMT:
state = new DspStatementDir(name, debug, trace);
break;
case SCAN_STMT:
state = new DspStatementScan(name, debug, trace);
break;
case SQL_STMT:
state = new DspStatementSql(name, debug, trace);
break;
default: throw new IllegalArgumentException("Invalid statement type: " + type);
}
return state;
} // makeStatement()
/**
* Returns the maximum (most positive) of the int arguments.
* Any null arguments are ignored.
*/
public static int max(Object[] args)
{
int psize;
if (args == null || ((psize = args.length) == 0)) return 0;
int result = 0;
try {
result = _int(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 0; ix < psize; ix++)
{
try {
int temp = _int(args[ix]);
if (temp > result) result = temp;
} catch (NullPointerException e) {
}
}
return result;
} // max()
/**
* Returns the minimum (most negative) of the int arguments.
* Any null arguments are ignored.
*/
public static int min(Object[] args)
{
int psize;
if (args == null || ((psize = args.length) == 0)) return 0;
int result = 0;
try {
result = _int(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 0; ix < psize; ix++)
{
try {
int temp = _int(args[ix]);
if (temp < result) result = temp;
} catch (NullPointerException e) {
}
}
return result;
} // min()
/**
* Returns the remainder of num / den
*/
public static int mod(int num, int den)
{
return num % den;
} // mod()
/**
* Retuns the difference between two millisecond time values, as a String.
*/
public static String msecDiff(long date1, long date2)
{
double diff = date1 > date2 ? date1 - date2 : date2 - date1;
String result = null;
if (diff == 0) result = "no time";
else
{
if (diff < 1000) result = diff + " milliseconds";
else
{
diff /= 1000;
if (diff < 60) result = tens.format(diff) + " seconds";
else
{
diff /= 60;
if (diff < 60) result = tens.format(diff) + " minutes";
else
{
diff /= 60;
if (diff < 24) result = tens.format(diff) + " hours";
else
{
diff /= 24l;
if (diff < 31) result = tens.format(diff) + " days";
else if (diff < 365) result = tens.format(diff / 31) + " months";
else result = tens.format(diff / 365) + " years";
}
}
}
}
}
if (DEBUG_MODE) ThreadState.logln("msecDiff(" + date1 + ", " + date2 + ") -> " + result);
return result;
} // msecDiff()
/**
* Integer multiplication. Returns the product of all arguments. Each argument
* is converted to an <b>int</b> type. An empty or null array <b>arg</b> evalutes to 0.
* Any null arguments are ignored.
*/
public static int mul(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("mul(" + psize + " args)");
int result = 1;
try {
result = _int(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1, end = psize; ix < end; ix++)
{
try {
result *= _int(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // mul()
/**
* Return one of several arguments depending the first. The first argument is compared
* with each odd indexed argument. If a match is found then the following argument is returned.
* If no match is found then the last argument is return as the default, or null if there
* were an odd number of arguments. If the first argument is a string, then the comparisons
* by converting the objects to strings and and ignoring the case. Otherwise, Object.equals()
* is used for comparison and the programmer must ensure type and value match.
*/
public static Object multiplex(Object[] args) throws IllegalArgumentException
{
int psize = args.length;
if (!(psize >= 3))
throw new IllegalArgumentException("multiplex() requires 3 or more arguments");
Object obj = args[0];
Object def = (psize & 1) == 0 ? args[psize - 1] : null;
Object result = def;
if (obj != null)
{
String str = obj instanceof String ? (String)obj : null;
for (int ix = 1, end = psize - 1; ix < end; ix += 2)
{
Object test = args[ix];
if (test != null)
{
if ((str != null && str.equalsIgnoreCase(_String(test)))
|| obj.equals(test))
{
result = args[ix + 1];
break;
}
}
}
}
if (DEBUG_MODE) ThreadState.logln("multiplex(" + args + ") -> " + result);
return result;
} // multiplex()
/**
* Not Equal. Return true if the two objects are not equal. This calls eq() and returns the
* boolean negative.
* @see eq(Object, Object)
*/
public boolean ne(Object arg1, Object arg2) //throws Exception
{
boolean result = !eq(arg1, arg2);
if (DEBUG_MODE) ThreadState.logln("ne(" + arg1 + ", " + arg2 + ") -> " + result);
return result;
} // ne()
/**
* Integer Negation. Return the integer negative of the argument.
*/
public static int neg(int arg)
{
int result = -arg;
if (DEBUG_MODE) ThreadState.logln("neg(" + arg + ") => " + result);
return result;
} // neg()
/**
* Returns a path with the /./, and // removed and /folder/../ simplified. Note: paths
* are converted to POSIX/Unix standard.
*/
public static String normalizePath(String path)
{
if (path == null || path.length() < 2) return path;
int ix = 0;
StringBuilder buf = new StringBuilder(path);
char sep = File.separatorChar;
// Convert non Posix file separators to slashes
if (sep != '/')
{
boolean changed = false;
while ((ix = path.indexOf(sep, ix)) >= 0)
{
buf.setCharAt(ix++, '/');
changed = true;
}
// If it starts with a DOS drive letter, preceed the path with a '/'
if (sep == '\\' && buf.charAt(1) == ':')
{
char c = buf.charAt(0);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
buf.insert(0, '/');
changed = true;
}
}
if (changed) path = buf.toString();
}
// loop until no changes happen
String temp = null;
do {
temp = path;
// convert // to /
while ((ix = path.indexOf("//")) >= 0)
{
buf.deleteCharAt(ix + 1);
path = buf.toString();
}
// convert /./ to /
while ((ix = path.indexOf("/./")) >= 0)
{
buf.delete(ix + 1, ix + 3);
path = buf.toString();
}
// convert /folder/../ to /
ix = -1;
while ((ix = path.indexOf("/../", ix + 1)) >= 0)
{
int iy = path.lastIndexOf('/', ix - 1);
if (iy >= 0 && (ix <= 2 || !buf.toString().substring(ix - 2, ix).equals("..")))
{
buf.delete(iy + 1, ix + 4);
path = buf.toString();
ix = iy - 1;
}
}
} while (!temp.equals(path));
return path;
} // normalizePath()
/**
* Return the boolean negative of the argument.
*/
public static boolean not(boolean arg)
{
boolean result = !arg;
if (DEBUG_MODE) ThreadState.logln("not(" + arg + ") => " + result);
return result;
} // not()
/**
* Return the Time of day.
*/
public static Time now()
{
Time result = new Time(System.currentTimeMillis());
if (DEBUG_MODE) ThreadState.logln("now() => " + result);
return result;
} // now()
/**
* Logical Or. Calculates the logical <b>or</b> of all arguments.
* Each argument is converted to a boolean as it is used. An empty or null
* array arg evaluates to 0. Note, this function cannot do short-circut
* evalation, as Java dose when you use the || operator.
* @see and()
*/
public static boolean or(Object[] args)
{
if (args == null || args.length == 0) return false;
int psize = args.length;
boolean result = false;
for (int ix = 0, end = psize; !result && ix < end; ix++)
{
try {
result |= _boolean(args[ix]);
} catch (NullPointerException e) {
}
}
if (DEBUG_MODE) ThreadState.logln("or(" + psize + " args) -> " + result);
return result;
} // or()
/**
* Make String ready for use in an SQL statement. Adds single quotes around the string
* and quotes embeded quotes.
* @see sql(String)
*/
public static String quote(String value)
{
int len;
boolean unicode = false;
if (value == null || (len = value.length()) == 0) return NULL;
StringBuilder buf = new StringBuilder(len + len / 10 + 5);
buf.append('\'');
for (int ix = 0, iz = value.length(); ix < iz; ix++)
{
char c = value.charAt(ix);
if (c > 127 && !unicode)
{
buf.insert(0, 'N'); // MS SQL Server 7 specific
unicode = true;
buf.append(c);
}
else
if (c == '\'')
{
buf.append("''");
}
else buf.append(c);
}
buf.append('\'');
String result = buf.toString();
if (DEBUG_MODE) ThreadState.logln("quote(" + value + ") -> " + result);
return result;
} // quote()
/**
* Make String ready for use as a double quoted HTML attribute. Converts embeded quotes to
* ", and <> to < and >. It will enclose the resulting string in double quotes if
* the second parameter is true.
*/
public static String quoteHtml(String value, boolean enclose)
{
int len;
if (value == null || (len = value.length()) == 0)
{
if (enclose) return "\"\"";
return "";
}
StringBuilder buf = new StringBuilder(len + len / 10 + 5);
if (enclose) buf.append('"');
for (int ix = 0, iz = value.length(); ix < iz; ix++)
{
char c = value.charAt(ix);
switch (c) {
case '"':
buf.append(""");
break;
case '<':
buf.append("<");
break;
case '>':
buf.append(">");
break;
default:
buf.append(c);
}
}
if (enclose) buf.append('"');
String result = buf.toString();
if (DEBUG_MODE) ThreadState.logln("quoteHtml(" + value + ", " + enclose + ") -> " + result);
return result;
} // quoteHtml()
/**
* Make String ready for use as a double quoted HTML attribute. Converts embeded quotes to
* ". It will not enclose the resulting string in double quotes.
*/
public static String quotes(String value)
{
return quoteHtml(value, false);
} // quotes()
/**
* Make String ready for use in a JavaScript expression. Adds single quotes around the string
* and backslashes embeded quotes.
* @see _script(String)
*/
public static String quoteScript(String value)
{
int len;
if (value == null) return NULL;
if ((len = value.length()) == 0) return "''";
StringBuilder buf = new StringBuilder(len + len / 10 + 5);
buf.append('\'');
for (int ix = 0, iz = value.length(); ix < iz; ix++)
{
char c = value.charAt(ix);
if (c == '<') {
buf.append("<");
continue;
}
if (c == '>') {
buf.append(">");
continue;
}
if (c == '"') {
buf.append(""");
continue;
}
if (c == '\'' || c == '\\') buf.append("\\");
buf.append(c);
}
buf.append('\'');
String result = buf.toString();
if (DEBUG_MODE) ThreadState.logln("quoteScript(" + value + ") -> " + result);
return result;
} // quoteScript()
/**
* Make String ready for use in a JavaScript expression. Adds double quotes around the string
* and backslashes embeded quotes.
* @see quotes(String)
*/
public static String quotesScript(String value)
{
int len;
if (value == null) return NULL;
if ((len = value.length()) == 0) return "''";
StringBuilder buf = new StringBuilder(len + len / 10 + 5);
buf.append('"');
for (int ix = 0, iz = value.length(); ix < iz; ix++)
{
char c = value.charAt(ix);
if (c == '<') {
buf.append("<");
continue;
}
if (c == '>') {
buf.append(">");
continue;
}
if (c == '"' || c == '\\')
{
buf.append("\\");
}
else buf.append(c);
}
buf.append('"');
String result = buf.toString();
if (DEBUG_MODE) ThreadState.logln("quotesScript(" + value + ") -> " + result);
return result;
} // quotesScript()
/**
* Stores the tag extension object for use later in the same request.
*/
public static void releaseTag(DspObject temp, String prefix, String action, Tag tag) throws DspException
{
tag.release();
temp.set('_' + prefix + '_' + action, tag);
} // releaseTag()
/**
* Substring Replacer. For each instance of <b>sub</b> found in <b>str</b>, it is replaced
* by <b>rep</b>. The resulting String is returned.
*/
public static String replace(String str, String sub, String rep)
{
StringBuilder buf = null;
int lenS = sub.length();
for (int last = 0;;)
{
int ix = str.indexOf(sub, last);
if (ix < 0)
{
if (buf != null)
{
buf.append(str.substring(last));
str = buf.toString(); // return str as result
}
break;
}
if (buf == null) buf = new StringBuilder(str.length() * 3 / 2);
buf.append(str.substring(last, ix));
buf.append(rep);
last = ix + lenS;
}
return str;
} // replace()
/**
* Substring Replacer. For each instance of <b>sub</b> found in <b>str</b>, it is replaced
* by <b>rep</b>. The buffer argument itself is modifed and returned. This is faster than
* replace(), especially useful when called multiple times for various replacements.
*/
public static StringBuilder replaceBuf(StringBuilder buf, String sub, String rep)
{
String str = buf.toString();
int lenS = sub.length();
int diff = rep.length() - lenS;
int offset = 0;
for (int last = 0;;)
{
int ix = str.indexOf(sub, last);
if (ix < 0) break;
buf.replace(ix + offset, ix + offset + lenS, rep);
last = ix + lenS;
offset += diff;
}
return buf;
} // replaceBuf()
/**
* Return the Timestamp of this instant.
*/
public static Timestamp rightNow()
{
return new Timestamp(System.currentTimeMillis());
} // rightNow()
/**
* Truncate the String to lim characters, from the right.
* @see limit()
*/
public static String rlimit(String data, int lim)
{
String result = null;
if (data != null && lim > 0)
{
result = data;
int len;
if (data != null && (len = data.length()) > lim)
{
result = data.substring(len - lim);
}
}
if (DEBUG_MODE) ThreadState.logln("rlimit(" + data + ", " + lim + ") -> " + result);
return result;
} // rlimit()
private static final double[] mulDig = {1, 10, 100, 1000, 10000, 100000,
1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12};
private static final double[] divDig = {1, .1, .01, .001, .0001, .00001,
1e-6, 1e-7, 1e-8, 1e-9, 1e-10, 1e-11, 1e-12};
/**
* Round value off to a specified number of digists.
* @param value the value to round off
* @param digits the number of digits to keep, 0-12
*/
public static double round(double value, int digits) throws IllegalArgumentException
{
if (digits < 0 || digits >= mulDig.length)
throw new IllegalArgumentException("Only 0 to 12 digits allowed for round()");
return Math.round(value * mulDig[digits]) * divDig[digits];
} // round()
/**
* Returns an integer that has it's bits scrambled. If the same resulting value is again sent
* through this function the original value will be returned.
*/
public static int scramble(int value, String key)
{
byte[] shifts = new byte[32];
for (int ix = 0; ix < 32; ix++)
{
shifts[ix] = (byte)ix;
}
int hash = key.hashCode();
int v = value ^ hash;
Random rand = new Random((long)hash << 32 | hash);
for (int ix = 0; ix < 32; ix++)
{
byte temp = shifts[ix];
int r = (int)(rand.nextFloat() * 32);
shifts[ix] = shifts[r];
shifts[r] = temp;
}
//System.out.print("scramble [");
//for (int ix = 0; ix < 32; ix++)
//{
// if (ix > 0) System.out.print(", ");
// System.out.print(shifts[ix]);
//}
//System.out.println("]");
int result = 0;
for (int ix = 0; ix < 32; ix++)
{
int shift = shifts[ix];
result |= ((v >>> ix) & 1) << shift;
}
//System.out.println("value " + Integer.toHexString(value) + ", hash " + Integer.toHexString(value) + ", result " + Integer.toHexString(result));
if (DEBUG_MODE) ThreadState.logln("scramble(" + value + ", " + key + ") -> " + result);
return result;
} // scramble()
/**
* Sets the value of the named member of the object to value. If the object is a DspObject
* set() is called. Otherwise, it uses reflection to look up and set the field.
*/
public static Object setMember(Object obj, String member, Object value) throws DspException
{
try {
((DspObject)obj).set(member, value);
} catch (ClassCastException e) {
Class<?> c = obj.getClass();
try {
Field f = c.getField(member);
// if (Modifier.isPublic(f.getModifiers())
// {
f.set(obj, value);
// }
} catch (NoSuchFieldException e1) {
throw new DspException("Could not find field " + member, e1);
} catch (IllegalAccessException e1) {
throw new DspException("Could not access field " + member, e1);
}
}
return value;
} // setMember()
/**
* Set the prop object. Used internally to set up the initial prop object.
*/
public void setProp(DspProp value)
{
prop = value;
} // setProp()
/**
* Return the sign of the argument: -1 negative, 0 for 0, or 1 for positive.
*/
public static int sgn(int arg)
{
if (arg < 0) return -1;
else
if (arg > 0) return 1;
else return 0;
} // sgn()
/**
* Convert characters not allowed in HTML to allowable characters. Example:
* < to &lt;. This is the opposite of fromHtml().
* @see fromHtml(String)
*/
public static String showHtml(String text)
{
if (text == null) return text;
int end = text.length();
StringBuilder buf = new StringBuilder(end * 5 / 4);
// loop:
for (int ix = 0; ix < end; ix++)
{
char c = text.charAt(ix);
String app = null;
switch (c)
{
case '<':
app = "<";
break;
case '>':
app = ">";
break;
case '&':
app = "&";
break;
case '"':
app = """;
break;
}
if (app != null) buf.append(app);
else if (c > 0) buf.append(c);
}
return buf.toString();
} // showHtml()
/**
* Format boolean for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(boolean value)
{
return value ? "1" : "0";
} // sql(boolean)
/**
* Format Boolean for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(Boolean value)
{
if (value == null) return NULL;
return value.booleanValue() ? "1" : "0";
} // sql(Boolean)
/**
* Format value for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(byte value)
{
return Byte.toString(value);
} // sql(byte)
/**
* Format char for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(char value)
{
return quote(String.valueOf(value));
} // sql(char)
/**
* Format Character for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(Character value)
{
if (value == null) return NULL;
return quote(String.valueOf(value));
} // sql(Character)
/**
* Format a list of objects as an paren enclosed comma delimited list.
*/
public static String sql(Collection<Object> value) {
Iterator<Object> it = value.iterator();
StringBuilder buf = new StringBuilder("(");
while (it.hasNext()) {
if (buf.length() > 1) buf.append(", ");
buf.append(sql(it.next()));
}
buf.append(')');
return buf.toString();
} // sql(Collection)
/**
* Format Date for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(Date value)
{
return dateSql(value);
} // sql(Date)
/**
* Format Date for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(java.util.Date value)
{
if (value == null) return NULL;
return instantSql(new Timestamp(value.getTime()));
} // sql(java.util.Date)
/**
* Format value for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(double value)
{
return Double.toString(value);
} // sql(double)
/**
* Format value for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(float value)
{
return Float.toString(value);
} // sql(float)
/**
* Format value for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(int value)
{
return Integer.toString(value);
} // sql(int)
/**
* Format Number for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(Number value)
{
return value == null ? NULL : value.toString();
} // sql(Number)
/**
* Format value for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(long value)
{
return Long.toString(value);
} // sql(long)
/**
* Format value for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(short value)
{
return Short.toString(value);
} // sql(String)
/**
* Format String for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(String value)
{
return quote(value);
} // sql(String)
/**
* Format Time for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(Time value)
{
return timeSql(value);
} // sql(Time)
/**
* Format Timestamp for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(Timestamp value)
{
return instantSql(value);
} // sql(Timestamp)
/**
* Format Object for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
@SuppressWarnings("unchecked")
public static String sql(Object value)
{
if (value == null) return NULL;
try {
return sql((Number) value);
} catch (ClassCastException e) {
try {
java.util.Date date = (java.util.Date) value;
try {
return sql((Time) date);
} catch (ClassCastException e1) {
try {
return sql((Date) date);
} catch (ClassCastException e2) {
try {
return sql((Timestamp) date);
} catch (ClassCastException e3) {
return sql(date);
}
}
}
} catch (ClassCastException e7) {
try {
return sql((Boolean) value);
} catch (ClassCastException e4) {
try {
return sql((Character) value);
} catch (ClassCastException e5) {
try {
return sql((Collection<Object>) value);
} catch (ClassCastException e6) {
try {
return sql((Object[]) value);
} catch (ClassCastException e8) {
return sql(value.toString());
}
}
}
}
}
}
} // sql()
/**
* Format an array of numbers as an paren enclosed comma delimited list.
*/
/* public static String sql(Number[] value) {
StringBuilder buf = new StringBuilder("(");
for (int ix = 0, ixz = value.length; ix < ixz; ix++) {
if (buf.length() > 1) buf.append(", ");
buf.append(sql(value[ix]));
}
buf.append(')');
return buf.toString();
} // sql(Number[])
*/
/**
* Format an array of objects as an paren enclosed comma delimited list.
*/
public static String sql(Object[] value) {
StringBuilder buf = new StringBuilder("(");
for (int ix = 0, ixz = value.length; ix < ixz; ix++) {
if (buf.length() > 1) buf.append(", ");
buf.append(sql(value[ix]));
}
buf.append(')');
return buf.toString();
} // sql(Object[])
/**
* Format an array of strings as an paren enclosed comma delimited list.
*/
/* public static String sql(String[] value) {
StringBuilder buf = new StringBuilder("(");
for (int ix = 0, ixz = value.length; ix < ixz; ix++) {
if (buf.length() > 1) buf.append(", ");
buf.append(sql(value[ix]));
}
buf.append(')');
return buf.toString();
} // sql(String[])
*/
/**
* Convert object to a Boolean and format it suitable for use in an SQL statement.
*/
public static String sqlBoolean(boolean arg)
{
return sql(arg);
} // sqlBoolean()
/**
* Convert value to char and format it suitable for use in an SQL statement.
*/
public static String sqlChar(char arg)
{
return sql(arg);
} // sqlChar()
/**
* Convert Object to Character and format it suitable for use in an SQL statement.
*/
public static String sqlCharacter(Object arg)
{
return sql(_Character(arg));
} // sqlCharacter()
/**
* Convert object to a Date and format it suitable for use in an SQL statement.
*/
public static String sqlDate(Date arg)
{
return sql(arg);
} // sqlDate()
/**
* Convert object to an Double and format it suitable for use in an SQL statement.
*/
public static String sqlDouble(Object arg)
{
return sql(_Double(arg));
} // sqlDouble()
/**
* Convert object to an Float and format it suitable for use in an SQL statement.
*/
public static String sqlFloat(Object arg)
{
return sql(_Float(arg));
} // sqlFloat()
/**
* Convert object to a Timestamp and format it suitable for use in an SQL statement.
*/
public static String sqlInstant(Timestamp arg)
{
return sql(arg);
} // sqlInstant()
/**
* Convert object to an int and format it suitable for use in an SQL statement.
*/
public static String sqlInt(int arg)
{
return sql(arg);
} // sqlInt()
/**
* Convert object to an Integer and format it suitable for use in an SQL statement.
*/
public static String sqlInteger(Object arg)
{
return sql(_Integer(arg));
} // sqlInteger()
/**
* Convert object to a String and format it suitable for use in an SQL statement.
* Same as calling quote().
* @see quote(String)
*/
public static String sqlString(String arg)
{
return quote(arg);
} // sqlString()
/**
* Convert object to a Time and format it suitable for use in an SQL statement.
*/
public static String sqlTime(Time arg)
{
return sql(arg);
} // sqlTime()
/**
* Strip various types of text from the String.
* @deprecated
*/
public static String strip(String type, String data) throws IllegalArgumentException
{
String result;
if (data == null) result = null;
if (HTML.equalsIgnoreCase(type)) result = stripHtml(data);
else
if (LINKS.equalsIgnoreCase(type)) result = stripLinks(data);
else
if (DOMAIN.equalsIgnoreCase(type)) result = stripDomain(data);
else
if (SPACE.equalsIgnoreCase(type)) result = stripSpace(data);
else throw new IllegalArgumentException("strip(" + type + ") invalid parameter");
if (DEBUG_MODE) ThreadState.logln("strip(" + type + ", " + data + ") -> " + result);
return result;
} // strip()
private static String stripContig(String text, int offset)
{
if (DEBUG_MODE) ThreadState.logln("stripContig(" + text + ", " + offset + ')');
int start = offset;
String before = "#ERROR#";
for (; start > 0; start--)
{
if (text.charAt(start) <= ' ')
{
before = text.substring(0, ++start) + before;
break;
}
}
int end = text.length();
for (; offset < end; offset++)
{
char c = text.charAt(offset);
if (c <= ' ' || c == ';' || c == '<') return before + text.substring(offset);
}
return before;
} // stripContig()
/**
* Strips out all but the domain name from the URL string.
*/
public static String stripDomain(String text)
{
String result;
if (text == null || text.length() < 3) result = text;
else
{
int start = text.indexOf("//");
int end = text.indexOf("/", start >= 0 ? start : 0);
if (start >= 0 && end >= 0) result = text.substring(start + 2, end);
else
if (start >= 0) result = text.substring(start + 2);
else
if (end > 0) result = text.substring(0, end);
else result = text;
}
if (DEBUG_MODE) ThreadState.logln("stripDomain(" + text + ") -> " + result);
return result;
} // stripDomain()
/**
* Strips out all HTML tags from the String.
*/
public static String stripHtml(String text)
{
String result;
if (text == null || text.length() < 3) result = text;
else
{
boolean inHtml = false, space = false;
int iz = text.length();
StringBuilder buf = new StringBuilder(iz);
for (int ix = 0; ix < iz; ix++)
{
char c = text.charAt(ix);
if (inHtml)
{
if (c == '>') inHtml = false;
continue;
}
else
if (space)
{
if (c > ' ') space = false;
else continue;
}
if (c == '<')
{
inHtml = true;
}
else
if (c <= ' ')
{
space = true;
buf.append(' ');
}
else buf.append(c);
}
result = buf.toString();
}
if (DEBUG_MODE) ThreadState.logln("stripHtml(" + text + ") -> " + result);
return result;
} // stripHtml()
/**
* String specified letters from the text String.
*/
private static String stripLetters(String text, String letters)
{
int len = 0;
if (text == null || (len = text.length()) == 0) return text;
StringBuilder buf = new StringBuilder(len);
for (int ix = 0; ix < len; ix++)
{
char c = text.charAt(ix);
if (letters.indexOf(c) < 0) buf.append(c);
}
return buf.toString();
} // stripLetters()
/**
* Strips out all anchor tags and references to an internet server.
*/
public static String stripLinks(String text)
{
String result;
if (text == null || text.length() < 4) result = text;
else
{
for (int ix = 0, end = types.length; ix < end; ix++)
{
// if (DEBUG_MODE) BZVar.logln("ix " + ix);
String type = types[ix];
for (int iy = 0; iy < 2; iy++) // 0 = lower case, 1 == upper case
{
// if (DEBUG_MODE) BZVar.logln("iy " + iy);
int index = 0;
for (;;)
{
index = text.indexOf(type, index);
if (index < 0) break;
// if (DEBUG_MODE) BZVar.logln("index " + index);
char c = type.charAt(0);
if (c == '<')
{
int iend = index + type.length();
if (text.length() > iend)
{
c = text.charAt(iend);
if (c < '0'
|| (c > '9' && c < 'A')
|| (c > 'Z' && c < 'a')
|| c > 'z')
{
text = stripTag(text, index);
}
}
else index++;
}
else text = stripContig(text, index);
}
type = type.toUpperCase();
}
}
result = text;
}
if (DEBUG_MODE) ThreadState.logln("stripLinks(" + text + ") -> " + result);
return result;
} // stripLinks()
/**
* Strips dollar sign and percent symbols from the String.
*/
public static String stripNonNumerics(String text)
{
String neg = (text != null && text.startsWith("-")) ? "-" : "";
return neg + stripLetters(text.trim(), "$%,-() ");
} // stripNonNumerics()
/**
* Strips all whitespace from the string.
*/
public static String stripSpace(String text)
{
String result;
int ixz;
if (text == null || (ixz = text.length()) == 0) result = text;
else
{
StringBuilder buf = new StringBuilder(ixz);
for (int ix = 0; ix < ixz; ix++)
{
char c = text.charAt(ix);
if (c > ' ') buf.append(c);
}
result = buf.toString();
}
if (DEBUG_MODE) ThreadState.logln("stripSpace(" + text + ") -> " + result);
return result;
} // stripSpace()
private static String stripTag(String text, int offset)
{
if (DEBUG_MODE) ThreadState.logln("stripTag(" + text + ", " + offset + ')');
String before = text.substring(0, offset) + ' ';
@SuppressWarnings("unused")
int start = offset++;
int end = text.length();
for (; offset < end; offset++)
{
if (text.charAt(offset) == '>') return before + text.substring(++offset);
}
return before;
} // stripTag()
/**
* Integer Subtraction. Each argument is subtracted from the first. If no arguments
* are submitted then the result is 0.
* Any null arguments are ignored.
*/
public static int sub(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("sub(" + psize + " args)");
int result = 0;
try {
result = _int(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1, end = psize; ix < end; ix++)
{
try {
result -= _int(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // sub()
/**
* Format Time in various ways. This multipurpose function can convert a Time object
* to a String in several formats, or extract parts of the date. This function only
* accepts one or two arg elements. If two, the first is the requested function
* to perform, and the second is converted to java.sql.Time. If one, the request is assumed
* to be "short". The following are the types of functions performed based on the request:
* <table><tr><td>Request (arg1)</td><td>Returned</td><td>Type</td><td>Example</td></tr>
* <tr><td>short</td><td>Short Time</td><td>String</td><td>12:13 PM</td></tr>
* <tr><td>long</td><td>Long Time</td><td>String</td><td>12:13:52.239 PM</td></tr>
* <tr><td>sql</td><td>SQL Time</td><td>String</td><td>{t '12:13:52.239 PM'}</td></tr></table>
*/
public static Object time(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 1 || psize == 2))
throw new IllegalArgumentException("time() can only accept 1 or 2 arguments");
String type = null;
Time date;
if (psize == 2)
{
type = _String(args[0]);
date = _Time(args[1]);
}
else date = _Time(args[0]);
Object result;
if (psize == 1
|| SHORT.equalsIgnoreCase(type)) result = timeShort(date);
else
if (LONG.equalsIgnoreCase(type)) result = timeLong(date);
else
if (SQL.equalsIgnoreCase(type)) result = timeSql(date);
else
if (MIL.equalsIgnoreCase(type)) result = timeMil(date);
else throw new IllegalArgumentException("time(" + type + ", " + date + ") error, unknown time function");
if (DEBUG_MODE) ThreadState.logln("time(" + args + ") -> " + result);
return result;
} // time()
/**
* Add units to Time. Adds hours, minutes, seconds, milliseconds to Time.
* It accepts 2 or three members of args. The first is convert to Time. The second
* is the value to be added. The third, if present, is the units String: hours,
* mins, secs, msecs. If no third member is present, the units are assumed to be seconds.
*/
public static Time timeAdd(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("timeAdd() can only accept 2 or 3 arguments");
Time date = _Time(args[0]);
int value = _int(args[1]);
String str = "seconds";
if (psize == 3)
{
str = _String(args[2]);
}
int type = 's';
if (str.length() > 0) type = Character.toLowerCase(str.charAt(0));
if (str.length() > 1 && type == 'm' && Character.toLowerCase(str.charAt(1)) == 's')
{
type = 'i';
}
Calendar c = Calendar.getInstance();
c.setTime(date);
switch (type)
{
case 'i':
c.add(Calendar.MILLISECOND, value);
break;
case 's':
c.add(Calendar.SECOND, value);
break;
case 'm':
c.add(Calendar.MINUTE, value);
break;
case 'h':
c.add(Calendar.HOUR, value);
break;
default:
throw new IllegalArgumentException("Unknown value type: " + str);
}
Time result = new Time(c.getTime().getTime());
if (DEBUG_MODE) ThreadState.logln("timeAdd(" + args + ") -> " + result);
return result;
} // timeAdd()
/**
* Retuns the difference between two Timestamps, as a String.
*/
public static String timeDiff(Timestamp time1, Timestamp time2)
{
return msecDiff(time1.getTime(), time2.getTime());
} // timeDiff()
/**
* Convert Time to long String. Returns a String with the time in long format.
*/
public static String timeLong(Time date)
{
String result;
if (date == null) result = null;
else result = timelong.format(date);
if (DEBUG_MODE) ThreadState.logln("timeLong(" + date + ") -> " + result);
return result;
} // timeLong()
/**
* Convert Time to a String. Returns a String with the time in military format.
*/
public static String timeMil(Time date)
{
if (DEBUG_MODE) ThreadState.logln("timeShort(" + date + ") -> " + date);
if (date == null) return null;
return date.toString();
} // timeMil()
/**
* Convert Time to a short String. Returns a String with the time in short format.
*/
public static String timeShort(Time date)
{
if (DEBUG_MODE) ThreadState.logln("timeShort(" + date + ") -> " + date);
if (date == null) return null;
return timeshort2.format(date);
} // timeShort()
/**
* Convert Time to SQL. Returns a String with the time encoded for use in an SQL statement.
*/
public static String timeSql(Time date)
{
String result;
if (date == null) result = NULL;
result = "{t '" + date + "'}";
if (DEBUG_MODE) ThreadState.logln("timeSql(" + date + " -> " + result);
return result;
} // timeSql()
/**
* Subtract units of time from Time. Subtracts hours, minutes, seconds, milliseconds from Time.
* It accepts 2 or three members of args. The first is convert to Time. The second
* is the value to be subtracted. The third, if present, is the units String: hours,
* mins, secs, msecs. If no third member is present, the units are assumed to be seconds.
*/
public static Time timeSub(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("timeSub() can only accept 2 or 3 arguments");
args[1] = new Integer(-_int(args[1]));
Time result = timeAdd(args);
if (DEBUG_MODE) ThreadState.logln("timeSub(" + args + ") -> " + result);
return result;
} // timeSub()
/**
* Return today's Date.
*/
public static Date today()
{
return new Date(System.currentTimeMillis());
} // today()
/**
* All possible chars for representing a number as a String
*/
private final static char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'A' , 'B' ,
'C' , 'D' , 'E' , 'F'
};
/**
* Convert arg to a hexadecimal. If two arguments are sent, the second specifies the number
* of digits desired.
*/
public static String toHex(Object[] args) throws IllegalArgumentException
{
int psize = args.length;
if (!(psize == 1))
throw new IllegalArgumentException("toHex() can only accept 1 or 2 arguments");
Object param = args[0];
if (param == null || (param instanceof String && ((String)param).trim().length() == 0)) return null;
int i = _int(param);
String result;
if (psize == 1) result = Integer.toHexString(i);
else
{
int dig = _int(args[1]);
char[] buf = new char[dig];
int charPos = dig;
int shift = 4;
int radix = 1 << shift;
int mask = radix - 1;
while (dig-- > 0) {
buf[--charPos] = digits[i & mask];
i >>>= shift;
}
result = new String(buf);
}
if (DEBUG_MODE) ThreadState.logln("toHex(" + args + ") -> " + result);
return result;
} // toHex()
/**
* Returns the value as a hexidecimal digit.
*/
private static char toHexDigit(int value)
{
value &= 0xf;
if (value <= 9) return (char)('0' + value);
return (char)('A' + value - 10);
} // toHexDigit()
/**
* Trims the whitespace from the beginning and end of the String.
*/
public static String trim(String arg)
{
String result;
if (arg == null) result = null;
else result = arg.trim();
if (DEBUG_MODE) ThreadState.logln("trim(" + arg + ") -> " + result);
return result;
} // trim()
/**
* Convert String to upper case. This function converts all characters of arg to upper case.
*/
public static String upperCase(String arg)
{
String result;
if (arg == null) result = null;
else result = _String(arg).toUpperCase();
if (DEBUG_MODE) ThreadState.logln("upperCase(" + arg + ") -> " + result);
return result;
} // upperCase()
/**
* Used by both url() and urlFull() to do their jobs, since the are so similar.
*/
private static String url(String value, boolean partial)
{
if (value == null) return null;
StringBuilder buf = new StringBuilder();
for (int ix = 0, end = value.length(); ix < end; ix++)
{
char c = value.charAt(ix);
// if (c <= ' ') buf.append('+');
// else
if ((c < '0' || (c > '9' && c < '@') || c > 'z')
&& !(c == '-' || c == '/' || c == ':' || c == '.')
&& (partial || !(c == '?' || c == '&' || c == '=' || c == '#')))
{
buf.append('%');
buf.append(toHexDigit(c >> 4));
buf.append(toHexDigit(c));
}
else buf.append(c);
}
return buf.toString();
} // url()
/**
* Format data for use in a URL String. This function formats arg as a String with
* characters that are not allowed in a URL converted to %hex. Use this when you
* need to put a field value into an HTML URL, on the right side of the ? character.
* @see urlFull(String)
*/
public static String url(String value)
{
String result = url(value, true);
if (DEBUG_MODE) ThreadState.logln("url(" + value + ") -> " + result);
return result;
} // url()
/**
* Format data for use as a URL String. This function formats arg as a String with
* characters that are not allowed in a full URL converted to %hex. Use this when you
* need to format a String to be the entire URL.
* @see url(String)
*/
public static String urlFull(String value)
{
String result = url(value, false);
if (DEBUG_MODE) ThreadState.logln("urlFull(" + value + ") -> " + result);
return result;
} // url()
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(boolean arg)
{
return arg;
} // _boolean(boolean)
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(double arg)
{
return arg != 0.0;
} // _boolean(double)
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(float arg)
{
return arg != 0.0f;
} // _boolean(float)
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(int arg)
{
return arg != 0;
} // _boolean(int)
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(long arg)
{
return arg != 0L;
} // _boolean(long)
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(String arg)
{
return arg != null && arg.length() > 0 && !arg.equalsIgnoreCase("false") && !arg.equalsIgnoreCase("0");
} // _boolean(String)
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(Object obj)
{
return _Boolean(obj).booleanValue();
} // _boolean(Object)
/**
* Convert to Boolean. This function converts the data to a Boolean object.
*/
public static Boolean _Boolean(Object obj)
{
if (obj == null) return Boolean.FALSE;
try {
return (Boolean)obj;
} catch (Exception e1) {
try {
return ((Number)obj).doubleValue() != 0.0 ? Boolean.TRUE : Boolean.FALSE;
} catch (Exception e) { // ClassCastException
return new Boolean(_boolean(_String(obj)));
}
}
} // _Boolean()
/**
* Convert value to char.
*/
public static char _char(int val)
{
return (char)val;
} // _char()
/**
* Convert Object to char.
*/
public static char _char(Object obj) throws IllegalArgumentException
{
Character c = _Character(obj);
if (c == null) throw new IllegalArgumentException("Cannot convert " + obj + " to a char");
return c.charValue();
} // _char()
/**
* Convert Object to Character.
*/
public static Character _Character(Object obj)
{
try {
return (Character)obj;
} catch (ClassCastException e) {
String str = _String(obj);
if (str.length() == 0) return null;
return new Character(str.charAt(0));
}
} // _Character()
/**
* Convert to Date. This function converts the data to a Date object.
*/
@SuppressWarnings("deprecation")
public static Date _Date(Object obj) throws NumberFormatException
{
if (obj == null) return null;
try {
return (Date)obj;
} catch (Exception e) {
try {
return new Date(((java.util.Date)obj).getTime());
} catch (Exception e1) {
try {
int date = ((Number)obj).intValue();
return new Date(date / 10000, date / 100 % 100 - 1, date % 100);
} catch (Exception e2) {
String value = _String(obj).trim();
if (value.length() == 0) return null;
try {
return Date.valueOf(value);
} catch (Exception e3) {
try {
return new Date(dform.parse(value).getTime());
} catch (Exception e4) {
try {
return new Date(zonedate.parse(value).getTime());
} catch (Exception e5) {
throw new NumberFormatException("Cannot convert '" + obj + "' to a date");
}
}
}
}
}
}
} // _Date()
/**
* Convert to double. This function converts the data to a double type.
*/
public static double _double(boolean arg)
{
return arg ? 1.0 : 0.0;
} // _double(boolean)
/**
* Convert to double. This function converts the data to a double type.
*/
public static double _double(double arg)
{
return arg;
} // _double(double)
/**
* Convert to double. This function converts the data to a double type.
*/
public static double _double(int arg)
{
return (double)arg;
} // _double(int)
/**
* Convert to double. This function converts the data to a double type.
*/
public static double _double(long arg)
{
return (double)arg;
} // _double(long)
/**
* Convert to double. This function converts the data to a double type.
*/
public static double _double(String arg) throws NumberFormatException
{
return Double.parseDouble(stripNonNumerics(arg));
} // _double(String)
/**
* Convert to double. This function converts the data to a double type.
*/
public static double _double(Object obj) throws NumberFormatException
{
Double d = _Double(obj);
return d == null ? 0.0 : d.doubleValue();
} // _double(Object)
/**
* Convert to double. This function converts the data to a double type.
*/
public static Double _Double(Object obj) throws NumberFormatException
{
try {
return (Double)obj;
} catch (Exception e0) {
try {
return new Double(((Number)obj).doubleValue());
} catch (Exception e) {
try {
String s = stripNonNumerics(obj.toString());
if (s.length() == 0) return null;
return new Double(s);
} catch (Exception e3) {
throw new NumberFormatException("Cannot convert '" + obj + "' to a double");
}
}
}
} // _Double()
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(boolean arg)
{
return arg ? 1.0f : 0.0f;
} // _float(boolean)
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(double arg)
{
return (float)arg;
} // _float(double)
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(float arg)
{
return arg;
} // _float(float)
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(int arg)
{
return (float)arg;
} // _float(int)
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(long arg)
{
return (float)arg;
} // _float(long)
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(String arg) throws NumberFormatException
{
return Float.parseFloat(stripNonNumerics(arg));
} // _float(String)
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(Object obj) throws NumberFormatException
{
Float f = _Float(obj);
return f == null ? 0f : f.floatValue();
} // _float()
/**
* Convert to Float. This function converts the data to a Float object.
*/
public static Float _Float(Object obj) throws NumberFormatException
{
try {
return (Float)obj;
} catch (Exception e0) {
try {
return new Float(((Number)obj).floatValue());
} catch (Exception e) {
try {
String s = stripNonNumerics(obj.toString());
if (s.length() == 0) return null;
return new Float(s);
} catch (Exception e3) {
throw new NumberFormatException("Cannot convert '" + obj + "' to a float");
}
}
}
} // _Float()
/**
* Convert Object to Timestamp.
*/
@SuppressWarnings("deprecation")
public static Timestamp _Instant(Object obj) throws NumberFormatException
{
if (obj == null) return null;
try {
return (Timestamp)obj;
} catch (Exception e) {
try {
return new Timestamp(((java.util.Date)obj).getTime());
} catch (Exception e1) {
try {
long time = ((Number)obj).longValue();
int msec = (int)(time % 10000);
time /= 10000;
int sec = (int)(time % 100);
time /= 100;
int min = (int)(time % 100);
time /= 100;
int hr = (int)(time % 100);
time /= 100;
int day = (int)(time % 100);
time /= 100;
int mon = (int)(time % 100);
int year = (int)(time / 100);
return new Timestamp(year, mon - 1, day, hr, min, sec, msec);
} catch (Exception e2) {
String value = _String(obj).trim();
if (value.length() == 0) return null;
try {
return Timestamp.valueOf(value);
} catch (Exception e3) {
try {
return new Timestamp(zoneinstant.parse(value).getTime());
} catch (Exception e4) {
try {
return new Timestamp(_Date(obj).getTime());
} catch (Exception e5) {
throw new NumberFormatException("Cannot convert '" + obj + "' to instant");
}
}
}
}
}
}
} // _Instant()
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(boolean arg)
{
return arg ? 1 : 0;
} // _int(boolean)
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(double arg)
{
return (int)arg;
} // _int(double)
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(float arg)
{
return (int)arg;
} // _int(float)
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(int arg)
{
return arg;
} // _int(int)
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(long arg)
{
return (int)arg;
} // _int(long)
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(String arg) throws NumberFormatException
{
return Integer.parseInt(stripNonNumerics(arg));
} // _int(String)
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(Object obj) throws NumberFormatException
{
Integer i = _Integer(obj);
return i == null ? 0 : i.intValue();
} // _int()
/**
* Convert to Integer. This function converts the data to an Integer object.
*/
public static Integer _Integer(Object obj) throws NumberFormatException
{
try {
return (Integer)obj;
} catch (Exception e0) {
try {
return new Integer(((Number)obj).intValue());
} catch (Exception e) {
try {
cal.setTime((Date)obj);
return new Integer(cal.get(Calendar.YEAR) * 10000 + (cal.get(Calendar.MONTH) + 1) * 100 + cal.get(Calendar.DAY_OF_MONTH));
} catch (Exception e1) {
try {
cal.setTime((Time)obj);
return new Integer(cal.get(Calendar.HOUR_OF_DAY) * 10000 + cal.get(Calendar.MINUTE) * 100 + cal.get(Calendar.SECOND));
} catch (Exception e2) {
try {
Boolean b = (Boolean)obj;
return new Integer(b.booleanValue() ? 1 : 0);
} catch (Exception e3) {
try {
String s = stripNonNumerics(obj.toString());
if (s.length() == 0) return null;
return new Integer(s);
} catch (Exception e4) {
try {
return new Integer(_Double(obj).intValue());
} catch (Exception e5) {
throw new NumberFormatException("Cannot convert '" + obj + "' to an int");
}
}
}
}
}
}
}
} // _Integer()
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(boolean arg)
{
return arg ? 1l : 0l;
} // _long(boolean)
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(double arg)
{
return (long)arg;
} // _long(double)
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(float arg)
{
return (long)arg;
} // _long(float)
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(int arg)
{
return arg;
} // _long(int)
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(long arg)
{
return arg;
} // _long(long)
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(String arg) throws NumberFormatException
{
return Long.parseLong(stripNonNumerics(arg));
} // _long(String)
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(Object obj) throws NumberFormatException
{
Long i = _Long(obj);
return i == null ? 0 : i.longValue();
} // _long()
/**
* Convert to Long. This function converts the data to an Integer object.
*/
public static Long _Long(Object obj) throws NumberFormatException
{
try {
return (Long)obj;
} catch (Exception e0) {
try {
return new Long(((Number)obj).longValue());
} catch (Exception e1) {
try {
cal.setTime((java.util.Date)obj);
return new Long(cal.get(Calendar.YEAR) * 10000000000l
+ (cal.get(Calendar.MONTH) + 1) * 100000000
+ cal.get(Calendar.DAY_OF_MONTH) * 1000000
+ cal.get(Calendar.HOUR_OF_DAY) * 10000
+ cal.get(Calendar.MINUTE) * 100
+ cal.get(Calendar.SECOND));
} catch (Exception e2) {
try {
Boolean b = (Boolean)obj;
return new Long(b.booleanValue() ? 1l : 0l);
} catch (Exception e3) {
try {
String s = stripNonNumerics(obj.toString());
if (s.length() == 0) return null;
return new Long(s);
} catch (Exception e4) {
try {
return new Long(_Double(obj).longValue());
} catch (Exception e5) {
throw new NumberFormatException("Cannot convert '" + obj + "' to an long");
}
}
}
}
}
}
} // _Long()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(boolean val)
{
return val ? Boolean.TRUE : Boolean.FALSE;
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(char val)
{
return new Character(val);
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(short val)
{
return new Short(val);
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(int val)
{
return new Integer(val);
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(long val)
{
return new Long(val);
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(float val)
{
return new Float(val);
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Double _Object(double val)
{
return new Double(val);
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(Object val)
{
return val;
} // _Object()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(boolean val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(char val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(short val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(int val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(long val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(float val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(double val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(Object val)
{
if (val == null) return EMPTY;
return val.toString();
} // _String()
/**
* Convert to Time. This function converts the data to a Time object.
*/
@SuppressWarnings("deprecation")
public static Time _Time(Object obj) throws NumberFormatException
{
if (obj == null) return null;
try {
return (Time)obj;
} catch (Exception e) {
try {
return new Time(((java.util.Date)obj).getTime());
} catch (Exception e1) {
try {
int time = ((Number)obj).intValue();
return new Time(time / 10000, time / 100 % 100, time % 100);
} catch (Exception e2) {
String value = _String(obj).trim();
if (value.length() == 0) return null;
try {
return new Time(timeshort.parse(value).getTime());
} catch (Exception e3) {
try {
return new Time(timeshort2.parse(value).getTime());
} catch (Exception e4) {
try {
return new Time(timeshort3.parse(value).getTime());
} catch (Exception e5) {
try {
return new Time(timeshort4.parse(value).getTime());
} catch (Exception e6) {
try {
return new Time(timeshort5.parse(value).getTime());
} catch (Exception e7) {
try {
return new Time(timeshort6.parse(value).getTime());
} catch (Exception e8) {
try {
return new Time(timelong.parse(value).getTime());
} catch (Exception e9) {
try {
return Time.valueOf(value);
} catch (Exception e10) {
try {
return new Time(zonetime.parse(value).getTime());
} catch (Exception e11) {
throw new NumberFormatException("Cannot convert '" + obj + "' to time");
}
}
}
}
}
}
}
}
}
}
}
}
} // _Time()
/**
* Main DSP page function. This function is created by the DSP engine for each page
* and is called by the DSP servlet for each request to the web page.
*/
public abstract void _jspService(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException;
} // DspPage
|
src/main/java/com/dsp/DspPage.java
|
/* Copyright 2015 Troy D. Heninger
*
* 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.dsp;
import java.io.IOException;
import java.io.File;
import java.lang.reflect.*; // Field, Method, Modifier
import java.sql.*;
import java.text.*; // DateFormat
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
/**
* This class is the default class that all DSP pages extend. When a page
* is written to extend another class then an object of this class still
* be created as the page object. Functions of this class are treated special
* in the DSP parser. Any arguments passed to functions which do not start
* with an underscore '_', will be converted to the proper type automatically.
* Functions that accept multiple arguments accept Object arrays. These functions
* call allow any number of arguments and the DSP parser will send all arguments
* as elements of the array.
*/
public abstract class DspPage extends HttpServlet implements HttpJspPage
{
private static final long serialVersionUID = 6527415972891184043L;
/** The empty string */
public static final String EMPTY = "";
/** The word NULL */
public static final String NULL = "NULL";
/** The word "day", used in dateAdd(), dateSub(), instantAdd(), and instantSub() */
public static final String DAY = "day";
/** The word "days", used in dateAdd(), dateSub(), instantAdd(), and instantSub() */
public static final String DAYS = "days";
public static final String MONTH = "month";
public static final String MONTHS = "months";
public static final String LONG = "long";
public static final String SHORT = "short";
public static final String YEAR = "year";
public static final String YEARS = "years";
/** The words 'sql' and 'mil', used in date(), time(), and instant() */
public static final String SQL = "sql";
public static final String MIL = "mil";
public static final String ACCESS = "access";
public static final String HTML = "html";
public static final String DOMAIN = "domain";
public static final String LINKS = "links";
public static final String SPACE = "space";
public static final int SQL_STMT = 0;
public static final int ARRAY_STMT = 1;
public static final int DIR_STMT = 2;
public static final int SCAN_STMT = 3;
static final boolean DEBUG_MODE = false;
// static final boolean TRACE_MODE = false;
static final Calendar cal = Calendar.getInstance();
static final DateFormat dform = DateFormat.getDateInstance(DateFormat.SHORT);
static final DateFormat dateAmer = new SimpleDateFormat("MM/dd/yyyy");
static final DateFormat datelong = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
static final DateFormat instantAmer = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
static final DateFormat instantAccessForm = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
static final DateFormat instantlong = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm:ss.SSSS a");
static final DateFormat timelong = new SimpleDateFormat("hh:mm:ss.SSSS a");
static final DateFormat timeshort = new SimpleDateFormat("hh:mm:ss a");
static final DateFormat timeshort2 = new SimpleDateFormat("hh:mm a");
static final DateFormat timeshort3 = new SimpleDateFormat("hh:mma");
static final DateFormat timeshort4 = new SimpleDateFormat("hh:mm:ssa");
static final DateFormat timeshort5 = new SimpleDateFormat("HH:mm:ss");
static final DateFormat timeshort6 = new SimpleDateFormat("HH:mm");
static final DateFormat zonedate = new SimpleDateFormat("yyyyMMdd");
static final DateFormat zoneinstant = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
static final DateFormat zonetime = new SimpleDateFormat("HHmmss");
static final DecimalFormat tens = new DecimalFormat("#,##0.#");
static final DecimalFormat percent = new DecimalFormat("#,##0.#%");
private static String[] types = {"<a", "</a", ".com", ".net", ".org", ".edu", ".gov", ".mil",};
protected DspProp prop;
/**
* Integer absolute value. Returns the absolute value of <b>arg</b>.
*/
public static int abs(int arg)
{
return arg < 0 ? -arg : arg;
} // abs()
/**
* Integer addition. Returns the summation of all arguments. Each argument
* is converted to an <b>int</b> type. An empty or null array <b>arg</b> evalutes to 0.
* Any null arguments are ignored.
*/
public static int add(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("add(" + psize + " args)");
int result = 0;
for (int ix = 0, end = psize; ix < end; ix++)
{
try {
result += _int(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // add()
/**
* Add anchor tags around text that looks like a hyperlink or an email addresses.
* Called from html().
* @see html()
*/
private static StringBuffer addAnchors(StringBuffer buf)
{
char c;
boolean inTag = false, mailto = false;
for (int ix = 0, end = buf.length(); ix < end; ix++)
{
c = buf.charAt(ix);
if (c == '<' && !inTag)
{
inTag = true;
if (ix + 2 < end && Character.toLowerCase(buf.charAt(ix + 1)) == 'a'
&& buf.charAt(ix + 2) <= ' ') return buf; // done if any anchor tags found
}
if (c == '>' && inTag) inTag = false;
if (c == '.' && !inTag)
{
int iz = ix + 1;
mailto = false;
for (; iz < end; iz++)
{
c = buf.charAt(iz);
if (c <= ' ' || c == '"' || c == '\'' || c == ';' || c == ','
|| c == '<' || c == '>' || c > 126)
{
break;
}
if (iz == ix + 1 && c == '&') break;
if (c == '@') mailto = true;
}
String url = buf.substring(ix, iz).toLowerCase();
if (url.startsWith(".exe") || url.startsWith(".doc")
|| url.startsWith(".htm") || url.startsWith(".txt")
|| url.startsWith(".dll") || url.startsWith(".zip")
|| url.startsWith(".gif") || url.startsWith(".jpg")
|| url.startsWith("..."))
{
ix += 2;
continue; // these are only files
}
// if (!(url.startsWith("com") || url.startsWith("org") || url.startsWith("net")
// || url.startsWith("mil") || url.startsWith("gov"))) continue; // only these allowed
c = buf.charAt(iz - 1);
while (c == '.')
{
iz--; // ignore ending periods
if (iz <= ix) break;
c = buf.charAt(iz - 1);
}
if (iz <= ix + 1) continue; // too short
int iy = ix - 1;
for (; iy > 0; iy--)
{
c = buf.charAt(iy);
if (c <= ' ' || c == '"' || c == '\'' || c == ';' || c == ','
|| c == '<' || c == '>' || c > 126)
{
iy++;
break;
}
if (c == '@') mailto = true;
}
if (iz < iy + 4 || iy < 0) continue; // too short
int ij = iy;
for (; ij < iz; ij++)
{
c = buf.charAt(ij);
if (c != '-' && c != '+' && c != '.' && c != 'e' && c != 'E'
&& c != '$' && (c < '0' || c > '9')) break;
}
if (ij >= iz) continue; // ignore floating point numbers
url = buf.substring(iy, iz);
// weed out things that can't be a URL
String lower = url.toLowerCase();
if (!mailto && lower.indexOf(".com") < 0 && lower.indexOf(".net") < 0
&& lower.indexOf("www") < 0 && lower.indexOf(".edu") < 0
&& lower.indexOf(".gov") < 0 && lower.indexOf(".org") < 0
&& lower.indexOf(".web") < 0 && lower.indexOf(".htm") < 0) continue;
//System.out.println("ix = " + ix + ", iy = " + iy + ", iz = " + iz + ", end = " + end
// + "\n\t'" + url + "'");
buf.insert(iz, "</a>");
if (mailto)
{
buf.insert(iy, "<a href=\"mailto:" + url + "\">");
}
else
{
if (url.toLowerCase().startsWith("http"))
{
buf.insert(iy, "<a href=\"" + url + "\">");
}
else
{
buf.insert(iy, "<a href=\"http://" + url + "\">");
}
}
int inc = buf.length() - end;
end += inc;
ix = iz + inc - 1;
}
}
return buf;
} // addAnchors()
/**
* Logical And. Calculates the logical <b>and</b> of all arguments.
* Each argument is converted to a boolean as it is used. An empty or null
* array arg evaluates to 0. Note, this function cannot do short-circut
* evalation, as Java dose when you use the || operator.
* @see or()
*/
public static boolean and(Object[] args)
{
if (args == null || args.length == 0) return false;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("and(" + psize + " args)");
boolean result = true;
for (int ix = 0, end = psize; result && ix < end; ix++)
{
try {
result &= _boolean(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // and()
static final String base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* Decode a Base64 String. This decodes a String that has been encoded with Base64
* encoding, as defined in RFC 1521.
*/
public static String base64Decode(String data)
{
String result = null;
if (data != null)
{
int len = data.length();
byte[] buf = new byte[len * 3 / 4];
int bits = 0, accum = 0, iy = 0;
boolean trunc = false;
for (int ix = 0; ix < len; ix++)
{
char c = data.charAt(ix);
if (c == '=')
{
trunc = true; // ignore the last 8 bits because the input had a non multiple of 6 bits
break; // If I hit '=' then I know I'm done
}
if (c >= 'A' && c <= 'Z')
{
accum = (accum << 6) | (c - 'A');
}
else
if (c >= 'a' && c <= 'z')
{
accum = (accum << 6) | (c - 'a' + 26);
}
else
if (c >= '0' && c <= '9')
{
accum = (accum << 6) | (c - '0' + 52);
}
else if (c == '+')
{
accum = (accum << 6) | 62;
}
else if (c == '/')
{
accum = (accum << 6) | 63;
}
else continue; // ignore all other characters; don't increment bits
bits += 6;
if (bits >= 24)
{
buf[iy++] = (byte)(accum >>> 16);
buf[iy++] = (byte)(accum >>> 8);
buf[iy++] = (byte)accum;
bits = 0;
accum = 0;
}
}
if (bits > 0)
{
int bitsOver = bits;
while (bitsOver < 24)
{
accum <<= 6;
bitsOver += 6;
}
if (trunc) bits -= 8; // ignore the last byte since it will be 0
while (bits > 0)
{
buf[iy++] = (byte)(accum >>> 16);
accum <<= 8;
bits -= 8;
}
}
try { result = new String(buf, 0, iy, "UTF-8"); } catch (java.io.UnsupportedEncodingException e) {}
}
if (DEBUG_MODE) ThreadState.logln("base64Decode(" + data + ") -> " + result);
return result;
} // base64Decode()
/**
* Encode a Base64 String. This encodes a String using Base64 encoding, as defined in
* RFC 1521.
*/
public static String base64Encode(String data)
{
String result;
if (data == null) result = null;
else
{
byte[] utf8 = null;
try { utf8 = data.getBytes("UTF-8"); } catch (java.io.UnsupportedEncodingException e) {}
int len = utf8.length;
StringBuffer buf = new StringBuffer(len * 5 / 3);
int bits = 0, accum = 0, line = 0;
for (int ix = 0; ix < len; ix++)
{
accum = (accum << 8) | (utf8[ix] & 0xff); // always positive
bits += 8;
if (bits >= 24)
{
buf.append(base64Chars.charAt(accum >>> 18));
buf.append(base64Chars.charAt((accum >>> 12) & 0x3f));
buf.append(base64Chars.charAt((accum >>> 6) & 0x3f));
buf.append(base64Chars.charAt(accum & 0x3f));
bits = 0;
accum = 0;
line += 4;
if (line >= 76)
{
buf.append("\r\n");
line = 0;
}
}
}
if (bits > 0)
{
int bitsOver = bits;
while (bitsOver < 24)
{
accum <<= 8;
bitsOver += 8;
}
buf.append(base64Chars.charAt(accum >>> 18));
bits -= 6;
buf.append(base64Chars.charAt((accum >>> 12) & 0x3f));
bits -= 6;
if (bits > 0)
{
buf.append(base64Chars.charAt((accum >>> 6) & 0x3f));
}
else
{
buf.append('=');
}
buf.append('=');
}
result = buf.toString();
}
if (DEBUG_MODE) ThreadState.logln("base64Encode(" + data + ") -> " + result);
return result;
} // base64Encode()
/**
* Bit-wise And. Calculates the bit-wise <b>and</b> of all arguments.
* Each argument is converted to an int as it is used. An empty or null
* array evaluates to 0.
*/
public static int bitAnd(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
int result = -1;
for (int ix = 0, end = psize; ix < end; ix++)
{
try {
result &= _int(args[ix]);
} catch (NullPointerException e) {
}
}
if (DEBUG_MODE) ThreadState.logln("bitAnd(" + psize + " args) -> " + result);
return result;
} // bitAnd()
/**
* Bit-wise Or. Calculates the bit-wise <b>or</b> of all arguments.
* Each argument is converted to an int as it is used. An empty or null
* array <b>arg</b> evaluates to 0.
*/
public static int bitOr(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
int result = 0;
for (int ix = 0, end = psize; ix < end; ix++)
{
try {
result |= _int(args[ix]);
} catch (NullPointerException e) {
}
}
if (DEBUG_MODE) ThreadState.logln("bitOr(" + psize + " args) -> " + result);
return result;
} // bitOr()
/**
* Bit-wise Exclusive-Or. Calculates the bit-wise <b>exclusive or</b> of all arguments.
* Each argument is converted to an int as it is used. An empty or null
* array <b>arg</b> evaluates to 0.
*/
public static int bitXor(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
int result = 0;
for (int ix = 0, end = psize; ix < end; ix++)
{
try {
result ^= _int(args[ix]);
} catch (NullPointerException e) {
}
}
if (DEBUG_MODE) ThreadState.logln("bitXor(" + psize + " args) -> " + result);
return result;
} // bitXor()
/**
* Concatenates Strings. This simply concatenates the arguments and returns the String.
* Each argument is converted to a String as it is used. Null arguments convert to the empty
* String "". An empty or null array <b>arg</b> evaluates to the empty string "".
*/
public static String concat(Object[] args)
{
StringBuffer result = new StringBuffer();
int psize = 0;
if (args != null)
{
psize = args.length;
for (int ix = 0; ix < psize; ix++)
{
String s = _String(args[ix]);
if (s != null)
{
// s = replace(s, "<br>", "\r\n");
result.append(s);
}
}
}
if (DEBUG_MODE) ThreadState.logln("concat(" + psize + " args) -> " + result);
return result.toString();
} // concat()
/**
* Date Conversion and Extraction. This multipurpose function can convert a Date object
* to a String in several formats, or can extract parts of the date. This function only
* accepts one or two arg elements. If two, the first is the requested function
* to perform, and the second is converted to java.sql.Date. If one, the request is assumed
* to be "short". The following are the types of functions performed based on the request:
* <table><tr><td>Request (arg1)</td><td>Returned</td><td>Type</td><td>Example</td></tr>
* <tr><td>short</td><td>Short Date</td><td>String</td><td>2000-11-20</td></tr>
* <tr><td>long</td><td>Long Date</td><td>String</td><td>Monday, November 20, 2000</td></tr>
* <tr><td>sql</td><td>SQL Date</td><td>String</td><td>{d '2000-11-20'}</td></tr>
* <tr><td>year</td><td>Year</td><td>Integer</td><td>2000</td></tr>
* <tr><td>month</td><td>Month</td><td>Integer</td><td>11</td></tr>
* <tr><td>day</td><td>Day of Month</td><td>Integer</td><td>20</td></tr></table>
* @deprecated
*/
public static Object date(Object[] args) throws IllegalArgumentException
{
int psize = args.length;
if (!(psize == 1 || psize == 2))
throw new IllegalArgumentException("date() can only accept 1 or 2 arguments");
String type = null;
Date date;
if (psize == 2)
{
type = _String(args[0]);
date = _Date(args[1]);
}
else date = _Date(args[0]);
Object result;
if (psize == 1 || SHORT.equalsIgnoreCase(type)) result = dateShort(date);
else
if (LONG.equalsIgnoreCase(type)) result = dateLong(date);
else
if (SQL.equalsIgnoreCase(type)) result = dateSql(date);
else
if (YEAR.equalsIgnoreCase(type)) result = new Integer(dateYear(date));
else
if (MONTH.equalsIgnoreCase(type)) result = new Integer(dateMonth(date));
else
if (DAY.equalsIgnoreCase(type)) result = new Integer(dateDay(date));
else
throw new IllegalArgumentException("date(" + type + ", " + date + ") error, unknown date type");
if (DEBUG_MODE) ThreadState.logln("date(" + psize + " args) -> " + result);
return result;
} // date()
/**
* Add date units to a Date. This function adds years, months, weeks, or days to a Date.
* This function accepts either two or three arg elements. The first element
* is converted to a java.sql.Date. The second is converted to an int. The last
* if present is converted to a String and specifies the type of addition to perform.
* If only two elements are sent the type is assumed to be "days". Here are
* the allowed addition requests: year, years, month, months, week, weeks, day, or days.
*/
public static Date dateAdd(Object[] args) throws IllegalArgumentException
{
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("dateAdd(" + psize + " args)");
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("dateAdd() can only accept 2 or 3 arguments");
Date date = _Date(args[0]);
int value = _int(args[1]);
String str = "days";
if (psize == 3)
{
str = _String(args[2]);
}
int type = 'd';
if (str.length() > 0) type = Character.toLowerCase(str.charAt(0));
Calendar c = Calendar.getInstance();
c.setTime(date);
switch (type)
{
case 'd':
c.add(Calendar.DATE, value);
break;
case 'm':
c.add(Calendar.MONTH, value);
break;
case 'w':
c.add(Calendar.WEEK_OF_YEAR, value);
break;
case 'y':
c.add(Calendar.YEAR, value);
break;
default:
throw new IllegalArgumentException("Unknown value type: " + str);
}
return new Date(c.getTime().getTime());
} // dateAdd()
/**
* Returns the date in the American standar format MM/DD/YYYY
*/
public static String dateAmerican(Date date)
{
String result;
if (date == null) result = null;
else result = dateAmer.format(date);
if (DEBUG_MODE) ThreadState.logln("dateAmerican(" + date + ") -> " + result);
return result;
} // dateAmerican()
/**
* Return the day of the month of the Date.
*/
public static int dateDay(Date date)
{
int result;
if (date == null) result = 0;
else
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
result = cal.get(Calendar.DAY_OF_MONTH);
}
if (DEBUG_MODE) ThreadState.logln("dateDay(" + date + ") -> " + result);
return result;
} // dateDay()
/**
* Returns the difference between the two dates as a String.
*/
public static String dateDiff(Date date1, Date date2)
{
return msecDiff(date1.getTime(), date2.getTime());
} // dateDiff()
/**
* Return the Date as a String in long format.
*/
public static String dateLong(Date date)
{
String result;
if (date == null) result = null;
else result = datelong.format(date);
if (DEBUG_MODE) ThreadState.logln("dateLong(" + date + ") -> " + result);
return result;
} // dateLong()
/**
* Return the month of the Date, as a number 1-12.
*/
public static int dateMonth(Date date)
{
int result;
if (date == null) result = 0;
else
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
result = cal.get(Calendar.MONTH) + 1;
}
if (DEBUG_MODE) ThreadState.logln("dateMonth(" + date + ") -> " + result);
return result;
} // dateMonth()
/**
* Return the Date as a String in short format.
*/
public static String dateShort(Date date)
{
String result;
if (date == null) result = null;
else result = date.toString();
if (DEBUG_MODE) ThreadState.logln("dateShort(" + date + ") -> " + result);
return result;
} // dateShort()
/**
* Return the Date as a String formated for use in an SQL statement.
*/
public static String dateSql(Date date)
{
String result;
if (date == null) result = NULL;
else result = "{d '" + date + "'}";
if (DEBUG_MODE) ThreadState.logln("dateSql(" + date + ") -> " + result);
return result;
} // dateSql()
/**
* Subtract date units from a Date. This function subtracts years, months, weeks, or days from a Date.
* This function accepts either two or three arg elements. The first element
* is converted to a java.sql.Date. The second is the value converted to an int. The last
* if present is converted to a String and specifies the type of subtraction to perform.
* If only two elements are sent the type is assumed to be "days". Here are
* the allowed subtraction requests: year, years, month, months, week, weeks, day, or days.
*/
public static Date dateSub(Object[] args) throws IllegalArgumentException
{
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("dateSub(" + psize + " args)");
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("dateSub() can only accept 2 or 3 arguments");
int value = _int(args[1]);
args[1] = new Integer(-value);
return dateAdd(args);
} // dateSub()
/**
* Return the year of the Date.
*/
public static int dateYear(Date date)
{
int result;
if (date == null) result = 0;
else
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
result = cal.get(Calendar.YEAR);
}
if (DEBUG_MODE) ThreadState.logln("dateYear(" + date + ")");
return result;
} // dateYear()
/**
* Returns an integer that has it's bits scrambled. If the same resulting value is again sent
* through this function the original value will be returned.
*/
public static int descramble(int value, String key)
{
byte[] shifts = new byte[32];
for (int ix = 0; ix < 32; ix++)
{
shifts[ix] = (byte)ix;
}
int hash = key.hashCode();
Random rand = new Random((long)hash << 32 | hash);
for (int ix = 0; ix < 32; ix++)
{
byte temp = shifts[ix];
int r = (int)(rand.nextFloat() * 32);
shifts[ix] = shifts[r];
shifts[r] = temp;
}
//System.out.println("descramble [");
//for (int ix = 0; ix < 32; ix++)
//{
// if (ix > 0) System.out.print(", ");
// System.out.print(shifts[ix]);
//}
//System.out.println("]");
int result = 0;
for (int ix = 0; ix < 32; ix++)
{
int shift = shifts[ix];
result |= ((value >>> shift) & 1) << ix;
}
result ^= hash;
//System.out.println("value " + Integer.toHexString(value) + ", hash " + Integer.toHexString(value) + ", result " + Integer.toHexString(result));
if (DEBUG_MODE) ThreadState.logln("descramble(" + value + ", " + key + ") -> " + result);
return result;
} // descramble()
/**
* Integer division. Returns the first argument divided by each of the reast. Each argument
* is converted to an <b>int</b> type. An empty or null array <b>arg</b> evalutes to 0.
* Any null arguments are ignored.
*/
public static int div(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("div(" + psize + " args)");
int result = 1;
try {
result = _int(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1, end = psize; ix < end; ix++)
{
try {
result /= _int(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // div()
/**
* Integer division with round-off. This works the similar to div(), except that
* when the resulting fractional part is 1/2 or greater the next higher integer (or lower
* in case of a negative result) is returned. Also, this only works with two arguments.
* @see div(Object[])
* @see divRoundUp(int, int)
*/
public static int divRoundOff(int i1, int i2) throws IllegalArgumentException
{
int result;
if (i2 == 0) throw new IllegalArgumentException("Cannot divide by 0.");
if ((i1 >= 0 && i2 > 0) || (i1 < 0 && i2 < 0)) result = (i1 + (i2 >> 1)) / i2;
else result = (i1 + (i2 >> 1)) / i2;
return result;
} // divRoundOff()
/**
* Integer division with round-up. This works the similar to div(), except that
* when their would be any remainder the next higher integer (or lower
* in case of a negative result) is returned. Also, this only works with two arguments.
* @see div(Object[])
* @see divRoundOff(int, int)
*/
public static int divRoundUp(int i1, int i2) throws IllegalArgumentException
{
int result;
if (i2 == 0) throw new IllegalArgumentException("Cannot divide by 0.");
if ((i1 >= 0 && i2 > 0) || (i1 < 0 && i2 < 0)) result = (i1 + i2 - 1) / i2;
else result = (i1 + i2 - 1) / i2;
return result;
} // divRoundUp()
// public void doGet(HttpServletRequest request, HttpServletResponse response)
// throws ServletException, IOException
// {
// _jspService(request, response);
// } // doGet()
// public void doPost(HttpServletRequest request, HttpServletResponse response)
// throws ServletException, IOException
// {
// _jspService(request, response);
// } // doPost()
/**
* Returns true if arg1 and arg2 are equals, false otherwise. Arg2 is converted to
* the same time as arg1, if the types to not match. If arg2 can't be converted the
* result is false. Case is ignored when comparing Strings.
*/
public boolean eq(Object arg1, Object arg2) //throws Exception
{
boolean result = false;
if (arg1 == null && arg2 == null) result = true;
else
if (arg1 != null && arg2 != null)
{
try {
if (arg1 instanceof String && ((String)arg1).equalsIgnoreCase(_String(arg2))) result = true;
else
if (arg1 instanceof Date && arg1.equals(_Date(arg2))) result = true;
else
if (arg1 instanceof Time && arg1.equals(_Time(arg2))) result = true;
else
if (arg1 instanceof Boolean && arg1.equals(_Boolean(arg2))) result = true;
else
if (arg1 instanceof Double && arg1.equals(_Double(arg2))) result = true;
else
if (arg1 instanceof Integer && arg1.equals(_Integer(arg2))) result = true;
else
if (arg1 instanceof Number && _Double(arg1).equals(_Double(arg2))) result = true;
else
if (_String(arg1).equalsIgnoreCase(_String(arg2))) result = true;
} catch (Exception e) {
}
}
if (DEBUG_MODE) ThreadState.logln("eq(" + arg1 + ", " + arg2 + ") -> " + result);
return result;
} // eq()
/**
* Make object ready for use in an SQL where clause. Outputs an '=' if value is set
* or 'is' if not, then converts the value to an Integer and outputs the value.
* @see quote(String)
*/
public static String eqInteger(Object value)
{
return (value == null || (value instanceof String && ((String)value).length() == 0)
? "is " : "= ") + sqlInteger(value);
} // eqInteger()
/**
* Make String ready for use in an SQL where clause. Outputs an '=' if value is set
* or 'is' if not, then quotes and outputs the value.
* @see quote(String)
*/
public static String eqQuote(String value)
{
return (value == null || value.length() == 0 ? " is " : " = ") + quote(value);
} // eqQuote()
/**
* Make object ready for use in an SQL where clause. Outputs an '=' if value is set
* or 'is' if not, then quotes and outputs the value.
* @see quote(String)
*/
public static String eqSql(Object value)
{
if (value == null || value instanceof String) return eqQuote((String)value);
if (value instanceof Object[] || value instanceof String[]
|| value instanceof Number[] || value instanceof Collection) return " in " + sql(value);
return " = " + sql(value);
} // eqSql()
/**
* Execute a statement. The first word specifies the type of statement: "array", "dir", "scan", or "sql".
* If none of those are found the statement is assumed to be of type "sql". The db option to switch
* databases is allowed at the beginning of sql statements.
*/
public DspStatement execute(String typeStr, Object obj) throws DspException
{
int type = SQL_STMT;
if (typeStr != null && typeStr.length() > 0)
{
if (typeStr.equals("scan"))
{
type = SCAN_STMT;
}
else
if (typeStr.equals("array"))
{
type = ARRAY_STMT;
}
else
if (typeStr.equals("dir"))
{
type = DIR_STMT;
}
else
if (!typeStr.equals("sql")) throw new IllegalArgumentException("Invalid statement type: " + typeStr);
}
return execute("_t999", type, obj);
} // execute()
/**
* Execute a statement. Used by DspDo, DspIf, DspSql, and DspWhile.
*/
protected DspStatement execute(String name, int type, Object obj)
throws DspException
{
DspStatement state = makeStatement(name, type);
state.execute(obj);
return state;
} // execute()
/**
* Execute a statement and return the first column of the first row if statement produces
* a result set. Otherwise, return the number of rows modified. The first word specifies
* the type of statement: "array", "dir", "scan", or "sql". If none of those are found the
* statement is assumed to be of type "sql". The db option to switch databases is allowed
* at the beginning of sql statements.
*/
public Object executeGet1st(String typeStr, Object obj) throws DspException
{
int type = SQL_STMT;
if (typeStr != null && typeStr.length() > 0)
{
if (typeStr.equals("scan"))
{
type = SCAN_STMT;
}
else
if (typeStr.equals("array"))
{
type = ARRAY_STMT;
}
else
if (typeStr.equals("dir"))
{
type = DIR_STMT;
}
else
if (!typeStr.equals("sql")) throw new IllegalArgumentException("Invalid statement type: " + typeStr);
}
return executeGet1st("_t998", type, obj);
} // executeGet1st()
/**
* Execute a statement and return the first column of the first row if statement produces
* a result set. Otherwise, return the number of rows modified. Used by DspSet and DspDefault.
*/
protected Object executeGet1st(String name, int type, Object obj)
throws DspException
{
DspStatement state = makeStatement(name, type);
try {
state.execute(obj);
if (state.hasResults())
{
state.next();
return state.getObject(1);
}
int result = state.getResult();
if (result == 0 || result == Integer.MIN_VALUE) return null;
return new Integer(result);
} finally {
state.close();
}
} // executeGet1st()
/**
* Real number absolute value. Returns the absolute value of <b>arg</b>.
*/
public static double fabs(double arg)
{
return arg < 0.0 ? -arg : arg;
} // fabs()
/**
* Real numebr addition. Returns the summation of all arguments. Each argument
* is converted to an <b>int</b> type. An empty or null array <b>arg</b> evalutes to 0.
* Any null arguments are ignored.
*/
public static double fadd(Object[] args)
{
if (args == null || args.length == 0) return 0.0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("fadd(" + psize + " args)");
double result = 0.0;
for (int ix = 0, end = psize; ix < end; ix++)
{
try {
result += _double(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // fadd()
/**
* Real number division. Returns the first argument divided by each of the reast. Each argument
* is converted to an <b>int</b> type. An empty or null array <b>arg</b> evalutes to 0.
* Any null arguments are ignored.
*/
public static double fdiv(Object[] args)
{
if (args == null || args.length == 0) return 0.0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("fdiv(" + psize + " args)");
double result = 1.0;
try {
result = _double(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1, end = psize; ix < end; ix++)
{
try {
result /= _double(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // div()
/**
* Returns the maximum (most positive) of the double arguments.
* Any null arguments are ignored.
*/
public static double fmax(Object[] args)
{
int psize;
if (args == null || ((psize = args.length) == 0)) return 0.0;
double result = 0.0;
try {
result = _double(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1; ix < psize; ix++)
{
try {
double temp = _double(args[ix]);
if (temp > result) result = temp;
} catch (NullPointerException e) {
}
}
return result;
} // fmax()
/**
* Returns the minimum (most negative) of the double arguments.
* Any null arguments are ignored.
*/
public static double fmin(Object[] args)
{
int psize;
if (args == null || ((psize = args.length) == 0)) return 0.0;
double result = 0.0;
try {
result = _double(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1; ix < psize; ix++)
{
try {
double temp = _double(args[ix]);
if (temp < result) result = temp;
} catch (NullPointerException e) {
}
}
return result;
} // fmin()
/**
* Real number multiplication. Returns the product of all arguments. Each argument
* is converted to an <b>int</b> type. An empty or null array <b>arg</b> evalutes to 0.
* Any null arguments are ignored.
*/
public static double fmul(Object[] args)
{
if (args == null || args.length == 0) return 0.0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("fmul(" + psize + " args)");
double result = 1.0;
try {
result = _double(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1, end = psize; ix < end; ix++)
{
try {
result *= _double(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // fmul()
/**
* Real number negation. Returns the negative of the argument.
*/
public static double fneg(double arg)
{
double result = -arg;
if (DEBUG_MODE) ThreadState.logln("fneg(" + arg + ") => " + result);
return result;
} // fneg()
/**
* Formats the value as a percentage, and returns the String.
*/
public static String formatPercent(double value)
{
return percent.format(value);
} // formatPercent()
/**
* Formats raw phone numbers both with and without area codes as follows:
* (aaa) eee-nnnn or eee-nnnn
*/
public static String formatPhone(String phone)
{
String phoneOrig = phone;
if (phone == null || phone.length() == 0) return phone;
phone = stripNonNumerics(phone.trim());
if (phone.length() == 0) return phone;
String prefix = "";
char c;
while ((c = phone.charAt(0)) == '0' || c == '1') {
prefix += c;
phone = phone.substring(1);
if (phone.length() == 0) break;
}
if (prefix.length() > 0) prefix += ' ';
int len = phone.length();
if (len == 7) return prefix + phone.substring(0, 3) + '-' + phone.substring(3);
if (len == 10) return prefix + '(' + phone.substring(0, 3) + ") " + phone.substring(3, 6)
+ '-' + phone.substring(6);
return phoneOrig;
} // formatPhone()
/**
* Convert from HTML to Unicode text. This function converts many of the encoded HTML
* characters to normal Unicode text. Example: &lt; to <. This is the opposite
* of showHtml().
* @see showHtml(String)
*/
public static String fromHtml(String text)
{
int ixz;
if (text == null || (ixz = text.length()) == 0) return text;
StringBuffer buf = new StringBuffer(ixz);
String rep = null;
for (int ix = 0; ix < ixz; ix++)
{
char c = text.charAt(ix);
if (c == '&');
{
String sub = text.substring(ix + 1).toLowerCase();
if (sub.startsWith("lt;"))
{
c = '<';
ix += 3;
}
else
if (sub.startsWith("gt;"))
{
c = '>';
ix += 3;
}
else
if (sub.startsWith("amp;"))
{
c = '&';
ix += 4;
}
else
if (sub.startsWith("nbsp;"))
{
c = ' ';
ix += 5;
}
else
if (sub.startsWith("semi;"))
{
c = ';';
ix += 5;
}
else
if (sub.startsWith("#"))
{
char c2 = 0;
for (int iy = ix + 1; iy < ixz; iy++)
{
char c1 = text.charAt(iy);
if (c1 >= '0' && c1 <= '9')
{
c2 = (char)(c2 * 10 + c1);
continue;
}
if (c1 == ';')
{
c = c2;
ix = iy;
}
break;
}
} else if (c == '<' && ix + 3 <= ixz && Character.toLowerCase(text.charAt(ix + 1)) == 'b'
&& Character.toLowerCase(text.charAt(ix + 2)) == 'r' && text.charAt(ix + 3) == '>') {
c = '\n';
}
}
if (rep != null)
{
buf.append(rep);
rep = null;
}
else buf.append(c);
}
return buf.toString();
} // fromHtml()
/**
* Real number subtraction. Each argument is subtracted from the first. If no arguments
* are submitted then the result is 0.
* Any null arguments are ignored.
*/
public static double fsub(Object[] args)
{
if (args == null || args.length == 0) return 0.0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("fsub(" + psize + " args)");
double result = 0.0;
try {
result = _double(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1, end = psize; ix < end; ix++)
{
try {
result -= _double(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // fsub()
/**
* Returns the sign of the argument as a real number: -1.0 if negative, 0.0 if 0.0, and
* 1.0 if positive.
*/
public static double fsgn(double arg)
{
if (arg < 0.0) return -1.0;
else
if (arg > 0.0) return 1.0;
else return 0.0;
} // fsgn()
/**
* Returns true if arg1 >= arg2, false otherwise.
*/
public static boolean ge(double arg1, double arg2)
{
return arg1 >= arg2;
} // ge()
/**
* Returns a new object instance.
*/
public static Object getBean(String className) throws DspException
{
try {
return Class.forName(className).newInstance();
} catch (Exception e) {
throw new DspException("Couldn't get bean " + className, e);
}
} // getBean()
/**
* Returns the value of the named member of the object. If the object is a DspObject
* get() is called. Otherwise, it uses reflection to look up and get the field.
*/
public static Object getMember(Object obj, String member) throws DspException
{
try {
return ((DspObject)obj).get(member);
} catch (ClassCastException e) {
Class<?> c = obj.getClass();
try {
Field f = c.getField(member);
// if (Modifier.isPublic(f.getModifiers())
// {
return f.get(obj);
// }
} catch (NoSuchFieldException e1) {
throw new DspException("Could not find field '" + member + '\'', e1);
} catch (IllegalAccessException e1) {
throw new DspException("Could not access field '" + member + '\'', e1);
}
}
} // getMember()
/**
* Returns the result of calling a named method of the object, passing args as the arguments
* of the function. If the object is a DspObject run() is called. Otherwise, it uses
* reflection to look up and call the method.
*/
public static Object getMember(Object obj, String member, Object[] args) throws DspException
{
// try {
// return ((DspObject) obj).run(member, args);
// } catch (ClassCastException e) {
Class<?> c = obj.getClass();
Class<?>[] types = null;
int len;
if (args != null && (len = args.length) > 0)
{
types = new Class[len];
for (int ix = 0; ix < len; ix++)
{
if (args[ix] != null)
{
types[ix] = args[ix].getClass();
}
}
}
try {
int close = 0;
Method[] meths = c.getMethods();
Method found = null;
//int choice = -1;
for (int ix = 0, ixz = meths.length; ix < ixz; ix++)
{
Method meth = meths[ix];
if (Modifier.isPublic(meth.getModifiers()) && meth.getName().equals(member))
{
Class<?>[] pTypes = meth.getParameterTypes();
if ((pTypes.length == 0 && args == null) || (args != null && pTypes.length == args.length))
{
int close1 = 1;
if (args != null)
{
for (int iy = 0, iyz = pTypes.length; iy < iyz; iy++)
{
if (pTypes[iy] == types[iy])
{
close1 += 2;
//ThreadState.logln(ix + " - " + pTypes[iy]);
}
else
if (pTypes[iy].isAssignableFrom(types[iy])) close1++;
} // for iy
} // if args
if (close1 > close)
{
//ThreadState.logln(ix + " got " + close1 + " points");
found = meth;
// choice = ix;
close = close1;
}
} // if name matches
} // for
}
if (found == null)
{
throw new DspException("Could not find method " + member + " in " + obj);
}
else
{
//ThreadState.logln("Choice " + choice);
return found.invoke(obj, args);
}
// } catch (NoSuchMethodException e1) {
// throw new DspException("Could not find method " + member + " in " + obj, e1);
} catch (IllegalAccessException e1) {
throw new DspException("Could not invoke method " + member + " in " + obj, e1);
} catch (InvocationTargetException e1) {
throw new DspException("Exception in method " + member + " in " + obj, e1.getTargetException());
} catch (Throwable e1) {
throw new DspException("Exception in method " + member + " in " + obj, e1);
}
// }
} // getMember(args)
/**
* Returns an instantiation of a tag extenion object.
*/
public static Tag getTag(DspObject temp, String prefix, String action, String className) throws DspException
{
Tag tag = (Tag)temp.get('_' + prefix + '_' + action);
if (tag == null)
{
try {
tag = (Tag)Class.forName(className).newInstance();
} catch (Exception e) {
throw new DspException("Could not create " + className);
}
}
return tag;
} // getTag()
// abstract public long getId();
/**
* Returns the prop object belonging to this group or pages.
*/
public DspProp getProp() { return prop; }
/**
* Returns true if arg1 > arg2.
*/
public static boolean gt(double arg1, double arg2)
{
boolean result = arg1 > arg2;
if (DEBUG_MODE) ThreadState.logln("gt(" + arg1 + ", " + arg2 + ") => " + result);
return result;
} // gt()
/**
* Converts the String to HTML format. It looks for certain characters and converts them
* to the proper HTML tags. If the String already contains HTML tags, these will be left
* intact. You will probably use this function heavily, unless you store HTML directly in
* your database. The following table lists the conversions that take place within this function:
* <table>
* <tr><td>From</td><td>To</td><td>Conditions and Comments</td></tr>
* <tr><td>\r, \n, or \r\n</td><td><br></td><td> </td></tr>
* <tr><td>\t</td><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td> </td></tr>
* <tr><td><space><space>...</td><td>&nbsp;...<space></td><td><space> means a space character</td></tr>
* <tr><td>&</td><td>&amp;</td><td> </td></tr>
* <tr><td>;</td><td>&semi;</td><td> </td></td>
* <tr><td>*</td><td><ul><li></td><td>Unordered list; must begin a line</td></tr>
* <tr><td>**...</td><td><ul><ul>...<li></td><td>Higher level lists; must begin a line</td></tr>
* <tr><td>#</td><td><ol><li></td><td>Ordered list; must begin a line</td></tr>
* <tr><td>##...</td><td><ol><ol>...<li></td><td>Higher level lists; must begin a line</td></tr>
* <tr><td>^</td><td><blockquote></td><td>Indented block; must begin a line</td></tr>
* <tr><td>^^...</td><td><blockquote><br><blockquote>...</td><td>Higher level indents; must begin a line</td></tr>
* <tr><td>(c) or (C)</td><td>&copy;</td><td>©</td></tr>
* <tr><td>(r) or (R)</td><td>&reg;</td><td>®</td></tr>
* <tr><td>(tm) or (TM)</td><td><small><sub>TM</small></sub></td><td><small><sup>TM</small></sup></td></tr>
* <tr><td>(sm) or (SM)</td><td><small><sub>SM</small></sub></td><td><small><sup>SM</small></sup></td></tr>
* <tr><td>{</td><td>&#123;</td><td>To prevent DSP from parsing published pages</td></tr>
* <tr><td>}</td><td>&#125;</td><td>same as above</td></tr>
* </table>
*/
public static String html(String text)
{
String org = text;
String result;
if (text == null || isHtml(text)) result = text;
else
{
int ix;
StringBuffer buf = new StringBuffer(text);
buf.ensureCapacity(text.length() * 5 / 4);
addAnchors(buf);
htmlCharsBuf(buf);
text = buf.toString();
int end = text.length();
buf.setLength(0);
int level0 = 0, level = 0, tab0 = 0, tab = 0;
char c1 = '\n', c;
boolean bar = false;
for (ix = 0; ix <= end; ix++)
{
c = c1;
c1 = ix < end ? text.charAt(ix) : (char)-1;
String app = null;
switch (c)
{
case '\r':
if (c1 == '\n')
{
c = c1;
c1 = ++ix < end ? text.charAt(ix) : (char)-1;
}
case '\n':
level = tab = 0;
if (c1 == '^')
{
while (c1 == '^')
{
c = c1;
c1 = ++ix < end ? text.charAt(ix) : (char)-1;
tab++;
}
}
if (c1 == '|')
{
bar = true;
while (c1 == '|')
{
c = c1;
c1 = ++ix < end ? text.charAt(ix) : (char)-1;
tab++;
}
}
if (c1 == '*')
{
while (c1 == '*')
{
c = c1;
c1 = ++ix < end ? text.charAt(ix) : (char)-1;
level++;
}
}
else
if (c1 == '#')
{
while (c1 == '#')
{
c = c1;
c1 = ++ix < end ? text.charAt(ix) : (char)-1;
level--;
}
}
//System.out.println("level " + level0 + " -> " + level);
//System.out.println("tab " + tab0 + " -> " + tab);
while (level0 > level && level0 > 0)
{
if (app != null) buf.append(app);
app = "</ul>";
level0--;
}
while (level0 < level && level0 < 0)
{
if (app != null) buf.append(app);
app = "</ol>";
level0++;
}
boolean br = ix > 0;
while (tab0 > tab)
{
br = false;
if (app != null) buf.append(app);
app = "</blockquote>";
tab0--;
}
while (tab0 < tab)
{
br = false;
if (app != null) buf.append(app);
if (bar) app = "<blockquote dir=ltr style=\"PADDING-RIGHT: 0px; PADDING-LEFT: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #000000 2px solid; MARGIN-RIGHT: 0px\">";
else app = "<blockquote>";
tab0++;
}
bar = false;
while (level0 < level)
{
if (app != null) buf.append(app);
app = "<ul>";
level0++;
}
while (level0 > level)
{
if (app != null) buf.append(app);
app = "<ol>";
level0--;
}
if (level != 0)
{
if (app != null) buf.append(app);
app = "<li>";
}
else if (br)
{
if (app != null) buf.append(app);
app = "<br>";
}
break;
case '\t':
app = " ";
break;
case ' ':
if (c1 == ' ') app = " ";
break;
}
if (app != null) buf.append(app);
else if (c > 0) buf.append(c);
}
while (level0 != 0)
{
if (level0 < 0)
{
buf.append("</ol>");
level0++;
}
else
{
buf.append("</ul>");
level0--;
}
}
result = buf.toString();
}
if (DEBUG_MODE) ThreadState.logln("html(" + org + ") -> " + result);
return result;
} // html()
/**
* Converts the String to HTML format. It looks for certain characters and converts them
* to the proper HTML tags. If the String already contains HTML tags, these will be left
* intact. You will probably use this function heavily, unless you store HTML directly in
* your database. The following table lists the conversions that take place within this function:
* <table>
* <tr><td>From</td><td>To</td><td>Conditions and Comments</td></tr>
* <tr><td>(c) or (C)</td><td>&copy;</td><td>©</td></tr>
* <tr><td>(r) or (R)</td><td>&reg;</td><td>®</td></tr>
* <tr><td>(tm) or (TM)</td><td><small><sub>TM</small></sub></td><td><small><sup>TM</small></sup></td></tr>
* <tr><td>(sm) or (SM)</td><td><small><sub>SM</small></sub></td><td><small><sup>SM</small></sup></td></tr>
* <tr><td>{</td><td>&#123;</td><td>To prevent DSP from parsing published pages</td></tr>
* <tr><td>}</td><td>&#125;</td><td>same as above</td></tr>
* </table>
*/
public static String htmlChars(String text)
{
StringBuffer buf = new StringBuffer(text);
buf.ensureCapacity(text.length() * 5 / 4);
htmlCharsBuf(buf);
String result = buf.toString();
if (DEBUG_MODE) ThreadState.logln("htmlChars(" + text + ") -> " + result);
return result;
} // htmlChars()
private static void htmlCharsBuf(StringBuffer buf)
{
replaceBuf(buf, "(TM)", "<small><small><sup>TM</sup></small></small>");
replaceBuf(buf, "(tm)", "<small><small><sup>TM</sup></small></small>");
replaceBuf(buf, "(SM)", "<small><small><sup>SM</sup></small></small>");
replaceBuf(buf, "(sm)", "<small><small><sup>SM</sup></small></small>");
replaceBuf(buf, "(R)", "®");
replaceBuf(buf, "(r)", "®");
replaceBuf(buf, "(C)", "©");
replaceBuf(buf, "(c)", "©");
if (buf != null)
{
for (int ix = 0, ixz = buf.length(); ix < ixz; ix++)
{
char c = buf.charAt(ix);
if (c > 0x7f || c == '{' || c == '}')
{
String str = "&#" + (int)c + ';';
buf.replace(ix, ix + 1, str);
ix += str.length() - 1;
}
}
}
if (DEBUG_MODE) ThreadState.logln("htmlCharsBuf()");
} // htmlCharsBuf()
/**
* Join a sequence into a single string, separated by sep.
* Items that are null are skipped.
* @param list list of items
* @param sep separator
* @return joined string
*/
public static CharSequence join(Collection<?> list, String sep) {
StringBuilder result = new StringBuilder();
for (Object item : list) {
if (item != null) {
if (result.length() > 0) result.append(sep);
result.append(item);
}
}
return result;
}
/**
* Join a sequence into a single string, separated by sep.
* Items that are null are skipped.
* @param list list of items
* @param sep separator
* @return joined string
*/
public static CharSequence join(Object[] list, String sep) {
StringBuilder result = new StringBuilder();
for (Object item : list) {
if (item != null) {
if (result.length() > 0) result.append(sep);
result.append(item);
}
}
return result;
}
/**
* Binary multiplexer, If the first argument evaluates to true then the second argument
* is returned. If false, the third argument is return, or null if there was no third argument.
*/
public static Object iff(Object[] args) throws IllegalArgumentException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("iff() can only accept 2 or 3 parameters");
Object param = args[0];
// ThreadState.log("iff(" + args + ") -> ");
if (_boolean(param))
{
if (DEBUG_MODE) ThreadState.logln(args[1]);
return args[1];
}
else
if (psize == 3)
{
if (DEBUG_MODE) ThreadState.logln(args[2]);
return args[2];
}
else
{
if (DEBUG_MODE) ThreadState.logln("null");
return null;
}
} // iff()
/**
* Return the first index of a substring within the String. This function returns the index of
* the second element as a String if found within the first as a String. If not found then -1 is returned.
* If three elements are sent, it is starting index for the search.
* @see lastIndexOf(Object[])
*/
public static int indexOf(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("indexOf() can only accept 2 or 3 arguments");
String data = _String(args[0]);
String find = _String(args[1]);
int result;
if (data == null || find == null) result = -1;
else
{
int index = 0;
if (psize > 2)
{
index = _int(args[2]);
}
result = data.indexOf(find, index);
}
if (DEBUG_MODE) ThreadState.logln("indexOf(" + args + ") -> " + result);
return result;
} // indexOf()
/**
* Format Timestamp in various ways. This multipurpose function can convert a Timestamp object
* to a String in several formats. This function only
* accepts one or two arg elements. If two, the first is the requested function
* to perform, and the second is converted to java.sql.Time. If one, the request is assumed
* to be "short". The following are the types of functions performed based on the request:
* <table><tr><td>Request (arg1)</td><td>Returned</td><td>Type</td><td>Example</td></tr>
* <tr><td>short</td><td>Short Timestamp</td><td>String</td><td>2000-11-20 12:13 PM</td></tr>
* <tr><td>long</td><td>Long Timestamp</td><td>String</td><td>Monday, November 20, 2000 12:13:52.239 PM MST</td></tr>
* <tr><td>sql</td><td>SQL Timestamp</td><td>String</td><td>{ts '2000-11-20 12:13:52.239 PM MST'}</td></tr>
* <tr><td>access</td><td>MS Access Timestamp</td><td>String</td><td>#2000-11-20 12:13:56 PM#</td></tr></table>
* @deprecated
*/
public static Object instant(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 1 || psize == 2))
throw new IllegalArgumentException("instant() can only accept 1 or 2 arguments");
String type = null;
Timestamp date;
if (psize == 2)
{
type = _String(args[0]);
date = _Instant(args[1]);
}
else date = _Instant(args[0]);
String result;
if (psize == 1
|| SHORT.equalsIgnoreCase(type)) result = instantShort(date);
else
if (LONG.equalsIgnoreCase(type)) result = instantLong(date);
else
if (SQL.equalsIgnoreCase(type)) result = instantSql(date);
else
if (ACCESS.equalsIgnoreCase(type)) result = instantAccess(date);
else throw new IllegalArgumentException("instant(" + type + ", " + date + ") error, unknown instant function");
if (DEBUG_MODE) ThreadState.logln("instant(" + args + ") -> " + result);
return result;
} // instant()
/**
* Convert Timestamp to an MS Access SQL String. Converts the Timestamp to a String for use
* in an SQL statement when using Microsoft Access(tm). This is needed because MS Access,
* using the JDBC-ODBC bridge, doesn't support the standard JDBC Timestamp format.
*/
public static String instantAccess(Timestamp date)
{
String result;
if (date == null) result = NULL;
else result = '#' + instantAccessForm.format(date) + '#';
if (DEBUG_MODE) ThreadState.logln("instantAccess(" + date + ") -> " + result);
return result;
} // instantAccess()
/**
* Add units of time to a Timestamp. Adds years, months, weeks, days, hours,
* minutes, seconds, milliseconds from Time. It accepts 2 or three members of args. The first
* is convert to Time. The second is the value to be added. The third, if present, is
* the units String: years, months, weeks, days, hours, mins, secs, msecs. If no third member
* is present, the units are assumed to be milliseconds.
*/
public static Timestamp instantAdd(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("instantAdd() can only accept 2 or 3 arguments");
Timestamp date = _Instant(args[0]);
int value = _int(args[1]);
String str = "msec";
if (psize == 3)
{
str = _String(args[2]);
}
int type = 'i';
if (str.length() > 0) type = Character.toLowerCase(str.charAt(0));
if (str.length() > 1 && type == 'm')
{
int t2 = Character.toLowerCase(str.charAt(1));
if (t2 == 's') type = 'i';
else
if (t2 == 'i') type = 'n';
}
Calendar c = Calendar.getInstance();
c.setTime(date);
switch (type)
{
case 'i':
c.add(Calendar.MILLISECOND, value);
break;
case 's':
c.add(Calendar.SECOND, value);
break;
case 'n':
c.add(Calendar.MINUTE, value);
break;
case 'h':
c.add(Calendar.HOUR, value);
break;
case 'd':
c.add(Calendar.DATE, value);
break;
case 'm':
c.add(Calendar.MONTH, value);
break;
case 'w':
c.add(Calendar.WEEK_OF_YEAR, value);
break;
case 'y':
c.add(Calendar.YEAR, value);
break;
default:
throw new IllegalArgumentException("Unknown value type: " + str);
}
Timestamp result = new Timestamp(c.getTime().getTime());
if (DEBUG_MODE) ThreadState.logln("instantAdd(" + args + ") -> " + result);
return result;
} // instantAdd()
/**
* Returns the date and time in the American standar format MM/DD/YYYY HH:MM AM|PM
*/
public static String instantAmerican(Date date)
{
String result;
if (date == null) result = null;
else result = instantAmer.format(date);
if (DEBUG_MODE) ThreadState.logln("instantAmerican(" + date + ") -> " + result);
return result;
} // instantAmerican()
/**
* Returns a String with the computed difference between two Timestamps.
*/
public static String instantDiff(Timestamp time1, Timestamp time2)
{
return msecDiff(time1.getTime(), time2.getTime());
} // instantDiff()
/**
* Convert Instant to long String. Converts the Timestamp to a long formatted String.
*/
public static String instantLong(Timestamp date)
{
String result;
if (date == null) result = null;
else result = instantlong.format(date);
if (DEBUG_MODE) ThreadState.logln("instantLong(" + date + ") -> " + result);
return result;
} // instantLong()
/**
* Convert Instant to short String. Converts the Timestamp to a short formatted String.
*/
public static String instantShort(Timestamp date)
{
String result;
if (date == null) result = null;
else result = date.toString();
if (DEBUG_MODE) ThreadState.logln("instantShort(" + date + ") -> " + result);
return result;
} // instantShort()
/**
* Convert Timestamp to an SQL String. Converts the Timestamp to a String for use
* in an SQL statement.
*/
public static String instantSql(Timestamp date)
{
String result;
if (date == null) result = NULL;
else result = "{ts '" + date + "'}";
if (DEBUG_MODE) ThreadState.logln("instantSql(" + date + ") -> " + result);
return result;
} // instantSql()
/**
* Subtract units of time from a Timestamp. Subtracts years, months, weeks, days, hours,
* minutes, seconds, milliseconds from Time. It accepts 2 or three members of args. The first
* is convert to Time. The second is the value to be subtracted. The third, if present, is
* the units String: years, months, weeks, days, hours, mins, secs, msecs. If no third member
* is present, the units are assumed to be milliseconds.
*/
public static Timestamp instantSub(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("instantSub() can only accept 2 or 3 arguments");
args[1] = new Integer(-_int(args[1]));
Timestamp result = instantAdd(args);
if (DEBUG_MODE) ThreadState.logln("instantSub(" + args + ") -> " + result);
return result;
} // instantSub()
/**
* Returns true if the object is a java.sql.Date or can be converted to one.
*/
public static boolean isDate(Object obj)
{
boolean result = false;
try {
result = _Date(obj) != null;
} catch (Exception e) {
}
if (DEBUG_MODE) ThreadState.logln("isDate(" + obj + ") -> " + result);
return result;
} // isDate()
/**
* Returns true if the object is a real number or can be converted to one.
*/
public static boolean isFloat(Object obj)
{
boolean result = false;
try {
result = _Float(obj) != null;
} catch (Exception e) {
}
if (DEBUG_MODE) ThreadState.logln("isFloat(" + obj + ") -> " + result);
return result;
} // isFloat()
/**
* Returns true if the String begins and ends with HTML tags.
*/
public static boolean isHtml(String text)
{
boolean result = false;
if (text != null)
{
String temp = text.trim();
int end = temp.length();
if (end >= 3 && temp.charAt(0) == '<'
&& temp.charAt(end - 1) == '>') result = true;
}
if (DEBUG_MODE) ThreadState.logln("isHtml(" + text + ") -> " + result);
return result;
} // isHtml()
/**
* Returns true if the object is a java.sql.Timestamp or can be converted to one.
*/
public static boolean isInstant(Object obj)
{
boolean result = false;
try {
result = _Instant(obj) != null;
} catch (Exception e) {
}
if (DEBUG_MODE) ThreadState.logln("isInstant(" + obj + ") -> " + result);
return result;
} // isInstant()
/**
* Returns true if the object is a integral number or can be converted to one.
*/
public static boolean isInt(Object obj)
{
boolean result = false;
try {
result = _Integer(obj) != null;
} catch (Exception e) {
}
if (DEBUG_MODE) ThreadState.logln("isInt(" + obj + ") -> " + result);
return result;
} // isInt()
/**
* Same as isInt(Object)
*/
public static boolean isInteger(Object obj)
{
return isInt(obj);
} // isInteger()
/**
* Returns true if the object is a null.
*/
public static boolean isNull(Object obj)
{
boolean result = (obj == null) || (obj instanceof DspNull);
if (DEBUG_MODE) ThreadState.logln("isNull(" + obj + ") -> " + result);
return result;
} // isNull()
/**
* Returns true if obj is not null or if obj is a String returns true if it is not empty.
*/
public static boolean isSet(Object obj)
{
if (obj == null) return false;
String str = _String(obj);
return str.length() > 0;
} // isSet()
/**
* Returns true if the object is a java.sql.Time or can be converted to one.
*/
public static boolean isTime(Object obj)
{
boolean result = false;
try {
result = _Time(obj) != null;
} catch (Exception e) {
}
if (DEBUG_MODE) ThreadState.logln("isTime(" + obj + ") -> " + result);
return result;
} // isTime()
public void jspInit() {}
public void jspDestroy() {}
/**
* Return the last index of a substring within the String. This function returns the index of
* the second element as a String if found within the first as a String. If not found then -1 is returned.
* If three elements are sent, it is starting index for the search.
* @see indexOf(Object[])
*/
public static int lastIndexOf(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("lastIndexOf() can only accept 2 or 3 arguments");
String data = _String(args[0]);
String find = _String(args[1]);
int result;
if (data == null || find == null) result = -1;
else
{
int index = data.length();
if (psize > 2)
{
index = _int(args[2]);
}
result = data.lastIndexOf(find, index);
}
if (DEBUG_MODE) ThreadState.logln("lastIndexOf(" + args + ") -> " + result);
return result;
} // lastIndexOf()
/**
* Returns true if the first argument is less than or equal to the second, comparison
* is done with real numbers.
*/
public static boolean le(double arg1, double arg2)
{
boolean result = arg1 <= arg2;
if (DEBUG_MODE) ThreadState.logln("le(" + arg1 + ", " + arg2 + ") => " + result);
return result;
} // le()
/**
* Return the length of the String.
*/
public static int length(String data)
{
int result;
if (data == null) result = 0;
else
{
result = data.length();
}
if (DEBUG_MODE) ThreadState.logln("length(" + data + ") -> " + result);
return result;
} // length()
/**
* Truncate the String to lim characters, from the left.
* @see rlimit()
*/
public static String limit(String data, int lim)
{
String result = null;
if (lim > 0)
{
result = data;
if (data != null && data.length() > lim)
{
result = data.substring(0, lim);
}
}
if (DEBUG_MODE) ThreadState.logln("limit(" + data + ", " + lim + ") -> " + result);
return result;
} // limit()
/**
* Convert String to lower case.
*/
public static String lowerCase(String arg)
{
String result;
if (arg == null) result = null;
else result = arg.toLowerCase();
if (DEBUG_MODE) ThreadState.logln("lowerCase(" + arg + ") -> " + arg);
return result;
} // lowerCase()
/**
* Returns true if the first argument is less than the second, compared as real numbers.
*/
public static boolean lt(double arg1, double arg2)
{
boolean result = arg1 < arg2;
if (DEBUG_MODE) ThreadState.logln("lt(" + arg1 + ", " + arg2 + ") => " + result);
return result;
} // lt()
private DspStatement makeStatement(String name, int type)
throws DspException, IllegalArgumentException
{
DspStatement state;
boolean debug = false, trace = false;
try { debug = _boolean(ThreadState.getOpen().get(DspObject.DEBUG)); } catch (NumberFormatException e) {}
try { trace = _boolean(ThreadState.getOpen().get(DspObject.TRACE)); } catch (NumberFormatException e) {}
switch (type)
{
case ARRAY_STMT:
state = new DspStatementArray(name, debug, trace);
break;
case DIR_STMT:
state = new DspStatementDir(name, debug, trace);
break;
case SCAN_STMT:
state = new DspStatementScan(name, debug, trace);
break;
case SQL_STMT:
state = new DspStatementSql(name, debug, trace);
break;
default: throw new IllegalArgumentException("Invalid statement type: " + type);
}
return state;
} // makeStatement()
/**
* Returns the maximum (most positive) of the int arguments.
* Any null arguments are ignored.
*/
public static int max(Object[] args)
{
int psize;
if (args == null || ((psize = args.length) == 0)) return 0;
int result = 0;
try {
result = _int(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 0; ix < psize; ix++)
{
try {
int temp = _int(args[ix]);
if (temp > result) result = temp;
} catch (NullPointerException e) {
}
}
return result;
} // max()
/**
* Returns the minimum (most negative) of the int arguments.
* Any null arguments are ignored.
*/
public static int min(Object[] args)
{
int psize;
if (args == null || ((psize = args.length) == 0)) return 0;
int result = 0;
try {
result = _int(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 0; ix < psize; ix++)
{
try {
int temp = _int(args[ix]);
if (temp < result) result = temp;
} catch (NullPointerException e) {
}
}
return result;
} // min()
/**
* Returns the remainder of num / den
*/
public static int mod(int num, int den)
{
return num % den;
} // mod()
/**
* Retuns the difference between two millisecond time values, as a String.
*/
public static String msecDiff(long date1, long date2)
{
double diff = date1 > date2 ? date1 - date2 : date2 - date1;
String result = null;
if (diff == 0) result = "no time";
else
{
if (diff < 1000) result = diff + " milliseconds";
else
{
diff /= 1000;
if (diff < 60) result = tens.format(diff) + " seconds";
else
{
diff /= 60;
if (diff < 60) result = tens.format(diff) + " minutes";
else
{
diff /= 60;
if (diff < 24) result = tens.format(diff) + " hours";
else
{
diff /= 24l;
if (diff < 31) result = tens.format(diff) + " days";
else if (diff < 365) result = tens.format(diff / 31) + " months";
else result = tens.format(diff / 365) + " years";
}
}
}
}
}
if (DEBUG_MODE) ThreadState.logln("msecDiff(" + date1 + ", " + date2 + ") -> " + result);
return result;
} // msecDiff()
/**
* Integer multiplication. Returns the product of all arguments. Each argument
* is converted to an <b>int</b> type. An empty or null array <b>arg</b> evalutes to 0.
* Any null arguments are ignored.
*/
public static int mul(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("mul(" + psize + " args)");
int result = 1;
try {
result = _int(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1, end = psize; ix < end; ix++)
{
try {
result *= _int(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // mul()
/**
* Return one of several arguments depending the first. The first argument is compared
* with each odd indexed argument. If a match is found then the following argument is returned.
* If no match is found then the last argument is return as the default, or null if there
* were an odd number of arguments. If the first argument is a string, then the comparisons
* by converting the objects to strings and and ignoring the case. Otherwise, Object.equals()
* is used for comparison and the programmer must ensure type and value match.
*/
public static Object multiplex(Object[] args) throws IllegalArgumentException
{
int psize = args.length;
if (!(psize >= 3))
throw new IllegalArgumentException("multiplex() requires 3 or more arguments");
Object obj = args[0];
Object def = (psize & 1) == 0 ? args[psize - 1] : null;
Object result = def;
if (obj != null)
{
String str = obj instanceof String ? (String)obj : null;
for (int ix = 1, end = psize - 1; ix < end; ix += 2)
{
Object test = args[ix];
if (test != null)
{
if ((str != null && str.equalsIgnoreCase(_String(test)))
|| obj.equals(test))
{
result = args[ix + 1];
break;
}
}
}
}
if (DEBUG_MODE) ThreadState.logln("multiplex(" + args + ") -> " + result);
return result;
} // multiplex()
/**
* Not Equal. Return true if the two objects are not equal. This calls eq() and returns the
* boolean negative.
* @see eq(Object, Object)
*/
public boolean ne(Object arg1, Object arg2) //throws Exception
{
boolean result = !eq(arg1, arg2);
if (DEBUG_MODE) ThreadState.logln("ne(" + arg1 + ", " + arg2 + ") -> " + result);
return result;
} // ne()
/**
* Integer Negation. Return the integer negative of the argument.
*/
public static int neg(int arg)
{
int result = -arg;
if (DEBUG_MODE) ThreadState.logln("neg(" + arg + ") => " + result);
return result;
} // neg()
/**
* Returns a path with the /./, and // removed and /folder/../ simplified. Note: paths
* are converted to POSIX/Unix standard.
*/
public static String normalizePath(String path)
{
if (path == null || path.length() < 2) return path;
int ix = 0;
StringBuffer buf = new StringBuffer(path);
char sep = File.separatorChar;
// Convert non Posix file separators to slashes
if (sep != '/')
{
boolean changed = false;
while ((ix = path.indexOf(sep, ix)) >= 0)
{
buf.setCharAt(ix++, '/');
changed = true;
}
// If it starts with a DOS drive letter, preceed the path with a '/'
if (sep == '\\' && buf.charAt(1) == ':')
{
char c = buf.charAt(0);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
{
buf.insert(0, '/');
changed = true;
}
}
if (changed) path = buf.toString();
}
// loop until no changes happen
String temp = null;
do {
temp = path;
// convert // to /
while ((ix = path.indexOf("//")) >= 0)
{
buf.deleteCharAt(ix + 1);
path = buf.toString();
}
// convert /./ to /
while ((ix = path.indexOf("/./")) >= 0)
{
buf.delete(ix + 1, ix + 3);
path = buf.toString();
}
// convert /folder/../ to /
ix = -1;
while ((ix = path.indexOf("/../", ix + 1)) >= 0)
{
int iy = path.lastIndexOf('/', ix - 1);
if (iy >= 0 && (ix <= 2 || !buf.toString().substring(ix - 2, ix).equals("..")))
{
buf.delete(iy + 1, ix + 4);
path = buf.toString();
ix = iy - 1;
}
}
} while (!temp.equals(path));
return path;
} // normalizePath()
/**
* Return the boolean negative of the argument.
*/
public static boolean not(boolean arg)
{
boolean result = !arg;
if (DEBUG_MODE) ThreadState.logln("not(" + arg + ") => " + result);
return result;
} // not()
/**
* Return the Time of day.
*/
public static Time now()
{
Time result = new Time(System.currentTimeMillis());
if (DEBUG_MODE) ThreadState.logln("now() => " + result);
return result;
} // now()
/**
* Logical Or. Calculates the logical <b>or</b> of all arguments.
* Each argument is converted to a boolean as it is used. An empty or null
* array arg evaluates to 0. Note, this function cannot do short-circut
* evalation, as Java dose when you use the || operator.
* @see and()
*/
public static boolean or(Object[] args)
{
if (args == null || args.length == 0) return false;
int psize = args.length;
boolean result = false;
for (int ix = 0, end = psize; !result && ix < end; ix++)
{
try {
result |= _boolean(args[ix]);
} catch (NullPointerException e) {
}
}
if (DEBUG_MODE) ThreadState.logln("or(" + psize + " args) -> " + result);
return result;
} // or()
/**
* Make String ready for use in an SQL statement. Adds single quotes around the string
* and quotes embeded quotes.
* @see sql(String)
*/
public static String quote(String value)
{
int len;
boolean unicode = false;
if (value == null || (len = value.length()) == 0) return NULL;
StringBuffer buf = new StringBuffer(len + len / 10 + 5);
buf.append('\'');
for (int ix = 0, iz = value.length(); ix < iz; ix++)
{
char c = value.charAt(ix);
if (c > 127 && !unicode)
{
buf.insert(0, 'N'); // MS SQL Server 7 specific
unicode = true;
buf.append(c);
}
else
if (c == '\'')
{
buf.append("''");
}
else buf.append(c);
}
buf.append('\'');
String result = buf.toString();
if (DEBUG_MODE) ThreadState.logln("quote(" + value + ") -> " + result);
return result;
} // quote()
/**
* Make String ready for use as a double quoted HTML attribute. Converts embeded quotes to
* ", and <> to < and >. It will enclose the resulting string in double quotes if
* the second parameter is true.
*/
public static String quoteHtml(String value, boolean enclose)
{
int len;
if (value == null || (len = value.length()) == 0)
{
if (enclose) return "\"\"";
return "";
}
StringBuffer buf = new StringBuffer(len + len / 10 + 5);
if (enclose) buf.append('"');
for (int ix = 0, iz = value.length(); ix < iz; ix++)
{
char c = value.charAt(ix);
switch (c) {
case '"':
buf.append(""");
break;
case '<':
buf.append("<");
break;
case '>':
buf.append(">");
break;
default:
buf.append(c);
}
}
if (enclose) buf.append('"');
String result = buf.toString();
if (DEBUG_MODE) ThreadState.logln("quoteHtml(" + value + ", " + enclose + ") -> " + result);
return result;
} // quoteHtml()
/**
* Make String ready for use as a double quoted HTML attribute. Converts embeded quotes to
* ". It will not enclose the resulting string in double quotes.
*/
public static String quotes(String value)
{
return quoteHtml(value, false);
} // quotes()
/**
* Make String ready for use in a JavaScript expression. Adds single quotes around the string
* and backslashes embeded quotes.
* @see _script(String)
*/
public static String quoteScript(String value)
{
int len;
if (value == null) return NULL;
if ((len = value.length()) == 0) return "''";
StringBuffer buf = new StringBuffer(len + len / 10 + 5);
buf.append('\'');
for (int ix = 0, iz = value.length(); ix < iz; ix++)
{
char c = value.charAt(ix);
if (c == '<') {
buf.append("<");
continue;
}
if (c == '>') {
buf.append(">");
continue;
}
if (c == '"') {
buf.append(""");
continue;
}
if (c == '\'' || c == '\\') buf.append("\\");
buf.append(c);
}
buf.append('\'');
String result = buf.toString();
if (DEBUG_MODE) ThreadState.logln("quoteScript(" + value + ") -> " + result);
return result;
} // quoteScript()
/**
* Make String ready for use in a JavaScript expression. Adds double quotes around the string
* and backslashes embeded quotes.
* @see quotes(String)
*/
public static String quotesScript(String value)
{
int len;
if (value == null) return NULL;
if ((len = value.length()) == 0) return "''";
StringBuffer buf = new StringBuffer(len + len / 10 + 5);
buf.append('"');
for (int ix = 0, iz = value.length(); ix < iz; ix++)
{
char c = value.charAt(ix);
if (c == '<') {
buf.append("<");
continue;
}
if (c == '>') {
buf.append(">");
continue;
}
if (c == '"' || c == '\\')
{
buf.append("\\");
}
else buf.append(c);
}
buf.append('"');
String result = buf.toString();
if (DEBUG_MODE) ThreadState.logln("quotesScript(" + value + ") -> " + result);
return result;
} // quotesScript()
/**
* Stores the tag extension object for use later in the same request.
*/
public static void releaseTag(DspObject temp, String prefix, String action, Tag tag) throws DspException
{
tag.release();
temp.set('_' + prefix + '_' + action, tag);
} // releaseTag()
/**
* Substring Replacer. For each instance of <b>sub</b> found in <b>str</b>, it is replaced
* by <b>rep</b>. The resulting String is returned.
*/
public static String replace(String str, String sub, String rep)
{
StringBuffer buf = null;
int lenS = sub.length();
for (int last = 0;;)
{
int ix = str.indexOf(sub, last);
if (ix < 0)
{
if (buf != null)
{
buf.append(str.substring(last));
str = buf.toString(); // return str as result
}
break;
}
if (buf == null) buf = new StringBuffer(str.length() * 3 / 2);
buf.append(str.substring(last, ix));
buf.append(rep);
last = ix + lenS;
}
return str;
} // replace()
/**
* Substring Replacer. For each instance of <b>sub</b> found in <b>str</b>, it is replaced
* by <b>rep</b>. The buffer argument itself is modifed and returned. This is faster than
* replace(), especially useful when called multiple times for various replacements.
*/
public static StringBuffer replaceBuf(StringBuffer buf, String sub, String rep)
{
String str = buf.toString();
int lenS = sub.length();
int diff = rep.length() - lenS;
int offset = 0;
for (int last = 0;;)
{
int ix = str.indexOf(sub, last);
if (ix < 0) break;
buf.replace(ix + offset, ix + offset + lenS, rep);
last = ix + lenS;
offset += diff;
}
return buf;
} // replaceBuf()
/**
* Return the Timestamp of this instant.
*/
public static Timestamp rightNow()
{
return new Timestamp(System.currentTimeMillis());
} // rightNow()
/**
* Truncate the String to lim characters, from the right.
* @see limit()
*/
public static String rlimit(String data, int lim)
{
String result = null;
if (data != null && lim > 0)
{
result = data;
int len;
if (data != null && (len = data.length()) > lim)
{
result = data.substring(len - lim);
}
}
if (DEBUG_MODE) ThreadState.logln("rlimit(" + data + ", " + lim + ") -> " + result);
return result;
} // rlimit()
private static final double[] mulDig = {1, 10, 100, 1000, 10000, 100000,
1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12};
private static final double[] divDig = {1, .1, .01, .001, .0001, .00001,
1e-6, 1e-7, 1e-8, 1e-9, 1e-10, 1e-11, 1e-12};
/**
* Round value off to a specified number of digists.
* @param value the value to round off
* @param digits the number of digits to keep, 0-12
*/
public static double round(double value, int digits) throws IllegalArgumentException
{
if (digits < 0 || digits >= mulDig.length)
throw new IllegalArgumentException("Only 0 to 12 digits allowed for round()");
return Math.round(value * mulDig[digits]) * divDig[digits];
} // round()
/**
* Returns an integer that has it's bits scrambled. If the same resulting value is again sent
* through this function the original value will be returned.
*/
public static int scramble(int value, String key)
{
byte[] shifts = new byte[32];
for (int ix = 0; ix < 32; ix++)
{
shifts[ix] = (byte)ix;
}
int hash = key.hashCode();
int v = value ^ hash;
Random rand = new Random((long)hash << 32 | hash);
for (int ix = 0; ix < 32; ix++)
{
byte temp = shifts[ix];
int r = (int)(rand.nextFloat() * 32);
shifts[ix] = shifts[r];
shifts[r] = temp;
}
//System.out.print("scramble [");
//for (int ix = 0; ix < 32; ix++)
//{
// if (ix > 0) System.out.print(", ");
// System.out.print(shifts[ix]);
//}
//System.out.println("]");
int result = 0;
for (int ix = 0; ix < 32; ix++)
{
int shift = shifts[ix];
result |= ((v >>> ix) & 1) << shift;
}
//System.out.println("value " + Integer.toHexString(value) + ", hash " + Integer.toHexString(value) + ", result " + Integer.toHexString(result));
if (DEBUG_MODE) ThreadState.logln("scramble(" + value + ", " + key + ") -> " + result);
return result;
} // scramble()
/**
* Sets the value of the named member of the object to value. If the object is a DspObject
* set() is called. Otherwise, it uses reflection to look up and set the field.
*/
public static Object setMember(Object obj, String member, Object value) throws DspException
{
try {
((DspObject)obj).set(member, value);
} catch (ClassCastException e) {
Class<?> c = obj.getClass();
try {
Field f = c.getField(member);
// if (Modifier.isPublic(f.getModifiers())
// {
f.set(obj, value);
// }
} catch (NoSuchFieldException e1) {
throw new DspException("Could not find field " + member, e1);
} catch (IllegalAccessException e1) {
throw new DspException("Could not access field " + member, e1);
}
}
return value;
} // setMember()
/**
* Set the prop object. Used internally to set up the initial prop object.
*/
public void setProp(DspProp value)
{
prop = value;
} // setProp()
/**
* Return the sign of the argument: -1 negative, 0 for 0, or 1 for positive.
*/
public static int sgn(int arg)
{
if (arg < 0) return -1;
else
if (arg > 0) return 1;
else return 0;
} // sgn()
/**
* Convert characters not allowed in HTML to allowable characters. Example:
* < to &lt;. This is the opposite of fromHtml().
* @see fromHtml(String)
*/
public static String showHtml(String text)
{
if (text == null) return text;
int end = text.length();
StringBuffer buf = new StringBuffer(end * 5 / 4);
// loop:
for (int ix = 0; ix < end; ix++)
{
char c = text.charAt(ix);
String app = null;
switch (c)
{
case '<':
app = "<";
break;
case '>':
app = ">";
break;
case '&':
app = "&";
break;
case '"':
app = """;
break;
}
if (app != null) buf.append(app);
else if (c > 0) buf.append(c);
}
return buf.toString();
} // showHtml()
/**
* Format boolean for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(boolean value)
{
return value ? "1" : "0";
} // sql(boolean)
/**
* Format Boolean for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(Boolean value)
{
if (value == null) return NULL;
return value.booleanValue() ? "1" : "0";
} // sql(Boolean)
/**
* Format value for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(byte value)
{
return Byte.toString(value);
} // sql(byte)
/**
* Format char for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(char value)
{
return quote(String.valueOf(value));
} // sql(char)
/**
* Format Character for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(Character value)
{
if (value == null) return NULL;
return quote(String.valueOf(value));
} // sql(Character)
/**
* Format a list of objects as an paren enclosed comma delimited list.
*/
public static String sql(Collection<Object> value) {
Iterator<Object> it = value.iterator();
StringBuffer buf = new StringBuffer("(");
while (it.hasNext()) {
if (buf.length() > 1) buf.append(", ");
buf.append(sql(it.next()));
}
buf.append(')');
return buf.toString();
} // sql(Collection)
/**
* Format Date for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(Date value)
{
return dateSql(value);
} // sql(Date)
/**
* Format Date for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(java.util.Date value)
{
if (value == null) return NULL;
return instantSql(new Timestamp(value.getTime()));
} // sql(java.util.Date)
/**
* Format value for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(double value)
{
return Double.toString(value);
} // sql(double)
/**
* Format value for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(float value)
{
return Float.toString(value);
} // sql(float)
/**
* Format value for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(int value)
{
return Integer.toString(value);
} // sql(int)
/**
* Format Number for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(Number value)
{
return value == null ? NULL : value.toString();
} // sql(Number)
/**
* Format value for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(long value)
{
return Long.toString(value);
} // sql(long)
/**
* Format value for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(short value)
{
return Short.toString(value);
} // sql(String)
/**
* Format String for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(String value)
{
return quote(value);
} // sql(String)
/**
* Format Time for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(Time value)
{
return timeSql(value);
} // sql(Time)
/**
* Format Timestamp for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
public static String sql(Timestamp value)
{
return instantSql(value);
} // sql(Timestamp)
/**
* Format Object for use in SQL. This function converts the data to a String suitable for use in an SQL statement.
*/
@SuppressWarnings("unchecked")
public static String sql(Object value)
{
if (value == null) return NULL;
try {
return sql((Number) value);
} catch (ClassCastException e) {
try {
java.util.Date date = (java.util.Date) value;
try {
return sql((Time) date);
} catch (ClassCastException e1) {
try {
return sql((Date) date);
} catch (ClassCastException e2) {
try {
return sql((Timestamp) date);
} catch (ClassCastException e3) {
return sql(date);
}
}
}
} catch (ClassCastException e7) {
try {
return sql((Boolean) value);
} catch (ClassCastException e4) {
try {
return sql((Character) value);
} catch (ClassCastException e5) {
try {
return sql((Collection<Object>) value);
} catch (ClassCastException e6) {
try {
return sql((Object[]) value);
} catch (ClassCastException e8) {
return sql(value.toString());
}
}
}
}
}
}
} // sql()
/**
* Format an array of numbers as an paren enclosed comma delimited list.
*/
/* public static String sql(Number[] value) {
StringBuffer buf = new StringBuffer("(");
for (int ix = 0, ixz = value.length; ix < ixz; ix++) {
if (buf.length() > 1) buf.append(", ");
buf.append(sql(value[ix]));
}
buf.append(')');
return buf.toString();
} // sql(Number[])
*/
/**
* Format an array of objects as an paren enclosed comma delimited list.
*/
public static String sql(Object[] value) {
StringBuffer buf = new StringBuffer("(");
for (int ix = 0, ixz = value.length; ix < ixz; ix++) {
if (buf.length() > 1) buf.append(", ");
buf.append(sql(value[ix]));
}
buf.append(')');
return buf.toString();
} // sql(Object[])
/**
* Format an array of strings as an paren enclosed comma delimited list.
*/
/* public static String sql(String[] value) {
StringBuffer buf = new StringBuffer("(");
for (int ix = 0, ixz = value.length; ix < ixz; ix++) {
if (buf.length() > 1) buf.append(", ");
buf.append(sql(value[ix]));
}
buf.append(')');
return buf.toString();
} // sql(String[])
*/
/**
* Convert object to a Boolean and format it suitable for use in an SQL statement.
*/
public static String sqlBoolean(boolean arg)
{
return sql(arg);
} // sqlBoolean()
/**
* Convert value to char and format it suitable for use in an SQL statement.
*/
public static String sqlChar(char arg)
{
return sql(arg);
} // sqlChar()
/**
* Convert Object to Character and format it suitable for use in an SQL statement.
*/
public static String sqlCharacter(Object arg)
{
return sql(_Character(arg));
} // sqlCharacter()
/**
* Convert object to a Date and format it suitable for use in an SQL statement.
*/
public static String sqlDate(Date arg)
{
return sql(arg);
} // sqlDate()
/**
* Convert object to an Double and format it suitable for use in an SQL statement.
*/
public static String sqlDouble(Object arg)
{
return sql(_Double(arg));
} // sqlDouble()
/**
* Convert object to an Float and format it suitable for use in an SQL statement.
*/
public static String sqlFloat(Object arg)
{
return sql(_Float(arg));
} // sqlFloat()
/**
* Convert object to a Timestamp and format it suitable for use in an SQL statement.
*/
public static String sqlInstant(Timestamp arg)
{
return sql(arg);
} // sqlInstant()
/**
* Convert object to an int and format it suitable for use in an SQL statement.
*/
public static String sqlInt(int arg)
{
return sql(arg);
} // sqlInt()
/**
* Convert object to an Integer and format it suitable for use in an SQL statement.
*/
public static String sqlInteger(Object arg)
{
return sql(_Integer(arg));
} // sqlInteger()
/**
* Convert object to a String and format it suitable for use in an SQL statement.
* Same as calling quote().
* @see quote(String)
*/
public static String sqlString(String arg)
{
return quote(arg);
} // sqlString()
/**
* Convert object to a Time and format it suitable for use in an SQL statement.
*/
public static String sqlTime(Time arg)
{
return sql(arg);
} // sqlTime()
/**
* Strip various types of text from the String.
* @deprecated
*/
public static String strip(String type, String data) throws IllegalArgumentException
{
String result;
if (data == null) result = null;
if (HTML.equalsIgnoreCase(type)) result = stripHtml(data);
else
if (LINKS.equalsIgnoreCase(type)) result = stripLinks(data);
else
if (DOMAIN.equalsIgnoreCase(type)) result = stripDomain(data);
else
if (SPACE.equalsIgnoreCase(type)) result = stripSpace(data);
else throw new IllegalArgumentException("strip(" + type + ") invalid parameter");
if (DEBUG_MODE) ThreadState.logln("strip(" + type + ", " + data + ") -> " + result);
return result;
} // strip()
private static String stripContig(String text, int offset)
{
if (DEBUG_MODE) ThreadState.logln("stripContig(" + text + ", " + offset + ')');
int start = offset;
String before = "#ERROR#";
for (; start > 0; start--)
{
if (text.charAt(start) <= ' ')
{
before = text.substring(0, ++start) + before;
break;
}
}
int end = text.length();
for (; offset < end; offset++)
{
char c = text.charAt(offset);
if (c <= ' ' || c == ';' || c == '<') return before + text.substring(offset);
}
return before;
} // stripContig()
/**
* Strips out all but the domain name from the URL string.
*/
public static String stripDomain(String text)
{
String result;
if (text == null || text.length() < 3) result = text;
else
{
int start = text.indexOf("//");
int end = text.indexOf("/", start >= 0 ? start : 0);
if (start >= 0 && end >= 0) result = text.substring(start + 2, end);
else
if (start >= 0) result = text.substring(start + 2);
else
if (end > 0) result = text.substring(0, end);
else result = text;
}
if (DEBUG_MODE) ThreadState.logln("stripDomain(" + text + ") -> " + result);
return result;
} // stripDomain()
/**
* Strips out all HTML tags from the String.
*/
public static String stripHtml(String text)
{
String result;
if (text == null || text.length() < 3) result = text;
else
{
boolean inHtml = false, space = false;
int iz = text.length();
StringBuffer buf = new StringBuffer(iz);
for (int ix = 0; ix < iz; ix++)
{
char c = text.charAt(ix);
if (inHtml)
{
if (c == '>') inHtml = false;
continue;
}
else
if (space)
{
if (c > ' ') space = false;
else continue;
}
if (c == '<')
{
inHtml = true;
}
else
if (c <= ' ')
{
space = true;
buf.append(' ');
}
else buf.append(c);
}
result = buf.toString();
}
if (DEBUG_MODE) ThreadState.logln("stripHtml(" + text + ") -> " + result);
return result;
} // stripHtml()
/**
* String specified letters from the text String.
*/
private static String stripLetters(String text, String letters)
{
int len = 0;
if (text == null || (len = text.length()) == 0) return text;
StringBuffer buf = new StringBuffer(len);
for (int ix = 0; ix < len; ix++)
{
char c = text.charAt(ix);
if (letters.indexOf(c) < 0) buf.append(c);
}
return buf.toString();
} // stripLetters()
/**
* Strips out all anchor tags and references to an internet server.
*/
public static String stripLinks(String text)
{
String result;
if (text == null || text.length() < 4) result = text;
else
{
for (int ix = 0, end = types.length; ix < end; ix++)
{
// if (DEBUG_MODE) BZVar.logln("ix " + ix);
String type = types[ix];
for (int iy = 0; iy < 2; iy++) // 0 = lower case, 1 == upper case
{
// if (DEBUG_MODE) BZVar.logln("iy " + iy);
int index = 0;
for (;;)
{
index = text.indexOf(type, index);
if (index < 0) break;
// if (DEBUG_MODE) BZVar.logln("index " + index);
char c = type.charAt(0);
if (c == '<')
{
int iend = index + type.length();
if (text.length() > iend)
{
c = text.charAt(iend);
if (c < '0'
|| (c > '9' && c < 'A')
|| (c > 'Z' && c < 'a')
|| c > 'z')
{
text = stripTag(text, index);
}
}
else index++;
}
else text = stripContig(text, index);
}
type = type.toUpperCase();
}
}
result = text;
}
if (DEBUG_MODE) ThreadState.logln("stripLinks(" + text + ") -> " + result);
return result;
} // stripLinks()
/**
* Strips dollar sign and percent symbols from the String.
*/
public static String stripNonNumerics(String text)
{
String neg = (text != null && text.startsWith("-")) ? "-" : "";
return neg + stripLetters(text.trim(), "$%,-() ");
} // stripNonNumerics()
/**
* Strips all whitespace from the string.
*/
public static String stripSpace(String text)
{
String result;
int ixz;
if (text == null || (ixz = text.length()) == 0) result = text;
else
{
StringBuffer buf = new StringBuffer(ixz);
for (int ix = 0; ix < ixz; ix++)
{
char c = text.charAt(ix);
if (c > ' ') buf.append(c);
}
result = buf.toString();
}
if (DEBUG_MODE) ThreadState.logln("stripSpace(" + text + ") -> " + result);
return result;
} // stripSpace()
private static String stripTag(String text, int offset)
{
if (DEBUG_MODE) ThreadState.logln("stripTag(" + text + ", " + offset + ')');
String before = text.substring(0, offset) + ' ';
@SuppressWarnings("unused")
int start = offset++;
int end = text.length();
for (; offset < end; offset++)
{
if (text.charAt(offset) == '>') return before + text.substring(++offset);
}
return before;
} // stripTag()
/**
* Integer Subtraction. Each argument is subtracted from the first. If no arguments
* are submitted then the result is 0.
* Any null arguments are ignored.
*/
public static int sub(Object[] args)
{
if (args == null || args.length == 0) return 0;
int psize = args.length;
if (DEBUG_MODE) ThreadState.logln("sub(" + psize + " args)");
int result = 0;
try {
result = _int(args[0]);
} catch (NullPointerException e) {
}
for (int ix = 1, end = psize; ix < end; ix++)
{
try {
result -= _int(args[ix]);
} catch (NullPointerException e) {
}
}
return result;
} // sub()
/**
* Format Time in various ways. This multipurpose function can convert a Time object
* to a String in several formats, or extract parts of the date. This function only
* accepts one or two arg elements. If two, the first is the requested function
* to perform, and the second is converted to java.sql.Time. If one, the request is assumed
* to be "short". The following are the types of functions performed based on the request:
* <table><tr><td>Request (arg1)</td><td>Returned</td><td>Type</td><td>Example</td></tr>
* <tr><td>short</td><td>Short Time</td><td>String</td><td>12:13 PM</td></tr>
* <tr><td>long</td><td>Long Time</td><td>String</td><td>12:13:52.239 PM</td></tr>
* <tr><td>sql</td><td>SQL Time</td><td>String</td><td>{t '12:13:52.239 PM'}</td></tr></table>
*/
public static Object time(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 1 || psize == 2))
throw new IllegalArgumentException("time() can only accept 1 or 2 arguments");
String type = null;
Time date;
if (psize == 2)
{
type = _String(args[0]);
date = _Time(args[1]);
}
else date = _Time(args[0]);
Object result;
if (psize == 1
|| SHORT.equalsIgnoreCase(type)) result = timeShort(date);
else
if (LONG.equalsIgnoreCase(type)) result = timeLong(date);
else
if (SQL.equalsIgnoreCase(type)) result = timeSql(date);
else
if (MIL.equalsIgnoreCase(type)) result = timeMil(date);
else throw new IllegalArgumentException("time(" + type + ", " + date + ") error, unknown time function");
if (DEBUG_MODE) ThreadState.logln("time(" + args + ") -> " + result);
return result;
} // time()
/**
* Add units to Time. Adds hours, minutes, seconds, milliseconds to Time.
* It accepts 2 or three members of args. The first is convert to Time. The second
* is the value to be added. The third, if present, is the units String: hours,
* mins, secs, msecs. If no third member is present, the units are assumed to be seconds.
*/
public static Time timeAdd(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("timeAdd() can only accept 2 or 3 arguments");
Time date = _Time(args[0]);
int value = _int(args[1]);
String str = "seconds";
if (psize == 3)
{
str = _String(args[2]);
}
int type = 's';
if (str.length() > 0) type = Character.toLowerCase(str.charAt(0));
if (str.length() > 1 && type == 'm' && Character.toLowerCase(str.charAt(1)) == 's')
{
type = 'i';
}
Calendar c = Calendar.getInstance();
c.setTime(date);
switch (type)
{
case 'i':
c.add(Calendar.MILLISECOND, value);
break;
case 's':
c.add(Calendar.SECOND, value);
break;
case 'm':
c.add(Calendar.MINUTE, value);
break;
case 'h':
c.add(Calendar.HOUR, value);
break;
default:
throw new IllegalArgumentException("Unknown value type: " + str);
}
Time result = new Time(c.getTime().getTime());
if (DEBUG_MODE) ThreadState.logln("timeAdd(" + args + ") -> " + result);
return result;
} // timeAdd()
/**
* Retuns the difference between two Timestamps, as a String.
*/
public static String timeDiff(Timestamp time1, Timestamp time2)
{
return msecDiff(time1.getTime(), time2.getTime());
} // timeDiff()
/**
* Convert Time to long String. Returns a String with the time in long format.
*/
public static String timeLong(Time date)
{
String result;
if (date == null) result = null;
else result = timelong.format(date);
if (DEBUG_MODE) ThreadState.logln("timeLong(" + date + ") -> " + result);
return result;
} // timeLong()
/**
* Convert Time to a String. Returns a String with the time in military format.
*/
public static String timeMil(Time date)
{
if (DEBUG_MODE) ThreadState.logln("timeShort(" + date + ") -> " + date);
if (date == null) return null;
return date.toString();
} // timeMil()
/**
* Convert Time to a short String. Returns a String with the time in short format.
*/
public static String timeShort(Time date)
{
if (DEBUG_MODE) ThreadState.logln("timeShort(" + date + ") -> " + date);
if (date == null) return null;
return timeshort2.format(date);
} // timeShort()
/**
* Convert Time to SQL. Returns a String with the time encoded for use in an SQL statement.
*/
public static String timeSql(Time date)
{
String result;
if (date == null) result = NULL;
result = "{t '" + date + "'}";
if (DEBUG_MODE) ThreadState.logln("timeSql(" + date + " -> " + result);
return result;
} // timeSql()
/**
* Subtract units of time from Time. Subtracts hours, minutes, seconds, milliseconds from Time.
* It accepts 2 or three members of args. The first is convert to Time. The second
* is the value to be subtracted. The third, if present, is the units String: hours,
* mins, secs, msecs. If no third member is present, the units are assumed to be seconds.
*/
public static Time timeSub(Object[] args) throws IllegalArgumentException, NumberFormatException
{
int psize = args.length;
if (!(psize == 2 || psize == 3))
throw new IllegalArgumentException("timeSub() can only accept 2 or 3 arguments");
args[1] = new Integer(-_int(args[1]));
Time result = timeAdd(args);
if (DEBUG_MODE) ThreadState.logln("timeSub(" + args + ") -> " + result);
return result;
} // timeSub()
/**
* Return today's Date.
*/
public static Date today()
{
return new Date(System.currentTimeMillis());
} // today()
/**
* All possible chars for representing a number as a String
*/
private final static char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'A' , 'B' ,
'C' , 'D' , 'E' , 'F'
};
/**
* Convert arg to a hexadecimal. If two arguments are sent, the second specifies the number
* of digits desired.
*/
public static String toHex(Object[] args) throws IllegalArgumentException
{
int psize = args.length;
if (!(psize == 1))
throw new IllegalArgumentException("toHex() can only accept 1 or 2 arguments");
Object param = args[0];
if (param == null || (param instanceof String && ((String)param).trim().length() == 0)) return null;
int i = _int(param);
String result;
if (psize == 1) result = Integer.toHexString(i);
else
{
int dig = _int(args[1]);
char[] buf = new char[dig];
int charPos = dig;
int shift = 4;
int radix = 1 << shift;
int mask = radix - 1;
while (dig-- > 0) {
buf[--charPos] = digits[i & mask];
i >>>= shift;
}
result = new String(buf);
}
if (DEBUG_MODE) ThreadState.logln("toHex(" + args + ") -> " + result);
return result;
} // toHex()
/**
* Returns the value as a hexidecimal digit.
*/
private static char toHexDigit(int value)
{
value &= 0xf;
if (value <= 9) return (char)('0' + value);
return (char)('A' + value - 10);
} // toHexDigit()
/**
* Trims the whitespace from the beginning and end of the String.
*/
public static String trim(String arg)
{
String result;
if (arg == null) result = null;
else result = arg.trim();
if (DEBUG_MODE) ThreadState.logln("trim(" + arg + ") -> " + result);
return result;
} // trim()
/**
* Convert String to upper case. This function converts all characters of arg to upper case.
*/
public static String upperCase(String arg)
{
String result;
if (arg == null) result = null;
else result = _String(arg).toUpperCase();
if (DEBUG_MODE) ThreadState.logln("upperCase(" + arg + ") -> " + result);
return result;
} // upperCase()
/**
* Used by both url() and urlFull() to do their jobs, since the are so similar.
*/
private static String url(String value, boolean partial)
{
if (value == null) return null;
StringBuffer buf = new StringBuffer();
for (int ix = 0, end = value.length(); ix < end; ix++)
{
char c = value.charAt(ix);
// if (c <= ' ') buf.append('+');
// else
if ((c < '0' || (c > '9' && c < '@') || c > 'z')
&& !(c == '-' || c == '/' || c == ':' || c == '.')
&& (partial || !(c == '?' || c == '&' || c == '=' || c == '#')))
{
buf.append('%');
buf.append(toHexDigit(c >> 4));
buf.append(toHexDigit(c));
}
else buf.append(c);
}
return buf.toString();
} // url()
/**
* Format data for use in a URL String. This function formats arg as a String with
* characters that are not allowed in a URL converted to %hex. Use this when you
* need to put a field value into an HTML URL, on the right side of the ? character.
* @see urlFull(String)
*/
public static String url(String value)
{
String result = url(value, true);
if (DEBUG_MODE) ThreadState.logln("url(" + value + ") -> " + result);
return result;
} // url()
/**
* Format data for use as a URL String. This function formats arg as a String with
* characters that are not allowed in a full URL converted to %hex. Use this when you
* need to format a String to be the entire URL.
* @see url(String)
*/
public static String urlFull(String value)
{
String result = url(value, false);
if (DEBUG_MODE) ThreadState.logln("urlFull(" + value + ") -> " + result);
return result;
} // url()
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(boolean arg)
{
return arg;
} // _boolean(boolean)
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(double arg)
{
return arg != 0.0;
} // _boolean(double)
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(float arg)
{
return arg != 0.0f;
} // _boolean(float)
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(int arg)
{
return arg != 0;
} // _boolean(int)
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(long arg)
{
return arg != 0L;
} // _boolean(long)
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(String arg)
{
return arg != null && arg.length() > 0 && !arg.equalsIgnoreCase("false") && !arg.equalsIgnoreCase("0");
} // _boolean(String)
/**
* Convert to boolean. This function converts the data to a boolean type.
*/
public static boolean _boolean(Object obj)
{
return _Boolean(obj).booleanValue();
} // _boolean(Object)
/**
* Convert to Boolean. This function converts the data to a Boolean object.
*/
public static Boolean _Boolean(Object obj)
{
if (obj == null) return Boolean.FALSE;
try {
return (Boolean)obj;
} catch (Exception e1) {
try {
return ((Number)obj).doubleValue() != 0.0 ? Boolean.TRUE : Boolean.FALSE;
} catch (Exception e) { // ClassCastException
return new Boolean(_boolean(_String(obj)));
}
}
} // _Boolean()
/**
* Convert value to char.
*/
public static char _char(int val)
{
return (char)val;
} // _char()
/**
* Convert Object to char.
*/
public static char _char(Object obj) throws IllegalArgumentException
{
Character c = _Character(obj);
if (c == null) throw new IllegalArgumentException("Cannot convert " + obj + " to a char");
return c.charValue();
} // _char()
/**
* Convert Object to Character.
*/
public static Character _Character(Object obj)
{
try {
return (Character)obj;
} catch (ClassCastException e) {
String str = _String(obj);
if (str.length() == 0) return null;
return new Character(str.charAt(0));
}
} // _Character()
/**
* Convert to Date. This function converts the data to a Date object.
*/
@SuppressWarnings("deprecation")
public static Date _Date(Object obj) throws NumberFormatException
{
if (obj == null) return null;
try {
return (Date)obj;
} catch (Exception e) {
try {
return new Date(((java.util.Date)obj).getTime());
} catch (Exception e1) {
try {
int date = ((Number)obj).intValue();
return new Date(date / 10000, date / 100 % 100 - 1, date % 100);
} catch (Exception e2) {
String value = _String(obj).trim();
if (value.length() == 0) return null;
try {
return Date.valueOf(value);
} catch (Exception e3) {
try {
return new Date(dform.parse(value).getTime());
} catch (Exception e4) {
try {
return new Date(zonedate.parse(value).getTime());
} catch (Exception e5) {
throw new NumberFormatException("Cannot convert '" + obj + "' to a date");
}
}
}
}
}
}
} // _Date()
/**
* Convert to double. This function converts the data to a double type.
*/
public static double _double(boolean arg)
{
return arg ? 1.0 : 0.0;
} // _double(boolean)
/**
* Convert to double. This function converts the data to a double type.
*/
public static double _double(double arg)
{
return arg;
} // _double(double)
/**
* Convert to double. This function converts the data to a double type.
*/
public static double _double(int arg)
{
return (double)arg;
} // _double(int)
/**
* Convert to double. This function converts the data to a double type.
*/
public static double _double(long arg)
{
return (double)arg;
} // _double(long)
/**
* Convert to double. This function converts the data to a double type.
*/
public static double _double(String arg) throws NumberFormatException
{
return Double.parseDouble(stripNonNumerics(arg));
} // _double(String)
/**
* Convert to double. This function converts the data to a double type.
*/
public static double _double(Object obj) throws NumberFormatException
{
Double d = _Double(obj);
return d == null ? 0.0 : d.doubleValue();
} // _double(Object)
/**
* Convert to double. This function converts the data to a double type.
*/
public static Double _Double(Object obj) throws NumberFormatException
{
try {
return (Double)obj;
} catch (Exception e0) {
try {
return new Double(((Number)obj).doubleValue());
} catch (Exception e) {
try {
String s = stripNonNumerics(obj.toString());
if (s.length() == 0) return null;
return new Double(s);
} catch (Exception e3) {
throw new NumberFormatException("Cannot convert '" + obj + "' to a double");
}
}
}
} // _Double()
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(boolean arg)
{
return arg ? 1.0f : 0.0f;
} // _float(boolean)
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(double arg)
{
return (float)arg;
} // _float(double)
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(float arg)
{
return arg;
} // _float(float)
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(int arg)
{
return (float)arg;
} // _float(int)
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(long arg)
{
return (float)arg;
} // _float(long)
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(String arg) throws NumberFormatException
{
return Float.parseFloat(stripNonNumerics(arg));
} // _float(String)
/**
* Convert to float. This function converts the data to a floating point number.
*/
public static float _float(Object obj) throws NumberFormatException
{
Float f = _Float(obj);
return f == null ? 0f : f.floatValue();
} // _float()
/**
* Convert to Float. This function converts the data to a Float object.
*/
public static Float _Float(Object obj) throws NumberFormatException
{
try {
return (Float)obj;
} catch (Exception e0) {
try {
return new Float(((Number)obj).floatValue());
} catch (Exception e) {
try {
String s = stripNonNumerics(obj.toString());
if (s.length() == 0) return null;
return new Float(s);
} catch (Exception e3) {
throw new NumberFormatException("Cannot convert '" + obj + "' to a float");
}
}
}
} // _Float()
/**
* Convert Object to Timestamp.
*/
@SuppressWarnings("deprecation")
public static Timestamp _Instant(Object obj) throws NumberFormatException
{
if (obj == null) return null;
try {
return (Timestamp)obj;
} catch (Exception e) {
try {
return new Timestamp(((java.util.Date)obj).getTime());
} catch (Exception e1) {
try {
long time = ((Number)obj).longValue();
int msec = (int)(time % 10000);
time /= 10000;
int sec = (int)(time % 100);
time /= 100;
int min = (int)(time % 100);
time /= 100;
int hr = (int)(time % 100);
time /= 100;
int day = (int)(time % 100);
time /= 100;
int mon = (int)(time % 100);
int year = (int)(time / 100);
return new Timestamp(year, mon - 1, day, hr, min, sec, msec);
} catch (Exception e2) {
String value = _String(obj).trim();
if (value.length() == 0) return null;
try {
return Timestamp.valueOf(value);
} catch (Exception e3) {
try {
return new Timestamp(zoneinstant.parse(value).getTime());
} catch (Exception e4) {
try {
return new Timestamp(_Date(obj).getTime());
} catch (Exception e5) {
throw new NumberFormatException("Cannot convert '" + obj + "' to instant");
}
}
}
}
}
}
} // _Instant()
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(boolean arg)
{
return arg ? 1 : 0;
} // _int(boolean)
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(double arg)
{
return (int)arg;
} // _int(double)
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(float arg)
{
return (int)arg;
} // _int(float)
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(int arg)
{
return arg;
} // _int(int)
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(long arg)
{
return (int)arg;
} // _int(long)
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(String arg) throws NumberFormatException
{
return Integer.parseInt(stripNonNumerics(arg));
} // _int(String)
/**
* Convert to int. This function converts the data to a int type.
*/
public static int _int(Object obj) throws NumberFormatException
{
Integer i = _Integer(obj);
return i == null ? 0 : i.intValue();
} // _int()
/**
* Convert to Integer. This function converts the data to an Integer object.
*/
public static Integer _Integer(Object obj) throws NumberFormatException
{
try {
return (Integer)obj;
} catch (Exception e0) {
try {
return new Integer(((Number)obj).intValue());
} catch (Exception e) {
try {
cal.setTime((Date)obj);
return new Integer(cal.get(Calendar.YEAR) * 10000 + (cal.get(Calendar.MONTH) + 1) * 100 + cal.get(Calendar.DAY_OF_MONTH));
} catch (Exception e1) {
try {
cal.setTime((Time)obj);
return new Integer(cal.get(Calendar.HOUR_OF_DAY) * 10000 + cal.get(Calendar.MINUTE) * 100 + cal.get(Calendar.SECOND));
} catch (Exception e2) {
try {
Boolean b = (Boolean)obj;
return new Integer(b.booleanValue() ? 1 : 0);
} catch (Exception e3) {
try {
String s = stripNonNumerics(obj.toString());
if (s.length() == 0) return null;
return new Integer(s);
} catch (Exception e4) {
try {
return new Integer(_Double(obj).intValue());
} catch (Exception e5) {
throw new NumberFormatException("Cannot convert '" + obj + "' to an int");
}
}
}
}
}
}
}
} // _Integer()
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(boolean arg)
{
return arg ? 1l : 0l;
} // _long(boolean)
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(double arg)
{
return (long)arg;
} // _long(double)
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(float arg)
{
return (long)arg;
} // _long(float)
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(int arg)
{
return arg;
} // _long(int)
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(long arg)
{
return arg;
} // _long(long)
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(String arg) throws NumberFormatException
{
return Long.parseLong(stripNonNumerics(arg));
} // _long(String)
/**
* Convert to long. This function converts the data to a long type.
*/
public static long _long(Object obj) throws NumberFormatException
{
Long i = _Long(obj);
return i == null ? 0 : i.longValue();
} // _long()
/**
* Convert to Long. This function converts the data to an Integer object.
*/
public static Long _Long(Object obj) throws NumberFormatException
{
try {
return (Long)obj;
} catch (Exception e0) {
try {
return new Long(((Number)obj).longValue());
} catch (Exception e1) {
try {
cal.setTime((java.util.Date)obj);
return new Long(cal.get(Calendar.YEAR) * 10000000000l
+ (cal.get(Calendar.MONTH) + 1) * 100000000
+ cal.get(Calendar.DAY_OF_MONTH) * 1000000
+ cal.get(Calendar.HOUR_OF_DAY) * 10000
+ cal.get(Calendar.MINUTE) * 100
+ cal.get(Calendar.SECOND));
} catch (Exception e2) {
try {
Boolean b = (Boolean)obj;
return new Long(b.booleanValue() ? 1l : 0l);
} catch (Exception e3) {
try {
String s = stripNonNumerics(obj.toString());
if (s.length() == 0) return null;
return new Long(s);
} catch (Exception e4) {
try {
return new Long(_Double(obj).longValue());
} catch (Exception e5) {
throw new NumberFormatException("Cannot convert '" + obj + "' to an long");
}
}
}
}
}
}
} // _Long()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(boolean val)
{
return val ? Boolean.TRUE : Boolean.FALSE;
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(char val)
{
return new Character(val);
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(short val)
{
return new Short(val);
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(int val)
{
return new Integer(val);
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(long val)
{
return new Long(val);
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(float val)
{
return new Float(val);
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Double _Object(double val)
{
return new Double(val);
} // _Object()
/**
* Convert to Object. This function converts the data to an Object object.
*/
protected static Object _Object(Object val)
{
return val;
} // _Object()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(boolean val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(char val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(short val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(int val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(long val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(float val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(double val)
{
return String.valueOf(val);
} // _String()
/**
* Convert to String. This function converts the data to a String object.
*/
public static String _String(Object val)
{
if (val == null) return EMPTY;
return val.toString();
} // _String()
/**
* Convert to Time. This function converts the data to a Time object.
*/
@SuppressWarnings("deprecation")
public static Time _Time(Object obj) throws NumberFormatException
{
if (obj == null) return null;
try {
return (Time)obj;
} catch (Exception e) {
try {
return new Time(((java.util.Date)obj).getTime());
} catch (Exception e1) {
try {
int time = ((Number)obj).intValue();
return new Time(time / 10000, time / 100 % 100, time % 100);
} catch (Exception e2) {
String value = _String(obj).trim();
if (value.length() == 0) return null;
try {
return new Time(timeshort.parse(value).getTime());
} catch (Exception e3) {
try {
return new Time(timeshort2.parse(value).getTime());
} catch (Exception e4) {
try {
return new Time(timeshort3.parse(value).getTime());
} catch (Exception e5) {
try {
return new Time(timeshort4.parse(value).getTime());
} catch (Exception e6) {
try {
return new Time(timeshort5.parse(value).getTime());
} catch (Exception e7) {
try {
return new Time(timeshort6.parse(value).getTime());
} catch (Exception e8) {
try {
return new Time(timelong.parse(value).getTime());
} catch (Exception e9) {
try {
return Time.valueOf(value);
} catch (Exception e10) {
try {
return new Time(zonetime.parse(value).getTime());
} catch (Exception e11) {
throw new NumberFormatException("Cannot convert '" + obj + "' to time");
}
}
}
}
}
}
}
}
}
}
}
}
} // _Time()
/**
* Main DSP page function. This function is created by the DSP engine for each page
* and is called by the DSP servlet for each request to the web page.
*/
public abstract void _jspService(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException;
} // DspPage
|
Replace StringBuffer with StringBuilder
|
src/main/java/com/dsp/DspPage.java
|
Replace StringBuffer with StringBuilder
|
|
Java
|
apache-2.0
|
b1b5f1eebdf5dd66b4c3f9ae6f9837a0a03898ce
| 0
|
apache/velocity-tools,apache/velocity-tools
|
package org.apache.velocity.tools.generic;
/*
* 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.
*/
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.velocity.tools.ConversionUtils;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.config.DefaultKey;
import org.apache.velocity.tools.config.InvalidScope;
import org.apache.velocity.tools.config.SkipSetters;
/**
* <p>Utility class for easy parsing of String values held in a Map.</p>
*
* <p>This comes in very handy when parsing parameters.</p>
*
* <p>When subkeys are allowed, getValue("foo") will also search for all keys
* of the form "foo.bar" and return a ValueParser of the type "bar" -> value for all found values.</p>
*
* TODO: someone doing java configuration ought to be able to put a source Map
* in the tool properties, allowing this to be used like other tools
*
* @author Nathan Bubna
* @version $Revision$ $Date$
* @since VelocityTools 1.2
*/
@DefaultKey("parser")
@InvalidScope(Scope.SESSION) /* session scope forbidden: Object may not be Serializable */
@SkipSetters
public class ValueParser extends FormatConfig implements Map<String,Object>
{
public static final String STRINGS_DELIMITER_FORMAT_KEY = "stringsDelimiter";
public static final String DEFAULT_STRINGS_DELIMITER = ",";
private String stringsDelimiter = DEFAULT_STRINGS_DELIMITER;
private Map<String,Object> source = null;
private boolean allowSubkeys = true;
/* when using subkeys, cache at least the presence of any subkey,
so that the rendering of templates not using subkeys will only
look once for subkeys
*/
private Boolean hasSubkeys = null;
/* whether the wrapped map should be read-only or not */
private boolean readOnly = true;
/**
* The key used for specifying whether to support subkeys
*/
public static final String ALLOWSUBKEYS_KEY = "allowSubkeys";
/**
* The key used for specifying whether to be read-only
*/
public static final String READONLY_KEY = "readOnly";
public ValueParser()
{
}
public ValueParser(Map<String,Object> source)
{
setSource(source);
}
protected void setSource(Map<String,Object> source)
{
this.source = source;
}
protected Map<String,Object> getSource(boolean create)
{
// If this method has not been overrided, make sure source is not null
if (source == null && create)
{
source = new HashMap<String, Object>();
}
return this.source;
}
protected Map<String,Object> getSource()
{
return getSource(true);
}
/**
* Are subkeys allowed ?
* @return yes/no
*/
protected boolean getAllowSubkeys()
{
return allowSubkeys;
}
/**
* allow or disallow subkeys
* @param allow
*/
protected void setAllowSubkeys(boolean allow)
{
allowSubkeys = allow;
}
/**
* Is the Map read-only?
* @return yes/no
*/
protected boolean getReadOnly()
{
return readOnly;
}
/**
* Set or unset read-only behaviour
* @param ro
*/
protected void setReadOnly(boolean ro)
{
readOnly = ro;
}
/**
* Sets the delimiter used for separating values in a single String value.
* The default string delimiter is a comma.
*
* @see #getValues(String)
*/
protected final void setStringsDelimiter(String stringsDelimiter)
{
this.stringsDelimiter = stringsDelimiter;
}
/**
* Does the actual configuration. This is protected, so
* subclasses may share the same ValueParser and call configure
* at any time, while preventing templates from doing so when
* configure(Map) is locked.
*/
@Override
protected void configure(ValueParser values)
{
super.configure(values);
String delimiter = values.getString(STRINGS_DELIMITER_FORMAT_KEY);
if (delimiter != null)
{
setStringsDelimiter(delimiter);
}
Boolean allow = values.getBoolean(ALLOWSUBKEYS_KEY);
if(allow != null)
{
setAllowSubkeys(allow);
}
Boolean ro = values.getBoolean(READONLY_KEY);
if(ro != null)
{
setReadOnly(ro);
}
}
// ----------------- public parsing methods --------------------------
/**
* Convenience method for checking whether a certain parameter exists.
*
* @param key the parameter's key
* @return <code>true</code> if a parameter exists for the specified
* key; otherwise, returns <code>false</code>.
*/
public boolean exists(String key)
{
return (getValue(key) != null);
}
/**
* Convenience method for use in Velocity templates.
* This allows for easy "dot" access to parameters.
*
* e.g. $params.foo instead of $params.getString('foo')
*
* @param key the parameter's key
* @return parameter matching the specified key or
* <code>null</code> if there is no matching
* parameter
*/
public Object get(String key)
{
Object value = getValue(key);
if (value == null && getSource() != null && getAllowSubkeys())
{
value = getSubkey(key);
}
return value;
}
/**
* Returns the value mapped to the specified key
* in the {@link Map} returned by {@link #getSource()}. If there is
* no source, then this will always return {@code null}.
*/
public Object getValue(String key)
{
if (getSource() == null)
{
return null;
}
return getSource().get(key);
}
/**
* @param key the desired parameter's key
* @param alternate The alternate value
* @return parameter matching the specified key or the
* specified alternate Object if there is no matching
* parameter
*/
public Object getValue(String key, Object alternate)
{
Object value = getValue(key);
if (value == null)
{
return alternate;
}
return value;
}
protected String[] parseStringList(String value)
{
String[] values;
if (stringsDelimiter.length() == 0 || value.indexOf(stringsDelimiter) < 0)
{
values = new String[] { value };
}
else
{
values = value.split(stringsDelimiter);
}
return values;
}
/**
* <p>Returns an array of values. If the internal value is a string, it is split using the configured delimitor
* (',' by default).</p>
* <p>If the internal value is not an array or is a string without any delimiter, a singletin array is returned.</p>
* @param key the desired parameter's key
* @return array of values, or null of the key has not been found.
* specified alternate Object if there is no matching
* parameter
*/
public Object[] getValues(String key)
{
Object value = getValue(key);
if (value == null)
{
return null;
}
if (value instanceof String)
{
return parseStringList((String)value);
}
if (value instanceof Object[])
{
return (Object[])value;
}
return new Object[] { value };
}
/**
* @param key the parameter's key
* @return parameter matching the specified key or
* <code>null</code> if there is no matching
* parameter
*/
public String getString(String key)
{
return ConversionUtils.toString(getValue(key));
}
/**
* @param key the desired parameter's key
* @param alternate The alternate value
* @return parameter matching the specified key or the
* specified alternate String if there is no matching
* parameter
*/
public String getString(String key, String alternate)
{
String s = getString(key);
return (s != null) ? s : alternate;
}
/**
* @param key the desired parameter's key
* @return a {@link Boolean} object for the specified key or
* <code>null</code> if no matching parameter is found
*/
public Boolean getBoolean(String key)
{
return ConversionUtils.toBoolean(getValue(key));
}
/**
* @param key the desired parameter's key
* @param alternate The alternate boolean value
* @return boolean value for the specified key or the
* alternate boolean is no value is found
*/
public boolean getBoolean(String key, boolean alternate)
{
Boolean bool = getBoolean(key);
return (bool != null) ? bool.booleanValue() : alternate;
}
/**
* @param key the desired parameter's key
* @param alternate the alternate {@link Boolean}
* @return a {@link Boolean} for the specified key or the specified
* alternate if no matching parameter is found
*/
public Boolean getBoolean(String key, Boolean alternate)
{
Boolean bool = getBoolean(key);
return (bool != null) ? bool : alternate;
}
/**
* @param key the desired parameter's key
* @return a {@link Integer} for the specified key or
* <code>null</code> if no matching parameter is found
*/
public Integer getInteger(String key)
{
Object value = getValue(key);
if (value == null)
{
return null;
}
Number number = ConversionUtils.toNumber(value, getFormat(), getLocale());
return number == null ? null : number.intValue();
}
/**
* @param key the desired parameter's key
* @param alternate The alternate Integer
* @return an Integer for the specified key or the specified
* alternate if no matching parameter is found
*/
public Integer getInteger(String key, Integer alternate)
{
Integer num = getInteger(key);
if (num == null)
{
return alternate;
}
return num;
}
/**
* @param key the desired parameter's key
* @return a {@link Double} for the specified key or
* <code>null</code> if no matching parameter is found
*/
public Double getDouble(String key)
{
Object value = getValue(key);
if (value == null)
{
return null;
}
Number number = ConversionUtils.toNumber(value, getFormat(), getLocale());
return number == null ? null : number.doubleValue();
}
/**
* @param key the desired parameter's key
* @param alternate The alternate Double
* @return an Double for the specified key or the specified
* alternate if no matching parameter is found
*/
public Double getDouble(String key, Double alternate)
{
Double num = getDouble(key);
if (num == null)
{
return alternate;
}
return num;
}
/**
* @param key the desired parameter's key
* @return a {@link Number} for the specified key or
* <code>null</code> if no matching parameter is found
*/
public Number getNumber(String key)
{
return ConversionUtils.toNumber(getValue(key), getFormat(), getLocale());
}
/**
* @param key the desired parameter's key
* @return a {@link Locale} for the specified key or
* <code>null</code> if no matching parameter is found
*/
public Locale getLocale(String key)
{
return toLocale(getValue(key));
}
/**
* @param key the desired parameter's key
* @param alternate The alternate Number
* @return a Number for the specified key or the specified
* alternate if no matching parameter is found
*/
public Number getNumber(String key, Number alternate)
{
Number n = getNumber(key);
return (n != null) ? n : alternate;
}
/**
* @param key the desired parameter's key
* @param alternate The alternate int value
* @return the int value for the specified key or the specified
* alternate value if no matching parameter is found
*/
public int getInt(String key, int alternate)
{
Number n = getNumber(key);
return (n != null) ? n.intValue() : alternate;
}
/**
* @param key the desired parameter's key
* @param alternate The alternate double value
* @return the double value for the specified key or the specified
* alternate value if no matching parameter is found
*/
public double getDouble(String key, double alternate)
{
Number n = getNumber(key);
return (n != null) ? n.doubleValue() : alternate;
}
/**
* @param key the desired parameter's key
* @param alternate The alternate Locale
* @return a Locale for the specified key or the specified
* alternate if no matching parameter is found
*/
public Locale getLocale(String key, Locale alternate)
{
Locale l = getLocale(key);
return (l != null) ? l : alternate;
}
/**
* @param key the key for the desired parameter
* @return an array of String objects containing all of the values
* associated with the given key, or <code>null</code>
* if the no values are associated with the given key
*/
public String[] getStrings(String key)
{
Object[] array = getValues(key);
if (array == null || String.class.isAssignableFrom(array.getClass().getComponentType()))
{
return (String[])array;
}
String[] ret = new String[array.length];
for (int i = 0; i < array.length; ++i)
{
ret[i] = ConversionUtils.toString(array[i]);
}
return ret;
}
/**
* @param key the key for the desired parameter
* @return an array of Boolean objects associated with the given key.
*/
public Boolean[] getBooleans(String key)
{
Object[] array = getValues(key);
if (array == null || Boolean.class.isAssignableFrom(array.getClass().getComponentType()))
{
return (Boolean[])array;
}
Boolean[] ret = new Boolean[array.length];
for (int i = 0; i < array.length; ++i)
{
ret[i] = ConversionUtils.toBoolean(array[i]);
}
return ret;
}
/**
* @param key the key for the desired parameter
* @return an array of Number objects associated with the given key,
* or <code>null</code> if Numbers are not associated with it.
*/
public Number[] getNumbers(String key)
{
Object[] array = getValues(key);
if (array == null || Number.class.isAssignableFrom(array.getClass().getComponentType()))
{
return (Number[])array;
}
Number[] ret = new Number[array.length];
for (int i = 0; i < array.length; ++i)
{
ret[i] = ConversionUtils.toNumber(array[i], getFormat(), getLocale());
}
return ret;
}
/**
* @param key the key for the desired parameter
* @return an array of int values associated with the given key,
* or <code>null</code> if numbers are not associated with it.
*/
public int[] getInts(String key)
{
Object[] array = getValues(key);
if (array == null)
{
return null;
}
int[] ret = new int[array.length];
for (int i = 0; i < array.length; ++i)
{
ret[i] = ConversionUtils.toNumber(array[i], getFormat(), getLocale()).intValue();
}
return ret;
}
/**
* @param key the key for the desired parameter
* @return an array of double values associated with the given key,
* or <code>null</code> if numbers are not associated with it.
*/
public double[] getDoubles(String key)
{
Object[] array = getValues(key);
if (array == null)
{
return null;
}
double[] ret = new double[array.length];
for (int i = 0; i < array.length; ++i)
{
ret[i] = ConversionUtils.toNumber(array[i], getFormat(), getLocale()).doubleValue();
}
return ret;
}
/**
* @param key the key for the desired parameter
* @return an array of Locale objects associated with the given key,
* or <code>null</code> if Locales are not associated with it.
*/
public Locale[] getLocales(String key)
{
Object[] array = getValues(key);
if (array == null || Locale.class.isAssignableFrom(array.getClass().getComponentType()))
{
return (Locale[])array;
}
Locale[] ret = new Locale[array.length];
for (int i = 0; i < array.length; ++i)
{
ret[i] = ConversionUtils.toLocale(String.valueOf(array[i]));
}
return ret;
}
/**
* Determines whether there are subkeys available in the source map.
*/
public boolean hasSubkeys()
{
if (getSource() == null || !getAllowSubkeys())
{
return false;
}
if (hasSubkeys == null)
{
for (String key : getSource().keySet())
{
int dot = key.indexOf('.');
if (dot > 0 && dot < key.length())
{
hasSubkeys = Boolean.TRUE;
break;
}
}
if (hasSubkeys == null)
{
hasSubkeys = Boolean.FALSE;
}
}
return hasSubkeys;
}
/**
* returns the set of all possible first-level subkeys, including complete keys without dots (or returns keySet() if allowSubKeys is false)
*/
public Set<String> getSubkeys()
{
Set<String> keys = keySet();
if (getSource() == null || !getAllowSubkeys())
{
return keys;
}
else
{
Set<String> result = new TreeSet<String>();
for (String key: keys)
{
int dot = key.indexOf('.');
if (dot > 0 && dot < key.length())
{
result.add(key.substring(0, dot));
}
}
return result;
}
}
/**
* subkey getter that returns a map <subkey#2> -> value
* for every "subkey.subkey2" found entry
*
* @param subkey subkey to search for
* @return the map of found values
*/
protected ValueParser getSubkey(String subkey)
{
if (!hasSubkeys() || subkey == null || subkey.length() == 0)
{
return null;
}
Map<String,Object> values = null;
subkey = subkey.concat(".");
for (Map.Entry<String,Object> entry : getSource().entrySet())
{
if (entry.getKey().startsWith(subkey) &&
entry.getKey().length() > subkey.length())
{
if (values == null)
{
values = new HashMap<String, Object>();
}
values.put(entry.getKey().substring(subkey.length()),entry.getValue());
}
}
if (values == null)
{
return null;
}
else
{
ValueParser ret = new ValueParser(values);
/* honnor readOnly option on submaps */
ret.setReadOnly(getReadOnly());
return ret;
}
}
public int size()
{
return getSource() == null ? 0 : getSource().size();
}
public boolean isEmpty()
{
return getSource() == null || getSource().isEmpty();
}
public boolean containsKey(Object key)
{
return getSource() == null ? false : getSource().containsKey(key);
}
public boolean containsValue(Object value)
{
return getSource() == null ? false : getSource().containsValue(value);
}
public Object get(Object key)
{
return get(String.valueOf(key));
}
public Object put(String key, Object value)
{
if(readOnly)
{
throw new UnsupportedOperationException("Cannot put("+key+","+value+"); "+getClass().getName()+" is read-only");
}
if(hasSubkeys != null && hasSubkeys.equals(Boolean.FALSE) && key.indexOf('.') != -1)
{
hasSubkeys = Boolean.TRUE;
}
return getSource().put(key,value); // TODO this tool should be made thread-safe (the request-scoped ParameterTool doesn't need it, but other uses could...)
}
public Object remove(Object key)
{
if(readOnly)
{
throw new UnsupportedOperationException("Cannot remove("+key+"); "+getClass().getName()+" is read-only");
}
if(hasSubkeys != null && hasSubkeys.equals(Boolean.TRUE) && ((String)key).indexOf('.') != -1)
{
hasSubkeys = null;
}
return getSource().remove(key);
}
public void putAll(Map<? extends String,? extends Object> m) {
if(readOnly)
{
throw new UnsupportedOperationException("Cannot putAll("+m+"); "+getClass().getName()+" is read-only");
}
hasSubkeys = null;
getSource().putAll(m);
}
public void clear() {
if(readOnly)
{
throw new UnsupportedOperationException("Cannot clear(); "+getClass().getName()+" is read-only");
}
hasSubkeys = Boolean.FALSE;
getSource().clear();
}
public Set<String> keySet() {
return getSource() == null ? null : getSource().keySet();
}
public Collection values() {
return getSource() == null ? null : getSource().values();
}
public Set<Map.Entry<String,Object>> entrySet() {
return getSource().entrySet();
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append('{');
boolean empty = true;
for(Map.Entry<String,Object> entry:entrySet())
{
if(!empty)
{
builder.append(", ");
}
empty = false;
builder.append(entry.getKey());
builder.append('=');
builder.append(String.valueOf(entry.getValue()));
}
builder.append('}');
return builder.toString();
}
}
|
velocity-tools-generic/src/main/java/org/apache/velocity/tools/generic/ValueParser.java
|
package org.apache.velocity.tools.generic;
/*
* 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.
*/
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.velocity.tools.ConversionUtils;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.config.DefaultKey;
import org.apache.velocity.tools.config.InvalidScope;
import org.apache.velocity.tools.config.SkipSetters;
/**
* <p>Utility class for easy parsing of String values held in a Map.</p>
*
* <p>This comes in very handy when parsing parameters.</p>
*
* <p>When subkeys are allowed, getValue("foo") will also search for all keys
* of the form "foo.bar" and return a ValueParser of the type "bar" -> value for all found values.</p>
*
* TODO: someone doing java configuration ought to be able to put a source Map
* in the tool properties, allowing this to be used like other tools
*
* @author Nathan Bubna
* @version $Revision$ $Date$
* @since VelocityTools 1.2
*/
@DefaultKey("parser")
@InvalidScope(Scope.SESSION) /* session scope forbidden: Object may not be Serializable */
@SkipSetters
public class ValueParser extends FormatConfig implements Map<String,Object>
{
public static final String STRINGS_DELIMITER_FORMAT_KEY = "stringsDelimiter";
public static final String DEFAULT_STRINGS_DELIMITER = ",";
private String stringsDelimiter = DEFAULT_STRINGS_DELIMITER;
private Map<String,Object> source = null;
private boolean allowSubkeys = true;
/* when using subkeys, cache at least the presence of any subkey,
so that the rendering of templates not using subkeys will only
look once for subkeys
*/
private Boolean hasSubkeys = null;
/* whether the wrapped map should be read-only or not */
private boolean readOnly = true;
/**
* The key used for specifying whether to support subkeys
*/
public static final String ALLOWSUBKEYS_KEY = "allowSubkeys";
/**
* The key used for specifying whether to be read-only
*/
public static final String READONLY_KEY = "readOnly";
public ValueParser()
{
}
public ValueParser(Map<String,Object> source)
{
setSource(source);
}
protected void setSource(Map<String,Object> source)
{
this.source = source;
}
protected Map<String,Object> getSource(boolean create)
{
// If this method has not been overrided, make sure source is not null
if (source == null && create)
{
source = new HashMap<String, Object>();
}
return this.source;
}
protected Map<String,Object> getSource()
{
return getSource(true);
}
/**
* Are subkeys allowed ?
* @return yes/no
*/
protected boolean getAllowSubkeys()
{
return allowSubkeys;
}
/**
* allow or disallow subkeys
* @param allow
*/
protected void setAllowSubkeys(boolean allow)
{
allowSubkeys = allow;
}
/**
* Is the Map read-only?
* @return yes/no
*/
protected boolean getReadOnly()
{
return readOnly;
}
/**
* Set or unset read-only behaviour
* @param ro
*/
protected void setReadOnly(boolean ro)
{
readOnly = ro;
}
/**
* Sets the delimiter used for separating values in a single String value.
* The default string delimiter is a comma.
*
* @see #getValues(String)
*/
protected final void setStringsDelimiter(String stringsDelimiter)
{
this.stringsDelimiter = stringsDelimiter;
}
/**
* Does the actual configuration. This is protected, so
* subclasses may share the same ValueParser and call configure
* at any time, while preventing templates from doing so when
* configure(Map) is locked.
*/
@Override
protected void configure(ValueParser values)
{
super.configure(values);
String delimiter = values.getString(STRINGS_DELIMITER_FORMAT_KEY);
if (delimiter != null)
{
setStringsDelimiter(delimiter);
}
Boolean allow = values.getBoolean(ALLOWSUBKEYS_KEY);
if(allow != null)
{
setAllowSubkeys(allow);
}
Boolean ro = values.getBoolean(READONLY_KEY);
if(ro != null)
{
setReadOnly(ro);
}
}
// ----------------- public parsing methods --------------------------
/**
* Convenience method for checking whether a certain parameter exists.
*
* @param key the parameter's key
* @return <code>true</code> if a parameter exists for the specified
* key; otherwise, returns <code>false</code>.
*/
public boolean exists(String key)
{
return (getValue(key) != null);
}
/**
* Convenience method for use in Velocity templates.
* This allows for easy "dot" access to parameters.
*
* e.g. $params.foo instead of $params.getString('foo')
*
* @param key the parameter's key
* @return parameter matching the specified key or
* <code>null</code> if there is no matching
* parameter
*/
public Object get(String key)
{
Object value = getValue(key);
if (value == null && getSource() != null && getAllowSubkeys())
{
value = getSubkey(key);
}
return value;
}
/**
* Returns the value mapped to the specified key
* in the {@link Map} returned by {@link #getSource()}. If there is
* no source, then this will always return {@code null}.
*/
public Object getValue(String key)
{
if (getSource() == null)
{
return null;
}
return getSource().get(key);
}
/**
* @param key the desired parameter's key
* @param alternate The alternate value
* @return parameter matching the specified key or the
* specified alternate Object if there is no matching
* parameter
*/
public Object getValue(String key, Object alternate)
{
Object value = getValue(key);
if (value == null)
{
return alternate;
}
return value;
}
protected String[] parseStringList(String value)
{
String[] values;
if (stringsDelimiter.length() == 0 || value.indexOf(stringsDelimiter) < 0)
{
values = new String[] { value };
}
else
{
values = value.split(stringsDelimiter);
}
return values;
}
/**
* <p>Returns an array of values. If the internal value is a string, it is split using the ',' delimitor (if you need
* to split strings around another separator, use $collection.split() with the properly configured separator).</p>
* <p>If the internal value is not an array or is a string without any ',', a singletin array is returned.</p>
* @param key the desired parameter's key
* @return array of values, or null of the key has not been found.
* specified alternate Object if there is no matching
* parameter
*/
public Object[] getValues(String key)
{
Object value = getValue(key);
if (value == null)
{
return null;
}
if (value instanceof String)
{
return parseStringList((String)value);
}
if (value instanceof Object[])
{
return (Object[])value;
}
return new Object[] { value };
}
/**
* @param key the parameter's key
* @return parameter matching the specified key or
* <code>null</code> if there is no matching
* parameter
*/
public String getString(String key)
{
return ConversionUtils.toString(getValue(key));
}
/**
* @param key the desired parameter's key
* @param alternate The alternate value
* @return parameter matching the specified key or the
* specified alternate String if there is no matching
* parameter
*/
public String getString(String key, String alternate)
{
String s = getString(key);
return (s != null) ? s : alternate;
}
/**
* @param key the desired parameter's key
* @return a {@link Boolean} object for the specified key or
* <code>null</code> if no matching parameter is found
*/
public Boolean getBoolean(String key)
{
return ConversionUtils.toBoolean(getValue(key));
}
/**
* @param key the desired parameter's key
* @param alternate The alternate boolean value
* @return boolean value for the specified key or the
* alternate boolean is no value is found
*/
public boolean getBoolean(String key, boolean alternate)
{
Boolean bool = getBoolean(key);
return (bool != null) ? bool.booleanValue() : alternate;
}
/**
* @param key the desired parameter's key
* @param alternate the alternate {@link Boolean}
* @return a {@link Boolean} for the specified key or the specified
* alternate if no matching parameter is found
*/
public Boolean getBoolean(String key, Boolean alternate)
{
Boolean bool = getBoolean(key);
return (bool != null) ? bool : alternate;
}
/**
* @param key the desired parameter's key
* @return a {@link Integer} for the specified key or
* <code>null</code> if no matching parameter is found
*/
public Integer getInteger(String key)
{
Object value = getValue(key);
if (value == null)
{
return null;
}
Number number = ConversionUtils.toNumber(value, getFormat(), getLocale());
return number == null ? null : number.intValue();
}
/**
* @param key the desired parameter's key
* @param alternate The alternate Integer
* @return an Integer for the specified key or the specified
* alternate if no matching parameter is found
*/
public Integer getInteger(String key, Integer alternate)
{
Integer num = getInteger(key);
if (num == null)
{
return alternate;
}
return num;
}
/**
* @param key the desired parameter's key
* @return a {@link Double} for the specified key or
* <code>null</code> if no matching parameter is found
*/
public Double getDouble(String key)
{
Object value = getValue(key);
if (value == null)
{
return null;
}
Number number = ConversionUtils.toNumber(value, getFormat(), getLocale());
return number == null ? null : number.doubleValue();
}
/**
* @param key the desired parameter's key
* @param alternate The alternate Double
* @return an Double for the specified key or the specified
* alternate if no matching parameter is found
*/
public Double getDouble(String key, Double alternate)
{
Double num = getDouble(key);
if (num == null)
{
return alternate;
}
return num;
}
/**
* @param key the desired parameter's key
* @return a {@link Number} for the specified key or
* <code>null</code> if no matching parameter is found
*/
public Number getNumber(String key)
{
return ConversionUtils.toNumber(getValue(key), getFormat(), getLocale());
}
/**
* @param key the desired parameter's key
* @return a {@link Locale} for the specified key or
* <code>null</code> if no matching parameter is found
*/
public Locale getLocale(String key)
{
return toLocale(getValue(key));
}
/**
* @param key the desired parameter's key
* @param alternate The alternate Number
* @return a Number for the specified key or the specified
* alternate if no matching parameter is found
*/
public Number getNumber(String key, Number alternate)
{
Number n = getNumber(key);
return (n != null) ? n : alternate;
}
/**
* @param key the desired parameter's key
* @param alternate The alternate int value
* @return the int value for the specified key or the specified
* alternate value if no matching parameter is found
*/
public int getInt(String key, int alternate)
{
Number n = getNumber(key);
return (n != null) ? n.intValue() : alternate;
}
/**
* @param key the desired parameter's key
* @param alternate The alternate double value
* @return the double value for the specified key or the specified
* alternate value if no matching parameter is found
*/
public double getDouble(String key, double alternate)
{
Number n = getNumber(key);
return (n != null) ? n.doubleValue() : alternate;
}
/**
* @param key the desired parameter's key
* @param alternate The alternate Locale
* @return a Locale for the specified key or the specified
* alternate if no matching parameter is found
*/
public Locale getLocale(String key, Locale alternate)
{
Locale l = getLocale(key);
return (l != null) ? l : alternate;
}
/**
* @param key the key for the desired parameter
* @return an array of String objects containing all of the values
* associated with the given key, or <code>null</code>
* if the no values are associated with the given key
*/
public String[] getStrings(String key)
{
Object[] array = getValues(key);
if (array == null || String.class.isAssignableFrom(array.getClass().getComponentType()))
{
return (String[])array;
}
String[] ret = new String[array.length];
for (int i = 0; i < array.length; ++i)
{
ret[i] = ConversionUtils.toString(array[i]);
}
return ret;
}
/**
* @param key the key for the desired parameter
* @return an array of Boolean objects associated with the given key.
*/
public Boolean[] getBooleans(String key)
{
Object[] array = getValues(key);
if (array == null || Boolean.class.isAssignableFrom(array.getClass().getComponentType()))
{
return (Boolean[])array;
}
Boolean[] ret = new Boolean[array.length];
for (int i = 0; i < array.length; ++i)
{
ret[i] = ConversionUtils.toBoolean(array[i]);
}
return ret;
}
/**
* @param key the key for the desired parameter
* @return an array of Number objects associated with the given key,
* or <code>null</code> if Numbers are not associated with it.
*/
public Number[] getNumbers(String key)
{
Object[] array = getValues(key);
if (array == null || Number.class.isAssignableFrom(array.getClass().getComponentType()))
{
return (Number[])array;
}
Number[] ret = new Number[array.length];
for (int i = 0; i < array.length; ++i)
{
ret[i] = ConversionUtils.toNumber(array[i], getFormat(), getLocale());
}
return ret;
}
/**
* @param key the key for the desired parameter
* @return an array of int values associated with the given key,
* or <code>null</code> if numbers are not associated with it.
*/
public int[] getInts(String key)
{
Object[] array = getValues(key);
if (array == null)
{
return null;
}
int[] ret = new int[array.length];
for (int i = 0; i < array.length; ++i)
{
ret[i] = ConversionUtils.toNumber(array[i], getFormat(), getLocale()).intValue();
}
return ret;
}
/**
* @param key the key for the desired parameter
* @return an array of double values associated with the given key,
* or <code>null</code> if numbers are not associated with it.
*/
public double[] getDoubles(String key)
{
Object[] array = getValues(key);
if (array == null)
{
return null;
}
double[] ret = new double[array.length];
for (int i = 0; i < array.length; ++i)
{
ret[i] = ConversionUtils.toNumber(array[i], getFormat(), getLocale()).doubleValue();
}
return ret;
}
/**
* @param key the key for the desired parameter
* @return an array of Locale objects associated with the given key,
* or <code>null</code> if Locales are not associated with it.
*/
public Locale[] getLocales(String key)
{
Object[] array = getValues(key);
if (array == null || Locale.class.isAssignableFrom(array.getClass().getComponentType()))
{
return (Locale[])array;
}
Locale[] ret = new Locale[array.length];
for (int i = 0; i < array.length; ++i)
{
ret[i] = ConversionUtils.toLocale(String.valueOf(array[i]));
}
return ret;
}
/**
* Determines whether there are subkeys available in the source map.
*/
public boolean hasSubkeys()
{
if (getSource() == null || !getAllowSubkeys())
{
return false;
}
if (hasSubkeys == null)
{
for (String key : getSource().keySet())
{
int dot = key.indexOf('.');
if (dot > 0 && dot < key.length())
{
hasSubkeys = Boolean.TRUE;
break;
}
}
if (hasSubkeys == null)
{
hasSubkeys = Boolean.FALSE;
}
}
return hasSubkeys;
}
/**
* returns the set of all possible first-level subkeys, including complete keys without dots (or returns keySet() if allowSubKeys is false)
*/
public Set<String> getSubkeys()
{
Set<String> keys = keySet();
if (getSource() == null || !getAllowSubkeys())
{
return keys;
}
else
{
Set<String> result = new TreeSet<String>();
for (String key: keys)
{
int dot = key.indexOf('.');
if (dot > 0 && dot < key.length())
{
result.add(key.substring(0, dot));
}
}
return result;
}
}
/**
* subkey getter that returns a map <subkey#2> -> value
* for every "subkey.subkey2" found entry
*
* @param subkey subkey to search for
* @return the map of found values
*/
protected ValueParser getSubkey(String subkey)
{
if (!hasSubkeys() || subkey == null || subkey.length() == 0)
{
return null;
}
Map<String,Object> values = null;
subkey = subkey.concat(".");
for (Map.Entry<String,Object> entry : getSource().entrySet())
{
if (entry.getKey().startsWith(subkey) &&
entry.getKey().length() > subkey.length())
{
if (values == null)
{
values = new HashMap<String, Object>();
}
values.put(entry.getKey().substring(subkey.length()),entry.getValue());
}
}
if (values == null)
{
return null;
}
else
{
ValueParser ret = new ValueParser(values);
/* honnor readOnly option on submaps */
ret.setReadOnly(getReadOnly());
return ret;
}
}
public int size()
{
return getSource() == null ? 0 : getSource().size();
}
public boolean isEmpty()
{
return getSource() == null || getSource().isEmpty();
}
public boolean containsKey(Object key)
{
return getSource() == null ? false : getSource().containsKey(key);
}
public boolean containsValue(Object value)
{
return getSource() == null ? false : getSource().containsValue(value);
}
public Object get(Object key)
{
return get(String.valueOf(key));
}
public Object put(String key, Object value)
{
if(readOnly)
{
throw new UnsupportedOperationException("Cannot put("+key+","+value+"); "+getClass().getName()+" is read-only");
}
if(hasSubkeys != null && hasSubkeys.equals(Boolean.FALSE) && key.indexOf('.') != -1)
{
hasSubkeys = Boolean.TRUE;
}
return getSource().put(key,value); // TODO this tool should be made thread-safe (the request-scoped ParameterTool doesn't need it, but other uses could...)
}
public Object remove(Object key)
{
if(readOnly)
{
throw new UnsupportedOperationException("Cannot remove("+key+"); "+getClass().getName()+" is read-only");
}
if(hasSubkeys != null && hasSubkeys.equals(Boolean.TRUE) && ((String)key).indexOf('.') != -1)
{
hasSubkeys = null;
}
return getSource().remove(key);
}
public void putAll(Map<? extends String,? extends Object> m) {
if(readOnly)
{
throw new UnsupportedOperationException("Cannot putAll("+m+"); "+getClass().getName()+" is read-only");
}
hasSubkeys = null;
getSource().putAll(m);
}
public void clear() {
if(readOnly)
{
throw new UnsupportedOperationException("Cannot clear(); "+getClass().getName()+" is read-only");
}
hasSubkeys = Boolean.FALSE;
getSource().clear();
}
public Set<String> keySet() {
return getSource() == null ? null : getSource().keySet();
}
public Collection values() {
return getSource() == null ? null : getSource().values();
}
public Set<Map.Entry<String,Object>> entrySet() {
return getSource().entrySet();
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append('{');
boolean empty = true;
for(Map.Entry<String,Object> entry:entrySet())
{
if(!empty)
{
builder.append(", ");
}
empty = false;
builder.append(entry.getKey());
builder.append('=');
builder.append(String.valueOf(entry.getValue()));
}
builder.append('}');
return builder.toString();
}
}
|
[tools] Javadoc fix
git-svn-id: 08feff1e20460d5e8b75c2f5109ada1fb2e66d41@1811712 13f79535-47bb-0310-9956-ffa450edef68
|
velocity-tools-generic/src/main/java/org/apache/velocity/tools/generic/ValueParser.java
|
[tools] Javadoc fix
|
|
Java
|
apache-2.0
|
08f38143779c45b145be08af8fda521138ef0ea0
| 0
|
ocpsoft/rewrite,ocpsoft/rewrite,chkal/rewrite,jsight/rewrite,jsight/rewrite,jsight/rewrite,chkal/rewrite,chkal/rewrite,jsight/rewrite,ocpsoft/rewrite,chkal/rewrite,jsight/rewrite,ocpsoft/rewrite,chkal/rewrite,ocpsoft/rewrite
|
/*
* Copyright 2011 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*
* 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.ocpsoft.rewrite.showcase.rest;
import java.io.IOException;
import java.io.PrintWriter;
import javax.inject.Inject;
import javax.servlet.ServletContext;
import com.ocpsoft.rewrite.bind.Evaluation;
import com.ocpsoft.rewrite.bind.ParameterizedPattern;
import com.ocpsoft.rewrite.config.Configuration;
import com.ocpsoft.rewrite.config.ConfigurationBuilder;
import com.ocpsoft.rewrite.context.EvaluationContext;
import com.ocpsoft.rewrite.servlet.config.HttpConfigurationProvider;
import com.ocpsoft.rewrite.servlet.config.HttpOperation;
import com.ocpsoft.rewrite.servlet.config.Method;
import com.ocpsoft.rewrite.servlet.config.Path;
import com.ocpsoft.rewrite.servlet.config.Response;
import com.ocpsoft.rewrite.servlet.config.SendStatus;
import com.ocpsoft.rewrite.servlet.http.event.HttpInboundServletRewrite;
import com.ocpsoft.rewrite.servlet.http.event.HttpServletRewrite;
/**
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*
*/
public class RestRewriteConfiguration extends HttpConfigurationProvider
{
@Inject
private ProductRegistry products;
@Override
public Configuration getConfiguration(final ServletContext context)
{
return ConfigurationBuilder
.begin()
.defineRule()
/**
* Define the inbound conditions and conversion mechanisms to be used when handling inbound requests.
*/
.when(Method.isGet()
.and(Path.matches("/store/product/{pid}")
.where("pid")
.bindsTo(Evaluation.property("pid").convertedBy(ProductConverter.class)
.validatedBy(ProductValidator.class))))
.perform(new HttpOperation() {
@Override
public void performHttp(final HttpServletRewrite event, final EvaluationContext context)
{
/**
* Extract the stored {pid} from our Path and load the Product. This is an example of how we can
* use a converter to directly bind and store the object we want into a binding. {@link Evaluation}
* is an low-level construct, and binds array values that must be dereferenced. If using other
* bindings such as {@link El}, the value will be bound directly to the type of the referenced
* property type, and this array downcast is not necessary.
*/
Product product = (Product) Evaluation.property("pid").retrieve(event, context);
/**
* Marshal the Product into XML using JAXB. This has been extracted into a utility class.
*/
try {
XMLUtil.streamFromObject(Product.class, product, event.getResponse()
.getOutputStream());
}
catch (IOException e) {
throw new RuntimeException(e);
}
/**
* Set the content type and status code of the response, this again could be extracted into a REST
* utility class.
*/
event.getResponse().setContentType("application/xml");
((HttpInboundServletRewrite) event).sendStatusCode(200);
}
})
.defineRule()
.when(Path.matches("/store/products").and(Method.isGet()))
.perform(new HttpOperation() {
@Override
public void performHttp(final HttpServletRewrite event, final EvaluationContext context)
{
try {
XMLUtil.streamFromObject(ProductRegistry.class, products, event.getResponse().getOutputStream());
event.getResponse().setContentType("application/xml");
((HttpInboundServletRewrite) event).sendStatusCode(200);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
})
.defineRule()
.when(Path.matches("/store/products").and(Method.isPost()))
.perform(new HttpOperation() {
@Override
public void performHttp(final HttpServletRewrite event, final EvaluationContext context)
{
try {
Product product = XMLUtil.streamToObject(Product.class, event.getRequest().getInputStream());
product = products.add(product);
/**
* Just for fun, set a response header containing the URL to the newly created Product.
*/
String location = new ParameterizedPattern(event.getContextPath() + "/store/product/{pid}")
.build(product.getId());
Response.addHeader("Location", location).perform(event, context);
event.getResponse().setContentType("text/html");
((HttpInboundServletRewrite) event).sendStatusCode(200);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
})
.defineRule().when(Path.matches("/")).perform(new HttpOperation() {
@Override
public void performHttp(final HttpServletRewrite event, final EvaluationContext context)
{
try {
PrintWriter writer = event.getResponse().getWriter();
writer.write("<html>"
+
"<body>"
+
"<h1>Rewrite Rest Demo</h1>"
+
"Sorry for the boring page, there are no HTML pages in this demo! Try some of the following operations:"
+ ""
+
"<ul>"
+
"<li>GET <a href=\""
+ event.getContextPath()
+ "/store/product/0\">/store/product/0</a></li>"
+
"<li>GET <a href=\""
+ event.getContextPath()
+ "/store/products\">/store/products</a></li>"
+
"<li>POST "
+ event.getContextPath()
+ "/store/products - This requires a rest client, or you can use `curl`<br/>"
+
"curl --data \"<product><name>James</name><description>yay</description><price>12.9</price></product>\" http://localhost:8080/rewrite-showcase-rest/store/products</li>"
+
"</ul>" +
"</body></html>");
SendStatus.code(200).perform(event, context);
}
catch (IOException e) {
throw new RuntimeException();
}
}
});
}
@Override
public int priority()
{
return 0;
}
}
|
showcase/rest-ws/src/main/java/com/ocpsoft/rewrite/showcase/rest/RestRewriteConfiguration.java
|
/*
* Copyright 2011 <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*
* 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.ocpsoft.rewrite.showcase.rest;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.ServletContext;
import com.ocpsoft.rewrite.bind.Evaluation;
import com.ocpsoft.rewrite.bind.ParameterizedPattern;
import com.ocpsoft.rewrite.config.Configuration;
import com.ocpsoft.rewrite.config.ConfigurationBuilder;
import com.ocpsoft.rewrite.context.EvaluationContext;
import com.ocpsoft.rewrite.servlet.config.HttpConfigurationProvider;
import com.ocpsoft.rewrite.servlet.config.HttpOperation;
import com.ocpsoft.rewrite.servlet.config.Method;
import com.ocpsoft.rewrite.servlet.config.Path;
import com.ocpsoft.rewrite.servlet.config.Response;
import com.ocpsoft.rewrite.servlet.http.event.HttpInboundServletRewrite;
import com.ocpsoft.rewrite.servlet.http.event.HttpServletRewrite;
/**
* @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a>
*
*/
public class RestRewriteConfiguration extends HttpConfigurationProvider
{
@Inject
private ProductRegistry products;
@Override
public Configuration getConfiguration(final ServletContext context)
{
return ConfigurationBuilder
.begin()
.defineRule()
/**
* Define the inbound conditions and conversion mechanisms to be used when handling inbound requests.
*/
.when(Method.isGet()
.and(Path.matches("/store/product/{pid}")
.where("pid")
.bindsTo(Evaluation.property("pid").convertedBy(ProductConverter.class)
.validatedBy(ProductValidator.class))))
.perform(new HttpOperation() {
@Override
public void performHttp(final HttpServletRewrite event, final EvaluationContext context)
{
/**
* Extract the stored {pid} from our Path and load the Product. This is an example of how we can
* use a converter to directly bind and store the object we want into a binding. {@link Evaluation}
* is an low-level construct, and binds array values that must be dereferenced. If using other
* bindings such as {@link El}, the value will be bound directly to the type of the referenced
* property type, and this array downcast is not necessary.
*/
Product product = (Product) Evaluation.property("pid").retrieve(event, context);
/**
* Marshal the Product into XML using JAXB. This has been extracted into a utility class.
*/
try {
XMLUtil.streamFromObject(Product.class, product, event.getResponse()
.getOutputStream());
}
catch (IOException e) {
throw new RuntimeException(e);
}
/**
* Set the content type and status code of the response, this again could be extracted into a REST
* utility class.
*/
event.getResponse().setContentType("application/xml");
((HttpInboundServletRewrite) event).sendStatusCode(200);
}
})
.defineRule()
.when(Path.matches("/store/products").and(Method.isGet()))
.perform(new HttpOperation() {
@Override
public void performHttp(final HttpServletRewrite event, final EvaluationContext context)
{
try {
XMLUtil.streamFromObject(ProductRegistry.class, products, event.getResponse().getOutputStream());
event.getResponse().setContentType("application/xml");
((HttpInboundServletRewrite) event).sendStatusCode(200);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
})
.defineRule()
.when(Path.matches("/store/products").and(Method.isPost()))
.perform(new HttpOperation() {
@Override
public void performHttp(final HttpServletRewrite event, final EvaluationContext context)
{
try {
Product product = XMLUtil.streamToObject(Product.class, event.getRequest().getInputStream());
product = products.add(product);
/**
* Just for fun, set a response header containing the URL to the newly created Product.
*/
String location = new ParameterizedPattern(event.getContextPath() + "/store/product/{pid}")
.build(product.getId());
Response.addHeader("Location", location).perform(event, context);
event.getResponse().setContentType("text/html");
((HttpInboundServletRewrite) event).sendStatusCode(200);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
@Override
public int priority()
{
return 0;
}
}
|
Added rest demo documentation
|
showcase/rest-ws/src/main/java/com/ocpsoft/rewrite/showcase/rest/RestRewriteConfiguration.java
|
Added rest demo documentation
|
|
Java
|
apache-2.0
|
0a2d8d8360df9c32bff64ade945ac0219dc0f687
| 0
|
cgeo/cgeo,cgeo/cgeo,cgeo/cgeo,cgeo/cgeo
|
package cgeo.geocaching.utils;
import cgeo.geocaching.CgeoApplication;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public final class ProcessUtils {
public static final String CHROME_PACKAGE_NAME = "com.android.chrome";
private ProcessUtils() {
// utility class
}
/**
* Preferred method to detect the availability of an external app
*/
public static boolean isLaunchable(@Nullable final String packageName) {
return getLaunchIntent(packageName) != null;
}
public static boolean isChromeLaunchable() {
return ProcessUtils.isLaunchable(CHROME_PACKAGE_NAME);
}
public static List<ResolveInfo> getInstalledBrowsers(final Context context) {
// We're using "https://example.com" as we only want to query for web browsers, not c:geo or other apps
final Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com"));
return context.getPackageManager().queryIntentActivities(browserIntent, PackageManager.MATCH_DEFAULT_ONLY);
}
/**
* Checks whether a launch intent is available or if the package is just installed
* This function is relatively costly, so if you know that the package in question has
* a launch intent, use isLaunchable() instead.
*/
public static boolean isInstalled(@NonNull final String packageName) {
return isLaunchable(packageName) || hasPackageInstalled(packageName);
}
/**
* This will find installed applications even without launch intent (e.g. the streetview plugin).
*
* Be aware:
* Starting with Android 11 getInstalledPackages() will only return packages declared in AndroidManifest.xml
* (Add a lint exception, as we have cross-checked our current usages for this method)
*/
@SuppressLint("QueryPermissionsNeeded")
private static boolean hasPackageInstalled(@NonNull final String packageName) {
final List<PackageInfo> packs = CgeoApplication.getInstance().getPackageManager().getInstalledPackages(0);
for (final PackageInfo packageInfo : packs) {
if (packageName.equals(packageInfo.packageName)) {
return true;
}
}
return false;
}
/**
* This will find applications, which can be launched.
*/
@Nullable
public static Intent getLaunchIntent(@Nullable final String packageName) {
if (packageName == null) {
return null;
}
final PackageManager packageManager = CgeoApplication.getInstance().getPackageManager();
try {
// This can throw an exception where the exception type is only defined on API Level > 3
// therefore surround with try-catch
return packageManager.getLaunchIntentForPackage(packageName);
} catch (final Exception ignored) {
return null;
}
}
public static boolean isIntentAvailable(@NonNull final String intent) {
return isIntentAvailable(intent, null);
}
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
*
* @param action The Intent action to check for availability.
* @param uri The Intent URI to check for availability.
* @return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
public static boolean isIntentAvailable(@NonNull final String action, @Nullable final Uri uri) {
final PackageManager packageManager = CgeoApplication.getInstance().getPackageManager();
final Intent intent;
if (uri == null) {
intent = new Intent(action);
} else {
intent = new Intent(action, uri);
}
final List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
final List<ResolveInfo> servicesList = packageManager.queryIntentServices(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return CollectionUtils.isNotEmpty(list) || CollectionUtils.isNotEmpty(servicesList);
}
public static void openMarket(final Activity activity, @NonNull final String packageName) {
try {
final String url = "market://details?id=" + packageName;
final Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
activity.startActivity(marketIntent);
} catch (final RuntimeException ignored) {
// market not available, fall back to browser
final String uri = "https://play.google.com/store/apps/details?id=" + packageName;
ShareUtils.openUrl(activity, uri);
}
}
public static void restartApplication(final Context c) {
try {
if (c != null) {
final PackageManager pm = c.getPackageManager();
if (pm != null) {
//create the intent with the default start activity for our application
final Intent mStartActivity = pm.getLaunchIntentForPackage(c.getPackageName());
if (mStartActivity != null) {
mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// create a pending intent so the application is restarted after System.exit(0) was called.
final PendingIntent mPendingIntent = PendingIntent.getActivity(c, 1633838708, mStartActivity, (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_IMMUTABLE : 0) | PendingIntent.FLAG_CANCEL_CURRENT);
final AlarmManager mgr = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
} else {
Log.e("Was not able to restart application, mStartActivity null");
}
} else {
Log.e("Was not able to restart application, PM null");
}
} else {
Log.e("Was not able to restart application, Context null");
}
} catch (Exception ex) {
Log.e("Was not able to restart application");
}
}
}
|
main/src/cgeo/geocaching/utils/ProcessUtils.java
|
package cgeo.geocaching.utils;
import cgeo.geocaching.CgeoApplication;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public final class ProcessUtils {
public static final String CHROME_PACKAGE_NAME = "com.android.chrome";
private ProcessUtils() {
// utility class
}
/**
* Preferred method to detect the availability of an external app
*/
public static boolean isLaunchable(@Nullable final String packageName) {
return getLaunchIntent(packageName) != null;
}
public static boolean isChromeLaunchable() {
return ProcessUtils.isLaunchable(CHROME_PACKAGE_NAME);
}
public static List<ResolveInfo> getInstalledBrowsers(final Context context) {
// We're using "https://example.com" as we only want to query for web browsers, not c:geo or other apps
final Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com"));
return context.getPackageManager().queryIntentActivities(browserIntent, PackageManager.MATCH_DEFAULT_ONLY);
}
/**
* Checks whether a launch intent is available or if the package is just installed
* This function is relatively costly, so if you know that the package in question has
* a launch intent, use isLaunchable() instead.
*/
public static boolean isInstalled(@NonNull final String packageName) {
return isLaunchable(packageName) || hasPackageInstalled(packageName);
}
/**
* This will find installed applications even without launch intent (e.g. the streetview plugin).
*/
private static boolean hasPackageInstalled(@NonNull final String packageName) {
final List<PackageInfo> packs = CgeoApplication.getInstance().getPackageManager().getInstalledPackages(0);
for (final PackageInfo packageInfo : packs) {
if (packageName.equals(packageInfo.packageName)) {
return true;
}
}
return false;
}
/**
* This will find applications, which can be launched.
*/
@Nullable
public static Intent getLaunchIntent(@Nullable final String packageName) {
if (packageName == null) {
return null;
}
final PackageManager packageManager = CgeoApplication.getInstance().getPackageManager();
try {
// This can throw an exception where the exception type is only defined on API Level > 3
// therefore surround with try-catch
return packageManager.getLaunchIntentForPackage(packageName);
} catch (final Exception ignored) {
return null;
}
}
public static boolean isIntentAvailable(@NonNull final String intent) {
return isIntentAvailable(intent, null);
}
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
*
* @param action The Intent action to check for availability.
* @param uri The Intent URI to check for availability.
* @return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
public static boolean isIntentAvailable(@NonNull final String action, @Nullable final Uri uri) {
final PackageManager packageManager = CgeoApplication.getInstance().getPackageManager();
final Intent intent;
if (uri == null) {
intent = new Intent(action);
} else {
intent = new Intent(action, uri);
}
final List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
final List<ResolveInfo> servicesList = packageManager.queryIntentServices(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return CollectionUtils.isNotEmpty(list) || CollectionUtils.isNotEmpty(servicesList);
}
public static void openMarket(final Activity activity, @NonNull final String packageName) {
try {
final String url = "market://details?id=" + packageName;
final Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
activity.startActivity(marketIntent);
} catch (final RuntimeException ignored) {
// market not available, fall back to browser
final String uri = "https://play.google.com/store/apps/details?id=" + packageName;
ShareUtils.openUrl(activity, uri);
}
}
public static void restartApplication(final Context c) {
try {
if (c != null) {
final PackageManager pm = c.getPackageManager();
if (pm != null) {
//create the intent with the default start activity for our application
final Intent mStartActivity = pm.getLaunchIntentForPackage(c.getPackageName());
if (mStartActivity != null) {
mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// create a pending intent so the application is restarted after System.exit(0) was called.
final PendingIntent mPendingIntent = PendingIntent.getActivity(c, 1633838708, mStartActivity, (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.FLAG_IMMUTABLE : 0) | PendingIntent.FLAG_CANCEL_CURRENT);
final AlarmManager mgr = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
} else {
Log.e("Was not able to restart application, mStartActivity null");
}
} else {
Log.e("Was not able to restart application, PM null");
}
} else {
Log.e("Was not able to restart application, Context null");
}
} catch (Exception ex) {
Log.e("Was not able to restart application");
}
}
}
|
lint: try to fix QueryPermissionsNeeded
|
main/src/cgeo/geocaching/utils/ProcessUtils.java
|
lint: try to fix QueryPermissionsNeeded
|
|
Java
|
apache-2.0
|
97c5260cc969b3c19c4bba36955505198e2fc1f6
| 0
|
nishantmonu51/hive,alanfgates/hive,alanfgates/hive,anishek/hive,lirui-apache/hive,jcamachor/hive,nishantmonu51/hive,lirui-apache/hive,b-slim/hive,vergilchiu/hive,jcamachor/hive,b-slim/hive,nishantmonu51/hive,b-slim/hive,nishantmonu51/hive,jcamachor/hive,nishantmonu51/hive,alanfgates/hive,vineetgarg02/hive,b-slim/hive,b-slim/hive,vergilchiu/hive,b-slim/hive,lirui-apache/hive,anishek/hive,lirui-apache/hive,vergilchiu/hive,b-slim/hive,sankarh/hive,vergilchiu/hive,lirui-apache/hive,nishantmonu51/hive,vineetgarg02/hive,sankarh/hive,jcamachor/hive,vineetgarg02/hive,lirui-apache/hive,nishantmonu51/hive,vineetgarg02/hive,b-slim/hive,lirui-apache/hive,anishek/hive,sankarh/hive,b-slim/hive,anishek/hive,sankarh/hive,alanfgates/hive,vineetgarg02/hive,lirui-apache/hive,vergilchiu/hive,vineetgarg02/hive,jcamachor/hive,alanfgates/hive,anishek/hive,lirui-apache/hive,anishek/hive,jcamachor/hive,alanfgates/hive,jcamachor/hive,vergilchiu/hive,jcamachor/hive,alanfgates/hive,nishantmonu51/hive,vineetgarg02/hive,vergilchiu/hive,alanfgates/hive,anishek/hive,sankarh/hive,sankarh/hive,sankarh/hive,alanfgates/hive,jcamachor/hive,vergilchiu/hive,vineetgarg02/hive,anishek/hive,vergilchiu/hive,nishantmonu51/hive,vineetgarg02/hive,sankarh/hive,sankarh/hive,anishek/hive
|
/**
* 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.hive.ql.exec;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.hadoop.hive.ql.exec.mr.ExecMapperContext;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.VirtualColumn;
import org.apache.hadoop.hive.ql.plan.MapWork;
import org.apache.hadoop.hive.ql.plan.OperatorDesc;
import org.apache.hadoop.hive.ql.plan.PartitionDesc;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.ql.plan.TableScanDesc;
import org.apache.hadoop.hive.ql.plan.api.OperatorType;
import org.apache.hadoop.hive.serde2.Deserializer;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.SerDeStats;
import org.apache.hadoop.hive.serde2.SerDeUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters.Converter;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.util.StringUtils;
/**
* Map operator. This triggers overall map side processing. This is a little
* different from regular operators in that it starts off by processing a
* Writable data structure from a Table (instead of a Hive Object).
**/
public class MapOperator extends Operator<MapWork> implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
/**
* Counter.
*
*/
public static enum Counter {
DESERIALIZE_ERRORS
}
private final transient LongWritable deserialize_error_count = new LongWritable();
private final Map<MapInputPath, MapOpCtx> opCtxMap = new HashMap<MapInputPath, MapOpCtx>();
private final Map<Operator<? extends OperatorDesc>, MapOpCtx> childrenOpToOpCtxMap =
new HashMap<Operator<? extends OperatorDesc>, MapOpCtx>();
private transient MapOpCtx current;
private transient List<Operator<? extends OperatorDesc>> extraChildrenToClose = null;
private static class MapInputPath {
String path;
String alias;
Operator<?> op;
PartitionDesc partDesc;
/**
* @param path
* @param alias
* @param op
*/
public MapInputPath(String path, String alias, Operator<?> op, PartitionDesc partDesc) {
this.path = path;
this.alias = alias;
this.op = op;
this.partDesc = partDesc;
}
@Override
public boolean equals(Object o) {
if (o instanceof MapInputPath) {
MapInputPath mObj = (MapInputPath) o;
return path.equals(mObj.path) && alias.equals(mObj.alias)
&& op.equals(mObj.op);
}
return false;
}
@Override
public int hashCode() {
int ret = (path == null) ? 0 : path.hashCode();
ret += (alias == null) ? 0 : alias.hashCode();
ret += (op == null) ? 0 : op.hashCode();
return ret;
}
}
private static class MapOpCtx {
StructObjectInspector tblRawRowObjectInspector; // columns
StructObjectInspector partObjectInspector; // partition columns
StructObjectInspector vcsObjectInspector; // virtual columns
StructObjectInspector rowObjectInspector;
Converter partTblObjectInspectorConverter;
Object[] rowWithPart;
Object[] rowWithPartAndVC;
Deserializer deserializer;
String tableName;
String partName;
List<VirtualColumn> vcs;
Writable[] vcValues;
private boolean isPartitioned() {
return partObjectInspector != null;
}
private boolean hasVC() {
return vcsObjectInspector != null;
}
private Object readRow(Writable value) throws SerDeException {
return partTblObjectInspectorConverter.convert(deserializer.deserialize(value));
}
}
/**
* Initializes this map op as the root of the tree. It sets JobConf &
* MapRedWork and starts initialization of the operator tree rooted at this
* op.
*
* @param hconf
* @param mrwork
* @throws HiveException
*/
public void initializeAsRoot(Configuration hconf, MapWork mapWork)
throws HiveException {
setConf(mapWork);
setChildren(hconf);
initialize(hconf, null);
}
private MapOpCtx initObjectInspector(Configuration hconf, MapInputPath ctx,
Map<TableDesc, StructObjectInspector> convertedOI) throws Exception {
PartitionDesc pd = ctx.partDesc;
TableDesc td = pd.getTableDesc();
MapOpCtx opCtx = new MapOpCtx();
// Use table properties in case of unpartitioned tables,
// and the union of table properties and partition properties, with partition
// taking precedence
Properties partProps = isPartitioned(pd) ?
pd.getOverlayedProperties() : pd.getTableDesc().getProperties();
Map<String, String> partSpec = pd.getPartSpec();
opCtx.tableName = String.valueOf(partProps.getProperty("name"));
opCtx.partName = String.valueOf(partSpec);
Class serdeclass = pd.getDeserializerClass();
if (serdeclass == null) {
String className = checkSerdeClassName(pd.getSerdeClassName(), opCtx.tableName);
serdeclass = hconf.getClassByName(className);
}
opCtx.deserializer = (Deserializer) serdeclass.newInstance();
opCtx.deserializer.initialize(hconf, partProps);
StructObjectInspector partRawRowObjectInspector =
(StructObjectInspector) opCtx.deserializer.getObjectInspector();
opCtx.tblRawRowObjectInspector = convertedOI.get(td);
opCtx.partTblObjectInspectorConverter = ObjectInspectorConverters.getConverter(
partRawRowObjectInspector, opCtx.tblRawRowObjectInspector);
// Next check if this table has partitions and if so
// get the list of partition names as well as allocate
// the serdes for the partition columns
String pcols = partProps.getProperty(hive_metastoreConstants.META_TABLE_PARTITION_COLUMNS);
// Log LOG = LogFactory.getLog(MapOperator.class.getName());
if (pcols != null && pcols.length() > 0) {
String[] partKeys = pcols.trim().split("/");
List<String> partNames = new ArrayList<String>(partKeys.length);
Object[] partValues = new Object[partKeys.length];
List<ObjectInspector> partObjectInspectors = new ArrayList<ObjectInspector>(partKeys.length);
for (int i = 0; i < partKeys.length; i++) {
String key = partKeys[i];
partNames.add(key);
// Partitions do not exist for this table
if (partSpec == null) {
// for partitionless table, initialize partValue to null
partValues[i] = null;
} else {
partValues[i] = new Text(partSpec.get(key));
}
partObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
}
opCtx.rowWithPart = new Object[] {null, partValues};
opCtx.partObjectInspector = ObjectInspectorFactory
.getStandardStructObjectInspector(partNames, partObjectInspectors);
}
// The op may not be a TableScan for mapjoins
// Consider the query: select /*+MAPJOIN(a)*/ count(*) FROM T1 a JOIN T2 b ON a.key = b.key;
// In that case, it will be a Select, but the rowOI need not be ammended
if (ctx.op instanceof TableScanOperator) {
TableScanOperator tsOp = (TableScanOperator) ctx.op;
TableScanDesc tsDesc = tsOp.getConf();
if (tsDesc != null && tsDesc.hasVirtualCols()) {
opCtx.vcs = tsDesc.getVirtualCols();
opCtx.vcValues = new Writable[opCtx.vcs.size()];
opCtx.vcsObjectInspector = VirtualColumn.getVCSObjectInspector(opCtx.vcs);
if (opCtx.isPartitioned()) {
opCtx.rowWithPartAndVC = Arrays.copyOfRange(opCtx.rowWithPart, 0, 3);
} else {
opCtx.rowWithPartAndVC = new Object[2];
}
}
}
if (!opCtx.hasVC() && !opCtx.isPartitioned()) {
opCtx.rowObjectInspector = opCtx.tblRawRowObjectInspector;
return opCtx;
}
List<StructObjectInspector> inspectors = new ArrayList<StructObjectInspector>();
inspectors.add(opCtx.tblRawRowObjectInspector);
if (opCtx.isPartitioned()) {
inspectors.add(opCtx.partObjectInspector);
}
if (opCtx.hasVC()) {
inspectors.add(opCtx.vcsObjectInspector);
}
opCtx.rowObjectInspector = ObjectInspectorFactory.getUnionStructObjectInspector(inspectors);
return opCtx;
}
// Return the mapping for table descriptor to the expected table OI
/**
* Traverse all the partitions for a table, and get the OI for the table.
* Note that a conversion is required if any of the partition OI is different
* from the table OI. For eg. if the query references table T (partitions P1, P2),
* and P1's schema is same as T, whereas P2's scheme is different from T, conversion
* might be needed for both P1 and P2, since SettableOI might be needed for T
*/
private Map<TableDesc, StructObjectInspector> getConvertedOI(Configuration hconf)
throws HiveException {
Map<TableDesc, StructObjectInspector> tableDescOI =
new HashMap<TableDesc, StructObjectInspector>();
Set<TableDesc> identityConverterTableDesc = new HashSet<TableDesc>();
try {
for (String onefile : conf.getPathToAliases().keySet()) {
PartitionDesc pd = conf.getPathToPartitionInfo().get(onefile);
TableDesc tableDesc = pd.getTableDesc();
Properties tblProps = tableDesc.getProperties();
// If the partition does not exist, use table properties
Properties partProps = isPartitioned(pd) ? pd.getOverlayedProperties() : tblProps;
Class sdclass = pd.getDeserializerClass();
if (sdclass == null) {
String className = checkSerdeClassName(pd.getSerdeClassName(),
pd.getProperties().getProperty("name"));
sdclass = hconf.getClassByName(className);
}
Deserializer partDeserializer = (Deserializer) sdclass.newInstance();
partDeserializer.initialize(hconf, partProps);
StructObjectInspector partRawRowObjectInspector = (StructObjectInspector) partDeserializer
.getObjectInspector();
StructObjectInspector tblRawRowObjectInspector = tableDescOI.get(tableDesc);
if ((tblRawRowObjectInspector == null) ||
(identityConverterTableDesc.contains(tableDesc))) {
sdclass = tableDesc.getDeserializerClass();
if (sdclass == null) {
String className = checkSerdeClassName(tableDesc.getSerdeClassName(),
tableDesc.getProperties().getProperty("name"));
sdclass = hconf.getClassByName(className);
}
Deserializer tblDeserializer = (Deserializer) sdclass.newInstance();
tblDeserializer.initialize(hconf, tblProps);
tblRawRowObjectInspector =
(StructObjectInspector) ObjectInspectorConverters.getConvertedOI(
partRawRowObjectInspector,
tblDeserializer.getObjectInspector(), true);
if (identityConverterTableDesc.contains(tableDesc)) {
if (!partRawRowObjectInspector.equals(tblRawRowObjectInspector)) {
identityConverterTableDesc.remove(tableDesc);
}
}
else if (partRawRowObjectInspector.equals(tblRawRowObjectInspector)) {
identityConverterTableDesc.add(tableDesc);
}
tableDescOI.put(tableDesc, tblRawRowObjectInspector);
}
}
} catch (Exception e) {
throw new HiveException(e);
}
return tableDescOI;
}
private boolean isPartitioned(PartitionDesc pd) {
return pd.getPartSpec() != null && !pd.getPartSpec().isEmpty();
}
private String checkSerdeClassName(String className, String tableName) throws HiveException {
if (className == null || className.isEmpty()) {
throw new HiveException(
"SerDe class or the SerDe class name is not set for table: " + tableName);
}
return className;
}
public void setChildren(Configuration hconf) throws HiveException {
Path fpath = new Path(HiveConf.getVar(hconf,
HiveConf.ConfVars.HADOOPMAPFILENAME));
boolean schemeless = fpath.toUri().getScheme() == null;
List<Operator<? extends OperatorDesc>> children =
new ArrayList<Operator<? extends OperatorDesc>>();
Map<TableDesc, StructObjectInspector> convertedOI = getConvertedOI(hconf);
try {
for (Map.Entry<String, ArrayList<String>> entry : conf.getPathToAliases().entrySet()) {
String onefile = entry.getKey();
List<String> aliases = entry.getValue();
Path onepath = new Path(onefile);
if (schemeless) {
onepath = new Path(onepath.toUri().getPath());
}
PartitionDesc partDesc = conf.getPathToPartitionInfo().get(onefile);
for (String onealias : aliases) {
Operator<? extends OperatorDesc> op = conf.getAliasToWork().get(onealias);
LOG.info("Adding alias " + onealias + " to work list for file "
+ onefile);
MapInputPath inp = new MapInputPath(onefile, onealias, op, partDesc);
if (opCtxMap.containsKey(inp)) {
continue;
}
MapOpCtx opCtx = initObjectInspector(hconf, inp, convertedOI);
opCtxMap.put(inp, opCtx);
op.setParentOperators(new ArrayList<Operator<? extends OperatorDesc>>());
op.getParentOperators().add(this);
// check for the operators who will process rows coming to this Map
// Operator
if (!onepath.toUri().relativize(fpath.toUri()).equals(fpath.toUri())) {
children.add(op);
childrenOpToOpCtxMap.put(op, opCtx);
LOG.info("dump " + op.getName() + " "
+ opCtxMap.get(inp).rowObjectInspector.getTypeName());
}
current = opCtx; // just need for TestOperators.testMapOperator
}
}
if (children.size() == 0) {
// didn't find match for input file path in configuration!
// serious problem ..
LOG.error("Configuration does not have any alias for path: "
+ fpath.toUri());
throw new HiveException("Configuration and input path are inconsistent");
}
// we found all the operators that we are supposed to process.
setChildOperators(children);
} catch (Exception e) {
throw new HiveException(e);
}
}
@Override
public void initializeOp(Configuration hconf) throws HiveException {
// set that parent initialization is done and call initialize on children
state = State.INIT;
statsMap.put(Counter.DESERIALIZE_ERRORS, deserialize_error_count);
List<Operator<? extends OperatorDesc>> children = getChildOperators();
for (Entry<Operator<? extends OperatorDesc>, MapOpCtx> entry : childrenOpToOpCtxMap
.entrySet()) {
Operator<? extends OperatorDesc> child = entry.getKey();
MapOpCtx mapOpCtx = entry.getValue();
// Add alias, table name, and partitions to hadoop conf so that their
// children will inherit these
HiveConf.setVar(hconf, HiveConf.ConfVars.HIVETABLENAME, mapOpCtx.tableName);
HiveConf.setVar(hconf, HiveConf.ConfVars.HIVEPARTITIONNAME, mapOpCtx.partName);
child.initialize(hconf, new ObjectInspector[] {mapOpCtx.rowObjectInspector});
}
for (Entry<MapInputPath, MapOpCtx> entry : opCtxMap.entrySet()) {
MapInputPath input = entry.getKey();
MapOpCtx mapOpCtx = entry.getValue();
// Add alias, table name, and partitions to hadoop conf so that their
// children will inherit these
HiveConf.setVar(hconf, HiveConf.ConfVars.HIVETABLENAME, mapOpCtx.tableName);
HiveConf.setVar(hconf, HiveConf.ConfVars.HIVEPARTITIONNAME, mapOpCtx.partName);
Operator<? extends OperatorDesc> op = input.op;
if (children.indexOf(op) == -1) {
// op is not in the children list, so need to remember it and close it afterwards
if (extraChildrenToClose == null) {
extraChildrenToClose = new ArrayList<Operator<? extends OperatorDesc>>();
}
extraChildrenToClose.add(op);
op.initialize(hconf, new ObjectInspector[] {entry.getValue().rowObjectInspector});
}
}
}
/**
* close extra child operators that are initialized but are not executed.
*/
@Override
public void closeOp(boolean abort) throws HiveException {
if (extraChildrenToClose != null) {
for (Operator<? extends OperatorDesc> op : extraChildrenToClose) {
op.close(abort);
}
}
}
// Find context for current input file
@Override
public void cleanUpInputFileChangedOp() throws HiveException {
Path fpath = normalizePath(getExecContext().getCurrentInputFile());
for (String onefile : conf.getPathToAliases().keySet()) {
Path onepath = normalizePath(onefile);
// check for the operators who will process rows coming to this Map
// Operator
if (onepath.toUri().relativize(fpath.toUri()).equals(fpath.toUri())) {
// not from this
continue;
}
PartitionDesc partDesc = conf.getPathToPartitionInfo().get(onefile);
for (String onealias : conf.getPathToAliases().get(onefile)) {
Operator<? extends OperatorDesc> op = conf.getAliasToWork().get(onealias);
MapInputPath inp = new MapInputPath(onefile, onealias, op, partDesc);
MapOpCtx context = opCtxMap.get(inp);
if (context != null) {
current = context;
LOG.info("Processing alias " + onealias + " for file " + onefile);
return;
}
}
}
throw new IllegalStateException("Invalid path " + fpath);
}
private Path normalizePath(String onefile) {
return new Path(onefile);
}
public void process(Writable value) throws HiveException {
// A mapper can span multiple files/partitions.
// The serializers need to be reset if the input file changed
ExecMapperContext context = getExecContext();
if (context != null && context.inputFileChanged()) {
// The child operators cleanup if input file has changed
cleanUpInputFileChanged();
}
Object row;
try {
row = current.readRow(value);
if (current.hasVC()) {
current.rowWithPartAndVC[0] = row;
if (context != null) {
populateVirtualColumnValues(context, current.vcs, current.vcValues, current.deserializer);
}
int vcPos = current.isPartitioned() ? 2 : 1;
current.rowWithPartAndVC[vcPos] = current.vcValues;
row = current.rowWithPartAndVC;
} else if (current.isPartitioned()) {
current.rowWithPart[0] = row;
row = current.rowWithPart;
}
} catch (Exception e) {
// Serialize the row and output.
String rawRowString;
try {
rawRowString = value.toString();
} catch (Exception e2) {
rawRowString = "[Error getting row data with exception " +
StringUtils.stringifyException(e2) + " ]";
}
// TODO: policy on deserialization errors
deserialize_error_count.set(deserialize_error_count.get() + 1);
throw new HiveException("Hive Runtime Error while processing writable " + rawRowString, e);
}
// The row has been converted to comply with table schema, irrespective of partition schema.
// So, use tblOI (and not partOI) for forwarding
try {
forward(row, current.rowObjectInspector);
} catch (Exception e) {
// Serialize the row and output the error message.
String rowString;
try {
rowString = SerDeUtils.getJSONString(row, current.rowObjectInspector);
} catch (Exception e2) {
rowString = "[Error getting row data with exception " +
StringUtils.stringifyException(e2) + " ]";
}
throw new HiveException("Hive Runtime Error while processing row " + rowString, e);
}
}
public static Writable[] populateVirtualColumnValues(ExecMapperContext ctx,
List<VirtualColumn> vcs, Writable[] vcValues, Deserializer deserializer) {
if (vcs == null) {
return vcValues;
}
if (vcValues == null) {
vcValues = new Writable[vcs.size()];
}
for (int i = 0; i < vcs.size(); i++) {
VirtualColumn vc = vcs.get(i);
if (vc.equals(VirtualColumn.FILENAME)) {
if (ctx.inputFileChanged()) {
vcValues[i] = new Text(ctx.getCurrentInputFile());
}
} else if (vc.equals(VirtualColumn.BLOCKOFFSET)) {
long current = ctx.getIoCxt().getCurrentBlockStart();
LongWritable old = (LongWritable) vcValues[i];
if (old == null) {
old = new LongWritable(current);
vcValues[i] = old;
continue;
}
if (current != old.get()) {
old.set(current);
}
} else if (vc.equals(VirtualColumn.ROWOFFSET)) {
long current = ctx.getIoCxt().getCurrentRow();
LongWritable old = (LongWritable) vcValues[i];
if (old == null) {
old = new LongWritable(current);
vcValues[i] = old;
continue;
}
if (current != old.get()) {
old.set(current);
}
} else if (vc.equals(VirtualColumn.RAWDATASIZE)) {
long current = 0L;
SerDeStats stats = deserializer.getSerDeStats();
if(stats != null) {
current = stats.getRawDataSize();
}
LongWritable old = (LongWritable) vcValues[i];
if (old == null) {
old = new LongWritable(current);
vcValues[i] = old;
continue;
}
if (current != old.get()) {
old.set(current);
}
}
}
return vcValues;
}
@Override
public void processOp(Object row, int tag) throws HiveException {
throw new HiveException("Hive 2 Internal error: should not be called!");
}
@Override
public String getName() {
return getOperatorName();
}
static public String getOperatorName() {
return "MAP";
}
@Override
public OperatorType getType() {
return null;
}
}
|
ql/src/java/org/apache/hadoop/hive/ql/exec/MapOperator.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.hive.ql.exec;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.hadoop.hive.ql.exec.mr.ExecMapperContext;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.VirtualColumn;
import org.apache.hadoop.hive.ql.plan.MapWork;
import org.apache.hadoop.hive.ql.plan.OperatorDesc;
import org.apache.hadoop.hive.ql.plan.PartitionDesc;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.ql.plan.TableScanDesc;
import org.apache.hadoop.hive.ql.plan.api.OperatorType;
import org.apache.hadoop.hive.serde2.Deserializer;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.SerDeStats;
import org.apache.hadoop.hive.serde2.SerDeUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters.Converter;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.util.StringUtils;
/**
* Map operator. This triggers overall map side processing. This is a little
* different from regular operators in that it starts off by processing a
* Writable data structure from a Table (instead of a Hive Object).
**/
public class MapOperator extends Operator<MapWork> implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
/**
* Counter.
*
*/
public static enum Counter {
DESERIALIZE_ERRORS
}
private final transient LongWritable deserialize_error_count = new LongWritable();
private final Map<MapInputPath, MapOpCtx> opCtxMap = new HashMap<MapInputPath, MapOpCtx>();
private final Map<Operator<? extends OperatorDesc>, MapOpCtx> childrenOpToOpCtxMap =
new HashMap<Operator<? extends OperatorDesc>, MapOpCtx>();
private transient MapOpCtx current;
private transient List<Operator<? extends OperatorDesc>> extraChildrenToClose = null;
private static class MapInputPath {
String path;
String alias;
Operator<?> op;
PartitionDesc partDesc;
/**
* @param path
* @param alias
* @param op
*/
public MapInputPath(String path, String alias, Operator<?> op, PartitionDesc partDesc) {
this.path = path;
this.alias = alias;
this.op = op;
this.partDesc = partDesc;
}
@Override
public boolean equals(Object o) {
if (o instanceof MapInputPath) {
MapInputPath mObj = (MapInputPath) o;
return path.equals(mObj.path) && alias.equals(mObj.alias)
&& op.equals(mObj.op);
}
return false;
}
@Override
public int hashCode() {
int ret = (path == null) ? 0 : path.hashCode();
ret += (alias == null) ? 0 : alias.hashCode();
ret += (op == null) ? 0 : op.hashCode();
return ret;
}
}
private static class MapOpCtx {
StructObjectInspector tblRawRowObjectInspector; // columns
StructObjectInspector partObjectInspector; // partition columns
StructObjectInspector vcsObjectInspector; // virtual columns
StructObjectInspector rowObjectInspector;
Converter partTblObjectInspectorConverter;
Object[] rowWithPart;
Object[] rowWithPartAndVC;
Deserializer deserializer;
String tableName;
String partName;
List<VirtualColumn> vcs;
Writable[] vcValues;
private boolean isPartitioned() {
return partObjectInspector != null;
}
private boolean hasVC() {
return vcsObjectInspector != null;
}
private Object readRow(Writable value) throws SerDeException {
return partTblObjectInspectorConverter.convert(deserializer.deserialize(value));
}
}
/**
* Initializes this map op as the root of the tree. It sets JobConf &
* MapRedWork and starts initialization of the operator tree rooted at this
* op.
*
* @param hconf
* @param mrwork
* @throws HiveException
*/
public void initializeAsRoot(Configuration hconf, MapWork mapWork)
throws HiveException {
setConf(mapWork);
setChildren(hconf);
initialize(hconf, null);
}
private MapOpCtx initObjectInspector(Configuration hconf, MapInputPath ctx,
Map<TableDesc, StructObjectInspector> convertedOI) throws Exception {
PartitionDesc pd = ctx.partDesc;
TableDesc td = pd.getTableDesc();
MapOpCtx opCtx = new MapOpCtx();
// Use table properties in case of unpartitioned tables,
// and the union of table properties and partition properties, with partition
// taking precedence
Properties partProps = isPartitioned(pd) ?
pd.getOverlayedProperties() : pd.getTableDesc().getProperties();
Map<String, String> partSpec = pd.getPartSpec();
opCtx.tableName = String.valueOf(partProps.getProperty("name"));
opCtx.partName = String.valueOf(partSpec);
Class serdeclass = pd.getDeserializerClass();
if (serdeclass == null) {
String className = checkSerdeClassName(pd.getSerdeClassName(), opCtx.tableName);
serdeclass = hconf.getClassByName(className);
}
opCtx.deserializer = (Deserializer) serdeclass.newInstance();
opCtx.deserializer.initialize(hconf, partProps);
StructObjectInspector partRawRowObjectInspector =
(StructObjectInspector) opCtx.deserializer.getObjectInspector();
opCtx.tblRawRowObjectInspector = convertedOI.get(td);
opCtx.partTblObjectInspectorConverter = ObjectInspectorConverters.getConverter(
partRawRowObjectInspector, opCtx.tblRawRowObjectInspector);
// Next check if this table has partitions and if so
// get the list of partition names as well as allocate
// the serdes for the partition columns
String pcols = partProps.getProperty(hive_metastoreConstants.META_TABLE_PARTITION_COLUMNS);
// Log LOG = LogFactory.getLog(MapOperator.class.getName());
if (pcols != null && pcols.length() > 0) {
String[] partKeys = pcols.trim().split("/");
List<String> partNames = new ArrayList<String>(partKeys.length);
Object[] partValues = new Object[partKeys.length];
List<ObjectInspector> partObjectInspectors = new ArrayList<ObjectInspector>(partKeys.length);
for (int i = 0; i < partKeys.length; i++) {
String key = partKeys[i];
partNames.add(key);
// Partitions do not exist for this table
if (partSpec == null) {
// for partitionless table, initialize partValue to null
partValues[i] = null;
} else {
partValues[i] = new Text(partSpec.get(key));
}
partObjectInspectors.add(PrimitiveObjectInspectorFactory.writableStringObjectInspector);
}
opCtx.rowWithPart = new Object[] {null, partValues};
opCtx.partObjectInspector = ObjectInspectorFactory
.getStandardStructObjectInspector(partNames, partObjectInspectors);
}
// The op may not be a TableScan for mapjoins
// Consider the query: select /*+MAPJOIN(a)*/ count(*) FROM T1 a JOIN T2 b ON a.key = b.key;
// In that case, it will be a Select, but the rowOI need not be ammended
if (ctx.op instanceof TableScanOperator) {
TableScanOperator tsOp = (TableScanOperator) ctx.op;
TableScanDesc tsDesc = tsOp.getConf();
if (tsDesc != null && tsDesc.hasVirtualCols()) {
opCtx.vcs = tsDesc.getVirtualCols();
opCtx.vcValues = new Writable[opCtx.vcs.size()];
opCtx.vcsObjectInspector = VirtualColumn.getVCSObjectInspector(opCtx.vcs);
if (opCtx.isPartitioned()) {
opCtx.rowWithPartAndVC = Arrays.copyOfRange(opCtx.rowWithPart, 0, 3);
} else {
opCtx.rowWithPartAndVC = new Object[2];
}
}
}
if (!opCtx.hasVC() && !opCtx.isPartitioned()) {
opCtx.rowObjectInspector = opCtx.tblRawRowObjectInspector;
return opCtx;
}
List<StructObjectInspector> inspectors = new ArrayList<StructObjectInspector>();
inspectors.add(opCtx.tblRawRowObjectInspector);
if (opCtx.isPartitioned()) {
inspectors.add(opCtx.partObjectInspector);
}
if (opCtx.hasVC()) {
inspectors.add(opCtx.vcsObjectInspector);
}
opCtx.rowObjectInspector = ObjectInspectorFactory.getUnionStructObjectInspector(inspectors);
return opCtx;
}
// Return the mapping for table descriptor to the expected table OI
/**
* Traverse all the partitions for a table, and get the OI for the table.
* Note that a conversion is required if any of the partition OI is different
* from the table OI. For eg. if the query references table T (partitions P1, P2),
* and P1's schema is same as T, whereas P2's scheme is different from T, conversion
* might be needed for both P1 and P2, since SettableOI might be needed for T
*/
private Map<TableDesc, StructObjectInspector> getConvertedOI(Configuration hconf)
throws HiveException {
Map<TableDesc, StructObjectInspector> tableDescOI =
new HashMap<TableDesc, StructObjectInspector>();
Set<TableDesc> identityConverterTableDesc = new HashSet<TableDesc>();
try {
for (String onefile : conf.getPathToAliases().keySet()) {
PartitionDesc pd = conf.getPathToPartitionInfo().get(onefile);
TableDesc tableDesc = pd.getTableDesc();
Properties tblProps = tableDesc.getProperties();
// If the partition does not exist, use table properties
Properties partProps = isPartitioned(pd) ? pd.getOverlayedProperties() : tblProps;
Class sdclass = pd.getDeserializerClass();
if (sdclass == null) {
String className = checkSerdeClassName(pd.getSerdeClassName(),
pd.getProperties().getProperty("name"));
sdclass = hconf.getClassByName(className);
}
Deserializer partDeserializer = (Deserializer) sdclass.newInstance();
partDeserializer.initialize(hconf, partProps);
StructObjectInspector partRawRowObjectInspector = (StructObjectInspector) partDeserializer
.getObjectInspector();
StructObjectInspector tblRawRowObjectInspector = tableDescOI.get(tableDesc);
if ((tblRawRowObjectInspector == null) ||
(identityConverterTableDesc.contains(tableDesc))) {
sdclass = tableDesc.getDeserializerClass();
if (sdclass == null) {
String className = checkSerdeClassName(tableDesc.getSerdeClassName(),
tableDesc.getProperties().getProperty("name"));
sdclass = hconf.getClassByName(className);
}
Deserializer tblDeserializer = (Deserializer) sdclass.newInstance();
tblDeserializer.initialize(hconf, tblProps);
tblRawRowObjectInspector =
(StructObjectInspector) ObjectInspectorConverters.getConvertedOI(
partRawRowObjectInspector,
tblDeserializer.getObjectInspector(), true);
if (identityConverterTableDesc.contains(tableDesc)) {
if (!partRawRowObjectInspector.equals(tblRawRowObjectInspector)) {
identityConverterTableDesc.remove(tableDesc);
}
}
else if (partRawRowObjectInspector.equals(tblRawRowObjectInspector)) {
identityConverterTableDesc.add(tableDesc);
}
tableDescOI.put(tableDesc, tblRawRowObjectInspector);
}
}
} catch (Exception e) {
throw new HiveException(e);
}
return tableDescOI;
}
private boolean isPartitioned(PartitionDesc pd) {
return pd.getPartSpec() != null && !pd.getPartSpec().isEmpty();
}
private String checkSerdeClassName(String className, String tableName) throws HiveException {
if (className == null || className.isEmpty()) {
throw new HiveException(
"SerDe class or the SerDe class name is not set for table: " + tableName);
}
return className;
}
public void setChildren(Configuration hconf) throws HiveException {
Path fpath = new Path(HiveConf.getVar(hconf,
HiveConf.ConfVars.HADOOPMAPFILENAME));
List<Operator<? extends OperatorDesc>> children =
new ArrayList<Operator<? extends OperatorDesc>>();
Map<TableDesc, StructObjectInspector> convertedOI = getConvertedOI(hconf);
try {
for (Map.Entry<String, ArrayList<String>> entry : conf.getPathToAliases().entrySet()) {
String onefile = entry.getKey();
List<String> aliases = entry.getValue();
Path onepath = new Path(onefile);
PartitionDesc partDesc = conf.getPathToPartitionInfo().get(onefile);
for (String onealias : aliases) {
Operator<? extends OperatorDesc> op = conf.getAliasToWork().get(onealias);
LOG.info("Adding alias " + onealias + " to work list for file "
+ onefile);
MapInputPath inp = new MapInputPath(onefile, onealias, op, partDesc);
if (opCtxMap.containsKey(inp)) {
continue;
}
MapOpCtx opCtx = initObjectInspector(hconf, inp, convertedOI);
opCtxMap.put(inp, opCtx);
op.setParentOperators(new ArrayList<Operator<? extends OperatorDesc>>());
op.getParentOperators().add(this);
// check for the operators who will process rows coming to this Map
// Operator
if (!onepath.toUri().relativize(fpath.toUri()).equals(fpath.toUri())) {
children.add(op);
childrenOpToOpCtxMap.put(op, opCtx);
LOG.info("dump " + op.getName() + " "
+ opCtxMap.get(inp).rowObjectInspector.getTypeName());
}
current = opCtx; // just need for TestOperators.testMapOperator
}
}
if (children.size() == 0) {
// didn't find match for input file path in configuration!
// serious problem ..
LOG.error("Configuration does not have any alias for path: "
+ fpath.toUri());
throw new HiveException("Configuration and input path are inconsistent");
}
// we found all the operators that we are supposed to process.
setChildOperators(children);
} catch (Exception e) {
throw new HiveException(e);
}
}
@Override
public void initializeOp(Configuration hconf) throws HiveException {
// set that parent initialization is done and call initialize on children
state = State.INIT;
statsMap.put(Counter.DESERIALIZE_ERRORS, deserialize_error_count);
List<Operator<? extends OperatorDesc>> children = getChildOperators();
for (Entry<Operator<? extends OperatorDesc>, MapOpCtx> entry : childrenOpToOpCtxMap
.entrySet()) {
Operator<? extends OperatorDesc> child = entry.getKey();
MapOpCtx mapOpCtx = entry.getValue();
// Add alias, table name, and partitions to hadoop conf so that their
// children will inherit these
HiveConf.setVar(hconf, HiveConf.ConfVars.HIVETABLENAME, mapOpCtx.tableName);
HiveConf.setVar(hconf, HiveConf.ConfVars.HIVEPARTITIONNAME, mapOpCtx.partName);
child.initialize(hconf, new ObjectInspector[] {mapOpCtx.rowObjectInspector});
}
for (Entry<MapInputPath, MapOpCtx> entry : opCtxMap.entrySet()) {
MapInputPath input = entry.getKey();
MapOpCtx mapOpCtx = entry.getValue();
// Add alias, table name, and partitions to hadoop conf so that their
// children will inherit these
HiveConf.setVar(hconf, HiveConf.ConfVars.HIVETABLENAME, mapOpCtx.tableName);
HiveConf.setVar(hconf, HiveConf.ConfVars.HIVEPARTITIONNAME, mapOpCtx.partName);
Operator<? extends OperatorDesc> op = input.op;
if (children.indexOf(op) == -1) {
// op is not in the children list, so need to remember it and close it afterwards
if (extraChildrenToClose == null) {
extraChildrenToClose = new ArrayList<Operator<? extends OperatorDesc>>();
}
extraChildrenToClose.add(op);
op.initialize(hconf, new ObjectInspector[] {entry.getValue().rowObjectInspector});
}
}
}
/**
* close extra child operators that are initialized but are not executed.
*/
@Override
public void closeOp(boolean abort) throws HiveException {
if (extraChildrenToClose != null) {
for (Operator<? extends OperatorDesc> op : extraChildrenToClose) {
op.close(abort);
}
}
}
// Find context for current input file
@Override
public void cleanUpInputFileChangedOp() throws HiveException {
Path fpath = normalizePath(getExecContext().getCurrentInputFile());
for (String onefile : conf.getPathToAliases().keySet()) {
Path onepath = normalizePath(onefile);
// check for the operators who will process rows coming to this Map
// Operator
if (onepath.toUri().relativize(fpath.toUri()).equals(fpath.toUri())) {
// not from this
continue;
}
PartitionDesc partDesc = conf.getPathToPartitionInfo().get(onefile);
for (String onealias : conf.getPathToAliases().get(onefile)) {
Operator<? extends OperatorDesc> op = conf.getAliasToWork().get(onealias);
MapInputPath inp = new MapInputPath(onefile, onealias, op, partDesc);
MapOpCtx context = opCtxMap.get(inp);
if (context != null) {
current = context;
LOG.info("Processing alias " + onealias + " for file " + onefile);
return;
}
}
}
throw new IllegalStateException("Invalid path " + fpath);
}
private Path normalizePath(String onefile) {
return new Path(onefile);
}
public void process(Writable value) throws HiveException {
// A mapper can span multiple files/partitions.
// The serializers need to be reset if the input file changed
ExecMapperContext context = getExecContext();
if (context != null && context.inputFileChanged()) {
// The child operators cleanup if input file has changed
cleanUpInputFileChanged();
}
Object row;
try {
row = current.readRow(value);
if (current.hasVC()) {
current.rowWithPartAndVC[0] = row;
if (context != null) {
populateVirtualColumnValues(context, current.vcs, current.vcValues, current.deserializer);
}
int vcPos = current.isPartitioned() ? 2 : 1;
current.rowWithPartAndVC[vcPos] = current.vcValues;
row = current.rowWithPartAndVC;
} else if (current.isPartitioned()) {
current.rowWithPart[0] = row;
row = current.rowWithPart;
}
} catch (Exception e) {
// Serialize the row and output.
String rawRowString;
try {
rawRowString = value.toString();
} catch (Exception e2) {
rawRowString = "[Error getting row data with exception " +
StringUtils.stringifyException(e2) + " ]";
}
// TODO: policy on deserialization errors
deserialize_error_count.set(deserialize_error_count.get() + 1);
throw new HiveException("Hive Runtime Error while processing writable " + rawRowString, e);
}
// The row has been converted to comply with table schema, irrespective of partition schema.
// So, use tblOI (and not partOI) for forwarding
try {
forward(row, current.rowObjectInspector);
} catch (Exception e) {
// Serialize the row and output the error message.
String rowString;
try {
rowString = SerDeUtils.getJSONString(row, current.rowObjectInspector);
} catch (Exception e2) {
rowString = "[Error getting row data with exception " +
StringUtils.stringifyException(e2) + " ]";
}
throw new HiveException("Hive Runtime Error while processing row " + rowString, e);
}
}
public static Writable[] populateVirtualColumnValues(ExecMapperContext ctx,
List<VirtualColumn> vcs, Writable[] vcValues, Deserializer deserializer) {
if (vcs == null) {
return vcValues;
}
if (vcValues == null) {
vcValues = new Writable[vcs.size()];
}
for (int i = 0; i < vcs.size(); i++) {
VirtualColumn vc = vcs.get(i);
if (vc.equals(VirtualColumn.FILENAME)) {
if (ctx.inputFileChanged()) {
vcValues[i] = new Text(ctx.getCurrentInputFile());
}
} else if (vc.equals(VirtualColumn.BLOCKOFFSET)) {
long current = ctx.getIoCxt().getCurrentBlockStart();
LongWritable old = (LongWritable) vcValues[i];
if (old == null) {
old = new LongWritable(current);
vcValues[i] = old;
continue;
}
if (current != old.get()) {
old.set(current);
}
} else if (vc.equals(VirtualColumn.ROWOFFSET)) {
long current = ctx.getIoCxt().getCurrentRow();
LongWritable old = (LongWritable) vcValues[i];
if (old == null) {
old = new LongWritable(current);
vcValues[i] = old;
continue;
}
if (current != old.get()) {
old.set(current);
}
} else if (vc.equals(VirtualColumn.RAWDATASIZE)) {
long current = 0L;
SerDeStats stats = deserializer.getSerDeStats();
if(stats != null) {
current = stats.getRawDataSize();
}
LongWritable old = (LongWritable) vcValues[i];
if (old == null) {
old = new LongWritable(current);
vcValues[i] = old;
continue;
}
if (current != old.get()) {
old.set(current);
}
}
}
return vcValues;
}
@Override
public void processOp(Object row, int tag) throws HiveException {
throw new HiveException("Hive 2 Internal error: should not be called!");
}
@Override
public String getName() {
return getOperatorName();
}
static public String getOperatorName() {
return "MAP";
}
@Override
public OperatorType getType() {
return null;
}
}
|
HIVE-4619 - Hive 0.11.0 is not working with pre-cdh3u6 and hadoop-0.23 (Navis via Brock Noland)
git-svn-id: c2303eb81cb646bce052f55f7f0d14f181a5956c@1521593 13f79535-47bb-0310-9956-ffa450edef68
|
ql/src/java/org/apache/hadoop/hive/ql/exec/MapOperator.java
|
HIVE-4619 - Hive 0.11.0 is not working with pre-cdh3u6 and hadoop-0.23 (Navis via Brock Noland)
|
|
Java
|
apache-2.0
|
c85fd123280cdda77c4d1c4aabd0376dd114f065
| 0
|
EsupPortail/esup-uportal,jl1955/uPortal5,EdiaEducationTechnology/uPortal,stalele/uPortal,joansmith/uPortal,doodelicious/uPortal,Mines-Albi/esup-uportal,doodelicious/uPortal,phillips1021/uPortal,jhelmer-unicon/uPortal,MichaelVose2/uPortal,mgillian/uPortal,joansmith/uPortal,EsupPortail/esup-uportal,GIP-RECIA/esup-uportal,jl1955/uPortal5,vbonamy/esup-uportal,GIP-RECIA/esup-uportal,stalele/uPortal,stalele/uPortal,timlevett/uPortal,cousquer/uPortal,drewwills/uPortal,jonathanmtran/uPortal,drewwills/uPortal,chasegawa/uPortal,vertein/uPortal,ChristianMurphy/uPortal,bjagg/uPortal,EdiaEducationTechnology/uPortal,andrewstuart/uPortal,chasegawa/uPortal,chasegawa/uPortal,Jasig/SSP-Platform,ASU-Capstone/uPortal,Jasig/uPortal,doodelicious/uPortal,jonathanmtran/uPortal,Mines-Albi/esup-uportal,MichaelVose2/uPortal,EsupPortail/esup-uportal,vertein/uPortal,apetro/uPortal,groybal/uPortal,EsupPortail/esup-uportal,Mines-Albi/esup-uportal,bjagg/uPortal,mgillian/uPortal,ASU-Capstone/uPortal-Forked,timlevett/uPortal,vbonamy/esup-uportal,GIP-RECIA/esup-uportal,ASU-Capstone/uPortal-Forked,pspaude/uPortal,ASU-Capstone/uPortal-Forked,Jasig/SSP-Platform,timlevett/uPortal,groybal/uPortal,jhelmer-unicon/uPortal,apetro/uPortal,joansmith/uPortal,vertein/uPortal,pspaude/uPortal,kole9273/uPortal,ChristianMurphy/uPortal,phillips1021/uPortal,vbonamy/esup-uportal,doodelicious/uPortal,kole9273/uPortal,ASU-Capstone/uPortal,jhelmer-unicon/uPortal,cousquer/uPortal,Jasig/uPortal-start,Mines-Albi/esup-uportal,chasegawa/uPortal,Jasig/SSP-Platform,MichaelVose2/uPortal,GIP-RECIA/esco-portail,mgillian/uPortal,jameswennmacher/uPortal,vertein/uPortal,ASU-Capstone/uPortal-Forked,GIP-RECIA/esup-uportal,GIP-RECIA/esco-portail,timlevett/uPortal,kole9273/uPortal,Jasig/uPortal-start,kole9273/uPortal,andrewstuart/uPortal,apetro/uPortal,joansmith/uPortal,jameswennmacher/uPortal,ASU-Capstone/uPortal,GIP-RECIA/esup-uportal,bjagg/uPortal,Jasig/uPortal,vbonamy/esup-uportal,jl1955/uPortal5,jonathanmtran/uPortal,EdiaEducationTechnology/uPortal,kole9273/uPortal,drewwills/uPortal,stalele/uPortal,jhelmer-unicon/uPortal,GIP-RECIA/esco-portail,ASU-Capstone/uPortal-Forked,EsupPortail/esup-uportal,groybal/uPortal,Jasig/SSP-Platform,ASU-Capstone/uPortal,ASU-Capstone/uPortal,vbonamy/esup-uportal,andrewstuart/uPortal,Jasig/SSP-Platform,jhelmer-unicon/uPortal,doodelicious/uPortal,pspaude/uPortal,andrewstuart/uPortal,MichaelVose2/uPortal,apetro/uPortal,cousquer/uPortal,ChristianMurphy/uPortal,phillips1021/uPortal,Mines-Albi/esup-uportal,stalele/uPortal,jl1955/uPortal5,phillips1021/uPortal,pspaude/uPortal,drewwills/uPortal,andrewstuart/uPortal,EdiaEducationTechnology/uPortal,jameswennmacher/uPortal,groybal/uPortal,chasegawa/uPortal,jameswennmacher/uPortal,Jasig/uPortal,MichaelVose2/uPortal,jameswennmacher/uPortal,joansmith/uPortal,groybal/uPortal,apetro/uPortal,phillips1021/uPortal,jl1955/uPortal5
|
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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.jasig.portal.groups.filesystem;
import org.jasig.portal.groups.ComponentGroupServiceDescriptor;
import org.jasig.portal.groups.GroupsException;
import org.jasig.portal.groups.IEntityGroupStore;
import org.jasig.portal.groups.IEntityGroupStoreFactory;
import org.jasig.portal.groups.IEntityStore;
import org.jasig.portal.groups.IEntityStoreFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Returns <code>IEntityGroupStore</code> and <code>IEntityStore</code>
* implementations for the file system group service.
*
* @author Dan Ellentuck
* @version $Revision$
*/
public class FileSystemGroupStoreFactory implements IEntityGroupStoreFactory,
IEntityStoreFactory {
private static final Log log = LogFactory.getLog(FileSystemGroupStoreFactory.class);
/**
* ReferenceGroupServiceFactory constructor.
*/
public FileSystemGroupStoreFactory() {
super();
}
/**
* @return org.jasig.portal.groups.filesystem.FileSystemGroupStore
*/
protected static FileSystemGroupStore getGroupStore() throws GroupsException
{
return new FileSystemGroupStore();
}
/**
* Return an instance of the entity store implementation.
* @return IEntityStore
* @exception GroupsException
*/
public IEntityStore newEntityStore() throws GroupsException
{
return getGroupStore();
}
/**
* Return an instance of the entity group store implementation.
* @return IEntityGroupStore
* @exception GroupsException
* @deprecated needs to be fixed, don't call
*/
@Deprecated()
public IEntityGroupStore newGroupStore() throws GroupsException
{
throw new UnsupportedOperationException("unimplemented method called");
}
/**
* Return an instance of the entity group store implementation.
* @return IEntityGroupStore
* @exception GroupsException
*/
public IEntityGroupStore newGroupStore(ComponentGroupServiceDescriptor svcDescriptor)
throws GroupsException
{
FileSystemGroupStore fsGroupStore = (FileSystemGroupStore)getGroupStore();
String groupsRoot = (String)svcDescriptor.get("groupsRoot");
if ( groupsRoot != null )
{ fsGroupStore.setGroupsRootPath(groupsRoot); }
return fsGroupStore;
}
}
|
uportal-impl/src/main/java/org/jasig/portal/groups/filesystem/FileSystemGroupStoreFactory.java
|
/**
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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.jasig.portal.groups.filesystem;
import org.jasig.portal.groups.ComponentGroupServiceDescriptor;
import org.jasig.portal.groups.GroupsException;
import org.jasig.portal.groups.IEntityGroupStore;
import org.jasig.portal.groups.IEntityGroupStoreFactory;
import org.jasig.portal.groups.IEntityStore;
import org.jasig.portal.groups.IEntityStoreFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Returns <code>IEntityGroupStore</code> and <code>IEntityStore</code>
* implementations for the file system group service.
*
* @author Dan Ellentuck
* @version $Revision$
*/
public class FileSystemGroupStoreFactory implements IEntityGroupStoreFactory,
IEntityStoreFactory {
private static final Log log = LogFactory.getLog(FileSystemGroupStoreFactory.class);
/**
* ReferenceGroupServiceFactory constructor.
*/
public FileSystemGroupStoreFactory() {
super();
}
/**
* @return org.jasig.portal.groups.filesystem.FileSystemGroupStore
*/
protected static FileSystemGroupStore getGroupStore() throws GroupsException
{
return new FileSystemGroupStore();
}
/**
* Return an instance of the entity store implementation.
* @return IEntityStore
* @exception GroupsException
*/
public IEntityStore newEntityStore() throws GroupsException
{
return getGroupStore();
}
/**
* Return an instance of the entity group store implementation.
* @return IEntityGroupStore
* @exception GroupsException
*/
public IEntityGroupStore newGroupStore() throws GroupsException
{
return newGroupStore(null);
}
/**
* Return an instance of the entity group store implementation.
* @return IEntityGroupStore
* @exception GroupsException
*/
public IEntityGroupStore newGroupStore(ComponentGroupServiceDescriptor svcDescriptor)
throws GroupsException
{
FileSystemGroupStore fsGroupStore = (FileSystemGroupStore)getGroupStore();
String groupsRoot = (String)svcDescriptor.get("groupsRoot");
if ( groupsRoot != null )
{ fsGroupStore.setGroupsRootPath(groupsRoot); }
return fsGroupStore;
}
}
|
UP-2387 Fix by throwing an exception
git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@21129 f5dbab47-78f9-eb45-b975-e544023573eb
|
uportal-impl/src/main/java/org/jasig/portal/groups/filesystem/FileSystemGroupStoreFactory.java
|
UP-2387 Fix by throwing an exception
|
|
Java
|
apache-2.0
|
ecb7bd2c640989d88decfd2771e26b7e24398640
| 0
|
cushon/bazel,cushon/bazel,cushon/bazel,meteorcloudy/bazel,safarmer/bazel,twitter-forks/bazel,bazelbuild/bazel,twitter-forks/bazel,perezd/bazel,katre/bazel,cushon/bazel,ButterflyNetwork/bazel,perezd/bazel,bazelbuild/bazel,meteorcloudy/bazel,twitter-forks/bazel,meteorcloudy/bazel,safarmer/bazel,ButterflyNetwork/bazel,cushon/bazel,katre/bazel,ButterflyNetwork/bazel,cushon/bazel,meteorcloudy/bazel,katre/bazel,perezd/bazel,bazelbuild/bazel,ButterflyNetwork/bazel,bazelbuild/bazel,perezd/bazel,meteorcloudy/bazel,bazelbuild/bazel,twitter-forks/bazel,safarmer/bazel,perezd/bazel,twitter-forks/bazel,katre/bazel,safarmer/bazel,twitter-forks/bazel,safarmer/bazel,meteorcloudy/bazel,meteorcloudy/bazel,katre/bazel,katre/bazel,perezd/bazel,ButterflyNetwork/bazel,safarmer/bazel,ButterflyNetwork/bazel,twitter-forks/bazel,perezd/bazel,bazelbuild/bazel
|
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// 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.devtools.build.lib.rules.java;
import static com.google.devtools.build.lib.packages.BuildType.NODEP_LABEL_LIST;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.shell.ShellUtils;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.List;
/** Utility methods for use by Java-related parts of Bazel. */
// TODO(bazel-team): Merge with JavaUtil.
public abstract class JavaHelper {
private JavaHelper() {}
/**
* Returns the java launcher implementation for the given target, if any. A null return value
* means "use the JDK launcher".
*/
public static TransitiveInfoCollection launcherForTarget(
JavaSemantics semantics, RuleContext ruleContext) {
String launcher = filterLauncherForTarget(ruleContext);
return (launcher == null) ? null : ruleContext.getPrerequisite(launcher);
}
/**
* Returns the java launcher artifact for the given target, if any. A null return value means "use
* the JDK launcher".
*/
public static Artifact launcherArtifactForTarget(
JavaSemantics semantics, RuleContext ruleContext) {
String launcher = filterLauncherForTarget(ruleContext);
return (launcher == null) ? null : ruleContext.getPrerequisiteArtifact(launcher);
}
/**
* Control structure abstraction for safely extracting a prereq from the launcher attribute or
* --java_launcher flag.
*/
private static String filterLauncherForTarget(RuleContext ruleContext) {
// create_executable=0 disables the launcher
if (ruleContext.getRule().isAttrDefined("create_executable", Type.BOOLEAN)
&& !ruleContext.attributes().get("create_executable", Type.BOOLEAN)) {
return null;
}
// BUILD rule "launcher" attribute
if (ruleContext.getRule().isAttrDefined("launcher", BuildType.LABEL)
&& ruleContext.attributes().get("launcher", BuildType.LABEL) != null) {
if (isJdkLauncher(ruleContext, ruleContext.attributes().get("launcher", BuildType.LABEL))) {
return null;
}
return "launcher";
}
// Blaze flag --java_launcher
JavaConfiguration javaConfig = ruleContext.getFragment(JavaConfiguration.class);
if (ruleContext.getRule().isAttrDefined(":java_launcher", BuildType.LABEL)
&& javaConfig.getJavaLauncherLabel() != null
&& !isJdkLauncher(ruleContext, javaConfig.getJavaLauncherLabel())) {
return ":java_launcher";
}
return null;
}
/**
* Javac options require special processing - People use them and expect the options to be
* tokenized.
*/
public static List<String> tokenizeJavaOptions(Iterable<String> inOpts) {
// Ideally, this would be in the options parser. Unfortunately,
// the options parser can't handle a converter that expands
// from a value X into a List<X> and allow-multiple at the
// same time.
List<String> result = new ArrayList<>();
for (String current : inOpts) {
try {
ShellUtils.tokenize(result, current);
} catch (ShellUtils.TokenizationException ex) {
// Tokenization failed; this likely means that the user
// did not want tokenization to happen on their argument.
// (Any tokenization where we should produce an error
// has already been done by the shell that invoked
// blaze). Therefore, pass the argument through to
// the tool, so that we can see the original error.
result.add(current);
}
}
return result;
}
public static PathFragment getJavaResourcePath(
JavaSemantics semantics, RuleContext ruleContext, Artifact resource) {
PathFragment resourcePath = resource.getRepositoryRelativePath();
if (!ruleContext.attributes().has("resource_strip_prefix", Type.STRING)
|| !ruleContext.attributes().isAttributeValueExplicitlySpecified("resource_strip_prefix")) {
return semantics.getDefaultJavaResourcePath(resourcePath);
}
PathFragment prefix =
PathFragment.create(ruleContext.attributes().get("resource_strip_prefix", Type.STRING));
if (!resourcePath.startsWith(prefix)) {
ruleContext.attributeError(
"resource_strip_prefix",
String.format(
"Resource file '%s' is not under the specified prefix to strip", resourcePath));
return resourcePath;
}
return resourcePath.relativeTo(prefix);
}
/**
* Returns true if the given Label is of the pseudo-cc_binary that tells Bazel a Java target's
* JAVABIN is never to be replaced by the contents of --java_launcher; only the JDK's launcher
* will ever be used.
*/
public static boolean isJdkLauncher(RuleContext ruleContext, Label label) {
if (!ruleContext.attributes().has("$no_launcher")) {
return false;
}
List<Label> noLauncherAttribute =
ruleContext.attributes().get("$no_launcher", NODEP_LABEL_LIST);
return noLauncherAttribute != null && noLauncherAttribute.contains(label);
}
}
|
src/main/java/com/google/devtools/build/lib/rules/java/JavaHelper.java
|
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// 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.devtools.build.lib.rules.java;
import static com.google.devtools.build.lib.packages.BuildType.NODEP_LABEL_LIST;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.BuildType;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.shell.ShellUtils;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.List;
import net.starlark.java.eval.StarlarkSemantics;
/** Utility methods for use by Java-related parts of Bazel. */
// TODO(bazel-team): Merge with JavaUtil.
public abstract class JavaHelper {
private JavaHelper() {}
/**
* Returns the java launcher implementation for the given target, if any. A null return value
* means "use the JDK launcher".
*/
public static TransitiveInfoCollection launcherForTarget(
JavaSemantics semantics, RuleContext ruleContext) {
String launcher = filterLauncherForTarget(ruleContext);
return (launcher == null) ? null : ruleContext.getPrerequisite(launcher);
}
/**
* Returns the java launcher artifact for the given target, if any. A null return value means "use
* the JDK launcher".
*/
public static Artifact launcherArtifactForTarget(
JavaSemantics semantics, RuleContext ruleContext) {
String launcher = filterLauncherForTarget(ruleContext);
return (launcher == null) ? null : ruleContext.getPrerequisiteArtifact(launcher);
}
/**
* Control structure abstraction for safely extracting a prereq from the launcher attribute or
* --java_launcher flag.
*/
private static String filterLauncherForTarget(RuleContext ruleContext) {
// create_executable=0 disables the launcher
if (ruleContext.getRule().isAttrDefined("create_executable", Type.BOOLEAN)
&& !ruleContext.attributes().get("create_executable", Type.BOOLEAN)) {
return null;
}
// BUILD rule "launcher" attribute
if (ruleContext.getRule().isAttrDefined("launcher", BuildType.LABEL)
&& ruleContext.attributes().get("launcher", BuildType.LABEL) != null) {
if (isJdkLauncher(ruleContext, ruleContext.attributes().get("launcher", BuildType.LABEL))) {
return null;
}
return "launcher";
}
// Blaze flag --java_launcher
JavaConfiguration javaConfig = ruleContext.getFragment(JavaConfiguration.class);
if (ruleContext.getRule().isAttrDefined(":java_launcher", BuildType.LABEL)
&& javaConfig.getJavaLauncherLabel() != null
&& !isJdkLauncher(ruleContext, javaConfig.getJavaLauncherLabel())) {
return ":java_launcher";
}
return null;
}
/**
* Javac options require special processing - People use them and expect the options to be
* tokenized.
*/
public static List<String> tokenizeJavaOptions(Iterable<String> inOpts) {
// Ideally, this would be in the options parser. Unfortunately,
// the options parser can't handle a converter that expands
// from a value X into a List<X> and allow-multiple at the
// same time.
List<String> result = new ArrayList<>();
for (String current : inOpts) {
try {
ShellUtils.tokenize(result, current);
} catch (ShellUtils.TokenizationException ex) {
// Tokenization failed; this likely means that the user
// did not want tokenization to happen on their argument.
// (Any tokenization where we should produce an error
// has already been done by the shell that invoked
// blaze). Therefore, pass the argument through to
// the tool, so that we can see the original error.
result.add(current);
}
}
return result;
}
public static PathFragment getJavaResourcePath(
JavaSemantics semantics, RuleContext ruleContext, Artifact resource)
throws InterruptedException {
PathFragment resourcePath = resource.getOutputDirRelativePath();
StarlarkSemantics starlarkSemantics =
ruleContext.getAnalysisEnvironment().getStarlarkSemantics();
if (!ruleContext.getLabel().getWorkspaceRoot(starlarkSemantics).isEmpty()) {
PathFragment workspace =
PathFragment.create(ruleContext.getLabel().getWorkspaceRoot(starlarkSemantics));
resourcePath = resourcePath.relativeTo(workspace);
}
if (!ruleContext.attributes().has("resource_strip_prefix", Type.STRING)
|| !ruleContext.attributes().isAttributeValueExplicitlySpecified("resource_strip_prefix")) {
return semantics.getDefaultJavaResourcePath(resourcePath);
}
PathFragment prefix =
PathFragment.create(ruleContext.attributes().get("resource_strip_prefix", Type.STRING));
if (!resourcePath.startsWith(prefix)) {
ruleContext.attributeError(
"resource_strip_prefix",
String.format(
"Resource file '%s' is not under the specified prefix to strip", resourcePath));
return resourcePath;
}
return resourcePath.relativeTo(prefix);
}
/**
* Returns true if the given Label is of the pseudo-cc_binary that tells Bazel a Java target's
* JAVABIN is never to be replaced by the contents of --java_launcher; only the JDK's launcher
* will ever be used.
*/
public static boolean isJdkLauncher(RuleContext ruleContext, Label label) {
if (!ruleContext.attributes().has("$no_launcher")) {
return false;
}
List<Label> noLauncherAttribute =
ruleContext.attributes().get("$no_launcher", NODEP_LABEL_LIST);
return noLauncherAttribute != null && noLauncherAttribute.contains(label);
}
}
|
Replace Artifact#getOutputDirRelativePath call in JavaHelper#getJavaResourcePath with getRepositoryRelativePath.
PiperOrigin-RevId: 337296892
|
src/main/java/com/google/devtools/build/lib/rules/java/JavaHelper.java
|
Replace Artifact#getOutputDirRelativePath call in JavaHelper#getJavaResourcePath with getRepositoryRelativePath.
|
|
Java
|
apache-2.0
|
b0f824ca4dee6463c619b9564e197091798a86aa
| 0
|
Governance/overlord-commons,Governance/overlord-commons
|
/*
* Copyright 2013 JBoss 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 org.overlord.commons.gwt.client.local.widgets;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.AttachEvent.Handler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.TextBox;
import java.util.Date;
import javax.annotation.PostConstruct;
/**
* Like a text box, except it deals with dates and presents the user with
* a calendar picker widget.
*
* @author eric.wittmann@redhat.com
*/
public class DateBox extends TextBox {
private static final String DEFAULT_DATE_FORMAT = "mm/dd/yyyy"; //$NON-NLS-1$
private static int cidCounter = 1;
private static String generateUniqueCid() {
return "cid-" + cidCounter++; //$NON-NLS-1$
}
private String cid;
/**
* Constructor.
*/
public DateBox() {
}
/**
* Called after construction.
*/
@PostConstruct
protected void postConstruct() {
addAttachHandler(new Handler() {
@Override
public void onAttachOrDetach(AttachEvent event) {
if (event.isAttached()) {
cid = generateUniqueCid();
getElement().addClassName(cid);
initPicker(cid);
} else {
removePicker(cid);
}
}
});
}
/**
* Initializes the bootstrap-datepicker javascript.
*/
protected native void initPicker(String cid) /*-{
var selector = '.' + cid;
$wnd.jQuery(selector).datepicker({
autoclose: true,
todayBtn: true,
todayHighlight: true
});
$wnd.jQuery(selector).change(function () {
});
}-*/;
/**
* Removes the bootstrap-datepicker from the DOM and cleans up all events.
*/
protected native void removePicker(String cid) /*-{
var selector = '.' + cid;
$wnd.jQuery(selector).datepicker('remove');
}-*/;
/**
* @return the current value as a {@link Date} or null if empty
*/
public Date getDateValue() {
return parseDate(getValue());
}
/**
* Parses the given value as a date using the configured date format.
* @param value
*/
private Date parseDate(String value) {
if (value == null || "".equals(value)) //$NON-NLS-1$
return null;
DateTimeFormat format = getFormat();
return format.parse(value);
}
/**
* @param value the new {@link Date} value
*/
public void setDateValue(Date value) {
String v = formatDate(value);
if (v == null)
v = ""; //$NON-NLS-1$
setValue(v);
}
/**
* Formats the date using the configured date format.
* @param value
* @return the Date formatted as a string or null if the input is null
*/
private String formatDate(Date value) {
if (value == null)
return null;
DateTimeFormat format = getFormat();
return format.format(value);
}
/**
* Gets the format.
*/
private DateTimeFormat getFormat() {
String strFmt = DEFAULT_DATE_FORMAT;
if (getElement().hasAttribute("data-date-format")) { //$NON-NLS-1$
strFmt = getElement().getAttribute("data-date-format"); //$NON-NLS-1$
}
return DateTimeFormat.getFormat(strFmt);
}
/**
* Sets the date format used by this instance and by bootstrap-datepicker for
* this date box.
* @param format
*/
public void setDateFormat(String format) {
getElement().setAttribute("data-date-format", format); //$NON-NLS-1$
}
}
|
overlord-commons-gwt/src/main/java/org/overlord/commons/gwt/client/local/widgets/DateBox.java
|
/*
* Copyright 2013 JBoss 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 org.overlord.commons.gwt.client.local.widgets;
import java.util.Date;
import javax.annotation.PostConstruct;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.AttachEvent.Handler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.TextBox;
/**
* Like a text box, except it deals with dates and presents the user with
* a calendar picker widget.
*
* @author eric.wittmann@redhat.com
*/
public class DateBox extends TextBox {
private static final String DEFAULT_DATE_FORMAT = "mm/dd/yyyy"; //$NON-NLS-1$
private static int cidCounter = 1;
private static String generateUniqueCid() {
return "cid-" + cidCounter++; //$NON-NLS-1$
}
private String cid;
/**
* Constructor.
*/
public DateBox() {
}
/**
* Called after construction.
*/
@PostConstruct
protected void postConstruct() {
addAttachHandler(new Handler() {
@Override
public void onAttachOrDetach(AttachEvent event) {
if (event.isAttached()) {
cid = generateUniqueCid();
getElement().addClassName(cid);
initPicker(cid);
} else {
removePicker(cid);
}
}
});
}
/**
* Initializes the bootstrap-datepicker javascript.
*/
protected native void initPicker(String cid) /*-{
var selector = '.' + cid;
$wnd.jQuery(selector).datepicker({
autoclose: true,
todayBtn: true,
todayHighlight: true
});
}-*/;
/**
* Removes the bootstrap-datepicker from the DOM and cleans up all events.
*/
protected native void removePicker(String cid) /*-{
var selector = '.' + cid;
$wnd.jQuery(selector).datepicker('remove');
}-*/;
/**
* @return the current value as a {@link Date} or null if empty
*/
public Date getDateValue() {
return parseDate(getValue());
}
/**
* Parses the given value as a date using the configured date format.
* @param value
*/
private Date parseDate(String value) {
if (value == null || "".equals(value)) //$NON-NLS-1$
return null;
DateTimeFormat format = getFormat();
return format.parse(value);
}
/**
* @param value the new {@link Date} value
*/
public void setDateValue(Date value) {
String v = formatDate(value);
if (v == null)
v = ""; //$NON-NLS-1$
setValue(v);
}
/**
* Formats the date using the configured date format.
* @param value
* @return the Date formatted as a string or null if the input is null
*/
private String formatDate(Date value) {
if (value == null)
return null;
DateTimeFormat format = getFormat();
return format.format(value);
}
/**
* Gets the format.
*/
private DateTimeFormat getFormat() {
String strFmt = DEFAULT_DATE_FORMAT;
if (getElement().hasAttribute("data-date-format")) { //$NON-NLS-1$
strFmt = getElement().getAttribute("data-date-format"); //$NON-NLS-1$
}
return DateTimeFormat.getFormat(strFmt);
}
/**
* Sets the date format used by this instance and by bootstrap-datepicker for
* this date box.
* @param format
*/
public void setDateFormat(String format) {
getElement().setAttribute("data-date-format", format); //$NON-NLS-1$
}
}
|
ENTESB-4123 Time Filter does not propagate its value to query string
|
overlord-commons-gwt/src/main/java/org/overlord/commons/gwt/client/local/widgets/DateBox.java
|
ENTESB-4123 Time Filter does not propagate its value to query string
|
|
Java
|
apache-2.0
|
7f8bffc5a2051d008a45f70a2a4ab7c8d9cf5bcb
| 0
|
oehf/ipf,oehf/ipf,oehf/ipf,krasserm/ipf,krasserm/ipf,oehf/ipf
|
/*
* Copyright 2009 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 org.openehealth.ipf.commons.ihe.hl7v3;
import java.io.ByteArrayInputStream;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.lang.Validate;
import org.openehealth.ipf.commons.core.modules.api.ValidationException;
import org.openehealth.ipf.commons.core.modules.api.Validator;
import org.openehealth.ipf.commons.xml.XsdValidator;
/**
* XSD-based validator for HL7 v3 messages.
* @author Dmytro Rud
*/
public class Hl7v3Validator implements Validator<String, Collection<String>> {
private static final Pattern ROOT_ELEMENT_PATTERN = Pattern.compile(
"(?:\\s*<\\!--.*?-->)*" + // optional comments before prolog (are they allowed?)
"(?:\\s*<\\?xml.+?\\?>(?:\\s*<\\!--.*?-->)*)?" + // optional prolog and comments after it
"\\s*<(?:[\\w\\.-]+?:)?([\\w\\.-]+)(?:\\s|(?:/?>))" // open tag of the root element
);
private static final String XSD_PATH = "schema/HL7V3/NE2008/multicacheschemas/";
private static XsdValidator XSD_VALIDATOR;
public static XsdValidator getXsdValidator() {
if (XSD_VALIDATOR == null){
XSD_VALIDATOR = new XsdValidator(Hl7v3Validator.class.getClassLoader());
}
return XSD_VALIDATOR;
}
/**
* Returns path to the XML Schema document which contains the definition
* of the root HL7 v3 element with the given name.
*/
public static String getXsdPathForElement(String rootElementName) {
return new StringBuilder(XSD_PATH)
.append(rootElementName)
.append(".xsd")
.toString();
}
/**
* Checks whether the given String seems to represent an XML document
* and whether its root element is a valid one.
*
* @param message
* a String which should contain an HL7 v3 XML document.
* @param validRootElementNames
* list of valid root element names (with suffixes).
* @return name of the extracted root element without suffix
* (i.e. <code>QUQI_IN000003UV01</code> instead of
* <code>QUQI_IN000003UV01_Cancel</code>).
* @throws ValidationException
* when the given String does not contain XML payload
* or the root element is not valid.
*/
public static String getRootElementName(String message, Collection<String> validRootElementNames) {
Matcher matcher = ROOT_ELEMENT_PATTERN.matcher(message);
if(( ! matcher.find()) || (matcher.start() != 0)) {
throw new ValidationException("Cannot extract root element, probably bad XML");
}
String rootElementName = matcher.group(1);
if( ! validRootElementNames.contains(rootElementName)) {
throw new ValidationException("Invalid root element '" + rootElementName + "'");
}
int pos1 = rootElementName.indexOf('_');
int pos2 = rootElementName.indexOf('_', pos1 + 1);
return (pos2 > 0) ? rootElementName.substring(0, pos2) : rootElementName;
}
/**
* Converts the given XML string to a Source object.
*/
public static Source getSource(String message) {
return new StreamSource(new ByteArrayInputStream(message.getBytes()));
}
/**
* Validates the given HL7 v3 message.
*/
@Override
public void validate(String message, Collection<String> validRootElementNames) throws ValidationException {
Validate.notNull(message, "message");
Validate.notEmpty(validRootElementNames, "list of valid root element names");
String rootElementName = getRootElementName(message, validRootElementNames);
Source source = getSource(message);
String xsdPath = getXsdPathForElement(rootElementName);
getXsdValidator().validate(source, xsdPath);
}
}
|
commons/ihe/hl7v3/src/main/java/org/openehealth/ipf/commons/ihe/hl7v3/Hl7v3Validator.java
|
/*
* Copyright 2009 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 org.openehealth.ipf.commons.ihe.hl7v3;
import java.io.ByteArrayInputStream;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.lang.Validate;
import org.openehealth.ipf.commons.core.modules.api.ValidationException;
import org.openehealth.ipf.commons.core.modules.api.Validator;
import org.openehealth.ipf.commons.xml.XsdValidator;
/**
* XSD-based validator for HL7 v3 messages.
* @author Dmytro Rud
*/
public class Hl7v3Validator implements Validator<String, Collection<String>> {
private static final Pattern ROOT_ELEMENT_PATTERN = Pattern.compile(
"(?:\\s*<\\!--.*?-->)*" + // optional comments before prolog (are they allowed?)
"(?:\\s*<\\?xml.+?\\?>(?:\\s*<\\!--.*?-->)*)?" + // optional prolog and comments after it
"\\s*<(?:[\\w\\.-]+?:)?([\\w\\.-]+)(?:\\s|(?:/?>))" // open tag of the root element
);
private static final String XSD_PATH = "schema/HL7V3/NE2008/multicacheschemas/";
public static XsdValidator getXsdValidator() {
return new XsdValidator(Hl7v3Validator.class.getClassLoader());
}
/**
* Returns path to the XML Schema document which contains the definition
* of the root HL7 v3 element with the given name.
*/
public static String getXsdPathForElement(String rootElementName) {
return new StringBuilder(XSD_PATH)
.append(rootElementName)
.append(".xsd")
.toString();
}
/**
* Checks whether the given String seems to represent an XML document
* and whether its root element is a valid one.
*
* @param message
* a String which should contain an HL7 v3 XML document.
* @param validRootElementNames
* list of valid root element names (with suffixes).
* @return name of the extracted root element without suffix
* (i.e. <code>QUQI_IN000003UV01</code> instead of
* <code>QUQI_IN000003UV01_Cancel</code>).
* @throws ValidationException
* when the given String does not contain XML payload
* or the root element is not valid.
*/
public static String getRootElementName(String message, Collection<String> validRootElementNames) {
Matcher matcher = ROOT_ELEMENT_PATTERN.matcher(message);
if(( ! matcher.find()) || (matcher.start() != 0)) {
throw new ValidationException("Cannot extract root element, probably bad XML");
}
String rootElementName = matcher.group(1);
if( ! validRootElementNames.contains(rootElementName)) {
throw new ValidationException("Invalid root element '" + rootElementName + "'");
}
int pos1 = rootElementName.indexOf('_');
int pos2 = rootElementName.indexOf('_', pos1 + 1);
return (pos2 > 0) ? rootElementName.substring(0, pos2) : rootElementName;
}
/**
* Converts the given XML string to a Source object.
*/
public static Source getSource(String message) {
return new StreamSource(new ByteArrayInputStream(message.getBytes()));
}
/**
* Validates the given HL7 v3 message.
*/
@Override
public void validate(String message, Collection<String> validRootElementNames) throws ValidationException {
Validate.notNull(message, "message");
Validate.notEmpty(validRootElementNames, "list of valid root element names");
String rootElementName = getRootElementName(message, validRootElementNames);
Source source = getSource(message);
String xsdPath = getXsdPathForElement(rootElementName);
getXsdValidator().validate(source, xsdPath);
}
}
|
refactoring
git-svn-id: 15d4771d83c46956b550e66b034a1e73d7ee3103@1148 d594d982-de57-441b-9a2b-38caaf397e83
|
commons/ihe/hl7v3/src/main/java/org/openehealth/ipf/commons/ihe/hl7v3/Hl7v3Validator.java
|
refactoring
|
|
Java
|
apache-2.0
|
e303ca71cc351eb4b618948177e45369237523e0
| 0
|
yokuyuki/Enrichr,yokuyuki/Enrichr,yokuyuki/Enrichr
|
package edu.mssm.pharm.maayanlab.Enrichr;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Set;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import edu.mssm.pharm.maayanlab.FileUtils;
import edu.mssm.pharm.maayanlab.HibernateUtil;
import edu.mssm.pharm.maayanlab.JSONify;
import edu.mssm.pharm.maayanlab.math.HashFunctions;
@WebServlet(urlPatterns = {"/account", "/login", "/register", "/forgot", "/reset", "/status", "/logout", "/contribute", "/delete"})
public class Account extends HttpServlet {
private static final long serialVersionUID = 19776535963654466L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
JSONify json = new JSONify();
HttpSession httpSession = request.getSession();
User user = (User) httpSession.getAttribute("user");
if (request.getServletPath().equals("/logout")) {
httpSession.removeAttribute("user");
response.sendRedirect("");
return;
}
if (user == null) {
json.add("user", "");
}
else {
json.add("user", user.getEmail());
json.add("firstname", user.getFirst());
// Get user lists
if (request.getServletPath().equals("/account")) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = null;
try {
session = sf.getCurrentSession();
} catch (HibernateException he) {
session = sf.openSession();
}
session.beginTransaction();
session.update(user);
json.add("lastname", user.getLast());
json.add("institution", user.getInstitute());
json.add("lists", user.getLists());
session.getTransaction().commit();
session.close();
}
}
json.write(response.getWriter());
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// All form submissions are ajax and take json responses
response.setContentType("application/json");
JSONify json = new JSONify();
// Create database session
SessionFactory sf = HibernateUtil.getSessionFactory();
Session dbSession = sf.openSession();
dbSession.beginTransaction();
if (request.getServletPath().equals("/login"))
login(request, response, dbSession, json);
else if (request.getServletPath().equals("/register"))
register(request, response, dbSession, json);
else if (request.getServletPath().equals("/forgot"))
forgot(request, response, dbSession, json);
else if (request.getServletPath().equals("/reset"))
reset(request, response, dbSession, json);
else if (request.getServletPath().equals("/account"))
modify(request, response, dbSession, json);
else if (request.getServletPath().equals("/contribute"))
contribute(request, response, dbSession, json);
// Close database session and write out json
dbSession.getTransaction().commit();
dbSession.close();
json.write(response.getWriter());
}
private void register(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
// Check for existing email
String email = request.getParameter("email");
Criteria criteria = dbSession.createCriteria(User.class)
.add(Restrictions.eq("email", email).ignoreCase());
User user = (User) criteria.uniqueResult();
if (user != null) { // If exists, throw error
json.add("message", "The email you entered is already registered.");
}
else { // Else, create user
User newUser = new User(email,
request.getParameter("password"),
request.getParameter("firstname"),
request.getParameter("lastname"),
request.getParameter("institution"));
dbSession.save(newUser);
request.getSession().setAttribute("user", newUser);
json.add("redirect", "index.html");
}
}
private void login(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
Criteria criteria = dbSession.createCriteria(User.class)
.add(Restrictions.eq("email", email).ignoreCase());
User user = (User) criteria.uniqueResult();
if (user == null) {
json.add("message", "The email you entered does not belong to a registered user.");
}
else if (user.checkPassword(password)) {
user.updateAccessed();
dbSession.update(user);
request.getSession().setAttribute("user", user);
json.add("redirect", "account.html");
}
else {
json.add("message", "The password you entered is incorrect.");
}
}
private void forgot(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
String email = request.getParameter("email");
Criteria criteria = dbSession.createCriteria(User.class)
.add(Restrictions.eq("email", email).ignoreCase());
User user = (User) criteria.uniqueResult();
if (user == null) {
json.add("message", "The email you entered does not belong to a registered user.");
}
else {
// One day token for password reset
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String token = user.getEmail() + user.getSalt() + formatter.format(Calendar.getInstance().getTime());
token = HashFunctions.md5(token);
Properties props = new Properties();
props.put("mail.smtp.host", "mail.maayanlab.net");
props.put("mail.smtp.auth", "true");
javax.mail.Session mailSession = javax.mail.Session.getInstance(props, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("amp@maayanlab.net", "1amp1");
}
});
MimeMessage message = new MimeMessage(mailSession);
try {
message.setFrom(new InternetAddress("Enrichr@amp.pharm.mssm.edu"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
message.setSubject("Enrichr Password Reset");
message.setSentDate(new Date());
message.setText("Reset your password at http://amp.pharm.mssm.edu/Enrichr/reset.html?user=" + email + "&token=" + token + ".\n\nIf you did not request this password reset, please ignore this email.");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
json.add("message", "Password reset request sent! Check your email for a reset link.");
}
}
private void reset(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
String email = request.getParameter("email");
Criteria criteria = dbSession.createCriteria(User.class)
.add(Restrictions.eq("email", email).ignoreCase());
User user = (User) criteria.uniqueResult();
if (user == null) {
json.add("message", "The email you entered does not belong to a registered user.");
}
else {
// Generate today and yesterday's tokens
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
String today = user.getEmail() + user.getSalt() + formatter.format(calendar.getTime());
calendar.add(Calendar.DATE, -1);
String yesterday = user.getEmail() + user.getSalt() + formatter.format(calendar.getTime());
String token = request.getParameter("token");
if (!token.equalsIgnoreCase(HashFunctions.md5(today)) && !token.equalsIgnoreCase(HashFunctions.md5(yesterday))) {
json.add("message", "Your reset token has expired. Please request a new one.");
}
else {
user.updatePassword(request.getParameter("password"));
dbSession.update(user);
json.add("redirect", "login.html");
}
}
}
private void modify(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
User user = (User) request.getSession().getAttribute("user");
String password = request.getParameter("password");
if (user == null) {
json.add("redirect", "login.html");
}
else if (user.checkPassword(password)) {
boolean changed = user.updateUser(request.getParameter("email"),
request.getParameter("newpassword"),
request.getParameter("firstname"),
request.getParameter("lastname"),
request.getParameter("institution"));
if (changed) {
dbSession.update(user);
json.add("message", "Changes saved.");
}
else {
json.add("message", "No changes found.");
}
}
else {
json.add("message", "The password you entered is incorrect.");
}
}
private void contribute(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
HttpSession httpSession = request.getSession();
User user = (User) httpSession.getAttribute("user");
if (user == null) {
json.add("redirect", "login.html");
return;
}
dbSession.update(user);
// Make sure the user does own the list and list isn't already shared
String sharedListEncodedId = request.getParameter("listId");
int sharedListId = Shortener.decode(sharedListEncodedId);
List list = (List) dbSession.get(List.class, sharedListId);
SharedList sharedList = (SharedList) dbSession.get(SharedList.class, sharedListId);
if (sharedList != null) {
json.add("message", "You've already contributed that list.");
}
else if (list != null && list.getUser().equals(user)) {
sharedList = new SharedList(sharedListId,
user,
request.getParameter("description"),
Boolean.parseBoolean(request.getParameter("privacy")));
// Look for list on path
String resourceUrl = Enrichr.RESOURCE_PATH + sharedListEncodedId + ".txt";
if (!(new File(resourceUrl)).isFile()) {
return;
}
// Read file
ArrayList<String> input = FileUtils.readResource(resourceUrl);
if (input.get(0).startsWith("#")) // If input line starts with comment
input.remove(0).replaceFirst("#", "");
// Add each gene in list
Set<SharedGene> sharedGenes = sharedList.getSharedGenes();
for (String gene : input) {
sharedGenes.add(new SharedGene(sharedList, gene));
}
dbSession.save(sharedList);
json.add("listId", sharedListEncodedId);
}
else {
json.add("message", "The list doesn't belong to you.");
}
}
private void delete(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
HttpSession httpSession = request.getSession();
User user = (User) httpSession.getAttribute("user");
if (user == null) {
json.add("redirect", "login.html");
return;
}
dbSession.update(user);
List list = (List) dbSession.get(List.class, Shortener.decode(request.getParameter("listId")));
if (list != null) {
user.getLists().remove(list);
dbSession.update(user);
}
json.add("redirect", "account.html");
}
// Static function to commit new lists to the user so the Enrichr class doesn't make any db calls
static void updateUser(User user) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = null;
try {
session = sf.getCurrentSession();
} catch (HibernateException he) {
session = sf.openSession();
}
session.beginTransaction();
session.update(user);
session.getTransaction().commit();
session.close();
}
}
|
src/main/java/edu/mssm/pharm/maayanlab/Enrichr/Account.java
|
package edu.mssm.pharm.maayanlab.Enrichr;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Set;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import edu.mssm.pharm.maayanlab.FileUtils;
import edu.mssm.pharm.maayanlab.HibernateUtil;
import edu.mssm.pharm.maayanlab.JSONify;
import edu.mssm.pharm.maayanlab.math.HashFunctions;
@WebServlet(urlPatterns = {"/account", "/login", "/register", "/forgot", "/reset", "/status", "/logout", "/contribute", "/delete"})
public class Account extends HttpServlet {
private static final long serialVersionUID = 19776535963654466L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
JSONify json = new JSONify();
HttpSession httpSession = request.getSession();
User user = (User) httpSession.getAttribute("user");
if (request.getServletPath().equals("/logout")) {
httpSession.removeAttribute("user");
response.sendRedirect("");
return;
}
if (user == null) {
json.add("user", "");
}
else {
json.add("user", user.getEmail());
json.add("firstname", user.getFirst());
// Get user lists
if (request.getServletPath().equals("/account")) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = null;
try {
session = sf.getCurrentSession();
} catch (HibernateException he) {
session = sf.openSession();
}
session.beginTransaction();
session.update(user);
json.add("lastname", user.getLast());
json.add("institution", user.getInstitute());
json.add("lists", user.getLists());
session.getTransaction().commit();
session.close();
}
}
json.write(response.getWriter());
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// All form submissions are ajax and take json responses
response.setContentType("application/json");
JSONify json = new JSONify();
// Create database session
SessionFactory sf = HibernateUtil.getSessionFactory();
Session dbSession = sf.openSession();
dbSession.beginTransaction();
if (request.getServletPath().equals("/login"))
login(request, response, dbSession, json);
else if (request.getServletPath().equals("/register"))
register(request, response, dbSession, json);
else if (request.getServletPath().equals("/forgot"))
forgot(request, response, dbSession, json);
else if (request.getServletPath().equals("/reset"))
reset(request, response, dbSession, json);
else if (request.getServletPath().equals("/account"))
modify(request, response, dbSession, json);
else if (request.getServletPath().equals("/contribute"))
contribute(request, response, dbSession, json);
// Close database session and write out json
dbSession.getTransaction().commit();
dbSession.close();
json.write(response.getWriter());
}
private void register(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
// Check for existing email
String email = request.getParameter("email");
Criteria criteria = dbSession.createCriteria(User.class)
.add(Restrictions.eq("email", email).ignoreCase());
User user = (User) criteria.uniqueResult();
if (user != null) { // If exists, throw error
json.add("message", "The email you entered is already registered.");
}
else { // Else, create user
User newUser = new User(email,
request.getParameter("password"),
request.getParameter("firstname"),
request.getParameter("lastname"),
request.getParameter("institution"));
dbSession.save(newUser);
request.getSession().setAttribute("user", newUser);
json.add("redirect", "index.html");
}
}
private void login(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
Criteria criteria = dbSession.createCriteria(User.class)
.add(Restrictions.eq("email", email).ignoreCase());
User user = (User) criteria.uniqueResult();
if (user == null) {
json.add("message", "The email you entered does not belong to a registered user.");
}
else if (user.checkPassword(password)) {
user.updateAccessed();
dbSession.update(user);
request.getSession().setAttribute("user", user);
json.add("redirect", "account.html");
}
else {
json.add("message", "The password you entered is incorrect.");
}
}
private void forgot(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
String email = request.getParameter("email");
Criteria criteria = dbSession.createCriteria(User.class)
.add(Restrictions.eq("email", email).ignoreCase());
User user = (User) criteria.uniqueResult();
if (user == null) {
json.add("message", "The email you entered does not belong to a registered user.");
}
else {
// One day token for password reset
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String token = user.getEmail() + user.getSalt() + formatter.format(Calendar.getInstance().getTime());
token = HashFunctions.md5(token);
Properties props = new Properties();
props.put("mail.smtp.host", "mail.maayanlab.net");
props.put("mail.smtp.auth", "true");
javax.mail.Session mailSession = javax.mail.Session.getInstance(props, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("amp@maayanlab.net", "1amp1");
}
});
MimeMessage message = new MimeMessage(mailSession);
try {
message.setFrom(new InternetAddress("Enrichr@amp.pharm.mssm.edu"));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
message.setSubject("Enrichr Password Reset");
message.setSentDate(new Date());
message.setText("Reset your password at http://amp.pharm.mssm.edu/Enrichr/reset.html?user=" + email + "&token=" + token + ".\n\nIf you did not request this password reset, please ignore this email.");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
json.add("message", "Password reset request sent! Check your email for a reset link.");
}
}
private void reset(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
String email = request.getParameter("email");
Criteria criteria = dbSession.createCriteria(User.class)
.add(Restrictions.eq("email", email).ignoreCase());
User user = (User) criteria.uniqueResult();
if (user == null) {
json.add("message", "The email you entered does not belong to a registered user.");
}
else {
// Generate today and yesterday's tokens
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
String today = user.getEmail() + user.getSalt() + formatter.format(calendar.getTime());
calendar.add(Calendar.DATE, -1);
String yesterday = user.getEmail() + user.getSalt() + formatter.format(calendar.getTime());
String token = request.getParameter("token");
if (!token.equalsIgnoreCase(HashFunctions.md5(today)) && !token.equalsIgnoreCase(HashFunctions.md5(yesterday))) {
json.add("message", "Your reset token has expired. Please request a new one.");
}
else {
user.updatePassword(request.getParameter("password"));
dbSession.update(user);
json.add("redirect", "login.html");
}
}
}
private void modify(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
User user = (User) request.getSession().getAttribute("user");
String password = request.getParameter("password");
if (user == null) {
json.add("redirect", "login.html");
}
else if (user.checkPassword(password)) {
boolean changed = user.updateUser(request.getParameter("email"),
request.getParameter("newpassword"),
request.getParameter("firstname"),
request.getParameter("lastname"),
request.getParameter("institution"));
if (changed) {
dbSession.update(user);
json.add("message", "Changes saved.");
}
else {
json.add("message", "No changes found.");
}
}
else {
json.add("message", "The password you entered is incorrect.");
}
}
private void contribute(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
HttpSession httpSession = request.getSession();
User user = (User) httpSession.getAttribute("user");
if (user == null) {
json.add("redirect", "login.html");
return;
}
dbSession.update(user);
// Make sure the user does own the list
String sharedListEncodedId = request.getParameter("listId");
int sharedListId = Shortener.decode(sharedListEncodedId);
List list = (List) dbSession.get(List.class, sharedListId);
if (list != null && list.getUser().equals(user)) {
SharedList sharedList = new SharedList(sharedListId,
user,
request.getParameter("description"),
Boolean.parseBoolean(request.getParameter("privacy")));
// Look for list on path
String resourceUrl = Enrichr.RESOURCE_PATH + sharedListEncodedId + ".txt";
if (!(new File(resourceUrl)).isFile()) {
return;
}
// Read file
ArrayList<String> input = FileUtils.readResource(resourceUrl);
if (input.get(0).startsWith("#")) // If input line starts with comment
input.remove(0).replaceFirst("#", "");
// Add each gene in list
Set<SharedGene> sharedGenes = sharedList.getSharedGenes();
for (String gene : input) {
sharedGenes.add(new SharedGene(sharedList, gene));
}
dbSession.save(sharedList);
json.add("listId", sharedListEncodedId);
}
else {
json.add("message", "The list doesn't belong to you.");
}
}
private void delete(HttpServletRequest request, HttpServletResponse response, Session dbSession, JSONify json) throws IOException {
HttpSession httpSession = request.getSession();
User user = (User) httpSession.getAttribute("user");
if (user == null) {
json.add("redirect", "login.html");
return;
}
dbSession.update(user);
List list = (List) dbSession.get(List.class, Shortener.decode(request.getParameter("listId")));
if (list != null) {
user.getLists().remove(list);
dbSession.update(user);
}
json.add("redirect", "account.html");
}
// Static function to commit new lists to the user so the Enrichr class doesn't make any db calls
static void updateUser(User user) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = null;
try {
session = sf.getCurrentSession();
} catch (HibernateException he) {
session = sf.openSession();
}
session.beginTransaction();
session.update(user);
session.getTransaction().commit();
session.close();
}
}
|
Check to ensure that the list isn't already shared
git-svn-id: f5921e6c9a61b6015ffa18fe349c03fb73f2cf99@1889 998562b1-c221-4fe5-b3d3-2fd2107a5f19
|
src/main/java/edu/mssm/pharm/maayanlab/Enrichr/Account.java
|
Check to ensure that the list isn't already shared
|
|
Java
|
apache-2.0
|
c5dcfdabf7ba9c80af5a4a127156b83306feeee1
| 0
|
pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus
|
/*
* This file or a portion of this file is licensed under the terms of
* the Globus Toolkit Public License, found in file GTPL, or at
* http://www.globus.org/toolkit/download/license.html. This notice must
* appear in redistributions of this file, with or without modification.
*
* Redistributions of this Software, with or without modification, must
* reproduce the GTPL in: (1) the Software, or (2) the Documentation or
* some other similar material which is provided with the Software (if
* any).
*
* Copyright 1999-2004 University of Chicago and The University of
* Southern California. All rights reserved.
*/
package org.griphyn.cPlanner.toolkit;
import org.griphyn.cPlanner.common.LogManager;
import org.griphyn.common.util.FactoryException;
import org.griphyn.common.util.Currently;
import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.TreeMap;
import java.util.HashMap;
import java.util.regex.Pattern;
/**
* A Central Properties class that keeps track of all the properties used by
* Pegasus. All other classes access the methods in this class to get the value
* of the property. It access the VDSProperties class to read the property file.
*
* @author Karan Vahi
* @author Gaurang Mehta
*
* @version $Revision$
*
* @see org.griphyn.common.util.VDSProperties
*/
public class VDS2PegasusProperties extends Executable {
/**
* The handle to the internal map, that maps vds properties to pegasus
* properties.
*/
private static Map mVDSToPegasusPropertiesTable;
/**
* An internal table that resolves the old transfer mode property, to
* the corresponding transfer implementation.
*/
private static Map mTXFERImplTable;
/**
* An internal table that resolves the old transfer mode property, to
* the corresponding transfer refiner.
*/
private static Map mTXFERRefinerTable;
/**
* Store the regular expressions necessary to match the * properties.
*/
private static final String mRegexExpression[]={
"(vds.replica.)([a-zA-Z_0-9]*[-]*)+(.prefer.stagein.sites)",
"(vds.replica.)([a-zA-Z_0-9]*[-]*)+(.ignore.stagein.sites)",
"(vds.site.selector.env.)([a-zA-Z_0-9]*[-]*)+",
"(vds.exitcode.path.)([a-zA-Z_0-9]*[-]*)+",
"(vds.partitioner.horizontal.bundle.)([a-zA-Z_0-9]*[-]*)+",
"(vds.partitioner.horizontal.collapse.)([a-zA-Z_0-9]*[-]*)+",
"(vds.transfer.rft.)([a-zA-Z_0-9]*[-]*)+",
"(vds.transfer.crft.)([a-zA-Z_0-9]*[-]*)+",
//"(vds.db.)([a-zA-Z_0-9]*[-]*)+(.)([a-zA-Z_0-9.]*[-]*)+"
"(vds.db.tc.driver)[.]+([a-zA-Z_0-9]*[-]*)+",
"(vds.db.ptc.driver)[.]+([a-zA-Z_0-9]*[-]*)+",
"(vds.db.\\*.driver)[.]+([a-zA-Z_0-9]*[-]*)+",
};
/**
* Replacement 2 D Array for the above properties.
*/
private static final String mStarReplacements [][] ={
{ "vds.replica.", "pegasus.selector.replica." },
{ "vds.replica.", "pegasus.selector.replica." },
{ "vds.site.selector.env.", "pegasus.selector.site.env."},
{ "vds.exitcode.path.", "pegasus.exitcode.path." },
{ "vds.partitioner.horizontal.bundle", "pegasus.partitioner.horizontal.bundle."},
{ "vds.partitioner.horizontal.collapse", "pegasus.partitioner.horizontal.collapse."},
{ "vds.transfer.rft.", "pegasus.transfer.rft."},
{ "vds.transfer.crft.", "pegasus.transfer.crft."},
//{ "vds.db.", "pegasus.db." }
{ "vds.db.tc.driver.", "pegasus.catalog.transformation.db." },
{ "vds.db.ptc.driver.", "pegasus.catalog.provenance.db." },
{ "vds.db.\\*.driver.", "pegasus.catalog.*.db." },
};
/**
* Stores compiled patterns at first use, quasi-Singleton.
*/
private static Pattern mCompiledPatterns[] = null;
/**
* The input directory containing the kickstart records.
*/
private String mInputFile;
/**
* The output directory where to generate the ploticus output.
*/
private String mOutputDir;
/**
* The default constructor. Compiles the patterns only once.
*/
public VDS2PegasusProperties(){
// initialize the compiled expressions once
if ( mCompiledPatterns == null ) {
mCompiledPatterns = new Pattern[ mRegexExpression.length ];
for (int i = 0; i < mRegexExpression.length; i++)
mCompiledPatterns[i] = Pattern.compile( mRegexExpression[i] );
}
}
/**
* Singleton access to the transfer implementation table.
* Contains the mapping of the old transfer property value to the
* new transfer implementation property value.
*
* @return map
*/
private static Map transferImplementationTable(){
//singleton access
if(mTXFERImplTable == null){
mTXFERImplTable = new HashMap(13);
mTXFERImplTable.put("Bundle","Transfer");
mTXFERImplTable.put("Chain","Transfer");
mTXFERImplTable.put("CRFT","CRFT");
mTXFERImplTable.put("GRMS","GRMS");
mTXFERImplTable.put("multiple","Transfer");
mTXFERImplTable.put("Multiple","Transfer");
mTXFERImplTable.put("MultipleTransfer","Transfer");
mTXFERImplTable.put("RFT","RFT");
mTXFERImplTable.put("single","OldGUC");
mTXFERImplTable.put("Single","OldGUC");
mTXFERImplTable.put("SingleTransfer","OldGUC");
mTXFERImplTable.put("StorkSingle","Stork");
mTXFERImplTable.put("T2","T2");
}
return mTXFERImplTable;
}
/**
* Singleton access to the transfer refiner table.
* Contains the mapping of the old transfer property value to the
* new transfer refiner property value.
*
* @return map
*/
private static Map transferRefinerTable(){
//singleton access
if(mTXFERRefinerTable == null){
mTXFERRefinerTable = new HashMap(13);
mTXFERRefinerTable.put("Bundle","Bundle");
mTXFERRefinerTable.put("Chain","Chain");
mTXFERRefinerTable.put("CRFT","Default");
mTXFERRefinerTable.put("GRMS","GRMS");
mTXFERRefinerTable.put("multiple","Default");
mTXFERRefinerTable.put("Multiple","Default");
mTXFERRefinerTable.put("MultipleTransfer","Default");
mTXFERRefinerTable.put("RFT","Default");
mTXFERRefinerTable.put("single","SDefault");
mTXFERRefinerTable.put("Single","SDefault");
mTXFERRefinerTable.put("SingleTransfer","SDefault");
mTXFERRefinerTable.put("StorkSingle","Single");
mTXFERRefinerTable.put("T2","Default");
}
return mTXFERRefinerTable;
}
/**
* Singleton access to the transfer implementation table.
* Contains the mapping of the old transfer property value to the
* new transfer implementation property value.
*
* @return map
*/
private static Map vdsToPegasusPropertiesTable(){
//return the already existing one if possible
if( mVDSToPegasusPropertiesTable != null ){
return mVDSToPegasusPropertiesTable;
}
associate( "vds.home", "pegasus.home" );
//PROPERTIES RELATED TO SCHEMAS
associate( "vds.schema.dax", "pegasus.schema.dax" );
associate( "vds.schema.pdax", "pegasus.schema.pdax" );
associate( "vds.schema.poolconfig", "pegasus.schema.sc" );
associate( "vds.schema.sc", "pegasus.schema.sc" );
associate( "vds.db.ptc.schema", "pegasus.catalog.provenance" );
//PROPERTIES RELATED TO DIRECTORIES
associate( "vds.dir.exec", "pegasus.dir.exec" );
associate( "vds.dir.storage", "pegasus.dir.storage" );
associate( "vds.dir.create.mode", "pegasus.dir.create" );
associate( "vds.dir.create", "pegasus.dir.create" );
associate( "vds.dir.timestamp.extended", "pegasus.dir.timestamp.extended" );
//PROPERTIES RELATED TO THE TRANSFORMATION CATALOG
associate( "vds.tc.mode", "pegasus.catalog.transformation" );
associate( "vds.tc", "pegasus.catalog.transformation" );
associate( "vds.tc.file", "pegasus.catalog.transformation.file" );
associate( "vds.tc.mapper", "pegasus.catalog.transformation.mapper" );
//REPLICA CATALOG PROPERTIES
associate( "vds.replica.mode", "pegasus.catalog.replica" );
associate( "vds.rc", "pegasus.catalog.replica" );
associate( "vds.rls.url", "pegasus.catalog.replica.url" );
associate( "vds.rc.url", "pegasus.catalog.replica.url" );
associate( "vds.rc.lrc.ignore", "pegasus.catalog.replica.lrc.ignore" );
associate( "vds.rc.lrc.restrict", "pegasus.catalog.replica.lrc.restrict" );
associate( "vds.cache.asrc", "pegasus.catalog.replica.cache.asrc" );
associate( "vds.rls.query", "" );
associate( "vds.rls.query.attrib","" );
associate( "vds.rls.exit", "" );
associate( "vds.rc.rls.timeout", "" );
//SITE CATALOG PROPERTIES
associate( "vds.pool.mode", "pegasus.catalog.site" );
associate( "vds.sc", "pegasus.catalog.site" );
associate( "vds.pool.file", "pegasus.catalog.site.file" );
associate( "vds.sc.file", "pegasus.catalog.site.file" );
//PROPERTIES RELATED TO SELECTION
associate( "vds.transformation.selector", "pegasus.selector.transformation" );
associate( "vds.rc.selector", "pegasus.selector.replica" );
associate( "vds.replica.selector", "pegasus.selector.replica" );
// associate( "vds.replica.*.prefer.stagein.sites", "pegasus.selector.replica.*.prefer.stagein.sites" );
associate( "vds.rc.restricted.sites", "pegasus.selector.replica.*.ignore.stagein.sites" );
// associate( "vds.replica.*.ignore.stagein.sites", "pegasus.selector.replica.*.ignore.stagein.sites" );
associate( "vds.site.selector", "pegasus.selector.site" );
associate( "vds.site.selector.path", "pegasus.selector.site.path" );
associate( "vds.site.selector.timeout", "pegasus.selector.site.timeout" );
associate( "vds.site.selector.keep.tmp", "pegasus.selector.site.keep.tmp" );
//TRANSFER MECHANISM PROPERTIES
associate( "vds.transfer.*.impl", "pegasus.transfer.*.impl" );
associate( "vds.transfer.stagein.impl", "pegasus.transfer.stagein.impl" );
associate( "vds.transfer.stageout.impl", "pegasus.transfer.stageout.impl" );
associate( "vds.transfer.stagein.impl", "pegasus.transfer.inter.impl" );
associate( "vds.transfer.refiner", "pegasus.transfer.refiner" );
associate( "vds.transfer.single.quote", "pegasus.transfer.single.quote" );
associate( "vds.transfer.throttle.processes", "pegasus.transfer.throttle.processes" );
associate( "vds.transfer.throttle.streams", "pegasus.transfer.throttle.streams" );
associate( "vds.transfer.force", "pegasus.transfer.force" );
associate( "vds.transfer.mode.links", "pegasus.transfer.links" );
associate( "vds.transfer.links", "pegasus.transfer.links" );
associate( "vds.transfer.thirdparty.sites", "pegasus.transfer.*.thirdparty.sites" );
associate( "vds.transfer.thirdparty.pools", "pegasus.transfer.*.thirdparty.sites" );
associate( "vds.transfer.*.thirdparty.sites", "pegasus.transfer.*.thirdparty.sites" );
associate( "vds.transfer.stagein.thirdparty.sites", "pegasus.transfer.stagein.thirdparty.sites" );
associate( "vds.transfer.stageout.thirdparty.sites", "pegasus.transfer.stageout.thirdparty.sites" );
associate( "vds.transfer.inter.thirdparty.sites", "pegasus.transfer.inter.thirdparty.sites" );
associate( "vds.transfer.staging.delimiter", "pegasus.transfer.staging.delimiter" );
associate( "vds.transfer.disable.chmod.sites","pegasus.transfer.disable.chmod.sites" );
associate( "vds.transfer.proxy", "pegasus.transfer.proxy");
associate( "vds.transfer.arguments", "pegasus.transfer.arguments" );
associate( "vds.transfer.*.priority", "pegasus.transfer.*.priority" );
associate( "vds.transfer.stagein.priority", "pegasus.transfer.stagein.priority" );
associate( "vds.transfer.stageout.priority", "pegasus.transfer.stageout.priority" );
associate( "vds.transfer.inter.priority", "pegasus.transfer.inter.priority" );
associate( "vds.scheduler.stork.cred", "pegasus.transfer.stork.cred" );
//PROPERTIES RELATED TO KICKSTART AND EXITCODE
associate( "vds.gridstart", "pegasus.gridstart" );
associate( "vds.gridstart.invoke.always", "pegasus.gristart.invoke.always" );
associate( "vds.gridstart.invoke.length", "pegasus.gridstart.invoke.length" );
associate( "vds.gridstart.kickstart.stat", "pegasus.gridstart.kickstart.stat" );
associate( "vds.gridstart.label", "pegasus.gristart.label" );
associate( "vds.exitcode.impl", "pegasus.exitcode.impl" );
associate( "vds.exitcode.mode", "pegasus.exitcode.scope" );
associate( "vds.exitcode", "pegasus.exitcode.scope" );
// associate( "vds.exitcode.path.[value]","pegasus.exitcode.path.[value]" );
associate( "vds.exitcode.arguments", "pegasus.exitcode.arguments" );
associate( "vds.exitcode.debug", "pegasus.exitcode.debug" );
associate( "vds.prescript.arguments", "pegasus.prescript.arguments" );
//PROPERTIES RELATED TO REMOTE SCHEDULERS
associate( "vds.scheduler.remote.projects", "pegasus.remote.scheduler.projects" );
associate( "vds.scheduler.remote.queues", "pegasus.remote.scheduler.queues" );
// associate( "vds.scheduler.remote.maxwalltimes", "pegasus.remote.scheduler.maxwalltimes" );
associate( "vds.scheduler.remote.min.maxtime", "pegasus.remote.scheduler.min.maxtime" );
associate( "vds.scheduler.remote.min.maxwalltime", "pegasus.remote.scheduler.min.maxwalltime" );
associate( "vds.scheduler.remote.min.maxcputime", "pegasus.remote.scheduler.min.maxcputime" );
//PROPERTIES RELATED TO Condor and DAGMAN
associate( "vds.scheduler.condor.release", "pegasus.condor.release" );
associate( "vds.scheduler.condor.remove", "pegasus.condor.remove" );
associate( "vds.scheduler.condor.arguments.quote", "pegasus.condor.arguments.quote" );
associate( "vds.scheduler.condor.output.stream", "pegasus.condor.output.stream" );
associate( "vds.scheduler.condor.error.stream", "pegasus.condor.error.stream" );
associate( "vds.scheduler.condor.retry", "pegasus.dagman.retry" );
//JOB CLUSTERING
associate( "vds.exec.node.collapse", "pegasus.clusterer.nodes" );
associate( "vds.job.aggregator", "pegasus.clusterer.job.aggregator" );
associate( "vds.job.aggregator.seqexec.isgloballog", "pegasus.clusterer.job.aggregator.hasgloballog" );
associate( "vds.clusterer.label.key", "pegasus.clusterer.label.key" );
//MISCELLANEOUS
associate( "vds.auth.gridftp.timeout", "pegasus.auth.gridftp.timeout" );
associate( "vds.submit.mode", "pegasus.submit" );
associate( "vds.job.priority", "pegasus.job.priority" );
associate( "vds.dax.callback", "pegasus.parser.dax.callback" );
associate( "vds.label.key", "pegasus.partitioner.label.key" );
associate( "vds.partitioner.label.key", "pegasus.partitioner.label.key" );
associate( "vds.partition.parser.mode", "pegasus.partitioner.parser.load" );
// associate( "vds.partitioner.horizontal.bundle.", "pegasus.partitioner.horizontal.bundle." );
// associate( "vds.partitioner.horizontal.collapse.", "pegasus.partitioner.horizontal.collapse." );
//SOME DB DRIVER PROPERTIES
associate( "vds.db.*.driver", "pegasus.catalog.*.db.driver" );
associate( "vds.db.tc.driver", "pegasus.catalog.transformation.db.driver" );
associate( "vds.db.ptc.driver", "pegasus.catalog.provenance.db.driver" );
//WORK DB PROPERTIES
associate( "work.db", "pegasus.catalog.work.db" );
associate( "work.db.hostname", "pegasus.catalog.work.db.hostname" );
associate( "work.db.database", "pegasus.catalog.work.db.database" );
associate( "work.db.user", "pegasus.catalog.work.db.user" );
associate( "work.db.password", "pegasus.catalog.work.db.password" );
return mVDSToPegasusPropertiesTable;
}
/**
* Convert a VDS Properties file to Pegasus properties.
*
* @param input the path to the VDS Properties file.
* @param directory the directory where the Pegasus properties file needs to be written out to.
*
* @return path to the properties file that is written.
*
* @exception IOException
*/
public String convert( String input, String directory ) throws IOException{
File dir = new File(directory);
//sanity check on the directory
sanityCheck( dir );
//we only want to write out the VDS properties for time being
Properties ipProperties = new Properties( );
ipProperties.load( new FileInputStream(input) );
Properties vdsProperties = this.matchingSubset( ipProperties, "vds", true );
//traverse through the VDS properties and convert them to
//the new names
Properties temp = new Properties();
for( Iterator it = vdsProperties.keySet().iterator(); it.hasNext(); ){
String vds = ( String )it.next();
String vdsValue = (String)vdsProperties.get( vds );
String pgs = ( String )vdsToPegasusPropertiesTable().get( vds );
//if pgs is not null store the pgs with the vds value
//if null then barf
if( pgs == null ){
//match for star properties
pgs = matchForStarProperties( vds );
if ( pgs == null ){
System.err.println("Unable to associate VDS property " + vds );
continue;
}
}
else{
if( pgs.length() == 0 ){
//ignore
continue;
}
}
//put the pegasus property with the vds value
temp.setProperty( pgs, vdsValue );
}
//put the properties in temp into PegasusProperties in a sorted order
//does not work, as the store method does not store it in that manner
Map pegasusProperties = new TreeMap();
for( Iterator it = temp.keySet().iterator(); it.hasNext(); ){
String key = (String)it.next();
pegasusProperties.put( key, (String)temp.get( key ));
}
//create a temporary file in directory
File f = File.createTempFile( "pegasus.", ".properties", dir );
PrintWriter pw = new PrintWriter( new FileWriter( f ) );
//the header of the file
StringBuffer header = new StringBuffer(64);
header.append( "############################################################################\n" );
header.append( "# PEGASUS USER PROPERTIES GENERATED FROM VDS PROPERTY FILE \n" )
.append( "# ( " + input + " ) \n" )
.append( "# GENERATED AT ").append( Currently.iso8601( false, true, false, new java.util.Date() )).append( "\n" );
header.append( "############################################################################" );
pw.println( header.toString() );
for( Iterator it = pegasusProperties.entrySet().iterator(); it.hasNext(); ){
Map.Entry entry = ( Map.Entry )it.next();
String line = entry.getKey() + " = " + entry.getValue();
pw.println( line );
}
pw.close();
/*
//the header of the file
StringBuffer header = new StringBuffer(64);
header.append( "############################################################################\n" );
header.append( "# PEGASUS USER PROPERTIES GENERATED FROM VDS PROPERTY FILE \n#( " + input + " ) \n" )
.append( "# ESCAPES IN VALUES ARE INTRODUCED \n");
header.append( "############################################################################" );
//create an output stream to this file and write out the properties
OutputStream os = new FileOutputStream( f );
pegasusProperties.store( os, header.toString() );
os.close();
//convert the properties file into a sorted properties file
convertToSorted( f, dir );
*/
return f.getAbsolutePath();
}
/**
* Returns a matching pegasus property for a VDS star property.
*
* @param vds the vds property.
*
* @return the new Pegasus Property if found else, null.
*/
protected String matchForStarProperties( String vds ){
String pgs = null;
// match against pattern
for ( int i=0; i< mRegexExpression.length; i++ ) {
//if a vds property matches against existing patterns
if( mCompiledPatterns[i].matcher( vds ).matches() ){
//get the replacement value
pgs = vds.replaceFirst( mStarReplacements[i][0], mStarReplacements[i][1] );
System.out.println( "The matching pegasus * property for " + vds + " is " + pgs );
break;
}
}
return pgs;
}
/**
* The main test program.
*
* @param args the arguments to the program.
*/
public static void main( String[] args ){
VDS2PegasusProperties me = new VDS2PegasusProperties();
int result = 0;
try{
me.executeCommand( args );
}
catch ( FactoryException fe){
me.log( fe.convertException() , LogManager.FATAL_MESSAGE_LEVEL);
result = 2;
}
catch ( RuntimeException rte ) {
//catch all runtime exceptions including our own that
//are thrown that may have chained causes
me.log( convertException(rte),
LogManager.FATAL_MESSAGE_LEVEL );
result = 1;
}
catch ( Exception e ) {
//unaccounted for exceptions
me.log(e.getMessage(),
LogManager.FATAL_MESSAGE_LEVEL );
e.printStackTrace();
result = 3;
}
// warn about non zero exit code
if ( result != 0 ) {
me.log("Non-zero exit-code " + result,
LogManager.WARNING_MESSAGE_LEVEL );
}
System.exit(result);
}
/**
* Executes the command on the basis of the options specified.
*
* @param args the command line options.
*/
public void executeCommand(String[] args) {
parseCommandLineArguments(args);
//sanity check on output directory
mOutputDir = ( mOutputDir == null ) ? "." : mOutputDir;
File dir = new File( mOutputDir );
if( dir.exists() ){
//directory already exists.
if ( dir.isDirectory() ){
if ( !dir.canWrite() ){
throw new RuntimeException( "Cannot write out to output directory " +
mOutputDir );
}
}
else{
//directory is a file
throw new RuntimeException( mOutputDir + " is not a directory ");
}
}
else{
dir.mkdirs();
}
String output;
try{
output = this.convert(mInputFile, mOutputDir );
System.out.println( "Pegasus Properties Written out to file " + output );
}
catch( IOException ioe ){
throw new RuntimeException( "Unable to convert properties file ", ioe );
}
}
/**
* Parses the command line arguments using GetOpt and returns a
* <code>PlannerOptions</code> contains all the options passed by the
* user at the command line.
*
* @param args the arguments passed by the user at command line.
*/
public void parseCommandLineArguments(String[] args){
LongOpt[] longOptions = generateValidOptions();
Getopt g = new Getopt( "properties-converter", args,
"i:o:h",
longOptions, false);
g.setOpterr(false);
int option = 0;
while( (option = g.getopt()) != -1){
//System.out.println("Option tag " + (char)option);
switch (option) {
case 'i'://input
this.mInputFile = g.getOptarg();
break;
case 'h'://help
printLongVersion();
System.exit( 0 );
return;
case 'o'://output directory
this.mOutputDir = g.getOptarg();
break;
default: //same as help
printShortVersion();
throw new RuntimeException("Incorrect option or option usage " +
(char)option);
}
}
}
/**
* Tt generates the LongOpt which contain the valid options that the command
* will accept.
*
* @return array of <code>LongOpt</code> objects , corresponding to the valid
* options
*/
public LongOpt[] generateValidOptions(){
LongOpt[] longopts = new LongOpt[3];
longopts[0] = new LongOpt( "input", LongOpt.REQUIRED_ARGUMENT, null, 'i' );
longopts[1] = new LongOpt( "output", LongOpt.REQUIRED_ARGUMENT, null, 'o' );
longopts[2] = new LongOpt( "help", LongOpt.NO_ARGUMENT, null, 'h' );
return longopts;
}
/**
* Prints out a short description of what the command does.
*/
public void printShortVersion(){
String text =
"\n $Id$ " +
"\n " + getGVDSVersion() +
"\n Usage : properties-converter [-Dprop [..]] -i <input directory> " +
" [-o output directory] [-h]";
System.out.println(text);
}
/**
* Prints the long description, displaying in detail what the various options
* to the command stand for.
*/
public void printLongVersion(){
String text =
"\n $Id$ " +
"\n " + getGVDSVersion() +
"\n properties-converter - A tool that converts the VDS properties file to " +
"\n the corresponding Pegasus properties file " +
"\n Usage: properties-converter [-Dprop [..]] --input <input file> " +
"\n [--output output directory] [--help] " +
"\n" +
"\n Mandatory Options " +
"\n --input the path to the VDS properties file." +
"\n Other Options " +
"\n -o |--output the output directory where to generate the pegasus property file." +
"\n -h |--help generates this help." +
"\n ";
System.out.println(text);
//mLogger.log(text,LogManager.INFO_MESSAGE_LEVEL);
}
/**
* Loads all the properties that would be needed by the Toolkit classes.
*/
public void loadProperties(){
//empty for time being
}
/**
* Returns the transfer implementation.
*
* @param property property name.
*
* @return the transfer implementation,
* else the one specified by "pegasus.transfer.*.impl",
* else the DEFAULT_TRANSFER_IMPLEMENTATION.
*/
/*
public String getTransferImplementation(String property){
String value = mProps.getProperty(property,
getDefaultTransferImplementation());
if(value == null){
//check for older deprecated properties
value = mProps.getProperty("pegasus.transfer");
value = (value == null)?
mProps.getProperty("pegasus.transfer.mode"):
value;
//convert a non null value to the corresponding
//transfer implementation
if(value != null){
value = (String)transferImplementationTable().get(value);
logDeprecatedWarning("pegasus.transfer","pegasus.transfer.*.impl and " +
"pegasus.transfer.refiner");
}
}
//put in default if still we have a non null
value = (value == null)?
DEFAULT_TRANSFER_IMPLEMENTATION:
value;
return value;
}
*/
/**
* Returns the transfer refiner that is to be used for adding in the
* transfer jobs in the workflow
*
* Referred to by the "pegasus.transfer.refiner" property.
*
* @return the transfer refiner, else the DEFAULT_TRANSFER_REFINER.
*
* @see #DEFAULT_TRANSFER_REFINER
*/
/*
public String getTransferRefiner(){
String value = mProps.getProperty("pegasus.transfer.refiner");
if(value == null){
//check for older deprecated properties
value = mProps.getProperty("pegasus.transfer");
value = (value == null)?
mProps.getProperty("pegasus.transfer.mode"):
value;
//convert a non null value to the corresponding
//transfer refiner
if(value != null){
value = (String)transferRefinerTable().get(value);
logDeprecatedWarning("pegasus.transfer","pegasus.transfer.impl and " +
"pegasus.transfer.refiner");
}
}
//put in default if still we have a non null
value = (value == null)?
DEFAULT_TRANSFER_REFINER:
value;
return value;
}
*/
//SOME LOGGING PROPERTIES
/**
* Returns the file to which all the logging needs to be directed to.
*
* Referred to by the "vds.log.*" property.
*
* @return the value of the property that is specified, else
* null
*/
// public String getLoggingFile(){
// return mProps.getProperty("vds.log.*");
// }
/**
* Returns the location of the local log file where you want the messages to
* be logged. Not used for the moment.
*
* Referred to by the "vds.log4j.log" property.
*
* @return the value specified in the property file,else null.
*/
// public String getLog4JLogFile() {
// return getProperty( "vds.log.file", "vds.log4j.log" );
// }
/**
* Return returns the environment string specified for the local pool. If
* specified the registration jobs are set with these environment variables.
*
* Referred to by the "vds.local.env" property
*
* @return the environment string for local pool in properties file if
* defined, else null.
*/
// public String getLocalPoolEnvVar() {
// return mProps.getProperty( "vds.local.env" );
// }
/**
* Returns a boolean indicating whether to treat the entries in the cache
* files as a replica catalog or not.
*
* @return boolean
*/
// public boolean treatCacheAsRC(){
// return Boolean.parse(mProps.getProperty( "vds.cache.asrc"),
// false);
// }
/**
* Checks the destination location for existence, if it can
* be created, if it is writable etc.
*
* @param dir is the new base directory to optionally create.
*
* @throws IOException in case of error while writing out files.
*/
protected static void sanityCheck( File dir ) throws IOException{
if ( dir.exists() ) {
// location exists
if ( dir.isDirectory() ) {
// ok, isa directory
if ( dir.canWrite() ) {
// can write, all is well
return;
} else {
// all is there, but I cannot write to dir
throw new IOException( "Cannot write to existing directory " +
dir.getPath() );
}
} else {
// exists but not a directory
throw new IOException( "Destination " + dir.getPath() + " already " +
"exists, but is not a directory." );
}
} else {
// does not exist, try to make it
if ( ! dir.mkdirs() ) {
throw new IOException( "Unable to create directory destination " +
dir.getPath() );
}
}
}
/**
* Extracts a specific property key subset from the known properties.
* The prefix may be removed from the keys in the resulting dictionary,
* or it may be kept. In the latter case, exact matches on the prefix
* will also be copied into the resulting dictionary.
*
* @param properties is the properties from where to get the subset.
* @param prefix is the key prefix to filter the properties by.
* @param keepPrefix if true, the key prefix is kept in the resulting
* dictionary. As side-effect, a key that matches the prefix
* exactly will also be copied. If false, the resulting
* dictionary's keys are shortened by the prefix. An
* exact prefix match will not be copied, as it would
* result in an empty string key.
*
* @return a property dictionary matching the filter key. May be
* an empty dictionary, if no prefix matches were found.
*
* @see #getProperty( String ) is used to assemble matches
*/
public Properties matchingSubset( Properties properties, String prefix, boolean keepPrefix ) {
Properties result = new Properties();
// sanity check
if ( prefix == null || prefix.length() == 0 ) return result;
String prefixMatch; // match prefix strings with this
String prefixSelf; // match self with this
if ( prefix.charAt(prefix.length()-1) != '.' ) {
// prefix does not end in a dot
prefixSelf = prefix;
prefixMatch = prefix + '.';
} else {
// prefix does end in one dot, remove for exact matches
prefixSelf = prefix.substring( 0, prefix.length()-1 );
prefixMatch = prefix;
}
// POSTCONDITION: prefixMatch and prefixSelf are initialized!
// now add all matches into the resulting properties.
// Remark 1: #propertyNames() will contain the System properties!
// Remark 2: We need to give priority to System properties. This is done
// automatically by calling this class's getProperty method.
String key;
for ( Enumeration e = properties.propertyNames(); e.hasMoreElements(); ) {
key = (String) e.nextElement();
if ( keepPrefix ) {
// keep full prefix in result, also copy direct matches
if ( key.startsWith(prefixMatch) || key.equals(prefixSelf) )
result.setProperty( key,
(String)properties.get(key) );
} else {
// remove full prefix in result, dont copy direct matches
if ( key.startsWith(prefixMatch) )
result.setProperty( key.substring( prefixMatch.length() ),
(String)properties.get(key) );
}
}
// done
return result;
}
/**
* Associates a VDS property with the new pegasus property.
*
* @param vdsProperty the old VDS property.
* @param pegasusProperty the new Pegasus property.
*
*/
private static void associate( String vdsProperty, String pegasusProperty ){
if( mVDSToPegasusPropertiesTable == null ){
mVDSToPegasusPropertiesTable = new HashMap(13);
}
mVDSToPegasusPropertiesTable.put( vdsProperty, pegasusProperty );
}
}
|
src/org/griphyn/cPlanner/toolkit/VDS2PegasusProperties.java
|
/*
* This file or a portion of this file is licensed under the terms of
* the Globus Toolkit Public License, found in file GTPL, or at
* http://www.globus.org/toolkit/download/license.html. This notice must
* appear in redistributions of this file, with or without modification.
*
* Redistributions of this Software, with or without modification, must
* reproduce the GTPL in: (1) the Software, or (2) the Documentation or
* some other similar material which is provided with the Software (if
* any).
*
* Copyright 1999-2004 University of Chicago and The University of
* Southern California. All rights reserved.
*/
package org.griphyn.cPlanner.toolkit;
import org.griphyn.cPlanner.common.LogManager;
import org.griphyn.common.util.FactoryException;
import org.griphyn.common.util.Currently;
import gnu.getopt.Getopt;
import gnu.getopt.LongOpt;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.TreeMap;
import java.util.HashMap;
import java.util.regex.Pattern;
/**
* A Central Properties class that keeps track of all the properties used by
* Pegasus. All other classes access the methods in this class to get the value
* of the property. It access the VDSProperties class to read the property file.
*
* @author Karan Vahi
* @author Gaurang Mehta
*
* @version $Revision$
*
* @see org.griphyn.common.util.VDSProperties
*/
public class VDS2PegasusProperties extends Executable {
/**
* The handle to the internal map, that maps vds properties to pegasus
* properties.
*/
private static Map mVDSToPegasusPropertiesTable;
/**
* An internal table that resolves the old transfer mode property, to
* the corresponding transfer implementation.
*/
private static Map mTXFERImplTable;
/**
* An internal table that resolves the old transfer mode property, to
* the corresponding transfer refiner.
*/
private static Map mTXFERRefinerTable;
/**
* Store the regular expressions necessary to match the * properties.
*/
private static final String mRegexExpression[]={
"(vds.replica.)([a-zA-Z_0-9]*[-]*)+(.prefer.stagein.sites)",
"(vds.replica.)([a-zA-Z_0-9]*[-]*)+(.ignore.stagein.sites)",
"(vds.site.selector.env.)([a-zA-Z_0-9]*[-]*)+",
"(vds.exitcode.path.)([a-zA-Z_0-9]*[-]*)+",
"(vds.partitioner.horizontal.bundle.)([a-zA-Z_0-9]*[-]*)+",
"(vds.partitioner.horizontal.collapse.)([a-zA-Z_0-9]*[-]*)+",
"(vds.transfer.rft.)([a-zA-Z_0-9]*[-]*)+",
"(vds.transfer.crft.)([a-zA-Z_0-9]*[-]*)+",
//"(vds.db.)([a-zA-Z_0-9]*[-]*)+(.)([a-zA-Z_0-9.]*[-]*)+"
"(vds.db.tc.driver)[.]+([a-zA-Z_0-9]*[-]*)+",
"(vds.db.ptc.driver)[.]+([a-zA-Z_0-9]*[-]*)+",
"(vds.db.\\*.driver)[.]+([a-zA-Z_0-9]*[-]*)+",
};
/**
* Replacement 2 D Array for the above properties.
*/
private static final String mStarReplacements [][] ={
{ "vds.replica.", "pegasus.selector.replica." },
{ "vds.replica.", "pegasus.selector.replica." },
{ "vds.site.selector.env.", "pegasus.selector.site.env."},
{ "vds.exitcode.path.", "pegasus.exitcode.path." },
{ "vds.partitioner.horizontal.bundle", "pegasus.partitioner.horizontal.bundle."},
{ "vds.partitioner.horizontal.collapse", "pegasus.partitioner.horizontal.collapse."},
{ "vds.transfer.rft.", "pegasus.transfer.rft."},
{ "vds.transfer.crft.", "pegasus.transfer.crft."},
//{ "vds.db.", "pegasus.db." }
{ "vds.db.tc.driver.", "pegasus.catalog.transformation.db." },
{ "vds.db.ptc.driver.", "pegasus.catalog.provenance.db." },
{ "vds.db.\\*.driver.", "pegasus.catalog.*.db." },
};
/**
* Stores compiled patterns at first use, quasi-Singleton.
*/
private static Pattern mCompiledPatterns[] = null;
/**
* The input directory containing the kickstart records.
*/
private String mInputFile;
/**
* The output directory where to generate the ploticus output.
*/
private String mOutputDir;
/**
* The default constructor. Compiles the patterns only once.
*/
public VDS2PegasusProperties(){
// initialize the compiled expressions once
if ( mCompiledPatterns == null ) {
mCompiledPatterns = new Pattern[ mRegexExpression.length ];
for (int i = 0; i < mRegexExpression.length; i++)
mCompiledPatterns[i] = Pattern.compile( mRegexExpression[i] );
}
}
/**
* Singleton access to the transfer implementation table.
* Contains the mapping of the old transfer property value to the
* new transfer implementation property value.
*
* @return map
*/
private static Map transferImplementationTable(){
//singleton access
if(mTXFERImplTable == null){
mTXFERImplTable = new HashMap(13);
mTXFERImplTable.put("Bundle","Transfer");
mTXFERImplTable.put("Chain","Transfer");
mTXFERImplTable.put("CRFT","CRFT");
mTXFERImplTable.put("GRMS","GRMS");
mTXFERImplTable.put("multiple","Transfer");
mTXFERImplTable.put("Multiple","Transfer");
mTXFERImplTable.put("MultipleTransfer","Transfer");
mTXFERImplTable.put("RFT","RFT");
mTXFERImplTable.put("single","OldGUC");
mTXFERImplTable.put("Single","OldGUC");
mTXFERImplTable.put("SingleTransfer","OldGUC");
mTXFERImplTable.put("StorkSingle","Stork");
mTXFERImplTable.put("T2","T2");
}
return mTXFERImplTable;
}
/**
* Singleton access to the transfer refiner table.
* Contains the mapping of the old transfer property value to the
* new transfer refiner property value.
*
* @return map
*/
private static Map transferRefinerTable(){
//singleton access
if(mTXFERRefinerTable == null){
mTXFERRefinerTable = new HashMap(13);
mTXFERRefinerTable.put("Bundle","Bundle");
mTXFERRefinerTable.put("Chain","Chain");
mTXFERRefinerTable.put("CRFT","Default");
mTXFERRefinerTable.put("GRMS","GRMS");
mTXFERRefinerTable.put("multiple","Default");
mTXFERRefinerTable.put("Multiple","Default");
mTXFERRefinerTable.put("MultipleTransfer","Default");
mTXFERRefinerTable.put("RFT","Default");
mTXFERRefinerTable.put("single","SDefault");
mTXFERRefinerTable.put("Single","SDefault");
mTXFERRefinerTable.put("SingleTransfer","SDefault");
mTXFERRefinerTable.put("StorkSingle","Single");
mTXFERRefinerTable.put("T2","Default");
}
return mTXFERRefinerTable;
}
/**
* Singleton access to the transfer implementation table.
* Contains the mapping of the old transfer property value to the
* new transfer implementation property value.
*
* @return map
*/
private static Map vdsToPegasusPropertiesTable(){
//return the already existing one if possible
if( mVDSToPegasusPropertiesTable != null ){
return mVDSToPegasusPropertiesTable;
}
associate( "vds.home", "pegasus.home" );
//PROPERTIES RELATED TO SCHEMAS
associate( "vds.schema.dax", "pegasus.schema.dax" );
associate( "vds.schema.pdax", "pegasus.schema.pdax" );
associate( "vds.schema.poolconfig", "pegasus.schema.sc" );
associate( "vds.schema.sc", "pegasus.schema.sc" );
associate( "vds.db.ptc.schema", "pegasus.schema.ptc" );
//PROPERTIES RELATED TO DIRECTORIES
associate( "vds.dir.exec", "pegasus.dir.exec" );
associate( "vds.dir.storage", "pegasus.dir.storage" );
associate( "vds.dir.create.mode", "pegasus.dir.create" );
associate( "vds.dir.create", "pegasus.dir.create" );
associate( "vds.dir.timestamp.extended", "pegasus.dir.timestamp.extended" );
//PROPERTIES RELATED TO THE TRANSFORMATION CATALOG
associate( "vds.tc.mode", "pegasus.catalog.transformation" );
associate( "vds.tc", "pegasus.catalog.transformation" );
associate( "vds.tc.file", "pegasus.catalog.transformation.file" );
associate( "vds.tc.mapper", "pegasus.catalog.transformation.mapper" );
//REPLICA CATALOG PROPERTIES
associate( "vds.replica.mode", "pegasus.catalog.replica" );
associate( "vds.rc", "pegasus.catalog.replica" );
associate( "vds.rls.url", "pegasus.catalog.replica.url" );
associate( "vds.rc.url", "pegasus.catalog.replica.url" );
associate( "vds.rc.lrc.ignore", "pegasus.catalog.replica.lrc.ignore" );
associate( "vds.rc.lrc.restrict", "pegasus.catalog.replica.lrc.restrict" );
associate( "vds.cache.asrc", "pegasus.catalog.replica.cache.asrc" );
associate( "vds.rls.query", "" );
associate( "vds.rls.query.attrib","" );
associate( "vds.rls.exit", "" );
associate( "vds.rc.rls.timeout", "" );
//SITE CATALOG PROPERTIES
associate( "vds.pool.mode", "pegasus.catalog.site" );
associate( "vds.sc", "pegasus.catalog.site" );
associate( "vds.pool.file", "pegasus.catalog.site.file" );
associate( "vds.sc.file", "pegasus.catalog.site.file" );
//PROPERTIES RELATED TO SELECTION
associate( "vds.transformation.selector", "pegasus.selector.transformation" );
associate( "vds.rc.selector", "pegasus.selector.replica" );
associate( "vds.replica.selector", "pegasus.selector.replica" );
// associate( "vds.replica.*.prefer.stagein.sites", "pegasus.selector.replica.*.prefer.stagein.sites" );
associate( "vds.rc.restricted.sites", "pegasus.selector.replica.*.ignore.stagein.sites" );
// associate( "vds.replica.*.ignore.stagein.sites", "pegasus.selector.replica.*.ignore.stagein.sites" );
associate( "vds.site.selector", "pegasus.selector.site" );
associate( "vds.site.selector.path", "pegasus.selector.site.path" );
associate( "vds.site.selector.timeout", "pegasus.selector.site.timeout" );
associate( "vds.site.selector.keep.tmp", "pegasus.selector.site.keep.tmp" );
//TRANSFER MECHANISM PROPERTIES
associate( "vds.transfer.*.impl", "pegasus.transfer.*.impl" );
associate( "vds.transfer.stagein.impl", "pegasus.transfer.stagein.impl" );
associate( "vds.transfer.stageout.impl", "pegasus.transfer.stageout.impl" );
associate( "vds.transfer.stagein.impl", "pegasus.transfer.inter.impl" );
associate( "vds.transfer.refiner", "pegasus.transfer.refiner" );
associate( "vds.transfer.single.quote", "pegasus.transfer.single.quote" );
associate( "vds.transfer.throttle.processes", "pegasus.transfer.throttle.processes" );
associate( "vds.transfer.throttle.streams", "pegasus.transfer.throttle.streams" );
associate( "vds.transfer.force", "pegasus.transfer.force" );
associate( "vds.transfer.mode.links", "pegasus.transfer.links" );
associate( "vds.transfer.links", "pegasus.transfer.links" );
associate( "vds.transfer.thirdparty.sites", "pegasus.transfer.*.thirdparty.sites" );
associate( "vds.transfer.thirdparty.pools", "pegasus.transfer.*.thirdparty.sites" );
associate( "vds.transfer.*.thirdparty.sites", "pegasus.transfer.*.thirdparty.sites" );
associate( "vds.transfer.stagein.thirdparty.sites", "pegasus.transfer.stagein.thirdparty.sites" );
associate( "vds.transfer.stageout.thirdparty.sites", "pegasus.transfer.stageout.thirdparty.sites" );
associate( "vds.transfer.inter.thirdparty.sites", "pegasus.transfer.inter.thirdparty.sites" );
associate( "vds.transfer.staging.delimiter", "pegasus.transfer.staging.delimiter" );
associate( "vds.transfer.disable.chmod.sites","pegasus.transfer.disable.chmod.sites" );
associate( "vds.transfer.proxy", "pegasus.transfer.proxy");
associate( "vds.transfer.arguments", "pegasus.transfer.arguments" );
associate( "vds.transfer.*.priority", "pegasus.transfer.*.priority" );
associate( "vds.transfer.stagein.priority", "pegasus.transfer.stagein.priority" );
associate( "vds.transfer.stageout.priority", "pegasus.transfer.stageout.priority" );
associate( "vds.transfer.inter.priority", "pegasus.transfer.inter.priority" );
associate( "vds.scheduler.stork.cred", "pegasus.transfer.stork.cred" );
//PROPERTIES RELATED TO KICKSTART AND EXITCODE
associate( "vds.gridstart", "pegasus.gridstart" );
associate( "vds.gridstart.invoke.always", "pegasus.gristart.invoke.always" );
associate( "vds.gridstart.invoke.length", "pegasus.gridstart.invoke.length" );
associate( "vds.gridstart.kickstart.stat", "pegasus.gridstart.kickstart.stat" );
associate( "vds.gridstart.label", "pegasus.gristart.label" );
associate( "vds.exitcode.impl", "pegasus.exitcode.impl" );
associate( "vds.exitcode.mode", "pegasus.exitcode.scope" );
associate( "vds.exitcode", "pegasus.exitcode.scope" );
// associate( "vds.exitcode.path.[value]","pegasus.exitcode.path.[value]" );
associate( "vds.exitcode.arguments", "pegasus.exitcode.arguments" );
associate( "vds.exitcode.debug", "pegasus.exitcode.debug" );
associate( "vds.prescript.arguments", "pegasus.prescript.arguments" );
//PROPERTIES RELATED TO REMOTE SCHEDULERS
associate( "vds.scheduler.remote.projects", "pegasus.remote.scheduler.projects" );
associate( "vds.scheduler.remote.queues", "pegasus.remote.scheduler.queues" );
// associate( "vds.scheduler.remote.maxwalltimes", "pegasus.remote.scheduler.maxwalltimes" );
associate( "vds.scheduler.remote.min.maxtime", "pegasus.remote.scheduler.min.maxtime" );
associate( "vds.scheduler.remote.min.maxwalltime", "pegasus.remote.scheduler.min.maxwalltime" );
associate( "vds.scheduler.remote.min.maxcputime", "pegasus.remote.scheduler.min.maxcputime" );
//PROPERTIES RELATED TO Condor and DAGMAN
associate( "vds.scheduler.condor.release", "pegasus.condor.release" );
associate( "vds.scheduler.condor.remove", "pegasus.condor.remove" );
associate( "vds.scheduler.condor.arguments.quote", "pegasus.condor.arguments.quote" );
associate( "vds.scheduler.condor.output.stream", "pegasus.condor.output.stream" );
associate( "vds.scheduler.condor.error.stream", "pegasus.condor.error.stream" );
associate( "vds.scheduler.condor.retry", "pegasus.dagman.retry" );
//JOB CLUSTERING
associate( "vds.exec.node.collapse", "pegasus.clusterer.nodes" );
associate( "vds.job.aggregator", "pegasus.clusterer.job.aggregator" );
associate( "vds.job.aggregator.seqexec.isgloballog", "pegasus.clusterer.job.aggregator.hasgloballog" );
associate( "vds.clusterer.label.key", "pegasus.clusterer.label.key" );
//MISCELLANEOUS
associate( "vds.auth.gridftp.timeout", "pegasus.auth.gridftp.timeout" );
associate( "vds.submit.mode", "pegasus.submit" );
associate( "vds.job.priority", "pegasus.job.priority" );
associate( "vds.dax.callback", "pegasus.parser.dax.callback" );
associate( "vds.label.key", "pegasus.partitioner.label.key" );
associate( "vds.partitioner.label.key", "pegasus.partitioner.label.key" );
associate( "vds.partition.parser.mode", "pegasus.partitioner.parser.load" );
// associate( "vds.partitioner.horizontal.bundle.", "pegasus.partitioner.horizontal.bundle." );
// associate( "vds.partitioner.horizontal.collapse.", "pegasus.partitioner.horizontal.collapse." );
//SOME DB DRIVER PROPERTIES
associate( "vds.db.*.driver", "pegasus.catalog.*.db.driver" );
associate( "vds.db.tc.driver", "pegasus.catalog.transformation.db.driver" );
associate( "vds.db.ptc.driver", "pegasus.catalog.provenance.db.driver" );
//WORK DB PROPERTIES
associate( "work.db", "pegasus.catalog.work.db" );
associate( "work.db.hostname", "pegasus.catalog.work.db.hostname" );
associate( "work.db.database", "pegasus.catalog.work.db.database" );
associate( "work.db.user", "pegasus.catalog.work.db.user" );
associate( "work.db.password", "pegasus.catalog.work.db.password" );
return mVDSToPegasusPropertiesTable;
}
/**
* Convert a VDS Properties file to Pegasus properties.
*
* @param input the path to the VDS Properties file.
* @param directory the directory where the Pegasus properties file needs to be written out to.
*
* @return path to the properties file that is written.
*
* @exception IOException
*/
public String convert( String input, String directory ) throws IOException{
File dir = new File(directory);
//sanity check on the directory
sanityCheck( dir );
//we only want to write out the VDS properties for time being
Properties ipProperties = new Properties( );
ipProperties.load( new FileInputStream(input) );
Properties vdsProperties = this.matchingSubset( ipProperties, "vds", true );
//traverse through the VDS properties and convert them to
//the new names
Properties temp = new Properties();
for( Iterator it = vdsProperties.keySet().iterator(); it.hasNext(); ){
String vds = ( String )it.next();
String vdsValue = (String)vdsProperties.get( vds );
String pgs = ( String )vdsToPegasusPropertiesTable().get( vds );
//if pgs is not null store the pgs with the vds value
//if null then barf
if( pgs == null ){
//match for star properties
pgs = matchForStarProperties( vds );
if ( pgs == null ){
System.err.println("Unable to associate VDS property " + vds );
continue;
}
}
else{
if( pgs.length() == 0 ){
//ignore
continue;
}
}
//put the pegasus property with the vds value
temp.setProperty( pgs, vdsValue );
}
//put the properties in temp into PegasusProperties in a sorted order
//does not work, as the store method does not store it in that manner
Map pegasusProperties = new TreeMap();
for( Iterator it = temp.keySet().iterator(); it.hasNext(); ){
String key = (String)it.next();
pegasusProperties.put( key, (String)temp.get( key ));
}
//create a temporary file in directory
File f = File.createTempFile( "pegasus.", ".properties", dir );
PrintWriter pw = new PrintWriter( new FileWriter( f ) );
//the header of the file
StringBuffer header = new StringBuffer(64);
header.append( "############################################################################\n" );
header.append( "# PEGASUS USER PROPERTIES GENERATED FROM VDS PROPERTY FILE \n" )
.append( "# ( " + input + " ) \n" )
.append( "# GENERATED AT ").append( Currently.iso8601( false, true, false, new java.util.Date() )).append( "\n" );
header.append( "############################################################################" );
pw.println( header.toString() );
for( Iterator it = pegasusProperties.entrySet().iterator(); it.hasNext(); ){
Map.Entry entry = ( Map.Entry )it.next();
String line = entry.getKey() + " = " + entry.getValue();
pw.println( line );
}
pw.close();
/*
//the header of the file
StringBuffer header = new StringBuffer(64);
header.append( "############################################################################\n" );
header.append( "# PEGASUS USER PROPERTIES GENERATED FROM VDS PROPERTY FILE \n#( " + input + " ) \n" )
.append( "# ESCAPES IN VALUES ARE INTRODUCED \n");
header.append( "############################################################################" );
//create an output stream to this file and write out the properties
OutputStream os = new FileOutputStream( f );
pegasusProperties.store( os, header.toString() );
os.close();
//convert the properties file into a sorted properties file
convertToSorted( f, dir );
*/
return f.getAbsolutePath();
}
/**
* Returns a matching pegasus property for a VDS star property.
*
* @param vds the vds property.
*
* @return the new Pegasus Property if found else, null.
*/
protected String matchForStarProperties( String vds ){
String pgs = null;
// match against pattern
for ( int i=0; i< mRegexExpression.length; i++ ) {
//if a vds property matches against existing patterns
if( mCompiledPatterns[i].matcher( vds ).matches() ){
//get the replacement value
pgs = vds.replaceFirst( mStarReplacements[i][0], mStarReplacements[i][1] );
System.out.println( "The matching pegasus * property for " + vds + " is " + pgs );
break;
}
}
return pgs;
}
/**
* The main test program.
*
* @param args the arguments to the program.
*/
public static void main( String[] args ){
VDS2PegasusProperties me = new VDS2PegasusProperties();
int result = 0;
try{
me.executeCommand( args );
}
catch ( FactoryException fe){
me.log( fe.convertException() , LogManager.FATAL_MESSAGE_LEVEL);
result = 2;
}
catch ( RuntimeException rte ) {
//catch all runtime exceptions including our own that
//are thrown that may have chained causes
me.log( convertException(rte),
LogManager.FATAL_MESSAGE_LEVEL );
result = 1;
}
catch ( Exception e ) {
//unaccounted for exceptions
me.log(e.getMessage(),
LogManager.FATAL_MESSAGE_LEVEL );
e.printStackTrace();
result = 3;
}
// warn about non zero exit code
if ( result != 0 ) {
me.log("Non-zero exit-code " + result,
LogManager.WARNING_MESSAGE_LEVEL );
}
System.exit(result);
}
/**
* Executes the command on the basis of the options specified.
*
* @param args the command line options.
*/
public void executeCommand(String[] args) {
parseCommandLineArguments(args);
//sanity check on output directory
mOutputDir = ( mOutputDir == null ) ? "." : mOutputDir;
File dir = new File( mOutputDir );
if( dir.exists() ){
//directory already exists.
if ( dir.isDirectory() ){
if ( !dir.canWrite() ){
throw new RuntimeException( "Cannot write out to output directory " +
mOutputDir );
}
}
else{
//directory is a file
throw new RuntimeException( mOutputDir + " is not a directory ");
}
}
else{
dir.mkdirs();
}
String output;
try{
output = this.convert(mInputFile, mOutputDir );
System.out.println( "Pegasus Properties Written out to file " + output );
}
catch( IOException ioe ){
throw new RuntimeException( "Unable to convert properties file ", ioe );
}
}
/**
* Parses the command line arguments using GetOpt and returns a
* <code>PlannerOptions</code> contains all the options passed by the
* user at the command line.
*
* @param args the arguments passed by the user at command line.
*/
public void parseCommandLineArguments(String[] args){
LongOpt[] longOptions = generateValidOptions();
Getopt g = new Getopt( "properties-converter", args,
"i:o:h",
longOptions, false);
g.setOpterr(false);
int option = 0;
while( (option = g.getopt()) != -1){
//System.out.println("Option tag " + (char)option);
switch (option) {
case 'i'://input
this.mInputFile = g.getOptarg();
break;
case 'h'://help
printLongVersion();
System.exit( 0 );
return;
case 'o'://output directory
this.mOutputDir = g.getOptarg();
break;
default: //same as help
printShortVersion();
throw new RuntimeException("Incorrect option or option usage " +
(char)option);
}
}
}
/**
* Tt generates the LongOpt which contain the valid options that the command
* will accept.
*
* @return array of <code>LongOpt</code> objects , corresponding to the valid
* options
*/
public LongOpt[] generateValidOptions(){
LongOpt[] longopts = new LongOpt[3];
longopts[0] = new LongOpt( "input", LongOpt.REQUIRED_ARGUMENT, null, 'i' );
longopts[1] = new LongOpt( "output", LongOpt.REQUIRED_ARGUMENT, null, 'o' );
longopts[2] = new LongOpt( "help", LongOpt.NO_ARGUMENT, null, 'h' );
return longopts;
}
/**
* Prints out a short description of what the command does.
*/
public void printShortVersion(){
String text =
"\n $Id$ " +
"\n " + getGVDSVersion() +
"\n Usage : properties-converter [-Dprop [..]] -i <input directory> " +
" [-o output directory] [-h]";
System.out.println(text);
}
/**
* Prints the long description, displaying in detail what the various options
* to the command stand for.
*/
public void printLongVersion(){
String text =
"\n $Id$ " +
"\n " + getGVDSVersion() +
"\n properties-converter - A tool that converts the VDS properties file to " +
"\n the corresponding Pegasus properties file " +
"\n Usage: properties-converter [-Dprop [..]] --input <input file> " +
"\n [--output output directory] [--help] " +
"\n" +
"\n Mandatory Options " +
"\n --input the path to the VDS properties file." +
"\n Other Options " +
"\n -o |--output the output directory where to generate the pegasus property file." +
"\n -h |--help generates this help." +
"\n ";
System.out.println(text);
//mLogger.log(text,LogManager.INFO_MESSAGE_LEVEL);
}
/**
* Loads all the properties that would be needed by the Toolkit classes.
*/
public void loadProperties(){
//empty for time being
}
/**
* Returns the transfer implementation.
*
* @param property property name.
*
* @return the transfer implementation,
* else the one specified by "pegasus.transfer.*.impl",
* else the DEFAULT_TRANSFER_IMPLEMENTATION.
*/
/*
public String getTransferImplementation(String property){
String value = mProps.getProperty(property,
getDefaultTransferImplementation());
if(value == null){
//check for older deprecated properties
value = mProps.getProperty("pegasus.transfer");
value = (value == null)?
mProps.getProperty("pegasus.transfer.mode"):
value;
//convert a non null value to the corresponding
//transfer implementation
if(value != null){
value = (String)transferImplementationTable().get(value);
logDeprecatedWarning("pegasus.transfer","pegasus.transfer.*.impl and " +
"pegasus.transfer.refiner");
}
}
//put in default if still we have a non null
value = (value == null)?
DEFAULT_TRANSFER_IMPLEMENTATION:
value;
return value;
}
*/
/**
* Returns the transfer refiner that is to be used for adding in the
* transfer jobs in the workflow
*
* Referred to by the "pegasus.transfer.refiner" property.
*
* @return the transfer refiner, else the DEFAULT_TRANSFER_REFINER.
*
* @see #DEFAULT_TRANSFER_REFINER
*/
/*
public String getTransferRefiner(){
String value = mProps.getProperty("pegasus.transfer.refiner");
if(value == null){
//check for older deprecated properties
value = mProps.getProperty("pegasus.transfer");
value = (value == null)?
mProps.getProperty("pegasus.transfer.mode"):
value;
//convert a non null value to the corresponding
//transfer refiner
if(value != null){
value = (String)transferRefinerTable().get(value);
logDeprecatedWarning("pegasus.transfer","pegasus.transfer.impl and " +
"pegasus.transfer.refiner");
}
}
//put in default if still we have a non null
value = (value == null)?
DEFAULT_TRANSFER_REFINER:
value;
return value;
}
*/
//SOME LOGGING PROPERTIES
/**
* Returns the file to which all the logging needs to be directed to.
*
* Referred to by the "vds.log.*" property.
*
* @return the value of the property that is specified, else
* null
*/
// public String getLoggingFile(){
// return mProps.getProperty("vds.log.*");
// }
/**
* Returns the location of the local log file where you want the messages to
* be logged. Not used for the moment.
*
* Referred to by the "vds.log4j.log" property.
*
* @return the value specified in the property file,else null.
*/
// public String getLog4JLogFile() {
// return getProperty( "vds.log.file", "vds.log4j.log" );
// }
/**
* Return returns the environment string specified for the local pool. If
* specified the registration jobs are set with these environment variables.
*
* Referred to by the "vds.local.env" property
*
* @return the environment string for local pool in properties file if
* defined, else null.
*/
// public String getLocalPoolEnvVar() {
// return mProps.getProperty( "vds.local.env" );
// }
/**
* Returns a boolean indicating whether to treat the entries in the cache
* files as a replica catalog or not.
*
* @return boolean
*/
// public boolean treatCacheAsRC(){
// return Boolean.parse(mProps.getProperty( "vds.cache.asrc"),
// false);
// }
/**
* Checks the destination location for existence, if it can
* be created, if it is writable etc.
*
* @param dir is the new base directory to optionally create.
*
* @throws IOException in case of error while writing out files.
*/
protected static void sanityCheck( File dir ) throws IOException{
if ( dir.exists() ) {
// location exists
if ( dir.isDirectory() ) {
// ok, isa directory
if ( dir.canWrite() ) {
// can write, all is well
return;
} else {
// all is there, but I cannot write to dir
throw new IOException( "Cannot write to existing directory " +
dir.getPath() );
}
} else {
// exists but not a directory
throw new IOException( "Destination " + dir.getPath() + " already " +
"exists, but is not a directory." );
}
} else {
// does not exist, try to make it
if ( ! dir.mkdirs() ) {
throw new IOException( "Unable to create directory destination " +
dir.getPath() );
}
}
}
/**
* Extracts a specific property key subset from the known properties.
* The prefix may be removed from the keys in the resulting dictionary,
* or it may be kept. In the latter case, exact matches on the prefix
* will also be copied into the resulting dictionary.
*
* @param properties is the properties from where to get the subset.
* @param prefix is the key prefix to filter the properties by.
* @param keepPrefix if true, the key prefix is kept in the resulting
* dictionary. As side-effect, a key that matches the prefix
* exactly will also be copied. If false, the resulting
* dictionary's keys are shortened by the prefix. An
* exact prefix match will not be copied, as it would
* result in an empty string key.
*
* @return a property dictionary matching the filter key. May be
* an empty dictionary, if no prefix matches were found.
*
* @see #getProperty( String ) is used to assemble matches
*/
public Properties matchingSubset( Properties properties, String prefix, boolean keepPrefix ) {
Properties result = new Properties();
// sanity check
if ( prefix == null || prefix.length() == 0 ) return result;
String prefixMatch; // match prefix strings with this
String prefixSelf; // match self with this
if ( prefix.charAt(prefix.length()-1) != '.' ) {
// prefix does not end in a dot
prefixSelf = prefix;
prefixMatch = prefix + '.';
} else {
// prefix does end in one dot, remove for exact matches
prefixSelf = prefix.substring( 0, prefix.length()-1 );
prefixMatch = prefix;
}
// POSTCONDITION: prefixMatch and prefixSelf are initialized!
// now add all matches into the resulting properties.
// Remark 1: #propertyNames() will contain the System properties!
// Remark 2: We need to give priority to System properties. This is done
// automatically by calling this class's getProperty method.
String key;
for ( Enumeration e = properties.propertyNames(); e.hasMoreElements(); ) {
key = (String) e.nextElement();
if ( keepPrefix ) {
// keep full prefix in result, also copy direct matches
if ( key.startsWith(prefixMatch) || key.equals(prefixSelf) )
result.setProperty( key,
(String)properties.get(key) );
} else {
// remove full prefix in result, dont copy direct matches
if ( key.startsWith(prefixMatch) )
result.setProperty( key.substring( prefixMatch.length() ),
(String)properties.get(key) );
}
}
// done
return result;
}
/**
* Associates a VDS property with the new pegasus property.
*
* @param vdsProperty the old VDS property.
* @param pegasusProperty the new Pegasus property.
*
*/
private static void associate( String vdsProperty, String pegasusProperty ){
if( mVDSToPegasusPropertiesTable == null ){
mVDSToPegasusPropertiesTable = new HashMap(13);
}
mVDSToPegasusPropertiesTable.put( vdsProperty, pegasusProperty );
}
}
|
Changed pegasus.schema.ptc to pegasus.catalog.provenance to be more consistent
|
src/org/griphyn/cPlanner/toolkit/VDS2PegasusProperties.java
|
Changed pegasus.schema.ptc to pegasus.catalog.provenance to be more consistent
|
|
Java
|
apache-2.0
|
2d820e4a9a609d9fd323c0f5683397b528108ff2
| 0
|
PangZhi/flink,fanzhidongyzby/flink,godfreyhe/flink,tillrohrmann/flink,zimmermatt/flink,zentol/flink,rmetzger/flink,hongyuhong/flink,StephanEwen/incubator-flink,darionyaphet/flink,DieBauer/flink,tony810430/flink,godfreyhe/flink,gyfora/flink,aljoscha/flink,kl0u/flink,hwstreaming/flink,bowenli86/flink,zhangminglei/flink,kl0u/flink,yew1eb/flink,zohar-mizrahi/flink,tony810430/flink,zentol/flink,hongyuhong/flink,wwjiang007/flink,fanzhidongyzby/flink,hongyuhong/flink,mylog00/flink,mtunique/flink,xccui/flink,zohar-mizrahi/flink,ueshin/apache-flink,apache/flink,mbode/flink,tillrohrmann/flink,mylog00/flink,DieBauer/flink,apache/flink,kaibozhou/flink,zohar-mizrahi/flink,yew1eb/flink,darionyaphet/flink,twalthr/flink,bowenli86/flink,hwstreaming/flink,hwstreaming/flink,DieBauer/flink,tillrohrmann/flink,GJL/flink,rmetzger/flink,mbode/flink,xccui/flink,tillrohrmann/flink,gyfora/flink,zjureel/flink,rmetzger/flink,lincoln-lil/flink,zohar-mizrahi/flink,yew1eb/flink,WangTaoTheTonic/flink,zhangminglei/flink,rmetzger/flink,greghogan/flink,StephanEwen/incubator-flink,gustavoanatoly/flink,zjureel/flink,yew1eb/flink,godfreyhe/flink,zjureel/flink,tony810430/flink,haohui/flink,kl0u/flink,ueshin/apache-flink,wwjiang007/flink,kl0u/flink,aljoscha/flink,tzulitai/flink,sunjincheng121/flink,tzulitai/flink,mtunique/flink,haohui/flink,zentol/flink,jinglining/flink,zentol/flink,godfreyhe/flink,rmetzger/flink,aljoscha/flink,shaoxuan-wang/flink,greghogan/flink,GJL/flink,clarkyzl/flink,apache/flink,ueshin/apache-flink,wwjiang007/flink,Xpray/flink,mylog00/flink,sunjincheng121/flink,zentol/flink,fhueske/flink,zentol/flink,jinglining/flink,hwstreaming/flink,gyfora/flink,bowenli86/flink,apache/flink,jinglining/flink,xccui/flink,greghogan/flink,jinglining/flink,haohui/flink,bowenli86/flink,wwjiang007/flink,shaoxuan-wang/flink,DieBauer/flink,ueshin/apache-flink,aljoscha/flink,fhueske/flink,fhueske/flink,twalthr/flink,greghogan/flink,kl0u/flink,tony810430/flink,tony810430/flink,jinglining/flink,lincoln-lil/flink,zjureel/flink,mylog00/flink,xccui/flink,StephanEwen/incubator-flink,tzulitai/flink,twalthr/flink,tillrohrmann/flink,mtunique/flink,greghogan/flink,gustavoanatoly/flink,fanzhidongyzby/flink,rmetzger/flink,Xpray/flink,fanzhidongyzby/flink,rmetzger/flink,tzulitai/flink,gustavoanatoly/flink,hongyuhong/flink,zjureel/flink,sunjincheng121/flink,kaibozhou/flink,bowenli86/flink,zimmermatt/flink,mbode/flink,tony810430/flink,gyfora/flink,hwstreaming/flink,zimmermatt/flink,fhueske/flink,zhangminglei/flink,lincoln-lil/flink,Xpray/flink,godfreyhe/flink,clarkyzl/flink,gustavoanatoly/flink,GJL/flink,twalthr/flink,GJL/flink,kl0u/flink,hequn8128/flink,zimmermatt/flink,apache/flink,darionyaphet/flink,fanyon/flink,tony810430/flink,StephanEwen/incubator-flink,kaibozhou/flink,fanyon/flink,sunjincheng121/flink,hequn8128/flink,tzulitai/flink,DieBauer/flink,xccui/flink,PangZhi/flink,zentol/flink,WangTaoTheTonic/flink,hequn8128/flink,mtunique/flink,zimmermatt/flink,sunjincheng121/flink,hequn8128/flink,wwjiang007/flink,zjureel/flink,zjureel/flink,PangZhi/flink,kaibozhou/flink,lincoln-lil/flink,fanzhidongyzby/flink,PangZhi/flink,WangTaoTheTonic/flink,hequn8128/flink,sunjincheng121/flink,tzulitai/flink,gyfora/flink,mbode/flink,WangTaoTheTonic/flink,gyfora/flink,Xpray/flink,haohui/flink,shaoxuan-wang/flink,zhangminglei/flink,GJL/flink,hongyuhong/flink,jinglining/flink,haohui/flink,twalthr/flink,tillrohrmann/flink,darionyaphet/flink,fanyon/flink,clarkyzl/flink,aljoscha/flink,shaoxuan-wang/flink,shaoxuan-wang/flink,PangZhi/flink,apache/flink,kaibozhou/flink,wwjiang007/flink,WangTaoTheTonic/flink,fanyon/flink,kaibozhou/flink,godfreyhe/flink,gyfora/flink,shaoxuan-wang/flink,StephanEwen/incubator-flink,lincoln-lil/flink,fhueske/flink,zohar-mizrahi/flink,tillrohrmann/flink,gustavoanatoly/flink,apache/flink,twalthr/flink,fhueske/flink,lincoln-lil/flink,bowenli86/flink,xccui/flink,wwjiang007/flink,xccui/flink,clarkyzl/flink,ueshin/apache-flink,GJL/flink,aljoscha/flink,fanyon/flink,darionyaphet/flink,yew1eb/flink,mtunique/flink,lincoln-lil/flink,clarkyzl/flink,godfreyhe/flink,twalthr/flink,Xpray/flink,mbode/flink,StephanEwen/incubator-flink,hequn8128/flink,zhangminglei/flink,mylog00/flink,greghogan/flink
|
/***********************************************************************************************************************
*
* Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu)
*
* 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 eu.stratosphere.sopremo.serialization;
import eu.stratosphere.pact.common.type.PactRecord;
import eu.stratosphere.pact.common.type.Value;
import eu.stratosphere.sopremo.pact.JsonNodeWrapper;
import eu.stratosphere.sopremo.pact.SopremoUtil;
import eu.stratosphere.sopremo.type.ArrayNode;
import eu.stratosphere.sopremo.type.IArrayNode;
import eu.stratosphere.sopremo.type.IJsonNode;
/**
* @author Michael Hopstock
* @author Tommy Neubert
*/
public class ArraySchema implements Schema {
// [ head, ArrayNode(others) ]
/**
*
*/
private static final long serialVersionUID = 4772055788210326536L;
private int headSize;
public void setHeadSize(int headSize) {
this.headSize = headSize;
}
/*
* (non-Javadoc)
* @see eu.stratosphere.sopremo.serialization.Schema#getPactSchema()
*/
@Override
public Class<? extends Value>[] getPactSchema() {
Class<? extends Value>[] schema = new Class[mappingSize()];
for (int i = 0; i < mappingSize(); i++) {
schema[i] = JsonNodeWrapper.class;
}
return schema;
}
/*
* (non-Javadoc)
* @see eu.stratosphere.sopremo.serialization.Schema#jsonToRecord(eu.stratosphere.sopremo.type.IJsonNode,
* eu.stratosphere.pact.common.type.PactRecord)
*/
@Override
public PactRecord jsonToRecord(IJsonNode value, PactRecord target) {
IArrayNode others;
if (target == null) {
// the last element is the field "others"
target = new PactRecord(this.headSize /*+ this.tailSize*/ + 1);
others = new ArrayNode();
target.setField(headSize, new JsonNodeWrapper(others));
} else {
//clear the others field if target was already used
others = (IArrayNode) SopremoUtil.unwrap(target.getField(this.headSize, JsonNodeWrapper.class));
others.clear();
}
IJsonNode arrayElement;
for (int i = 0; i < this.headSize; i++) {
arrayElement = ((IArrayNode) value).get(i);
if(!arrayElement.isMissing()){
target.setField(i, new JsonNodeWrapper());
} else{
target.setNull(i);
}
}
//if there are still remaining elements in the array we put insert them into the others field
if (this.mappingSize() < ((IArrayNode) value).size()) {
for (int i = this.headSize; i < ((IArrayNode) value).size(); i++){
others.add(((IArrayNode)value).get(i));
}
}
return target;
}
/*
* (non-Javadoc)
* @see eu.stratosphere.sopremo.serialization.Schema#recordToJson(eu.stratosphere.pact.common.type.PactRecord,
* eu.stratosphere.sopremo.type.IJsonNode)
*/
@Override
public IJsonNode recordToJson(PactRecord record, IJsonNode target) {
// TODO
return target;
}
/**
* @return
*/
private int mappingSize() {
return this.headSize;
}
}
|
sopremo/sopremo-common/src/main/java/eu/stratosphere/sopremo/serialization/ArraySchema.java
|
/***********************************************************************************************************************
*
* Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu)
*
* 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 eu.stratosphere.sopremo.serialization;
import eu.stratosphere.pact.common.type.PactRecord;
import eu.stratosphere.pact.common.type.Value;
import eu.stratosphere.sopremo.pact.JsonNodeWrapper;
import eu.stratosphere.sopremo.type.ArrayNode;
import eu.stratosphere.sopremo.type.IArrayNode;
import eu.stratosphere.sopremo.type.IJsonNode;
/**
* @author Michael Hopstock
* @author Tommy Neubert
*/
public class ArraySchema implements Schema {
// [ head, tail, ArrayNode(others) ]
/**
*
*/
private static final long serialVersionUID = 4772055788210326536L;
private int headSize;
private int tailSize;
public void setHeadSize(int headSize) {
this.headSize = headSize;
}
public void setTailSize(int tailSize) {
this.tailSize = tailSize;
}
/*
* (non-Javadoc)
* @see eu.stratosphere.sopremo.serialization.Schema#getPactSchema()
*/
@Override
public Class<? extends Value>[] getPactSchema() {
Class<? extends Value>[] schema = new Class[mappingSize()];
for (int i = 0; i < mappingSize(); i++) {
schema[i] = JsonNodeWrapper.class;
}
return schema;
}
/*
* (non-Javadoc)
* @see eu.stratosphere.sopremo.serialization.Schema#jsonToRecord(eu.stratosphere.sopremo.type.IJsonNode,
* eu.stratosphere.pact.common.type.PactRecord)
*/
@Override
public PactRecord jsonToRecord(IJsonNode value, PactRecord target) {
if (target == null) {
// the last element is the field "others"
target = new PactRecord(this.headSize + this.tailSize + 1);
}
for (int i = 0; i < mappingSize(); i++) {
if (i < this.headSize) {
// traverse head
target.setField(i, new JsonNodeWrapper(((IArrayNode) value).get(i)));
} else {
// traverse tail, insert them after head
target.setField(
i,
new JsonNodeWrapper(((IArrayNode) value).get(((IArrayNode) value).size() - this.tailSize
+ (i - this.headSize))));
}
}
if (this.headSize + this.tailSize >= ((IArrayNode) value).size()) {
target.setField(this.mappingSize(), new JsonNodeWrapper(new ArrayNode()));
} else {
}
return target;
}
/*
* (non-Javadoc)
* @see eu.stratosphere.sopremo.serialization.Schema#recordToJson(eu.stratosphere.pact.common.type.PactRecord,
* eu.stratosphere.sopremo.type.IJsonNode)
*/
@Override
public IJsonNode recordToJson(PactRecord record, IJsonNode target) {
// TODO
return target;
}
/**
* @return
*/
private int mappingSize() {
return this.headSize + this.tailSize;
}
}
|
removed tail from ArraySchema
|
sopremo/sopremo-common/src/main/java/eu/stratosphere/sopremo/serialization/ArraySchema.java
|
removed tail from ArraySchema
|
|
Java
|
apache-2.0
|
52f3e5bf2e519f0f08a998c0b382831cffead331
| 0
|
binfalse/incubator-taverna-language,taverna-incubator/incubator-taverna-language,taverna-incubator/incubator-taverna-language,taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language,binfalse/incubator-taverna-language,binfalse/incubator-taverna-language,taverna-incubator/incubator-taverna-language
|
package uk.org.taverna.scufl2.api.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import uk.org.taverna.scufl2.api.ExampleWorkflow;
import uk.org.taverna.scufl2.api.activity.Activity;
import uk.org.taverna.scufl2.api.common.Visitor.VisitorWithPath;
import uk.org.taverna.scufl2.api.configurations.Configuration;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;
import uk.org.taverna.scufl2.api.core.BlockingControlLink;
import uk.org.taverna.scufl2.api.core.ControlLink;
import uk.org.taverna.scufl2.api.core.DataLink;
import uk.org.taverna.scufl2.api.core.Processor;
import uk.org.taverna.scufl2.api.iterationstrategy.CrossProduct;
import uk.org.taverna.scufl2.api.profiles.ProcessorBinding;
import uk.org.taverna.scufl2.api.profiles.ProcessorInputPortBinding;
import uk.org.taverna.scufl2.api.profiles.ProcessorOutputPortBinding;
import uk.org.taverna.scufl2.api.property.PropertyResource;
public class TestURIToolsBeans {
private static final String BUNDLE_URI = "http://ns.taverna.org.uk/2010/workflowBundle/28f7c554-4f35-401f-b34b-516e9a0ef731/";
private static final String HELLOWORLD_URI = BUNDLE_URI
+ "workflow/HelloWorld/";
private static final String HELLO_URI = HELLOWORLD_URI + "processor/Hello/";
private URITools uriTools = new URITools();
private Scufl2Tools scufl2Tools = new Scufl2Tools();
private WorkflowBundle wfBundle;
@Before
public void makeExampleWorkflow() {
wfBundle = new ExampleWorkflow().makeWorkflowBundle();
}
@Test
public void uriForActivity() throws Exception {
Activity activity = wfBundle.getMainProfile().getActivities()
.getByName("HelloScript");
URI uri = uriTools.uriForBean(activity);
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "activity/HelloScript/", uri.toASCIIString());
}
@Test
public void uriForActivityInput() throws Exception {
Activity activity = wfBundle.getMainProfile().getActivities()
.getByName("HelloScript");
URI uri = uriTools.uriForBean(activity.getInputPorts().getByName(
"personName"));
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "activity/HelloScript/in/personName", uri.toASCIIString());
}
@Test
public void uriForActivityOutput() throws Exception {
Activity activity = wfBundle.getMainProfile().getActivities()
.getByName("HelloScript");
URI uri = uriTools.uriForBean(activity.getOutputPorts().getByName(
"hello"));
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "activity/HelloScript/out/hello", uri.toASCIIString());
}
@Test
public void uriForConfig() throws Exception {
Configuration config = wfBundle.getMainProfile().getConfigurations()
.getByName("Hello");
URI uri = uriTools.uriForBean(config);
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "configuration/Hello/" + "", uri.toASCIIString());
}
@Test(expected = IllegalStateException.class)
public void uriForConfigPropertyResourceFails() throws Exception {
PropertyResource propResource = wfBundle.getMainProfile()
.getConfigurations().getByName("Hello").getPropertyResource();
URI uri = uriTools.uriForBean(propResource);
}
@Test
public void uriForConfigPropertyResourceWithUri() throws Exception {
PropertyResource propResource = wfBundle.getMainProfile()
.getConfigurations().getByName("Hello").getPropertyResource();
propResource.setResourceURI(URI.create("http://example.com/fish"));
URI uri = uriTools.uriForBean(propResource);
assertEquals("http://example.com/fish", uri.toASCIIString());
}
@Test
public void uriForControlLink() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
ControlLink condition = wfBundle.getMainWorkflow().getControlLinks()
.iterator().next();
assertTrue(condition instanceof BlockingControlLink);
URI uri = uriTools.uriForBean(condition);
assertEquals(
HELLOWORLD_URI
+ "control?block=processor/Hello/&untilFinished=processor/wait4me/",
uri.toASCIIString());
}
@Test
public void uriForDatalink() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
List<DataLink> nameLinks = scufl2Tools.datalinksTo(hello
.getInputPorts().getByName("name"));
URI uri = uriTools.uriForBean(nameLinks.get(0));
assertEquals(HELLOWORLD_URI
+ "datalink?from=in/yourName&to=processor/Hello/in/name",
uri.toASCIIString());
}
@Test
public void uriForDatalinkWithMerge() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
List<DataLink> greetingLinks = scufl2Tools.datalinksFrom(hello
.getOutputPorts().getByName("greeting"));
URI uri = uriTools.uriForBean(greetingLinks.get(0));
assertEquals(
HELLOWORLD_URI
+ "datalink?from=processor/Hello/out/greeting&to=out/results&mergePosition=0",
uri.toASCIIString());
}
@Test
public void uriForDispatchStack() throws Exception {
URI uri = uriTools.uriForBean(wfBundle.getMainWorkflow()
.getProcessors().getByName("Hello").getDispatchStack());
assertEquals(HELLO_URI + "dispatchstack/", uri.toASCIIString());
}
@Test
public void uriForDispatchStackLayer() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
URI uri = uriTools.uriForBean(hello.getDispatchStack().get(0));
assertEquals(HELLO_URI + "dispatchstack/0/", uri.toASCIIString());
}
@Test
public void uriForIterationStrategyCross() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
CrossProduct crossProduct = (CrossProduct) hello
.getIterationStrategyStack().get(0);
URI uri = uriTools.uriForBean(crossProduct.get(0));
assertEquals(HELLO_URI + "iterationstrategy/0/0/",
uri.toASCIIString());
}
@Test
public void uriForIterationStrategyRoot() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
URI uri = uriTools.uriForBean(hello.getIterationStrategyStack().get(0));
assertEquals(HELLO_URI + "iterationstrategy/0/",
uri.toASCIIString());
}
@Test
public void uriForIterationStrategyStack() throws Exception {
URI uri = uriTools
.uriForBean(wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello").getIterationStrategyStack());
assertEquals(HELLO_URI +
"iterationstrategy/", uri.toASCIIString());
}
@Test
public void uriForProcessor() throws Exception {
URI uri = uriTools.uriForBean(wfBundle.getMainWorkflow()
.getProcessors().getByName("Hello"));
assertEquals(HELLO_URI, uri.toASCIIString());
}
@Test
public void uriForProcessorBinding() throws Exception {
ProcessorBinding processorBinding = wfBundle.getMainProfile()
.getProcessorBindings().getByName("Hello");
URI uri = uriTools.uriForBean(processorBinding);
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "processorbinding/Hello/", uri.toASCIIString());
}
@Test
public void uriForProcessorBindingIn() throws Exception {
ProcessorBinding processorBinding = wfBundle.getMainProfile()
.getProcessorBindings().getByName("Hello");
ProcessorInputPortBinding inputPortBinding = processorBinding
.getInputPortBindings().iterator().next();
URI uri = uriTools.uriForBean(inputPortBinding);
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "processorbinding/Hello/in/name" + "", uri.toASCIIString());
}
@Test
public void uriForProcessorBindingOut() throws Exception {
ProcessorBinding processorBinding = wfBundle.getMainProfile()
.getProcessorBindings().getByName("Hello");
ProcessorOutputPortBinding outputPortBinding = processorBinding
.getOutputPortBindings().iterator().next();
URI uri = uriTools.uriForBean(outputPortBinding);
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "processorbinding/Hello/out/greeting" + "",
uri.toASCIIString());
}
@Test
public void uriForProcessorInPort() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
URI uri = uriTools.uriForBean(hello.getInputPorts().getByName("name"));
assertEquals(HELLO_URI + "in/name", uri.toASCIIString());
}
@Test
public void uriForProcessorOutPort() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
URI uri = uriTools.uriForBean(hello.getOutputPorts().getByName(
"greeting"));
assertEquals(HELLO_URI + "out/greeting", uri.toASCIIString());
}
@Test
public void uriForProfile() throws Exception {
URI uri = uriTools.uriForBean(wfBundle.getMainProfile());
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/" + "",
uri.toASCIIString());
}
@Test
public void uriForWfBundle() throws Exception {
URI uri = uriTools.uriForBean(wfBundle);
assertEquals(BUNDLE_URI, uri.toASCIIString());
}
@Test
public void uriForWorkflow() throws Exception {
URI uri = uriTools.uriForBean(wfBundle.getMainWorkflow());
assertEquals(HELLOWORLD_URI, uri.toASCIIString());
}
@Test
public void uriForWorkflowInPort() throws Exception {
URI uri = uriTools.uriForBean(wfBundle.getMainWorkflow()
.getInputPorts().getByName("yourName"));
assertEquals(HELLOWORLD_URI + "in/yourName", uri.toASCIIString());
}
@Test
public void uriForWorkflowOutPort() throws Exception {
URI uri = uriTools.uriForBean(wfBundle.getMainWorkflow()
.getOutputPorts().getByName("results"));
assertEquals(HELLOWORLD_URI + "out/results", uri.toASCIIString());
}
@Test
public void uriVisitor() {
final StringBuffer paths = new StringBuffer();
wfBundle.accept(new VisitorWithPath() {
@Override
public boolean visit() {
WorkflowBean node = getCurrentNode();
URI uri;
if (getCurrentPath().isEmpty()) {
uri = uriTools.uriForBean(node);
} else {
uri = uriTools.relativeUriForBean(node, getCurrentPath()
.peek());
}
String indent = "";
for (int i = 0; i < getCurrentPath().size(); i++) {
indent += " ";
}
paths.append(indent);
paths.append(uri);
paths.append("\n");
// we won't recurse into Configuration as PropertyResource's
// don't have URIs
return !(node instanceof Configuration);
}
});
// System.out.println(paths);
assertEquals(
"http://ns.taverna.org.uk/2010/workflowBundle/28f7c554-4f35-401f-b34b-516e9a0ef731/\n"
+ " workflow/HelloWorld/\n"
+ " in/yourName\n"
+ " out/results\n"
+ " processor/Hello/\n"
+ " in/name\n"
+ " out/greeting\n"
+ " iterationstrategy/\n"
+ " 0/\n"
+ " 0/\n"
+ " dispatchstack/\n"
+ " 0/\n"
+ " 1/\n"
+ " 2/\n"
+ " 3/\n"
+ " 4/\n"
+ " 5/\n"
+ " processor/wait4me/\n"
+ " iterationstrategy/\n"
+ " 0/\n"
+ " dispatchstack/\n"
+ " 0/\n"
+ " 1/\n"
+ " 2/\n"
+ " 3/\n"
+ " 4/\n"
+ " 5/\n"
+ " datalink?from=in/yourName&to=processor/Hello/in/name\n"
+ " datalink?from=in/yourName&to=out/results&mergePosition=1\n"
+ " datalink?from=processor/Hello/out/greeting&to=out/results&mergePosition=0\n"
+ " control?block=processor/Hello/&untilFinished=processor/wait4me/\n"
+ " ../../../../workflow/00626652-55ae-4a9e-80d4-c8e9ac84e2ca/\n"
+ " profile/tavernaServer/\n"
+ " activity/HelloScript/\n"
+ " in/personName\n"
+ " out/hello\n"
+ " processorbinding/Hello/\n"
+ " in/name\n"
+ " out/greeting\n"
+ " configuration/Hello/\n"
+ " profile/tavernaWorkbench/\n"
+ " activity/HelloScript/\n"
+ " in/personName\n"
+ " out/hello\n"
+ " processorbinding/Hello/\n"
+ " in/name\n"
+ " out/greeting\n"
+ " configuration/Hello/\n",
paths.toString());
}
}
|
scufl2-api/src/test/java/uk/org/taverna/scufl2/api/common/TestURIToolsBeans.java
|
package uk.org.taverna.scufl2.api.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import uk.org.taverna.scufl2.api.ExampleWorkflow;
import uk.org.taverna.scufl2.api.activity.Activity;
import uk.org.taverna.scufl2.api.common.Visitor.VisitorWithPath;
import uk.org.taverna.scufl2.api.configurations.Configuration;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;
import uk.org.taverna.scufl2.api.core.BlockingControlLink;
import uk.org.taverna.scufl2.api.core.ControlLink;
import uk.org.taverna.scufl2.api.core.DataLink;
import uk.org.taverna.scufl2.api.core.Processor;
import uk.org.taverna.scufl2.api.iterationstrategy.CrossProduct;
import uk.org.taverna.scufl2.api.profiles.ProcessorBinding;
import uk.org.taverna.scufl2.api.profiles.ProcessorInputPortBinding;
import uk.org.taverna.scufl2.api.profiles.ProcessorOutputPortBinding;
import uk.org.taverna.scufl2.api.property.PropertyResource;
public class TestURIToolsBeans {
private static final String BUNDLE_URI = "http://ns.taverna.org.uk/2010/workflowBundle/28f7c554-4f35-401f-b34b-516e9a0ef731/";
private static final String HELLOWORLD_URI = BUNDLE_URI
+ "workflow/HelloWorld/";
private static final String HELLO_URI = HELLOWORLD_URI + "processor/Hello/";
private URITools uriTools = new URITools();
private Scufl2Tools scufl2Tools = new Scufl2Tools();
private WorkflowBundle wfBundle;
@Before
public void makeExampleWorkflow() {
wfBundle = new ExampleWorkflow().makeWorkflowBundle();
}
@Test
public void uriForActivity() throws Exception {
Activity activity = wfBundle.getMainProfile().getActivities()
.getByName("HelloScript");
URI uri = uriTools.uriForBean(activity);
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "activity/HelloScript/", uri.toASCIIString());
}
@Test
public void uriForActivityInput() throws Exception {
Activity activity = wfBundle.getMainProfile().getActivities()
.getByName("HelloScript");
URI uri = uriTools.uriForBean(activity.getInputPorts().getByName(
"personName"));
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "activity/HelloScript/in/personName", uri.toASCIIString());
}
@Test
public void uriForActivityOutput() throws Exception {
Activity activity = wfBundle.getMainProfile().getActivities()
.getByName("HelloScript");
URI uri = uriTools.uriForBean(activity.getOutputPorts().getByName(
"hello"));
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "activity/HelloScript/out/hello", uri.toASCIIString());
}
@Test
public void uriForConfig() throws Exception {
Configuration config = wfBundle.getMainProfile().getConfigurations()
.getByName("Hello");
URI uri = uriTools.uriForBean(config);
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "configuration/Hello/" + "", uri.toASCIIString());
}
@Test(expected = IllegalStateException.class)
public void uriForConfigPropertyResourceFails() throws Exception {
PropertyResource propResource = wfBundle.getMainProfile()
.getConfigurations().getByName("Hello").getPropertyResource();
URI uri = uriTools.uriForBean(propResource);
}
@Test
public void uriForConfigPropertyResourceWithUri() throws Exception {
PropertyResource propResource = wfBundle.getMainProfile()
.getConfigurations().getByName("Hello").getPropertyResource();
propResource.setResourceURI(URI.create("http://example.com/fish"));
URI uri = uriTools.uriForBean(propResource);
assertEquals("http://example.com/fish", uri.toASCIIString());
}
@Test
public void uriForControlLink() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
ControlLink condition = wfBundle.getMainWorkflow().getControlLinks()
.iterator().next();
assertTrue(condition instanceof BlockingControlLink);
URI uri = uriTools.uriForBean(condition);
assertEquals(
HELLOWORLD_URI
+ "control?block=processor/Hello/&untilFinished=processor/wait4me/",
uri.toASCIIString());
}
@Test
public void uriForDatalink() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
List<DataLink> nameLinks = scufl2Tools.datalinksTo(hello
.getInputPorts().getByName("name"));
URI uri = uriTools.uriForBean(nameLinks.get(0));
assertEquals(HELLOWORLD_URI
+ "datalink?from=in/yourName&to=processor/Hello/in/name",
uri.toASCIIString());
}
@Test
public void uriForDatalinkWithMerge() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
List<DataLink> greetingLinks = scufl2Tools.datalinksFrom(hello
.getOutputPorts().getByName("greeting"));
URI uri = uriTools.uriForBean(greetingLinks.get(0));
assertEquals(
HELLOWORLD_URI
+ "datalink?from=processor/Hello/out/greeting&to=out/results&mergePosition=0",
uri.toASCIIString());
}
@Test
public void uriForDispatchStack() throws Exception {
URI uri = uriTools.uriForBean(wfBundle.getMainWorkflow()
.getProcessors().getByName("Hello").getDispatchStack());
assertEquals(HELLO_URI + "dispatchstack/", uri.toASCIIString());
}
@Test
public void uriForDispatchStackLayer() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
URI uri = uriTools.uriForBean(hello.getDispatchStack().get(0));
assertEquals(HELLO_URI + "dispatchstack/0/", uri.toASCIIString());
}
@Test
public void uriForIterationStrategyCross() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
CrossProduct crossProduct = (CrossProduct) hello
.getIterationStrategyStack().get(0);
URI uri = uriTools.uriForBean(crossProduct.get(0));
assertEquals(HELLO_URI + "iterationstrategy/0/0/",
uri.toASCIIString());
}
@Test
public void uriForIterationStrategyRoot() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
URI uri = uriTools.uriForBean(hello.getIterationStrategyStack().get(0));
assertEquals(HELLO_URI + "iterationstrategy/0/",
uri.toASCIIString());
}
@Test
public void uriForIterationStrategyStack() throws Exception {
URI uri = uriTools
.uriForBean(wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello").getIterationStrategyStack());
assertEquals(HELLO_URI +
"iterationstrategy/", uri.toASCIIString());
}
@Test
public void uriForProcessor() throws Exception {
URI uri = uriTools.uriForBean(wfBundle.getMainWorkflow()
.getProcessors().getByName("Hello"));
assertEquals(HELLO_URI, uri.toASCIIString());
}
@Test
public void uriForProcessorBinding() throws Exception {
ProcessorBinding processorBinding = wfBundle.getMainProfile()
.getProcessorBindings().getByName("Hello");
URI uri = uriTools.uriForBean(processorBinding);
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "processorbinding/Hello/", uri.toASCIIString());
}
@Test
public void uriForProcessorBindingIn() throws Exception {
ProcessorBinding processorBinding = wfBundle.getMainProfile()
.getProcessorBindings().getByName("Hello");
ProcessorInputPortBinding inputPortBinding = processorBinding
.getInputPortBindings().iterator().next();
URI uri = uriTools.uriForBean(inputPortBinding);
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "processorbinding/Hello/in/name" + "", uri.toASCIIString());
}
@Test
public void uriForProcessorBindingOut() throws Exception {
ProcessorBinding processorBinding = wfBundle.getMainProfile()
.getProcessorBindings().getByName("Hello");
ProcessorOutputPortBinding outputPortBinding = processorBinding
.getOutputPortBindings().iterator().next();
URI uri = uriTools.uriForBean(outputPortBinding);
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/"
+ "processorbinding/Hello/out/greeting" + "",
uri.toASCIIString());
}
@Test
public void uriForProcessorInPort() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
URI uri = uriTools.uriForBean(hello.getInputPorts().getByName("name"));
assertEquals(HELLO_URI + "in/name", uri.toASCIIString());
}
@Test
public void uriForProcessorOutPort() throws Exception {
Processor hello = wfBundle.getMainWorkflow().getProcessors()
.getByName("Hello");
URI uri = uriTools.uriForBean(hello.getOutputPorts().getByName(
"greeting"));
assertEquals(HELLO_URI + "out/greeting", uri.toASCIIString());
}
@Test
public void uriForProfile() throws Exception {
URI uri = uriTools.uriForBean(wfBundle.getMainProfile());
assertEquals(BUNDLE_URI + "profile/tavernaWorkbench/" + "",
uri.toASCIIString());
}
@Test
public void uriForWfBundle() throws Exception {
URI uri = uriTools.uriForBean(wfBundle);
assertEquals(BUNDLE_URI, uri.toASCIIString());
}
@Test
public void uriForWorkflow() throws Exception {
URI uri = uriTools.uriForBean(wfBundle.getMainWorkflow());
assertEquals(HELLOWORLD_URI, uri.toASCIIString());
}
@Test
public void uriForWorkflowInPort() throws Exception {
URI uri = uriTools.uriForBean(wfBundle.getMainWorkflow()
.getInputPorts().getByName("yourName"));
assertEquals(HELLOWORLD_URI + "in/yourName", uri.toASCIIString());
}
@Test
public void uriForWorkflowOutPort() throws Exception {
URI uri = uriTools.uriForBean(wfBundle.getMainWorkflow()
.getOutputPorts().getByName("results"));
assertEquals(HELLOWORLD_URI + "out/results", uri.toASCIIString());
}
@Test
public void uriVisitor() {
final StringBuffer paths = new StringBuffer();
wfBundle.accept(new VisitorWithPath() {
@Override
public boolean visit() {
WorkflowBean node = getCurrentNode();
URI uri;
if (getCurrentPath().isEmpty()) {
uri = uriTools.uriForBean(node);
} else {
uri = uriTools.relativeUriForBean(node, getCurrentPath()
.peek());
}
String indent = "";
for (int i = 0; i < getCurrentPath().size(); i++) {
indent += " ";
}
paths.append(indent);
paths.append(uri);
paths.append("\n");
// we won't recurse into Configuration as PropertyResource's
// don't have URIs
return !(node instanceof Configuration);
}
});
// System.out.println(paths);
assertEquals(
"http://ns.taverna.org.uk/2010/workflowBundle/28f7c554-4f35-401f-b34b-516e9a0ef731/\n"
+ " workflow/HelloWorld/\n"
+ " in/yourName\n"
+ " out/results\n"
+ " processor/Hello/\n"
+ " in/name\n"
+ " out/greeting\n"
+ " iterationstrategy/\n"
+ " 0/\n"
+ " 0/\n"
+ " dispatchstack/\n"
+ " 0/\n"
+ " 1/\n"
+ " 2/\n"
+ " 3/\n"
+ " 4/\n"
+ " 5/\n"
+ " processor/wait4me/\n"
+ " iterationstrategy/\n"
+ " 0/\n"
+ " dispatchstack/\n"
+ " 0/\n"
+ " 1/\n"
+ " 2/\n"
+ " 3/\n"
+ " 4/\n"
+ " 5/\n"
+ " datalink?from=processor/Hello/out/greeting&to=out/results&mergePosition=0\n"
+ " datalink?from=in/yourName&to=processor/Hello/in/name\n"
+ " datalink?from=in/yourName&to=out/results&mergePosition=1\n"
+ " control?block=processor/Hello/&untilFinished=processor/wait4me/\n"
+ " ../../../../workflow/00626652-55ae-4a9e-80d4-c8e9ac84e2ca/\n"
+ " profile/tavernaServer/\n"
+ " activity/HelloScript/\n"
+ " in/personName\n"
+ " out/hello\n"
+ " processorbinding/Hello/\n"
+ " in/name\n"
+ " out/greeting\n"
+ " configuration/Hello/\n"
+ " profile/tavernaWorkbench/\n"
+ " activity/HelloScript/\n"
+ " in/personName\n"
+ " out/hello\n"
+ " processorbinding/Hello/\n"
+ " in/name\n"
+ " out/greeting\n"
+ " configuration/Hello/\n",
paths.toString());
}
}
|
Allow slightly different order of datalinks
|
scufl2-api/src/test/java/uk/org/taverna/scufl2/api/common/TestURIToolsBeans.java
|
Allow slightly different order of datalinks
|
|
Java
|
apache-2.0
|
bd4aaf41f9914c6f19db164d183c32931b51059c
| 0
|
OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,halober/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,halober/ovirt-engine,OpenUniversity/ovirt-engine,halober/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine,walteryang47/ovirt-engine
|
package org.ovirt.engine.core.utils.ovf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.OriginType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkStatistics;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.utils.MockConfigRule;
public class OvfVmWriterTest {
@ClassRule
public static MockConfigRule mockConfigRule =
new MockConfigRule(MockConfigRule.mockConfig(ConfigValues.VdcVersion, "1.0.0.0"));
private OvfManager manager;
@Before
public void setUp() throws Exception {
manager = new OvfManager();
}
private static void assertVm(VM vm, VM newVm, long expectedDbGeneration) {
assertEquals("imported vm is different than expected", vm, newVm);
assertEquals("imported db generation is different than expected", expectedDbGeneration, newVm.getDbGeneration());
assertEquals(vm.getStaticData(), newVm.getStaticData());
}
@Test
public void testVmOvfCreation() throws Exception {
VM vm = createVM();
String xml = manager.ExportVm(vm, new ArrayList<DiskImage>());
assertNotNull(xml);
final VM newVm = new VM();
manager.ImportVm(xml, newVm, new ArrayList<DiskImage>(), new ArrayList<VmNetworkInterface>());
assertVm(vm, newVm, vm.getDbGeneration());
}
@Test
public void testVmOvfImportWithoutDbGeneration() throws Exception {
VM vm = createVM();
String xml = manager.ExportVm(vm, new ArrayList<DiskImage>());
assertNotNull(xml);
final VM newVm = new VM();
assertTrue(xml.contains("Generation"));
String replacedXml = xml.replaceAll("Generation", "test_replaced");
manager.ImportVm(replacedXml, newVm, new ArrayList<DiskImage>(), new ArrayList<VmNetworkInterface>());
assertVm(vm, newVm, 1);
}
@Test
public void testTemplateOvfCreation() throws Exception {
VmTemplate template = createVmTemplate();
String xml = manager.ExportTemplate(template, new ArrayList<DiskImage>());
assertNotNull(xml);
final VmTemplate newtemplate = new VmTemplate();
manager.ImportTemplate(xml, newtemplate, new ArrayList<DiskImage>(), new ArrayList<VmNetworkInterface>());
assertEquals("imported template is different than expected",template, newtemplate);
assertEquals("imported db generation is different than expected",template.getDbGeneration(), newtemplate.getDbGeneration());
}
@Test
public void testTemplateOvfImportWithoutDbGeneration() throws Exception {
VmTemplate template = createVmTemplate();
String xml = manager.ExportTemplate(template, new ArrayList<DiskImage>());
assertNotNull(xml);
String replacedXml = xml.replaceAll("Generation", "test_replaced");
final VmTemplate newtemplate = new VmTemplate();
manager.ImportTemplate(replacedXml,
newtemplate,
new ArrayList<DiskImage>(),
new ArrayList<VmNetworkInterface>());
assertEquals("imported template is different than expected", template, newtemplate);
assertTrue("imported db generation is different than expected",newtemplate.getDbGeneration() == 1);
}
private static VM createVM() {
VM vm = new VM();
vm.setName("test-vm");
vm.setOrigin(OriginType.OVIRT);
vm.setId(new Guid());
vm.setVmDescription("test-description");
vm.getStaticData().setDomain("domain_name");
vm.setTimeZone("Israel Standard Time");
vm.setDbGeneration(2L);
initInterfaces(vm);
return vm;
}
private static void initInterfaces(VM vm) {
VmNetworkInterface vmInterface = new VmNetworkInterface();
vmInterface.setStatistics(new VmNetworkStatistics());
vmInterface.setId(Guid.NewGuid());
vmInterface.setName("eth77");
vmInterface.setNetworkName("blue");
vmInterface.setLinked(false);
vmInterface.setSpeed(1000);
vmInterface.setType(3);
vmInterface.setMacAddress("01:C0:81:21:71:17");
VmNetworkInterface vmInterface2 = new VmNetworkInterface();
vmInterface2.setStatistics(new VmNetworkStatistics());
vmInterface2.setId(Guid.NewGuid());
vmInterface2.setName("eth88");
vmInterface2.setNetworkName(null);
vmInterface2.setLinked(true);
vmInterface2.setSpeed(1234);
vmInterface2.setType(1);
vmInterface2.setMacAddress("02:C1:92:22:25:28");
vm.setInterfaces(Arrays.asList(vmInterface, vmInterface2));
}
private static VmTemplate createVmTemplate() {
VmTemplate template = new VmTemplate();
template.setName("test-template");
template.setOrigin(OriginType.OVIRT);
template.setId(new Guid());
template.setDescription("test-description");
template.setDbGeneration(2L);
return template;
}
}
|
backend/manager/modules/utils/src/test/java/org/ovirt/engine/core/utils/ovf/OvfVmWriterTest.java
|
package org.ovirt.engine.core.utils.ovf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.OriginType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkStatistics;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.utils.MockConfigRule;
public class OvfVmWriterTest {
@ClassRule
public static MockConfigRule mockConfigRule =
new MockConfigRule(MockConfigRule.mockConfig(ConfigValues.VdcVersion, "1.0.0.0"));
private OvfManager manager;
@Before
public void setUp() throws Exception {
manager = new OvfManager();
}
private void assertVm(VM vm, VM newVm, long expectedDbGeneration) {
assertEquals("imported vm is different than expected", vm, newVm);
assertEquals("imported db generation is different than expected", expectedDbGeneration, newVm.getDbGeneration());
assertEquals(vm.getStaticData(), newVm.getStaticData());
//assertEquals(vm.getInterfaces(), newVm.getInterfaces());
}
@Test
public void testVmOvfCreation() throws Exception {
VM vm = createVM();
String xml = manager.ExportVm(vm, new ArrayList<DiskImage>());
assertNotNull(xml);
final VM newVm = new VM();
manager.ImportVm(xml, newVm, new ArrayList<DiskImage>(), new ArrayList<VmNetworkInterface>());
assertVm(vm, newVm, vm.getDbGeneration());
}
@Test
public void testVmOvfImportWithoutDbGeneration() throws Exception {
VM vm = createVM();
String xml = manager.ExportVm(vm, new ArrayList<DiskImage>());
assertNotNull(xml);
final VM newVm = new VM();
assertTrue(xml.contains("Generation"));
String replacedXml = xml.replaceAll("Generation", "test_replaced");
manager.ImportVm(replacedXml, newVm, new ArrayList<DiskImage>(), new ArrayList<VmNetworkInterface>());
assertVm(vm, newVm, 1);
}
@Test
public void testTemplateOvfCreation() throws Exception {
VmTemplate template = createVmTemplate();
String xml = manager.ExportTemplate(template, new ArrayList<DiskImage>());
assertNotNull(xml);
final VmTemplate newtemplate = new VmTemplate();
manager.ImportTemplate(xml, newtemplate, new ArrayList<DiskImage>(), new ArrayList<VmNetworkInterface>());
assertEquals("imported template is different than expected",template, newtemplate);
assertEquals("imported db generation is different than expected",template.getDbGeneration(), newtemplate.getDbGeneration());
}
@Test
public void testTemplateOvfImportWithoutDbGeneration() throws Exception {
VmTemplate template = createVmTemplate();
String xml = manager.ExportTemplate(template, new ArrayList<DiskImage>());
assertNotNull(xml);
String replacedXml = xml.replaceAll("Generation", "test_replaced");
final VmTemplate newtemplate = new VmTemplate();
manager.ImportTemplate(replacedXml,
newtemplate,
new ArrayList<DiskImage>(),
new ArrayList<VmNetworkInterface>());
assertEquals("imported template is different than expected", template, newtemplate);
assertTrue("imported db generation is different than expected",newtemplate.getDbGeneration() == 1);
}
private static VM createVM() {
VM vm = new VM();
vm.setName("test-vm");
vm.setOrigin(OriginType.OVIRT);
vm.setId(new Guid());
vm.setVmDescription("test-description");
vm.getStaticData().setDomain("domain_name");
vm.setTimeZone("Israel Standard Time");
vm.setDbGeneration(2L);
initInterfaces(vm);
return vm;
}
private static void initInterfaces(VM vm) {
VmNetworkInterface vmInterface = new VmNetworkInterface();
vmInterface.setStatistics(new VmNetworkStatistics());
vmInterface.setId(Guid.NewGuid());
vmInterface.setName("eth77");
vmInterface.setNetworkName("blue");
vmInterface.setLinked(false);
vmInterface.setSpeed(1000);
vmInterface.setType(3);
vmInterface.setMacAddress("01:C0:81:21:71:17");
VmNetworkInterface vmInterface2 = new VmNetworkInterface();
vmInterface2.setStatistics(new VmNetworkStatistics());
vmInterface2.setId(Guid.NewGuid());
vmInterface2.setName("eth88");
vmInterface2.setNetworkName(null);
vmInterface2.setLinked(true);
vmInterface2.setSpeed(1234);
vmInterface2.setType(1);
vmInterface2.setMacAddress("02:C1:92:22:25:28");
vm.setInterfaces(Arrays.asList(vmInterface, vmInterface2));
}
private static VmTemplate createVmTemplate() {
VmTemplate template = new VmTemplate();
template.setName("test-template");
template.setOrigin(OriginType.OVIRT);
template.setId(new Guid());
template.setDescription("test-description");
template.setDbGeneration(2L);
return template;
}
}
|
core: OvfVmWriterTest.assertVm cleanup
Fixed the method's modifiers and removed a commented out line.
Change-Id: I65c7d797a725626adb7bd67f1f73f8084b803daf
Signed-off-by: Allon Mureinik <abc9ddaceaf0c059a5d9bc2aed71f25cb5370dba@redhat.com>
|
backend/manager/modules/utils/src/test/java/org/ovirt/engine/core/utils/ovf/OvfVmWriterTest.java
|
core: OvfVmWriterTest.assertVm cleanup
|
|
Java
|
apache-2.0
|
4bf3c37508563385824bed7072fdb666c97d1275
| 0
|
finmath/finmath-lib,finmath/finmath-lib
|
package net.finmath.montecarlo.interestrate.products;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import net.finmath.exception.CalculationException;
import net.finmath.functions.AnalyticFormulas;
import net.finmath.marketdata.products.Swap;
import net.finmath.marketdata.products.SwapAnnuity;
import net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationModel;
import net.finmath.montecarlo.process.ProcessTimeDiscretizationProvider;
import net.finmath.stochastic.RandomVariable;
import net.finmath.time.FloatingpointDate;
import net.finmath.time.Period;
import net.finmath.time.Schedule;
import net.finmath.time.TimeDiscretization;
import net.finmath.time.TimeDiscretizationFromArray;
/**
* Implementation of a Monte-Carlo valuation of a swaption valuation being compatible with AAD.
*
* The valuation internally uses an analytic valuation of a swap such that the {@link #getValue(double, LIBORModelMonteCarloSimulationModel)} method
* returns an valuation being \( \mathcal{F}_{t} \}-measurable where \( t \) is the evaluationTime argument.
*
* @author Christian Fries
*/
public class SwaptionFromSwapSchedules extends AbstractLIBORMonteCarloProduct implements ProcessTimeDiscretizationProvider, net.finmath.modelling.products.Swaption {
public enum SwaptionType{
PAYER,
RECEIVER
}
private final SwaptionType swaptionType;
private final LocalDate exerciseDate;
private final Schedule scheduleFixedLeg;
private final Schedule scheduleFloatLeg;
private final double swaprate;
private final double notional;
private final ValueUnit valueUnit;
private final LocalDateTime referenceDate;
public SwaptionFromSwapSchedules(
LocalDateTime referenceDate,
SwaptionType swaptionType,
LocalDate exerciseDate,
Schedule scheduleFixedLeg,
Schedule scheduleFloatLeg,
double swaprate,
double notional,
ValueUnit valueUnit) {
this.referenceDate = referenceDate;
this.swaptionType = swaptionType;
this.exerciseDate = exerciseDate;
this.scheduleFixedLeg = scheduleFixedLeg;
this.scheduleFloatLeg = scheduleFloatLeg;
this.swaprate = swaprate;
this.notional = notional;
this.valueUnit = valueUnit;
}
@Override
public RandomVariable getValue(double evaluationTime, LIBORModelMonteCarloSimulationModel model)
throws CalculationException {
LocalDate modelReferenceDate = null;
try {
modelReferenceDate = model.getReferenceDate().toLocalDate();
if(modelReferenceDate == null) {
modelReferenceDate = referenceDate.toLocalDate();
}
}
catch(UnsupportedOperationException e) {}
double exerciseTime = FloatingpointDate.getFloatingPointDateFromDate(modelReferenceDate, exerciseDate);
RandomVariable discountedCashflowFixLeg = getValueOfLegAnalytic(exerciseTime, model, scheduleFixedLeg, false, swaprate, notional);
RandomVariable discountedCashflowFloatingLeg = getValueOfLegAnalytic(exerciseTime, model, scheduleFloatLeg, true, 0.0, notional);
// Distinguish whether the swaption is of type "Payer" or "Receiver":
RandomVariable values;
if(swaptionType.equals(SwaptionType.PAYER)){
values = discountedCashflowFloatingLeg.sub(discountedCashflowFixLeg);
}
else if(swaptionType.equals(SwaptionType.RECEIVER)){
values = discountedCashflowFixLeg.sub(discountedCashflowFloatingLeg);
}
else {
throw new IllegalArgumentException("Unkown swaptionType " + swaptionType);
}
// Floor at zero
values = values.floor(0.0);
RandomVariable numeraire = model.getNumeraire(exerciseTime);
RandomVariable monteCarloProbabilities = model.getMonteCarloWeights(exerciseTime);
values = values.div(numeraire).mult(monteCarloProbabilities);
// Note that values is a relative price - no numeraire division is required
RandomVariable numeraireAtZero = model.getNumeraire(evaluationTime);
RandomVariable monteCarloProbabilitiesAtZero = model.getMonteCarloWeights(evaluationTime);
values = values.mult(numeraireAtZero).div(monteCarloProbabilitiesAtZero);
if(valueUnit == ValueUnit.VALUE) {
return values;
}
/*
* Need to convert value to different value unit.
*/
// Use analytic formula to calculate the options black/bachelier implied vol using the MC price from above:
double atmSwaprate = Swap.getForwardSwapRate(scheduleFixedLeg, scheduleFloatLeg, model.getModel().getForwardRateCurve(), model.getModel().getAnalyticModel());
double forward = atmSwaprate;
double optionStrike = swaprate;
double optionMaturity = FloatingpointDate.getFloatingPointDateFromDate(modelReferenceDate, exerciseDate);
double[] swapTenor = new double[scheduleFixedLeg.getNumberOfPeriods() + 1];
for(int i = 0; i < scheduleFixedLeg.getNumberOfPeriods(); i++) {
swapTenor[i] = scheduleFixedLeg.getFixing(i);
}
swapTenor[scheduleFixedLeg.getNumberOfPeriods()] = scheduleFixedLeg.getPayment(scheduleFixedLeg.getNumberOfPeriods() - 1);
double swapAnnuity = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor), model.getModel().getDiscountCurve());
switch(valueUnit) {
case VALUE:
return values;
case VOLATILITYNORMAL:
double volatitliy = AnalyticFormulas.bachelierOptionImpliedVolatility(forward, optionMaturity, optionStrike, swapAnnuity, values.getAverage());
return model.getRandomVariableForConstant(volatitliy);
case VOLATILITYLOGNORMAL:
return model.getRandomVariableForConstant(AnalyticFormulas.blackScholesOptionImpliedVolatility(forward, optionMaturity, optionStrike, swapAnnuity, values.getAverage()));
case VOLATILITYNORMALATM:
RandomVariable annuity = getValueOfLegAnalytic(evaluationTime, model, scheduleFixedLeg, false, 1.0, notional);
annuity = annuity.div(numeraire).mult(monteCarloProbabilities).mult(numeraireAtZero).div(monteCarloProbabilitiesAtZero);
return values.div(Math.sqrt(optionMaturity / Math.PI / 2.0)).div(annuity.average());
default:
throw new IllegalArgumentException("Unsupported valueUnit " + valueUnit.name());
}
}
@Override
public TimeDiscretization getProcessTimeDiscretization(LocalDateTime referenceDate) {
Set<Double> times = new HashSet<>();
times.add(FloatingpointDate.getFloatingPointDateFromDate(referenceDate, exerciseDate.atStartOfDay()));
Function<Period, Double> periodToTime = period -> { return FloatingpointDate.getFloatingPointDateFromDate(referenceDate, period.getPayment().atStartOfDay()); };
times.addAll(scheduleFixedLeg.getPeriods().stream().map(periodToTime).collect(Collectors.toList()));
times.addAll(scheduleFloatLeg.getPeriods().stream().map(periodToTime).collect(Collectors.toList()));
return new TimeDiscretizationFromArray(times);
}
/**
* @return the exercise date
*/
public LocalDate getExerciseDate() {
return exerciseDate;
}
/**
* Determines the time \( t \)-measurable value of a swap leg (can handle fix or float).
*
* @param evaluationTime The time \( t \) conditional to which the value is calculated.
* @param model The model implmeneting LIBORModelMonteCarloSimulationModel.
* @param schedule The schedule of the leg.
* @param paysFloatingRate If true, the leg will pay {@link LIBORModelMonteCarloSimulationModel#getLIBOR(double, double, double)}
* @param fixRate The fixed rate (if any)
* @param notional The notional
* @return The time \( t \)-measurable value
* @throws CalculationException
*/
public RandomVariable getValueOfLegAnalytic(double evaluationTime, LIBORModelMonteCarloSimulationModel model, Schedule schedule, boolean paysFloatingRate, double fixRate, double notional) throws CalculationException {
LocalDate modelReferenceDate = null;
try {
modelReferenceDate = model.getReferenceDate().toLocalDate();
if(modelReferenceDate == null) {
modelReferenceDate = referenceDate.toLocalDate();
}
}
catch(UnsupportedOperationException e) {}
RandomVariable discountedCashflowFloatingLeg = model.getRandomVariableForConstant(0.0);
for(int peridIndex = schedule.getNumberOfPeriods() - 1; peridIndex >= 0; peridIndex--) {
Period period = schedule.getPeriod(peridIndex);
double paymentTime = FloatingpointDate.getFloatingPointDateFromDate(modelReferenceDate, period.getPayment());
double fixingTime = FloatingpointDate.getFloatingPointDateFromDate(modelReferenceDate, period.getFixing());
double periodLength = schedule.getPeriodLength(peridIndex);
/*
* Note that it is important that getForwardDiscountBond and getLIBOR are called with evaluationTime = exerciseTime.
*/
RandomVariable discountBond = model.getModel().getForwardDiscountBond(evaluationTime, paymentTime);
if(paysFloatingRate) {
RandomVariable libor = model.getLIBOR(evaluationTime, fixingTime, paymentTime);
RandomVariable periodCashFlow = libor.mult(periodLength).mult(notional);
discountedCashflowFloatingLeg = discountedCashflowFloatingLeg.add(periodCashFlow.mult(discountBond));
}
if(fixRate != 0) {
RandomVariable periodCashFlow = model.getRandomVariableForConstant(swaprate * periodLength * notional);
discountedCashflowFloatingLeg = discountedCashflowFloatingLeg.add(periodCashFlow.mult(discountBond));
}
}
return discountedCashflowFloatingLeg;
}
@Override
public String toString() {
return "SwaptionConditionalAnalytic [swaptionType=" + swaptionType + ", referenceDate=" + referenceDate + ", exerciseDate="
+ exerciseDate + ", swaprate=" + swaprate + ", valueUnit=" + valueUnit
+ ", fixMetaSchedule=" + scheduleFixedLeg + ", floatMetaSchedule="
+ scheduleFloatLeg + ", notional=" + notional + "]";
}
}
|
src/main/java/net/finmath/montecarlo/interestrate/products/SwaptionFromSwapSchedules.java
|
package net.finmath.montecarlo.interestrate.products;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import net.finmath.exception.CalculationException;
import net.finmath.functions.AnalyticFormulas;
import net.finmath.marketdata.products.Swap;
import net.finmath.marketdata.products.SwapAnnuity;
import net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationModel;
import net.finmath.montecarlo.process.ProcessTimeDiscretizationProvider;
import net.finmath.stochastic.RandomVariable;
import net.finmath.time.FloatingpointDate;
import net.finmath.time.Period;
import net.finmath.time.Schedule;
import net.finmath.time.TimeDiscretization;
import net.finmath.time.TimeDiscretizationFromArray;
/**
* Implementation of a Monte-Carlo valuation of a swaption valuation being compatible with AAD.
*
* The valuation internally uses an analytic valuation of a swap such that the {@link #getValue(double, LIBORModelMonteCarloSimulationModel)} method
* returns an valuation being \( \mathcal{F}_{t} \}-measurable where \( t \) is the evaluationTime argument.
*
* @author Christian Fries
*/
public class SwaptionFromSwapSchedules extends AbstractLIBORMonteCarloProduct implements ProcessTimeDiscretizationProvider, net.finmath.modelling.products.Swaption {
public enum SwaptionType{
PAYER,
RECEIVER
}
private final SwaptionType swaptionType;
private final LocalDate exerciseDate;
private final Schedule scheduleFixedLeg;
private final Schedule scheduleFloatLeg;
private final double swaprate;
private final double notional;
private final ValueUnit valueUnit;
private final LocalDateTime referenceDate;
public SwaptionFromSwapSchedules(
LocalDateTime referenceDate,
SwaptionType swaptionType,
LocalDate exerciseDate,
Schedule scheduleFixedLeg,
Schedule scheduleFloatLeg,
double swaprate,
double notional,
ValueUnit valueUnit) {
this.referenceDate = referenceDate;
this.swaptionType = swaptionType;
this.exerciseDate = exerciseDate;
this.scheduleFixedLeg = scheduleFixedLeg;
this.scheduleFloatLeg = scheduleFloatLeg;
this.swaprate = swaprate;
this.notional = notional;
this.valueUnit = valueUnit;
}
@Override
public RandomVariable getValue(double evaluationTime, LIBORModelMonteCarloSimulationModel model)
throws CalculationException {
LocalDate modelReferenceDate = null;
try {
modelReferenceDate = model.getReferenceDate().toLocalDate();
if(modelReferenceDate == null) {
modelReferenceDate = referenceDate.toLocalDate();
}
}
catch(UnsupportedOperationException e) {}
double exerciseTime = FloatingpointDate.getFloatingPointDateFromDate(modelReferenceDate, exerciseDate);
RandomVariable discountedCashflowFixLeg = getValueOfLegAnalytic(exerciseTime, model, scheduleFixedLeg, false, swaprate, notional);
RandomVariable discountedCashflowFloatingLeg = getValueOfLegAnalytic(exerciseTime, model, scheduleFloatLeg, true, 0.0, notional);
// Distinguish whether the swaption is of type "Payer" or "Receiver":
RandomVariable values;
if(swaptionType.equals(SwaptionType.PAYER)){
values = discountedCashflowFloatingLeg.sub(discountedCashflowFixLeg);
}
else if(swaptionType.equals(SwaptionType.RECEIVER)){
values = discountedCashflowFixLeg.sub(discountedCashflowFloatingLeg);
}
else {
throw new IllegalArgumentException("Unkown swaptionType " + swaptionType);
}
// Floor at zero
values = values.floor(0.0);
RandomVariable numeraire = model.getNumeraire(exerciseTime);
RandomVariable monteCarloProbabilities = model.getMonteCarloWeights(exerciseTime);
values = values.div(numeraire).mult(monteCarloProbabilities);
// Note that values is a relative price - no numeraire division is required
RandomVariable numeraireAtZero = model.getNumeraire(evaluationTime);
RandomVariable monteCarloProbabilitiesAtZero = model.getMonteCarloWeights(evaluationTime);
values = values.mult(numeraireAtZero).div(monteCarloProbabilitiesAtZero);
if(valueUnit == ValueUnit.VALUE) {
return values;
}
/*
* Need to convert value to different value unit.
*/
// Use analytic formula to calculate the options black/bachelier implied vol using the MC price from above:
double atmSwaprate = Swap.getForwardSwapRate(scheduleFixedLeg, scheduleFloatLeg, model.getModel().getForwardRateCurve(), model.getModel().getAnalyticModel());
double forward = atmSwaprate;
double optionStrike = swaprate;
double optionMaturity = FloatingpointDate.getFloatingPointDateFromDate(modelReferenceDate, exerciseDate);
double[] swapTenor = new double[scheduleFixedLeg.getNumberOfPeriods() + 1];
for(int i = 0; i < scheduleFixedLeg.getNumberOfPeriods(); i++) {
swapTenor[i] = scheduleFixedLeg.getFixing(i);
}
swapTenor[scheduleFixedLeg.getNumberOfPeriods()] = scheduleFixedLeg.getPayment(scheduleFixedLeg.getNumberOfPeriods() - 1);
double swapAnnuity = SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor), model.getModel().getDiscountCurve());
switch(valueUnit) {
case VALUE:
return values;
case VOLATILITYNORMAL:
double volatitliy = AnalyticFormulas.bachelierOptionImpliedVolatility(forward, optionMaturity, optionStrike, swapAnnuity, values.getAverage());
return model.getRandomVariableForConstant(volatitliy);
case VOLATILITYLOGNORMAL:
return model.getRandomVariableForConstant(AnalyticFormulas.blackScholesOptionImpliedVolatility(forward, optionMaturity, optionStrike, swapAnnuity, values.getAverage()));
case VOLATILITYNORMALATM:
RandomVariable annuity = getValueOfLegAnalytic(evaluationTime, model, scheduleFixedLeg, false, 1.0, notional);
annuity = annuity.div(numeraire).mult(monteCarloProbabilities).mult(numeraireAtZero).div(monteCarloProbabilitiesAtZero);
return values.div(Math.sqrt(optionMaturity / Math.PI / 2.0)).div(annuity.average());
default:
throw new IllegalArgumentException("Unsupported valueUnit " + valueUnit.name());
}
}
@Override
public TimeDiscretization getProcessTimeDiscretization(LocalDateTime referenceDate) {
Set<Double> times = new HashSet<>();
times.add(FloatingpointDate.getFloatingPointDateFromDate(referenceDate, exerciseDate.atStartOfDay()));
Function<Period, Double> periodToTime = period -> { return FloatingpointDate.getFloatingPointDateFromDate(referenceDate, period.getPayment().atStartOfDay()); };
times.addAll(scheduleFixedLeg.getPeriods().stream().map(periodToTime).collect(Collectors.toList()));
times.addAll(scheduleFloatLeg.getPeriods().stream().map(periodToTime).collect(Collectors.toList()));
return new TimeDiscretizationFromArray(times);
}
/**
* @return the exercise date
*/
public LocalDate getExerciseDate() {
return exerciseDate;
}
/**
* Determines the discounted cashflow of a leg (can handle fix or float).
*
* @param model The monte carlo model
* @param schedule The schedule of the fixed leg
* @param notional The notional
* @return discountedCashflowFloatingLeg
* @throws CalculationException
*/
private RandomVariable getValueOfLegAnalytic(double exerciseTime, LIBORModelMonteCarloSimulationModel model, Schedule schedule, boolean paysFloatingRate, double fixRate, double notional) throws CalculationException {
LocalDate modelReferenceDate = null;
try {
modelReferenceDate = model.getReferenceDate().toLocalDate();
if(modelReferenceDate == null) {
modelReferenceDate = referenceDate.toLocalDate();
}
}
catch(UnsupportedOperationException e) {}
RandomVariable discountedCashflowFloatingLeg = model.getRandomVariableForConstant(0.0);
for(int peridIndex = schedule.getNumberOfPeriods() - 1; peridIndex >= 0; peridIndex--) {
Period period = schedule.getPeriod(peridIndex);
double paymentTime = FloatingpointDate.getFloatingPointDateFromDate(modelReferenceDate, period.getPayment());
double fixingTime = FloatingpointDate.getFloatingPointDateFromDate(modelReferenceDate, period.getFixing());
double periodLength = schedule.getPeriodLength(peridIndex);
/*
* Note that it is important that getForwardDiscountBond and getLIBOR are called with evaluationTime = exerciseTime.
*/
RandomVariable discountBond = model.getModel().getForwardDiscountBond(exerciseTime, paymentTime);
if(paysFloatingRate) {
RandomVariable libor = model.getLIBOR(exerciseTime, fixingTime, paymentTime);
RandomVariable periodCashFlow = libor.mult(periodLength).mult(notional);
discountedCashflowFloatingLeg = discountedCashflowFloatingLeg.add(periodCashFlow.mult(discountBond));
}
if(fixRate != 0) {
RandomVariable periodCashFlow = model.getRandomVariableForConstant(swaprate * periodLength * notional);
discountedCashflowFloatingLeg = discountedCashflowFloatingLeg.add(periodCashFlow.mult(discountBond));
}
}
return discountedCashflowFloatingLeg;
}
@Override
public String toString() {
return "SwaptionConditionalAnalytic [swaptionType=" + swaptionType + ", referenceDate=" + referenceDate + ", exerciseDate="
+ exerciseDate + ", swaprate=" + swaprate + ", valueUnit=" + valueUnit
+ ", fixMetaSchedule=" + scheduleFixedLeg + ", floatMetaSchedule="
+ scheduleFloatLeg + ", notional=" + notional + "]";
}
}
|
Method getValueOfLegAnalytic is public.
|
src/main/java/net/finmath/montecarlo/interestrate/products/SwaptionFromSwapSchedules.java
|
Method getValueOfLegAnalytic is public.
|
|
Java
|
apache-2.0
|
cdeddfe8ce7792f87cc7d278444638fb5288084c
| 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.openapi.editor.impl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
import com.intellij.openapi.editor.ex.util.EditorUIUtil;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.ex.util.LexerEditorHighlighter;
import com.intellij.openapi.editor.impl.view.FontLayoutService;
import com.intellij.openapi.editor.impl.view.IterationState;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.registry.RegistryValue;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import com.intellij.util.Consumer;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import sun.awt.image.SunVolatileImage;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.VolatileImage;
import java.util.ArrayList;
import java.util.List;
import static com.intellij.util.ui.UIUtil.useSafely;
/**
* @author Pavel Fatin
*/
class ImmediatePainter {
private static final int DEBUG_PAUSE_DURATION = 1000;
static final RegistryValue ENABLED = Registry.get("editor.zero.latency.rendering");
static final RegistryValue DOUBLE_BUFFERING = Registry.get("editor.zero.latency.rendering.double.buffering");
private static final RegistryValue PIPELINE_FLUSH = Registry.get("editor.zero.latency.rendering.pipeline.flush");
private static final RegistryValue DEBUG = Registry.get("editor.zero.latency.rendering.debug");
private final EditorImpl myEditor;
private Image myImage;
ImmediatePainter(EditorImpl editor) {
myEditor = editor;
Disposer.register(editor.getDisposable(), () -> {
if (myImage != null) {
myImage.flush();
}
});
}
boolean paint(final Graphics g, final EditorActionPlan plan) {
if (ENABLED.asBoolean() && canPaintImmediately(myEditor)) {
if (plan.getCaretShift() != 1) return false;
final List<EditorActionPlan.Replacement> replacements = plan.getReplacements();
if (replacements.size() != 1) return false;
final EditorActionPlan.Replacement replacement = replacements.get(0);
if (replacement.getText().length() != 1) return false;
final int caretOffset = replacement.getBegin();
final char c = replacement.getText().charAt(0);
paintImmediately(g, caretOffset, c);
return true;
}
return false;
}
private static boolean canPaintImmediately(final EditorImpl editor) {
final CaretModel caretModel = editor.getCaretModel();
final Caret caret = caretModel.getPrimaryCaret();
final Document document = editor.getDocument();
return document instanceof DocumentImpl &&
editor.getHighlighter() instanceof LexerEditorHighlighter &&
!(editor.getComponent().getParent() instanceof EditorTextField) &&
editor.myView.getTopOverhang() <= 0 && editor.myView.getBottomOverhang() <= 0 &&
!editor.getSelectionModel().hasSelection() &&
caretModel.getCaretCount() == 1 &&
!isInVirtualSpace(editor, caret) &&
!isInsertion(document, caret.getOffset()) &&
!caret.isAtRtlLocation() &&
!caret.isAtBidiRunBoundary();
}
private static boolean isInVirtualSpace(final Editor editor, final Caret caret) {
return caret.getLogicalPosition().compareTo(editor.offsetToLogicalPosition(caret.getOffset())) != 0;
}
private static boolean isInsertion(final Document document, final int offset) {
return offset < document.getTextLength() && document.getCharsSequence().charAt(offset) != '\n';
}
private void paintImmediately(final Graphics g, final int offset, final char c2) {
final EditorImpl editor = myEditor;
final Document document = editor.getDocument();
final LexerEditorHighlighter highlighter = (LexerEditorHighlighter)myEditor.getHighlighter();
final EditorSettings settings = editor.getSettings();
final boolean isBlockCursor = editor.isInsertMode() == settings.isBlockCursor();
final int lineHeight = editor.getLineHeight();
final int ascent = editor.getAscent();
final int topOverhang = editor.myView.getTopOverhang();
final int bottomOverhang = editor.myView.getBottomOverhang();
final char c1 = offset == 0 ? ' ' : document.getCharsSequence().charAt(offset - 1);
final List<TextAttributes> attributes = highlighter.getAttributesForPreviousAndTypedChars(document, offset, c2);
updateAttributes(editor, offset, attributes);
final TextAttributes attributes1 = attributes.get(0);
final TextAttributes attributes2 = attributes.get(1);
if (!(canRender(attributes1) && canRender(attributes2))) {
return;
}
FontLayoutService fontLayoutService = FontLayoutService.getInstance();
final float width1 = fontLayoutService.charWidth2D(editor.getFontMetrics(attributes1.getFontType()), c1);
final float width2 = fontLayoutService.charWidth2D(editor.getFontMetrics(attributes2.getFontType()), c2);
final Font font1 = EditorUtil.fontForChar(c1, attributes1.getFontType(), editor).getFont();
final Font font2 = EditorUtil.fontForChar(c1, attributes2.getFontType(), editor).getFont();
final Point2D p2 = editor.offsetToPoint2D(offset);
float p2x = (float)p2.getX();
int p2y = (int)p2.getY();
int width1i = (int)(p2x) - (int)(p2x - width1);
int width2i = (int)(p2x + width2) - (int)p2x;
Caret caret = editor.getCaretModel().getPrimaryCaret();
//noinspection ConstantConditions
final int caretWidth = isBlockCursor ? editor.getCaretLocations(false)[0].myWidth
: JBUI.scale(caret.getVisualAttributes().getWidth(settings.getLineCursorWidth()));
final float caretShift = isBlockCursor ? 0 : caretWidth == 1 ? 0 : 1 / JBUI.sysScale((Graphics2D)g);
final Rectangle2D caretRectangle = new Rectangle2D.Float((int)(p2x + width2) - caretShift, p2y - topOverhang,
caretWidth, lineHeight + topOverhang + bottomOverhang);
final Rectangle rectangle1 = new Rectangle((int)(p2x - width1), p2y, width1i, lineHeight);
final Rectangle rectangle2 = new Rectangle((int)p2x, p2y, (int)(width2i + caretWidth - caretShift), lineHeight);
final Consumer<Graphics> painter = graphics -> {
EditorUIUtil.setupAntialiasing(graphics);
((Graphics2D)graphics).setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, editor.myFractionalMetricsHintValue);
fillRect(graphics, rectangle2, attributes2.getBackgroundColor());
drawChar(graphics, c2, p2x, p2y + ascent, font2, attributes2.getForegroundColor());
fillRect(graphics, caretRectangle, getCaretColor(editor));
fillRect(graphics, rectangle1, attributes1.getBackgroundColor());
drawChar(graphics, c1, p2x - width1, p2y + ascent, font1, attributes1.getForegroundColor());
};
final Shape originalClip = g.getClip();
g.setClip(new Rectangle2D.Float((int)p2x - caretShift, p2y, width2i + caretWidth, lineHeight));
if (DOUBLE_BUFFERING.asBoolean()) {
paintWithDoubleBuffering(g, painter);
}
else {
painter.consume(g);
}
g.setClip(originalClip);
if (PIPELINE_FLUSH.asBoolean()) {
Toolkit.getDefaultToolkit().sync();
}
if (DEBUG.asBoolean()) {
pause();
}
}
private static boolean canRender(final TextAttributes attributes) {
return attributes.getEffectType() != EffectType.BOXED || attributes.getEffectColor() == null;
}
private void paintWithDoubleBuffering(final Graphics graphics, final Consumer<? super Graphics> painter) {
final Rectangle bounds = graphics.getClipBounds();
createOrUpdateImageBuffer(myEditor.getComponent(), bounds.getSize());
useSafely(myImage.getGraphics(), imageGraphics -> {
imageGraphics.translate(-bounds.x, -bounds.y);
painter.consume(imageGraphics);
});
graphics.drawImage(myImage, bounds.x, bounds.y, null);
}
private void createOrUpdateImageBuffer(final JComponent component, final Dimension size) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
if (myImage == null || !isLargeEnough(myImage, size)) {
myImage = UIUtil.createImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
}
}
else {
if (myImage == null) {
myImage = component.createVolatileImage(size.width, size.height);
}
else if (!isLargeEnough(myImage, size) || !isImageValid((VolatileImage)myImage, component)) {
myImage.flush();
myImage = component.createVolatileImage(size.width, size.height);
}
}
}
private static boolean isLargeEnough(final Image image, final Dimension size) {
final int width = image.getWidth(null);
final int height = image.getHeight(null);
if (width == -1 || height == -1) {
throw new IllegalArgumentException("Image size is undefined");
}
return width >= size.width && height >= size.height;
}
private static boolean isImageValid(VolatileImage image, Component component) {
GraphicsConfiguration componentConfig = component.getGraphicsConfiguration();
if (SystemInfo.isWindows && image instanceof SunVolatileImage) { // JBR-1540
GraphicsConfiguration imageConfig = ((SunVolatileImage)image).getGraphicsConfig();
if (imageConfig != null && componentConfig != null && imageConfig.getDevice() != componentConfig.getDevice()) return false;
}
return image.validate(componentConfig) != VolatileImage.IMAGE_INCOMPATIBLE;
}
private static void fillRect(final Graphics g, final Rectangle2D r, final Color color) {
g.setColor(color);
((Graphics2D)g).fill(r);
}
private static void drawChar(final Graphics g,
final char c,
final float x, final float y,
final Font font, final Color color) {
g.setFont(font);
g.setColor(color);
((Graphics2D)g).drawString(String.valueOf(c), x, y);
}
private static Color getCaretColor(final Editor editor) {
Color overriddenColor = editor.getCaretModel().getPrimaryCaret().getVisualAttributes().getColor();
if (overriddenColor != null) return overriddenColor;
final Color caretColor = editor.getColorsScheme().getColor(EditorColors.CARET_COLOR);
return caretColor == null ? new JBColor(Gray._0, Gray._255) : caretColor;
}
private static void updateAttributes(final EditorImpl editor, final int offset, final List<? extends TextAttributes> attributes) {
final List<RangeHighlighterEx> list1 = new ArrayList<>();
final List<RangeHighlighterEx> list2 = new ArrayList<>();
final Processor<RangeHighlighterEx> processor = highlighter -> {
if (!highlighter.isValid()) return true;
final boolean isLineHighlighter = highlighter.getTargetArea() == HighlighterTargetArea.LINES_IN_RANGE;
if (isLineHighlighter || highlighter.getStartOffset() < offset) {
list1.add(highlighter);
}
if (isLineHighlighter || highlighter.getEndOffset() > offset ||
(highlighter.getEndOffset() == offset && (highlighter.isGreedyToRight()))) {
list2.add(highlighter);
}
return true;
};
editor.getFilteredDocumentMarkupModel().processRangeHighlightersOverlappingWith(Math.max(0, offset - 1), offset, processor);
editor.getMarkupModel().processRangeHighlightersOverlappingWith(Math.max(0, offset - 1), offset, processor);
updateAttributes(editor, attributes.get(0), list1);
updateAttributes(editor, attributes.get(1), list2);
}
// TODO Unify with com.intellij.openapi.editor.impl.view.IterationState.setAttributes
private static void updateAttributes(final EditorImpl editor,
final TextAttributes attributes,
final List<? extends RangeHighlighterEx> highlighters) {
if (highlighters.size() > 1) {
ContainerUtil.quickSort(highlighters, IterationState.BY_LAYER_THEN_ATTRIBUTES);
}
TextAttributes syntax = attributes;
TextAttributes caretRow = editor.getCaretModel().getTextAttributes();
final int size = highlighters.size();
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < size; i++) {
RangeHighlighterEx highlighter = highlighters.get(i);
if (highlighter.getTextAttributes() == TextAttributes.ERASE_MARKER) {
syntax = null;
}
}
final List<TextAttributes> cachedAttributes = new ArrayList<>();
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < size; i++) {
RangeHighlighterEx highlighter = highlighters.get(i);
if (caretRow != null && highlighter.getLayer() < HighlighterLayer.CARET_ROW) {
cachedAttributes.add(caretRow);
caretRow = null;
}
if (syntax != null && highlighter.getLayer() < HighlighterLayer.SYNTAX) {
cachedAttributes.add(syntax);
syntax = null;
}
TextAttributes textAttributes = highlighter.getTextAttributes();
if (textAttributes != null && textAttributes != TextAttributes.ERASE_MARKER) {
cachedAttributes.add(textAttributes);
}
}
if (caretRow != null) cachedAttributes.add(caretRow);
if (syntax != null) cachedAttributes.add(syntax);
Color foreground = null;
Color background = null;
Color effect = null;
EffectType effectType = null;
int fontType = 0;
//noinspection ForLoopReplaceableByForEach, Duplicates
for (int i = 0; i < cachedAttributes.size(); i++) {
TextAttributes attrs = cachedAttributes.get(i);
if (foreground == null) {
foreground = attrs.getForegroundColor();
}
if (background == null) {
background = attrs.getBackgroundColor();
}
if (fontType == Font.PLAIN) {
fontType = attrs.getFontType();
}
if (effect == null) {
effect = attrs.getEffectColor();
effectType = attrs.getEffectType();
}
}
if (foreground == null) foreground = editor.getForegroundColor();
if (background == null) background = editor.getBackgroundColor();
if (effectType == null) effectType = EffectType.BOXED;
TextAttributes defaultAttributes = editor.getColorsScheme().getAttributes(HighlighterColors.TEXT);
if (fontType == Font.PLAIN) fontType = defaultAttributes == null ? Font.PLAIN : defaultAttributes.getFontType();
attributes.setAttributes(foreground, background, effect, null, effectType, fontType);
}
private static void pause() {
try {
Thread.sleep(DEBUG_PAUSE_DURATION);
}
catch (InterruptedException e) {
// ...
}
}
}
|
platform/platform-impl/src/com/intellij/openapi/editor/impl/ImmediatePainter.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.openapi.editor.impl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
import com.intellij.openapi.editor.ex.util.EditorUIUtil;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.ex.util.LexerEditorHighlighter;
import com.intellij.openapi.editor.impl.view.FontLayoutService;
import com.intellij.openapi.editor.impl.view.IterationState;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.registry.RegistryValue;
import com.intellij.ui.EditorTextField;
import com.intellij.ui.Gray;
import com.intellij.ui.JBColor;
import com.intellij.util.Consumer;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.VolatileImage;
import java.util.ArrayList;
import java.util.List;
import static com.intellij.util.ui.UIUtil.useSafely;
/**
* @author Pavel Fatin
*/
class ImmediatePainter {
private static final int DEBUG_PAUSE_DURATION = 1000;
static final RegistryValue ENABLED = Registry.get("editor.zero.latency.rendering");
static final RegistryValue DOUBLE_BUFFERING = Registry.get("editor.zero.latency.rendering.double.buffering");
private static final RegistryValue PIPELINE_FLUSH = Registry.get("editor.zero.latency.rendering.pipeline.flush");
private static final RegistryValue DEBUG = Registry.get("editor.zero.latency.rendering.debug");
private final EditorImpl myEditor;
private Image myImage;
ImmediatePainter(EditorImpl editor) {
myEditor = editor;
Disposer.register(editor.getDisposable(), () -> {
if (myImage != null) {
myImage.flush();
}
});
}
boolean paint(final Graphics g, final EditorActionPlan plan) {
if (ENABLED.asBoolean() && canPaintImmediately(myEditor)) {
if (plan.getCaretShift() != 1) return false;
final List<EditorActionPlan.Replacement> replacements = plan.getReplacements();
if (replacements.size() != 1) return false;
final EditorActionPlan.Replacement replacement = replacements.get(0);
if (replacement.getText().length() != 1) return false;
final int caretOffset = replacement.getBegin();
final char c = replacement.getText().charAt(0);
paintImmediately(g, caretOffset, c);
return true;
}
return false;
}
private static boolean canPaintImmediately(final EditorImpl editor) {
final CaretModel caretModel = editor.getCaretModel();
final Caret caret = caretModel.getPrimaryCaret();
final Document document = editor.getDocument();
return document instanceof DocumentImpl &&
editor.getHighlighter() instanceof LexerEditorHighlighter &&
!(editor.getComponent().getParent() instanceof EditorTextField) &&
editor.myView.getTopOverhang() <= 0 && editor.myView.getBottomOverhang() <= 0 &&
!editor.getSelectionModel().hasSelection() &&
caretModel.getCaretCount() == 1 &&
!isInVirtualSpace(editor, caret) &&
!isInsertion(document, caret.getOffset()) &&
!caret.isAtRtlLocation() &&
!caret.isAtBidiRunBoundary();
}
private static boolean isInVirtualSpace(final Editor editor, final Caret caret) {
return caret.getLogicalPosition().compareTo(editor.offsetToLogicalPosition(caret.getOffset())) != 0;
}
private static boolean isInsertion(final Document document, final int offset) {
return offset < document.getTextLength() && document.getCharsSequence().charAt(offset) != '\n';
}
private void paintImmediately(final Graphics g, final int offset, final char c2) {
final EditorImpl editor = myEditor;
final Document document = editor.getDocument();
final LexerEditorHighlighter highlighter = (LexerEditorHighlighter)myEditor.getHighlighter();
final EditorSettings settings = editor.getSettings();
final boolean isBlockCursor = editor.isInsertMode() == settings.isBlockCursor();
final int lineHeight = editor.getLineHeight();
final int ascent = editor.getAscent();
final int topOverhang = editor.myView.getTopOverhang();
final int bottomOverhang = editor.myView.getBottomOverhang();
final char c1 = offset == 0 ? ' ' : document.getCharsSequence().charAt(offset - 1);
final List<TextAttributes> attributes = highlighter.getAttributesForPreviousAndTypedChars(document, offset, c2);
updateAttributes(editor, offset, attributes);
final TextAttributes attributes1 = attributes.get(0);
final TextAttributes attributes2 = attributes.get(1);
if (!(canRender(attributes1) && canRender(attributes2))) {
return;
}
FontLayoutService fontLayoutService = FontLayoutService.getInstance();
final float width1 = fontLayoutService.charWidth2D(editor.getFontMetrics(attributes1.getFontType()), c1);
final float width2 = fontLayoutService.charWidth2D(editor.getFontMetrics(attributes2.getFontType()), c2);
final Font font1 = EditorUtil.fontForChar(c1, attributes1.getFontType(), editor).getFont();
final Font font2 = EditorUtil.fontForChar(c1, attributes2.getFontType(), editor).getFont();
final Point2D p2 = editor.offsetToPoint2D(offset);
float p2x = (float)p2.getX();
int p2y = (int)p2.getY();
int width1i = (int)(p2x) - (int)(p2x - width1);
int width2i = (int)(p2x + width2) - (int)p2x;
Caret caret = editor.getCaretModel().getPrimaryCaret();
//noinspection ConstantConditions
final int caretWidth = isBlockCursor ? editor.getCaretLocations(false)[0].myWidth
: JBUI.scale(caret.getVisualAttributes().getWidth(settings.getLineCursorWidth()));
final float caretShift = isBlockCursor ? 0 : caretWidth == 1 ? 0 : 1 / JBUI.sysScale((Graphics2D)g);
final Rectangle2D caretRectangle = new Rectangle2D.Float((int)(p2x + width2) - caretShift, p2y - topOverhang,
caretWidth, lineHeight + topOverhang + bottomOverhang);
final Rectangle rectangle1 = new Rectangle((int)(p2x - width1), p2y, width1i, lineHeight);
final Rectangle rectangle2 = new Rectangle((int)p2x, p2y, (int)(width2i + caretWidth - caretShift), lineHeight);
final Consumer<Graphics> painter = graphics -> {
EditorUIUtil.setupAntialiasing(graphics);
((Graphics2D)graphics).setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, editor.myFractionalMetricsHintValue);
fillRect(graphics, rectangle2, attributes2.getBackgroundColor());
drawChar(graphics, c2, p2x, p2y + ascent, font2, attributes2.getForegroundColor());
fillRect(graphics, caretRectangle, getCaretColor(editor));
fillRect(graphics, rectangle1, attributes1.getBackgroundColor());
drawChar(graphics, c1, p2x - width1, p2y + ascent, font1, attributes1.getForegroundColor());
};
final Shape originalClip = g.getClip();
g.setClip(new Rectangle2D.Float((int)p2x - caretShift, p2y, width2i + caretWidth, lineHeight));
if (DOUBLE_BUFFERING.asBoolean()) {
paintWithDoubleBuffering(g, painter);
}
else {
painter.consume(g);
}
g.setClip(originalClip);
if (PIPELINE_FLUSH.asBoolean()) {
Toolkit.getDefaultToolkit().sync();
}
if (DEBUG.asBoolean()) {
pause();
}
}
private static boolean canRender(final TextAttributes attributes) {
return attributes.getEffectType() != EffectType.BOXED || attributes.getEffectColor() == null;
}
private void paintWithDoubleBuffering(final Graphics graphics, final Consumer<? super Graphics> painter) {
final Rectangle bounds = graphics.getClipBounds();
createOrUpdateImageBuffer(myEditor.getComponent(), bounds.getSize());
useSafely(myImage.getGraphics(), imageGraphics -> {
imageGraphics.translate(-bounds.x, -bounds.y);
painter.consume(imageGraphics);
});
graphics.drawImage(myImage, bounds.x, bounds.y, null);
}
private void createOrUpdateImageBuffer(final JComponent component, final Dimension size) {
if (ApplicationManager.getApplication().isUnitTestMode()) {
if (myImage == null || !isLargeEnough(myImage, size)) {
myImage = UIUtil.createImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
}
}
else {
if (myImage == null) {
myImage = component.createVolatileImage(size.width, size.height);
}
else if (!isLargeEnough(myImage, size) ||
((VolatileImage)myImage).validate(component.getGraphicsConfiguration()) == VolatileImage.IMAGE_INCOMPATIBLE) {
myImage.flush();
myImage = component.createVolatileImage(size.width, size.height);
}
}
}
private static boolean isLargeEnough(final Image image, final Dimension size) {
final int width = image.getWidth(null);
final int height = image.getHeight(null);
if (width == -1 || height == -1) {
throw new IllegalArgumentException("Image size is undefined");
}
return width >= size.width && height >= size.height;
}
private static void fillRect(final Graphics g, final Rectangle2D r, final Color color) {
g.setColor(color);
((Graphics2D)g).fill(r);
}
private static void drawChar(final Graphics g,
final char c,
final float x, final float y,
final Font font, final Color color) {
g.setFont(font);
g.setColor(color);
((Graphics2D)g).drawString(String.valueOf(c), x, y);
}
private static Color getCaretColor(final Editor editor) {
Color overriddenColor = editor.getCaretModel().getPrimaryCaret().getVisualAttributes().getColor();
if (overriddenColor != null) return overriddenColor;
final Color caretColor = editor.getColorsScheme().getColor(EditorColors.CARET_COLOR);
return caretColor == null ? new JBColor(Gray._0, Gray._255) : caretColor;
}
private static void updateAttributes(final EditorImpl editor, final int offset, final List<? extends TextAttributes> attributes) {
final List<RangeHighlighterEx> list1 = new ArrayList<>();
final List<RangeHighlighterEx> list2 = new ArrayList<>();
final Processor<RangeHighlighterEx> processor = highlighter -> {
if (!highlighter.isValid()) return true;
final boolean isLineHighlighter = highlighter.getTargetArea() == HighlighterTargetArea.LINES_IN_RANGE;
if (isLineHighlighter || highlighter.getStartOffset() < offset) {
list1.add(highlighter);
}
if (isLineHighlighter || highlighter.getEndOffset() > offset ||
(highlighter.getEndOffset() == offset && (highlighter.isGreedyToRight()))) {
list2.add(highlighter);
}
return true;
};
editor.getFilteredDocumentMarkupModel().processRangeHighlightersOverlappingWith(Math.max(0, offset - 1), offset, processor);
editor.getMarkupModel().processRangeHighlightersOverlappingWith(Math.max(0, offset - 1), offset, processor);
updateAttributes(editor, attributes.get(0), list1);
updateAttributes(editor, attributes.get(1), list2);
}
// TODO Unify with com.intellij.openapi.editor.impl.view.IterationState.setAttributes
private static void updateAttributes(final EditorImpl editor,
final TextAttributes attributes,
final List<? extends RangeHighlighterEx> highlighters) {
if (highlighters.size() > 1) {
ContainerUtil.quickSort(highlighters, IterationState.BY_LAYER_THEN_ATTRIBUTES);
}
TextAttributes syntax = attributes;
TextAttributes caretRow = editor.getCaretModel().getTextAttributes();
final int size = highlighters.size();
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < size; i++) {
RangeHighlighterEx highlighter = highlighters.get(i);
if (highlighter.getTextAttributes() == TextAttributes.ERASE_MARKER) {
syntax = null;
}
}
final List<TextAttributes> cachedAttributes = new ArrayList<>();
//noinspection ForLoopReplaceableByForEach
for (int i = 0; i < size; i++) {
RangeHighlighterEx highlighter = highlighters.get(i);
if (caretRow != null && highlighter.getLayer() < HighlighterLayer.CARET_ROW) {
cachedAttributes.add(caretRow);
caretRow = null;
}
if (syntax != null && highlighter.getLayer() < HighlighterLayer.SYNTAX) {
cachedAttributes.add(syntax);
syntax = null;
}
TextAttributes textAttributes = highlighter.getTextAttributes();
if (textAttributes != null && textAttributes != TextAttributes.ERASE_MARKER) {
cachedAttributes.add(textAttributes);
}
}
if (caretRow != null) cachedAttributes.add(caretRow);
if (syntax != null) cachedAttributes.add(syntax);
Color foreground = null;
Color background = null;
Color effect = null;
EffectType effectType = null;
int fontType = 0;
//noinspection ForLoopReplaceableByForEach, Duplicates
for (int i = 0; i < cachedAttributes.size(); i++) {
TextAttributes attrs = cachedAttributes.get(i);
if (foreground == null) {
foreground = attrs.getForegroundColor();
}
if (background == null) {
background = attrs.getBackgroundColor();
}
if (fontType == Font.PLAIN) {
fontType = attrs.getFontType();
}
if (effect == null) {
effect = attrs.getEffectColor();
effectType = attrs.getEffectType();
}
}
if (foreground == null) foreground = editor.getForegroundColor();
if (background == null) background = editor.getBackgroundColor();
if (effectType == null) effectType = EffectType.BOXED;
TextAttributes defaultAttributes = editor.getColorsScheme().getAttributes(HighlighterColors.TEXT);
if (fontType == Font.PLAIN) fontType = defaultAttributes == null ? Font.PLAIN : defaultAttributes.getFontType();
attributes.setAttributes(foreground, background, effect, null, effectType, fontType);
}
private static void pause() {
try {
Thread.sleep(DEBUG_PAUSE_DURATION);
}
catch (InterruptedException e) {
// ...
}
}
}
|
IDEA-215015 Text "jitter" during typing in editor on Windows after dragging editor onto a different monitor
GitOrigin-RevId: 5f4bc02fbc2426a72e22c82c9439a8c5c632fe68
|
platform/platform-impl/src/com/intellij/openapi/editor/impl/ImmediatePainter.java
|
IDEA-215015 Text "jitter" during typing in editor on Windows after dragging editor onto a different monitor
|
|
Java
|
apache-2.0
|
1c151f657ca316568e8e82c6c9efdee18152c6a1
| 0
|
DongwonChoi/ISAAC,Apelon-VA/va-isaac-gui,vaskaloidis/va-isaac-gui,vaskaloidis/va-isaac-gui,DongwonChoi/ISAAC,Apelon-VA/ISAAC,Apelon-VA/ISAAC,Apelon-VA/ISAAC,DongwonChoi/ISAAC,Apelon-VA/va-isaac-gui
|
/**
* Copyright Notice
*
* This is a work of the U.S. Government and is not subject to copyright
* protection in the United States. Foreign copyrights may apply.
*
* 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 gov.va.isaac.gui.refexViews.refexEdit;
import gov.va.isaac.AppContext;
import gov.va.isaac.ExtendedAppContext;
import gov.va.isaac.gui.ConceptNode;
import gov.va.isaac.gui.SimpleDisplayConcept;
import gov.va.isaac.gui.dragAndDrop.DragRegistry;
import gov.va.isaac.gui.refexViews.util.RefexDataTypeFXNodeBuilder;
import gov.va.isaac.gui.refexViews.util.RefexDataTypeNodeDetails;
import gov.va.isaac.gui.util.CopyableLabel;
import gov.va.isaac.gui.util.ErrorMarkerUtils;
import gov.va.isaac.gui.util.FxUtils;
import gov.va.isaac.gui.util.Images;
import gov.va.isaac.interfaces.gui.views.PopupViewI;
import gov.va.isaac.util.CommonlyUsedConcepts;
import gov.va.isaac.util.UpdateableBooleanBinding;
import gov.va.isaac.util.WBUtility;
import java.util.ArrayList;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Tooltip;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import javafx.util.StringConverter;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.hk2.api.PerLookup;
import org.glassfish.hk2.runlevel.RunLevelException;
import org.ihtsdo.otf.query.lucene.LuceneDynamicRefexIndexer;
import org.ihtsdo.otf.tcc.api.blueprint.IdDirective;
import org.ihtsdo.otf.tcc.api.blueprint.RefexDirective;
import org.ihtsdo.otf.tcc.api.blueprint.RefexDynamicCAB;
import org.ihtsdo.otf.tcc.api.blueprint.TerminologyBuilderBI;
import org.ihtsdo.otf.tcc.api.concept.ConceptVersionBI;
import org.ihtsdo.otf.tcc.api.coordinate.Status;
import org.ihtsdo.otf.tcc.api.metadata.binding.RefexDynamic;
import org.ihtsdo.otf.tcc.api.refexDynamic.RefexDynamicChronicleBI;
import org.ihtsdo.otf.tcc.api.refexDynamic.data.RefexDynamicColumnInfo;
import org.ihtsdo.otf.tcc.api.refexDynamic.data.RefexDynamicDataBI;
import org.ihtsdo.otf.tcc.api.refexDynamic.data.RefexDynamicDataType;
import org.ihtsdo.otf.tcc.api.refexDynamic.data.RefexDynamicUsageDescription;
import org.ihtsdo.otf.tcc.model.cc.refexDynamic.data.RefexDynamicData;
import org.ihtsdo.otf.tcc.model.cc.refexDynamic.data.RefexDynamicUsageDescriptionBuilder;
import org.ihtsdo.otf.tcc.model.index.service.IndexedGenerationCallable;
import org.jvnet.hk2.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.javafx.collections.ObservableListWrapper;
/**
*
* Refset View
*
* @author <a href="mailto:daniel.armbrust.list@gmail.com">Dan Armbrust</a>
*/
@Service
@PerLookup
public class AddRefexPopup extends Stage implements PopupViewI
{
private DynamicRefexView callingView_;
private InputType createRefexFocus_;
private RefexDynamicGUI editRefex_;
private Label unselectableComponentLabel_;;
private ScrollPane sp_;
private ConceptNode selectableConcept_;
private RefexDynamicUsageDescription assemblageInfo_;
private SimpleBooleanProperty assemblageIsValid_ = new SimpleBooleanProperty(false);
private Logger logger_ = LoggerFactory.getLogger(this.getClass());
private UpdateableBooleanBinding allValid_;
private ArrayList<ReadOnlyStringProperty> currentDataFieldWarnings_ = new ArrayList<>();
private ArrayList<RefexDataTypeNodeDetails> currentDataFields_ = new ArrayList<>();
private ObservableList<SimpleDisplayConcept> refexDropDownOptions = FXCollections.observableArrayList();
private GridPane gp_;
private Label title_;
//TODO use the word Sememe
private AddRefexPopup()
{
super();
BorderPane root = new BorderPane();
VBox topItems = new VBox();
topItems.setFillWidth(true);
title_ = new Label("Create new refex instance");
title_.getStyleClass().add("titleLabel");
title_.setAlignment(Pos.CENTER);
title_.prefWidthProperty().bind(topItems.widthProperty());
topItems.getChildren().add(title_);
VBox.setMargin(title_, new Insets(10, 10, 10, 10));
gp_ = new GridPane();
gp_.setHgap(10.0);
gp_.setVgap(10.0);
VBox.setMargin(gp_, new Insets(5, 5, 5, 5));
topItems.getChildren().add(gp_);
Label referencedComponent = new Label("Referenced Component");
referencedComponent.getStyleClass().add("boldLabel");
gp_.add(referencedComponent, 0, 0);
unselectableComponentLabel_ = new CopyableLabel();
unselectableComponentLabel_.setWrapText(true);
AppContext.getService(DragRegistry.class).setupDragOnly(unselectableComponentLabel_, () ->
{
if (editRefex_ == null)
{
if (createRefexFocus_.getComponentNid() != null)
{
return createRefexFocus_.getComponentNid() + "";
}
else
{
return createRefexFocus_.getAssemblyNid() + "";
}
}
else
{
return editRefex_.getRefex().getAssemblageNid() + "";
}
});
//delay adding till we know which row
Label assemblageConceptLabel = new Label("Assemblage Concept");
assemblageConceptLabel.getStyleClass().add("boldLabel");
gp_.add(assemblageConceptLabel, 0, 1);
selectableConcept_ = new ConceptNode(null, true, refexDropDownOptions, null);
selectableConcept_.getConceptProperty().addListener(new ChangeListener<ConceptVersionBI>()
{
@Override
public void changed(ObservableValue<? extends ConceptVersionBI> observable, ConceptVersionBI oldValue, ConceptVersionBI newValue)
{
if (createRefexFocus_ != null && createRefexFocus_.getComponentNid() != null)
{
if (selectableConcept_.isValid().get())
{
//Its a valid concept, but is it a valid assemblage concept?
try
{
assemblageInfo_ = RefexDynamicUsageDescriptionBuilder.readRefexDynamicUsageDescriptionConcept(selectableConcept_.getConceptNoWait().getNid());
assemblageIsValid_.set(true);
}
catch (Exception e)
{
selectableConcept_.isValid().setInvalid("The selected concept is not properly constructed for use as an Assemblage concept");
logger_.info("Concept not a valid concept for a refex assemblage", e);
assemblageIsValid_.set(false);
}
}
else
{
assemblageInfo_ = null;
assemblageIsValid_.set(false);
}
buildDataFields(assemblageIsValid_.get(), null);
}
}
});
//delay adding concept till we know where
ColumnConstraints cc = new ColumnConstraints();
cc.setHgrow(Priority.NEVER);
cc.setMinWidth(FxUtils.calculateNecessaryWidthOfBoldLabel(referencedComponent));
gp_.getColumnConstraints().add(cc);
cc = new ColumnConstraints();
cc.setHgrow(Priority.ALWAYS);
gp_.getColumnConstraints().add(cc);
Label l = new Label("Data Fields");
l.getStyleClass().add("boldLabel");
VBox.setMargin(l, new Insets(5, 5, 5, 5));
topItems.getChildren().add(l);
root.setTop(topItems);
sp_ = new ScrollPane();
sp_.visibleProperty().bind(assemblageIsValid_);
sp_.setFitToHeight(true);
sp_.setFitToWidth(true);
root.setCenter(sp_);
allValid_ = new UpdateableBooleanBinding()
{
{
addBinding(assemblageIsValid_, selectableConcept_.isValid());
}
@Override
protected boolean computeValue()
{
if (assemblageIsValid_.get() && selectableConcept_.isValid().get())
{
boolean allDataValid = true;
for (ReadOnlyStringProperty ssp : currentDataFieldWarnings_)
{
if (ssp.get().length() > 0)
{
allDataValid = false;
break;
}
}
if (allDataValid)
{
clearInvalidReason();
return true;
}
}
setInvalidReason("All errors must be corrected before save is allowed");
return false;
}
};
GridPane bottomRow = new GridPane();
//spacer col
bottomRow.add(new Region(), 0, 0);
Button cancelButton = new Button("Cancel");
cancelButton.setOnAction((action) -> {
close();
});
GridPane.setMargin(cancelButton, new Insets(5, 20, 5, 0));
GridPane.setHalignment(cancelButton, HPos.RIGHT);
bottomRow.add(cancelButton, 1, 0);
Button saveButton = new Button("Save");
saveButton.disableProperty().bind(allValid_.not());
saveButton.setOnAction((action) -> {
doSave();
});
Node wrappedSave = ErrorMarkerUtils.setupDisabledInfoMarker(saveButton, allValid_.getReasonWhyInvalid());
GridPane.setMargin(wrappedSave, new Insets(5, 0, 5, 20));
bottomRow.add(wrappedSave, 2, 0);
//spacer col
bottomRow.add(new Region(), 3, 0);
cc = new ColumnConstraints();
cc.setHgrow(Priority.SOMETIMES);
cc.setFillWidth(true);
bottomRow.getColumnConstraints().add(cc);
cc = new ColumnConstraints();
cc.setHgrow(Priority.NEVER);
bottomRow.getColumnConstraints().add(cc);
cc = new ColumnConstraints();
cc.setHgrow(Priority.NEVER);
bottomRow.getColumnConstraints().add(cc);
cc = new ColumnConstraints();
cc.setHgrow(Priority.SOMETIMES);
cc.setFillWidth(true);
bottomRow.getColumnConstraints().add(cc);
root.setBottom(bottomRow);
Scene scene = new Scene(root);
scene.getStylesheets().add(AddRefexPopup.class.getResource("/isaac-shared-styles.css").toString());
setScene(scene);
}
public void finishInit(RefexDynamicGUI refexToEdit, DynamicRefexView viewToRefresh)
{
callingView_ = viewToRefresh;
createRefexFocus_ = null;
editRefex_ = refexToEdit;
title_.setText("Edit existing refex instance");
gp_.add(unselectableComponentLabel_, 1, 1);
unselectableComponentLabel_.setText(WBUtility.getDescription(editRefex_.getRefex().getAssemblageNid()));
//don't actually put this in the view
selectableConcept_.set(WBUtility.getConceptVersion(editRefex_.getRefex().getReferencedComponentNid()));
Label refComp = new CopyableLabel(WBUtility.getDescription(editRefex_.getRefex().getReferencedComponentNid()));
refComp.setWrapText(true);
AppContext.getService(DragRegistry.class).setupDragOnly(refComp, () -> {return editRefex_.getRefex().getReferencedComponentNid() + "";});
gp_.add(refComp, 1, 0);
refexDropDownOptions.clear();
try
{
assemblageInfo_ = RefexDynamicUsageDescriptionBuilder.readRefexDynamicUsageDescriptionConcept(editRefex_.getRefex().getAssemblageNid());
assemblageIsValid_.set(true);
buildDataFields(true, editRefex_.getRefex().getData());
}
catch (Exception e)
{
logger_.error("Unexpected", e);
AppContext.getCommonDialogs().showErrorDialog("Unexpected Error reading Assembly concept", e);
}
}
public void finishInit(InputType setFromType, DynamicRefexView viewToRefresh)
{
callingView_ = viewToRefresh;
createRefexFocus_ = setFromType;
editRefex_ = null;
title_.setText("Create new refex instance");
if (createRefexFocus_.getComponentNid() != null)
{
gp_.add(unselectableComponentLabel_, 1, 0);
unselectableComponentLabel_.setText(WBUtility.getDescription(createRefexFocus_.getComponentNid()));
gp_.add(selectableConcept_.getNode(), 1, 1);
refexDropDownOptions.clear();
refexDropDownOptions.addAll(buildAssemblageConceptList());
}
else
{
gp_.add(unselectableComponentLabel_, 1, 1);
unselectableComponentLabel_.setText(WBUtility.getDescription(createRefexFocus_.getAssemblyNid()));
gp_.add(selectableConcept_.getNode(), 1, 0);
refexDropDownOptions.clear();
refexDropDownOptions.addAll(AppContext.getService(CommonlyUsedConcepts.class).getObservableConcepts());
try
{
assemblageInfo_ = RefexDynamicUsageDescriptionBuilder.readRefexDynamicUsageDescriptionConcept(createRefexFocus_.getAssemblyNid());
assemblageIsValid_.set(true);
buildDataFields(true, null);
}
catch (Exception e)
{
logger_.error("Unexpected", e);
AppContext.getCommonDialogs().showErrorDialog("Unexpected Error reading Assembly concept", e);
}
}
}
private void buildDataFields(boolean assemblageValid, RefexDynamicDataBI[] currentValues)
{
if (assemblageValid)
{
for (ReadOnlyStringProperty ssp : currentDataFieldWarnings_)
{
allValid_.removeBinding(ssp);
}
currentDataFieldWarnings_.clear();
for (RefexDataTypeNodeDetails nd : currentDataFields_)
{
nd.cleanupListener();
}
currentDataFields_.clear();
GridPane gp = new GridPane();
gp.setHgap(10.0);
gp.setVgap(10.0);
gp.setStyle("-fx-padding: 5;");
int row = 0;
boolean extraInfoColumnIsRequired = false;
for (RefexDynamicColumnInfo ci : assemblageInfo_.getColumnInfo())
{
SimpleStringProperty valueIsRequired = (ci.isColumnRequired() ? new SimpleStringProperty("") : null);
SimpleStringProperty defaultValueTooltip = ((ci.getDefaultColumnValue() == null && ci.getValidator() == null) ? null : new SimpleStringProperty());
ComboBox<RefexDynamicDataType> polymorphicType = null;
Label l = new Label(ci.getColumnName());
l.getStyleClass().add("boldLabel");
l.setMinWidth(FxUtils.calculateNecessaryWidthOfBoldLabel(l));
Tooltip.install(l, new Tooltip(ci.getColumnDescription()));
int col = 0;
gp.add(l, col++, row);
if (ci.getColumnDataType() == RefexDynamicDataType.POLYMORPHIC)
{
polymorphicType = new ComboBox<>();
polymorphicType.setEditable(false);
polymorphicType.setConverter(new StringConverter<RefexDynamicDataType>()
{
@Override
public String toString(RefexDynamicDataType object)
{
return object.getDisplayName();
}
@Override
public RefexDynamicDataType fromString(String string)
{
throw new RuntimeException("unecessary");
}
});
for (RefexDynamicDataType type : RefexDynamicDataType.values())
{
if (type == RefexDynamicDataType.POLYMORPHIC || type == RefexDynamicDataType.UNKNOWN)
{
continue;
}
else
{
polymorphicType.getItems().add(type);
}
}
polymorphicType.getSelectionModel().select((currentValues == null ? RefexDynamicDataType.STRING : currentValues[row].getRefexDataType()));
}
RefexDataTypeNodeDetails nd = RefexDataTypeFXNodeBuilder.buildNodeForType(ci.getColumnDataType(), ci.getDefaultColumnValue(),
(currentValues == null ? null : currentValues[row]),valueIsRequired, defaultValueTooltip,
(polymorphicType == null ? null : polymorphicType.getSelectionModel().selectedItemProperty()), allValid_,
new SimpleObjectProperty<>(ci.getValidator()), new SimpleObjectProperty<>(ci.getValidatorData()));
currentDataFieldWarnings_.addAll(nd.getBoundToAllValid());
if (ci.getColumnDataType() == RefexDynamicDataType.POLYMORPHIC)
{
nd.addUpdateParentListListener(currentDataFieldWarnings_);
}
currentDataFields_.add(nd);
gp.add(nd.getNodeForDisplay(), col++, row);
if (ci.isColumnRequired() || ci.getDefaultColumnValue() != null || ci.getValidator() != null)
{
extraInfoColumnIsRequired = true;
StackPane stackPane = new StackPane();
stackPane.setMaxWidth(Double.MAX_VALUE);
if (ci.getDefaultColumnValue() != null || ci.getValidator() != null)
{
ImageView information = Images.INFORMATION.createImageView();
Tooltip tooltip = new Tooltip();
tooltip.textProperty().bind(defaultValueTooltip);
Tooltip.install(information, tooltip);
tooltip.setAutoHide(true);
information.setOnMouseClicked(event -> tooltip.show(information, event.getScreenX(), event.getScreenY()));
stackPane.getChildren().add(information);
}
if (ci.isColumnRequired())
{
ImageView exclamation = Images.EXCLAMATION.createImageView();
final BooleanProperty showExclamation = new SimpleBooleanProperty(StringUtils.isNotBlank(valueIsRequired.get()));
valueIsRequired.addListener((ChangeListener<String>) (observable, oldValue, newValue) -> showExclamation.set(StringUtils.isNotBlank(newValue)));
exclamation.visibleProperty().bind(showExclamation);
Tooltip tooltip = new Tooltip();
tooltip.textProperty().bind(valueIsRequired);
Tooltip.install(exclamation, tooltip);
tooltip.setAutoHide(true);
exclamation.setOnMouseClicked(event -> tooltip.show(exclamation, event.getScreenX(), event.getScreenY()));
stackPane.getChildren().add(exclamation);
}
gp.add(stackPane, col++, row);
}
Label colType = new Label(ci.getColumnDataType().getDisplayName());
colType.setMinWidth(FxUtils.calculateNecessaryWidthOfLabel(colType));
gp.add((polymorphicType == null ? colType : polymorphicType), col++, row++);
}
ColumnConstraints cc = new ColumnConstraints();
cc.setHgrow(Priority.NEVER);
gp.getColumnConstraints().add(cc);
cc = new ColumnConstraints();
cc.setHgrow(Priority.ALWAYS);
gp.getColumnConstraints().add(cc);
if (extraInfoColumnIsRequired)
{
cc = new ColumnConstraints();
cc.setHgrow(Priority.NEVER);
gp.getColumnConstraints().add(cc);
}
cc = new ColumnConstraints();
cc.setHgrow(Priority.NEVER);
gp.getColumnConstraints().add(cc);
if (row == 0)
{
sp_.setContent(new Label("This assemblage does not allow data fields"));
}
else
{
sp_.setContent(gp);
}
allValid_.invalidate();
}
else
{
sp_.setContent(null);
}
}
private void doSave()
{
try
{
RefexDynamicDataBI[] data = new RefexDynamicData[assemblageInfo_.getColumnInfo().length];
int i = 0;
for (RefexDynamicColumnInfo ci : assemblageInfo_.getColumnInfo())
{
data[i] = RefexDataTypeFXNodeBuilder.getDataForType(currentDataFields_.get(i++).getDataField(), ci);
}
int componentNid;
int assemblageNid;
RefexDynamicCAB cab;
if (createRefexFocus_ != null)
{
if (createRefexFocus_.getComponentNid() == null)
{
componentNid = selectableConcept_.getConcept().getNid();
assemblageNid = createRefexFocus_.getAssemblyNid();
}
else
{
componentNid = createRefexFocus_.getComponentNid();
assemblageNid = selectableConcept_.getConcept().getNid();
}
cab = new RefexDynamicCAB(componentNid, assemblageNid);
}
else
{
componentNid = editRefex_.getRefex().getReferencedComponentNid();
assemblageNid = editRefex_.getRefex().getAssemblageNid();
cab = editRefex_.getRefex().makeBlueprint(WBUtility.getViewCoordinate(),IdDirective.PRESERVE, RefexDirective.INCLUDE);
//If they are editing, we assume that they want it back active, if it is retired.
cab.setStatus(Status.ACTIVE);
}
cab.setData(data, WBUtility.getViewCoordinate());
TerminologyBuilderBI builder = ExtendedAppContext.getDataStore().getTerminologyBuilder(WBUtility.getEC(), WBUtility.getViewCoordinate());
RefexDynamicChronicleBI<?> rdc = builder.construct(cab);
boolean isAnnotationStyle = WBUtility.getConceptVersion(assemblageNid).isAnnotationStyleRefex();
IndexedGenerationCallable indexGen = null;
//In order to make sure we can wait for the index to have this entry, we need a latch...
if (isAnnotationStyle)
{
indexGen = AppContext.getService(LuceneDynamicRefexIndexer.class).getIndexedGenerationCallable(rdc.getNid());
}
ExtendedAppContext.getDataStore().addUncommitted(ExtendedAppContext.getDataStore().getConceptForNid(componentNid));
if (!isAnnotationStyle)
{
ExtendedAppContext.getDataStore().addUncommitted(WBUtility.getConceptVersion(assemblageNid));
}
if (callingView_ != null)
{
ExtendedAppContext.getDataStore().waitTillWritesFinished();
callingView_.setNewComponentHint(componentNid, indexGen);
callingView_.refresh();
}
close();
}
catch (Exception e)
{
logger_.error("Error saving refex", e);
AppContext.getCommonDialogs().showErrorDialog("Unexpected error", "There was an error saving the refex", e.getMessage(), this);
}
}
/**
* Call setReferencedComponent first
*
* @see gov.va.isaac.interfaces.gui.views.PopupViewI#showView(javafx.stage.Window)
*/
@Override
public void showView(Window parent)
{
if (createRefexFocus_ == null && editRefex_ == null)
{
throw new RunLevelException("referenced component nid must be set first");
}
setTitle("Create new Refex");
setResizable(true);
initOwner(parent);
initModality(Modality.NONE);
initStyle(StageStyle.DECORATED);
setWidth(600);
setHeight(400);
show();
}
private ObservableList<SimpleDisplayConcept> buildAssemblageConceptList()
{
ObservableList<SimpleDisplayConcept> assemblageConcepts = new ObservableListWrapper<>(new ArrayList<SimpleDisplayConcept>());
try
{
ConceptVersionBI colCon = WBUtility.getConceptVersion(RefexDynamic.REFEX_DYNAMIC_IDENTITY.getNid());
ArrayList<ConceptVersionBI> colCons = WBUtility.getAllChildrenOfConcept(colCon, false);
for (ConceptVersionBI col : colCons) {
assemblageConcepts.add(new SimpleDisplayConcept(col));
}
}
catch (Exception e)
{
logger_.error("Unexpected error reading existing assemblage concepts", e);
}
return assemblageConcepts;
}
}
|
refex-view/src/main/java/gov/va/isaac/gui/refexViews/refexEdit/AddRefexPopup.java
|
/**
* Copyright Notice
*
* This is a work of the U.S. Government and is not subject to copyright
* protection in the United States. Foreign copyrights may apply.
*
* 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 gov.va.isaac.gui.refexViews.refexEdit;
import gov.va.isaac.AppContext;
import gov.va.isaac.ExtendedAppContext;
import gov.va.isaac.gui.ConceptNode;
import gov.va.isaac.gui.SimpleDisplayConcept;
import gov.va.isaac.gui.refexViews.util.RefexDataTypeFXNodeBuilder;
import gov.va.isaac.gui.refexViews.util.RefexDataTypeNodeDetails;
import gov.va.isaac.gui.util.ErrorMarkerUtils;
import gov.va.isaac.gui.util.FxUtils;
import gov.va.isaac.gui.util.Images;
import gov.va.isaac.interfaces.gui.views.PopupViewI;
import gov.va.isaac.util.CommonlyUsedConcepts;
import gov.va.isaac.util.UpdateableBooleanBinding;
import gov.va.isaac.util.WBUtility;
import java.util.ArrayList;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Tooltip;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import javafx.util.StringConverter;
import org.apache.commons.lang3.StringUtils;
import org.glassfish.hk2.api.PerLookup;
import org.glassfish.hk2.runlevel.RunLevelException;
import org.ihtsdo.otf.query.lucene.LuceneDynamicRefexIndexer;
import org.ihtsdo.otf.tcc.api.blueprint.IdDirective;
import org.ihtsdo.otf.tcc.api.blueprint.RefexDirective;
import org.ihtsdo.otf.tcc.api.blueprint.RefexDynamicCAB;
import org.ihtsdo.otf.tcc.api.blueprint.TerminologyBuilderBI;
import org.ihtsdo.otf.tcc.api.concept.ConceptVersionBI;
import org.ihtsdo.otf.tcc.api.coordinate.Status;
import org.ihtsdo.otf.tcc.api.metadata.binding.RefexDynamic;
import org.ihtsdo.otf.tcc.api.refexDynamic.RefexDynamicChronicleBI;
import org.ihtsdo.otf.tcc.api.refexDynamic.data.RefexDynamicColumnInfo;
import org.ihtsdo.otf.tcc.api.refexDynamic.data.RefexDynamicDataBI;
import org.ihtsdo.otf.tcc.api.refexDynamic.data.RefexDynamicDataType;
import org.ihtsdo.otf.tcc.api.refexDynamic.data.RefexDynamicUsageDescription;
import org.ihtsdo.otf.tcc.model.cc.refexDynamic.data.RefexDynamicData;
import org.ihtsdo.otf.tcc.model.cc.refexDynamic.data.RefexDynamicUsageDescriptionBuilder;
import org.ihtsdo.otf.tcc.model.index.service.IndexedGenerationCallable;
import org.jvnet.hk2.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.javafx.collections.ObservableListWrapper;
/**
*
* Refset View
*
* @author <a href="mailto:daniel.armbrust.list@gmail.com">Dan Armbrust</a>
*/
@Service
@PerLookup
public class AddRefexPopup extends Stage implements PopupViewI
{
private DynamicRefexView callingView_;
private InputType createRefexFocus_;
private RefexDynamicGUI editRefex_;
private Label unselectableComponentLabel_;;
private ScrollPane sp_;
private ConceptNode selectableConcept_;
private RefexDynamicUsageDescription assemblageInfo_;
private SimpleBooleanProperty assemblageIsValid_ = new SimpleBooleanProperty(false);
private Logger logger_ = LoggerFactory.getLogger(this.getClass());
private UpdateableBooleanBinding allValid_;
private ArrayList<ReadOnlyStringProperty> currentDataFieldWarnings_ = new ArrayList<>();
private ArrayList<RefexDataTypeNodeDetails> currentDataFields_ = new ArrayList<>();
private ObservableList<SimpleDisplayConcept> refexDropDownOptions = FXCollections.observableArrayList();
private GridPane gp_;
private Label title_;
//TODO use the word Sememe
private AddRefexPopup()
{
super();
BorderPane root = new BorderPane();
VBox topItems = new VBox();
topItems.setFillWidth(true);
title_ = new Label("Create new refex instance");
title_.getStyleClass().add("titleLabel");
title_.setAlignment(Pos.CENTER);
title_.prefWidthProperty().bind(topItems.widthProperty());
topItems.getChildren().add(title_);
VBox.setMargin(title_, new Insets(10, 10, 10, 10));
gp_ = new GridPane();
gp_.setHgap(10.0);
gp_.setVgap(10.0);
VBox.setMargin(gp_, new Insets(5, 5, 5, 5));
topItems.getChildren().add(gp_);
Label referencedComponent = new Label("Referenced Component");
referencedComponent.getStyleClass().add("boldLabel");
gp_.add(referencedComponent, 0, 0);
unselectableComponentLabel_ = new Label();
//delay adding till we know which row
Label assemblageConceptLabel = new Label("Assemblage Concept");
assemblageConceptLabel.getStyleClass().add("boldLabel");
gp_.add(assemblageConceptLabel, 0, 1);
selectableConcept_ = new ConceptNode(null, true, refexDropDownOptions, null);
selectableConcept_.getConceptProperty().addListener(new ChangeListener<ConceptVersionBI>()
{
@Override
public void changed(ObservableValue<? extends ConceptVersionBI> observable, ConceptVersionBI oldValue, ConceptVersionBI newValue)
{
if (createRefexFocus_ != null && createRefexFocus_.getComponentNid() != null)
{
if (selectableConcept_.isValid().get())
{
//Its a valid concept, but is it a valid assemblage concept?
try
{
assemblageInfo_ = RefexDynamicUsageDescriptionBuilder.readRefexDynamicUsageDescriptionConcept(selectableConcept_.getConceptNoWait().getNid());
assemblageIsValid_.set(true);
}
catch (Exception e)
{
selectableConcept_.isValid().setInvalid("The selected concept is not properly constructed for use as an Assemblage concept");
logger_.info("Concept not a valid concept for a refex assemblage", e);
assemblageIsValid_.set(false);
}
}
else
{
assemblageInfo_ = null;
assemblageIsValid_.set(false);
}
buildDataFields(assemblageIsValid_.get(), null);
}
}
});
//delay adding concept till we know where
ColumnConstraints cc = new ColumnConstraints();
cc.setHgrow(Priority.NEVER);
cc.setMinWidth(FxUtils.calculateNecessaryWidthOfBoldLabel(referencedComponent));
gp_.getColumnConstraints().add(cc);
cc = new ColumnConstraints();
cc.setHgrow(Priority.ALWAYS);
gp_.getColumnConstraints().add(cc);
Label l = new Label("Data Fields");
l.getStyleClass().add("boldLabel");
VBox.setMargin(l, new Insets(5, 5, 5, 5));
topItems.getChildren().add(l);
root.setTop(topItems);
sp_ = new ScrollPane();
sp_.visibleProperty().bind(assemblageIsValid_);
sp_.setFitToHeight(true);
sp_.setFitToWidth(true);
root.setCenter(sp_);
allValid_ = new UpdateableBooleanBinding()
{
{
addBinding(assemblageIsValid_, selectableConcept_.isValid());
}
@Override
protected boolean computeValue()
{
if (assemblageIsValid_.get() && selectableConcept_.isValid().get())
{
boolean allDataValid = true;
for (ReadOnlyStringProperty ssp : currentDataFieldWarnings_)
{
if (ssp.get().length() > 0)
{
allDataValid = false;
break;
}
}
if (allDataValid)
{
clearInvalidReason();
return true;
}
}
setInvalidReason("All errors must be corrected before save is allowed");
return false;
}
};
GridPane bottomRow = new GridPane();
//spacer col
bottomRow.add(new Region(), 0, 0);
Button cancelButton = new Button("Cancel");
cancelButton.setOnAction((action) -> {
close();
});
GridPane.setMargin(cancelButton, new Insets(5, 20, 5, 0));
GridPane.setHalignment(cancelButton, HPos.RIGHT);
bottomRow.add(cancelButton, 1, 0);
Button saveButton = new Button("Save");
saveButton.disableProperty().bind(allValid_.not());
saveButton.setOnAction((action) -> {
doSave();
});
Node wrappedSave = ErrorMarkerUtils.setupDisabledInfoMarker(saveButton, allValid_.getReasonWhyInvalid());
GridPane.setMargin(wrappedSave, new Insets(5, 0, 5, 20));
bottomRow.add(wrappedSave, 2, 0);
//spacer col
bottomRow.add(new Region(), 3, 0);
cc = new ColumnConstraints();
cc.setHgrow(Priority.SOMETIMES);
cc.setFillWidth(true);
bottomRow.getColumnConstraints().add(cc);
cc = new ColumnConstraints();
cc.setHgrow(Priority.NEVER);
bottomRow.getColumnConstraints().add(cc);
cc = new ColumnConstraints();
cc.setHgrow(Priority.NEVER);
bottomRow.getColumnConstraints().add(cc);
cc = new ColumnConstraints();
cc.setHgrow(Priority.SOMETIMES);
cc.setFillWidth(true);
bottomRow.getColumnConstraints().add(cc);
root.setBottom(bottomRow);
Scene scene = new Scene(root);
scene.getStylesheets().add(AddRefexPopup.class.getResource("/isaac-shared-styles.css").toString());
setScene(scene);
}
public void finishInit(RefexDynamicGUI refexToEdit, DynamicRefexView viewToRefresh)
{
callingView_ = viewToRefresh;
createRefexFocus_ = null;
editRefex_ = refexToEdit;
title_.setText("Edit existing refex instance");
gp_.add(unselectableComponentLabel_, 1, 1);
unselectableComponentLabel_.setText(WBUtility.getDescription(editRefex_.getRefex().getAssemblageNid()));
//don't actually put this in the view
selectableConcept_.set(WBUtility.getConceptVersion(editRefex_.getRefex().getReferencedComponentNid()));
gp_.add(new Label(WBUtility.getDescription(editRefex_.getRefex().getReferencedComponentNid())), 1, 0);
refexDropDownOptions.clear();
try
{
assemblageInfo_ = RefexDynamicUsageDescriptionBuilder.readRefexDynamicUsageDescriptionConcept(editRefex_.getRefex().getAssemblageNid());
assemblageIsValid_.set(true);
buildDataFields(true, editRefex_.getRefex().getData());
}
catch (Exception e)
{
logger_.error("Unexpected", e);
AppContext.getCommonDialogs().showErrorDialog("Unexpected Error reading Assembly concept", e);
}
}
public void finishInit(InputType setFromType, DynamicRefexView viewToRefresh)
{
callingView_ = viewToRefresh;
createRefexFocus_ = setFromType;
editRefex_ = null;
title_.setText("Create new refex instance");
if (createRefexFocus_.getComponentNid() != null)
{
gp_.add(unselectableComponentLabel_, 1, 0);
unselectableComponentLabel_.setText(WBUtility.getDescription(createRefexFocus_.getComponentNid()));
gp_.add(selectableConcept_.getNode(), 1, 1);
refexDropDownOptions.clear();
refexDropDownOptions.addAll(buildAssemblageConceptList());
}
else
{
gp_.add(unselectableComponentLabel_, 1, 1);
unselectableComponentLabel_.setText(WBUtility.getDescription(createRefexFocus_.getAssemblyNid()));
gp_.add(selectableConcept_.getNode(), 1, 0);
refexDropDownOptions.clear();
refexDropDownOptions.addAll(AppContext.getService(CommonlyUsedConcepts.class).getObservableConcepts());
try
{
assemblageInfo_ = RefexDynamicUsageDescriptionBuilder.readRefexDynamicUsageDescriptionConcept(createRefexFocus_.getAssemblyNid());
assemblageIsValid_.set(true);
buildDataFields(true, null);
}
catch (Exception e)
{
logger_.error("Unexpected", e);
AppContext.getCommonDialogs().showErrorDialog("Unexpected Error reading Assembly concept", e);
}
}
}
private void buildDataFields(boolean assemblageValid, RefexDynamicDataBI[] currentValues)
{
if (assemblageValid)
{
for (ReadOnlyStringProperty ssp : currentDataFieldWarnings_)
{
allValid_.removeBinding(ssp);
}
currentDataFieldWarnings_.clear();
for (RefexDataTypeNodeDetails nd : currentDataFields_)
{
nd.cleanupListener();
}
currentDataFields_.clear();
GridPane gp = new GridPane();
gp.setHgap(10.0);
gp.setVgap(10.0);
gp.setStyle("-fx-padding: 5;");
int row = 0;
boolean extraInfoColumnIsRequired = false;
for (RefexDynamicColumnInfo ci : assemblageInfo_.getColumnInfo())
{
SimpleStringProperty valueIsRequired = (ci.isColumnRequired() ? new SimpleStringProperty("") : null);
SimpleStringProperty defaultValueTooltip = ((ci.getDefaultColumnValue() == null && ci.getValidator() == null) ? null : new SimpleStringProperty());
ComboBox<RefexDynamicDataType> polymorphicType = null;
Label l = new Label(ci.getColumnName());
l.getStyleClass().add("boldLabel");
l.setMinWidth(FxUtils.calculateNecessaryWidthOfBoldLabel(l));
Tooltip.install(l, new Tooltip(ci.getColumnDescription()));
int col = 0;
gp.add(l, col++, row);
if (ci.getColumnDataType() == RefexDynamicDataType.POLYMORPHIC)
{
polymorphicType = new ComboBox<>();
polymorphicType.setEditable(false);
polymorphicType.setConverter(new StringConverter<RefexDynamicDataType>()
{
@Override
public String toString(RefexDynamicDataType object)
{
return object.getDisplayName();
}
@Override
public RefexDynamicDataType fromString(String string)
{
throw new RuntimeException("unecessary");
}
});
for (RefexDynamicDataType type : RefexDynamicDataType.values())
{
if (type == RefexDynamicDataType.POLYMORPHIC || type == RefexDynamicDataType.UNKNOWN)
{
continue;
}
else
{
polymorphicType.getItems().add(type);
}
}
polymorphicType.getSelectionModel().select((currentValues == null ? RefexDynamicDataType.STRING : currentValues[row].getRefexDataType()));
}
RefexDataTypeNodeDetails nd = RefexDataTypeFXNodeBuilder.buildNodeForType(ci.getColumnDataType(), ci.getDefaultColumnValue(),
(currentValues == null ? null : currentValues[row]),valueIsRequired, defaultValueTooltip,
(polymorphicType == null ? null : polymorphicType.getSelectionModel().selectedItemProperty()), allValid_,
new SimpleObjectProperty<>(ci.getValidator()), new SimpleObjectProperty<>(ci.getValidatorData()));
currentDataFieldWarnings_.addAll(nd.getBoundToAllValid());
if (ci.getColumnDataType() == RefexDynamicDataType.POLYMORPHIC)
{
nd.addUpdateParentListListener(currentDataFieldWarnings_);
}
currentDataFields_.add(nd);
gp.add(nd.getNodeForDisplay(), col++, row);
if (ci.isColumnRequired() || ci.getDefaultColumnValue() != null || ci.getValidator() != null)
{
extraInfoColumnIsRequired = true;
StackPane stackPane = new StackPane();
stackPane.setMaxWidth(Double.MAX_VALUE);
if (ci.getDefaultColumnValue() != null || ci.getValidator() != null)
{
ImageView information = Images.INFORMATION.createImageView();
Tooltip tooltip = new Tooltip();
tooltip.textProperty().bind(defaultValueTooltip);
Tooltip.install(information, tooltip);
tooltip.setAutoHide(true);
information.setOnMouseClicked(event -> tooltip.show(information, event.getScreenX(), event.getScreenY()));
stackPane.getChildren().add(information);
}
if (ci.isColumnRequired())
{
ImageView exclamation = Images.EXCLAMATION.createImageView();
final BooleanProperty showExclamation = new SimpleBooleanProperty(StringUtils.isNotBlank(valueIsRequired.get()));
valueIsRequired.addListener((ChangeListener<String>) (observable, oldValue, newValue) -> showExclamation.set(StringUtils.isNotBlank(newValue)));
exclamation.visibleProperty().bind(showExclamation);
Tooltip tooltip = new Tooltip();
tooltip.textProperty().bind(valueIsRequired);
Tooltip.install(exclamation, tooltip);
tooltip.setAutoHide(true);
exclamation.setOnMouseClicked(event -> tooltip.show(exclamation, event.getScreenX(), event.getScreenY()));
stackPane.getChildren().add(exclamation);
}
gp.add(stackPane, col++, row);
}
Label colType = new Label(ci.getColumnDataType().getDisplayName());
colType.setMinWidth(FxUtils.calculateNecessaryWidthOfLabel(colType));
gp.add((polymorphicType == null ? colType : polymorphicType), col++, row++);
}
ColumnConstraints cc = new ColumnConstraints();
cc.setHgrow(Priority.NEVER);
gp.getColumnConstraints().add(cc);
cc = new ColumnConstraints();
cc.setHgrow(Priority.ALWAYS);
gp.getColumnConstraints().add(cc);
if (extraInfoColumnIsRequired)
{
cc = new ColumnConstraints();
cc.setHgrow(Priority.NEVER);
gp.getColumnConstraints().add(cc);
}
cc = new ColumnConstraints();
cc.setHgrow(Priority.NEVER);
gp.getColumnConstraints().add(cc);
if (row == 0)
{
sp_.setContent(new Label("This assemblage does not allow data fields"));
}
else
{
sp_.setContent(gp);
}
allValid_.invalidate();
}
else
{
sp_.setContent(null);
}
}
private void doSave()
{
try
{
RefexDynamicDataBI[] data = new RefexDynamicData[assemblageInfo_.getColumnInfo().length];
int i = 0;
for (RefexDynamicColumnInfo ci : assemblageInfo_.getColumnInfo())
{
data[i] = RefexDataTypeFXNodeBuilder.getDataForType(currentDataFields_.get(i++).getDataField(), ci);
}
int componentNid;
int assemblageNid;
RefexDynamicCAB cab;
if (createRefexFocus_ != null)
{
if (createRefexFocus_.getComponentNid() == null)
{
componentNid = selectableConcept_.getConcept().getNid();
assemblageNid = createRefexFocus_.getAssemblyNid();
}
else
{
componentNid = createRefexFocus_.getComponentNid();
assemblageNid = selectableConcept_.getConcept().getNid();
}
cab = new RefexDynamicCAB(componentNid, assemblageNid);
}
else
{
componentNid = editRefex_.getRefex().getReferencedComponentNid();
assemblageNid = editRefex_.getRefex().getAssemblageNid();
cab = editRefex_.getRefex().makeBlueprint(WBUtility.getViewCoordinate(),IdDirective.PRESERVE, RefexDirective.INCLUDE);
//If they are editing, we assume that they want it back active, if it is retired.
cab.setStatus(Status.ACTIVE);
}
cab.setData(data, WBUtility.getViewCoordinate());
TerminologyBuilderBI builder = ExtendedAppContext.getDataStore().getTerminologyBuilder(WBUtility.getEC(), WBUtility.getViewCoordinate());
RefexDynamicChronicleBI<?> rdc = builder.construct(cab);
boolean isAnnotationStyle = WBUtility.getConceptVersion(assemblageNid).isAnnotationStyleRefex();
IndexedGenerationCallable indexGen = null;
//In order to make sure we can wait for the index to have this entry, we need a latch...
if (isAnnotationStyle)
{
indexGen = AppContext.getService(LuceneDynamicRefexIndexer.class).getIndexedGenerationCallable(rdc.getNid());
}
ExtendedAppContext.getDataStore().addUncommitted(ExtendedAppContext.getDataStore().getConceptForNid(componentNid));
if (!isAnnotationStyle)
{
ExtendedAppContext.getDataStore().addUncommitted(WBUtility.getConceptVersion(assemblageNid));
}
if (callingView_ != null)
{
ExtendedAppContext.getDataStore().waitTillWritesFinished();
callingView_.setNewComponentHint(componentNid, indexGen);
callingView_.refresh();
}
close();
}
catch (Exception e)
{
logger_.error("Error saving refex", e);
AppContext.getCommonDialogs().showErrorDialog("Unexpected error", "There was an error saving the refex", e.getMessage(), this);
}
}
/**
* Call setReferencedComponent first
*
* @see gov.va.isaac.interfaces.gui.views.PopupViewI#showView(javafx.stage.Window)
*/
@Override
public void showView(Window parent)
{
if (createRefexFocus_ == null && editRefex_ == null)
{
throw new RunLevelException("referenced component nid must be set first");
}
setTitle("Create new Refex");
setResizable(true);
initOwner(parent);
initModality(Modality.NONE);
initStyle(StageStyle.DECORATED);
setWidth(600);
setHeight(400);
show();
}
private ObservableList<SimpleDisplayConcept> buildAssemblageConceptList()
{
ObservableList<SimpleDisplayConcept> assemblageConcepts = new ObservableListWrapper<>(new ArrayList<SimpleDisplayConcept>());
try
{
ConceptVersionBI colCon = WBUtility.getConceptVersion(RefexDynamic.REFEX_DYNAMIC_IDENTITY.getNid());
ArrayList<ConceptVersionBI> colCons = WBUtility.getAllChildrenOfConcept(colCon, false);
for (ConceptVersionBI col : colCons) {
assemblageConcepts.add(new SimpleDisplayConcept(col));
}
}
catch (Exception e)
{
logger_.error("Unexpected error reading existing assemblage concepts", e);
}
return assemblageConcepts;
}
}
|
make concept labels copyable / draggable
|
refex-view/src/main/java/gov/va/isaac/gui/refexViews/refexEdit/AddRefexPopup.java
|
make concept labels copyable / draggable
|
|
Java
|
apache-2.0
|
de6c791848008454425dea354f55dd1bc5e7ec1c
| 0
|
EvilMcJerkface/atlasdb,EvilMcJerkface/atlasdb,palantir/atlasdb,EvilMcJerkface/atlasdb,palantir/atlasdb,palantir/atlasdb
|
/*
* Copyright 2015 Palantir Technologies, Inc. All rights reserved.
* <p>
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://opensource.org/licenses/BSD-3-Clause
* <p>
* 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.palantir.atlasdb.keyvalue.dbkvs;
import java.net.InetSocketAddress;
import java.util.concurrent.Callable;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.jayway.awaitility.Awaitility;
import com.jayway.awaitility.Duration;
import com.palantir.atlasdb.keyvalue.dbkvs.impl.ConnectionManagerAwareDbKvs;
import com.palantir.docker.compose.DockerComposeRule;
import com.palantir.docker.compose.configuration.ShutdownStrategy;
import com.palantir.docker.compose.connection.Container;
import com.palantir.docker.compose.connection.DockerPort;
import com.palantir.docker.compose.logging.LogDirectory;
import com.palantir.nexus.db.pool.config.ConnectionConfig;
import com.palantir.nexus.db.pool.config.ImmutableMaskedValue;
import com.palantir.nexus.db.pool.config.ImmutablePostgresConnectionConfig;
@RunWith(Suite.class)
@SuiteClasses({
DbkvsPostgresKeyValueServiceTest.class,
DbkvsPostgresSerializableTransactionTest.class,
DbkvsPostgresSweeperTest.class,
PostgresDbTimestampBoundStoreTest.class
})
public final class DbkvsPostgresTestSuite {
private static final int POSTGRES_PORT_NUMBER = 5432;
private DbkvsPostgresTestSuite() {
// Test suite
}
@ClassRule
public static final DockerComposeRule docker = DockerComposeRule.builder()
.file("src/test/resources/docker-compose.yml")
.waitingForService("postgres", Container::areAllPortsOpen)
.saveLogsTo(LogDirectory.circleAwareLogDirectory(DbkvsPostgresTestSuite.class))
.shutdownStrategy(ShutdownStrategy.AGGRESSIVE_WITH_NETWORK_CLEANUP)
.build();
@BeforeClass
public static void waitUntilDbkvsIsUp() throws InterruptedException {
Awaitility.await()
.atMost(Duration.ONE_MINUTE)
.pollInterval(Duration.ONE_SECOND)
.until(canCreateKeyValueService());
}
public static DbKeyValueServiceConfig getKvsConfig() {
DockerPort port = docker.containers()
.container("postgres")
.port(POSTGRES_PORT_NUMBER);
InetSocketAddress postgresAddress = new InetSocketAddress(port.getIp(), port.getExternalPort());
ConnectionConfig connectionConfig = ImmutablePostgresConnectionConfig.builder()
.dbName("atlas")
.dbLogin("palantir")
.dbPassword(ImmutableMaskedValue.of("palantir"))
.host(postgresAddress.getHostName())
.port(postgresAddress.getPort())
.build();
return ImmutableDbKeyValueServiceConfig.builder()
.connection(connectionConfig)
.ddl(ImmutablePostgresDdlConfig.builder().build())
.build();
}
private static Callable<Boolean> canCreateKeyValueService() {
return () -> {
ConnectionManagerAwareDbKvs kvs = null;
try {
kvs = ConnectionManagerAwareDbKvs.create(getKvsConfig());
return kvs.getConnectionManager().getConnection().isValid(5);
} catch (Exception ex) {
if (ex.getMessage().contains("The connection attempt failed.")) {
return false;
} else {
throw ex;
}
} finally {
if (kvs != null) {
kvs.close();
}
}
};
}
}
|
atlasdb-dbkvs-tests/src/test/java/com/palantir/atlasdb/keyvalue/dbkvs/DbkvsPostgresTestSuite.java
|
/*
* Copyright 2015 Palantir Technologies, Inc. All rights reserved.
* <p>
* Licensed under the BSD-3 License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://opensource.org/licenses/BSD-3-Clause
* <p>
* 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.palantir.atlasdb.keyvalue.dbkvs;
import java.net.InetSocketAddress;
import java.util.concurrent.Callable;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.jayway.awaitility.Awaitility;
import com.jayway.awaitility.Duration;
import com.palantir.atlasdb.keyvalue.dbkvs.impl.ConnectionManagerAwareDbKvs;
import com.palantir.docker.compose.DockerComposeRule;
import com.palantir.docker.compose.configuration.ShutdownStrategy;
import com.palantir.docker.compose.connection.Container;
import com.palantir.docker.compose.connection.DockerPort;
import com.palantir.docker.compose.logging.LogDirectory;
import com.palantir.nexus.db.pool.config.ConnectionConfig;
import com.palantir.nexus.db.pool.config.ImmutableMaskedValue;
import com.palantir.nexus.db.pool.config.ImmutablePostgresConnectionConfig;
@RunWith(Suite.class)
@SuiteClasses({
DbkvsPostgresKeyValueServiceTest.class,
DbkvsPostgresSerializableTransactionTest.class,
DbkvsPostgresSweeperTest.class,
PostgresDbTimestampBoundStoreTest.class
})
public final class DbkvsPostgresTestSuite {
private static final int POSTGRES_PORT_NUMBER = 5432;
private DbkvsPostgresTestSuite() {
// Test suite
}
@ClassRule
public static final DockerComposeRule docker = DockerComposeRule.builder()
.file("src/test/resources/docker-compose.yml")
.waitingForService("postgres", Container::areAllPortsOpen)
.saveLogsTo(LogDirectory.circleAwareLogDirectory(DbkvsPostgresTestSuite.class))
.shutdownStrategy(ShutdownStrategy.AGGRESSIVE_WITH_NETWORK_CLEANUP)
.build();
@BeforeClass
public static void waitUntilDbkvsIsUp() throws InterruptedException {
Awaitility.await()
.atMost(Duration.ONE_MINUTE)
.pollInterval(Duration.ONE_SECOND)
.until(canCreateKeyValueService());
}
public static DbKeyValueServiceConfig getKvsConfig() {
DockerPort port = docker.containers()
.container("postgres")
.port(POSTGRES_PORT_NUMBER);
InetSocketAddress postgresAddress = new InetSocketAddress(port.getIp(), port.getExternalPort());
ConnectionConfig connectionConfig = ImmutablePostgresConnectionConfig.builder()
.dbName("atlas")
.dbLogin("palantir")
.dbPassword(ImmutableMaskedValue.of("palantir"))
.host(postgresAddress.getHostName())
.port(postgresAddress.getPort())
.build();
return ImmutableDbKeyValueServiceConfig.builder()
.connection(connectionConfig)
.ddl(ImmutablePostgresDdlConfig.builder().build())
.build();
}
private static Callable<Boolean> canCreateKeyValueService() {
return () -> {
ConnectionManagerAwareDbKvs kvs = null;
try {
kvs = ConnectionManagerAwareDbKvs.create(getKvsConfig());
return kvs.getConnectionManager().getConnection().isValid(5);
} catch (Exception e) {
if (e.getMessage().contains("The connection attempt failed.")) {
return false;
} else {
throw e;
}
} finally {
if (kvs != null) {
kvs.close();
}
}
};
}
}
|
[no release notes]
(trivial change so I can do this from github)
|
atlasdb-dbkvs-tests/src/test/java/com/palantir/atlasdb/keyvalue/dbkvs/DbkvsPostgresTestSuite.java
|
[no release notes]
|
|
Java
|
apache-2.0
|
3385a450802f09e6cfc141b853d78f511c3c6c4b
| 0
|
sabriarabacioglu/engerek,sabriarabacioglu/engerek,rpudil/midpoint,Pardus-Engerek/engerek,sabriarabacioglu/engerek,arnost-starosta/midpoint,Pardus-Engerek/engerek,gureronder/midpoint,arnost-starosta/midpoint,Pardus-Engerek/engerek,PetrGasparik/midpoint,PetrGasparik/midpoint,Pardus-Engerek/engerek,rpudil/midpoint,PetrGasparik/midpoint,arnost-starosta/midpoint,arnost-starosta/midpoint,gureronder/midpoint,PetrGasparik/midpoint,arnost-starosta/midpoint,gureronder/midpoint,rpudil/midpoint,rpudil/midpoint,gureronder/midpoint
|
/*
* Copyright (c) 2010-2013 Evolveum
*
* 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.evolveum.midpoint.web.page.admin.configuration;
import com.evolveum.midpoint.model.api.ModelExecuteOptions;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.match.PolyStringNormMatchingRule;
import com.evolveum.midpoint.prism.match.PolyStringOrigMatchingRule;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.polystring.PolyStringNormalizer;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.SubstringFilter;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.SchemaConstantsGenerated;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.button.AjaxLinkButton;
import com.evolveum.midpoint.web.component.button.AjaxSubmitLinkButton;
import com.evolveum.midpoint.web.component.button.ButtonType;
import com.evolveum.midpoint.web.component.data.RepositoryObjectDataProvider;
import com.evolveum.midpoint.web.component.data.TablePanel;
import com.evolveum.midpoint.web.component.data.column.ButtonColumn;
import com.evolveum.midpoint.web.component.data.column.CheckBoxHeaderColumn;
import com.evolveum.midpoint.web.component.data.column.LinkColumn;
import com.evolveum.midpoint.web.component.dialog.ConfirmationDialog;
import com.evolveum.midpoint.web.component.option.OptionContent;
import com.evolveum.midpoint.web.component.option.OptionItem;
import com.evolveum.midpoint.web.component.option.OptionPanel;
import com.evolveum.midpoint.web.component.util.LoadableModel;
import com.evolveum.midpoint.web.page.PageBase;
import com.evolveum.midpoint.web.page.admin.configuration.component.PageDebugDownloadBehaviour;
import com.evolveum.midpoint.web.page.admin.configuration.dto.DebugObjectItem;
import com.evolveum.midpoint.web.security.MidPointApplication;
import com.evolveum.midpoint.web.security.WebApplicationConfiguration;
import com.evolveum.midpoint.web.session.ConfigurationStorage;
import com.evolveum.midpoint.web.util.WebMiscUtil;
import com.evolveum.midpoint.xml.ns._public.common.common_2a.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_2a.ShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_2a.UserType;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.file.File;
import org.apache.wicket.util.file.Files;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author lazyman
* @author mserbak
*/
public class PageDebugList extends PageAdminConfiguration {
private static final Trace LOGGER = TraceManager.getTrace(PageDebugList.class);
private static final String DOT_CLASS = PageDebugList.class.getName() + ".";
private static final String OPERATION_DELETE_OBJECT = DOT_CLASS + "deleteObject";
private static final String OPERATION_DELETE_OBJECTS = DOT_CLASS + "deleteObjects";
private static final String ID_CONFIRM_DELETE_POPUP = "confirmDeletePopup";
private static final String ID_MAIN_FORM = "mainForm";
private static final String ID_ZIP_CHECK = "zipCheck";
private static final String ID_OPTION_CONTENT = "optionContent";
private static final String ID_OPTION = "option";
private static final String ID_SEARCH = "search";
private static final String ID_CATEGORY = "category";
private static final String ID_TABLE = "table";
private static final String ID_CHOICE = "choice";
private static final String ID_DELETE_SELECTED = "deleteSelected";
private static final String ID_EXPORT = "export";
private static final String ID_EXPORT_ALL = "exportAll";
private static final String ID_SEARCH_TEXT = "searchText";
private static final String ID_CLEAR_BUTTON = "clearButton";
private static final String ID_SEARCH_BUTTON = "searchButton";
private boolean deleteSelected; //todo what is this used for?
private IModel<ObjectTypes> choice = null;
private DebugObjectItem object = null; //todo what is this used for?
public PageDebugList() {
initLayout();
}
private void initLayout() {
//confirm delete
add(new ConfirmationDialog(ID_CONFIRM_DELETE_POPUP,
createStringResource("pageDebugList.dialog.title.confirmDelete"), createDeleteConfirmString()) {
@Override
public void yesPerformed(AjaxRequestTarget target) {
close(target);
//todo wtf
if (deleteSelected) {
deleteSelected = false;
deleteSelectedConfirmedPerformed(target);
} else {
deleteObjectConfirmedPerformed(target);
}
}
});
final Form main = new Form(ID_MAIN_FORM);
add(main);
choice = new Model<ObjectTypes>() {
@Override
public ObjectTypes getObject() {
ObjectTypes types = super.getObject();
if (types == null) {
ConfigurationStorage storage = getSessionStorage().getConfiguration();
types = storage.getDebugListCategory();
}
return types;
}
};
OptionPanel option = new OptionPanel(ID_OPTION, createStringResource("pageDebugList.optionsTitle"), false);
option.setOutputMarkupId(true);
main.add(option);
OptionItem item = new OptionItem(ID_SEARCH, createStringResource("pageDebugList.search"));
option.getBodyContainer().add(item);
IModel<String> searchNameModel = initSearch(item);
item = new OptionItem(ID_CATEGORY, createStringResource("pageDebugList.selectType"));
option.getBodyContainer().add(item);
initCategory(item, searchNameModel);
OptionContent content = new OptionContent(ID_OPTION_CONTENT);
main.add(content);
ConfigurationStorage storage = getSessionStorage().getConfiguration();
Class type = storage.getDebugListCategory().getClassDefinition();
addOrReplaceTable(new RepositoryObjectDataProvider(this, type));
initButtonBar(main);
}
private void initButtonBar(Form main) {
AjaxLinkButton delete = new AjaxLinkButton(ID_DELETE_SELECTED, ButtonType.NEGATIVE,
createStringResource("pageDebugList.button.deleteSelected")) {
@Override
public void onClick(AjaxRequestTarget target) {
deleteSelectedPerformed(target, choice);
}
};
main.add(delete);
final PageDebugDownloadBehaviour ajaxDownloadBehavior = new PageDebugDownloadBehaviour();
main.add(ajaxDownloadBehavior);
AjaxLinkButton export = new AjaxLinkButton(ID_EXPORT,
createStringResource("pageDebugList.button.export")) {
@Override
public void onClick(AjaxRequestTarget target) {
initDownload(ajaxDownloadBehavior, target, false);
}
};
main.add(export);
AjaxLinkButton exportAll = new AjaxLinkButton(ID_EXPORT_ALL,
createStringResource("pageDebugList.button.exportAll")) {
@Override
public void onClick(AjaxRequestTarget target) {
initDownload(ajaxDownloadBehavior, target, true);
}
};
main.add(exportAll);
AjaxCheckBox zipCheck = new AjaxCheckBox(ID_ZIP_CHECK, new Model<Boolean>(false)) {
@Override
protected void onUpdate(AjaxRequestTarget target) {
}
};
main.add(zipCheck);
}
private void initDownload(PageDebugDownloadBehaviour downloadBehaviour, AjaxRequestTarget target, boolean all) {
Class<? extends ObjectType> type = all ? ObjectType.class : getExportType();
downloadBehaviour.setType(type);
downloadBehaviour.setQuery(createExportQuery());
downloadBehaviour.setUseZip(hasToZip());
downloadBehaviour.initiate(target);
}
private Class<? extends ObjectType> getExportType() {
Class type = getTableDataProvider().getType();
return type == null ? ObjectType.class : type;
}
private ObjectQuery createExportQuery() {
ObjectQuery query = getTableDataProvider().getQuery();
ObjectQuery clonedQuery = null;
if (query != null) {
clonedQuery = new ObjectQuery();
clonedQuery.setFilter(query.getFilter());
}
return clonedQuery;
}
private void addOrReplaceTable(RepositoryObjectDataProvider provider) {
OptionContent content = (OptionContent) get(createComponentPath(ID_MAIN_FORM, ID_OPTION_CONTENT));
TablePanel table = new TablePanel(ID_TABLE, provider, initColumns(provider.getType()));
table.setOutputMarkupId(true);
content.getBodyContainer().addOrReplace(table);
}
private List<IColumn> initColumns(final Class<? extends ObjectType> type) {
List<IColumn> columns = new ArrayList<IColumn>();
IColumn column = new CheckBoxHeaderColumn<ObjectType>();
columns.add(column);
column = new LinkColumn<DebugObjectItem>(createStringResource("pageDebugList.name"),
DebugObjectItem.F_NAME, DebugObjectItem.F_NAME) {
@Override
public void onClick(AjaxRequestTarget target, IModel<DebugObjectItem> rowModel) {
DebugObjectItem object = rowModel.getObject();
objectEditPerformed(target, object.getOid(), type);
}
};
columns.add(column);
if (ShadowType.class.isAssignableFrom(type)) {
columns.add(new PropertyColumn(createStringResource("pageDebugList.resourceName"),
DebugObjectItem.F_RESOURCE_NAME));
columns.add(new PropertyColumn(createStringResource("pageDebugList.resourceType"),
DebugObjectItem.F_RESOURCE_TYPE));
}
column = new ButtonColumn<DebugObjectItem>(createStringResource("pageDebugList.operation"),
createStringResource("pageDebugList.button.delete")) {
@Override
public void onClick(AjaxRequestTarget target, IModel<DebugObjectItem> rowModel) {
DebugObjectItem object = rowModel.getObject();
deleteObjectPerformed(target, choice, object);
}
};
columns.add(column);
return columns;
}
private boolean hasToZip() {
AjaxCheckBox zipCheck = (AjaxCheckBox) get(createComponentPath(ID_MAIN_FORM, ID_ZIP_CHECK));
return zipCheck.getModelObject();
}
private IModel<String> initSearch(OptionItem item) {
final IModel<String> model = new Model<String>();
TextField<String> search = new TextField<String>(ID_SEARCH_TEXT, model);
item.add(search);
AjaxSubmitLinkButton clearButton = new AjaxSubmitLinkButton(ID_CLEAR_BUTTON,
new StringResourceModel("pageDebugList.button.clear", this, null)) {
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
PageBase page = (PageBase) getPage();
target.add(page.getFeedbackPanel());
}
@Override
public void onSubmit(AjaxRequestTarget target, Form<?> form) {
model.setObject(null);
target.appendJavaScript("init()");
target.add(PageDebugList.this.get(createComponentPath(ID_MAIN_FORM, ID_OPTION)));
listObjectsPerformed(target, model.getObject(), null);
}
};
item.add(clearButton);
AjaxSubmitLinkButton searchButton = new AjaxSubmitLinkButton(ID_SEARCH_BUTTON,
new StringResourceModel("pageDebugList.button.search", this, null)) {
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
PageBase page = (PageBase) getPage();
target.add(page.getFeedbackPanel());
}
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
listObjectsPerformed(target, model.getObject(), null);
}
};
item.add(searchButton);
return model;
}
private void initCategory(OptionItem item, final IModel<String> searchNameModel) {
IChoiceRenderer<ObjectTypes> renderer = new IChoiceRenderer<ObjectTypes>() {
@Override
public Object getDisplayValue(ObjectTypes object) {
return new StringResourceModel(object.getLocalizationKey(), PageDebugList.this, null).getString();
}
@Override
public String getIdValue(ObjectTypes object, int index) {
return object.getClassDefinition().getSimpleName();
}
};
IModel<List<ObjectTypes>> choiceModel = createChoiceModel(renderer);
final ListChoice listChoice = new ListChoice(ID_CHOICE, choice, choiceModel, renderer, choiceModel.getObject().size()) {
@Override
protected CharSequence getDefaultChoice(String selectedValue) {
return "";
}
};
listChoice.add(new OnChangeAjaxBehavior() {
@Override
protected void onUpdate(AjaxRequestTarget target) {
target.add(listChoice);
listObjectsPerformed(target, searchNameModel.getObject(), choice.getObject());
}
});
item.getBodyContainer().add(listChoice);
}
private IModel<List<ObjectTypes>> createChoiceModel(final IChoiceRenderer<ObjectTypes> renderer) {
return new LoadableModel<List<ObjectTypes>>(false) {
@Override
protected List<ObjectTypes> load() {
List<ObjectTypes> choices = new ArrayList<ObjectTypes>();
Collections.addAll(choices, ObjectTypes.values());
choices.remove(ObjectTypes.OBJECT);
Collections.sort(choices, new Comparator<ObjectTypes>() {
@Override
public int compare(ObjectTypes o1, ObjectTypes o2) {
String str1 = (String) renderer.getDisplayValue(o1);
String str2 = (String) renderer.getDisplayValue(o2);
return String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
}
});
return choices;
}
};
}
private TablePanel getListTable() {
OptionContent content = (OptionContent) get(createComponentPath(ID_MAIN_FORM, ID_OPTION_CONTENT));
return (TablePanel) content.getBodyContainer().get(ID_TABLE);
}
private void listObjectsPerformed(AjaxRequestTarget target, String nameText, ObjectTypes selected) {
RepositoryObjectDataProvider provider = getTableDataProvider();
if (StringUtils.isNotEmpty(nameText)) {
try {
PolyStringNormalizer normalizer = getPrismContext().getDefaultPolyStringNormalizer();
String normalizedString = normalizer.normalize(nameText);
ObjectFilter substring = SubstringFilter.createSubstring(ObjectType.class, getPrismContext(),
ObjectType.F_NAME, PolyStringNormMatchingRule.NAME.getLocalPart(), normalizedString);
ObjectQuery query = new ObjectQuery();
query.setFilter(substring);
provider.setQuery(query);
} catch (Exception ex) {
LoggingUtils.logException(LOGGER, "Couldn't create substring filter", ex);
error(getString("pageDebugList.message.queryException", ex.getMessage()));
target.add(getFeedbackPanel());
}
} else {
provider.setQuery(null);
}
if (selected != null) {
provider.setType(selected.getClassDefinition());
addOrReplaceTable(provider);
}
TablePanel table = getListTable();
target.add(table);
}
private void objectEditPerformed(AjaxRequestTarget target, String oid, Class<? extends ObjectType> type) {
PageParameters parameters = new PageParameters();
parameters.add(PageDebugView.PARAM_OBJECT_ID, oid);
parameters.add(PageDebugView.PARAM_OBJECT_TYPE, type.getSimpleName());
setResponsePage(PageDebugView.class, parameters);
}
private RepositoryObjectDataProvider getTableDataProvider() {
TablePanel tablePanel = getListTable();
DataTable table = tablePanel.getDataTable();
return (RepositoryObjectDataProvider) table.getDataProvider();
}
private IModel<String> createDeleteConfirmString() {
return new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
if (deleteSelected) {
List<DebugObjectItem> selectedList = WebMiscUtil
.getSelectedData(getListTable());
if (selectedList.size() > 1) {
return createStringResource("pageDebugList.message.deleteSelectedConfirm",
selectedList.size()).getString();
}
DebugObjectItem selectedItem = selectedList.get(0);
return createStringResource("pageDebugList.message.deleteObjectConfirm",
selectedItem.getName()).getString();
}
return createStringResource("pageDebugList.message.deleteObjectConfirm", object.getName())
.getString();
}
};
}
private void deleteSelectedConfirmedPerformed(AjaxRequestTarget target) {
ObjectTypes type = choice.getObject();
OperationResult result = new OperationResult(OPERATION_DELETE_OBJECTS);
List<DebugObjectItem> beans = WebMiscUtil.getSelectedData(getListTable());
for (DebugObjectItem bean : beans) {
OperationResult subResult = result.createSubresult(OPERATION_DELETE_OBJECT);
try {
ObjectDelta delta = ObjectDelta.createDeleteDelta(type.getClassDefinition(), bean.getOid(), getPrismContext());
getModelService().executeChanges(WebMiscUtil.createDeltaCollection(delta),
ModelExecuteOptions.createRaw(),
createSimpleTask(OPERATION_DELETE_OBJECT), subResult);
subResult.recordSuccess();
} catch (Exception ex) {
subResult.recordFatalError("Couldn't delete objects.", ex);
LoggingUtils.logException(LOGGER, "Couldn't delete objects", ex);
}
}
result.recomputeStatus();
RepositoryObjectDataProvider provider = getTableDataProvider();
provider.clearCache();
showResult(result);
target.add(getListTable());
target.add(getFeedbackPanel());
}
private void deleteObjectConfirmedPerformed(AjaxRequestTarget target) {
OperationResult result = new OperationResult(OPERATION_DELETE_OBJECT);
try {
ObjectTypes type = choice.getObject();
ObjectDelta delta = ObjectDelta.createDeleteDelta(type.getClassDefinition(), object.getOid(), getPrismContext());
getModelService().executeChanges(WebMiscUtil.createDeltaCollection(delta),
ModelExecuteOptions.createRaw(),
createSimpleTask(OPERATION_DELETE_OBJECT), result);
result.recordSuccess();
} catch (Exception ex) {
result.recordFatalError("Couldn't delete object '" + object.getName() + "'.", ex);
}
RepositoryObjectDataProvider provider = getTableDataProvider();
provider.clearCache();
showResult(result);
target.add(getListTable());
target.add(getFeedbackPanel());
}
private void deleteSelectedPerformed(AjaxRequestTarget target, IModel<ObjectTypes> choice) {
List<DebugObjectItem> selected = WebMiscUtil.getSelectedData(getListTable());
if (selected.isEmpty()) {
warn(getString("pageDebugList.message.nothingSelected"));
target.add(getFeedbackPanel());
return;
}
ModalWindow dialog = (ModalWindow) get(ID_CONFIRM_DELETE_POPUP);
deleteSelected = true;
this.choice = choice;
dialog.show(target);
}
private void deleteObjectPerformed(AjaxRequestTarget target, IModel<ObjectTypes> choice, DebugObjectItem object) {
ModalWindow dialog = (ModalWindow) get(ID_CONFIRM_DELETE_POPUP);
this.choice = choice;
this.object = object;
dialog.show(target);
}
}
|
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageDebugList.java
|
/*
* Copyright (c) 2010-2013 Evolveum
*
* 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.evolveum.midpoint.web.page.admin.configuration;
import com.evolveum.midpoint.model.api.ModelExecuteOptions;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.match.PolyStringOrigMatchingRule;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.SubstringFilter;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.SchemaConstantsGenerated;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.button.AjaxLinkButton;
import com.evolveum.midpoint.web.component.button.AjaxSubmitLinkButton;
import com.evolveum.midpoint.web.component.button.ButtonType;
import com.evolveum.midpoint.web.component.data.RepositoryObjectDataProvider;
import com.evolveum.midpoint.web.component.data.TablePanel;
import com.evolveum.midpoint.web.component.data.column.ButtonColumn;
import com.evolveum.midpoint.web.component.data.column.CheckBoxHeaderColumn;
import com.evolveum.midpoint.web.component.data.column.LinkColumn;
import com.evolveum.midpoint.web.component.dialog.ConfirmationDialog;
import com.evolveum.midpoint.web.component.option.OptionContent;
import com.evolveum.midpoint.web.component.option.OptionItem;
import com.evolveum.midpoint.web.component.option.OptionPanel;
import com.evolveum.midpoint.web.component.util.LoadableModel;
import com.evolveum.midpoint.web.page.PageBase;
import com.evolveum.midpoint.web.page.admin.configuration.component.PageDebugDownloadBehaviour;
import com.evolveum.midpoint.web.page.admin.configuration.dto.DebugObjectItem;
import com.evolveum.midpoint.web.security.MidPointApplication;
import com.evolveum.midpoint.web.security.WebApplicationConfiguration;
import com.evolveum.midpoint.web.session.ConfigurationStorage;
import com.evolveum.midpoint.web.util.WebMiscUtil;
import com.evolveum.midpoint.xml.ns._public.common.common_2a.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_2a.ShadowType;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.file.File;
import org.apache.wicket.util.file.Files;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author lazyman
* @author mserbak
*/
public class PageDebugList extends PageAdminConfiguration {
private static final Trace LOGGER = TraceManager.getTrace(PageDebugList.class);
private static final String DOT_CLASS = PageDebugList.class.getName() + ".";
private static final String OPERATION_DELETE_OBJECT = DOT_CLASS + "deleteObject";
private static final String OPERATION_DELETE_OBJECTS = DOT_CLASS + "deleteObjects";
private static final String ID_CONFIRM_DELETE_POPUP = "confirmDeletePopup";
private static final String ID_MAIN_FORM = "mainForm";
private static final String ID_ZIP_CHECK = "zipCheck";
private static final String ID_OPTION_CONTENT = "optionContent";
private static final String ID_OPTION = "option";
private static final String ID_SEARCH = "search";
private static final String ID_CATEGORY = "category";
private static final String ID_TABLE = "table";
private static final String ID_CHOICE = "choice";
private static final String ID_DELETE_SELECTED = "deleteSelected";
private static final String ID_EXPORT = "export";
private static final String ID_EXPORT_ALL = "exportAll";
private static final String ID_SEARCH_TEXT = "searchText";
private static final String ID_CLEAR_BUTTON = "clearButton";
private static final String ID_SEARCH_BUTTON = "searchButton";
private boolean deleteSelected; //todo what is this used for?
private IModel<ObjectTypes> choice = null;
private DebugObjectItem object = null; //todo what is this used for?
public PageDebugList() {
initLayout();
}
private void initLayout() {
//confirm delete
add(new ConfirmationDialog(ID_CONFIRM_DELETE_POPUP,
createStringResource("pageDebugList.dialog.title.confirmDelete"), createDeleteConfirmString()) {
@Override
public void yesPerformed(AjaxRequestTarget target) {
close(target);
//todo wtf
if (deleteSelected) {
deleteSelected = false;
deleteSelectedConfirmedPerformed(target);
} else {
deleteObjectConfirmedPerformed(target);
}
}
});
final Form main = new Form(ID_MAIN_FORM);
add(main);
choice = new Model<ObjectTypes>() {
@Override
public ObjectTypes getObject() {
ObjectTypes types = super.getObject();
if (types == null) {
ConfigurationStorage storage = getSessionStorage().getConfiguration();
types = storage.getDebugListCategory();
}
return types;
}
};
OptionPanel option = new OptionPanel(ID_OPTION, createStringResource("pageDebugList.optionsTitle"), false);
option.setOutputMarkupId(true);
main.add(option);
OptionItem item = new OptionItem(ID_SEARCH, createStringResource("pageDebugList.search"));
option.getBodyContainer().add(item);
IModel<String> searchNameModel = initSearch(item);
item = new OptionItem(ID_CATEGORY, createStringResource("pageDebugList.selectType"));
option.getBodyContainer().add(item);
initCategory(item, searchNameModel);
OptionContent content = new OptionContent(ID_OPTION_CONTENT);
main.add(content);
ConfigurationStorage storage = getSessionStorage().getConfiguration();
Class type = storage.getDebugListCategory().getClassDefinition();
addOrReplaceTable(new RepositoryObjectDataProvider(this, type));
initButtonBar(main);
}
private void initButtonBar(Form main) {
AjaxLinkButton delete = new AjaxLinkButton(ID_DELETE_SELECTED, ButtonType.NEGATIVE,
createStringResource("pageDebugList.button.deleteSelected")) {
@Override
public void onClick(AjaxRequestTarget target) {
deleteSelectedPerformed(target, choice);
}
};
main.add(delete);
final PageDebugDownloadBehaviour ajaxDownloadBehavior = new PageDebugDownloadBehaviour();
main.add(ajaxDownloadBehavior);
AjaxLinkButton export = new AjaxLinkButton(ID_EXPORT,
createStringResource("pageDebugList.button.export")) {
@Override
public void onClick(AjaxRequestTarget target) {
initDownload(ajaxDownloadBehavior, target, false);
}
};
main.add(export);
AjaxLinkButton exportAll = new AjaxLinkButton(ID_EXPORT_ALL,
createStringResource("pageDebugList.button.exportAll")) {
@Override
public void onClick(AjaxRequestTarget target) {
initDownload(ajaxDownloadBehavior, target, true);
}
};
main.add(exportAll);
AjaxCheckBox zipCheck = new AjaxCheckBox(ID_ZIP_CHECK, new Model<Boolean>(false)) {
@Override
protected void onUpdate(AjaxRequestTarget target) {
}
};
main.add(zipCheck);
}
private void initDownload(PageDebugDownloadBehaviour downloadBehaviour, AjaxRequestTarget target, boolean all) {
Class<? extends ObjectType> type = all ? ObjectType.class : getExportType();
downloadBehaviour.setType(type);
downloadBehaviour.setQuery(createExportQuery());
downloadBehaviour.setUseZip(hasToZip());
downloadBehaviour.initiate(target);
}
private Class<? extends ObjectType> getExportType() {
Class type = getTableDataProvider().getType();
return type == null ? ObjectType.class : type;
}
private ObjectQuery createExportQuery() {
ObjectQuery query = getTableDataProvider().getQuery();
ObjectQuery clonedQuery = null;
if (query != null) {
clonedQuery = new ObjectQuery();
clonedQuery.setFilter(query.getFilter());
}
return clonedQuery;
}
private void addOrReplaceTable(RepositoryObjectDataProvider provider) {
OptionContent content = (OptionContent) get(createComponentPath(ID_MAIN_FORM, ID_OPTION_CONTENT));
TablePanel table = new TablePanel(ID_TABLE, provider, initColumns(provider.getType()));
table.setOutputMarkupId(true);
content.getBodyContainer().addOrReplace(table);
}
private List<IColumn> initColumns(final Class<? extends ObjectType> type) {
List<IColumn> columns = new ArrayList<IColumn>();
IColumn column = new CheckBoxHeaderColumn<ObjectType>();
columns.add(column);
column = new LinkColumn<DebugObjectItem>(createStringResource("pageDebugList.name"),
DebugObjectItem.F_NAME, DebugObjectItem.F_NAME) {
@Override
public void onClick(AjaxRequestTarget target, IModel<DebugObjectItem> rowModel) {
DebugObjectItem object = rowModel.getObject();
objectEditPerformed(target, object.getOid(), type);
}
};
columns.add(column);
if (ShadowType.class.isAssignableFrom(type)) {
columns.add(new PropertyColumn(createStringResource("pageDebugList.resourceName"),
DebugObjectItem.F_RESOURCE_NAME));
columns.add(new PropertyColumn(createStringResource("pageDebugList.resourceType"),
DebugObjectItem.F_RESOURCE_TYPE));
}
column = new ButtonColumn<DebugObjectItem>(createStringResource("pageDebugList.operation"),
createStringResource("pageDebugList.button.delete")) {
@Override
public void onClick(AjaxRequestTarget target, IModel<DebugObjectItem> rowModel) {
DebugObjectItem object = rowModel.getObject();
deleteObjectPerformed(target, choice, object);
}
};
columns.add(column);
return columns;
}
private boolean hasToZip() {
AjaxCheckBox zipCheck = (AjaxCheckBox) get(createComponentPath(ID_MAIN_FORM, ID_ZIP_CHECK));
return zipCheck.getModelObject();
}
private IModel<String> initSearch(OptionItem item) {
final IModel<String> model = new Model<String>();
TextField<String> search = new TextField<String>(ID_SEARCH_TEXT, model);
item.add(search);
AjaxSubmitLinkButton clearButton = new AjaxSubmitLinkButton(ID_CLEAR_BUTTON,
new StringResourceModel("pageDebugList.button.clear", this, null)) {
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
PageBase page = (PageBase) getPage();
target.add(page.getFeedbackPanel());
}
@Override
public void onSubmit(AjaxRequestTarget target, Form<?> form) {
model.setObject(null);
target.appendJavaScript("init()");
target.add(PageDebugList.this.get(createComponentPath(ID_MAIN_FORM, ID_OPTION)));
listObjectsPerformed(target, model.getObject(), null);
}
};
item.add(clearButton);
AjaxSubmitLinkButton searchButton = new AjaxSubmitLinkButton(ID_SEARCH_BUTTON,
new StringResourceModel("pageDebugList.button.search", this, null)) {
@Override
protected void onError(AjaxRequestTarget target, Form<?> form) {
PageBase page = (PageBase) getPage();
target.add(page.getFeedbackPanel());
}
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
listObjectsPerformed(target, model.getObject(), null);
}
};
item.add(searchButton);
return model;
}
private void initCategory(OptionItem item, final IModel<String> searchNameModel) {
IChoiceRenderer<ObjectTypes> renderer = new IChoiceRenderer<ObjectTypes>() {
@Override
public Object getDisplayValue(ObjectTypes object) {
return new StringResourceModel(object.getLocalizationKey(), PageDebugList.this, null).getString();
}
@Override
public String getIdValue(ObjectTypes object, int index) {
return object.getClassDefinition().getSimpleName();
}
};
IModel<List<ObjectTypes>> choiceModel = createChoiceModel(renderer);
final ListChoice listChoice = new ListChoice(ID_CHOICE, choice, choiceModel, renderer, choiceModel.getObject().size()) {
@Override
protected CharSequence getDefaultChoice(String selectedValue) {
return "";
}
};
listChoice.add(new OnChangeAjaxBehavior() {
@Override
protected void onUpdate(AjaxRequestTarget target) {
target.add(listChoice);
listObjectsPerformed(target, searchNameModel.getObject(), choice.getObject());
}
});
item.getBodyContainer().add(listChoice);
}
private IModel<List<ObjectTypes>> createChoiceModel(final IChoiceRenderer<ObjectTypes> renderer) {
return new LoadableModel<List<ObjectTypes>>(false) {
@Override
protected List<ObjectTypes> load() {
List<ObjectTypes> choices = new ArrayList<ObjectTypes>();
Collections.addAll(choices, ObjectTypes.values());
choices.remove(ObjectTypes.OBJECT);
Collections.sort(choices, new Comparator<ObjectTypes>() {
@Override
public int compare(ObjectTypes o1, ObjectTypes o2) {
String str1 = (String) renderer.getDisplayValue(o1);
String str2 = (String) renderer.getDisplayValue(o2);
return String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
}
});
return choices;
}
};
}
private TablePanel getListTable() {
OptionContent content = (OptionContent) get(createComponentPath(ID_MAIN_FORM, ID_OPTION_CONTENT));
return (TablePanel) content.getBodyContainer().get(ID_TABLE);
}
private void listObjectsPerformed(AjaxRequestTarget target, String nameText, ObjectTypes selected) {
RepositoryObjectDataProvider provider = getTableDataProvider();
if (StringUtils.isNotEmpty(nameText)) {
try {
ObjectFilter substring = SubstringFilter.createSubstring(ObjectType.class, getPrismContext(),
ObjectType.F_NAME, PolyStringOrigMatchingRule.NAME.getLocalPart(), nameText);
ObjectQuery query = new ObjectQuery();
query.setFilter(substring);
provider.setQuery(query);
} catch (Exception ex) {
LoggingUtils.logException(LOGGER, "Couldn't create substring filter", ex);
error(getString("pageDebugList.message.queryException", ex.getMessage()));
target.add(getFeedbackPanel());
}
} else {
provider.setQuery(null);
}
if (selected != null) {
provider.setType(selected.getClassDefinition());
addOrReplaceTable(provider);
}
TablePanel table = getListTable();
target.add(table);
}
private void objectEditPerformed(AjaxRequestTarget target, String oid, Class<? extends ObjectType> type) {
PageParameters parameters = new PageParameters();
parameters.add(PageDebugView.PARAM_OBJECT_ID, oid);
parameters.add(PageDebugView.PARAM_OBJECT_TYPE, type.getSimpleName());
setResponsePage(PageDebugView.class, parameters);
}
private RepositoryObjectDataProvider getTableDataProvider() {
TablePanel tablePanel = getListTable();
DataTable table = tablePanel.getDataTable();
return (RepositoryObjectDataProvider) table.getDataProvider();
}
private IModel<String> createDeleteConfirmString() {
return new AbstractReadOnlyModel<String>() {
@Override
public String getObject() {
if (deleteSelected) {
List<DebugObjectItem> selectedList = WebMiscUtil
.getSelectedData(getListTable());
if (selectedList.size() > 1) {
return createStringResource("pageDebugList.message.deleteSelectedConfirm",
selectedList.size()).getString();
}
DebugObjectItem selectedItem = selectedList.get(0);
return createStringResource("pageDebugList.message.deleteObjectConfirm",
selectedItem.getName()).getString();
}
return createStringResource("pageDebugList.message.deleteObjectConfirm", object.getName())
.getString();
}
};
}
private void deleteSelectedConfirmedPerformed(AjaxRequestTarget target) {
ObjectTypes type = choice.getObject();
OperationResult result = new OperationResult(OPERATION_DELETE_OBJECTS);
List<DebugObjectItem> beans = WebMiscUtil.getSelectedData(getListTable());
for (DebugObjectItem bean : beans) {
OperationResult subResult = result.createSubresult(OPERATION_DELETE_OBJECT);
try {
ObjectDelta delta = ObjectDelta.createDeleteDelta(type.getClassDefinition(), bean.getOid(), getPrismContext());
getModelService().executeChanges(WebMiscUtil.createDeltaCollection(delta),
ModelExecuteOptions.createRaw(),
createSimpleTask(OPERATION_DELETE_OBJECT), subResult);
subResult.recordSuccess();
} catch (Exception ex) {
subResult.recordFatalError("Couldn't delete objects.", ex);
LoggingUtils.logException(LOGGER, "Couldn't delete objects", ex);
}
}
result.recomputeStatus();
RepositoryObjectDataProvider provider = getTableDataProvider();
provider.clearCache();
showResult(result);
target.add(getListTable());
target.add(getFeedbackPanel());
}
private void deleteObjectConfirmedPerformed(AjaxRequestTarget target) {
OperationResult result = new OperationResult(OPERATION_DELETE_OBJECT);
try {
ObjectTypes type = choice.getObject();
ObjectDelta delta = ObjectDelta.createDeleteDelta(type.getClassDefinition(), object.getOid(), getPrismContext());
getModelService().executeChanges(WebMiscUtil.createDeltaCollection(delta),
ModelExecuteOptions.createRaw(),
createSimpleTask(OPERATION_DELETE_OBJECT), result);
result.recordSuccess();
} catch (Exception ex) {
result.recordFatalError("Couldn't delete object '" + object.getName() + "'.", ex);
}
RepositoryObjectDataProvider provider = getTableDataProvider();
provider.clearCache();
showResult(result);
target.add(getListTable());
target.add(getFeedbackPanel());
}
private void deleteSelectedPerformed(AjaxRequestTarget target, IModel<ObjectTypes> choice) {
List<DebugObjectItem> selected = WebMiscUtil.getSelectedData(getListTable());
if (selected.isEmpty()) {
warn(getString("pageDebugList.message.nothingSelected"));
target.add(getFeedbackPanel());
return;
}
ModalWindow dialog = (ModalWindow) get(ID_CONFIRM_DELETE_POPUP);
deleteSelected = true;
this.choice = choice;
dialog.show(target);
}
private void deleteObjectPerformed(AjaxRequestTarget target, IModel<ObjectTypes> choice, DebugObjectItem object) {
ModalWindow dialog = (ModalWindow) get(ID_CONFIRM_DELETE_POPUP);
this.choice = choice;
this.object = object;
dialog.show(target);
}
}
|
fix for MID-1458
|
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageDebugList.java
|
fix for MID-1458
|
|
Java
|
apache-2.0
|
5c1c16dfc29a7e87d235eb36ca542f8f2e758720
| 0
|
Cognifide/knotx,Cognifide/knotx
|
/*
* Knot.x - Reactive microservice assembler - View Knot
*
* Copyright (C) 2016 Cognifide Limited
*
* 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.cognifide.knotx.knot.view.service;
import com.cognifide.knotx.dataobjects.ClientResponse;
import com.cognifide.knotx.dataobjects.KnotContext;
import com.cognifide.knotx.knot.view.ViewKnotConfiguration;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.rxjava.core.buffer.Buffer;
import io.vertx.rxjava.core.eventbus.EventBus;
import io.vertx.rxjava.core.eventbus.Message;
import rx.Observable;
public class ServiceEngine {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceEngine.class);
private static final String RESULT_NAMESPACE_KEY = "_result";
private static final String RESPONSE_NAMESPACE_KEY = "_response";
private final ViewKnotConfiguration configuration;
private final EventBus eventBus;
public ServiceEngine(EventBus eventBus, ViewKnotConfiguration serviceConfiguration) {
this.eventBus = eventBus;
this.configuration = serviceConfiguration;
}
public Observable<JsonObject> doServiceCall(ServiceEntry serviceEntry,
KnotContext knotContext) {
JsonObject serviceMessage = new JsonObject();
serviceMessage.put("clientRequest", knotContext.clientRequest().toJson());
serviceMessage.put("params", serviceEntry.getParams());
return eventBus.<JsonObject>sendObservable(serviceEntry.getAddress(), serviceMessage)
.compose(transformResponse());
}
private Observable.Transformer<Message<JsonObject>, JsonObject> transformResponse() {
return messageObs -> messageObs.map(msg -> new ClientResponse(msg.body()))
.map(this::buildResultObject);
}
public ServiceEntry mergeWithConfiguration(final ServiceEntry serviceEntry) {
return configuration.getServices().stream()
.filter(service -> serviceEntry.getName().matches(service.getName()))
.findFirst().map(metadata ->
serviceEntry.setAddress(metadata.getAddress())
.mergeParams(metadata.getParams())
.overrideCacheKey(metadata.getCacheKey())
)
.get();
}
private JsonObject buildResultObject(ClientResponse response) {
JsonObject object = new JsonObject();
String rawData = response.body().toString().trim();
if (rawData.charAt(0) == '[') {
object.put(RESULT_NAMESPACE_KEY, new JsonArray(rawData));
} else if (rawData.charAt(0) == '{') {
object.put(RESULT_NAMESPACE_KEY, new JsonObject(rawData));
} else {
throw new DecodeException("Result is neither Json Array nor Json Object");
}
object.put(RESPONSE_NAMESPACE_KEY, new JsonObject().put("statusCode", response.statusCode().codeAsText()));
return object;
}
}
|
knotx-core/knotx-knot-view/src/main/java/com/cognifide/knotx/knot/view/service/ServiceEngine.java
|
/*
* Knot.x - Reactive microservice assembler - View Knot
*
* Copyright (C) 2016 Cognifide Limited
*
* 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.cognifide.knotx.knot.view.service;
import com.cognifide.knotx.dataobjects.ClientResponse;
import com.cognifide.knotx.dataobjects.KnotContext;
import com.cognifide.knotx.knot.view.ViewKnotConfiguration;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.rxjava.core.eventbus.EventBus;
import io.vertx.rxjava.core.eventbus.Message;
import rx.Observable;
public class ServiceEngine {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceEngine.class);
private static final String RESULT_NAMESPACE_KEY = "_result";
private static final String RESPONSE_NAMESPACE_KEY = "_response";
private final ViewKnotConfiguration configuration;
private final EventBus eventBus;
public ServiceEngine(EventBus eventBus, ViewKnotConfiguration serviceConfiguration) {
this.eventBus = eventBus;
this.configuration = serviceConfiguration;
}
public Observable<JsonObject> doServiceCall(ServiceEntry serviceEntry,
KnotContext knotContext) {
JsonObject serviceMessage = new JsonObject();
serviceMessage.put("clientRequest", knotContext.clientRequest().toJson());
serviceMessage.put("params", serviceEntry.getParams());
return eventBus.<JsonObject>sendObservable(serviceEntry.getAddress(), serviceMessage)
.compose(transformResponse());
}
private Observable.Transformer<Message<JsonObject>, JsonObject> transformResponse() {
return messageObs -> messageObs.map(msg -> new ClientResponse(msg.body()))
.map(this::buildResultObject);
}
public ServiceEntry mergeWithConfiguration(final ServiceEntry serviceEntry) {
return configuration.getServices().stream()
.filter(service -> serviceEntry.getName().matches(service.getName()))
.findFirst().map(metadata ->
serviceEntry.setAddress(metadata.getAddress())
.mergeParams(metadata.getParams())
.overrideCacheKey(metadata.getCacheKey())
)
.get();
}
private JsonObject buildResultObject(ClientResponse response) {
JsonObject object = new JsonObject();
String rawData = response.body().toString().trim();
if (rawData.charAt(0) == '[') {
object.put(RESULT_NAMESPACE_KEY, new JsonArray(rawData));
} else if (rawData.charAt(0) == '{') {
object.put(RESULT_NAMESPACE_KEY, response.toJson());
} else {
throw new DecodeException("Result is neither Json Array nor Json Object");
}
object.put(RESPONSE_NAMESPACE_KEY, new JsonObject().put("statusCode", response.statusCode().codeAsText()));
return object;
}
}
|
Fixed getting results from service as array or object
|
knotx-core/knotx-knot-view/src/main/java/com/cognifide/knotx/knot/view/service/ServiceEngine.java
|
Fixed getting results from service as array or object
|
|
Java
|
apache-2.0
|
9825343949d5c2f835d14601c27645ad145d870d
| 0
|
songeunwoo/ngrinder,nanpa83/ngrinder,chengaomin/ngrinder,chengaomin/ngrinder,songeunwoo/ngrinder,GwonGisoo/ngrinder,bwahn/ngrinder,bwahn/ngrinder,chengaomin/ngrinder,SRCB-CloudPart/ngrinder,naver/ngrinder,SRCB-CloudPart/ngrinder,ropik/ngrinder,songeunwoo/ngrinder,nanpa83/ngrinder,bwahn/ngrinder,naver/ngrinder,nanpa83/ngrinder,SRCB-CloudPart/ngrinder,GwonGisoo/ngrinder,GwonGisoo/ngrinder,SRCB-CloudPart/ngrinder,nanpa83/ngrinder,ropik/ngrinder,SRCB-CloudPart/ngrinder,songeunwoo/ngrinder,ropik/ngrinder,bwahn/ngrinder,bwahn/ngrinder,chengaomin/ngrinder,naver/ngrinder,songeunwoo/ngrinder,GwonGisoo/ngrinder,naver/ngrinder,chengaomin/ngrinder,nanpa83/ngrinder,ropik/ngrinder,naver/ngrinder,GwonGisoo/ngrinder
|
/*
* 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.ngrinder.operation.cotroller;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.Iterator;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.ngrinder.agent.service.AgentManagerService;
import org.ngrinder.common.controller.NGrinderBaseController;
import org.ngrinder.infra.annotation.RuntimeOnlyController;
import org.ngrinder.infra.plugin.PluginManager;
import org.ngrinder.perftest.service.AgentManager;
import org.ngrinder.perftest.service.ConsoleManager;
import org.ngrinder.perftest.service.PerfTestService;
import org.ngrinder.perftest.service.TagService;
import org.ngrinder.region.service.RegionService;
import org.ngrinder.script.service.FileEntryService;
import org.ngrinder.user.service.UserService;
import org.python.util.PythonInterpreter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Script Runner for maintenance.
*
* This class has the jython instance and put the most important class instances as variable in the
* jython. Admin and super user can run any jython code to print out or modify the internal ngrinder
* status.
*
* @author JunHo Yoon
* @since 3.0
*/
@RuntimeOnlyController
@RequestMapping("/operation/scriptConsole")
@PreAuthorize("hasAnyRole('A')")
public class ScriptConsoleController extends NGrinderBaseController implements ApplicationContextAware {
private static final int SCRIPT_CONSOLE_PYTHON_EXPIRE_TIMEOUT = 30000;
private ApplicationContext applicationContext;
@Autowired
private AgentManager agentManager;
@Autowired
private AgentManagerService agentManagerService;
@Autowired
private ConsoleManager consoleManager;
@Autowired
private PerfTestService perfTestService;
@Autowired
private FileEntryService fileEntryService;
@Autowired
private UserService userService;
@Autowired
private RegionService regionService;
@Autowired
private PluginManager pluginManager;
@Autowired
private TagService tagService;
@Autowired
private CacheManager cacheManager;
private PythonInterpreter interp;
/**
* Initialize Jython and puts several managers and services into jython context.
*/
@PostConstruct
public void init() {
Iterator<MemoryPoolMXBean> iter = ManagementFactory.getMemoryPoolMXBeans().iterator();
MemoryUsage usage = null;
while (iter.hasNext()) {
MemoryPoolMXBean item = (MemoryPoolMXBean) iter.next();
if (item.getName().contains("Perm Gen")) {
usage = item.getUsage();
}
}
File jythonCache = new File(FileUtils.getTempDirectory(), "jython");
jythonCache.mkdirs();
System.setProperty("python.cachedir", jythonCache.getAbsolutePath());
if (usage != null && isPermGenMemoryEnough(usage)) {
interp = new PythonInterpreter();
intVars(interp);
}
}
@PreDestroy
public void destroy() {
if (interp != null) {
interp.cleanup();
}
}
private boolean isPermGenMemoryEnough(MemoryUsage usage) {
return (usage.getMax() - usage.getUsed()) > 50000000;
}
protected void intVars(PythonInterpreter interp) {
interp.set("applicationContext", this.applicationContext);
interp.set("agentManager", this.agentManager);
interp.set("agentManagerService", this.agentManagerService);
interp.set("regionService", this.regionService);
interp.set("consoleManager", this.consoleManager);
interp.set("userService", this.userService);
interp.set("perfTestService", this.perfTestService);
interp.set("tagService", this.tagService);
interp.set("fileEntryService", this.fileEntryService);
interp.set("config", getConfig());
interp.set("pluginManager", this.pluginManager);
interp.set("cacheManager", this.cacheManager);
}
/**
* Run script. The run result is stored in "result" of the given model.
*
* @param script
* script
* @param model
* model
* @return "operation/scriptConsole"
*/
@RequestMapping("")
public String runScript(@RequestParam(value = "script", required = false) String script, Model model) {
if (interp == null) {
model.addAttribute("script", script);
model.addAttribute("result", "Scrpt Console is disabled due to memory config."
+ " Please set up Perm Gen memory more than 200M");
} else if (StringUtils.isNotBlank(script)) {
String result = processPython(script);
model.addAttribute("script", script);
model.addAttribute("result", result);
}
return "operation/scriptConsole";
}
/**
* Run python script.
*
* @param script
* script
* @return result printed in stdout and err
*/
public String processPython(final String script) {
try {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
synchronized (interp) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
interp.cleanup();
interp.setOut(bos);
interp.setErr(bos);
interp.exec(script);
interp.cleanup();
}
});
thread.start();
thread.join(SCRIPT_CONSOLE_PYTHON_EXPIRE_TIMEOUT);
if (thread.isAlive()) {
thread.interrupt();
}
}
return bos.toString();
} catch (Exception e) {
String message = ExceptionUtils.getMessage(e);
message = message + "\n" + ExceptionUtils.getStackTrace(e);
return message;
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
|
ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/ScriptConsoleController.java
|
/*
* 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.ngrinder.operation.cotroller;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.Iterator;
import javax.annotation.PostConstruct;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.ngrinder.agent.service.AgentManagerService;
import org.ngrinder.common.controller.NGrinderBaseController;
import org.ngrinder.infra.annotation.RuntimeOnlyController;
import org.ngrinder.infra.plugin.PluginManager;
import org.ngrinder.perftest.service.AgentManager;
import org.ngrinder.perftest.service.ConsoleManager;
import org.ngrinder.perftest.service.PerfTestService;
import org.ngrinder.perftest.service.TagService;
import org.ngrinder.region.service.RegionService;
import org.ngrinder.script.service.FileEntryService;
import org.ngrinder.user.service.UserService;
import org.python.util.PythonInterpreter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Script Runner for maintenance.
*
* This class has the jython instance and put the most important class instances as variable in the
* jython. Admin and super user can run any jython code to print out or modify the internal ngrinder
* status.
*
* @author JunHo Yoon
* @since 3.0
*/
@RuntimeOnlyController
@RequestMapping("/operation/scriptConsole")
@PreAuthorize("hasAnyRole('A')")
public class ScriptConsoleController extends NGrinderBaseController implements ApplicationContextAware {
private static final int SCRIPT_CONSOLE_PYTHON_EXPIRE_TIMEOUT = 30000;
private ApplicationContext applicationContext;
@Autowired
private AgentManager agentManager;
@Autowired
private AgentManagerService agentManagerService;
@Autowired
private ConsoleManager consoleManager;
@Autowired
private PerfTestService perfTestService;
@Autowired
private FileEntryService fileEntryService;
@Autowired
private UserService userService;
@Autowired
private RegionService regionService;
@Autowired
private PluginManager pluginManager;
@Autowired
private TagService tagService;
@Autowired
private CacheManager cacheManager;
private PythonInterpreter interp;
/**
* Initialize Jython and puts several managers and services into jython context.
*/
@PostConstruct
public void init() {
Iterator<MemoryPoolMXBean> iter = ManagementFactory.getMemoryPoolMXBeans().iterator();
MemoryUsage usage = null;
while (iter.hasNext()) {
MemoryPoolMXBean item = (MemoryPoolMXBean) iter.next();
if (item.getName().contains("Perm Gen")) {
usage = item.getUsage();
}
}
File jythonCache = new File(FileUtils.getTempDirectory(), "jython");
jythonCache.mkdirs();
System.setProperty("python.cachedir", jythonCache.getAbsolutePath());
if (usage != null && isPermGenMemoryEnough(usage)) {
interp = new PythonInterpreter();
intVars(interp);
}
}
private boolean isPermGenMemoryEnough(MemoryUsage usage) {
return (usage.getMax() - usage.getUsed()) > 50000000;
}
protected void intVars(PythonInterpreter interp) {
interp.set("applicationContext", this.applicationContext);
interp.set("agentManager", this.agentManager);
interp.set("agentManagerService", this.agentManagerService);
interp.set("regionService", this.regionService);
interp.set("consoleManager", this.consoleManager);
interp.set("userService", this.userService);
interp.set("perfTestService", this.perfTestService);
interp.set("tagService", this.tagService);
interp.set("fileEntryService", this.fileEntryService);
interp.set("config", getConfig());
interp.set("pluginManager", this.pluginManager);
interp.set("cacheManager", this.cacheManager);
}
/**
* Run script. The run result is stored in "result" of the given model.
*
* @param script
* script
* @param model
* model
* @return "operation/scriptConsole"
*/
@RequestMapping("")
public String runScript(@RequestParam(value = "script", required = false) String script, Model model) {
if (interp == null) {
model.addAttribute("script", script);
model.addAttribute("result", "Scrpt Console is disabled due to memory config."
+ " Please set up Perm Gen memory more than 200M");
} else if (StringUtils.isNotBlank(script)) {
String result = processPython(script);
model.addAttribute("script", script);
model.addAttribute("result", result);
}
return "operation/scriptConsole";
}
/**
* Run python script.
*
* @param script
* script
* @return result printed in stdout and err
*/
public String processPython(final String script) {
try {
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
synchronized (interp) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
interp.cleanup();
interp.setOut(bos);
interp.setErr(bos);
interp.exec(script);
interp.cleanup();
}
});
thread.start();
thread.join(SCRIPT_CONSOLE_PYTHON_EXPIRE_TIMEOUT);
if (thread.isAlive()) {
thread.interrupt();
}
}
return bos.toString();
} catch (Exception e) {
String message = ExceptionUtils.getMessage(e);
message = message + "\n" + ExceptionUtils.getStackTrace(e);
return message;
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
|
[NGRINDER-517] Clean up script console when bean destroy is called.
|
ngrinder-controller/src/main/java/org/ngrinder/operation/cotroller/ScriptConsoleController.java
|
[NGRINDER-517] Clean up script console when bean destroy is called.
|
|
Java
|
apache-2.0
|
13ecc52061619f82aceb3eccda14f96156f4c49e
| 0
|
tetrapods/core,tetrapods/core,tetrapods/core,tetrapods/core,tetrapods/core
|
package io.tetrapod.core.web;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.ReferenceCountUtil;
import io.tetrapod.core.*;
import io.tetrapod.core.json.JSONObject;
import io.tetrapod.protocol.core.RequestHeader;
import java.io.*;
import java.util.Map;
import org.slf4j.*;
import com.codahale.metrics.Timer;
import com.codahale.metrics.Timer.Context;
public class WebSocketSession extends WebHttpSession {
private static final Logger logger = LoggerFactory.getLogger(WebSocketSession.class);
private final String wsLocation;
public static final Timer requestTimes = Metrics.timer(Dispatcher.class, "web", "requests", "time");
private WebSocketServerHandshaker handshaker;
public WebSocketSession(SocketChannel ch, Session.Helper helper, Map<String, WebRoot> contentRootMap, String wsLocation) {
super(ch, helper, contentRootMap);
this.wsLocation = wsLocation;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FullHttpRequest) {
handleHttpRequest(ctx, (FullHttpRequest) msg);
} else if (msg instanceof WebSocketFrame) {
handleWebSocketFrame(ctx, (WebSocketFrame) msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
protected void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
logger.debug("### REQUEST = {} : {}", ctx.channel().remoteAddress(), req.getUri());
final long now = System.currentTimeMillis();
final Context context = requestTimes.time();
if (wsLocation.equals(req.getUri())) {
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(wsLocation, null, false);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
} else {
super.handleHttpRequest(ctx, req);
}
context.stop();
logger.debug(String.format(" REQUEST = %s : %s - DONE in %d ms",
ctx.channel().remoteAddress(), req.getUri(), (System.currentTimeMillis() - now)));
}
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
// Check for closing frame
if (frame instanceof CloseWebSocketFrame) {
//handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
ctx.channel().close();
return;
}
if (frame instanceof PingWebSocketFrame) {
ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
return;
}
if (!(frame instanceof TextWebSocketFrame)) {
throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
}
String request = ((TextWebSocketFrame) frame).text();
ReferenceCountUtil.release(frame);
try {
JSONObject jo = new JSONObject(request);
WebContext webContext = new WebContext(jo);
RequestHeader header = webContext.makeRequestHeader(this, relayHandler.getWebRoutes());
readRequest(header, webContext);
return;
} catch (IOException e) {
logger.error("error processing websocket request", e);
ctx.channel().writeAndFlush(new TextWebSocketFrame("Illegal request: " + request));
}
}
@Override
protected Object makeFrame(JSONObject jo) {
return new TextWebSocketFrame(jo.toString(3));
}
}
|
Tetrapod-Core/src/io/tetrapod/core/web/WebSocketSession.java
|
package io.tetrapod.core.web;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.ReferenceCountUtil;
import io.tetrapod.core.*;
import io.tetrapod.core.json.JSONObject;
import io.tetrapod.protocol.core.RequestHeader;
import java.io.*;
import java.util.Map;
import org.slf4j.*;
import com.codahale.metrics.Timer;
import com.codahale.metrics.Timer.Context;
public class WebSocketSession extends WebHttpSession {
private static final Logger logger = LoggerFactory.getLogger(WebSocketSession.class);
private final String wsLocation;
public static final Timer requestTimes = Metrics.timer(Dispatcher.class, "web", "requests", "time");
private WebSocketServerHandshaker handshaker;
public WebSocketSession(SocketChannel ch, Session.Helper helper, Map<String, WebRoot> contentRootMap, String wsLocation) {
super(ch, helper, contentRootMap);
this.wsLocation = wsLocation;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof FullHttpRequest) {
handleHttpRequest(ctx, (FullHttpRequest) msg);
} else if (msg instanceof WebSocketFrame) {
handleWebSocketFrame(ctx, (WebSocketFrame) msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
protected void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
logger.debug("### REQUEST = {} : {}", ctx.channel().remoteAddress(), req.getUri());
final Context context = requestTimes.time();
if (wsLocation.equals(req.getUri())) {
// Handshake
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(wsLocation, null, false);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
} else {
super.handleHttpRequest(ctx, req);
}
context.stop();
}
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
// Check for closing frame
if (frame instanceof CloseWebSocketFrame) {
//handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
ctx.channel().close();
return;
}
if (frame instanceof PingWebSocketFrame) {
ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
return;
}
if (!(frame instanceof TextWebSocketFrame)) {
throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
}
String request = ((TextWebSocketFrame) frame).text();
ReferenceCountUtil.release(frame);
try {
JSONObject jo = new JSONObject(request);
WebContext webContext = new WebContext(jo);
RequestHeader header = webContext.makeRequestHeader(this, relayHandler.getWebRoutes());
readRequest(header, webContext);
return;
} catch (IOException e) {
logger.error("error processing websocket request", e);
ctx.channel().writeAndFlush(new TextWebSocketFrame("Illegal request: " + request));
}
}
@Override
protected Object makeFrame(JSONObject jo) {
return new TextWebSocketFrame(jo.toString(3));
}
}
|
MOAR debug loggings
|
Tetrapod-Core/src/io/tetrapod/core/web/WebSocketSession.java
|
MOAR debug loggings
|
|
Java
|
apache-2.0
|
c964668e3df618932b92028e76bc203d03f53164
| 0
|
gladyscarrizales/manifoldcf,kishorejangid/manifoldcf,cogfor/mcf-cogfor,gladyscarrizales/manifoldcf,kishorejangid/manifoldcf,apache/manifoldcf,gladyscarrizales/manifoldcf,cogfor/mcf-cogfor,apache/manifoldcf,kishorejangid/manifoldcf,apache/manifoldcf,kishorejangid/manifoldcf,cogfor/mcf-cogfor,cogfor/mcf-cogfor,apache/manifoldcf,cogfor/mcf-cogfor,gladyscarrizales/manifoldcf,gladyscarrizales/manifoldcf,kishorejangid/manifoldcf,apache/manifoldcf,apache/manifoldcf,cogfor/mcf-cogfor,kishorejangid/manifoldcf,gladyscarrizales/manifoldcf
|
/* $Id$ */
/**
* 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.lcf.core.lockmanager;
import org.apache.lcf.core.interfaces.*;
import org.apache.lcf.core.system.Logging;
import org.apache.lcf.core.system.LCF;
import java.util.*;
import java.io.*;
/** The lock manager manages locks across all threads and JVMs and cluster members. There should be no more than ONE
* instance of this class per thread!!! The factory should enforce this.
*/
public class LockManager implements ILockManager
{
public static final String _rcsid = "@(#)$Id$";
/** Synchronization directory property - local to this implementation of ILockManager */
public static final String synchDirectoryProperty = "org.apache.lcf.synchdirectory";
// These are the lock/section types, in order of escalation
protected final static int TYPE_READ = 1;
protected final static int TYPE_WRITENONEX = 2;
protected final static int TYPE_WRITE = 3;
// These are for locks (which cross JVM boundaries)
protected HashMap localLocks = new HashMap();
protected static LockPool myLocks = new LockPool();
// These are for critical sections (which do not cross JVM boundaries)
protected HashMap localSections = new HashMap();
protected static LockPool mySections = new LockPool();
// This is the directory used for cross-JVM synchronization, or null if off
protected String synchDirectory = null;
public LockManager()
throws LCFException
{
synchDirectory = LCF.getProperty(synchDirectoryProperty);
if (synchDirectory != null)
{
if (!new File(synchDirectory).isDirectory())
throw new LCFException("Property "+synchDirectoryProperty+" must point to an existing, writeable directory!",LCFException.SETUP_ERROR);
}
}
/** Calculate the name of a flag resource.
*@param flagName is the name of the flag.
*@return the name for the flag resource.
*/
protected static String getFlagResourceName(String flagName)
{
return "flag-"+flagName;
}
/** Global flag information. This is used only when all of LCF is run within one process. */
protected static HashMap globalFlags = new HashMap();
/** Raise a flag. Use this method to assert a condition, or send a global signal. The flag will be reset when the
* entire system is restarted.
*@param flagName is the name of the flag to set.
*/
public void setGlobalFlag(String flagName)
throws LCFException
{
if (synchDirectory == null)
{
// Keep local flag information in memory
synchronized (globalFlags)
{
globalFlags.put(flagName,new Boolean(true));
}
}
else
{
String resourceName = getFlagResourceName(flagName);
String path = makeFilePath(resourceName);
(new File(path)).mkdirs();
File f = new File(path,LCF.safeFileName(resourceName));
try
{
f.createNewFile();
}
catch (InterruptedIOException e)
{
throw new LCFException("Interrupted: "+e.getMessage(),e,LCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new LCFException(e.getMessage(),e);
}
}
}
/** Clear a flag. Use this method to clear a condition, or retract a global signal.
*@param flagName is the name of the flag to clear.
*/
public void clearGlobalFlag(String flagName)
throws LCFException
{
if (synchDirectory == null)
{
// Keep flag information in memory
synchronized (globalFlags)
{
globalFlags.remove(flagName);
}
}
else
{
String resourceName = getFlagResourceName(flagName);
File f = new File(makeFilePath(resourceName),LCF.safeFileName(resourceName));
f.delete();
}
}
/** Check the condition of a specified flag.
*@param flagName is the name of the flag to check.
*@return true if the flag is set, false otherwise.
*/
public boolean checkGlobalFlag(String flagName)
throws LCFException
{
if (synchDirectory == null)
{
// Keep flag information in memory
synchronized (globalFlags)
{
return globalFlags.get(flagName) != null;
}
}
else
{
String resourceName = getFlagResourceName(flagName);
File f = new File(makeFilePath(resourceName),LCF.safeFileName(resourceName));
return f.exists();
}
}
/** Global resource data. Used only when LCF is run entirely out of one process. */
protected static HashMap globalData = new HashMap();
/** Read data from a shared data resource. Use this method to read any existing data, or get a null back if there is no such resource.
* Note well that this is not necessarily an atomic operation, and it must thus be protected by a lock.
*@param resourceName is the global name of the resource.
*@return a byte array containing the data, or null.
*/
public byte[] readData(String resourceName)
throws LCFException
{
if (synchDirectory == null)
{
// Keep resource data local
synchronized (globalData)
{
return (byte[])globalData.get(resourceName);
}
}
else
{
File f = new File(makeFilePath(resourceName),LCF.safeFileName(resourceName));
try
{
InputStream is = new FileInputStream(f);
try
{
ByteArrayBuffer bab = new ByteArrayBuffer();
while (true)
{
int x = is.read();
if (x == -1)
break;
bab.add((byte)x);
}
return bab.toArray();
}
finally
{
is.close();
}
}
catch (FileNotFoundException e)
{
return null;
}
catch (InterruptedIOException e)
{
throw new LCFException("Interrupted: "+e.getMessage(),e,LCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new LCFException("IO exception: "+e.getMessage(),e);
}
}
}
/** Write data to a shared data resource. Use this method to write a body of data into a shared resource.
* Note well that this is not necessarily an atomic operation, and it must thus be protected by a lock.
*@param resourceName is the global name of the resource.
*@param data is the byte array containing the data. Pass null if you want to delete the resource completely.
*/
public void writeData(String resourceName, byte[] data)
throws LCFException
{
if (synchDirectory == null)
{
// Keep resource data local
synchronized (globalData)
{
if (data == null)
globalData.remove(resourceName);
else
globalData.put(resourceName,data);
}
}
else
{
try
{
String path = makeFilePath(resourceName);
// Make sure the directory exists
(new File(path)).mkdirs();
File f = new File(path,LCF.safeFileName(resourceName));
if (data == null)
{
f.delete();
return;
}
FileOutputStream os = new FileOutputStream(f);
try
{
os.write(data,0,data.length);
}
finally
{
os.close();
}
}
catch (InterruptedIOException e)
{
throw new LCFException("Interrupted: "+e.getMessage(),e,LCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new LCFException("IO exception: "+e.getMessage(),e);
}
}
}
/** Wait for a time before retrying a lock.
*/
public void timedWait(int time)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Waiting for time "+Integer.toString(time));
}
try
{
LCF.sleep(time);
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
/** Enter a non-exclusive write-locked area (blocking out all readers, but letting in other "writers").
* This kind of lock is designed to be used in conjunction with read locks. It is used typically in
* a situation where the read lock represents a query and the non-exclusive write lock represents a modification
* to an individual item that might affect the query, but where multiple modifications do not individually
* interfere with one another (use of another, standard, write lock per item can guarantee this).
*/
public void enterNonExWriteLock(String lockKey)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering non-ex write lock '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
// See if we already own a write lock for the object
// If we do, there is no reason to change the status of the global lock we own.
if (ll.hasNonExWriteLock() || ll.hasWriteLock())
{
ll.incrementNonExWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
return;
}
// Check for illegalities
if (ll.hasReadLock())
{
throw new LCFException("Illegal lock sequence: NonExWrite lock can't be within read lock",LCFException.GENERAL_ERROR);
}
// We don't own a local non-ex write lock. Get one. The global lock will need
// to know if we already have a a read lock.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.enterNonExWriteLock();
break;
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again to get a valid object
}
}
ll.incrementNonExWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
}
public void enterNonExWriteLockNoWait(String lockKey)
throws LCFException, LockException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering non-ex write lock no wait '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
// See if we already own a write lock for the object
// If we do, there is no reason to change the status of the global lock we own.
if (ll.hasNonExWriteLock() || ll.hasWriteLock())
{
ll.incrementNonExWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
return;
}
// Check for illegalities
if (ll.hasReadLock())
{
throw new LCFException("Illegal lock sequence: NonExWrite lock can't be within read lock",LCFException.GENERAL_ERROR);
}
// We don't own a local non-ex write lock. Get one. The global lock will need
// to know if we already have a a read lock.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
synchronized (lo)
{
lo.enterNonExWriteLockNoWait();
break;
}
}
catch (LocalLockException e)
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug(" Could not non-ex write lock '"+lockKey+"', lock exception");
}
// Throw LockException instead
throw new LockException(e.getMessage());
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again to get a valid object
}
}
ll.incrementNonExWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
}
/** Leave a non-exclusive write lock.
*/
public void leaveNonExWriteLock(String lockKey)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Leaving non-ex write lock '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
ll.decrementNonExWriteLocks();
// See if we no longer have a write lock for the object.
// If we retain the stronger exclusive lock, we still do not need to
// change the status of the global lock.
if (!(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.leaveNonExWriteLock();
break;
}
catch (InterruptedException e)
{
// try one more time
try
{
lo.leaveNonExWriteLock();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (InterruptedException e2)
{
ll.incrementNonExWriteLocks();
throw new LCFException("Interrupted",e2,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e2)
{
ll.incrementNonExWriteLocks();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
catch (ExpiredObjectException e)
{
// Try again to get a valid object
}
}
releaseLocalLock(lockKey);
}
}
/** Enter a write locked area (i.e., block out both readers and other writers)
* NOTE: Can't enter until all readers have left.
*/
public void enterWriteLock(String lockKey)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering write lock '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
// See if we already own the write lock for the object
if (ll.hasWriteLock())
{
ll.incrementWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
return;
}
// Check for illegalities
if (ll.hasReadLock() || ll.hasNonExWriteLock())
{
throw new LCFException("Illegal lock sequence: Write lock can't be within read lock or non-ex write lock",LCFException.GENERAL_ERROR);
}
// We don't own a local write lock. Get one. The global lock will need
// to know if we already have a non-exclusive lock or a read lock, which we don't because
// it's illegal.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.enterWriteLock();
break;
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
}
public void enterWriteLockNoWait(String lockKey)
throws LCFException, LockException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering write lock no wait '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
// See if we already own the write lock for the object
if (ll.hasWriteLock())
{
ll.incrementWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
return;
}
// Check for illegalities
if (ll.hasReadLock() || ll.hasNonExWriteLock())
{
throw new LCFException("Illegal lock sequence: Write lock can't be within read lock or non-ex write lock",LCFException.GENERAL_ERROR);
}
// We don't own a local write lock. Get one. The global lock will need
// to know if we already have a non-exclusive lock or a read lock, which we don't because
// it's illegal.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
synchronized (lo)
{
lo.enterWriteLockNoWait();
break;
}
}
catch (LocalLockException e)
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug(" Could not write lock '"+lockKey+"', lock exception");
}
throw new LockException(e.getMessage());
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
}
public void leaveWriteLock(String lockKey)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Leaving write lock '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
ll.decrementWriteLocks();
if (!ll.hasWriteLock())
{
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.leaveWriteLock();
break;
}
catch (InterruptedException e)
{
// try one more time
try
{
lo.leaveWriteLock();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (InterruptedException e2)
{
ll.incrementWriteLocks();
throw new LCFException("Interrupted",e2,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e2)
{
ll.incrementWriteLocks();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
catch (ExpiredObjectException e)
{
// Try again
}
}
releaseLocalLock(lockKey);
}
}
/** Enter a read-only locked area (i.e., block ONLY if there's a writer)
*/
public void enterReadLock(String lockKey)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering read lock '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
// See if we already own the read lock for the object.
// Write locks or non-ex writelocks count as well (they're stronger).
if (ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock())
{
ll.incrementReadLocks();
Logging.lock.debug(" Successfully obtained lock!");
return;
}
// We don't own a local read lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.enterReadLock();
break;
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementReadLocks();
Logging.lock.debug(" Successfully obtained lock!");
}
public void enterReadLockNoWait(String lockKey)
throws LCFException, LockException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering read lock no wait '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
// See if we already own the read lock for the object.
// Write locks or non-ex writelocks count as well (they're stronger).
if (ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock())
{
ll.incrementReadLocks();
Logging.lock.debug(" Successfully obtained lock!");
return;
}
// We don't own a local read lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
synchronized (lo)
{
lo.enterReadLockNoWait();
break;
}
}
catch (LocalLockException e)
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug(" Could not read lock '"+lockKey+"', lock exception");
}
throw new LockException(e.getMessage());
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementReadLocks();
Logging.lock.debug(" Successfully obtained lock!");
}
public void leaveReadLock(String lockKey)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Leaving read lock '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
ll.decrementReadLocks();
if (!(ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.leaveReadLock();
break;
}
catch (InterruptedException e)
{
// Try one more time
try
{
lo.leaveReadLock();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (InterruptedException e2)
{
ll.incrementReadLocks();
throw new LCFException("Interrupted",e2,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e2)
{
ll.incrementReadLocks();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
catch (ExpiredObjectException e)
{
// Try again
}
}
releaseLocalLock(lockKey);
}
}
public void clearLocks()
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Clearing all locks");
}
Iterator e = localLocks.keySet().iterator();
while (e.hasNext())
{
String keyValue = (String)e.next();
LocalLock ll = (LocalLock)localLocks.get(keyValue);
while (ll.hasWriteLock())
leaveWriteLock(keyValue);
while (ll.hasNonExWriteLock())
leaveNonExWriteLock(keyValue);
while (ll.hasReadLock())
leaveReadLock(keyValue);
}
}
/** Enter multiple locks
*/
public void enterLocks(String[] readLocks, String[] nonExWriteLocks, String[] writeLocks)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering multiple locks:");
int i;
if (readLocks != null)
{
i = 0;
while (i < readLocks.length)
{
Logging.lock.debug(" Read lock '"+readLocks[i++]+"'");
}
}
if (nonExWriteLocks != null)
{
i = 0;
while (i < nonExWriteLocks.length)
{
Logging.lock.debug(" Non-ex write lock '"+nonExWriteLocks[i++]+"'");
}
}
if (writeLocks != null)
{
i = 0;
while (i < writeLocks.length)
{
Logging.lock.debug(" Write lock '"+writeLocks[i++]+"'");
}
}
}
// Sort the locks. This improves the chances of making it through the locking process without
// contention!
LockDescription lds[] = getSortedUniqueLocks(readLocks,nonExWriteLocks,writeLocks);
int locksProcessed = 0;
try
{
while (locksProcessed < lds.length)
{
LockDescription ld = lds[locksProcessed];
int lockType = ld.getType();
String lockKey = ld.getKey();
LocalLock ll;
switch (lockType)
{
case TYPE_WRITE:
ll = getLocalLock(lockKey);
// Check for illegalities
if ((ll.hasReadLock() || ll.hasNonExWriteLock()) && !ll.hasWriteLock())
{
throw new LCFException("Illegal lock sequence: Write lock can't be within read lock or non-ex write lock",LCFException.GENERAL_ERROR);
}
// See if we already own the write lock for the object
if (!ll.hasWriteLock())
{
// We don't own a local write lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.enterWriteLock();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
ll.incrementWriteLocks();
break;
case TYPE_WRITENONEX:
ll = getLocalLock(lockKey);
// Check for illegalities
if (ll.hasReadLock() && !(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
throw new LCFException("Illegal lock sequence: NonExWrite lock can't be within read lock",LCFException.GENERAL_ERROR);
}
// See if we already own the write lock for the object
if (!(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
// We don't own a local write lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.enterNonExWriteLock();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
ll.incrementNonExWriteLocks();
break;
case TYPE_READ:
ll = getLocalLock(lockKey);
if (!(ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
// We don't own a local read lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.enterReadLock();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
ll.incrementReadLocks();
break;
}
locksProcessed++;
}
// Got all; we are done!
Logging.lock.debug(" Successfully obtained multiple locks!");
return;
}
catch (Throwable ex)
{
// No matter what, undo the locks we've taken
LCFException ae = null;
int errno = 0;
while (--locksProcessed >= 0)
{
LockDescription ld = lds[locksProcessed];
int lockType = ld.getType();
String lockKey = ld.getKey();
try
{
switch (lockType)
{
case TYPE_READ:
leaveReadLock(lockKey);
break;
case TYPE_WRITENONEX:
leaveNonExWriteLock(lockKey);
break;
case TYPE_WRITE:
leaveWriteLock(lockKey);
break;
}
}
catch (LCFException e)
{
ae = e;
}
}
if (ae != null)
{
throw ae;
}
if (ex instanceof LCFException)
{
throw (LCFException)ex;
}
if (ex instanceof InterruptedException)
{
// It's InterruptedException
throw new LCFException("Interrupted",ex,LCFException.INTERRUPTED);
}
if (!(ex instanceof Error))
{
throw new Error("Unexpected exception",ex);
}
throw (Error)ex;
}
}
public void enterLocksNoWait(String[] readLocks, String[] nonExWriteLocks, String[] writeLocks)
throws LCFException, LockException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering multiple locks no wait:");
int i;
if (readLocks != null)
{
i = 0;
while (i < readLocks.length)
{
Logging.lock.debug(" Read lock '"+readLocks[i++]+"'");
}
}
if (nonExWriteLocks != null)
{
i = 0;
while (i < nonExWriteLocks.length)
{
Logging.lock.debug(" Non-ex write lock '"+nonExWriteLocks[i++]+"'");
}
}
if (writeLocks != null)
{
i = 0;
while (i < writeLocks.length)
{
Logging.lock.debug(" Write lock '"+writeLocks[i++]+"'");
}
}
}
// Sort the locks. This improves the chances of making it through the locking process without
// contention!
LockDescription lds[] = getSortedUniqueLocks(readLocks,nonExWriteLocks,writeLocks);
int locksProcessed = 0;
try
{
while (locksProcessed < lds.length)
{
LockDescription ld = lds[locksProcessed];
int lockType = ld.getType();
String lockKey = ld.getKey();
LocalLock ll;
switch (lockType)
{
case TYPE_WRITE:
ll = getLocalLock(lockKey);
// Check for illegalities
if ((ll.hasReadLock() || ll.hasNonExWriteLock()) && !ll.hasWriteLock())
{
throw new LCFException("Illegal lock sequence: Write lock can't be within read lock or non-ex write lock",LCFException.GENERAL_ERROR);
}
// See if we already own the write lock for the object
if (!ll.hasWriteLock())
{
// We don't own a local write lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
synchronized (lo)
{
try
{
lo.enterWriteLockNoWait();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
}
ll.incrementWriteLocks();
break;
case TYPE_WRITENONEX:
ll = getLocalLock(lockKey);
// Check for illegalities
if (ll.hasReadLock() && !(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
throw new LCFException("Illegal lock sequence: NonExWrite lock can't be within read lock",LCFException.GENERAL_ERROR);
}
// See if we already own the write lock for the object
if (!(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
// We don't own a local write lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
synchronized (lo)
{
try
{
lo.enterNonExWriteLockNoWait();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
}
ll.incrementNonExWriteLocks();
break;
case TYPE_READ:
ll = getLocalLock(lockKey);
if (!(ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
// We don't own a local read lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
synchronized (lo)
{
try
{
lo.enterReadLockNoWait();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
}
ll.incrementReadLocks();
break;
}
locksProcessed++;
}
// Got all; we are done!
Logging.lock.debug(" Successfully obtained multiple locks!");
return;
}
catch (Throwable ex)
{
// No matter what, undo the locks we've taken
LCFException ae = null;
int errno = 0;
while (--locksProcessed >= 0)
{
LockDescription ld = lds[locksProcessed];
int lockType = ld.getType();
String lockKey = ld.getKey();
try
{
switch (lockType)
{
case TYPE_READ:
leaveReadLock(lockKey);
break;
case TYPE_WRITENONEX:
leaveNonExWriteLock(lockKey);
break;
case TYPE_WRITE:
leaveWriteLock(lockKey);
break;
}
}
catch (LCFException e)
{
ae = e;
}
}
if (ae != null)
{
throw ae;
}
if (ex instanceof LCFException)
{
throw (LCFException)ex;
}
if (ex instanceof LockException || ex instanceof LocalLockException)
{
Logging.lock.debug(" Couldn't get lock; throwing LockException");
// It's either LockException or LocalLockException
throw new LockException(ex.getMessage());
}
if (ex instanceof InterruptedException)
{
throw new LCFException("Interrupted",ex,LCFException.INTERRUPTED);
}
if (!(ex instanceof Error))
{
throw new Error("Unexpected exception",ex);
}
throw (Error)ex;
}
}
/** Leave multiple locks
*/
public void leaveLocks(String[] readLocks, String[] writeNonExLocks, String[] writeLocks)
throws LCFException
{
LockDescription[] lds = getSortedUniqueLocks(readLocks,writeNonExLocks,writeLocks);
// Free them all... one at a time is fine
LCFException ae = null;
int i = lds.length;
while (--i >= 0)
{
LockDescription ld = lds[i];
String lockKey = ld.getKey();
int lockType = ld.getType();
try
{
switch (lockType)
{
case TYPE_READ:
leaveReadLock(lockKey);
break;
case TYPE_WRITENONEX:
leaveNonExWriteLock(lockKey);
break;
case TYPE_WRITE:
leaveWriteLock(lockKey);
break;
}
}
catch (LCFException e)
{
ae = e;
}
}
if (ae != null)
{
throw ae;
}
}
/** Enter a named, read critical section (NOT a lock). Critical sections never cross JVM boundaries.
* Critical section names do not collide with lock names; they have a distinct namespace.
*@param sectionKey is the name of the section to enter. Only one thread can be in any given named
* section at a time.
*/
public void enterReadCriticalSection(String sectionKey)
throws LCFException
{
LocalLock ll = getLocalSection(sectionKey);
// See if we already own the read lock for the object.
// Write locks or non-ex writelocks count as well (they're stronger).
if (ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock())
{
ll.incrementReadLocks();
return;
}
// We don't own a local read lock. Get one.
while (true)
{
LockObject lo = mySections.getObject(sectionKey,null);
try
{
lo.enterReadLock();
break;
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementReadLocks();
}
/** Leave a named, read critical section (NOT a lock). Critical sections never cross JVM boundaries.
* Critical section names do not collide with lock names; they have a distinct namespace.
*@param sectionKey is the name of the section to leave. Only one thread can be in any given named
* section at a time.
*/
public void leaveReadCriticalSection(String sectionKey)
throws LCFException
{
LocalLock ll = getLocalSection(sectionKey);
ll.decrementReadLocks();
if (!(ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
while (true)
{
LockObject lo = mySections.getObject(sectionKey,null);
try
{
lo.leaveReadLock();
break;
}
catch (InterruptedException e)
{
// Try one more time
try
{
lo.leaveReadLock();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (InterruptedException e2)
{
ll.incrementReadLocks();
throw new LCFException("Interrupted",e2,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e2)
{
ll.incrementReadLocks();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
catch (ExpiredObjectException e)
{
// Try again
}
}
releaseLocalSection(sectionKey);
}
}
/** Enter a named, non-exclusive write critical section (NOT a lock). Critical sections never cross JVM boundaries.
* Critical section names do not collide with lock names; they have a distinct namespace.
*@param sectionKey is the name of the section to enter. Only one thread can be in any given named
* section at a time.
*/
public void enterNonExWriteCriticalSection(String sectionKey)
throws LCFException
{
LocalLock ll = getLocalSection(sectionKey);
// See if we already own a write lock for the object
// If we do, there is no reason to change the status of the global lock we own.
if (ll.hasNonExWriteLock() || ll.hasWriteLock())
{
ll.incrementNonExWriteLocks();
return;
}
// Check for illegalities
if (ll.hasReadLock())
{
throw new LCFException("Illegal lock sequence: NonExWrite critical section can't be within read critical section",LCFException.GENERAL_ERROR);
}
// We don't own a local non-ex write lock. Get one. The global lock will need
// to know if we already have a a read lock.
while (true)
{
LockObject lo = mySections.getObject(sectionKey,null);
try
{
lo.enterNonExWriteLock();
break;
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementNonExWriteLocks();
}
/** Leave a named, non-exclusive write critical section (NOT a lock). Critical sections never cross JVM boundaries.
* Critical section names do not collide with lock names; they have a distinct namespace.
*@param sectionKey is the name of the section to leave. Only one thread can be in any given named
* section at a time.
*/
public void leaveNonExWriteCriticalSection(String sectionKey)
throws LCFException
{
LocalLock ll = getLocalSection(sectionKey);
ll.decrementNonExWriteLocks();
// See if we no longer have a write lock for the object.
// If we retain the stronger exclusive lock, we still do not need to
// change the status of the global lock.
if (!(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
while (true)
{
LockObject lo = mySections.getObject(sectionKey,null);
try
{
lo.leaveNonExWriteLock();
break;
}
catch (InterruptedException e)
{
// try one more time
try
{
lo.leaveNonExWriteLock();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (InterruptedException e2)
{
ll.incrementNonExWriteLocks();
throw new LCFException("Interrupted",e2,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e2)
{
ll.incrementNonExWriteLocks();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
catch (ExpiredObjectException e)
{
// Try again
}
}
releaseLocalSection(sectionKey);
}
}
/** Enter a named, exclusive critical section (NOT a lock). Critical sections never cross JVM boundaries.
* Critical section names should be distinct from all lock names.
*@param sectionKey is the name of the section to enter. Only one thread can be in any given named
* section at a time.
*/
public void enterWriteCriticalSection(String sectionKey)
throws LCFException
{
LocalLock ll = getLocalSection(sectionKey);
// See if we already own the write lock for the object
if (ll.hasWriteLock())
{
ll.incrementWriteLocks();
return;
}
// Check for illegalities
if (ll.hasReadLock() || ll.hasNonExWriteLock())
{
throw new LCFException("Illegal lock sequence: Write lock can't be within read lock or non-ex write lock",LCFException.GENERAL_ERROR);
}
// We don't own a local write lock. Get one. The global lock will need
// to know if we already have a non-exclusive lock or a read lock, which we don't because
// it's illegal.
while (true)
{
LockObject lo = mySections.getObject(sectionKey,null);
try
{
lo.enterWriteLock();
break;
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementWriteLocks();
}
/** Leave a named, exclusive critical section (NOT a lock). Critical sections never cross JVM boundaries.
* Critical section names should be distinct from all lock names.
*@param sectionKey is the name of the section to leave. Only one thread can be in any given named
* section at a time.
*/
public void leaveWriteCriticalSection(String sectionKey)
throws LCFException
{
LocalLock ll = getLocalSection(sectionKey);
ll.decrementWriteLocks();
if (!ll.hasWriteLock())
{
while (true)
{
LockObject lo = mySections.getObject(sectionKey,null);
try
{
lo.leaveWriteLock();
break;
}
catch (InterruptedException e)
{
// try one more time
try
{
lo.leaveWriteLock();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (InterruptedException e2)
{
ll.incrementWriteLocks();
throw new LCFException("Interrupted",e2,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e2)
{
ll.incrementWriteLocks();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
catch (ExpiredObjectException e)
{
// Try again
}
}
releaseLocalSection(sectionKey);
}
}
/** Enter multiple critical sections simultaneously.
*@param readSectionKeys is an array of read section descriptors, or null if there are no read sections desired.
*@param nonExSectionKeys is an array of non-ex write section descriptors, or null if none desired.
*@param writeSectionKeys is an array of write section descriptors, or null if there are none desired.
*/
public void enterCriticalSections(String[] readSectionKeys, String[] nonExSectionKeys, String[] writeSectionKeys)
throws LCFException
{
// Sort the locks. This improves the chances of making it through the locking process without
// contention!
LockDescription lds[] = getSortedUniqueLocks(readSectionKeys,nonExSectionKeys,writeSectionKeys);
int locksProcessed = 0;
try
{
while (locksProcessed < lds.length)
{
LockDescription ld = lds[locksProcessed];
int lockType = ld.getType();
String lockKey = ld.getKey();
LocalLock ll;
switch (lockType)
{
case TYPE_WRITE:
ll = getLocalSection(lockKey);
// Check for illegalities
if ((ll.hasReadLock() || ll.hasNonExWriteLock()) && !ll.hasWriteLock())
{
throw new LCFException("Illegal lock sequence: Write critical section can't be within read critical section or non-ex write critical section",LCFException.GENERAL_ERROR);
}
// See if we already own the write lock for the object
if (!ll.hasWriteLock())
{
// We don't own a local write lock. Get one.
while (true)
{
LockObject lo = mySections.getObject(lockKey,null);
try
{
lo.enterWriteLock();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
ll.incrementWriteLocks();
break;
case TYPE_WRITENONEX:
ll = getLocalSection(lockKey);
// Check for illegalities
if (ll.hasReadLock() && !(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
throw new LCFException("Illegal lock sequence: NonExWrite critical section can't be within read critical section",LCFException.GENERAL_ERROR);
}
// See if we already own the write lock for the object
if (!(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
// We don't own a local write lock. Get one.
while (true)
{
LockObject lo = mySections.getObject(lockKey,null);
try
{
lo.enterNonExWriteLock();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
ll.incrementNonExWriteLocks();
break;
case TYPE_READ:
ll = getLocalSection(lockKey);
if (!(ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
// We don't own a local read lock. Get one.
while (true)
{
LockObject lo = mySections.getObject(lockKey,null);
try
{
lo.enterReadLock();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
ll.incrementReadLocks();
break;
}
locksProcessed++;
}
// Got all; we are done!
return;
}
catch (Throwable ex)
{
// No matter what, undo the locks we've taken
LCFException ae = null;
int errno = 0;
while (--locksProcessed >= 0)
{
LockDescription ld = lds[locksProcessed];
int lockType = ld.getType();
String lockKey = ld.getKey();
try
{
switch (lockType)
{
case TYPE_READ:
leaveReadCriticalSection(lockKey);
break;
case TYPE_WRITENONEX:
leaveNonExWriteCriticalSection(lockKey);
break;
case TYPE_WRITE:
leaveWriteCriticalSection(lockKey);
break;
}
}
catch (LCFException e)
{
ae = e;
}
}
if (ae != null)
{
throw ae;
}
if (ex instanceof LCFException)
{
throw (LCFException)ex;
}
if (ex instanceof InterruptedException)
{
// It's InterruptedException
throw new LCFException("Interrupted",ex,LCFException.INTERRUPTED);
}
if (!(ex instanceof Error))
{
throw new Error("Unexpected exception",ex);
}
throw (Error)ex;
}
}
/** Leave multiple critical sections simultaneously.
*@param readSectionKeys is an array of read section descriptors, or null if there are no read sections desired.
*@param nonExSectionKeys is an array of non-ex write section descriptors, or null if none desired.
*@param writeSectionKeys is an array of write section descriptors, or null if there are none desired.
*/
public void leaveCriticalSections(String[] readSectionKeys, String[] nonExSectionKeys, String[] writeSectionKeys)
throws LCFException
{
LockDescription[] lds = getSortedUniqueLocks(readSectionKeys,nonExSectionKeys,writeSectionKeys);
// Free them all... one at a time is fine
LCFException ae = null;
int i = lds.length;
while (--i >= 0)
{
LockDescription ld = lds[i];
String lockKey = ld.getKey();
int lockType = ld.getType();
try
{
switch (lockType)
{
case TYPE_READ:
leaveReadCriticalSection(lockKey);
break;
case TYPE_WRITENONEX:
leaveNonExWriteCriticalSection(lockKey);
break;
case TYPE_WRITE:
leaveWriteCriticalSection(lockKey);
break;
}
}
catch (LCFException e)
{
ae = e;
}
}
if (ae != null)
{
throw ae;
}
}
protected LocalLock getLocalLock(String lockKey)
{
LocalLock ll = (LocalLock)localLocks.get(lockKey);
if (ll == null)
{
ll = new LocalLock();
localLocks.put(lockKey,ll);
}
return ll;
}
protected void releaseLocalLock(String lockKey)
{
localLocks.remove(lockKey);
}
protected LocalLock getLocalSection(String sectionKey)
{
LocalLock ll = (LocalLock)localSections.get(sectionKey);
if (ll == null)
{
ll = new LocalLock();
localSections.put(sectionKey,ll);
}
return ll;
}
protected void releaseLocalSection(String sectionKey)
{
localSections.remove(sectionKey);
}
/** Process inbound locks into a sorted vector of most-restrictive unique locks
*/
protected LockDescription[] getSortedUniqueLocks(String[] readLocks, String[] writeNonExLocks,
String[] writeLocks)
{
// First build a unique hash of lock descriptions
HashMap ht = new HashMap();
int i;
if (readLocks != null)
{
i = 0;
while (i < readLocks.length)
{
String key = readLocks[i++];
LockDescription ld = (LockDescription)ht.get(key);
if (ld == null)
{
ld = new LockDescription(TYPE_READ,key);
ht.put(key,ld);
}
else
ld.set(TYPE_READ);
}
}
if (writeNonExLocks != null)
{
i = 0;
while (i < writeNonExLocks.length)
{
String key = writeNonExLocks[i++];
LockDescription ld = (LockDescription)ht.get(key);
if (ld == null)
{
ld = new LockDescription(TYPE_WRITENONEX,key);
ht.put(key,ld);
}
else
ld.set(TYPE_WRITENONEX);
}
}
if (writeLocks != null)
{
i = 0;
while (i < writeLocks.length)
{
String key = writeLocks[i++];
LockDescription ld = (LockDescription)ht.get(key);
if (ld == null)
{
ld = new LockDescription(TYPE_WRITE,key);
ht.put(key,ld);
}
else
ld.set(TYPE_WRITE);
}
}
// Now, sort by key name
LockDescription[] rval = new LockDescription[ht.size()];
String[] sortarray = new String[ht.size()];
i = 0;
Iterator iter = ht.keySet().iterator();
while (iter.hasNext())
{
String key = (String)iter.next();
sortarray[i++] = key;
}
java.util.Arrays.sort(sortarray);
i = 0;
while (i < sortarray.length)
{
rval[i] = (LockDescription)ht.get(sortarray[i]);
i++;
}
return rval;
}
/** Create a file path given a key name.
*@param key is the key name.
*@return the file path.
*/
protected String makeFilePath(String key)
{
int hashcode = key.hashCode();
int outerDirNumber = (hashcode & (1023));
int innerDirNumber = ((hashcode >> 10) & (1023));
String fullDir = synchDirectory;
if (fullDir.length() == 0 || !fullDir.endsWith("/"))
fullDir = fullDir + "/";
fullDir = fullDir + Integer.toString(outerDirNumber)+"/"+Integer.toString(innerDirNumber);
return fullDir;
}
protected class LockDescription
{
protected int lockType;
protected String lockKey;
public LockDescription(int lockType, String lockKey)
{
this.lockType = lockType;
this.lockKey = lockKey;
}
public void set(int lockType)
{
if (lockType > this.lockType)
this.lockType = lockType;
}
public int getType()
{
return lockType;
}
public String getKey()
{
return lockKey;
}
}
protected class LocalLock
{
private int readCount = 0;
private int writeCount = 0;
private int nonExWriteCount = 0;
public LocalLock()
{
}
public boolean hasWriteLock()
{
return (writeCount > 0);
}
public boolean hasReadLock()
{
return (readCount > 0);
}
public boolean hasNonExWriteLock()
{
return (nonExWriteCount > 0);
}
public void incrementReadLocks()
{
readCount++;
}
public void incrementNonExWriteLocks()
{
nonExWriteCount++;
}
public void incrementWriteLocks()
{
writeCount++;
}
public void decrementReadLocks()
{
readCount--;
}
public void decrementNonExWriteLocks()
{
nonExWriteCount--;
}
public void decrementWriteLocks()
{
writeCount--;
}
}
protected static final int BASE_SIZE = 128;
protected static class ByteArrayBuffer
{
protected byte[] buffer;
protected int length;
public ByteArrayBuffer()
{
buffer = new byte[BASE_SIZE];
length = 0;
}
public void add(byte b)
{
if (length == buffer.length)
{
byte[] oldbuffer = buffer;
buffer = new byte[length * 2];
System.arraycopy(oldbuffer,0,buffer,0,length);
}
buffer[length++] = b;
}
public byte[] toArray()
{
byte[] rval = new byte[length];
System.arraycopy(buffer,0,rval,0,length);
return rval;
}
}
}
|
modules/framework/core/org/apache/lcf/core/lockmanager/LockManager.java
|
/* $Id$ */
/**
* 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.lcf.core.lockmanager;
import org.apache.lcf.core.interfaces.*;
import org.apache.lcf.core.system.Logging;
import org.apache.lcf.core.system.LCF;
import java.util.*;
import java.io.*;
/** The lock manager manages locks across all threads and JVMs and cluster members. There should be no more than ONE
* instance of this class per thread!!! The factory should enforce this.
*/
public class LockManager implements ILockManager
{
public static final String _rcsid = "@(#)$Id$";
/** Synchronization directory property - local to this implementation of ILockManager */
public static final String synchDirectoryProperty = "org.apache.lcf.synchdirectory";
// These are the lock/section types, in order of escalation
protected final static int TYPE_READ = 1;
protected final static int TYPE_WRITENONEX = 2;
protected final static int TYPE_WRITE = 3;
// These are for locks (which cross JVM boundaries)
protected HashMap localLocks = new HashMap();
protected static LockPool myLocks = new LockPool();
// These are for critical sections (which do not cross JVM boundaries)
protected HashMap localSections = new HashMap();
protected static LockPool mySections = new LockPool();
// This is the directory used for cross-JVM synchronization, or null if off
protected String synchDirectory = null;
public LockManager()
throws LCFException
{
synchDirectory = LCF.getProperty(synchDirectoryProperty);
if (synchDirectory == null)
throw new LCFException("Property "+synchDirectoryProperty+" must be set!",LCFException.SETUP_ERROR);
if (!new File(synchDirectory).isDirectory())
throw new LCFException("Property "+synchDirectoryProperty+" must point to an existing, writeable directory!",LCFException.SETUP_ERROR);
}
/** Raise a flag. Use this method to assert a condition, or send a global signal. The flag will be reset when the
* entire system is restarted.
*@param flagName is the name of the flag to set.
*/
public void setGlobalFlag(String flagName)
throws LCFException
{
String resourceName = "flag-" + flagName;
String path = makeFilePath(resourceName);
(new File(path)).mkdirs();
File f = new File(path,LCF.safeFileName(resourceName));
try
{
f.createNewFile();
}
catch (InterruptedIOException e)
{
throw new LCFException("Interrupted: "+e.getMessage(),e,LCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new LCFException(e.getMessage(),e);
}
}
/** Clear a flag. Use this method to clear a condition, or retract a global signal.
*@param flagName is the name of the flag to clear.
*/
public void clearGlobalFlag(String flagName)
throws LCFException
{
String resourceName = "flag-" + flagName;
File f = new File(makeFilePath(resourceName),LCF.safeFileName(resourceName));
f.delete();
}
/** Check the condition of a specified flag.
*@param flagName is the name of the flag to check.
*@return true if the flag is set, false otherwise.
*/
public boolean checkGlobalFlag(String flagName)
throws LCFException
{
String resourceName = "flag-" + flagName;
File f = new File(makeFilePath(resourceName),LCF.safeFileName(resourceName));
return f.exists();
}
/** Read data from a shared data resource. Use this method to read any existing data, or get a null back if there is no such resource.
* Note well that this is not necessarily an atomic operation, and it must thus be protected by a lock.
*@param resourceName is the global name of the resource.
*@return a byte array containing the data, or null.
*/
public byte[] readData(String resourceName)
throws LCFException
{
File f = new File(makeFilePath(resourceName),LCF.safeFileName(resourceName));
try
{
InputStream is = new FileInputStream(f);
try
{
ByteArrayBuffer bab = new ByteArrayBuffer();
while (true)
{
int x = is.read();
if (x == -1)
break;
bab.add((byte)x);
}
return bab.toArray();
}
finally
{
is.close();
}
}
catch (FileNotFoundException e)
{
return null;
}
catch (InterruptedIOException e)
{
throw new LCFException("Interrupted: "+e.getMessage(),e,LCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new LCFException("IO exception: "+e.getMessage(),e);
}
}
/** Write data to a shared data resource. Use this method to write a body of data into a shared resource.
* Note well that this is not necessarily an atomic operation, and it must thus be protected by a lock.
*@param resourceName is the global name of the resource.
*@param data is the byte array containing the data. Pass null if you want to delete the resource completely.
*/
public void writeData(String resourceName, byte[] data)
throws LCFException
{
try
{
String path = makeFilePath(resourceName);
// Make sure the directory exists
(new File(path)).mkdirs();
File f = new File(path,LCF.safeFileName(resourceName));
if (data == null)
{
f.delete();
return;
}
FileOutputStream os = new FileOutputStream(f);
try
{
os.write(data,0,data.length);
}
finally
{
os.close();
}
}
catch (InterruptedIOException e)
{
throw new LCFException("Interrupted: "+e.getMessage(),e,LCFException.INTERRUPTED);
}
catch (IOException e)
{
throw new LCFException("IO exception: "+e.getMessage(),e);
}
}
/** Wait for a time before retrying a lock.
*/
public void timedWait(int time)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Waiting for time "+Integer.toString(time));
}
try
{
LCF.sleep(time);
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
/** Enter a non-exclusive write-locked area (blocking out all readers, but letting in other "writers").
* This kind of lock is designed to be used in conjunction with read locks. It is used typically in
* a situation where the read lock represents a query and the non-exclusive write lock represents a modification
* to an individual item that might affect the query, but where multiple modifications do not individually
* interfere with one another (use of another, standard, write lock per item can guarantee this).
*/
public void enterNonExWriteLock(String lockKey)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering non-ex write lock '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
// See if we already own a write lock for the object
// If we do, there is no reason to change the status of the global lock we own.
if (ll.hasNonExWriteLock() || ll.hasWriteLock())
{
ll.incrementNonExWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
return;
}
// Check for illegalities
if (ll.hasReadLock())
{
throw new LCFException("Illegal lock sequence: NonExWrite lock can't be within read lock",LCFException.GENERAL_ERROR);
}
// We don't own a local non-ex write lock. Get one. The global lock will need
// to know if we already have a a read lock.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.enterNonExWriteLock();
break;
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again to get a valid object
}
}
ll.incrementNonExWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
}
public void enterNonExWriteLockNoWait(String lockKey)
throws LCFException, LockException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering non-ex write lock no wait '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
// See if we already own a write lock for the object
// If we do, there is no reason to change the status of the global lock we own.
if (ll.hasNonExWriteLock() || ll.hasWriteLock())
{
ll.incrementNonExWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
return;
}
// Check for illegalities
if (ll.hasReadLock())
{
throw new LCFException("Illegal lock sequence: NonExWrite lock can't be within read lock",LCFException.GENERAL_ERROR);
}
// We don't own a local non-ex write lock. Get one. The global lock will need
// to know if we already have a a read lock.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
synchronized (lo)
{
lo.enterNonExWriteLockNoWait();
break;
}
}
catch (LocalLockException e)
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug(" Could not non-ex write lock '"+lockKey+"', lock exception");
}
// Throw LockException instead
throw new LockException(e.getMessage());
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again to get a valid object
}
}
ll.incrementNonExWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
}
/** Leave a non-exclusive write lock.
*/
public void leaveNonExWriteLock(String lockKey)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Leaving non-ex write lock '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
ll.decrementNonExWriteLocks();
// See if we no longer have a write lock for the object.
// If we retain the stronger exclusive lock, we still do not need to
// change the status of the global lock.
if (!(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.leaveNonExWriteLock();
break;
}
catch (InterruptedException e)
{
// try one more time
try
{
lo.leaveNonExWriteLock();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (InterruptedException e2)
{
ll.incrementNonExWriteLocks();
throw new LCFException("Interrupted",e2,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e2)
{
ll.incrementNonExWriteLocks();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
catch (ExpiredObjectException e)
{
// Try again to get a valid object
}
}
releaseLocalLock(lockKey);
}
}
/** Enter a write locked area (i.e., block out both readers and other writers)
* NOTE: Can't enter until all readers have left.
*/
public void enterWriteLock(String lockKey)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering write lock '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
// See if we already own the write lock for the object
if (ll.hasWriteLock())
{
ll.incrementWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
return;
}
// Check for illegalities
if (ll.hasReadLock() || ll.hasNonExWriteLock())
{
throw new LCFException("Illegal lock sequence: Write lock can't be within read lock or non-ex write lock",LCFException.GENERAL_ERROR);
}
// We don't own a local write lock. Get one. The global lock will need
// to know if we already have a non-exclusive lock or a read lock, which we don't because
// it's illegal.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.enterWriteLock();
break;
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
}
public void enterWriteLockNoWait(String lockKey)
throws LCFException, LockException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering write lock no wait '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
// See if we already own the write lock for the object
if (ll.hasWriteLock())
{
ll.incrementWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
return;
}
// Check for illegalities
if (ll.hasReadLock() || ll.hasNonExWriteLock())
{
throw new LCFException("Illegal lock sequence: Write lock can't be within read lock or non-ex write lock",LCFException.GENERAL_ERROR);
}
// We don't own a local write lock. Get one. The global lock will need
// to know if we already have a non-exclusive lock or a read lock, which we don't because
// it's illegal.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
synchronized (lo)
{
lo.enterWriteLockNoWait();
break;
}
}
catch (LocalLockException e)
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug(" Could not write lock '"+lockKey+"', lock exception");
}
throw new LockException(e.getMessage());
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementWriteLocks();
Logging.lock.debug(" Successfully obtained lock!");
}
public void leaveWriteLock(String lockKey)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Leaving write lock '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
ll.decrementWriteLocks();
if (!ll.hasWriteLock())
{
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.leaveWriteLock();
break;
}
catch (InterruptedException e)
{
// try one more time
try
{
lo.leaveWriteLock();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (InterruptedException e2)
{
ll.incrementWriteLocks();
throw new LCFException("Interrupted",e2,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e2)
{
ll.incrementWriteLocks();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
catch (ExpiredObjectException e)
{
// Try again
}
}
releaseLocalLock(lockKey);
}
}
/** Enter a read-only locked area (i.e., block ONLY if there's a writer)
*/
public void enterReadLock(String lockKey)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering read lock '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
// See if we already own the read lock for the object.
// Write locks or non-ex writelocks count as well (they're stronger).
if (ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock())
{
ll.incrementReadLocks();
Logging.lock.debug(" Successfully obtained lock!");
return;
}
// We don't own a local read lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.enterReadLock();
break;
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementReadLocks();
Logging.lock.debug(" Successfully obtained lock!");
}
public void enterReadLockNoWait(String lockKey)
throws LCFException, LockException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering read lock no wait '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
// See if we already own the read lock for the object.
// Write locks or non-ex writelocks count as well (they're stronger).
if (ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock())
{
ll.incrementReadLocks();
Logging.lock.debug(" Successfully obtained lock!");
return;
}
// We don't own a local read lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
synchronized (lo)
{
lo.enterReadLockNoWait();
break;
}
}
catch (LocalLockException e)
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug(" Could not read lock '"+lockKey+"', lock exception");
}
throw new LockException(e.getMessage());
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementReadLocks();
Logging.lock.debug(" Successfully obtained lock!");
}
public void leaveReadLock(String lockKey)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Leaving read lock '"+lockKey+"'");
}
LocalLock ll = getLocalLock(lockKey);
ll.decrementReadLocks();
if (!(ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.leaveReadLock();
break;
}
catch (InterruptedException e)
{
// Try one more time
try
{
lo.leaveReadLock();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (InterruptedException e2)
{
ll.incrementReadLocks();
throw new LCFException("Interrupted",e2,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e2)
{
ll.incrementReadLocks();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
catch (ExpiredObjectException e)
{
// Try again
}
}
releaseLocalLock(lockKey);
}
}
public void clearLocks()
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Clearing all locks");
}
Iterator e = localLocks.keySet().iterator();
while (e.hasNext())
{
String keyValue = (String)e.next();
LocalLock ll = (LocalLock)localLocks.get(keyValue);
while (ll.hasWriteLock())
leaveWriteLock(keyValue);
while (ll.hasNonExWriteLock())
leaveNonExWriteLock(keyValue);
while (ll.hasReadLock())
leaveReadLock(keyValue);
}
}
/** Enter multiple locks
*/
public void enterLocks(String[] readLocks, String[] nonExWriteLocks, String[] writeLocks)
throws LCFException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering multiple locks:");
int i;
if (readLocks != null)
{
i = 0;
while (i < readLocks.length)
{
Logging.lock.debug(" Read lock '"+readLocks[i++]+"'");
}
}
if (nonExWriteLocks != null)
{
i = 0;
while (i < nonExWriteLocks.length)
{
Logging.lock.debug(" Non-ex write lock '"+nonExWriteLocks[i++]+"'");
}
}
if (writeLocks != null)
{
i = 0;
while (i < writeLocks.length)
{
Logging.lock.debug(" Write lock '"+writeLocks[i++]+"'");
}
}
}
// Sort the locks. This improves the chances of making it through the locking process without
// contention!
LockDescription lds[] = getSortedUniqueLocks(readLocks,nonExWriteLocks,writeLocks);
int locksProcessed = 0;
try
{
while (locksProcessed < lds.length)
{
LockDescription ld = lds[locksProcessed];
int lockType = ld.getType();
String lockKey = ld.getKey();
LocalLock ll;
switch (lockType)
{
case TYPE_WRITE:
ll = getLocalLock(lockKey);
// Check for illegalities
if ((ll.hasReadLock() || ll.hasNonExWriteLock()) && !ll.hasWriteLock())
{
throw new LCFException("Illegal lock sequence: Write lock can't be within read lock or non-ex write lock",LCFException.GENERAL_ERROR);
}
// See if we already own the write lock for the object
if (!ll.hasWriteLock())
{
// We don't own a local write lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.enterWriteLock();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
ll.incrementWriteLocks();
break;
case TYPE_WRITENONEX:
ll = getLocalLock(lockKey);
// Check for illegalities
if (ll.hasReadLock() && !(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
throw new LCFException("Illegal lock sequence: NonExWrite lock can't be within read lock",LCFException.GENERAL_ERROR);
}
// See if we already own the write lock for the object
if (!(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
// We don't own a local write lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.enterNonExWriteLock();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
ll.incrementNonExWriteLocks();
break;
case TYPE_READ:
ll = getLocalLock(lockKey);
if (!(ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
// We don't own a local read lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
try
{
lo.enterReadLock();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
ll.incrementReadLocks();
break;
}
locksProcessed++;
}
// Got all; we are done!
Logging.lock.debug(" Successfully obtained multiple locks!");
return;
}
catch (Throwable ex)
{
// No matter what, undo the locks we've taken
LCFException ae = null;
int errno = 0;
while (--locksProcessed >= 0)
{
LockDescription ld = lds[locksProcessed];
int lockType = ld.getType();
String lockKey = ld.getKey();
try
{
switch (lockType)
{
case TYPE_READ:
leaveReadLock(lockKey);
break;
case TYPE_WRITENONEX:
leaveNonExWriteLock(lockKey);
break;
case TYPE_WRITE:
leaveWriteLock(lockKey);
break;
}
}
catch (LCFException e)
{
ae = e;
}
}
if (ae != null)
{
throw ae;
}
if (ex instanceof LCFException)
{
throw (LCFException)ex;
}
if (ex instanceof InterruptedException)
{
// It's InterruptedException
throw new LCFException("Interrupted",ex,LCFException.INTERRUPTED);
}
if (!(ex instanceof Error))
{
throw new Error("Unexpected exception",ex);
}
throw (Error)ex;
}
}
public void enterLocksNoWait(String[] readLocks, String[] nonExWriteLocks, String[] writeLocks)
throws LCFException, LockException
{
if (Logging.lock.isDebugEnabled())
{
Logging.lock.debug("Entering multiple locks no wait:");
int i;
if (readLocks != null)
{
i = 0;
while (i < readLocks.length)
{
Logging.lock.debug(" Read lock '"+readLocks[i++]+"'");
}
}
if (nonExWriteLocks != null)
{
i = 0;
while (i < nonExWriteLocks.length)
{
Logging.lock.debug(" Non-ex write lock '"+nonExWriteLocks[i++]+"'");
}
}
if (writeLocks != null)
{
i = 0;
while (i < writeLocks.length)
{
Logging.lock.debug(" Write lock '"+writeLocks[i++]+"'");
}
}
}
// Sort the locks. This improves the chances of making it through the locking process without
// contention!
LockDescription lds[] = getSortedUniqueLocks(readLocks,nonExWriteLocks,writeLocks);
int locksProcessed = 0;
try
{
while (locksProcessed < lds.length)
{
LockDescription ld = lds[locksProcessed];
int lockType = ld.getType();
String lockKey = ld.getKey();
LocalLock ll;
switch (lockType)
{
case TYPE_WRITE:
ll = getLocalLock(lockKey);
// Check for illegalities
if ((ll.hasReadLock() || ll.hasNonExWriteLock()) && !ll.hasWriteLock())
{
throw new LCFException("Illegal lock sequence: Write lock can't be within read lock or non-ex write lock",LCFException.GENERAL_ERROR);
}
// See if we already own the write lock for the object
if (!ll.hasWriteLock())
{
// We don't own a local write lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
synchronized (lo)
{
try
{
lo.enterWriteLockNoWait();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
}
ll.incrementWriteLocks();
break;
case TYPE_WRITENONEX:
ll = getLocalLock(lockKey);
// Check for illegalities
if (ll.hasReadLock() && !(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
throw new LCFException("Illegal lock sequence: NonExWrite lock can't be within read lock",LCFException.GENERAL_ERROR);
}
// See if we already own the write lock for the object
if (!(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
// We don't own a local write lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
synchronized (lo)
{
try
{
lo.enterNonExWriteLockNoWait();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
}
ll.incrementNonExWriteLocks();
break;
case TYPE_READ:
ll = getLocalLock(lockKey);
if (!(ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
// We don't own a local read lock. Get one.
while (true)
{
LockObject lo = myLocks.getObject(lockKey,synchDirectory);
synchronized (lo)
{
try
{
lo.enterReadLockNoWait();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
}
ll.incrementReadLocks();
break;
}
locksProcessed++;
}
// Got all; we are done!
Logging.lock.debug(" Successfully obtained multiple locks!");
return;
}
catch (Throwable ex)
{
// No matter what, undo the locks we've taken
LCFException ae = null;
int errno = 0;
while (--locksProcessed >= 0)
{
LockDescription ld = lds[locksProcessed];
int lockType = ld.getType();
String lockKey = ld.getKey();
try
{
switch (lockType)
{
case TYPE_READ:
leaveReadLock(lockKey);
break;
case TYPE_WRITENONEX:
leaveNonExWriteLock(lockKey);
break;
case TYPE_WRITE:
leaveWriteLock(lockKey);
break;
}
}
catch (LCFException e)
{
ae = e;
}
}
if (ae != null)
{
throw ae;
}
if (ex instanceof LCFException)
{
throw (LCFException)ex;
}
if (ex instanceof LockException || ex instanceof LocalLockException)
{
Logging.lock.debug(" Couldn't get lock; throwing LockException");
// It's either LockException or LocalLockException
throw new LockException(ex.getMessage());
}
if (ex instanceof InterruptedException)
{
throw new LCFException("Interrupted",ex,LCFException.INTERRUPTED);
}
if (!(ex instanceof Error))
{
throw new Error("Unexpected exception",ex);
}
throw (Error)ex;
}
}
/** Leave multiple locks
*/
public void leaveLocks(String[] readLocks, String[] writeNonExLocks, String[] writeLocks)
throws LCFException
{
LockDescription[] lds = getSortedUniqueLocks(readLocks,writeNonExLocks,writeLocks);
// Free them all... one at a time is fine
LCFException ae = null;
int i = lds.length;
while (--i >= 0)
{
LockDescription ld = lds[i];
String lockKey = ld.getKey();
int lockType = ld.getType();
try
{
switch (lockType)
{
case TYPE_READ:
leaveReadLock(lockKey);
break;
case TYPE_WRITENONEX:
leaveNonExWriteLock(lockKey);
break;
case TYPE_WRITE:
leaveWriteLock(lockKey);
break;
}
}
catch (LCFException e)
{
ae = e;
}
}
if (ae != null)
{
throw ae;
}
}
/** Enter a named, read critical section (NOT a lock). Critical sections never cross JVM boundaries.
* Critical section names do not collide with lock names; they have a distinct namespace.
*@param sectionKey is the name of the section to enter. Only one thread can be in any given named
* section at a time.
*/
public void enterReadCriticalSection(String sectionKey)
throws LCFException
{
LocalLock ll = getLocalSection(sectionKey);
// See if we already own the read lock for the object.
// Write locks or non-ex writelocks count as well (they're stronger).
if (ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock())
{
ll.incrementReadLocks();
return;
}
// We don't own a local read lock. Get one.
while (true)
{
LockObject lo = mySections.getObject(sectionKey,null);
try
{
lo.enterReadLock();
break;
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementReadLocks();
}
/** Leave a named, read critical section (NOT a lock). Critical sections never cross JVM boundaries.
* Critical section names do not collide with lock names; they have a distinct namespace.
*@param sectionKey is the name of the section to leave. Only one thread can be in any given named
* section at a time.
*/
public void leaveReadCriticalSection(String sectionKey)
throws LCFException
{
LocalLock ll = getLocalSection(sectionKey);
ll.decrementReadLocks();
if (!(ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
while (true)
{
LockObject lo = mySections.getObject(sectionKey,null);
try
{
lo.leaveReadLock();
break;
}
catch (InterruptedException e)
{
// Try one more time
try
{
lo.leaveReadLock();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (InterruptedException e2)
{
ll.incrementReadLocks();
throw new LCFException("Interrupted",e2,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e2)
{
ll.incrementReadLocks();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
catch (ExpiredObjectException e)
{
// Try again
}
}
releaseLocalSection(sectionKey);
}
}
/** Enter a named, non-exclusive write critical section (NOT a lock). Critical sections never cross JVM boundaries.
* Critical section names do not collide with lock names; they have a distinct namespace.
*@param sectionKey is the name of the section to enter. Only one thread can be in any given named
* section at a time.
*/
public void enterNonExWriteCriticalSection(String sectionKey)
throws LCFException
{
LocalLock ll = getLocalSection(sectionKey);
// See if we already own a write lock for the object
// If we do, there is no reason to change the status of the global lock we own.
if (ll.hasNonExWriteLock() || ll.hasWriteLock())
{
ll.incrementNonExWriteLocks();
return;
}
// Check for illegalities
if (ll.hasReadLock())
{
throw new LCFException("Illegal lock sequence: NonExWrite critical section can't be within read critical section",LCFException.GENERAL_ERROR);
}
// We don't own a local non-ex write lock. Get one. The global lock will need
// to know if we already have a a read lock.
while (true)
{
LockObject lo = mySections.getObject(sectionKey,null);
try
{
lo.enterNonExWriteLock();
break;
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementNonExWriteLocks();
}
/** Leave a named, non-exclusive write critical section (NOT a lock). Critical sections never cross JVM boundaries.
* Critical section names do not collide with lock names; they have a distinct namespace.
*@param sectionKey is the name of the section to leave. Only one thread can be in any given named
* section at a time.
*/
public void leaveNonExWriteCriticalSection(String sectionKey)
throws LCFException
{
LocalLock ll = getLocalSection(sectionKey);
ll.decrementNonExWriteLocks();
// See if we no longer have a write lock for the object.
// If we retain the stronger exclusive lock, we still do not need to
// change the status of the global lock.
if (!(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
while (true)
{
LockObject lo = mySections.getObject(sectionKey,null);
try
{
lo.leaveNonExWriteLock();
break;
}
catch (InterruptedException e)
{
// try one more time
try
{
lo.leaveNonExWriteLock();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (InterruptedException e2)
{
ll.incrementNonExWriteLocks();
throw new LCFException("Interrupted",e2,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e2)
{
ll.incrementNonExWriteLocks();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
catch (ExpiredObjectException e)
{
// Try again
}
}
releaseLocalSection(sectionKey);
}
}
/** Enter a named, exclusive critical section (NOT a lock). Critical sections never cross JVM boundaries.
* Critical section names should be distinct from all lock names.
*@param sectionKey is the name of the section to enter. Only one thread can be in any given named
* section at a time.
*/
public void enterWriteCriticalSection(String sectionKey)
throws LCFException
{
LocalLock ll = getLocalSection(sectionKey);
// See if we already own the write lock for the object
if (ll.hasWriteLock())
{
ll.incrementWriteLocks();
return;
}
// Check for illegalities
if (ll.hasReadLock() || ll.hasNonExWriteLock())
{
throw new LCFException("Illegal lock sequence: Write lock can't be within read lock or non-ex write lock",LCFException.GENERAL_ERROR);
}
// We don't own a local write lock. Get one. The global lock will need
// to know if we already have a non-exclusive lock or a read lock, which we don't because
// it's illegal.
while (true)
{
LockObject lo = mySections.getObject(sectionKey,null);
try
{
lo.enterWriteLock();
break;
}
catch (InterruptedException e)
{
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e)
{
// Try again
}
}
ll.incrementWriteLocks();
}
/** Leave a named, exclusive critical section (NOT a lock). Critical sections never cross JVM boundaries.
* Critical section names should be distinct from all lock names.
*@param sectionKey is the name of the section to leave. Only one thread can be in any given named
* section at a time.
*/
public void leaveWriteCriticalSection(String sectionKey)
throws LCFException
{
LocalLock ll = getLocalSection(sectionKey);
ll.decrementWriteLocks();
if (!ll.hasWriteLock())
{
while (true)
{
LockObject lo = mySections.getObject(sectionKey,null);
try
{
lo.leaveWriteLock();
break;
}
catch (InterruptedException e)
{
// try one more time
try
{
lo.leaveWriteLock();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
catch (InterruptedException e2)
{
ll.incrementWriteLocks();
throw new LCFException("Interrupted",e2,LCFException.INTERRUPTED);
}
catch (ExpiredObjectException e2)
{
ll.incrementWriteLocks();
throw new LCFException("Interrupted",e,LCFException.INTERRUPTED);
}
}
catch (ExpiredObjectException e)
{
// Try again
}
}
releaseLocalSection(sectionKey);
}
}
/** Enter multiple critical sections simultaneously.
*@param readSectionKeys is an array of read section descriptors, or null if there are no read sections desired.
*@param nonExSectionKeys is an array of non-ex write section descriptors, or null if none desired.
*@param writeSectionKeys is an array of write section descriptors, or null if there are none desired.
*/
public void enterCriticalSections(String[] readSectionKeys, String[] nonExSectionKeys, String[] writeSectionKeys)
throws LCFException
{
// Sort the locks. This improves the chances of making it through the locking process without
// contention!
LockDescription lds[] = getSortedUniqueLocks(readSectionKeys,nonExSectionKeys,writeSectionKeys);
int locksProcessed = 0;
try
{
while (locksProcessed < lds.length)
{
LockDescription ld = lds[locksProcessed];
int lockType = ld.getType();
String lockKey = ld.getKey();
LocalLock ll;
switch (lockType)
{
case TYPE_WRITE:
ll = getLocalSection(lockKey);
// Check for illegalities
if ((ll.hasReadLock() || ll.hasNonExWriteLock()) && !ll.hasWriteLock())
{
throw new LCFException("Illegal lock sequence: Write critical section can't be within read critical section or non-ex write critical section",LCFException.GENERAL_ERROR);
}
// See if we already own the write lock for the object
if (!ll.hasWriteLock())
{
// We don't own a local write lock. Get one.
while (true)
{
LockObject lo = mySections.getObject(lockKey,null);
try
{
lo.enterWriteLock();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
ll.incrementWriteLocks();
break;
case TYPE_WRITENONEX:
ll = getLocalSection(lockKey);
// Check for illegalities
if (ll.hasReadLock() && !(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
throw new LCFException("Illegal lock sequence: NonExWrite critical section can't be within read critical section",LCFException.GENERAL_ERROR);
}
// See if we already own the write lock for the object
if (!(ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
// We don't own a local write lock. Get one.
while (true)
{
LockObject lo = mySections.getObject(lockKey,null);
try
{
lo.enterNonExWriteLock();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
ll.incrementNonExWriteLocks();
break;
case TYPE_READ:
ll = getLocalSection(lockKey);
if (!(ll.hasReadLock() || ll.hasNonExWriteLock() || ll.hasWriteLock()))
{
// We don't own a local read lock. Get one.
while (true)
{
LockObject lo = mySections.getObject(lockKey,null);
try
{
lo.enterReadLock();
break;
}
catch (ExpiredObjectException e)
{
// Try again
}
}
}
ll.incrementReadLocks();
break;
}
locksProcessed++;
}
// Got all; we are done!
return;
}
catch (Throwable ex)
{
// No matter what, undo the locks we've taken
LCFException ae = null;
int errno = 0;
while (--locksProcessed >= 0)
{
LockDescription ld = lds[locksProcessed];
int lockType = ld.getType();
String lockKey = ld.getKey();
try
{
switch (lockType)
{
case TYPE_READ:
leaveReadCriticalSection(lockKey);
break;
case TYPE_WRITENONEX:
leaveNonExWriteCriticalSection(lockKey);
break;
case TYPE_WRITE:
leaveWriteCriticalSection(lockKey);
break;
}
}
catch (LCFException e)
{
ae = e;
}
}
if (ae != null)
{
throw ae;
}
if (ex instanceof LCFException)
{
throw (LCFException)ex;
}
if (ex instanceof InterruptedException)
{
// It's InterruptedException
throw new LCFException("Interrupted",ex,LCFException.INTERRUPTED);
}
if (!(ex instanceof Error))
{
throw new Error("Unexpected exception",ex);
}
throw (Error)ex;
}
}
/** Leave multiple critical sections simultaneously.
*@param readSectionKeys is an array of read section descriptors, or null if there are no read sections desired.
*@param nonExSectionKeys is an array of non-ex write section descriptors, or null if none desired.
*@param writeSectionKeys is an array of write section descriptors, or null if there are none desired.
*/
public void leaveCriticalSections(String[] readSectionKeys, String[] nonExSectionKeys, String[] writeSectionKeys)
throws LCFException
{
LockDescription[] lds = getSortedUniqueLocks(readSectionKeys,nonExSectionKeys,writeSectionKeys);
// Free them all... one at a time is fine
LCFException ae = null;
int i = lds.length;
while (--i >= 0)
{
LockDescription ld = lds[i];
String lockKey = ld.getKey();
int lockType = ld.getType();
try
{
switch (lockType)
{
case TYPE_READ:
leaveReadCriticalSection(lockKey);
break;
case TYPE_WRITENONEX:
leaveNonExWriteCriticalSection(lockKey);
break;
case TYPE_WRITE:
leaveWriteCriticalSection(lockKey);
break;
}
}
catch (LCFException e)
{
ae = e;
}
}
if (ae != null)
{
throw ae;
}
}
protected LocalLock getLocalLock(String lockKey)
{
LocalLock ll = (LocalLock)localLocks.get(lockKey);
if (ll == null)
{
ll = new LocalLock();
localLocks.put(lockKey,ll);
}
return ll;
}
protected void releaseLocalLock(String lockKey)
{
localLocks.remove(lockKey);
}
protected LocalLock getLocalSection(String sectionKey)
{
LocalLock ll = (LocalLock)localSections.get(sectionKey);
if (ll == null)
{
ll = new LocalLock();
localSections.put(sectionKey,ll);
}
return ll;
}
protected void releaseLocalSection(String sectionKey)
{
localSections.remove(sectionKey);
}
/** Process inbound locks into a sorted vector of most-restrictive unique locks
*/
protected LockDescription[] getSortedUniqueLocks(String[] readLocks, String[] writeNonExLocks,
String[] writeLocks)
{
// First build a unique hash of lock descriptions
HashMap ht = new HashMap();
int i;
if (readLocks != null)
{
i = 0;
while (i < readLocks.length)
{
String key = readLocks[i++];
LockDescription ld = (LockDescription)ht.get(key);
if (ld == null)
{
ld = new LockDescription(TYPE_READ,key);
ht.put(key,ld);
}
else
ld.set(TYPE_READ);
}
}
if (writeNonExLocks != null)
{
i = 0;
while (i < writeNonExLocks.length)
{
String key = writeNonExLocks[i++];
LockDescription ld = (LockDescription)ht.get(key);
if (ld == null)
{
ld = new LockDescription(TYPE_WRITENONEX,key);
ht.put(key,ld);
}
else
ld.set(TYPE_WRITENONEX);
}
}
if (writeLocks != null)
{
i = 0;
while (i < writeLocks.length)
{
String key = writeLocks[i++];
LockDescription ld = (LockDescription)ht.get(key);
if (ld == null)
{
ld = new LockDescription(TYPE_WRITE,key);
ht.put(key,ld);
}
else
ld.set(TYPE_WRITE);
}
}
// Now, sort by key name
LockDescription[] rval = new LockDescription[ht.size()];
String[] sortarray = new String[ht.size()];
i = 0;
Iterator iter = ht.keySet().iterator();
while (iter.hasNext())
{
String key = (String)iter.next();
sortarray[i++] = key;
}
java.util.Arrays.sort(sortarray);
i = 0;
while (i < sortarray.length)
{
rval[i] = (LockDescription)ht.get(sortarray[i]);
i++;
}
return rval;
}
/** Create a file path given a key name.
*@param key is the key name.
*@return the file path.
*/
protected String makeFilePath(String key)
{
int hashcode = key.hashCode();
int outerDirNumber = (hashcode & (1023));
int innerDirNumber = ((hashcode >> 10) & (1023));
String fullDir = synchDirectory;
if (fullDir.length() == 0 || !fullDir.endsWith("/"))
fullDir = fullDir + "/";
fullDir = fullDir + Integer.toString(outerDirNumber)+"/"+Integer.toString(innerDirNumber);
return fullDir;
}
protected class LockDescription
{
protected int lockType;
protected String lockKey;
public LockDescription(int lockType, String lockKey)
{
this.lockType = lockType;
this.lockKey = lockKey;
}
public void set(int lockType)
{
if (lockType > this.lockType)
this.lockType = lockType;
}
public int getType()
{
return lockType;
}
public String getKey()
{
return lockKey;
}
}
protected class LocalLock
{
private int readCount = 0;
private int writeCount = 0;
private int nonExWriteCount = 0;
public LocalLock()
{
}
public boolean hasWriteLock()
{
return (writeCount > 0);
}
public boolean hasReadLock()
{
return (readCount > 0);
}
public boolean hasNonExWriteLock()
{
return (nonExWriteCount > 0);
}
public void incrementReadLocks()
{
readCount++;
}
public void incrementNonExWriteLocks()
{
nonExWriteCount++;
}
public void incrementWriteLocks()
{
writeCount++;
}
public void decrementReadLocks()
{
readCount--;
}
public void decrementNonExWriteLocks()
{
nonExWriteCount--;
}
public void decrementWriteLocks()
{
writeCount--;
}
}
protected static final int BASE_SIZE = 128;
protected static class ByteArrayBuffer
{
protected byte[] buffer;
protected int length;
public ByteArrayBuffer()
{
buffer = new byte[BASE_SIZE];
length = 0;
}
public void add(byte b)
{
if (length == buffer.length)
{
byte[] oldbuffer = buffer;
buffer = new byte[length * 2];
System.arraycopy(oldbuffer,0,buffer,0,length);
}
buffer[length++] = b;
}
public byte[] toArray()
{
byte[] rval = new byte[length];
System.arraycopy(buffer,0,rval,0,length);
return rval;
}
}
}
|
Implement local objects to allow a single LCF process to run without using a synchdirectory. This is, once again, meant to help LCF run as a single process for executing tests.
git-svn-id: 0503cfb7d358eaa9bd718f348f448f10022ea703@952264 13f79535-47bb-0310-9956-ffa450edef68
|
modules/framework/core/org/apache/lcf/core/lockmanager/LockManager.java
|
Implement local objects to allow a single LCF process to run without using a synchdirectory. This is, once again, meant to help LCF run as a single process for executing tests.
|
|
Java
|
apache-2.0
|
298abd331aed7406371a835bce877a203d9da900
| 0
|
redisson/redisson
|
/**
* Copyright (c) 2013-2021 Nikita Koksharov
*
* 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.redisson.executor;
import io.netty.buffer.ByteBufUtil;
import org.redisson.RedissonExecutorService;
import org.redisson.api.RFuture;
import org.redisson.client.codec.Codec;
import org.redisson.client.codec.LongCodec;
import org.redisson.client.codec.StringCodec;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.executor.params.ScheduledParameters;
import org.redisson.remote.RemoteServiceRequest;
import org.redisson.remote.ResponseEntry;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ThreadLocalRandom;
/**
*
* @author Nikita Koksharov
*
*/
public class ScheduledTasksService extends TasksService {
private String requestId;
public ScheduledTasksService(Codec codec, String name, CommandAsyncExecutor commandExecutor, String redissonId, ConcurrentMap<String, ResponseEntry> responses) {
super(codec, name, commandExecutor, redissonId, responses);
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
@Override
protected CompletableFuture<Boolean> addAsync(String requestQueueName, RemoteServiceRequest request) {
ScheduledParameters params = (ScheduledParameters) request.getArgs()[0];
params.setRequestId(request.getId());
long expireTime = 0;
if (params.getTtl() > 0) {
expireTime = System.currentTimeMillis() + params.getTtl();
}
RFuture<Boolean> f = commandExecutor.evalWriteNoRetryAsync(name, LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
// check if executor service not in shutdown state
"if redis.call('exists', KEYS[2]) == 0 then "
+ "local retryInterval = redis.call('get', KEYS[6]); "
+ "if retryInterval ~= false then "
+ "local time = tonumber(ARGV[1]) + tonumber(retryInterval);"
+ "redis.call('zadd', KEYS[3], time, 'ff' .. ARGV[2]);"
+ "elseif tonumber(ARGV[4]) > 0 then "
+ "redis.call('set', KEYS[6], ARGV[4]);"
+ "local time = tonumber(ARGV[1]) + tonumber(ARGV[4]);"
+ "redis.call('zadd', KEYS[3], time, 'ff' .. ARGV[2]);"
+ "end; "
+ "if tonumber(ARGV[5]) > 0 then "
+ "redis.call('zadd', KEYS[7], ARGV[5], ARGV[2]);"
+ "end; "
+ "redis.call('zadd', KEYS[3], ARGV[1], ARGV[2]);"
+ "redis.call('hset', KEYS[5], ARGV[2], ARGV[3]);"
+ "redis.call('incr', KEYS[1]);"
+ "local v = redis.call('zrange', KEYS[3], 0, 0); "
// if new task added to queue head then publish its startTime
// to all scheduler workers
+ "if v[1] == ARGV[2] then "
+ "redis.call('publish', KEYS[4], ARGV[1]); "
+ "end "
+ "return 1;"
+ "end;"
+ "return 0;",
Arrays.asList(tasksCounterName, statusName, schedulerQueueName,
schedulerChannelName, tasksName, tasksRetryIntervalName, tasksExpirationTimeName),
params.getStartTime(), request.getId(), encode(request), tasksRetryInterval, expireTime);
return f.toCompletableFuture();
}
@Override
protected CompletableFuture<Boolean> removeAsync(String requestQueueName, String taskId) {
RFuture<Boolean> f = commandExecutor.evalWriteNoRetryAsync(name, StringCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
// remove from scheduler queue
"if redis.call('exists', KEYS[3]) == 0 then "
+ "return 1;"
+ "end;"
+ "local task = redis.call('hget', KEYS[6], ARGV[1]); "
+ "redis.call('hdel', KEYS[6], ARGV[1]); "
+ "redis.call('zrem', KEYS[2], 'ff' .. ARGV[1]); "
+ "local removedScheduled = redis.call('zrem', KEYS[2], ARGV[1]); "
+ "local removed = redis.call('lrem', KEYS[1], 1, ARGV[1]); "
// remove from executor queue
+ "if task ~= false and (removed > 0 or removedScheduled > 0) then "
+ "if redis.call('decr', KEYS[3]) == 0 then "
+ "redis.call('del', KEYS[3]);"
+ "if redis.call('get', KEYS[4]) == ARGV[2] then "
+ "redis.call('del', KEYS[7]);"
+ "redis.call('set', KEYS[4], ARGV[3]);"
+ "redis.call('publish', KEYS[5], ARGV[3]);"
+ "end;"
+ "end;"
+ "return 1;"
+ "end;"
+ "if task == false then "
+ "return 1; "
+ "end;"
+ "return 0;",
Arrays.asList(requestQueueName, schedulerQueueName, tasksCounterName, statusName,
terminationTopicName, tasksName, tasksRetryIntervalName),
taskId, RedissonExecutorService.SHUTDOWN_STATE, RedissonExecutorService.TERMINATED_STATE);
return f.toCompletableFuture();
}
@Override
protected long getTimeout(Long executionTimeoutInMillis, RemoteServiceRequest request) {
if (request.getArgs()[0].getClass() == ScheduledParameters.class) {
ScheduledParameters params = (ScheduledParameters) request.getArgs()[0];
return executionTimeoutInMillis + params.getStartTime() - System.currentTimeMillis();
}
return executionTimeoutInMillis;
}
@Override
protected String generateRequestId(Object[] args) {
if (requestId == null) {
byte[] id = new byte[17];
ThreadLocalRandom.current().nextBytes(id);
id[0] = 01;
return ByteBufUtil.hexDump(id);
}
return requestId;
}
}
|
redisson/src/main/java/org/redisson/executor/ScheduledTasksService.java
|
/**
* Copyright (c) 2013-2021 Nikita Koksharov
*
* 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.redisson.executor;
import io.netty.buffer.ByteBufUtil;
import org.redisson.RedissonExecutorService;
import org.redisson.api.RFuture;
import org.redisson.client.codec.Codec;
import org.redisson.client.codec.LongCodec;
import org.redisson.client.codec.StringCodec;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.executor.params.ScheduledParameters;
import org.redisson.remote.RemoteServiceRequest;
import org.redisson.remote.ResponseEntry;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ThreadLocalRandom;
/**
*
* @author Nikita Koksharov
*
*/
public class ScheduledTasksService extends TasksService {
private String requestId;
public ScheduledTasksService(Codec codec, String name, CommandAsyncExecutor commandExecutor, String redissonId, ConcurrentMap<String, ResponseEntry> responses) {
super(codec, name, commandExecutor, redissonId, responses);
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
@Override
protected CompletableFuture<Boolean> addAsync(String requestQueueName, RemoteServiceRequest request) {
ScheduledParameters params = (ScheduledParameters) request.getArgs()[0];
params.setRequestId(request.getId());
long expireTime = 0;
if (params.getTtl() > 0) {
expireTime = System.currentTimeMillis() + params.getTtl();
}
RFuture<Boolean> f = commandExecutor.evalWriteNoRetryAsync(name, LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
// check if executor service not in shutdown state
"if redis.call('exists', KEYS[2]) == 0 then "
+ "local retryInterval = redis.call('get', KEYS[6]); "
+ "if retryInterval ~= false then "
+ "local time = tonumber(ARGV[1]) + tonumber(retryInterval);"
+ "redis.call('zadd', KEYS[3], time, 'ff' .. ARGV[2]);"
+ "elseif tonumber(ARGV[4]) > 0 then "
+ "redis.call('set', KEYS[6], ARGV[4]);"
+ "local time = tonumber(ARGV[1]) + tonumber(ARGV[4]);"
+ "redis.call('zadd', KEYS[3], time, 'ff' .. ARGV[2]);"
+ "end; "
+ "if tonumber(ARGV[5]) > 0 then "
+ "redis.call('zadd', KEYS[7], ARGV[5], ARGV[2]);"
+ "end; "
+ "redis.call('zadd', KEYS[3], ARGV[1], ARGV[2]);"
+ "redis.call('hset', KEYS[5], ARGV[2], ARGV[3]);"
+ "redis.call('incr', KEYS[1]);"
+ "local v = redis.call('zrange', KEYS[3], 0, 0); "
// if new task added to queue head then publish its startTime
// to all scheduler workers
+ "if v[1] == ARGV[2] then "
+ "redis.call('publish', KEYS[4], ARGV[1]); "
+ "end "
+ "return 1;"
+ "end;"
+ "return 0;",
Arrays.asList(tasksCounterName, statusName, schedulerQueueName,
schedulerChannelName, tasksName, tasksRetryIntervalName, tasksExpirationTimeName),
params.getStartTime(), request.getId(), encode(request), tasksRetryInterval, expireTime);
return f.toCompletableFuture();
}
@Override
protected CompletableFuture<Boolean> removeAsync(String requestQueueName, String taskId) {
RFuture<Boolean> f = commandExecutor.evalWriteNoRetryAsync(name, StringCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
// remove from scheduler queue
"if redis.call('exists', KEYS[3]) == 0 then "
+ "return 1;"
+ "end;"
+ "local task = redis.call('hget', KEYS[6], ARGV[1]); "
+ "redis.call('hdel', KEYS[6], ARGV[1]); "
+ "redis.call('zrem', KEYS[2], 'ff' .. ARGV[1]); "
+ "local removedScheduled = redis.call('zrem', KEYS[2], ARGV[1]); "
+ "local removed = redis.call('lrem', KEYS[1], 1, ARGV[1]); "
// remove from executor queue
+ "if task ~= false and (removed > 0 or removedScheduled > 0) then "
+ "if redis.call('decr', KEYS[3]) == 0 then "
+ "redis.call('del', KEYS[3]);"
+ "if redis.call('get', KEYS[4]) == ARGV[2] then "
+ "redis.call('del', KEYS[7]);"
+ "redis.call('set', KEYS[4], ARGV[3]);"
+ "redis.call('publish', KEYS[5], ARGV[3]);"
+ "end;"
+ "end;"
+ "return 1;"
+ "end;"
+ "if task == false then "
+ "return 1; "
+ "end;"
+ "return 0;",
Arrays.asList(requestQueueName, schedulerQueueName, tasksCounterName, statusName,
terminationTopicName, tasksName, tasksRetryIntervalName),
taskId.toString(), RedissonExecutorService.SHUTDOWN_STATE, RedissonExecutorService.TERMINATED_STATE);
return f.toCompletableFuture();
}
@Override
protected long getTimeout(Long executionTimeoutInMillis, RemoteServiceRequest request) {
if (request.getArgs()[0].getClass() == ScheduledParameters.class) {
ScheduledParameters params = (ScheduledParameters) request.getArgs()[0];
return executionTimeoutInMillis + params.getStartTime() - System.currentTimeMillis();
}
return executionTimeoutInMillis;
}
@Override
protected String generateRequestId(Object[] args) {
if (requestId == null) {
byte[] id = new byte[17];
ThreadLocalRandom.current().nextBytes(id);
id[0] = 01;
return ByteBufUtil.hexDump(id);
}
return requestId;
}
}
|
refactoring
|
redisson/src/main/java/org/redisson/executor/ScheduledTasksService.java
|
refactoring
|
|
Java
|
apache-2.0
|
91810804a63d6d0954a8be67b571448f5025f781
| 0
|
osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi
|
package org.osgi.service.application.midlet;
import java.util.Map;
import org.osgi.service.application.ApplicationDescriptor;
import org.osgi.service.application.ApplicationHandle;
public final class MidletDescriptor extends ApplicationDescriptor {
protected ApplicationHandle launchSpecific(Map arguments) throws Exception {
return delegate.launchSpecific( arguments );
}
protected Map getPropertiesSpecific(String locale) {
return delegate.getPropertiesSpecific( locale );
}
protected void lockSpecific() {
delegate.lockSpecific();
}
protected void unlockSpecific() {
delegate.unlockSpecific();
}
protected MidletDescriptor(String pid) {
super( pid );
try {
delegate = (Delegate) implementation
.newInstance();
delegate.setMidletDescriptor( this );
}
catch (Exception e) {
// Too bad ...
e.printStackTrace();
System.err
.println("No implementation available for ApplicationDescriptor, property is: "
+ cName);
}
}
Delegate delegate;
String pid;
static Class implementation;
static String cName;
static
{
try {
cName = System
.getProperty("org.osgi.vendor.application.midlet.MidletDescriptor");
implementation = Class.forName(cName);
}
catch (Throwable t) {
// Ignore
}
}
public interface Delegate {
void setMidletDescriptor( MidletDescriptor descriptor );
ApplicationHandle launchSpecific(Map arguments) throws Exception;
Map getPropertiesSpecific(String locale);
void lockSpecific();
void unlockSpecific();
}
}
|
org.osgi.service.application/src/org/osgi/service/application/midlet/MidletDescriptor.java
|
package org.osgi.service.application.midlet;
import java.util.Map;
import org.osgi.service.application.ApplicationDescriptor;
import org.osgi.service.application.ApplicationHandle;
public final class MidletDescriptor extends ApplicationDescriptor {
protected ApplicationHandle launchSpecific(Map arguments) throws Exception {
return delegate.launchSpecific( arguments );
}
protected Map getPropertiesSpecific(String locale) {
return delegate.getPropertiesSpecific( locale );
}
protected void lockSpecific() {
delegate.lockSpecific();
}
protected void unlockSpecific() {
delegate.unlockSpecific();
}
protected MidletDescriptor(String pid) {
super( pid );
try {
delegate = (Delegate) implementation
.newInstance();
delegate.setMidletDescriptor( this );
}
catch (Exception e) {
// Too bad ...
e.printStackTrace();
System.err
.println("No implementation available for ApplicationDescriptor, property is: "
+ cName);
}
}
Delegate delegate;
String pid;
static Class implementation;
static String cName;
{
try {
cName = System
.getProperty("org.osgi.vendor.application.meglet.MegletDescriptor");
implementation = Class.forName(cName);
}
catch (Throwable t) {
// Ignore
}
}
public interface Delegate {
void setMidletDescriptor( MidletDescriptor descriptor );
ApplicationHandle launchSpecific(Map arguments) throws Exception;
Map getPropertiesSpecific(String locale);
void lockSpecific();
void unlockSpecific();
}
}
|
FIXED: wrong descriptor value
|
org.osgi.service.application/src/org/osgi/service/application/midlet/MidletDescriptor.java
|
FIXED: wrong descriptor value
|
|
Java
|
apache-2.0
|
cce832b4e5e9845f9036ad4188e2f0ee354ebe68
| 0
|
wcmc-its/ReCiter,wcmc-its/ReCiter
|
package reciter.algorithm.evidence.targetauthor.name.strategy;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reciter.algorithm.cluster.article.scorer.ReCiterArticleScorer;
import reciter.algorithm.evidence.targetauthor.AbstractTargetAuthorStrategy;
import reciter.algorithm.util.ReCiterStringUtil;
import reciter.engine.Feature;
import reciter.engine.analysis.evidence.AuthorNameEvidence;
import reciter.model.article.ReCiterArticle;
import reciter.model.article.ReCiterAuthor;
import reciter.model.identity.AuthorName;
import reciter.model.identity.Identity;
/**
* @author szd2013
* This class scores ReCiterArticles based on name and assigns score for each part of the name - first, middle and last
*
*/
public class ScoreByNameStrategy extends AbstractTargetAuthorStrategy {
private static final Logger slf4jLogger = LoggerFactory.getLogger(ScoreByNameStrategy.class);
@Override
public double executeStrategy(List<ReCiterArticle> reCiterArticles, Identity identity) {
List<AuthorName> sanitizedIdentityAuthor = new ArrayList<AuthorName>();
Set<AuthorName> sanitizedTargetAuthor = new HashSet<AuthorName>();
AuthorNameEvidence authorNameEvidence;
if(identity != null) {
sanitizeIdentityAuthorNames(identity, sanitizedIdentityAuthor);
checkToIgnoreNameVariants(sanitizedIdentityAuthor);
}
List<AuthorNameEvidence> authorNameEvidences = new ArrayList<AuthorNameEvidence>(sanitizedIdentityAuthor.size());
for(ReCiterArticle reCiterArticle: reCiterArticles) {
int targetAuthorCount = getTargetAuthorCount(reCiterArticle);
if(targetAuthorCount >=1) {
sanitizeTargetAuthorNames(reCiterArticle, sanitizedTargetAuthor);
for(AuthorName identityAuthorName: sanitizedIdentityAuthor) {
authorNameEvidence = new AuthorNameEvidence();
//Combine following identity.middleName, identity.lastName into mergedName. Now attempt match against article.lastName.
//Example: Garcia (identity.middleName) + Marquez (identity.lastName) = GarciaMarques (article.lastName)
//If match: stop scoring middle and last name; move on to only score first name;
scoreCombinedMiddleLastName(identityAuthorName, sanitizedTargetAuthor, authorNameEvidence);
if(authorNameEvidence.getNameMatchFirstType() != null
&&
authorNameEvidence.getNameMatchMiddleType() != null
&&
authorNameEvidence.getNameMatchLastType() != null
&&
authorNameEvidence.getNameMatchModifier() != null) {
slf4jLogger.info("Combine following identity.middleName, identity.lastName into mergedName. Now attempt match against article.lastName.");
}
else {
scoreLastName(identityAuthorName, sanitizedTargetAuthor, authorNameEvidence);
if(!isNotNullIdentityMiddleName(sanitizedIdentityAuthor)) {
scoreFirstNameMiddleNameNull(identityAuthorName, sanitizedTargetAuthor, authorNameEvidence);
} else {
if(identityAuthorName.getMiddleName() == null) {
scoreFirstNameMiddleNameNull(identityAuthorName, sanitizedTargetAuthor, authorNameEvidence);
} else {
scoreFirstNameMiddleName(identityAuthorName, sanitizedTargetAuthor, authorNameEvidence);
}
}
}
if(authorNameEvidence.getNameMatchMiddleType() != null
&&
StringUtils.equalsIgnoreCase(authorNameEvidence.getNameMatchMiddleType(), "full-exact")
&&
identityAuthorName.getMiddleName() != null
&&
identityAuthorName.getMiddleName().length() == 1) {
authorNameEvidence.setNameMatchMiddleType("exact-singleInitial");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeExactSingleInitialScore());
authorNameEvidence.setNameScoreTotal(authorNameEvidence.getNameMatchFirstScore() + authorNameEvidence.getNameMatchLastScore() + authorNameEvidence.getNameMatchMiddleScore() + authorNameEvidence.getNameMatchModifierScore());
}
authorNameEvidences.add(authorNameEvidence);
}
authorNameEvidence = calculateHighestScore(authorNameEvidences);
//Clear the target author set
if(sanitizedTargetAuthor != null
&&
sanitizedTargetAuthor.size() > 0) {
sanitizedTargetAuthor.clear();
}
//Clear AuthorNameEvidences
if(authorNameEvidences != null
&&
authorNameEvidences.size() > 0) {
authorNameEvidences.clear();
}
} else {
authorNameEvidence = new AuthorNameEvidence();
authorNameEvidence.setInstitutionalAuthorName(identity.getPrimaryName());
authorNameEvidence.setNameMatchFirstType("nullTargetAuthor-MatchNotAttempted");
authorNameEvidence.setNameMatchLastType("nullTargetAuthor-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleType("nullTargetAuthor-MatchNotAttempted");
}
reCiterArticle.setAuthorNameEvidence(authorNameEvidence);
slf4jLogger.info("Pmid: " + reCiterArticle.getArticleId() + " " + authorNameEvidence.toString());
}
return 1;
}
private void scoreCombinedMiddleLastName(AuthorName identityAuthor, Set<AuthorName> articleAuthorNames, AuthorNameEvidence authorNameEvidence) {
if(articleAuthorNames.size() > 0) {
AuthorName articleAuthorName = articleAuthorNames.iterator().next();
if(identityAuthor.getMiddleName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getMiddleName() + identityAuthor.getLastName()), ReCiterStringUtil.deAccent(articleAuthorName.getLastName()))
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))
) {
//Combine following identity.middleName, identity.lastName into mergedName. Now attempt match against article.lastName.
//Example: Garcia (identity.middleName) + Marquez (identity.lastName) = GarciaMarquez (article.lastName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchLastType("full-exact");
authorNameEvidence.setNameMatchLastScore(ReCiterArticleScorer.strategyParameters.getNameMatchLastTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("combinedMiddleNameLastName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierCombinedMiddleNameLastNameScore());
} else if(identityAuthor.getMiddleName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getMiddleName() + identityAuthor.getLastName()), ReCiterStringUtil.deAccent(articleAuthorName.getLastName()))
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstInitial()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchLastType("full-exact");
authorNameEvidence.setNameMatchLastScore(ReCiterArticleScorer.strategyParameters.getNameMatchLastTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("combinedMiddleNameLastName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierCombinedMiddleNameLastNameScore());
}
authorNameEvidence.setInstitutionalAuthorName(identityAuthor);
authorNameEvidence.setArticleAuthorName(articleAuthorName);
authorNameEvidence.setNameScoreTotal(authorNameEvidence.getNameMatchFirstScore() + authorNameEvidence.getNameMatchMiddleScore() + authorNameEvidence.getNameMatchLastScore() + authorNameEvidence.getNameMatchModifierScore());
}
}
private void scoreLastName(AuthorName identityAuthor, Set<AuthorName> articleAuthorNames, AuthorNameEvidence authorNameEvidence) {
if(articleAuthorNames.size() > 0) {
AuthorName articleAuthorName = articleAuthorNames.iterator().next();
if(StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getLastName()), ReCiterStringUtil.deAccent(articleAuthorName.getLastName()))) {
//Attempt full exact match where identity.lastName = article.lastName.
//Example: Cole (identity.lastName) = Cole (article.lastName)
authorNameEvidence.setNameMatchLastType("full-exact");
authorNameEvidence.setNameMatchLastScore(ReCiterArticleScorer.strategyParameters.getNameMatchLastTypeFullExactScore());
} else if(identityAuthor.getMiddleName() != null && ReCiterStringUtil.deAccent(identityAuthor.getLastName()).contains(ReCiterStringUtil.deAccent(articleAuthorName.getLastName()))) {
//Attempt partial match where "%" + identity.lastName + "%" = article.lastName
//Example: Cole (identity.lastName) = Del Cole (article.lastName)
authorNameEvidence.setNameMatchLastType("full-exact");
authorNameEvidence.setNameMatchLastScore(ReCiterArticleScorer.strategyParameters.getNameMatchLastTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-lastName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleLastnameScore());
} else if(identityAuthor.getLastName().length() >= 4 && ReCiterStringUtil.levenshteinDistance(ReCiterStringUtil.deAccent(identityAuthor.getLastName()), ReCiterStringUtil.deAccent(articleAuthorName.getLastName())) <= 1) {
//Attempt match where identity.lastName >= 4 characters and levenshteinDistance between identity.lastName and article.lastName is <=1.
//Example: Kaushal (identity.lastName) = Kaushai (article.lastName)
authorNameEvidence.setNameMatchLastType("full-fuzzy");
authorNameEvidence.setNameMatchLastScore(ReCiterArticleScorer.strategyParameters.getNameMatchLastTypeFullFuzzyScore());
} else {
authorNameEvidence.setNameMatchLastType("full-conflictingEntirely");
authorNameEvidence.setNameMatchLastScore(ReCiterArticleScorer.strategyParameters.getNameMatchLastTypeFullConflictingEntirelyScore());
}
authorNameEvidence.setInstitutionalAuthorName(identityAuthor);
authorNameEvidence.setArticleAuthorName(articleAuthorName);
authorNameEvidence.setNameScoreTotal(authorNameEvidence.getNameMatchFirstScore() + authorNameEvidence.getNameMatchMiddleScore() + authorNameEvidence.getNameMatchLastScore() + authorNameEvidence.getNameMatchModifierScore());
}
}
/** This function matches and scores first name and middle name where middle name is null in identity
* All of the matching that follows should be evaluated as a series of ifElse statements (once we get a match, we stop). The goal is to match as early on in the process as possible.
* Matching should be case insensitive, however, we will pull out some characters below based on case.
*/
private void scoreFirstNameMiddleNameNull(AuthorName identityAuthor, Set<AuthorName> articleAuthorNames, AuthorNameEvidence authorNameEvidence) {
if(articleAuthorNames.size() > 0) {
AuthorName articleAuthorName = articleAuthorNames.iterator().next();
if(identityAuthor.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.firstName = article.firstName
//Example: Paul (identity.firstName) = Paul (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
} else if(identityAuthor.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).startsWith(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()))) {
//Attempt match where identity.firstName is a left-anchored substring of article.firstName
//Example: Paul (identity.firstName) = PaulJames (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstnameScore());
} else if(identityAuthor.getFirstName() != null
&&
ReCiterStringUtil.deAccent(identityAuthor.getFirstName()).startsWith(ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where article.firstName is a left-anchored substring of identity.firstName
//Example: Paul (identity.firstName) = P (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getFirstName().length() >= 3
&&
articleAuthorName.getFirstName().length() >= 3
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName().substring(0, 2)),ReCiterStringUtil.deAccent(articleAuthorName.getFirstName().substring(0, 2)))) {
//Attempt match where first three characters of identity.firstName = first three characters of article.firstName
//Example: Paul (identity.firstName) = Pau (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-fuzzy");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullFuzzyScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getFirstName().length() >= 4
&&
ReCiterStringUtil.levenshteinDistance(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName())) == 1) {
//Attempt match where identity.firstName is greater than 4 characters and Levenshtein distance between identity.firstName and article.firstName is 1.
//Example: Paula (identity.firstName) = Pauly (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-fuzzy");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullFuzzyScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
} else if(identityAuthor.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstInitial()),ReCiterStringUtil.deAccent(articleAuthorName.getFirstInitial()))) {
//Attempt match where first character of identity.firstName = first character of article.firstName
//Example: Paul (identity.firstName) = Peter (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-conflictingAllButInitials");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullConflictingAllButInitialsScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
} else {
authorNameEvidence.setNameMatchFirstType("full-conflictingEntirely");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullConflictingEntirelyScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
}
authorNameEvidence.setInstitutionalAuthorName(identityAuthor);
authorNameEvidence.setArticleAuthorName(articleAuthorName);
authorNameEvidence.setNameScoreTotal(authorNameEvidence.getNameMatchFirstScore() + authorNameEvidence.getNameMatchMiddleScore() + authorNameEvidence.getNameMatchLastScore() + authorNameEvidence.getNameMatchModifierScore());
}
}
/**
* We need to score first and middle names in conjunction with each other, because PubMed and Scopus combine them into a single field; also, it's often the case that first and middle names are conflated in identity systems of record.
All of the matching that follows should be evaluated as a series of ifElse statements (once we get a match, we stop). The goal is to match as early on in the process as possible.
It's conceivable that we can use the firstName from one alias in conjunction with the middleName of another to match to our article. We can use any combination of first and middle names to do the matching.
Preprocessing: ignore/discard name variants in which it's pretty clear that one name variant has a middle name that is an abbreviation of another.
Example: there are two name variants for ajdannen:
"Andrew[firstName] + Jess[middleName] + Dannenberg[lastName]"
"Andrew[firstName] + J[middleName] + Dannenberg[lastName]"
In cases where one of the middle names is a left-anchored substring of the other, discard/ignore the shorter one.
* @param identityAuthor
* @param articleAuthorNames
* @param authorNameEvidence
*/
private void scoreFirstNameMiddleName(AuthorName identityAuthor, Set<AuthorName> articleAuthorNames, AuthorNameEvidence authorNameEvidence) {
if(articleAuthorNames.size() > 0) {
AuthorName articleAuthorName = articleAuthorNames.iterator().next();
if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName() + identityAuthor.getMiddleName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.firstName + identity.middleName = article.firstName
//Example: Paul (identity.firstName) + James (identity.middleName) = PaulJames (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()) + "(.*)" + ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()))) {
//Attempt match where identity.firstName + "%" + identity.middleName = article.firstName
//Example: Paul (identity.firstName) + James (identity.middleName) = PaulaJames (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstMiddleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName() + identityAuthor.getMiddleInitial()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.firstName + identity.middleInitial = article.firstName
//Example: Paul (identity.firstName) + J (identity.middleInitial) = PaulJ (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("inferredInitials-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeInferredInitialsExactScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()) + "(.*)" + ReCiterStringUtil.deAccent(identityAuthor.getMiddleInitial()))) {
//Attempt match where identity.firstName + "%" + identity.middleInitial = article.firstName
//Example: Paul (identity.firstName) + J (identity.middleInitial) = PaulaJ (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("inferredInitials-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstMiddleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstInitial() + identityAuthor.getMiddleInitial()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.firstInitial + identity.middleInitial = article.firstName
//Example: P (identity.firstInitial) + J (identity.middleInitial) = PJ (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("inferredInitials-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeInferredInitialsExactScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstInitial() + identityAuthor.getMiddleName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.firstInitial + identity.middleName = article.firstName
//Example: M (identity.firstInitial) + Carrington (identity.middleName) = MCarrington (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()) + ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()) + "(.*)")) {
//Attempt match where identity.firstName + identity.middleName + "%" = article.firstName
//Example: Paul (identity.firstName) + James (identity.middleName) = PaulJamesA (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstMiddleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()) + ReCiterStringUtil.deAccent(identityAuthor.getMiddleInitial()) + "(.*)")) {
//Attempt match where identity.firstName + identity.middleInitial + "%" = article.firstName
//Example: Paul (identity.firstName) + J (identity.middleInitial) = PaulJZ (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("inferredInitials-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstMiddleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.firstName = article.firstName
//Example: Paul (identity.firstName) = Paul (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getMiddleInitial() + identityAuthor.getFirstInitial()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("inferredInitials-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchModifier("incorrectOrder");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIncorrectOrderScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
(identityAuthor.getFirstName().codePoints().filter(c-> c>='A' && c<='Z').count() > 1 || identityAuthor.getMiddleName().codePoints().filter(c-> c>='A' && c<='Z').count() > 1) //check if there is more than 1 capital letters
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()).chars().filter(Character::isUpperCase)
.mapToObj(c -> Character.toString((char)c))
.collect(Collectors.joining()) +
ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()).chars().filter(Character::isUpperCase)
.mapToObj(c -> Character.toString((char)c))
.collect(Collectors.joining()),
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//If there's more than one capital letter in identity.firstName or identity.middleName, attempt match where any capitals in identity.firstName + any capital letters in identity.middleName = article.firstName
//Example: KS (identity.initialsInFirstName) + C (identity.initialsInMiddleName) = KSC (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("inferredInitials-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeInferredInitialsExactScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
identityAuthor.getFirstName().codePoints().filter(c-> c>='A' && c<='Z').count() > 1 //check if there is more than 1 capital letters
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()).chars().filter(Character::isUpperCase)
.mapToObj(c -> Character.toString((char)c))
.collect(Collectors.joining()) ,
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//If there's more than one capital letter in identity.firstName, attempt match where any capitals in identity.firstName = article.firstName
//Example: KS (identity.initialsInFirstName) = KS (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
identityAuthor.getFirstName().codePoints().filter(c-> c>='A' && c<='Z').count() > 1 && //check if there is more than 1 capital letters
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()).chars().filter(Character::isUpperCase)
.mapToObj(c -> Character.toString((char)c))
.collect(Collectors.joining()) + identityAuthor.getMiddleName() ,
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//If there's more than one capital letter in identity.firstName, attempt match where any capitals in identity.firstName + identity.middleName = article.firstName
//Example: KS (identity.initialsInFirstName) + Clifford (identity.middleName) = KSClifford (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()) + "(.*)")) {
//Attempt match where identity.firstName + "%" = article.firstName
//Example: Robert (identity.firstName) = RobertR (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstnameScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches("(.*)" + ReCiterStringUtil.deAccent(identityAuthor.getFirstName()))) {
//Attempt match where "%" + identity.firstName = article.firstName
//Example: Cary (identity.firstName) = MCary (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstnameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.middleName = article.firstName
//Example: Clifford (identity.middleName) = Clifford (article.firstName)
authorNameEvidence.setNameMatchFirstType("noMatch");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeNoMatchScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()) + "(.*)")) {
//Attempt match where identity.middleName + "%" = article.firstName
//Example: Clifford (identity.middleName) = CliffordKS (article.firstName)
authorNameEvidence.setNameMatchFirstType("noMatch");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeNoMatchScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-middleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches("(.*)" + ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()))) {
//Attempt match where "%" + identity.middleName = article.firstName
//Example: Clifford (identity.middleName) = KunSungClifford (article.firstName)
authorNameEvidence.setNameMatchFirstType("noMatch");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeNoMatchScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-middleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.levenshteinDistance(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()) + ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName())) <= 2) {
//Attempt match where levenshteinDistance between identity.firstName + identity.middleName and article.firstName is <=2.
//Example: Manney (identity.firstName) + Carrington (identity.middleName) = MannyCarrington (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-fuzzy");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullFuzzyScore());
authorNameEvidence.setNameMatchMiddleType("full-fuzzy");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullFuzzyScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
identityAuthor.getFirstName().length() >= 4
&&
ReCiterStringUtil.levenshteinDistance(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName())) <= 1) {
//Attempt match where identity.firstName >= 4 characters and levenshteinDistance between identity.firstName and article.firstName is <=1.
//Example: Nassar (identity.firstName) = Nasser (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-fuzzy");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullFuzzyScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
identityAuthor.getFirstName().length() >=3
&&
articleAuthorName.getFirstName().length() >=3
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName().substring(0, 3)),ReCiterStringUtil.deAccent(articleAuthorName.getFirstName().substring(0, 3)))) {
//Attempt match where first three characters of identity.firstName = first three characters of identity.firstName.
//Example: Massimiliano (identity.firstName) = Massimo (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-fuzzy");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullFuzzyScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getFirstInitial()) + "(.*)" + ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()))) {
//Attempt match where identity.firstInitial + "%" + identity.middleName = article.firstName
//Example: M (identity.firstInitial) + Carrington (identity.middleName) = MannyCarrington (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstMiddleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getMiddleName() + identityAuthor.getFirstInitial()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.middleName + identity.firstInitial = article.firstName
//Example: Carrington (identity.middleName) + M (identity.firstInitial) = CarringtonM (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("incorrectOrder");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIncorrectOrderScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
articleAuthorName.getFirstName().length() == 1
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstInitial()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where article.firstName is only one character and identity.firstName = first character of article.firstName.
//Example: Jessica (identity.firstName) = J (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
identityAuthor.getFirstName().length() > 0
&&
articleAuthorName.getFirstName().length() > 0
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName().substring(0, 1)), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName().substring(0, 1)))) {
//Attempt match where first character of identity.firstName = first character of identity.firstName.
//Example: Jessica (identity.firstName) = Jochen (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-conflictingAllButInitials");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullConflictingAllButInitialsScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
} else {
//Else, we have no match of any kind.
//Example: Pascale vs. Curtis
authorNameEvidence.setNameMatchFirstType("full-conflictingEntirely");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullConflictingEntirelyScore());
authorNameEvidence.setNameMatchMiddleType("full-conflictingEntirely");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullConflictingEntirelyScore());
}
authorNameEvidence.setInstitutionalAuthorName(identityAuthor);
authorNameEvidence.setArticleAuthorName(articleAuthorName);
authorNameEvidence.setNameScoreTotal(authorNameEvidence.getNameMatchFirstScore() + authorNameEvidence.getNameMatchMiddleScore() + authorNameEvidence.getNameMatchLastScore() + authorNameEvidence.getNameMatchModifierScore());
}
}
private int getTargetAuthorCount(ReCiterArticle reCiterArticle) {
int targetAuthorCount = 0;
for(ReCiterAuthor targetAuthorName: reCiterArticle.getArticleCoAuthors().getAuthors()) {
if(targetAuthorName.isTargetAuthor()) {
targetAuthorCount++;
}
}
return targetAuthorCount;
}
/**
* @author szd2013
* Preprocess identity.firstName, identity.middleName, and article.firstName
If any names are in quotes or parentheses in identity.firstName or identity.middleName, pull them out so they can be matched against.
Wing Tak "Jack" --> add "Jack" to identity.firstName, add "Wing Tak" to identity.firstName
Qihui (Jim) --> add Jim to identity.firstName, add Qihui to identity.firstName
Remove any periods, spaces, or dashes from both identity.firstName, identity.middleName, and article.firstName. For example:
"Chi-chao" --> "Chichao"
"Minh-Nhut Yvonne" --> "MinhNhutYvonne"
"Eliot A." --> "EliotA"
Disregard any cases where one variant of identity.firstName is a substring of another case of identity.firstName. Disregard any cases where one variant of identity.middleName is a substring of another case of identity.middleName. For example:
"Cary" (keep) vs "C" (disregard)
Null for middle name should only be included as possible value if none of the names or aliases contain a middle name
A given target author might have N different first names and M different middle names.
Go to D
Retrieve article.lastName where targetAuthor=TRUE and all distinct cases of identity.lastName for our target author from identity. Preprocess identity.lastName and article.lastName.
Remove any periods from both identity.lastName and article.lastName
Remove any of the following endings from identity.lastName:
", Jr"
", MD PhD"
", MD-PhD"
", PhD"
", MD"
", III"
", II"
", Sr"
" Jr"
" MD PhD"
" MD-PhD"
" PhD"
" MD"
" III"
" II"
" Sr"
Remove any periods, spaces, dashes, or quotes.
For example:
"Del Cole" --> "Delcole"
"Garcia-Marquez" --> ""GarciaMarquez"
"Capetillo Gonzalez de Zarate" --> "CapetilloGonzalezdeZarate"
*
*/
private void sanitizeIdentityAuthorNames(Identity identity, List<AuthorName> sanitizedIdentityAuthorName) {
AuthorName identityPrimaryName = new AuthorName();
AuthorName additionalName = new AuthorName();
String firstName = null;
String lastName = null;
String middleName = null;
//Sanitize Identity Names
if(identity.getPrimaryName() != null) {
if(identity.getPrimaryName().getFirstName() != null) {
if(identity.getPrimaryName().getFirstName().contains("\"") || (identity.getPrimaryName().getFirstName().contains("(") && identity.getPrimaryName().getFirstName().contains(")"))) {
firstName = identity.getPrimaryName().getFirstName().replaceAll("[-.,()\\s]", "").replaceAll("\"([^\"]*)\"|(\"([^\"]*)\")|(([a-z]*))/i/g", "");
if(firstName !=null) {
additionalName.setFirstName(firstName);
}
Pattern pattern = Pattern.compile("\"([^\"]*)\"|(\"([^\"]*)\")|(([a-z]*))/i/g");
Matcher matcher = pattern.matcher(identity.getPrimaryName().getFirstName());
while(matcher.find()) {
identityPrimaryName.setFirstName(matcher.group().replaceAll("\"", ""));
}
} else {
identityPrimaryName.setFirstName(identity.getPrimaryName().getFirstName().replaceAll("[-.,()\\s]", ""));
}
}
if(identity.getPrimaryName().getMiddleName() != null) {
if(identity.getPrimaryName().getMiddleName().contains("\"") || (identity.getPrimaryName().getMiddleName().contains("(") && identity.getPrimaryName().getMiddleName().contains(")"))) {
middleName = identity.getPrimaryName().getMiddleName().replaceAll("[-.,()\\s]", "").replaceAll("\"([^\"]*)\"|(\"([^\"]*)\")|(([a-z]*))/i/g", "");
if(middleName !=null) {
additionalName.setMiddleName(middleName);
}
Pattern pattern = Pattern.compile("\"([^\"]*)\"|(\"([^\"]*)\")|(([a-z]*))/i/g");
Matcher matcher = pattern.matcher(identity.getPrimaryName().getMiddleName());
while(matcher.find()) {
identityPrimaryName.setMiddleName(matcher.group().replaceAll("\"", ""));
}
} else {
identityPrimaryName.setMiddleName(identity.getPrimaryName().getMiddleName().replaceAll("[-.,()\\s]", ""));
}
}
if(identity.getPrimaryName().getLastName() != null) {
lastName = identity.getPrimaryName().getLastName().replaceAll("[-.,,()\\s]|(,Jr|, Jr|, MD PhD|,MD PhD|, MD-PhD|,MD-PhD|, PhD|,PhD|, MD|,MD|, III|,III|, II|,II|, Sr|,Sr|Jr|MD PhD|MD-PhD|PhD|MD|III|II|Sr)$", "");
identityPrimaryName.setLastName(lastName);
if(additionalName.getFirstName() != null) {
additionalName.setLastName(lastName);
}
}
if(identityPrimaryName.getLastName() != null) {
sanitizedIdentityAuthorName.add(identityPrimaryName);
}
}
if(identity.getAlternateNames() != null && identity.getAlternateNames().size() > 0) {
for(AuthorName aliasAuthorName: identity.getAlternateNames()) {
AuthorName identityAliasAuthorName = new AuthorName();
if(aliasAuthorName.getFirstName() != null) {
identityAliasAuthorName.setFirstName(aliasAuthorName.getFirstName().replaceAll("[-.\",()\\s]", ""));
}
if(aliasAuthorName.getMiddleName() != null) {
identityAliasAuthorName.setMiddleName(aliasAuthorName.getMiddleName().replaceAll("[-.\",()\\s]", ""));
}
if(aliasAuthorName.getLastName() != null) {
identityAliasAuthorName.setLastName(aliasAuthorName.getLastName().replaceAll("[-.\",()\\s]|(,Jr|, Jr|, MD PhD|,MD PhD|, MD-PhD|,MD-PhD|, PhD|,PhD|, MD|,MD|, III|,III|, II|,II|, Sr|,Sr|Jr|MD PhD|MD-PhD|PhD|MD|III|II|Sr)$", ""));
}
if(identityAliasAuthorName.getLastName() != null) {
sanitizedIdentityAuthorName.add(identityAliasAuthorName);
}
}
}
if(additionalName != null && additionalName.getLastName() != null) {
sanitizedIdentityAuthorName.add(additionalName);
}
}
private void sanitizeTargetAuthorNames(ReCiterArticle reCiterArticle, Set<AuthorName> sanitizedAuthorName) {
//Sanitize targetAuthorName
for(ReCiterAuthor targetAuthorName: reCiterArticle.getArticleCoAuthors().getAuthors()) {
if(targetAuthorName.isTargetAuthor()) {
AuthorName targetAuthor = new AuthorName();
if(targetAuthorName.getAuthorName().getFirstName() != null) {
targetAuthor.setFirstName(targetAuthorName.getAuthorName().getFirstName().replaceAll("[-.\"() ]", ""));
}
if(targetAuthorName.getAuthorName().getLastName() != null) {
targetAuthor.setLastName(targetAuthorName.getAuthorName().getLastName().replaceAll("[-.\",()\\s]|(,Jr|, Jr|, MD PhD|,MD PhD|, MD-PhD|,MD-PhD|, PhD|,PhD|, MD|,MD|, III|,III|, II|,II|, Sr|,Sr|Jr|MD PhD|MD-PhD|PhD|MD|III|II|Sr)$", ""));
}
sanitizedAuthorName.add(targetAuthor);
}
}
}
/**
* This function check if middle name is null in all variants of identity name. If there is null return false
*/
private boolean isNotNullIdentityMiddleName(List<AuthorName> idenityAuthorName) {
boolean middleNameNull = false;
for(AuthorName authorName: idenityAuthorName) {
if(authorName.getMiddleName() != null) {
middleNameNull = true;
return middleNameNull;
}
}
return middleNameNull;
}
private void checkToIgnoreNameVariants(List<AuthorName> idenityAuthorNames) {
for(int i= 0 ; i < idenityAuthorNames.size() ; i++) {
for(int j = 0; j < idenityAuthorNames.size(); j++) {
if(i==j) {
continue;
}
if(idenityAuthorNames.get(i) != null && idenityAuthorNames.get(j) != null) {
if(StringUtils.equalsIgnoreCase(idenityAuthorNames.get(i).getLastName(), idenityAuthorNames.get(j).getLastName()) &&
idenityAuthorNames.get(i).getFirstName().startsWith(idenityAuthorNames.get(j).getFirstName())) {
if(idenityAuthorNames.get(j).getMiddleName() == null) {
idenityAuthorNames.remove(j);
}
}
//Case - ajdannen - Throw away Andrew J Dannenberg because Andrew Jess Dannenberg exists
if(idenityAuthorNames.size() - 1 >= j && idenityAuthorNames.size() > 1) {
if(idenityAuthorNames.get(i).getLastName() != null
&&
idenityAuthorNames.get(j).getLastName() != null
&&
idenityAuthorNames.get(i).getFirstName() != null
&&
idenityAuthorNames.get(j).getFirstName() != null
&&
idenityAuthorNames.get(i).getMiddleName() != null
&&
idenityAuthorNames.get(j).getMiddleName() != null
&&
StringUtils.equalsIgnoreCase(idenityAuthorNames.get(i).getLastName(), idenityAuthorNames.get(j).getLastName())
&&
StringUtils.equalsIgnoreCase(idenityAuthorNames.get(i).getFirstName(), idenityAuthorNames.get(j).getFirstName())
&&
idenityAuthorNames.get(i).getMiddleName().startsWith(idenityAuthorNames.get(j).getMiddleName())) {
idenityAuthorNames.remove(j);
}
}
}
}
}
}
/**
* This function compares all the AuthorNameEvidences and returns the highest AuthorNameEvidence total score
* @param authorNameEvidences
* @return
*/
private AuthorNameEvidence calculateHighestScore(List<AuthorNameEvidence> authorNameEvidences) {
return authorNameEvidences.stream().max(Comparator.comparing(AuthorNameEvidence::getNameScoreTotal)).orElseThrow(NoSuchElementException::new);
}
@Override
public double executeStrategy(ReCiterArticle reCiterArticle, Identity identity) {
return 0;
}
@Override
public void populateFeature(ReCiterArticle reCiterArticle, Identity identity, Feature feature) {
// TODO Auto-generated method stub
}
}
|
src/main/java/reciter/algorithm/evidence/targetauthor/name/strategy/ScoreByNameStrategy.java
|
package reciter.algorithm.evidence.targetauthor.name.strategy;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reciter.algorithm.cluster.article.scorer.ReCiterArticleScorer;
import reciter.algorithm.evidence.targetauthor.AbstractTargetAuthorStrategy;
import reciter.algorithm.util.ReCiterStringUtil;
import reciter.engine.Feature;
import reciter.engine.analysis.evidence.AuthorNameEvidence;
import reciter.model.article.ReCiterArticle;
import reciter.model.article.ReCiterAuthor;
import reciter.model.identity.AuthorName;
import reciter.model.identity.Identity;
/**
* @author szd2013
* This class scores ReCiterArticles based on name and assigns score for each part of the name - first, middle and last
*
*/
public class ScoreByNameStrategy extends AbstractTargetAuthorStrategy {
private static final Logger slf4jLogger = LoggerFactory.getLogger(ScoreByNameStrategy.class);
@Override
public double executeStrategy(List<ReCiterArticle> reCiterArticles, Identity identity) {
List<AuthorName> sanitizedIdentityAuthor = new ArrayList<AuthorName>();
Set<AuthorName> sanitizedTargetAuthor = new HashSet<AuthorName>();
AuthorNameEvidence authorNameEvidence;
if(identity != null) {
sanitizeIdentityAuthorNames(identity, sanitizedIdentityAuthor);
checkToIgnoreNameVariants(sanitizedIdentityAuthor);
}
List<AuthorNameEvidence> authorNameEvidences = new ArrayList<AuthorNameEvidence>(sanitizedIdentityAuthor.size());
for(ReCiterArticle reCiterArticle: reCiterArticles) {
int targetAuthorCount = getTargetAuthorCount(reCiterArticle);
if(targetAuthorCount >=1) {
sanitizeTargetAuthorNames(reCiterArticle, sanitizedTargetAuthor);
for(AuthorName identityAuthorName: sanitizedIdentityAuthor) {
authorNameEvidence = new AuthorNameEvidence();
//Combine following identity.middleName, identity.lastName into mergedName. Now attempt match against article.lastName.
//Example: Garcia (identity.middleName) + Marquez (identity.lastName) = GarciaMarques (article.lastName)
//If match: stop scoring middle and last name; move on to only score first name;
scoreCombinedMiddleLastName(identityAuthorName, sanitizedTargetAuthor, authorNameEvidence);
if(authorNameEvidence.getNameMatchFirstType() != null
&&
authorNameEvidence.getNameMatchMiddleType() != null
&&
authorNameEvidence.getNameMatchLastType() != null
&&
authorNameEvidence.getNameMatchModifier() != null) {
slf4jLogger.info("Combine following identity.middleName, identity.lastName into mergedName. Now attempt match against article.lastName.");
}
else {
scoreLastName(identityAuthorName, sanitizedTargetAuthor, authorNameEvidence);
if(!isNotNullIdentityMiddleName(sanitizedIdentityAuthor)) {
scoreFirstNameMiddleNameNull(identityAuthorName, sanitizedTargetAuthor, authorNameEvidence);
} else {
if(identityAuthorName.getMiddleName() == null) {
scoreFirstNameMiddleNameNull(identityAuthorName, sanitizedTargetAuthor, authorNameEvidence);
} else {
scoreFirstNameMiddleName(identityAuthorName, sanitizedTargetAuthor, authorNameEvidence);
}
}
}
if(authorNameEvidence.getNameMatchMiddleType() != null
&&
StringUtils.equalsIgnoreCase(authorNameEvidence.getNameMatchMiddleType(), "full-exact")
&&
identityAuthorName.getMiddleName() != null
&&
identityAuthorName.getMiddleName().length() == 1) {
authorNameEvidence.setNameMatchMiddleType("exact-singleInitial");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeExactSingleInitialScore());
authorNameEvidence.setTotalScore(authorNameEvidence.getNameMatchFirstScore() + authorNameEvidence.getNameMatchLastScore() + authorNameEvidence.getNameMatchMiddleScore() + authorNameEvidence.getNameMatchModifierScore());
}
authorNameEvidences.add(authorNameEvidence);
}
authorNameEvidence = calculateHighestScore(authorNameEvidences);
//Clear the target author set
if(sanitizedTargetAuthor != null
&&
sanitizedTargetAuthor.size() > 0) {
sanitizedTargetAuthor.clear();
}
//Clear AuthorNameEvidences
if(authorNameEvidences != null
&&
authorNameEvidences.size() > 0) {
authorNameEvidences.clear();
}
} else {
authorNameEvidence = new AuthorNameEvidence();
authorNameEvidence.setInstitutionalAuthorName(identity.getPrimaryName());
authorNameEvidence.setNameMatchFirstType("nullTargetAuthor-MatchNotAttempted");
authorNameEvidence.setNameMatchLastType("nullTargetAuthor-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleType("nullTargetAuthor-MatchNotAttempted");
}
reCiterArticle.setAuthorNameEvidence(authorNameEvidence);
slf4jLogger.info("Pmid: " + reCiterArticle.getArticleId() + " " + authorNameEvidence.toString());
}
return 1;
}
private void scoreCombinedMiddleLastName(AuthorName identityAuthor, Set<AuthorName> articleAuthorNames, AuthorNameEvidence authorNameEvidence) {
if(articleAuthorNames.size() > 0) {
AuthorName articleAuthorName = articleAuthorNames.iterator().next();
if(identityAuthor.getMiddleName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getMiddleName() + identityAuthor.getLastName()), ReCiterStringUtil.deAccent(articleAuthorName.getLastName()))
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))
) {
//Combine following identity.middleName, identity.lastName into mergedName. Now attempt match against article.lastName.
//Example: Garcia (identity.middleName) + Marquez (identity.lastName) = GarciaMarquez (article.lastName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchLastType("full-exact");
authorNameEvidence.setNameMatchLastScore(ReCiterArticleScorer.strategyParameters.getNameMatchLastTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("combinedMiddleNameLastName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierCombinedMiddleNameLastNameScore());
} else if(identityAuthor.getMiddleName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getMiddleName() + identityAuthor.getLastName()), ReCiterStringUtil.deAccent(articleAuthorName.getLastName()))
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstInitial()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchLastType("full-exact");
authorNameEvidence.setNameMatchLastScore(ReCiterArticleScorer.strategyParameters.getNameMatchLastTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("combinedMiddleNameLastName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierCombinedMiddleNameLastNameScore());
}
authorNameEvidence.setInstitutionalAuthorName(identityAuthor);
authorNameEvidence.setArticleAuthorName(articleAuthorName);
authorNameEvidence.setTotalScore(authorNameEvidence.getNameMatchFirstScore() + authorNameEvidence.getNameMatchMiddleScore() + authorNameEvidence.getNameMatchLastScore() + authorNameEvidence.getNameMatchModifierScore());
}
}
private void scoreLastName(AuthorName identityAuthor, Set<AuthorName> articleAuthorNames, AuthorNameEvidence authorNameEvidence) {
if(articleAuthorNames.size() > 0) {
AuthorName articleAuthorName = articleAuthorNames.iterator().next();
if(StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getLastName()), ReCiterStringUtil.deAccent(articleAuthorName.getLastName()))) {
//Attempt full exact match where identity.lastName = article.lastName.
//Example: Cole (identity.lastName) = Cole (article.lastName)
authorNameEvidence.setNameMatchLastType("full-exact");
authorNameEvidence.setNameMatchLastScore(ReCiterArticleScorer.strategyParameters.getNameMatchLastTypeFullExactScore());
} else if(identityAuthor.getMiddleName() != null && ReCiterStringUtil.deAccent(identityAuthor.getLastName()).contains(ReCiterStringUtil.deAccent(articleAuthorName.getLastName()))) {
//Attempt partial match where "%" + identity.lastName + "%" = article.lastName
//Example: Cole (identity.lastName) = Del Cole (article.lastName)
authorNameEvidence.setNameMatchLastType("full-exact");
authorNameEvidence.setNameMatchLastScore(ReCiterArticleScorer.strategyParameters.getNameMatchLastTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-lastName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleLastnameScore());
} else if(identityAuthor.getLastName().length() >= 4 && ReCiterStringUtil.levenshteinDistance(ReCiterStringUtil.deAccent(identityAuthor.getLastName()), ReCiterStringUtil.deAccent(articleAuthorName.getLastName())) <= 1) {
//Attempt match where identity.lastName >= 4 characters and levenshteinDistance between identity.lastName and article.lastName is <=1.
//Example: Kaushal (identity.lastName) = Kaushai (article.lastName)
authorNameEvidence.setNameMatchLastType("full-fuzzy");
authorNameEvidence.setNameMatchLastScore(ReCiterArticleScorer.strategyParameters.getNameMatchLastTypeFullFuzzyScore());
} else {
authorNameEvidence.setNameMatchLastType("full-conflictingEntirely");
authorNameEvidence.setNameMatchLastScore(ReCiterArticleScorer.strategyParameters.getNameMatchLastTypeFullConflictingEntirelyScore());
}
authorNameEvidence.setInstitutionalAuthorName(identityAuthor);
authorNameEvidence.setArticleAuthorName(articleAuthorName);
authorNameEvidence.setTotalScore(authorNameEvidence.getNameMatchFirstScore() + authorNameEvidence.getNameMatchMiddleScore() + authorNameEvidence.getNameMatchLastScore() + authorNameEvidence.getNameMatchModifierScore());
}
}
/** This function matches and scores first name and middle name where middle name is null in identity
* All of the matching that follows should be evaluated as a series of ifElse statements (once we get a match, we stop). The goal is to match as early on in the process as possible.
* Matching should be case insensitive, however, we will pull out some characters below based on case.
*/
private void scoreFirstNameMiddleNameNull(AuthorName identityAuthor, Set<AuthorName> articleAuthorNames, AuthorNameEvidence authorNameEvidence) {
if(articleAuthorNames.size() > 0) {
AuthorName articleAuthorName = articleAuthorNames.iterator().next();
if(identityAuthor.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.firstName = article.firstName
//Example: Paul (identity.firstName) = Paul (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
} else if(identityAuthor.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).startsWith(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()))) {
//Attempt match where identity.firstName is a left-anchored substring of article.firstName
//Example: Paul (identity.firstName) = PaulJames (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstnameScore());
} else if(identityAuthor.getFirstName() != null
&&
ReCiterStringUtil.deAccent(identityAuthor.getFirstName()).startsWith(ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where article.firstName is a left-anchored substring of identity.firstName
//Example: Paul (identity.firstName) = P (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getFirstName().length() >= 3
&&
articleAuthorName.getFirstName().length() >= 3
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName().substring(0, 2)),ReCiterStringUtil.deAccent(articleAuthorName.getFirstName().substring(0, 2)))) {
//Attempt match where first three characters of identity.firstName = first three characters of article.firstName
//Example: Paul (identity.firstName) = Pau (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-fuzzy");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullFuzzyScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getFirstName().length() >= 4
&&
ReCiterStringUtil.levenshteinDistance(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName())) == 1) {
//Attempt match where identity.firstName is greater than 4 characters and Levenshtein distance between identity.firstName and article.firstName is 1.
//Example: Paula (identity.firstName) = Pauly (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-fuzzy");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullFuzzyScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
} else if(identityAuthor.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstInitial()),ReCiterStringUtil.deAccent(articleAuthorName.getFirstInitial()))) {
//Attempt match where first character of identity.firstName = first character of article.firstName
//Example: Paul (identity.firstName) = Peter (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-conflictingAllButInitials");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullConflictingAllButInitialsScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
} else {
authorNameEvidence.setNameMatchFirstType("full-conflictingEntirely");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullConflictingEntirelyScore());
authorNameEvidence.setNameMatchMiddleType("identityNull-MatchNotAttempted");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeIdentityNullMatchNotAttemptedScore());
}
authorNameEvidence.setInstitutionalAuthorName(identityAuthor);
authorNameEvidence.setArticleAuthorName(articleAuthorName);
authorNameEvidence.setTotalScore(authorNameEvidence.getNameMatchFirstScore() + authorNameEvidence.getNameMatchMiddleScore() + authorNameEvidence.getNameMatchLastScore() + authorNameEvidence.getNameMatchModifierScore());
}
}
/**
* We need to score first and middle names in conjunction with each other, because PubMed and Scopus combine them into a single field; also, it's often the case that first and middle names are conflated in identity systems of record.
All of the matching that follows should be evaluated as a series of ifElse statements (once we get a match, we stop). The goal is to match as early on in the process as possible.
It's conceivable that we can use the firstName from one alias in conjunction with the middleName of another to match to our article. We can use any combination of first and middle names to do the matching.
Preprocessing: ignore/discard name variants in which it's pretty clear that one name variant has a middle name that is an abbreviation of another.
Example: there are two name variants for ajdannen:
"Andrew[firstName] + Jess[middleName] + Dannenberg[lastName]"
"Andrew[firstName] + J[middleName] + Dannenberg[lastName]"
In cases where one of the middle names is a left-anchored substring of the other, discard/ignore the shorter one.
* @param identityAuthor
* @param articleAuthorNames
* @param authorNameEvidence
*/
private void scoreFirstNameMiddleName(AuthorName identityAuthor, Set<AuthorName> articleAuthorNames, AuthorNameEvidence authorNameEvidence) {
if(articleAuthorNames.size() > 0) {
AuthorName articleAuthorName = articleAuthorNames.iterator().next();
if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName() + identityAuthor.getMiddleName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.firstName + identity.middleName = article.firstName
//Example: Paul (identity.firstName) + James (identity.middleName) = PaulJames (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()) + "(.*)" + ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()))) {
//Attempt match where identity.firstName + "%" + identity.middleName = article.firstName
//Example: Paul (identity.firstName) + James (identity.middleName) = PaulaJames (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstMiddleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName() + identityAuthor.getMiddleInitial()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.firstName + identity.middleInitial = article.firstName
//Example: Paul (identity.firstName) + J (identity.middleInitial) = PaulJ (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("inferredInitials-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeInferredInitialsExactScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()) + "(.*)" + ReCiterStringUtil.deAccent(identityAuthor.getMiddleInitial()))) {
//Attempt match where identity.firstName + "%" + identity.middleInitial = article.firstName
//Example: Paul (identity.firstName) + J (identity.middleInitial) = PaulaJ (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("inferredInitials-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstMiddleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstInitial() + identityAuthor.getMiddleInitial()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.firstInitial + identity.middleInitial = article.firstName
//Example: P (identity.firstInitial) + J (identity.middleInitial) = PJ (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("inferredInitials-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeInferredInitialsExactScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstInitial() + identityAuthor.getMiddleName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.firstInitial + identity.middleName = article.firstName
//Example: M (identity.firstInitial) + Carrington (identity.middleName) = MCarrington (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()) + ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()) + "(.*)")) {
//Attempt match where identity.firstName + identity.middleName + "%" = article.firstName
//Example: Paul (identity.firstName) + James (identity.middleName) = PaulJamesA (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstMiddleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()) + ReCiterStringUtil.deAccent(identityAuthor.getMiddleInitial()) + "(.*)")) {
//Attempt match where identity.firstName + identity.middleInitial + "%" = article.firstName
//Example: Paul (identity.firstName) + J (identity.middleInitial) = PaulJZ (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("inferredInitials-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstMiddleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.firstName = article.firstName
//Example: Paul (identity.firstName) = Paul (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getMiddleInitial() + identityAuthor.getFirstInitial()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("inferredInitials-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchModifier("incorrectOrder");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIncorrectOrderScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
(identityAuthor.getFirstName().codePoints().filter(c-> c>='A' && c<='Z').count() > 1 || identityAuthor.getMiddleName().codePoints().filter(c-> c>='A' && c<='Z').count() > 1) //check if there is more than 1 capital letters
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()).chars().filter(Character::isUpperCase)
.mapToObj(c -> Character.toString((char)c))
.collect(Collectors.joining()) +
ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()).chars().filter(Character::isUpperCase)
.mapToObj(c -> Character.toString((char)c))
.collect(Collectors.joining()),
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//If there's more than one capital letter in identity.firstName or identity.middleName, attempt match where any capitals in identity.firstName + any capital letters in identity.middleName = article.firstName
//Example: KS (identity.initialsInFirstName) + C (identity.initialsInMiddleName) = KSC (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("inferredInitials-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeInferredInitialsExactScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
identityAuthor.getFirstName().codePoints().filter(c-> c>='A' && c<='Z').count() > 1 //check if there is more than 1 capital letters
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()).chars().filter(Character::isUpperCase)
.mapToObj(c -> Character.toString((char)c))
.collect(Collectors.joining()) ,
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//If there's more than one capital letter in identity.firstName, attempt match where any capitals in identity.firstName = article.firstName
//Example: KS (identity.initialsInFirstName) = KS (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
identityAuthor.getFirstName().codePoints().filter(c-> c>='A' && c<='Z').count() > 1 && //check if there is more than 1 capital letters
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()).chars().filter(Character::isUpperCase)
.mapToObj(c -> Character.toString((char)c))
.collect(Collectors.joining()) + identityAuthor.getMiddleName() ,
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//If there's more than one capital letter in identity.firstName, attempt match where any capitals in identity.firstName + identity.middleName = article.firstName
//Example: KS (identity.initialsInFirstName) + Clifford (identity.middleName) = KSClifford (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()) + "(.*)")) {
//Attempt match where identity.firstName + "%" = article.firstName
//Example: Robert (identity.firstName) = RobertR (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstnameScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches("(.*)" + ReCiterStringUtil.deAccent(identityAuthor.getFirstName()))) {
//Attempt match where "%" + identity.firstName = article.firstName
//Example: Cary (identity.firstName) = MCary (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullExactScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstnameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.middleName = article.firstName
//Example: Clifford (identity.middleName) = Clifford (article.firstName)
authorNameEvidence.setNameMatchFirstType("noMatch");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeNoMatchScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()) + "(.*)")) {
//Attempt match where identity.middleName + "%" = article.firstName
//Example: Clifford (identity.middleName) = CliffordKS (article.firstName)
authorNameEvidence.setNameMatchFirstType("noMatch");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeNoMatchScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-middleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches("(.*)" + ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()))) {
//Attempt match where "%" + identity.middleName = article.firstName
//Example: Clifford (identity.middleName) = KunSungClifford (article.firstName)
authorNameEvidence.setNameMatchFirstType("noMatch");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeNoMatchScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-middleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.levenshteinDistance(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()) + ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName())) <= 2) {
//Attempt match where levenshteinDistance between identity.firstName + identity.middleName and article.firstName is <=2.
//Example: Manney (identity.firstName) + Carrington (identity.middleName) = MannyCarrington (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-fuzzy");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullFuzzyScore());
authorNameEvidence.setNameMatchMiddleType("full-fuzzy");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullFuzzyScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
identityAuthor.getFirstName().length() >= 4
&&
ReCiterStringUtil.levenshteinDistance(ReCiterStringUtil.deAccent(identityAuthor.getFirstName()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName())) <= 1) {
//Attempt match where identity.firstName >= 4 characters and levenshteinDistance between identity.firstName and article.firstName is <=1.
//Example: Nassar (identity.firstName) = Nasser (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-fuzzy");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullFuzzyScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
identityAuthor.getFirstName().length() >=3
&&
articleAuthorName.getFirstName().length() >=3
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName().substring(0, 3)),ReCiterStringUtil.deAccent(articleAuthorName.getFirstName().substring(0, 3)))) {
//Attempt match where first three characters of identity.firstName = first three characters of identity.firstName.
//Example: Massimiliano (identity.firstName) = Massimo (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-fuzzy");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullFuzzyScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()).matches(ReCiterStringUtil.deAccent(identityAuthor.getFirstInitial()) + "(.*)" + ReCiterStringUtil.deAccent(identityAuthor.getMiddleName()))) {
//Attempt match where identity.firstInitial + "%" + identity.middleName = article.firstName
//Example: M (identity.firstInitial) + Carrington (identity.middleName) = MannyCarrington (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("identitySubstringOfArticle-firstMiddleName");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIdentitySubstringOfArticleFirstMiddlenameScore());
} else if(identityAuthor.getFirstName() != null
&&
identityAuthor.getMiddleName() != null
&&
articleAuthorName.getFirstName() != null
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getMiddleName() + identityAuthor.getFirstInitial()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where identity.middleName + identity.firstInitial = article.firstName
//Example: Carrington (identity.middleName) + M (identity.firstInitial) = CarringtonM (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("full-exact");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullExactScore());
authorNameEvidence.setNameMatchModifier("incorrectOrder");
authorNameEvidence.setNameMatchModifierScore(ReCiterArticleScorer.strategyParameters.getNameMatchModifierIncorrectOrderScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
articleAuthorName.getFirstName().length() == 1
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstInitial()), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName()))) {
//Attempt match where article.firstName is only one character and identity.firstName = first character of article.firstName.
//Example: Jessica (identity.firstName) = J (article.firstName)
authorNameEvidence.setNameMatchFirstType("inferredInitials-exact");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeInferredInitialsExactScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
} else if(identityAuthor.getFirstName() != null
&&
articleAuthorName.getFirstName() != null
&&
identityAuthor.getFirstName().length() > 0
&&
articleAuthorName.getFirstName().length() > 0
&&
StringUtils.equalsIgnoreCase(ReCiterStringUtil.deAccent(identityAuthor.getFirstName().substring(0, 1)), ReCiterStringUtil.deAccent(articleAuthorName.getFirstName().substring(0, 1)))) {
//Attempt match where first character of identity.firstName = first character of identity.firstName.
//Example: Jessica (identity.firstName) = Jochen (article.firstName)
authorNameEvidence.setNameMatchFirstType("full-conflictingAllButInitials");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullConflictingAllButInitialsScore());
authorNameEvidence.setNameMatchMiddleType("noMatch");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeNoMatchScore());
} else {
//Else, we have no match of any kind.
//Example: Pascale vs. Curtis
authorNameEvidence.setNameMatchFirstType("full-conflictingEntirely");
authorNameEvidence.setNameMatchFirstScore(ReCiterArticleScorer.strategyParameters.getNameMatchFirstTypeFullConflictingEntirelyScore());
authorNameEvidence.setNameMatchMiddleType("full-conflictingEntirely");
authorNameEvidence.setNameMatchMiddleScore(ReCiterArticleScorer.strategyParameters.getNameMatchMiddleTypeFullConflictingEntirelyScore());
}
authorNameEvidence.setInstitutionalAuthorName(identityAuthor);
authorNameEvidence.setArticleAuthorName(articleAuthorName);
authorNameEvidence.setTotalScore(authorNameEvidence.getNameMatchFirstScore() + authorNameEvidence.getNameMatchMiddleScore() + authorNameEvidence.getNameMatchLastScore() + authorNameEvidence.getNameMatchModifierScore());
}
}
private int getTargetAuthorCount(ReCiterArticle reCiterArticle) {
int targetAuthorCount = 0;
for(ReCiterAuthor targetAuthorName: reCiterArticle.getArticleCoAuthors().getAuthors()) {
if(targetAuthorName.isTargetAuthor()) {
targetAuthorCount++;
}
}
return targetAuthorCount;
}
/**
* @author szd2013
* Preprocess identity.firstName, identity.middleName, and article.firstName
If any names are in quotes or parentheses in identity.firstName or identity.middleName, pull them out so they can be matched against.
Wing Tak "Jack" --> add "Jack" to identity.firstName, add "Wing Tak" to identity.firstName
Qihui (Jim) --> add Jim to identity.firstName, add Qihui to identity.firstName
Remove any periods, spaces, or dashes from both identity.firstName, identity.middleName, and article.firstName. For example:
"Chi-chao" --> "Chichao"
"Minh-Nhut Yvonne" --> "MinhNhutYvonne"
"Eliot A." --> "EliotA"
Disregard any cases where one variant of identity.firstName is a substring of another case of identity.firstName. Disregard any cases where one variant of identity.middleName is a substring of another case of identity.middleName. For example:
"Cary" (keep) vs "C" (disregard)
Null for middle name should only be included as possible value if none of the names or aliases contain a middle name
A given target author might have N different first names and M different middle names.
Go to D
Retrieve article.lastName where targetAuthor=TRUE and all distinct cases of identity.lastName for our target author from identity. Preprocess identity.lastName and article.lastName.
Remove any periods from both identity.lastName and article.lastName
Remove any of the following endings from identity.lastName:
", Jr"
", MD PhD"
", MD-PhD"
", PhD"
", MD"
", III"
", II"
", Sr"
" Jr"
" MD PhD"
" MD-PhD"
" PhD"
" MD"
" III"
" II"
" Sr"
Remove any periods, spaces, dashes, or quotes.
For example:
"Del Cole" --> "Delcole"
"Garcia-Marquez" --> ""GarciaMarquez"
"Capetillo Gonzalez de Zarate" --> "CapetilloGonzalezdeZarate"
*
*/
private void sanitizeIdentityAuthorNames(Identity identity, List<AuthorName> sanitizedIdentityAuthorName) {
AuthorName identityPrimaryName = new AuthorName();
AuthorName additionalName = new AuthorName();
String firstName = null;
String lastName = null;
String middleName = null;
//Sanitize Identity Names
if(identity.getPrimaryName() != null) {
if(identity.getPrimaryName().getFirstName() != null) {
if(identity.getPrimaryName().getFirstName().contains("\"") || (identity.getPrimaryName().getFirstName().contains("(") && identity.getPrimaryName().getFirstName().contains(")"))) {
firstName = identity.getPrimaryName().getFirstName().replaceAll("[-.,()\\s]", "").replaceAll("\"([^\"]*)\"|(\"([^\"]*)\")|(([a-z]*))/i/g", "");
if(firstName !=null) {
additionalName.setFirstName(firstName);
}
Pattern pattern = Pattern.compile("\"([^\"]*)\"|(\"([^\"]*)\")|(([a-z]*))/i/g");
Matcher matcher = pattern.matcher(identity.getPrimaryName().getFirstName());
while(matcher.find()) {
identityPrimaryName.setFirstName(matcher.group().replaceAll("\"", ""));
}
} else {
identityPrimaryName.setFirstName(identity.getPrimaryName().getFirstName().replaceAll("[-.,()\\s]", ""));
}
}
if(identity.getPrimaryName().getMiddleName() != null) {
if(identity.getPrimaryName().getMiddleName().contains("\"") || (identity.getPrimaryName().getMiddleName().contains("(") && identity.getPrimaryName().getMiddleName().contains(")"))) {
middleName = identity.getPrimaryName().getMiddleName().replaceAll("[-.,()\\s]", "").replaceAll("\"([^\"]*)\"|(\"([^\"]*)\")|(([a-z]*))/i/g", "");
if(middleName !=null) {
additionalName.setMiddleName(middleName);
}
Pattern pattern = Pattern.compile("\"([^\"]*)\"|(\"([^\"]*)\")|(([a-z]*))/i/g");
Matcher matcher = pattern.matcher(identity.getPrimaryName().getMiddleName());
while(matcher.find()) {
identityPrimaryName.setMiddleName(matcher.group().replaceAll("\"", ""));
}
} else {
identityPrimaryName.setMiddleName(identity.getPrimaryName().getMiddleName().replaceAll("[-.,()\\s]", ""));
}
}
if(identity.getPrimaryName().getLastName() != null) {
lastName = identity.getPrimaryName().getLastName().replaceAll("[-.,,()\\s]|(,Jr|, Jr|, MD PhD|,MD PhD|, MD-PhD|,MD-PhD|, PhD|,PhD|, MD|,MD|, III|,III|, II|,II|, Sr|,Sr|Jr|MD PhD|MD-PhD|PhD|MD|III|II|Sr)$", "");
identityPrimaryName.setLastName(lastName);
if(additionalName.getFirstName() != null) {
additionalName.setLastName(lastName);
}
}
if(identityPrimaryName.getLastName() != null) {
sanitizedIdentityAuthorName.add(identityPrimaryName);
}
}
if(identity.getAlternateNames() != null && identity.getAlternateNames().size() > 0) {
for(AuthorName aliasAuthorName: identity.getAlternateNames()) {
AuthorName identityAliasAuthorName = new AuthorName();
if(aliasAuthorName.getFirstName() != null) {
identityAliasAuthorName.setFirstName(aliasAuthorName.getFirstName().replaceAll("[-.\",()\\s]", ""));
}
if(aliasAuthorName.getMiddleName() != null) {
identityAliasAuthorName.setMiddleName(aliasAuthorName.getMiddleName().replaceAll("[-.\",()\\s]", ""));
}
if(aliasAuthorName.getLastName() != null) {
identityAliasAuthorName.setLastName(aliasAuthorName.getLastName().replaceAll("[-.\",()\\s]|(,Jr|, Jr|, MD PhD|,MD PhD|, MD-PhD|,MD-PhD|, PhD|,PhD|, MD|,MD|, III|,III|, II|,II|, Sr|,Sr|Jr|MD PhD|MD-PhD|PhD|MD|III|II|Sr)$", ""));
}
if(identityAliasAuthorName.getLastName() != null) {
sanitizedIdentityAuthorName.add(identityAliasAuthorName);
}
}
}
if(additionalName != null && additionalName.getLastName() != null) {
sanitizedIdentityAuthorName.add(additionalName);
}
}
private void sanitizeTargetAuthorNames(ReCiterArticle reCiterArticle, Set<AuthorName> sanitizedAuthorName) {
//Sanitize targetAuthorName
for(ReCiterAuthor targetAuthorName: reCiterArticle.getArticleCoAuthors().getAuthors()) {
if(targetAuthorName.isTargetAuthor()) {
AuthorName targetAuthor = new AuthorName();
if(targetAuthorName.getAuthorName().getFirstName() != null) {
targetAuthor.setFirstName(targetAuthorName.getAuthorName().getFirstName().replaceAll("[-.\"() ]", ""));
}
if(targetAuthorName.getAuthorName().getLastName() != null) {
targetAuthor.setLastName(targetAuthorName.getAuthorName().getLastName().replaceAll("[-.\",()\\s]|(,Jr|, Jr|, MD PhD|,MD PhD|, MD-PhD|,MD-PhD|, PhD|,PhD|, MD|,MD|, III|,III|, II|,II|, Sr|,Sr|Jr|MD PhD|MD-PhD|PhD|MD|III|II|Sr)$", ""));
}
sanitizedAuthorName.add(targetAuthor);
}
}
}
/**
* This function check if middle name is null in all variants of identity name. If there is null return false
*/
private boolean isNotNullIdentityMiddleName(List<AuthorName> idenityAuthorName) {
boolean middleNameNull = false;
for(AuthorName authorName: idenityAuthorName) {
if(authorName.getMiddleName() != null) {
middleNameNull = true;
return middleNameNull;
}
}
return middleNameNull;
}
private void checkToIgnoreNameVariants(List<AuthorName> idenityAuthorNames) {
for(int i= 0 ; i < idenityAuthorNames.size() ; i++) {
for(int j = 0; j < idenityAuthorNames.size(); j++) {
if(i==j) {
continue;
}
if(idenityAuthorNames.get(i) != null && idenityAuthorNames.get(j) != null) {
if(StringUtils.equalsIgnoreCase(idenityAuthorNames.get(i).getLastName(), idenityAuthorNames.get(j).getLastName()) &&
idenityAuthorNames.get(i).getFirstName().startsWith(idenityAuthorNames.get(j).getFirstName())) {
if(idenityAuthorNames.get(j).getMiddleName() == null) {
idenityAuthorNames.remove(j);
}
}
//Case - ajdannen - Throw away Andrew J Dannenberg because Andrew Jess Dannenberg exists
if(idenityAuthorNames.size() - 1 >= j && idenityAuthorNames.size() > 1) {
if(idenityAuthorNames.get(i).getLastName() != null
&&
idenityAuthorNames.get(j).getLastName() != null
&&
idenityAuthorNames.get(i).getFirstName() != null
&&
idenityAuthorNames.get(j).getFirstName() != null
&&
idenityAuthorNames.get(i).getMiddleName() != null
&&
idenityAuthorNames.get(j).getMiddleName() != null
&&
StringUtils.equalsIgnoreCase(idenityAuthorNames.get(i).getLastName(), idenityAuthorNames.get(j).getLastName())
&&
StringUtils.equalsIgnoreCase(idenityAuthorNames.get(i).getFirstName(), idenityAuthorNames.get(j).getFirstName())
&&
idenityAuthorNames.get(i).getMiddleName().startsWith(idenityAuthorNames.get(j).getMiddleName())) {
idenityAuthorNames.remove(j);
}
}
}
}
}
}
/**
* This function compares all the AuthorNameEvidences and returns the highest AuthorNameEvidence total score
* @param authorNameEvidences
* @return
*/
private AuthorNameEvidence calculateHighestScore(List<AuthorNameEvidence> authorNameEvidences) {
return authorNameEvidences.stream().max(Comparator.comparing(AuthorNameEvidence::getTotalScore)).orElseThrow(NoSuchElementException::new);
}
@Override
public double executeStrategy(ReCiterArticle reCiterArticle, Identity identity) {
return 0;
}
@Override
public void populateFeature(ReCiterArticle reCiterArticle, Identity identity, Feature feature) {
// TODO Auto-generated method stub
}
}
|
change in total score for name evidence
|
src/main/java/reciter/algorithm/evidence/targetauthor/name/strategy/ScoreByNameStrategy.java
|
change in total score for name evidence
|
|
Java
|
apache-2.0
|
7ce4b869eadcb44bef929e362482589e405ff533
| 0
|
bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
|
package com.planet_ink.coffee_mud.Common;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Expire;
import com.planet_ink.coffee_mud.core.exceptions.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.CMClass.CMObjectType;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat;
import com.planet_ink.coffee_mud.Common.interfaces.Session.InputCallback;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.ChannelsLibrary.CMChannel;
import com.planet_ink.coffee_mud.Libraries.interfaces.DatabaseEngine.PlayerData;
import com.planet_ink.coffee_mud.Libraries.interfaces.XMLLibrary.XMLTag;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import org.mozilla.javascript.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
Copyright 2008-2020 Bo Zimmerman
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.
*/
public class DefaultScriptingEngine implements ScriptingEngine
{
@Override
public String ID()
{
return "DefaultScriptingEngine";
}
@Override
public String name()
{
return "Default Scripting Engine";
}
protected static final Map<String,Integer> funcH = new Hashtable<String,Integer>();
protected static final Map<String,Integer> methH = new Hashtable<String,Integer>();
protected static final Map<String,Integer> progH = new Hashtable<String,Integer>();
protected static final Map<String,Integer> connH = new Hashtable<String,Integer>();
protected static final Map<String,Integer> gstatH = new Hashtable<String,Integer>();
protected static final Map<String,Integer> signH = new Hashtable<String,Integer>();
protected static final Map<String, AtomicInteger> counterCache= new Hashtable<String, AtomicInteger>();
protected static final Map<String, Pattern> patterns = new Hashtable<String, Pattern>();
protected boolean noDelay = CMSecurity.isDisabled(CMSecurity.DisFlag.SCRIPTABLEDELAY);
protected String scope = "";
protected int tickStatus = Tickable.STATUS_NOT;
protected boolean isSavable = true;
protected boolean alwaysTriggers = false;
protected MOB lastToHurtMe = null;
protected Room lastKnownLocation= null;
protected Room homeKnownLocation= null;
protected Tickable altStatusTickable= null;
protected List<DVector> oncesDone = new Vector<DVector>();
protected Map<Integer,Integer> delayTargetTimes = new Hashtable<Integer,Integer>();
protected Map<Integer,int[]> delayProgCounters= new Hashtable<Integer,int[]>();
protected Map<Integer,Integer> lastTimeProgsDone= new Hashtable<Integer,Integer>();
protected Map<Integer,Integer> lastDayProgsDone = new Hashtable<Integer,Integer>();
protected Set<Integer> registeredEvents = new HashSet<Integer>();
protected Map<Integer,Long> noTrigger = new Hashtable<Integer,Long>();
protected MOB backupMOB = null;
protected CMMsg lastMsg = null;
protected Resources resources = null;
protected Environmental lastLoaded = null;
protected String myScript = "";
protected String defaultQuestName = "";
protected String scriptKey = null;
protected boolean runInPassiveAreas= true;
protected boolean debugBadScripts = false;
protected List<ScriptableResponse>que = new Vector<ScriptableResponse>();
protected final AtomicInteger recurseCounter = new AtomicInteger();
protected volatile Object cachedRef = null;
public DefaultScriptingEngine()
{
super();
//CMClass.bumpCounter(this,CMClass.CMObjectType.COMMON);//removed for mem & perf
debugBadScripts=CMSecurity.isDebugging(CMSecurity.DbgFlag.BADSCRIPTS);
resources = Resources.instance();
}
@Override
public boolean isSavable()
{
return isSavable;
}
@Override
public void setSavable(final boolean truefalse)
{
isSavable = truefalse;
}
@Override
public String defaultQuestName()
{
return defaultQuestName;
}
protected Quest defaultQuest()
{
if(defaultQuestName.length()==0)
return null;
return CMLib.quests().fetchQuest(defaultQuestName);
}
@Override
public void setVarScope(final String newScope)
{
if((newScope==null)||(newScope.trim().length()==0)||newScope.equalsIgnoreCase("GLOBAL"))
{
scope="";
resources=Resources.instance();
}
else
scope=newScope.toUpperCase().trim();
if(scope.equalsIgnoreCase("*")||scope.equals("INDIVIDUAL"))
resources = Resources.newResources();
else
{
resources=(Resources)Resources.getResource("VARSCOPE-"+scope);
if(resources==null)
{
resources = Resources.newResources();
Resources.submitResource("VARSCOPE-"+scope,resources);
}
if(cachedRef==this)
bumpUpCache(scope);
}
}
@Override
public String getVarScope()
{
return scope;
}
protected Object[] newObjs()
{
return new Object[ScriptingEngine.SPECIAL_NUM_OBJECTS];
}
@Override
public String getLocalVarXML()
{
if((scope==null)||(scope.length()==0))
return "";
final StringBuffer str=new StringBuffer("");
for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();)
{
final String key=k.next();
if(key.startsWith("SCRIPTVAR-"))
{
str.append("<"+key.substring(10)+">");
@SuppressWarnings("unchecked")
final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource(key);
for(final Enumeration<String> e=H.keys();e.hasMoreElements();)
{
final String vn=e.nextElement();
final String val=H.get(vn);
str.append("<"+vn+">"+CMLib.xml().parseOutAngleBrackets(val)+"</"+vn+">");
}
str.append("</"+key.substring(10)+">");
}
}
return str.toString();
}
@Override
public void setLocalVarXML(final String xml)
{
for(final Iterator<String> k = Resources.findResourceKeys("SCRIPTVAR-");k.hasNext();)
{
final String key=k.next();
if(key.startsWith("SCRIPTVAR-"))
resources._removeResource(key);
}
final List<XMLLibrary.XMLTag> V=CMLib.xml().parseAllXML(xml);
for(int v=0;v<V.size();v++)
{
final XMLTag piece=V.get(v);
if((piece.contents()!=null)&&(piece.contents().size()>0))
{
final String kkey="SCRIPTVAR-"+piece.tag();
final Hashtable<String,String> H=new Hashtable<String,String>();
for(int c=0;c<piece.contents().size();c++)
{
final XMLTag piece2=piece.contents().get(c);
H.put(piece2.tag(),piece2.value());
}
resources._submitResource(kkey,H);
}
}
}
private Quest getQuest(final String named)
{
if((defaultQuestName.length()>0)
&&(named.equals("*")||named.equalsIgnoreCase(defaultQuestName)))
return defaultQuest();
Quest Q=null;
for(int i=0;i<CMLib.quests().numQuests();i++)
{
try
{
Q = CMLib.quests().fetchQuest(i);
}
catch (final Exception e)
{
}
if(Q!=null)
{
if(Q.name().equalsIgnoreCase(named))
{
if(Q.running())
return Q;
}
}
}
return CMLib.quests().fetchQuest(named);
}
@Override
public int getTickStatus()
{
final Tickable T=altStatusTickable;
if(T!=null)
return T.getTickStatus();
return tickStatus;
}
@Override
public void registerDefaultQuest(final String qName)
{
if((qName==null)||(qName.trim().length()==0))
defaultQuestName="";
else
{
defaultQuestName=qName.trim();
if(cachedRef==this)
bumpUpCache(defaultQuestName);
}
}
@Override
public CMObject newInstance()
{
try
{
return this.getClass().newInstance();
}
catch(final Exception e)
{
Log.errOut(ID(),e);
}
return new DefaultScriptingEngine();
}
@Override
public CMObject copyOf()
{
try
{
final DefaultScriptingEngine S=(DefaultScriptingEngine)this.clone();
//CMClass.bumpCounter(S,CMClass.CMObjectType.COMMON);//removed for mem & perf
S.reset();
return S;
}
catch(final CloneNotSupportedException e)
{
return new DefaultScriptingEngine();
}
}
/*
protected void finalize()
{
CMClass.unbumpCounter(this, CMClass.CMObjectType.COMMON);
}// removed for mem & perf
*/
/*
* c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger
*/
protected String[] parseBits(final DVector script, final int row, final String instructions)
{
final String line=(String)script.elementAt(row,1);
final String[] newLine=parseBits(line,instructions);
script.setElementAt(row,2,newLine);
return newLine;
}
protected String[] parseSpecial3PartEval(final String[][] eval, final int t)
{
String[] tt=eval[0];
final String funcParms=tt[t];
final String[] tryTT=parseBits(funcParms,"ccr");
if(signH.containsKey(tryTT[1]))
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
else
{
String[] parsed=null;
if(CMParms.cleanBit(funcParms).equals(funcParms))
parsed=parseBits("'"+funcParms+"' . .","cr");
else
parsed=parseBits(funcParms+" . .","cr");
tt=insertStringArray(tt,parsed,t);
eval[0]=tt;
}
return tt;
}
/*
* c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger
*/
protected String[] parseBits(String line, final String instructions)
{
String[] newLine=new String[instructions.length()];
for(int i=0;i<instructions.length();i++)
{
switch(instructions.charAt(i))
{
case 'c':
newLine[i] = CMParms.getCleanBit(line, i);
break;
case 'C':
newLine[i] = CMParms.getCleanBit(line, i).toUpperCase().trim();
break;
case 'r':
newLine[i] = CMParms.getPastBitClean(line, i - 1);
break;
case 'R':
newLine[i] = CMParms.getPastBitClean(line, i - 1).toUpperCase().trim();
break;
case 'p':
newLine[i] = CMParms.getPastBit(line, i - 1);
break;
case 'P':
newLine[i] = CMParms.getPastBit(line, i - 1).toUpperCase().trim();
break;
case 'S':
line = line.toUpperCase();
//$FALL-THROUGH$
case 's':
{
final String s = CMParms.getPastBit(line, i - 1);
final int numBits = CMParms.numBits(s);
final String[] newNewLine = new String[newLine.length - 1 + numBits];
for (int x = 0; x < i; x++)
newNewLine[x] = newLine[x];
for (int x = 0; x < numBits; x++)
newNewLine[i + x] = CMParms.getCleanBit(s, i - 1);
newLine = newNewLine;
i = instructions.length();
break;
}
case 'T':
line = line.toUpperCase();
//$FALL-THROUGH$
case 't':
{
final String s = CMParms.getPastBit(line, i - 1);
String[] newNewLine = null;
if (CMParms.getCleanBit(s, 0).equalsIgnoreCase("P"))
{
newNewLine = new String[newLine.length + 1];
for (int x = 0; x < i; x++)
newNewLine[x] = newLine[x];
newNewLine[i] = "P";
newNewLine[i + 1] = CMParms.getPastBitClean(s, 0);
}
else
{
final int numNewBits = (s.trim().length() == 0) ? 1 : CMParms.numBits(s);
newNewLine = new String[newLine.length - 1 + numNewBits];
for (int x = 0; x < i; x++)
newNewLine[x] = newLine[x];
for (int x = 0; x < numNewBits; x++)
newNewLine[i + x] = CMParms.getCleanBit(s, x);
}
newLine = newNewLine;
i = instructions.length();
break;
}
}
}
return newLine;
}
protected String[] insertStringArray(final String[] oldS, final String[] inS, final int where)
{
final String[] newLine=new String[oldS.length+inS.length-1];
for(int i=0;i<where;i++)
newLine[i]=oldS[i];
for(int i=0;i<inS.length;i++)
newLine[where+i]=inS[i];
for(int i=where+1;i<oldS.length;i++)
newLine[inS.length+i-1]=oldS[i];
return newLine;
}
/*
* c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger
*/
protected String[] parseBits(final String[][] oldBits, final int start, final String instructions)
{
final String[] tt=oldBits[0];
final String parseMe=tt[start];
final String[] parsed=parseBits(parseMe,instructions);
if(parsed.length==1)
{
tt[start]=parsed[0];
return tt;
}
final String[] newLine=insertStringArray(tt,parsed,start);
oldBits[0]=newLine;
return newLine;
}
@Override
public boolean endQuest(final PhysicalAgent hostObj, final MOB mob, final String quest)
{
if(mob!=null)
{
final List<DVector> scripts=getScripts();
if(!mob.amDead())
{
lastKnownLocation=mob.location();
if(homeKnownLocation==null)
homeKnownLocation=lastKnownLocation;
}
String trigger="";
String[] tt=null;
for(int v=0;v<scripts.size();v++)
{
final DVector script=scripts.get(v);
if(script.size()>0)
{
trigger=((String)script.elementAt(0,1)).toUpperCase().trim();
tt=(String[])script.elementAt(0,2);
if((getTriggerCode(trigger,tt)==13) //questtimeprog quest_time_prog
&&(!oncesDone.contains(script)))
{
if(tt==null)
tt=parseBits(script,0,"CCC");
if((tt!=null)
&&((tt[1].equals(quest)||(tt[1].equals("*"))))
&&(CMath.s_int(tt[2])<0))
{
oncesDone.add(script);
execute(hostObj,mob,mob,mob,null,null,script,null,newObjs());
return true;
}
}
}
}
}
return false;
}
@Override
public List<String> externalFiles()
{
final Vector<String> xmlfiles=new Vector<String>();
parseLoads(getScript(), 0, xmlfiles, null);
return xmlfiles;
}
protected String getVarHost(final Environmental E,
String rawHost,
final MOB source,
final Environmental target,
final PhysicalAgent scripted,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final String msg,
final Object[] tmp)
{
if(!rawHost.equals("*"))
{
if(E==null)
rawHost=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,rawHost);
else
if(E instanceof Room)
rawHost=CMLib.map().getExtendedRoomID((Room)E);
else
rawHost=E.Name();
}
return rawHost;
}
@SuppressWarnings("unchecked")
@Override
public boolean isVar(final String host, String var)
{
if(host.equalsIgnoreCase("*"))
{
String val=null;
Hashtable<String,String> H=null;
String key=null;
var=var.toUpperCase();
for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();)
{
key=k.next();
if(key.startsWith("SCRIPTVAR-"))
{
H=(Hashtable<String,String>)resources._getResource(key);
val=H.get(var);
if(val!=null)
return true;
}
}
return false;
}
final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+host);
String val=null;
if(H!=null)
val=H.get(var.toUpperCase());
return (val!=null);
}
public String getVar(final Environmental E, final String rawHost, final String var, final MOB source, final Environmental target,
final PhysicalAgent scripted, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg,
final Object[] tmp)
{
return getVar(getVarHost(E,rawHost,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp),var);
}
@Override
public String getVar(final String host, final String var)
{
String varVal = getVar(resources,host,var,null);
if(varVal != null)
return varVal;
if((this.defaultQuestName!=null)&&(this.defaultQuestName.length()>0))
{
final Resources questResources=(Resources)Resources.getResource("VARSCOPE-"+this.defaultQuestName);
if((questResources != null)&&(resources!=questResources))
{
varVal = getVar(questResources,host,var,null);
if(varVal != null)
return varVal;
}
}
if(resources == Resources.instance())
return "";
return getVar(Resources.instance(),host,var,"");
}
@SuppressWarnings("unchecked")
public String getVar(final Resources resources, final String host, String var, final String defaultVal)
{
if(host.equalsIgnoreCase("*"))
{
if(var.equals("COFFEEMUD_SYSTEM_INTERNAL_NONFILENAME_SCRIPT"))
{
final StringBuffer str=new StringBuffer("");
parseLoads(getScript(),0,null,str);
return str.toString();
}
String val=null;
Hashtable<String,String> H=null;
String key=null;
var=var.toUpperCase();
for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();)
{
key=k.next();
if(key.startsWith("SCRIPTVAR-"))
{
H=(Hashtable<String,String>)resources._getResource(key);
val=H.get(var);
if(val!=null)
return val;
}
}
return defaultVal;
}
Resources.instance();
final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+host);
String val=null;
if(H!=null)
val=H.get(var.toUpperCase());
else
if((defaultQuestName!=null)&&(defaultQuestName.length()>0))
{
final MOB M=CMLib.players().getPlayerAllHosts(host);
if(M!=null)
{
for(final Enumeration<ScriptingEngine> e=M.scripts();e.hasMoreElements();)
{
final ScriptingEngine SE=e.nextElement();
if((SE!=null)
&&(SE!=this)
&&(defaultQuestName.equalsIgnoreCase(SE.defaultQuestName()))
&&(SE.isVar(host,var)))
return SE.getVar(host,var);
}
}
}
if(val==null)
return defaultVal;
return val;
}
private StringBuffer getResourceFileData(final String named, final boolean showErrors)
{
final Quest Q=getQuest("*");
if(Q!=null)
return Q.getResourceFileData(named, showErrors);
return new CMFile(Resources.makeFileResourceName(named),null,CMFile.FLAG_LOGERRORS).text();
}
@Override
public String getScript()
{
return myScript;
}
public void reset()
{
que = new Vector<ScriptableResponse>();
lastToHurtMe = null;
lastKnownLocation= null;
homeKnownLocation=null;
altStatusTickable= null;
oncesDone = new Vector<DVector>();
delayTargetTimes = new Hashtable<Integer,Integer>();
delayProgCounters= new Hashtable<Integer,int[]>();
lastTimeProgsDone= new Hashtable<Integer,Integer>();
lastDayProgsDone = new Hashtable<Integer,Integer>();
registeredEvents = new HashSet<Integer>();
noTrigger = new Hashtable<Integer,Long>();
backupMOB = null;
lastMsg = null;
bumpUpCache();
}
@Override
public void setScript(String newParms)
{
newParms=CMStrings.replaceAll(newParms,"'","`");
if(newParms.startsWith("+"))
{
final String superParms=getScript();
Resources.removeResource(getScriptResourceKey());
newParms=superParms+";"+newParms.substring(1);
}
myScript=newParms;
if(myScript.length()>100)
scriptKey="PARSEDPRG: "+myScript.substring(0,100)+myScript.length()+myScript.hashCode();
else
scriptKey="PARSEDPRG: "+myScript;
reset();
}
public boolean isFreeToBeTriggered(final Tickable affecting)
{
if(alwaysTriggers)
return CMLib.flags().canActAtAll(affecting);
else
return CMLib.flags().canFreelyBehaveNormal(affecting);
}
protected String parseLoads(final String text, final int depth, final Vector<String> filenames, final StringBuffer nonFilenameScript)
{
final StringBuffer results=new StringBuffer("");
String parse=text;
if(depth>10) return ""; // no including off to infinity
String p=null;
while(parse.length()>0)
{
final int y=parse.toUpperCase().indexOf("LOAD=");
if(y>=0)
{
p=parse.substring(0,y).trim();
if((!p.endsWith(";"))
&&(!p.endsWith("\n"))
&&(!p.endsWith("~"))
&&(!p.endsWith("\r"))
&&(p.length()>0))
{
if(nonFilenameScript!=null)
nonFilenameScript.append(parse.substring(0,y+1));
results.append(parse.substring(0,y+1));
parse=parse.substring(y+1);
continue;
}
results.append(p+"\n");
int z=parse.indexOf('~',y);
while((z>0)&&(parse.charAt(z-1)=='\\'))
z=parse.indexOf('~',z+1);
if(z>0)
{
final String filename=parse.substring(y+5,z).trim();
parse=parse.substring(z+1);
if((filenames!=null)&&(!filenames.contains(filename)))
filenames.addElement(filename);
results.append(parseLoads(getResourceFileData(filename, true).toString(),depth+1,filenames,null));
}
else
{
final String filename=parse.substring(y+5).trim();
if((filenames!=null)&&(!filenames.contains(filename)))
filenames.addElement(filename);
results.append(parseLoads(getResourceFileData(filename, true).toString(),depth+1,filenames,null));
break;
}
}
else
{
if(nonFilenameScript!=null)
nonFilenameScript.append(parse);
results.append(parse);
break;
}
}
return results.toString();
}
protected void buildHashes()
{
if(funcH.size()==0)
{
synchronized(funcH)
{
if(funcH.size()==0)
{
for(int i=0;i<funcs.length;i++)
funcH.put(funcs[i],Integer.valueOf(i+1));
for(int i=0;i<methods.length;i++)
methH.put(methods[i],Integer.valueOf(i+1));
for(int i=0;i<progs.length;i++)
progH.put(progs[i],Integer.valueOf(i+1));
for(int i=0;i<progs.length;i++)
methH.put(progs[i],Integer.valueOf(Integer.MIN_VALUE));
for(int i=0;i<CONNECTORS.length;i++)
connH.put(CONNECTORS[i],Integer.valueOf(i));
for(int i=0;i<SIGNS.length;i++)
signH.put(SIGNS[i],Integer.valueOf(i));
}
}
}
}
protected List<DVector> parseScripts(String text)
{
buildHashes();
while((text.length()>0)
&&(Character.isWhitespace(text.charAt(0))))
text=text.substring(1);
boolean staticSet=false;
if((text.length()>10)
&&(text.substring(0,10).toUpperCase().startsWith("STATIC=")))
{
staticSet=true;
text=text.substring(7);
}
text=parseLoads(text,0,null,null);
if(staticSet)
{
text=CMStrings.replaceAll(text,"'","`");
myScript=text;
reset();
}
final List<List<String>> V = CMParms.parseDoubleDelimited(text,'~',';');
final Vector<DVector> V2=new Vector<DVector>(3);
for(final List<String> ls : V)
{
final DVector DV=new DVector(3);
for(final String s : ls)
DV.addElement(s,null,null);
V2.add(DV);
}
return V2;
}
protected Room getRoom(final String thisName, final Room imHere)
{
if(thisName.length()==0)
return null;
if(imHere!=null)
{
if(imHere.roomID().equalsIgnoreCase(thisName))
return imHere;
if((thisName.startsWith("#"))&&(CMath.isLong(thisName.substring(1))))
return CMLib.map().getRoom(imHere.getArea().Name()+thisName);
if(Character.isDigit(thisName.charAt(0))&&(CMath.isLong(thisName)))
return CMLib.map().getRoom(imHere.getArea().Name()+"#"+thisName);
}
final Room room=CMLib.map().getRoom(thisName);
if((room!=null)&&(room.roomID().equalsIgnoreCase(thisName)))
{
if(CMath.bset(room.getArea().flags(),Area.FLAG_INSTANCE_PARENT)
&&(imHere!=null)
&&(CMath.bset(imHere.getArea().flags(),Area.FLAG_INSTANCE_CHILD))
&&(imHere.getArea().Name().endsWith("_"+room.getArea().Name()))
&&(thisName.indexOf('#')>=0))
{
final Room otherRoom=CMLib.map().getRoom(imHere.getArea().Name()+thisName.substring(thisName.indexOf('#')));
if((otherRoom!=null)&&(otherRoom.roomID().endsWith(thisName)))
return otherRoom;
}
return room;
}
List<Room> rooms=new ArrayList<Room>(1);
if((imHere!=null)&&(imHere.getArea()!=null))
rooms=CMLib.map().findAreaRoomsLiberally(null, imHere.getArea(), thisName, "RIEPM",100);
if(rooms.size()==0)
{
if(debugBadScripts)
Log.debugOut("ScriptingEngine","World room search called for: "+thisName);
rooms=CMLib.map().findWorldRoomsLiberally(null,thisName, "RIEPM",100,2000);
}
if(rooms.size()>0)
return rooms.get(CMLib.dice().roll(1,rooms.size(),-1));
if(room == null)
{
final int x=thisName.indexOf('@');
if(x>0)
{
Room R=CMLib.map().getRoom(thisName.substring(x+1));
if((R==null)||(R==imHere))
{
final Area A=CMLib.map().getArea(thisName.substring(x+1));
R=(A!=null)?A.getRandomMetroRoom():null;
}
if((R!=null)&&(R!=imHere))
return getRoom(thisName.substring(0,x),R);
}
}
return room;
}
protected void logError(final Environmental scripted, final String cmdName, final String errType, final String errMsg)
{
if(scripted!=null)
{
final Room R=CMLib.map().roomLocation(scripted);
String scriptFiles=CMParms.toListString(externalFiles());
if((scriptFiles == null)||(scriptFiles.trim().length()==0))
scriptFiles=CMStrings.limit(this.getScript(),80);
if((scriptFiles == null)||(scriptFiles.trim().length()==0))
Log.errOut(new Exception("Scripting Error"));
if((scriptFiles == null)||(scriptFiles.trim().length()==0))
scriptFiles=getScriptResourceKey();
Log.errOut("Scripting",scripted.name()+"/"+CMLib.map().getDescriptiveExtendedRoomID(R)+"/"+ cmdName+"/"+errType+"/"+errMsg+"/"+scriptFiles);
if(R!=null)
R.showHappens(CMMsg.MSG_OK_VISUAL,L("Scripting Error: @x1/@x2/@x3/@x4/@x5/@x6",scripted.name(),CMLib.map().getExtendedRoomID(R),cmdName,errType,errMsg,scriptFiles));
}
else
Log.errOut("Scripting","*/*/"+CMParms.toListString(externalFiles())+"/"+cmdName+"/"+errType+"/"+errMsg);
}
protected boolean simpleEvalStr(final Environmental scripted, final String arg1, final String arg2, final String cmp, final String cmdName)
{
final int x=arg1.compareToIgnoreCase(arg2);
final Integer SIGN=signH.get(cmp);
if(SIGN==null)
{
logError(scripted,cmdName,"Syntax",arg1+" "+cmp+" "+arg2);
return false;
}
switch(SIGN.intValue())
{
case SIGN_EQUL:
return (x == 0);
case SIGN_EQGT:
case SIGN_GTEQ:
return (x == 0) || (x > 0);
case SIGN_EQLT:
case SIGN_LTEQ:
return (x == 0) || (x < 0);
case SIGN_GRAT:
return (x > 0);
case SIGN_LEST:
return (x < 0);
case SIGN_NTEQ:
return (x != 0);
default:
return (x == 0);
}
}
protected boolean simpleEval(final Environmental scripted, final String arg1, final String arg2, final String cmp, final String cmdName)
{
final long val1=CMath.s_long(arg1.trim());
final long val2=CMath.s_long(arg2.trim());
final Integer SIGN=signH.get(cmp);
if(SIGN==null)
{
logError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2);
return false;
}
switch(SIGN.intValue())
{
case SIGN_EQUL:
return (val1 == val2);
case SIGN_EQGT:
case SIGN_GTEQ:
return val1 >= val2;
case SIGN_EQLT:
case SIGN_LTEQ:
return val1 <= val2;
case SIGN_GRAT:
return (val1 > val2);
case SIGN_LEST:
return (val1 < val2);
case SIGN_NTEQ:
return (val1 != val2);
default:
return (val1 == val2);
}
}
protected boolean simpleExpressionEval(final Environmental scripted, final String arg1, final String arg2, final String cmp, final String cmdName)
{
final double val1=CMath.s_parseMathExpression(arg1.trim());
final double val2=CMath.s_parseMathExpression(arg2.trim());
final Integer SIGN=signH.get(cmp);
if(SIGN==null)
{
logError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2);
return false;
}
switch(SIGN.intValue())
{
case SIGN_EQUL:
return (val1 == val2);
case SIGN_EQGT:
case SIGN_GTEQ:
return val1 >= val2;
case SIGN_EQLT:
case SIGN_LTEQ:
return val1 <= val2;
case SIGN_GRAT:
return (val1 > val2);
case SIGN_LEST:
return (val1 < val2);
case SIGN_NTEQ:
return (val1 != val2);
default:
return (val1 == val2);
}
}
protected List<MOB> loadMobsFromFile(final Environmental scripted, String filename)
{
filename=filename.trim();
@SuppressWarnings("unchecked")
List<MOB> monsters=(List<MOB>)Resources.getResource("RANDOMMONSTERS-"+filename);
if(monsters!=null)
return monsters;
final StringBuffer buf=getResourceFileData(filename, true);
String thangName="null";
final Room R=CMLib.map().roomLocation(scripted);
if(R!=null)
thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted);
else
if(scripted!=null)
thangName=scripted.name();
if((buf==null)||(buf.length()<20))
{
logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName);
return null;
}
final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString());
monsters=new Vector<MOB>();
if(xml!=null)
{
if(CMLib.xml().getContentsFromPieces(xml,"MOBS")!=null)
{
final String error=CMLib.coffeeMaker().addMOBsFromXML(xml,monsters,null);
if(error.length()>0)
{
logError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"'");
return null;
}
if(monsters.size()<=0)
{
logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'");
return null;
}
Resources.submitResource("RANDOMMONSTERS-"+filename,monsters);
for(final Object O : monsters)
{
if(O instanceof MOB)
CMLib.threads().deleteAllTicks((MOB)O);
}
}
else
{
logError(scripted,"XMLLOAD","?","No MOBs in XML file: '"+filename+"' in "+thangName);
return null;
}
}
else
{
logError(scripted,"XMLLOAD","?","Invalid XML file: '"+filename+"' in "+thangName);
return null;
}
return monsters;
}
protected List<MOB> generateMobsFromFile(final Environmental scripted, String filename, final String tagName, final String rest)
{
filename=filename.trim();
@SuppressWarnings("unchecked")
List<MOB> monsters=(List<MOB>)Resources.getResource("RANDOMGENMONSTERS-"+filename+"."+tagName+"-"+rest);
if(monsters!=null)
return monsters;
final StringBuffer buf=getResourceFileData(filename, true);
String thangName="null";
final Room R=CMLib.map().roomLocation(scripted);
if(R!=null)
thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted);
else
if(scripted!=null)
thangName=scripted.name();
if((buf==null)||(buf.length()<20))
{
logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName);
return null;
}
final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString());
monsters=new Vector<MOB>();
if(xml!=null)
{
if(CMLib.xml().getContentsFromPieces(xml,"AREADATA")!=null)
{
final Hashtable<String,Object> definedIDs = new Hashtable<String,Object>();
final Map<String,String> eqParms=new HashMap<String,String>();
eqParms.putAll(CMParms.parseEQParms(rest.trim()));
final String idName=tagName.toUpperCase();
try
{
CMLib.percolator().buildDefinedIDSet(xml,definedIDs, new TreeSet<String>());
if((!(definedIDs.get(idName) instanceof XMLTag))
||(!((XMLTag)definedIDs.get(idName)).tag().equalsIgnoreCase("MOB")))
{
logError(scripted,"XMLLOAD","?","Non-MOB tag '"+idName+"' for XML file: '"+filename+"' in "+thangName);
return null;
}
final XMLTag piece=(XMLTag)definedIDs.get(idName);
definedIDs.putAll(eqParms);
try
{
CMLib.percolator().checkRequirements(piece, definedIDs);
}
catch(final CMException cme)
{
logError(scripted,"XMLLOAD","?","Required ids for "+idName+" were missing for XML file: '"+filename+"' in "+thangName+": "+cme.getMessage());
return null;
}
CMLib.percolator().preDefineReward(piece, definedIDs);
CMLib.percolator().defineReward(piece,definedIDs);
monsters.addAll(CMLib.percolator().findMobs(piece, definedIDs));
CMLib.percolator().postProcess(definedIDs);
if(monsters.size()<=0)
{
logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'");
return null;
}
Resources.submitResource("RANDOMGENMONSTERS-"+filename+"."+tagName+"-"+rest,monsters);
}
catch(final CMException cex)
{
logError(scripted,"XMLLOAD","?","Unable to generate "+idName+" from XML file: '"+filename+"' in "+thangName+": "+cex.getMessage());
return null;
}
}
else
{
logError(scripted,"XMLLOAD","?","Invalid GEN XML file: '"+filename+"' in "+thangName);
return null;
}
}
else
{
logError(scripted,"XMLLOAD","?","Empty or Invalid XML file: '"+filename+"' in "+thangName);
return null;
}
return monsters;
}
protected List<Item> loadItemsFromFile(final Environmental scripted, String filename)
{
filename=filename.trim();
@SuppressWarnings("unchecked")
List<Item> items=(List<Item>)Resources.getResource("RANDOMITEMS-"+filename);
if(items!=null)
return items;
final StringBuffer buf=getResourceFileData(filename, true);
String thangName="null";
final Room R=CMLib.map().roomLocation(scripted);
if(R!=null)
thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted);
else
if(scripted!=null)
thangName=scripted.name();
if((buf==null)||(buf.length()<20))
{
logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName);
return null;
}
items=new Vector<Item>();
final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString());
if(xml!=null)
{
if(CMLib.xml().getContentsFromPieces(xml,"ITEMS")!=null)
{
final String error=CMLib.coffeeMaker().addItemsFromXML(buf.toString(),items,null);
if(error.length()>0)
{
logError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"' in "+thangName);
return null;
}
if(items.size()<=0)
{
logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'");
return null;
}
for(final Object O : items)
{
if(O instanceof Item)
CMLib.threads().deleteTick((Item)O, -1);
}
Resources.submitResource("RANDOMITEMS-"+filename,items);
}
else
{
logError(scripted,"XMLLOAD","?","No ITEMS in XML file: '"+filename+"' in "+thangName);
return null;
}
}
else
{
logError(scripted,"XMLLOAD","?","Empty or invalid XML file: '"+filename+"' in "+thangName);
return null;
}
return items;
}
protected List<Item> generateItemsFromFile(final Environmental scripted, String filename, final String tagName, final String rest)
{
filename=filename.trim();
@SuppressWarnings("unchecked")
List<Item> items=(List<Item>)Resources.getResource("RANDOMGENITEMS-"+filename+"."+tagName+"-"+rest);
if(items!=null)
return items;
final StringBuffer buf=getResourceFileData(filename, true);
String thangName="null";
final Room R=CMLib.map().roomLocation(scripted);
if(R!=null)
thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted);
else
if(scripted!=null)
thangName=scripted.name();
if((buf==null)||(buf.length()<20))
{
logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName);
return null;
}
items=new Vector<Item>();
final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString());
if(xml!=null)
{
if(CMLib.xml().getContentsFromPieces(xml,"AREADATA")!=null)
{
final Hashtable<String,Object> definedIDs = new Hashtable<String,Object>();
final Map<String,String> eqParms=new HashMap<String,String>();
eqParms.putAll(CMParms.parseEQParms(rest.trim()));
final String idName=tagName.toUpperCase();
try
{
CMLib.percolator().buildDefinedIDSet(xml,definedIDs, new TreeSet<String>());
if((!(definedIDs.get(idName) instanceof XMLTag))
||(!((XMLTag)definedIDs.get(idName)).tag().equalsIgnoreCase("ITEM")))
{
logError(scripted,"XMLLOAD","?","Non-ITEM tag '"+idName+"' for XML file: '"+filename+"' in "+thangName);
return null;
}
final XMLTag piece=(XMLTag)definedIDs.get(idName);
definedIDs.putAll(eqParms);
try
{
CMLib.percolator().checkRequirements(piece, definedIDs);
}
catch(final CMException cme)
{
logError(scripted,"XMLLOAD","?","Required ids for "+idName+" were missing for XML file: '"+filename+"' in "+thangName+": "+cme.getMessage());
return null;
}
CMLib.percolator().preDefineReward(piece, definedIDs);
CMLib.percolator().defineReward(piece,definedIDs);
items.addAll(CMLib.percolator().findItems(piece, definedIDs));
CMLib.percolator().postProcess(definedIDs);
if(items.size()<=0)
{
logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"' in "+thangName);
return null;
}
Resources.submitResource("RANDOMGENITEMS-"+filename+"."+tagName+"-"+rest,items);
}
catch(final CMException cex)
{
logError(scripted,"XMLLOAD","?","Unable to generate "+idName+" from XML file: '"+filename+"' in "+thangName+": "+cex.getMessage());
return null;
}
}
else
{
logError(scripted,"XMLLOAD","?","Not a GEN XML file: '"+filename+"' in "+thangName);
return null;
}
}
else
{
logError(scripted,"XMLLOAD","?","Empty or Invalid XML file: '"+filename+"' in "+thangName);
return null;
}
return items;
}
@SuppressWarnings("unchecked")
protected Environmental findSomethingCalledThis(final String thisName, final MOB meMOB, final Room imHere, List<Environmental> OBJS, final boolean mob)
{
if(thisName.length()==0)
return null;
Environmental thing=null;
Environmental areaThing=null;
if(thisName.toUpperCase().trim().startsWith("FROMFILE "))
{
try
{
List<? extends Environmental> V=null;
if(mob)
V=loadMobsFromFile(null,CMParms.getCleanBit(thisName,1));
else
V=loadItemsFromFile(null,CMParms.getCleanBit(thisName,1));
if(V!=null)
{
final String name=CMParms.getPastBitClean(thisName,1);
if(name.equalsIgnoreCase("ALL"))
OBJS=(List<Environmental>)V;
else
if(name.equalsIgnoreCase("ANY"))
{
if(V.size()>0)
areaThing=V.get(CMLib.dice().roll(1,V.size(),-1));
}
else
{
areaThing=CMLib.english().fetchEnvironmental(V,name,true);
if(areaThing==null)
areaThing=CMLib.english().fetchEnvironmental(V,name,false);
}
}
}
catch(final Exception e)
{
}
}
else
if(thisName.toUpperCase().trim().startsWith("FROMGENFILE "))
{
try
{
List<? extends Environmental> V=null;
final String filename=CMParms.getCleanBit(thisName, 1);
final String name=CMParms.getCleanBit(thisName, 2);
final String tagName=CMParms.getCleanBit(thisName, 3);
final String theRest=CMParms.getPastBitClean(thisName,3);
if(mob)
V=generateMobsFromFile(null,filename, tagName, theRest);
else
V=generateItemsFromFile(null,filename, tagName, theRest);
if(V!=null)
{
if(name.equalsIgnoreCase("ALL"))
OBJS=(List<Environmental>)V;
else
if(name.equalsIgnoreCase("ANY"))
{
if(V.size()>0)
areaThing=V.get(CMLib.dice().roll(1,V.size(),-1));
}
else
{
areaThing=CMLib.english().fetchEnvironmental(V,name,true);
if(areaThing==null)
areaThing=CMLib.english().fetchEnvironmental(V,name,false);
}
}
}
catch(final Exception e)
{
}
}
else
{
if(!mob)
areaThing=(meMOB!=null)?meMOB.findItem(thisName):null;
try
{
if(areaThing==null)
{
final Area A=imHere.getArea();
final Vector<Environmental> all=new Vector<Environmental>();
if(mob)
{
all.addAll(CMLib.map().findInhabitants(A.getProperMap(),null,thisName,100));
if(all.size()==0)
all.addAll(CMLib.map().findShopStock(A.getProperMap(), null, thisName,100));
for(int a=all.size()-1;a>=0;a--)
{
if(!(all.elementAt(a) instanceof MOB))
all.removeElementAt(a);
}
if(all.size()>0)
areaThing=all.elementAt(CMLib.dice().roll(1,all.size(),-1));
else
{
all.addAll(CMLib.map().findInhabitantsFavorExact(CMLib.map().rooms(),null,thisName,false,100));
if(all.size()==0)
all.addAll(CMLib.map().findShopStock(CMLib.map().rooms(), null, thisName,100));
for(int a=all.size()-1;a>=0;a--)
{
if(!(all.elementAt(a) instanceof MOB))
all.removeElementAt(a);
}
if(all.size()>0)
thing=all.elementAt(CMLib.dice().roll(1,all.size(),-1));
}
}
if(all.size()==0)
{
all.addAll(CMLib.map().findRoomItems(A.getProperMap(), null,thisName,true,100));
if(all.size()==0)
all.addAll(CMLib.map().findInventory(A.getProperMap(), null,thisName,100));
if(all.size()==0)
all.addAll(CMLib.map().findShopStock(A.getProperMap(), null,thisName,100));
if(all.size()>0)
areaThing=all.elementAt(CMLib.dice().roll(1,all.size(),-1));
else
{
all.addAll(CMLib.map().findRoomItems(CMLib.map().rooms(), null,thisName,true,100));
if(all.size()==0)
all.addAll(CMLib.map().findInventory(CMLib.map().rooms(), null,thisName,100));
if(all.size()==0)
all.addAll(CMLib.map().findShopStock(CMLib.map().rooms(), null,thisName,100));
if(all.size()>0)
thing=all.elementAt(CMLib.dice().roll(1,all.size(),-1));
}
}
}
}
catch(final NoSuchElementException nse)
{
}
}
if(areaThing!=null)
OBJS.add(areaThing);
else
if(thing!=null)
OBJS.add(thing);
if(OBJS.size()>0)
return OBJS.get(0);
return null;
}
protected PhysicalAgent getArgumentMOB(final String str,
final MOB source,
final MOB monster,
final Environmental target,
final Item primaryItem,
final Item secondaryItem,
final String msg,
final Object[] tmp)
{
return getArgumentItem(str,source,monster,monster,target,primaryItem,secondaryItem,msg,tmp);
}
protected PhysicalAgent getArgumentItem(String str,
final MOB source,
final MOB monster,
final PhysicalAgent scripted,
final Environmental target,
final Item primaryItem,
final Item secondaryItem,
final String msg,
final Object[] tmp)
{
if(str.length()<2)
return null;
if(str.charAt(0)=='$')
{
if(Character.isDigit(str.charAt(1)))
{
Object O=tmp[CMath.s_int(Character.toString(str.charAt(1)))];
if(O instanceof PhysicalAgent)
return (PhysicalAgent)O;
else
if((O instanceof List)&&(str.length()>3)&&(str.charAt(2)=='.'))
{
final List<?> V=(List<?>)O;
String back=str.substring(2);
if(back.charAt(1)=='$')
back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back);
if((back.length()>1)&&Character.isDigit(back.charAt(1)))
{
int x=1;
while((x<back.length())&&(Character.isDigit(back.charAt(x))))
x++;
final int y=CMath.s_int(back.substring(1,x).trim());
if((V.size()>0)&&(y>=0))
{
if(y>=V.size())
return null;
O=V.get(y);
if(O instanceof PhysicalAgent)
return (PhysicalAgent)O;
}
str=O.toString(); // will fall through
}
}
else
if(O!=null)
str=O.toString(); // will fall through
else
return null;
}
else
switch(str.charAt(1))
{
case 'a':
return (lastKnownLocation != null) ? lastKnownLocation.getArea() : null;
case 'B':
case 'b':
return (lastLoaded instanceof PhysicalAgent) ? (PhysicalAgent) lastLoaded : null;
case 'N':
case 'n':
return ((source == backupMOB) && (backupMOB != null) && (monster != scripted)) ? scripted : source;
case 'I':
case 'i':
return scripted;
case 'T':
case 't':
return ((target == backupMOB) && (backupMOB != null) && (monster != scripted))
? scripted : (target instanceof PhysicalAgent) ? (PhysicalAgent) target : null;
case 'O':
case 'o':
return primaryItem;
case 'P':
case 'p':
return secondaryItem;
case 'd':
case 'D':
return lastKnownLocation;
case 'F':
case 'f':
if ((monster != null) && (monster.amFollowing() != null))
return monster.amFollowing();
return null;
case 'r':
case 'R':
return getRandPC(monster, tmp, lastKnownLocation);
case 'c':
case 'C':
return getRandAnyone(monster, tmp, lastKnownLocation);
case 'w':
return primaryItem != null ? primaryItem.owner() : null;
case 'W':
return secondaryItem != null ? secondaryItem.owner() : null;
case 'x':
case 'X':
if (lastKnownLocation != null)
{
if ((str.length() > 2) && (CMLib.directions().getGoodDirectionCode("" + str.charAt(2)) >= 0))
return lastKnownLocation.getExitInDir(CMLib.directions().getGoodDirectionCode("" + str.charAt(2)));
int i = 0;
Exit E = null;
while (((++i) < 100) || (E != null))
E = lastKnownLocation.getExitInDir(CMLib.dice().roll(1, Directions.NUM_DIRECTIONS(), -1));
return E;
}
return null;
case '[':
{
final int x = str.substring(2).indexOf(']');
if (x >= 0)
{
String mid = str.substring(2).substring(0, x);
final int y = mid.indexOf(' ');
if (y > 0)
{
final int num = CMath.s_int(mid.substring(0, y).trim());
mid = mid.substring(y + 1).trim();
final Quest Q = getQuest(mid);
if (Q != null)
return Q.getQuestItem(num);
}
}
break;
}
case '{':
{
final int x = str.substring(2).indexOf('}');
if (x >= 0)
{
String mid = str.substring(2).substring(0, x).trim();
final int y = mid.indexOf(' ');
if (y > 0)
{
final int num = CMath.s_int(mid.substring(0, y).trim());
mid = mid.substring(y + 1).trim();
final Quest Q = getQuest(mid);
if (Q != null)
{
final MOB M=Q.getQuestMob(num);
return M;
}
}
}
break;
}
}
}
if(lastKnownLocation!=null)
{
str=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,str);
Environmental E=null;
if(str.indexOf('#')>0)
E=CMLib.map().getRoom(str);
if(E==null)
E=lastKnownLocation.fetchFromRoomFavorMOBs(null,str);
if(E==null)
E=lastKnownLocation.fetchFromMOBRoomFavorsItems(monster,null,str,Wearable.FILTER_ANY);
if(E==null)
E=lastKnownLocation.findItem(str);
if((E==null)&&(monster!=null))
E=monster.findItem(str);
if(E==null)
E=CMLib.players().getPlayerAllHosts(str);
if((E==null)&&(source!=null))
E=source.findItem(str);
if(E instanceof PhysicalAgent)
return (PhysicalAgent)E;
}
return null;
}
private String makeNamedString(final Object O)
{
if(O instanceof List)
return makeParsableString((List<?>)O);
else
if(O instanceof Room)
return ((Room)O).displayText(null);
else
if(O instanceof Environmental)
return ((Environmental)O).Name();
else
if(O!=null)
return O.toString();
return "";
}
private String makeParsableString(final List<?> V)
{
if((V==null)||(V.size()==0))
return "";
if(V.get(0) instanceof String)
return CMParms.combineQuoted(V,0);
final StringBuffer ret=new StringBuffer("");
String S=null;
for(int v=0;v<V.size();v++)
{
S=makeNamedString(V.get(v)).trim();
if(S.length()==0)
ret.append("? ");
else
if(S.indexOf(' ')>=0)
ret.append("\""+S+"\" ");
else
ret.append(S+" ");
}
return ret.toString();
}
@Override
public String varify(final MOB source,
final Environmental target,
final PhysicalAgent scripted,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final String msg,
final Object[] tmp,
String varifyable)
{
int t=varifyable.indexOf('$');
if((monster!=null)&&(monster.location()!=null))
lastKnownLocation=monster.location();
if(lastKnownLocation==null)
{
lastKnownLocation=source.location();
if(homeKnownLocation==null)
homeKnownLocation=lastKnownLocation;
}
else
if(homeKnownLocation==null)
homeKnownLocation=lastKnownLocation;
MOB randMOB=null;
while((t>=0)&&(t<varifyable.length()-1))
{
final char c=varifyable.charAt(t+1);
String middle="";
final String front=varifyable.substring(0,t);
String back=varifyable.substring(t+2);
if(Character.isDigit(c))
middle=makeNamedString(tmp[CMath.s_int(Character.toString(c))]);
else
switch(c)
{
case '@':
if ((t < varifyable.length() - 2)
&& (Character.isLetter(varifyable.charAt(t + 2))||Character.isDigit(varifyable.charAt(t + 2))))
{
final Environmental E = getArgumentItem("$" + varifyable.charAt(t + 2),
source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(back.length()>0)
back=back.substring(1);
middle = (E == null) ? "null" : "" + E;
}
break;
case 'a':
if (lastKnownLocation != null)
middle = lastKnownLocation.getArea().name();
break;
// case 'a':
case 'A':
// unnecessary, since, in coffeemud, this is part of the
// name
break;
case 'b':
middle = lastLoaded != null ? lastLoaded.name() : "";
break;
case 'B':
middle = lastLoaded != null ? lastLoaded.displayText() : "";
break;
case 'c':
case 'C':
randMOB = getRandAnyone(monster, tmp, lastKnownLocation);
if (randMOB != null)
middle = randMOB.name();
break;
case 'd':
middle = (lastKnownLocation != null) ? lastKnownLocation.displayText(monster) : "";
break;
case 'D':
middle = (lastKnownLocation != null) ? lastKnownLocation.description(monster) : "";
break;
case 'e':
if (source != null)
middle = source.charStats().heshe();
break;
case 'E':
if ((target != null) && (target instanceof MOB))
middle = ((MOB) target).charStats().heshe();
break;
case 'f':
if ((monster != null) && (monster.amFollowing() != null))
middle = monster.amFollowing().name();
break;
case 'F':
if ((monster != null) && (monster.amFollowing() != null))
middle = monster.amFollowing().charStats().heshe();
break;
case 'g':
middle = ((msg == null) ? "" : msg.toLowerCase());
break;
case 'G':
middle = ((msg == null) ? "" : msg);
break;
case 'h':
if (monster != null)
middle = monster.charStats().himher();
break;
case 'H':
randMOB = getRandPC(monster, tmp, lastKnownLocation);
if (randMOB != null)
middle = randMOB.charStats().himher();
break;
case 'i':
if (monster != null)
middle = monster.name();
break;
case 'I':
if (monster != null)
middle = monster.displayText();
break;
case 'j':
if (monster != null)
middle = monster.charStats().heshe();
break;
case 'J':
randMOB = getRandPC(monster, tmp, lastKnownLocation);
if (randMOB != null)
middle = randMOB.charStats().heshe();
break;
case 'k':
if (monster != null)
middle = monster.charStats().hisher();
break;
case 'K':
randMOB = getRandPC(monster, tmp, lastKnownLocation);
if (randMOB != null)
middle = randMOB.charStats().hisher();
break;
case 'l':
if (lastKnownLocation != null)
{
final StringBuffer str = new StringBuffer("");
for (int i = 0; i < lastKnownLocation.numInhabitants(); i++)
{
final MOB M = lastKnownLocation.fetchInhabitant(i);
if ((M != null) && (M != monster) && (CMLib.flags().canBeSeenBy(M, monster)))
str.append("\"" + M.name() + "\" ");
}
middle = str.toString();
}
break;
case 'L':
if (lastKnownLocation != null)
{
final StringBuffer str = new StringBuffer("");
for (int i = 0; i < lastKnownLocation.numItems(); i++)
{
final Item I = lastKnownLocation.getItem(i);
if ((I != null) && (I.container() == null) && (CMLib.flags().canBeSeenBy(I, monster)))
str.append("\"" + I.name() + "\" ");
}
middle = str.toString();
}
break;
case 'm':
if (source != null)
middle = source.charStats().hisher();
break;
case 'M':
if ((target != null) && (target instanceof MOB))
middle = ((MOB) target).charStats().hisher();
break;
case 'n':
case 'N':
if (source != null)
middle = source.name();
break;
case 'o':
case 'O':
if (primaryItem != null)
middle = primaryItem.name();
break;
case 'p':
case 'P':
if (secondaryItem != null)
middle = secondaryItem.name();
break;
case 'r':
case 'R':
randMOB = getRandPC(monster, tmp, lastKnownLocation);
if (randMOB != null)
middle = randMOB.name();
break;
case 's':
if (source != null)
middle = source.charStats().himher();
break;
case 'S':
if ((target != null) && (target instanceof MOB))
middle = ((MOB) target).charStats().himher();
break;
case 't':
case 'T':
if (target != null)
middle = target.name();
break;
case 'w':
middle = primaryItem != null ? primaryItem.owner().Name() : middle;
break;
case 'W':
middle = secondaryItem != null ? secondaryItem.owner().Name() : middle;
break;
case 'x':
case 'X':
if (lastKnownLocation != null)
{
middle = "";
Exit E = null;
int dir = -1;
if ((t < varifyable.length() - 2) && (CMLib.directions().getGoodDirectionCode("" + varifyable.charAt(t + 2)) >= 0))
{
dir = CMLib.directions().getGoodDirectionCode("" + varifyable.charAt(t + 2));
E = lastKnownLocation.getExitInDir(dir);
}
else
{
int i = 0;
while (((++i) < 100) || (E != null))
{
dir = CMLib.dice().roll(1, Directions.NUM_DIRECTIONS(), -1);
E = lastKnownLocation.getExitInDir(dir);
}
}
if ((dir >= 0) && (E != null))
{
if (c == 'x')
middle = CMLib.directions().getDirectionName(dir);
else
middle = E.name();
}
}
break;
case 'y':
if (source != null)
middle = source.charStats().sirmadam();
break;
case 'Y':
if ((target != null) && (target instanceof MOB))
middle = ((MOB) target).charStats().sirmadam();
break;
case '<':
{
final int x = back.indexOf('>');
if (x >= 0)
{
String mid = back.substring(0, x);
final int y = mid.indexOf(' ');
Environmental E = null;
String arg1 = "";
if (y >= 0)
{
arg1 = mid.substring(0, y).trim();
E = getArgumentItem(arg1, source, monster, monster, target, primaryItem, secondaryItem, msg, tmp);
mid = mid.substring(y + 1).trim();
}
if (arg1.length() > 0)
middle = getVar(E, arg1, mid, source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp);
back = back.substring(x + 1);
}
break;
}
case '[':
{
middle = "";
final int x = back.indexOf(']');
if (x >= 0)
{
String mid = back.substring(0, x);
final int y = mid.indexOf(' ');
if (y > 0)
{
final int num = CMath.s_int(mid.substring(0, y).trim());
mid = mid.substring(y + 1).trim();
final Quest Q = getQuest(mid);
if (Q != null)
middle = Q.getQuestItemName(num);
}
back = back.substring(x + 1);
}
break;
}
case '{':
{
middle = "";
final int x = back.indexOf('}');
if (x >= 0)
{
String mid = back.substring(0, x).trim();
final int y = mid.indexOf(' ');
if (y > 0)
{
final int num = CMath.s_int(mid.substring(0, y).trim());
mid = mid.substring(y + 1).trim();
final Quest Q = getQuest(mid);
if (Q != null)
middle = Q.getQuestMobName(num);
}
back = back.substring(x + 1);
}
break;
}
case '%':
{
middle = "";
final int x = back.indexOf('%');
if (x >= 0)
{
middle = functify(scripted, source, target, monster, primaryItem, secondaryItem, msg, tmp, back.substring(0, x).trim());
back = back.substring(x + 1);
}
break;
}
}
if((back.startsWith("."))
&&(back.length()>1))
{
if(back.charAt(1)=='$')
back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back);
if(back.startsWith(".LENGTH#"))
{
middle=""+CMParms.parse(middle).size();
back=back.substring(8);
}
else
if((back.length()>1)&&Character.isDigit(back.charAt(1)))
{
int x=1;
while((x<back.length())
&&(Character.isDigit(back.charAt(x))))
x++;
final int y=CMath.s_int(back.substring(1,x).trim());
back=back.substring(x);
final boolean rest=back.startsWith("..");
if(rest)
back=back.substring(2);
final Vector<String> V=CMParms.parse(middle);
if((V.size()>0)&&(y>=0))
{
if(y>=V.size())
middle="";
else
if(rest)
middle=CMParms.combine(V,y);
else
middle=V.elementAt(y);
}
}
}
varifyable=front+middle+back;
t=varifyable.indexOf('$');
}
return varifyable;
}
protected PairList<String,String> getScriptVarSet(final String mobname, final String varname)
{
final PairList<String,String> set=new PairVector<String,String>();
if(mobname.equals("*"))
{
for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();)
{
final String key=k.next();
if(key.startsWith("SCRIPTVAR-"))
{
@SuppressWarnings("unchecked")
final Hashtable<String,?> H=(Hashtable<String,?>)resources._getResource(key);
if(varname.equals("*"))
{
if(H!=null)
{
for(final Enumeration<String> e=H.keys();e.hasMoreElements();)
{
final String vn=e.nextElement();
set.add(key.substring(10),vn);
}
}
}
else
set.add(key.substring(10),varname);
}
}
}
else
{
@SuppressWarnings("unchecked")
final Hashtable<String,?> H=(Hashtable<String,?>)resources._getResource("SCRIPTVAR-"+mobname);
if(varname.equals("*"))
{
if(H!=null)
{
for(final Enumeration<String> e=H.keys();e.hasMoreElements();)
{
final String vn=e.nextElement();
set.add(mobname,vn);
}
}
}
else
set.add(mobname,varname);
}
return set;
}
protected String getStatValue(final Environmental E, final String arg2)
{
boolean found=false;
String val="";
final String uarg2=arg2.toUpperCase().trim();
for(int i=0;i<E.getStatCodes().length;i++)
{
if(E.getStatCodes()[i].equals(uarg2))
{
val=E.getStat(uarg2);
found=true;
break;
}
}
if((!found)&&(E instanceof MOB))
{
final MOB M=(MOB)E;
for(final int i : CharStats.CODES.ALLCODES())
{
if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2))
{
val=""+M.charStats().getStat(CharStats.CODES.NAME(i)); //yes, this is right
found=true;
break;
}
}
if(!found)
{
for(int i=0;i<M.curState().getStatCodes().length;i++)
{
if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=M.curState().getStat(M.curState().getStatCodes()[i]);
found=true;
break;
}
}
}
if(!found)
{
for(int i=0;i<M.phyStats().getStatCodes().length;i++)
{
if(M.phyStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=M.phyStats().getStat(M.phyStats().getStatCodes()[i]);
found=true;
break;
}
}
}
if((!found)&&(M.playerStats()!=null))
{
for(int i=0;i<M.playerStats().getStatCodes().length;i++)
{
if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]);
found=true;
break;
}
}
}
if((!found)&&(uarg2.startsWith("BASE")))
{
for(int i=0;i<M.baseState().getStatCodes().length;i++)
{
if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4)))
{
val=M.baseState().getStat(M.baseState().getStatCodes()[i]);
found=true;
break;
}
}
}
if((!found)&&(uarg2.equals("STINK")))
{
found=true;
val=CMath.toPct(M.playerStats().getHygiene()/PlayerStats.HYGIENE_DELIMIT);
}
if((!found)
&&(CMath.s_valueOf(GenericBuilder.GenMOBBonusFakeStats.class,uarg2)!=null))
{
found=true;
val=CMLib.coffeeMaker().getAnyGenStat(M, uarg2);
}
}
if((!found)
&&(E instanceof Item)
&&(CMath.s_valueOf(GenericBuilder.GenItemBonusFakeStats.class,uarg2)!=null))
{
found=true;
val=CMLib.coffeeMaker().getAnyGenStat((Item)E, uarg2);
}
if((!found)
&&(E instanceof Physical)
&&(CMath.s_valueOf(GenericBuilder.GenPhysBonusFakeStats.class,uarg2)!=null))
{
found=true;
val=CMLib.coffeeMaker().getAnyGenStat((Physical)E, uarg2);
}
if(!found)
return null;
return val;
}
protected String getGStatValue(final Environmental E, String arg2)
{
if(E==null)
return null;
boolean found=false;
String val="";
for(int i=0;i<E.getStatCodes().length;i++)
{
if(E.getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=E.getStat(arg2);
found=true; break;
}
}
if(!found)
if(E instanceof MOB)
{
arg2=arg2.toUpperCase().trim();
final GenericBuilder.GenMOBCode element = (GenericBuilder.GenMOBCode)CMath.s_valueOf(GenericBuilder.GenMOBCode.class,arg2);
if(element != null)
{
val=CMLib.coffeeMaker().getGenMobStat((MOB)E,element.name());
found=true;
}
if(!found)
{
final MOB M=(MOB)E;
for(final int i : CharStats.CODES.ALLCODES())
{
if(CharStats.CODES.NAME(i).equals(arg2)||CharStats.CODES.DESC(i).equals(arg2))
{
val=""+M.charStats().getStat(CharStats.CODES.NAME(i));
found=true;
break;
}
}
if(!found)
{
for(int i=0;i<M.curState().getStatCodes().length;i++)
{
if(M.curState().getStatCodes()[i].equals(arg2))
{
val=M.curState().getStat(M.curState().getStatCodes()[i]);
found=true;
break;
}
}
}
if(!found)
{
for(int i=0;i<M.phyStats().getStatCodes().length;i++)
{
if(M.phyStats().getStatCodes()[i].equals(arg2))
{
val=M.phyStats().getStat(M.phyStats().getStatCodes()[i]);
found=true;
break;
}
}
}
if((!found)&&(M.playerStats()!=null))
{
for(int i=0;i<M.playerStats().getStatCodes().length;i++)
{
if(M.playerStats().getStatCodes()[i].equals(arg2))
{
val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]);
found=true;
break;
}
}
}
if((!found)&&(arg2.startsWith("BASE")))
{
final String arg4=arg2.substring(4);
for(int i=0;i<M.baseState().getStatCodes().length;i++)
{
if(M.baseState().getStatCodes()[i].equals(arg4))
{
val=M.baseState().getStat(M.baseState().getStatCodes()[i]);
found=true;
break;
}
}
if(!found)
{
for(final int i : CharStats.CODES.ALLCODES())
{
if(CharStats.CODES.NAME(i).equals(arg4)||CharStats.CODES.DESC(i).equals(arg4))
{
val=""+M.baseCharStats().getStat(CharStats.CODES.NAME(i));
found=true;
break;
}
}
}
}
if((!found)&&(arg2.equals("STINK")))
{
found=true;
val=CMath.toPct(M.playerStats().getHygiene()/PlayerStats.HYGIENE_DELIMIT);
}
}
}
else
if(E instanceof Item)
{
final GenericBuilder.GenItemCode code = (GenericBuilder.GenItemCode)CMath.s_valueOf(GenericBuilder.GenItemCode.class, arg2.toUpperCase().trim());
if(code != null)
{
val=CMLib.coffeeMaker().getGenItemStat((Item)E,code.name());
found=true;
}
}
if((!found)
&&(E instanceof Physical))
{
if(CMLib.coffeeMaker().isAnyGenStat((Physical)E, arg2.toUpperCase().trim()))
return CMLib.coffeeMaker().getAnyGenStat((Physical)E, arg2.toUpperCase().trim());
if((!found)&&(arg2.startsWith("BASE")))
{
final String arg4=arg2.substring(4);
for(int i=0;i<((Physical)E).basePhyStats().getStatCodes().length;i++)
{
if(((Physical)E).basePhyStats().getStatCodes()[i].equals(arg4))
{
val=((Physical)E).basePhyStats().getStat(((Physical)E).basePhyStats().getStatCodes()[i]);
found=true;
break;
}
}
}
}
if(found)
return val;
return null;
}
protected List<Ability> getQuestAbilities()
{
final List<Ability> able=new ArrayList<Ability>();
final Quest Q=defaultQuest();
if(Q!=null)
{
final Ability A=(Ability)Q.getDesignatedObject("ABILITY");
if(A!=null)
able.add(A);
@SuppressWarnings("unchecked")
final
List<Ability> grp=(List<Ability>)Q.getDesignatedObject("ABILITYGROUP");
if(grp != null)
able.addAll(grp);
final Object O=Q.getDesignatedObject("TOOL");
if(O instanceof Ability)
able.add((Ability)O);
@SuppressWarnings("unchecked")
final
List<Object> grp2=(List<Object>)Q.getDesignatedObject("TOOLGROUP");
if(grp2 != null)
{
for(final Object O1 : grp2)
{
if(O1 instanceof Ability)
able.add((Ability)O1);
}
}
}
return able;
}
protected Ability getAbility(final String arg)
{
if((arg==null)||(arg.length()==0))
return null;
Ability A;
A=CMClass.getAbility(arg);
if(A!=null)
return A;
for(final Ability A1 : getQuestAbilities())
{
if(A1.ID().equalsIgnoreCase(arg))
return (Ability)A1.copyOf();
}
return null;
}
protected Ability findAbility(final String arg)
{
if((arg==null)||(arg.length()==0))
return null;
Ability A;
A=CMClass.findAbility(arg);
if(A!=null)
return A;
final List<Ability> ableV=getQuestAbilities();
A=(Ability)CMLib.english().fetchEnvironmental(ableV,arg,true);
if(A==null)
A=(Ability)CMLib.english().fetchEnvironmental(ableV,arg,false);
if(A!=null)
return (Ability)A.copyOf();
return null;
}
@Override
public void setVar(final String baseName, String key, String val)
{
final PairList<String,String> vars=getScriptVarSet(baseName,key);
for(int v=0;v<vars.size();v++)
{
final String name=vars.elementAtFirst(v);
key=vars.elementAtSecond(v).toUpperCase();
@SuppressWarnings("unchecked")
Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+name);
if((H==null)&&(defaultQuestName!=null)&&(defaultQuestName.length()>0))
{
final MOB M=CMLib.players().getPlayerAllHosts(name);
if(M!=null)
{
for(final Enumeration<ScriptingEngine> e=M.scripts();e.hasMoreElements();)
{
final ScriptingEngine SE=e.nextElement();
if((SE!=null)
&&(SE!=this)
&&(defaultQuestName.equalsIgnoreCase(SE.defaultQuestName()))
&&(SE.isVar(name,key)))
{
SE.setVar(name,key,val);
return;
}
}
}
}
if(H==null)
{
if(val.length()==0)
continue;
H=new Hashtable<String,String>();
resources._submitResource("SCRIPTVAR-"+name,H);
}
if(val.length()>0)
{
switch(val.charAt(0))
{
case '+':
if(val.equals("++"))
{
String num=H.get(key);
if(num==null)
num="0";
val=Integer.toString(CMath.s_int(num.trim())+1);
}
else
{
String num=H.get(key);
// add via +number form
if(CMath.isNumber(val.substring(1).trim()))
{
if(num==null)
num="0";
val=val.substring(1);
final int amount=CMath.s_int(val.trim());
val=Integer.toString(CMath.s_int(num.trim())+amount);
}
else
if((num!=null)&&(CMath.isNumber(num)))
val=num;
}
break;
case '-':
if(val.equals("--"))
{
String num=H.get(key);
if(num==null)
num="0";
val=Integer.toString(CMath.s_int(num.trim())-1);
}
else
{
// subtract -number form
String num=H.get(key);
if(CMath.isNumber(val.substring(1).trim()))
{
val=val.substring(1);
final int amount=CMath.s_int(val.trim());
if(num==null)
num="0";
val=Integer.toString(CMath.s_int(num.trim())-amount);
}
else
if((num!=null)&&(CMath.isNumber(num)))
val=num;
}
break;
case '*':
{
// multiply via *number form
String num=H.get(key);
if(CMath.isNumber(val.substring(1).trim()))
{
val=val.substring(1);
final int amount=CMath.s_int(val.trim());
if(num==null)
num="0";
val=Integer.toString(CMath.s_int(num.trim())*amount);
}
else
if((num!=null)&&(CMath.isNumber(num)))
val=num;
break;
}
case '/':
{
// divide /number form
String num=H.get(key);
if(CMath.isNumber(val.substring(1).trim()))
{
val=val.substring(1);
final int amount=CMath.s_int(val.trim());
if(num==null)
num="0";
if(amount==0)
Log.errOut("Scripting","Scripting SetVar error: Division by 0: "+name+"/"+key+"="+val);
else
val=Integer.toString(CMath.s_int(num.trim())/amount);
}
else
if((num!=null)&&(CMath.isNumber(num)))
val=num;
break;
}
default:
break;
}
}
if(H.containsKey(key))
H.remove(key);
if(val.trim().length()>0)
H.put(key,val);
if(H.size()==0)
resources._removeResource("SCRIPTVAR-"+name);
}
}
@Override
public String[] parseEval(final String evaluable) throws ScriptParseException
{
final int STATE_MAIN=0;
final int STATE_INFUNCTION=1;
final int STATE_INFUNCQUOTE=2;
final int STATE_POSTFUNCTION=3;
final int STATE_POSTFUNCEVAL=4;
final int STATE_POSTFUNCQUOTE=5;
final int STATE_MAYFUNCTION=6;
buildHashes();
final List<String> V=new ArrayList<String>();
if((evaluable==null)||(evaluable.trim().length()==0))
return new String[]{};
final char[] evalC=evaluable.toCharArray();
int state=0;
int dex=0;
char lastQuote='\0';
String s=null;
int depth=0;
for(int c=0;c<evalC.length;c++)
{
switch(state)
{
case STATE_MAIN:
{
if(Character.isWhitespace(evalC[c]))
{
s=new String(evalC,dex,c-dex).trim();
if(s.length()>0)
{
s=s.toUpperCase();
V.add(s);
dex=c+1;
if(funcH.containsKey(s))
state=STATE_MAYFUNCTION;
else
if(!connH.containsKey(s))
throw new ScriptParseException("Unknown keyword: "+s);
}
}
else
if(Character.isLetter(evalC[c])
||(Character.isDigit(evalC[c])
&&(c>0)&&Character.isLetter(evalC[c-1])
&&(c<evalC.length-1)
&&Character.isLetter(evalC[c+1])))
{ /* move along */
}
else
{
switch(evalC[c])
{
case '!':
{
if(c==evalC.length-1)
throw new ScriptParseException("Bad Syntax on last !");
V.add("NOT");
dex=c+1;
break;
}
case '(':
{
s=new String(evalC,dex,c-dex).trim();
if(s.length()>0)
{
s=s.toUpperCase();
V.add(s);
V.add("(");
dex=c+1;
if(funcH.containsKey(s))
state=STATE_INFUNCTION;
else
if(connH.containsKey(s))
state=STATE_MAIN;
else
throw new ScriptParseException("Unknown keyword: "+s);
}
else
{
V.add("(");
depth++;
dex=c+1;
}
break;
}
case ')':
s=new String(evalC,dex,c-dex).trim();
if(s.length()>0)
throw new ScriptParseException("Bad syntax before ) at: "+s);
if(depth==0)
throw new ScriptParseException("Unmatched ) character");
V.add(")");
depth--;
dex=c+1;
break;
default:
throw new ScriptParseException("Unknown character at: "+new String(evalC,dex,c-dex+1).trim()+": "+evaluable);
}
}
break;
}
case STATE_MAYFUNCTION:
{
if(evalC[c]=='(')
{
V.add("(");
dex=c+1;
state=STATE_INFUNCTION;
}
else
if(!Character.isWhitespace(evalC[c]))
throw new ScriptParseException("Expected ( at "+evalC[c]+": "+evaluable);
break;
}
case STATE_POSTFUNCTION:
{
if(!Character.isWhitespace(evalC[c]))
{
switch(evalC[c])
{
case '=':
case '>':
case '<':
case '!':
{
if(c==evalC.length-1)
throw new ScriptParseException("Bad Syntax on last "+evalC[c]);
if(!Character.isWhitespace(evalC[c+1]))
{
s=new String(evalC,c,2);
if((!signH.containsKey(s))&&(evalC[c]!='!'))
s=""+evalC[c];
}
else
s=""+evalC[c];
if(!signH.containsKey(s))
{
c=dex-1;
state=STATE_MAIN;
break;
}
V.add(s);
dex=c+(s.length());
c=c+(s.length()-1);
state=STATE_POSTFUNCEVAL;
break;
}
default:
c=dex-1;
state=STATE_MAIN;
break;
}
}
break;
}
case STATE_INFUNCTION:
{
if(evalC[c]==')')
{
V.add(new String(evalC,dex,c-dex));
V.add(")");
dex=c+1;
state=STATE_POSTFUNCTION;
}
else
if((evalC[c]=='\'')||(evalC[c]=='`'))
{
lastQuote=evalC[c];
state=STATE_INFUNCQUOTE;
}
break;
}
case STATE_INFUNCQUOTE:
{
if((evalC[c]==lastQuote)
&&((c==evalC.length-1)
||((!Character.isLetter(evalC[c-1]))
||(!Character.isLetter(evalC[c+1])))))
state=STATE_INFUNCTION;
break;
}
case STATE_POSTFUNCQUOTE:
{
if(evalC[c]==lastQuote)
{
if((V.size()>2)
&&(signH.containsKey(V.get(V.size()-1)))
&&(V.get(V.size()-2).equals(")")))
{
final String sign=V.get(V.size()-1);
V.remove(V.size()-1);
V.remove(V.size()-1);
final String prev=V.get(V.size()-1);
if(prev.equals("("))
s=sign+" "+new String(evalC,dex+1,c-dex);
else
{
V.remove(V.size()-1);
s=prev+" "+sign+" "+new String(evalC,dex+1,c-dex);
}
V.add(s);
V.add(")");
dex=c+1;
state=STATE_MAIN;
}
else
throw new ScriptParseException("Bad postfunc Eval somewhere");
}
break;
}
case STATE_POSTFUNCEVAL:
{
if(Character.isWhitespace(evalC[c]))
{
s=new String(evalC,dex,c-dex).trim();
if(s.length()>0)
{
if((V.size()>1)
&&(signH.containsKey(V.get(V.size()-1)))
&&(V.get(V.size()-2).equals(")")))
{
final String sign=V.get(V.size()-1);
V.remove(V.size()-1);
V.remove(V.size()-1);
final String prev=V.get(V.size()-1);
if(prev.equals("("))
s=sign+" "+new String(evalC,dex+1,c-dex);
else
{
V.remove(V.size()-1);
s=prev+" "+sign+" "+new String(evalC,dex+1,c-dex);
}
V.add(s);
V.add(")");
dex=c+1;
state=STATE_MAIN;
}
else
throw new ScriptParseException("Bad postfunc Eval somewhere");
}
}
else
if(Character.isLetterOrDigit(evalC[c]))
{ /* move along */
}
else
if((evalC[c]=='\'')||(evalC[c]=='`'))
{
s=new String(evalC,dex,c-dex).trim();
if(s.length()==0)
{
lastQuote=evalC[c];
state=STATE_POSTFUNCQUOTE;
}
}
break;
}
}
}
if((state==STATE_POSTFUNCQUOTE)
||(state==STATE_INFUNCQUOTE))
throw new ScriptParseException("Unclosed "+lastQuote+" in "+evaluable);
if(depth>0)
throw new ScriptParseException("Unclosed ( in "+evaluable);
return CMParms.toStringArray(V);
}
public void pushEvalBoolean(final List<Object> stack, boolean trueFalse)
{
if(stack.size()>0)
{
final Object O=stack.get(stack.size()-1);
if(O instanceof Integer)
{
final int connector=((Integer)O).intValue();
stack.remove(stack.size()-1);
if((stack.size()>0)
&&((stack.get(stack.size()-1) instanceof Boolean)))
{
final boolean preTrueFalse=((Boolean)stack.get(stack.size()-1)).booleanValue();
stack.remove(stack.size()-1);
switch(connector)
{
case CONNECTOR_AND:
trueFalse = preTrueFalse && trueFalse;
break;
case CONNECTOR_OR:
trueFalse = preTrueFalse || trueFalse;
break;
case CONNECTOR_ANDNOT:
trueFalse = preTrueFalse && (!trueFalse);
break;
case CONNECTOR_NOT:
case CONNECTOR_ORNOT:
trueFalse = preTrueFalse || (!trueFalse);
break;
}
}
else
switch(connector)
{
case CONNECTOR_ANDNOT:
case CONNECTOR_NOT:
case CONNECTOR_ORNOT:
trueFalse = !trueFalse;
break;
default:
break;
}
}
else
if(O instanceof Boolean)
{
final boolean preTrueFalse=((Boolean)stack.get(stack.size()-1)).booleanValue();
stack.remove(stack.size()-1);
trueFalse=preTrueFalse&&trueFalse;
}
}
stack.add(trueFalse?Boolean.TRUE:Boolean.FALSE);
}
/**
* Returns the index, in the given string vector, of the given string, starting
* from the given index. If the string to search for contains more than one
* "word", where a word is defined in space-delimited terms respecting double-quotes,
* then it will return the index at which all the words in the parsed search string
* are found in the given string list.
* @param V the string list to search in
* @param str the string to search for
* @param start the index to start at (0 is good)
* @return the index at which the search string was found in the string list, or -1
*/
private static int strIndex(final Vector<String> V, final String str, final int start)
{
int x=V.indexOf(str,start);
if(x>=0)
return x;
final List<String> V2=CMParms.parse(str);
if(V2.size()==0)
return -1;
x=V.indexOf(V2.get(0),start);
boolean found=false;
while((x>=0)&&((x+V2.size())<=V.size())&&(!found))
{
found=true;
for(int v2=1;v2<V2.size();v2++)
{
if(!V.get(x+v2).equals(V2.get(v2)))
{
found=false;
break;
}
}
if(!found)
x=V.indexOf(V2.get(0),x+1);
}
if(found)
return x;
return -1;
}
/**
* Weird method. Accepts a string list, a combiner (see below), a string buffer to search for,
* and a previously found index. The stringbuffer is always cleared during this call.
* If the stringbuffer was empty, the previous found index is returned. Otherwise:
* If the combiner is '&', the first index of the given stringbuffer in the string list is returned (or -1).
* If the combiner is '|', the previous index is returned if it was found, otherwise the first index
* of the given stringbuffer in the string list is returned (or -1).
* If the combiner is '>', then the previous index is returned if it was not found (-1), otherwise the
* next highest found stringbuffer since the last string list search is returned, or (-1) if no more found.
* If the combiner is '<', then the previous index is returned if it was not found (-1), otherwise the
* first found stringbuffer index is returned if it is lower than the previously found index.
* Other combiners return -1.
* @param V the string list to search
* @param combiner the combiner, either &,|,<,or >.
* @param buf the stringbuffer to search for, which is always cleared
* @param lastIndex the previously found index
* @return the result of the search
*/
private static int stringContains(final Vector<String> V, final char combiner, final StringBuffer buf, int lastIndex)
{
final String str=buf.toString().trim();
if(str.length()==0)
return lastIndex;
buf.setLength(0);
switch (combiner)
{
case '&':
lastIndex = strIndex(V, str, 0);
return lastIndex;
case '|':
if (lastIndex >= 0)
return lastIndex;
return strIndex(V, str, 0);
case '>':
if (lastIndex < 0)
return lastIndex;
return strIndex(V, str, lastIndex + 1);
case '<':
{
if (lastIndex < 0)
return lastIndex;
final int newIndex = strIndex(V, str, 0);
if (newIndex < lastIndex)
return newIndex;
return -1;
}
}
return -1;
}
/**
* Main workhorse of the stringcontains mobprog function.
* @param V parsed string to search
* @param str the coded search function
* @param index a 1-dim array of the index in the coded search str to start the search at
* @param depth the number of close parenthesis to expect
* @return the last index in the coded search function evaluated
*/
private static int stringContains(final Vector<String> V, final char[] str, final int[] index, final int depth)
{
final StringBuffer buf=new StringBuffer("");
int lastIndex=0;
boolean quoteMode=false;
char combiner='&';
for(int i=index[0];i<str.length;i++)
{
switch(str[i])
{
case ')':
if((depth>0)&&(!quoteMode))
{
index[0]=i;
return stringContains(V,combiner,buf,lastIndex);
}
buf.append(str[i]);
break;
case ' ':
buf.append(str[i]);
break;
case '&':
case '|':
case '>':
case '<':
if(quoteMode)
buf.append(str[i]);
else
{
lastIndex=stringContains(V,combiner,buf,lastIndex);
combiner=str[i];
}
break;
case '(':
if(!quoteMode)
{
lastIndex=stringContains(V,combiner,buf,lastIndex);
index[0]=i+1;
final int newIndex=stringContains(V,str,index,depth+1);
i=index[0];
switch(combiner)
{
case '&':
if((lastIndex<0)||(newIndex<0))
lastIndex=-1;
break;
case '|':
if(newIndex>=0)
lastIndex=newIndex;
break;
case '>':
if(newIndex<=lastIndex)
lastIndex=-1;
else
lastIndex=newIndex;
break;
case '<':
if((newIndex<0)||(newIndex>=lastIndex))
lastIndex=-1;
else
lastIndex=newIndex;
break;
}
}
else
buf.append(str[i]);
break;
case '\"':
quoteMode=(!quoteMode);
break;
case '\\':
if(i<str.length-1)
{
buf.append(str[i+1]);
i++;
}
break;
default:
if(Character.isLetter(str[i]))
buf.append(Character.toLowerCase(str[i]));
else
buf.append(str[i]);
break;
}
}
return stringContains(V,combiner,buf,lastIndex);
}
/**
* As the name implies, this is the implementation of the stringcontains mobprog function
* @param str1 the string to search in
* @param str2 the coded search expression
* @return the index of the found string in the first string
*/
protected final static int stringContainsFunctionImpl(final String str1, final String str2)
{
final StringBuffer buf1=new StringBuffer(str1.toLowerCase());
for(int i=buf1.length()-1;i>=0;i--)
{
switch(buf1.charAt(i))
{
case ' ':
case '\"':
case '`':
break;
case '\'':
buf1.setCharAt(i, '`');
break;
default:
if(!Character.isLetterOrDigit(buf1.charAt(i)))
buf1.setCharAt(i,' ');
break;
}
}
final StringBuffer buf2=new StringBuffer(str2.toLowerCase());
for(int i=buf2.length()-1;i>=0;i--)
{
switch(buf2.charAt(i))
{
case ' ':
case '\"':
case '`':
break;
case '\'':
buf2.setCharAt(i, '`');
break;
case ')': case '(': case '|': case '>': case '<':
// these are the actual control codes for strcontains
break;
default:
if(!Character.isLetterOrDigit(buf2.charAt(i)))
buf2.setCharAt(i,' ');
break;
}
}
final Vector<String> V=CMParms.parse(buf1.toString());
return stringContains(V,buf2.toString().toCharArray(),new int[]{0},0);
}
@Override
public boolean eval(final PhysicalAgent scripted,
final MOB source,
final Environmental target,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final String msg,
Object[] tmp,
final String[][] eval,
final int startEval)
{
String[] tt=eval[0];
if(tmp == null)
tmp = newObjs();
final List<Object> stack=new ArrayList<Object>();
for(int t=startEval;t<tt.length;t++)
{
if(tt[t].equals("("))
stack.add(tt[t]);
else
if(tt[t].equals(")"))
{
if(stack.size()>0)
{
if((!(stack.get(stack.size()-1) instanceof Boolean))
||(stack.size()==1)
||(!(stack.get(stack.size()-2)).equals("(")))
{
logError(scripted,"EVAL","SYNTAX",") Format error: "+CMParms.toListString(tt));
return false;
}
final boolean b=((Boolean)stack.get(stack.size()-1)).booleanValue();
stack.remove(stack.size()-1);
stack.remove(stack.size()-1);
pushEvalBoolean(stack,b);
}
}
else
if(connH.containsKey(tt[t]))
{
Integer curr=connH.get(tt[t]);
if((stack.size()>0)
&&(stack.get(stack.size()-1) instanceof Integer))
{
final int old=((Integer)stack.get(stack.size()-1)).intValue();
stack.remove(stack.size()-1);
curr=Integer.valueOf(CONNECTOR_MAP[old][curr.intValue()]);
}
stack.add(curr);
}
else
if(funcH.containsKey(tt[t]))
{
final Integer funcCode=funcH.get(tt[t]);
if((t==tt.length-1)
||(!tt[t+1].equals("(")))
{
logError(scripted,"EVAL","SYNTAX","No ( for fuction "+tt[t]+": "+CMParms.toListString(tt));
return false;
}
t+=2;
int tlen=0;
while(((t+tlen)<tt.length)&&(!tt[t+tlen].equals(")")))
tlen++;
if((t+tlen)==tt.length)
{
logError(scripted,"EVAL","SYNTAX","No ) for fuction "+tt[t-1]+": "+CMParms.toListString(tt));
return false;
}
tickStatus=Tickable.STATUS_MISC+funcCode.intValue();
final String funcParms=tt[t];
boolean returnable=false;
switch(funcCode.intValue())
{
case 1: // rand
{
String num=funcParms;
if(num.endsWith("%"))
num=num.substring(0,num.length()-1);
final int arg=CMath.s_int(num);
if(CMLib.dice().rollPercentage()<arg)
returnable=true;
else
returnable=false;
break;
}
case 2: // has
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HAS","Syntax","'"+eval[0][t]+"' in "+CMParms.toListString(eval[0]));
return returnable;
}
if(E==null)
returnable=false;
else
{
if((E instanceof MOB)
&&(((MOB)E).findItem(arg2)!=null))
returnable = true;
else
if((E instanceof Room)
&&(((Room)E).findItem(arg2)!=null))
returnable=true;
else
{
final Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
{
if(E2!=null)
returnable=((MOB)E).isMine(E2);
else
returnable=(((MOB)E).findItem(arg2)!=null);
}
else
if(E instanceof Item)
returnable=CMLib.english().containsString(E.name(),arg2);
else
if(E instanceof Room)
{
if(E2 instanceof Item)
returnable=((Room)E).isContent((Item)E2);
else
returnable=(((Room)E).findItem(null,arg2)!=null);
}
else
returnable=false;
}
}
break;
}
case 74: // hasnum
{
if (tlen == 1)
tt = parseBits(eval, t, "cccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String cmp=tt[t+2];
final String value=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((value.length()==0)||(item.length()==0)||(cmp.length()==0))
{
logError(scripted,"HASNUM","Syntax",funcParms);
return returnable;
}
Item I=null;
int num=0;
if(E==null)
returnable=false;
else
if(E instanceof MOB)
{
final MOB M=(MOB)E;
for(int i=0;i<M.numItems();i++)
{
I=M.getItem(i);
if(I==null)
break;
if((item.equalsIgnoreCase("all"))
||(CMLib.english().containsString(I.Name(),item)))
num++;
}
returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM");
}
else
if(E instanceof Item)
{
num=CMLib.english().containsString(E.name(),item)?1:0;
returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM");
}
else
if(E instanceof Room)
{
final Room R=(Room)E;
for(int i=0;i<R.numItems();i++)
{
I=R.getItem(i);
if(I==null)
break;
if((item.equalsIgnoreCase("all"))
||(CMLib.english().containsString(I.Name(),item)))
num++;
}
returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM");
}
else
returnable=false;
break;
}
case 67: // hastitle
{
if (tlen == 1)
tt = parseBits(eval, t, "cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HASTITLE","Syntax",funcParms);
return returnable;
}
if(E instanceof MOB)
{
final MOB M=(MOB)E;
returnable=(M.playerStats()!=null)&&(M.playerStats().getTitles().contains(arg2));
}
else
returnable=false;
break;
}
case 3: // worn
{
if (tlen == 1)
tt = parseBits(eval, t, "cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"WORN","Syntax",funcParms);
return returnable;
}
if(E==null)
returnable=false;
else
if(E instanceof MOB)
returnable=(((MOB)E).fetchItem(null,Wearable.FILTER_WORNONLY,arg2)!=null);
else
if(E instanceof Item)
returnable=(CMLib.english().containsString(E.name(),arg2)&&(!((Item)E).amWearingAt(Wearable.IN_INVENTORY)));
else
returnable=false;
break;
}
case 4: // isnpc
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=((MOB)E).isMonster();
break;
}
case 87: // isbirthday
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final MOB mob=(MOB)E;
if(mob.playerStats()==null)
returnable=false;
else
{
final TimeClock C=CMLib.time().localClock(mob.getStartRoom());
final int month=C.getMonth();
final int day=C.getDayOfMonth();
final int bday=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_DAY];
final int bmonth=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_MONTH];
if((C.getYear()==mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_LASTYEARCELEBRATED])
&&((month==bmonth)&&(day==bday)))
returnable=true;
else
returnable=false;
}
}
break;
}
case 5: // ispc
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=!((MOB)E).isMonster();
break;
}
case 6: // isgood
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
returnable=CMLib.flags().isGood(P);
break;
}
case 8: // isevil
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
returnable=CMLib.flags().isEvil(P);
break;
}
case 9: // isneutral
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
returnable=CMLib.flags().isNeutral(P);
break;
}
case 54: // isalive
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead()))
returnable=true;
else
returnable=false;
break;
}
case 58: // isable
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead()))
{
final ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true);
if(X!=null)
returnable=((MOB)E).fetchExpertise(X.ID())!=null;
else
returnable=((MOB)E).findAbility(arg2)!=null;
}
else
returnable=false;
break;
}
case 112: // cansee
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final PhysicalAgent MP=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(!(MP instanceof MOB))
returnable=false;
else
{
final MOB M=(MOB)MP;
final Physical P=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
returnable=CMLib.flags().canBeSeenBy(P, M);
}
break;
}
case 113: // canhear
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final PhysicalAgent MP=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(!(MP instanceof MOB))
returnable=false;
else
{
final MOB M=(MOB)MP;
final Physical P=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
returnable=CMLib.flags().canBeHeardMovingBy(P, M);
}
break;
}
case 59: // isopen
{
final String arg1=CMParms.cleanBit(funcParms);
final int dir=CMLib.directions().getGoodDirectionCode(arg1);
returnable=false;
if(dir<0)
{
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof Container))
returnable=((Container)E).isOpen();
else
if((E!=null)&&(E instanceof Exit))
returnable=((Exit)E).isOpen();
}
else
if(lastKnownLocation!=null)
{
final Exit E=lastKnownLocation.getExitInDir(dir);
if(E!=null)
returnable= E.isOpen();
}
break;
}
case 60: // islocked
{
final String arg1=CMParms.cleanBit(funcParms);
final int dir=CMLib.directions().getGoodDirectionCode(arg1);
returnable=false;
if(dir<0)
{
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof Container))
returnable=((Container)E).isLocked();
else
if((E!=null)&&(E instanceof Exit))
returnable=((Exit)E).isLocked();
}
else
if(lastKnownLocation!=null)
{
final Exit E=lastKnownLocation.getExitInDir(dir);
if(E!=null)
returnable= E.isLocked();
}
break;
}
case 10: // isfight
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=((MOB)E).isInCombat();
break;
}
case 11: // isimmort
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=CMSecurity.isAllowed(((MOB)E),lastKnownLocation,CMSecurity.SecFlag.IMMORT);
break;
}
case 12: // ischarmed
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING).size()>0;
break;
}
case 15: // isfollow
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
if(((MOB)E).amFollowing()==null)
returnable=false;
else
if(((MOB)E).amFollowing().location()!=lastKnownLocation)
returnable=false;
else
returnable=true;
break;
}
case 73: // isservant
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB))||(lastKnownLocation==null))
returnable=false;
else
if((((MOB)E).getLiegeID()==null)||(((MOB)E).getLiegeID().length()==0))
returnable=false;
else
if(lastKnownLocation.fetchInhabitant("$"+((MOB)E).getLiegeID()+"$")==null)
returnable=false;
else
returnable=true;
break;
}
case 95: // isspeaking
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB))||(lastKnownLocation==null))
returnable=false;
else
{
final MOB TM=(MOB)E;
final Language L=CMLib.utensils().getLanguageSpoken(TM);
if((L!=null)
&&(!L.ID().equalsIgnoreCase("Common"))
&&(L.ID().equalsIgnoreCase(arg2)||L.Name().equalsIgnoreCase(arg2)||arg2.equalsIgnoreCase("any")))
returnable=true;
else
if(arg2.equalsIgnoreCase("common")||arg2.equalsIgnoreCase("none"))
returnable=true;
else
returnable=false;
}
break;
}
case 55: // ispkill
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
if(((MOB)E).isAttributeSet(MOB.Attrib.PLAYERKILL))
returnable=true;
else
returnable=false;
break;
}
case 7: // isname
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=CMLib.english().containsString(E.name(),arg2);
break;
}
case 56: // name
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=simpleEvalStr(scripted,E.Name(),arg3,arg2,"NAME");
break;
}
case 75: // currency
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=simpleEvalStr(scripted,CMLib.beanCounter().getCurrency(E),arg3,arg2,"CURRENCY");
break;
}
case 61: // strin
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2;
if(tt[t+1].equals("$$r"))
arg2=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(monster));
else
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final List<String> V=CMParms.parse(arg1.toUpperCase());
returnable=V.contains(arg2.toUpperCase());
break;
}
case 62: // callfunc
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
String found=null;
boolean validFunc=false;
final List<DVector> scripts=getScripts();
String trigger=null;
String[] ttrigger=null;
for(int v=0;v<scripts.size();v++)
{
final DVector script2=scripts.get(v);
if(script2.size()<1)
continue;
trigger=((String)script2.elementAt(0,1)).toUpperCase().trim();
ttrigger=(String[])script2.elementAt(0,2);
if(getTriggerCode(trigger,ttrigger)==17)
{
final String fnamed=
(ttrigger!=null)
?ttrigger[1]
:CMParms.getCleanBit(trigger,1);
if(fnamed.equalsIgnoreCase(arg1))
{
validFunc=true;
found=
execute(scripted,
source,
target,
monster,
primaryItem,
secondaryItem,
script2,
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2),
tmp);
if(found==null)
found="";
break;
}
}
}
if(!validFunc)
logError(scripted,"CALLFUNC","Unknown","Function: "+arg1);
else
if(found!=null)
{
final String resp=found.trim().toLowerCase();
if(resp.equals("cancel"))
returnable=false;
else
returnable=resp.length()!=0;
}
else
returnable=false;
break;
}
case 14: // affected
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
{
final Ability A=findAbility(arg2);
if((A==null)||(arg2==null)||(arg2.length()==0))
logError(scripted,"AFFECTED","RunTime",arg2+" is not a valid ability name.");
else
if(A!=null)
arg2=A.ID();
returnable=(P.fetchEffect(arg2)!=null);
}
break;
}
case 69: // isbehave
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final PhysicalAgent P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
{
final Behavior B=CMClass.findBehavior(arg2);
if(B!=null)
arg2=B.ID();
returnable=(P.fetchBehavior(arg2)!=null);
}
break;
}
case 70: // ipaddress
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB))||(((MOB)E).isMonster()))
returnable=false;
else
returnable=simpleEvalStr(scripted,((MOB)E).session().getAddress(),arg3,arg2,"ADDRESS");
break;
}
case 28: // questwinner
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
arg1=E.Name();
if(arg2.equalsIgnoreCase("previous"))
{
returnable=true;
final String quest=defaultQuestName();
if((quest!=null)
&&(quest.length()>0))
{
ScriptingEngine prevE=null;
final List<ScriptingEngine> list=new LinkedList<ScriptingEngine>();
for(final Enumeration<ScriptingEngine> e = scripted.scripts();e.hasMoreElements();)
list.add(e.nextElement());
for(final Enumeration<Behavior> b=scripted.behaviors();b.hasMoreElements();)
{
final Behavior B=b.nextElement();
if(B instanceof ScriptingEngine)
list.add((ScriptingEngine)B);
}
for(final ScriptingEngine engine : list)
{
if((engine!=null)
&&(engine.defaultQuestName()!=null)
&&(engine.defaultQuestName().length()>0))
{
if(engine == this)
{
if(prevE != null)
{
final Quest Q=CMLib.quests().fetchQuest(prevE.defaultQuestName());
if(Q != null)
returnable=Q.wasWinner(arg1);
}
break;
}
prevE=engine;
}
}
}
}
else
{
final Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
returnable=Q.wasWinner(arg1);
}
break;
}
case 93: // questscripted
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final PhysicalAgent E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=tt[t+1];
if(arg2.equalsIgnoreCase("ALL"))
{
returnable=false;
for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();)
{
final Quest Q=q.nextElement();
if(Q.running())
{
if(E!=null)
{
for(final Enumeration<ScriptingEngine> e=E.scripts();e.hasMoreElements();)
{
final ScriptingEngine SE=e.nextElement();
if((SE!=null)&&(SE.defaultQuestName().equalsIgnoreCase(Q.name())))
returnable=true;
}
for(final Enumeration<Behavior> b=E.behaviors();b.hasMoreElements();)
{
final Behavior B=b.nextElement();
if(B instanceof ScriptingEngine)
{
final ScriptingEngine SE=(ScriptingEngine)B;
if((SE.defaultQuestName().equalsIgnoreCase(Q.name())))
returnable=true;
}
}
}
}
}
}
else
{
final Quest Q=getQuest(arg2);
returnable=false;
if((Q!=null)&&(E!=null))
{
for(final Enumeration<ScriptingEngine> e=E.scripts();e.hasMoreElements();)
{
final ScriptingEngine SE=e.nextElement();
if((SE!=null)&&(SE.defaultQuestName().equalsIgnoreCase(Q.name())))
returnable=true;
}
for(final Enumeration<Behavior> b=E.behaviors();b.hasMoreElements();)
{
final Behavior B=b.nextElement();
if(B instanceof ScriptingEngine)
{
final ScriptingEngine SE=(ScriptingEngine)B;
if((SE.defaultQuestName().equalsIgnoreCase(Q.name())))
returnable=true;
}
}
}
}
break;
}
case 94: // questroom
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
final Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
returnable=(Q.getQuestRoomIndex(arg1)>=0);
break;
}
case 114: // questarea
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
final Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
{
int num=1;
Environmental E=Q.getQuestRoom(num);
returnable = false;
final Area parent=CMLib.map().getArea(arg1);
if(parent == null)
logError(scripted,"QUESTAREA","NoArea",funcParms);
else
while(E!=null)
{
final Area A=CMLib.map().areaLocation(E);
if((A==parent)||(parent.isChild(A))||(A.isChild(parent)))
{
returnable=true;
break;
}
num++;
E=Q.getQuestRoom(num);
}
}
break;
}
case 29: // questmob
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
final PhysicalAgent E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.equalsIgnoreCase("ALL"))
{
returnable=false;
for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();)
{
final Quest Q=q.nextElement();
if(Q.running())
{
if(E!=null)
{
if(Q.isObjectInUse(E))
{
returnable=true;
break;
}
}
else
if(Q.getQuestMobIndex(arg1)>=0)
{
returnable=true;
break;
}
}
}
}
else
{
final Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
returnable=(Q.getQuestMobIndex(arg1)>=0);
}
break;
}
case 31: // isquestmobalive
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
if(arg2.equalsIgnoreCase("ALL"))
{
returnable=false;
for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();)
{
final Quest Q=q.nextElement();
if(Q.running())
{
MOB M=null;
if(CMath.s_int(arg1.trim())>0)
M=Q.getQuestMob(CMath.s_int(arg1.trim()));
else
M=Q.getQuestMob(Q.getQuestMobIndex(arg1));
if(M!=null)
{
returnable=!M.amDead();
break;
}
}
}
}
else
{
final Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
{
MOB M=null;
if(CMath.s_int(arg1.trim())>0)
M=Q.getQuestMob(CMath.s_int(arg1.trim()));
else
M=Q.getQuestMob(Q.getQuestMobIndex(arg1));
if(M==null)
returnable=false;
else
returnable=!M.amDead();
}
}
break;
}
case 111: // itemcount
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
if(arg2.length()==0)
{
logError(scripted,"ITEMCOUNT","Syntax",funcParms);
return returnable;
}
if(E==null)
returnable=false;
else
{
int num=0;
if(E instanceof Container)
{
num++;
for(final Item I : ((Container)E).getContents())
num+=I.numberOfItems();
}
else
if(E instanceof Item)
num=((Item)E).numberOfItems();
else
if(E instanceof MOB)
{
for(final Enumeration<Item> i=((MOB)E).items();i.hasMoreElements();)
num += i.nextElement().numberOfItems();
}
else
if(E instanceof Room)
{
for(final Enumeration<Item> i=((Room)E).items();i.hasMoreElements();)
num += i.nextElement().numberOfItems();
}
else
if(E instanceof Area)
{
for(final Enumeration<Room> r=((Area)E).getFilledCompleteMap();r.hasMoreElements();)
{
for(final Enumeration<Item> i=r.nextElement().items();i.hasMoreElements();)
num += i.nextElement().numberOfItems();
}
}
else
returnable=false;
returnable=simpleEval(scripted,""+num,arg3,arg2,"ITEMCOUNT");
}
break;
}
case 32: // nummobsinarea
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase();
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
int num=0;
MaskingLibrary.CompiledZMask MASK=null;
if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("="))))
{
arg1=arg1.substring(4).trim();
arg1=arg1.substring(1).trim();
MASK=CMLib.masking().maskCompile(arg1);
}
for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
final Room R=e.nextElement();
if(arg1.equals("*"))
num+=R.numInhabitants();
else
{
for(int m=0;m<R.numInhabitants();m++)
{
final MOB M=R.fetchInhabitant(m);
if(M==null)
continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.name(),arg1))
num++;
}
}
}
returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBSINAREA");
break;
}
case 33: // nummobs
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase();
final String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
int num=0;
MaskingLibrary.CompiledZMask MASK=null;
if((arg3.toUpperCase().startsWith("MASK")&&(arg3.substring(4).trim().startsWith("="))))
{
arg3=arg3.substring(4).trim();
arg3=arg3.substring(1).trim();
MASK=CMLib.masking().maskCompile(arg3);
}
try
{
for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();)
{
final Room R=e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
final MOB M=R.fetchInhabitant(m);
if(M==null)
continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.name(),arg1))
num++;
}
}
}
catch (final NoSuchElementException nse)
{
}
returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBS");
break;
}
case 34: // numracesinarea
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase();
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
int num=0;
Room R=null;
MOB M=null;
for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
R=e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
M=R.fetchInhabitant(m);
if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1)))
num++;
}
}
returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACESINAREA");
break;
}
case 35: // numraces
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase();
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
int num=0;
try
{
for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();)
{
final Room R=e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
final MOB M=R.fetchInhabitant(m);
if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1)))
num++;
}
}
}
catch (final NoSuchElementException nse)
{
}
returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACES");
break;
}
case 30: // questobj
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
final PhysicalAgent E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.equalsIgnoreCase("ALL"))
{
returnable=false;
for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();)
{
final Quest Q=q.nextElement();
if(Q.running())
{
if(E!=null)
{
if(Q.isObjectInUse(E))
{
returnable=true;
break;
}
}
else
if(Q.getQuestItemIndex(arg1)>=0)
{
returnable=true;
break;
}
}
}
}
else
{
final Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
returnable=(Q.getQuestItemIndex(arg1)>=0);
}
break;
}
case 85: // islike
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=CMLib.masking().maskCheck(arg2, E,false);
break;
}
case 86: // strcontains
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
returnable=stringContainsFunctionImpl(arg1,arg2)>=0;
break;
}
case 92: // isodd
{
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim();
boolean isodd = false;
if( CMath.isLong( val ) )
{
isodd = (CMath.s_long(val) %2 == 1);
}
returnable = isodd;
break;
}
case 16: // hitprcnt
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"HITPRCNT","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints());
final int val1=(int)Math.round(hitPctD*100.0);
returnable=simpleEval(scripted,""+val1,arg3,arg2,"HITPRCNT");
}
break;
}
case 50: // isseason
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
returnable=false;
if(monster.location()!=null)
{
arg1=arg1.toUpperCase();
for(final TimeClock.Season season : TimeClock.Season.values())
{
if(season.toString().startsWith(arg1.toUpperCase())
&&(monster.location().getArea().getTimeObj().getSeasonCode()==season))
{
returnable=true;
break;
}
}
}
break;
}
case 51: // isweather
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
returnable=false;
if(monster.location()!=null)
for(int a=0;a<Climate.WEATHER_DESCS.length;a++)
{
if((Climate.WEATHER_DESCS[a]).startsWith(arg1.toUpperCase())
&&(monster.location().getArea().getClimateObj().weatherType(monster.location())==a))
{
returnable = true;
break;
}
}
break;
}
case 57: // ismoon
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
returnable=false;
if(monster.location()!=null)
{
if(arg1.length()==0)
returnable=monster.location().getArea().getClimateObj().canSeeTheStars(monster.location());
else
{
arg1=arg1.toUpperCase();
for(final TimeClock.MoonPhase phase : TimeClock.MoonPhase.values())
{
if(phase.toString().startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getMoonPhase(monster.location())==phase))
{
returnable=true;
break;
}
}
}
}
break;
}
case 110: // ishour
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toLowerCase().trim();
if(monster.location()==null)
returnable=false;
else
if((monster.location().getArea().getTimeObj().getHourOfDay()==CMath.s_int(arg1)))
returnable=true;
else
returnable=false;
break;
}
case 38: // istime
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toLowerCase().trim();
if(monster.location()==null)
returnable=false;
else
if(("daytime").startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.DAY))
returnable=true;
else
if(("dawn").startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.DAWN))
returnable=true;
else
if(("dusk").startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.DUSK))
returnable=true;
else
if(("nighttime").startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.NIGHT))
returnable=true;
else
if((monster.location().getArea().getTimeObj().getHourOfDay()==CMath.s_int(arg1)))
returnable=true;
else
returnable=false;
break;
}
case 39: // isday
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getDayOfMonth()==CMath.s_int(arg1.trim())))
returnable=true;
else
returnable=false;
break;
}
case 103: // ismonth
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getMonth()==CMath.s_int(arg1.trim())))
returnable=true;
else
returnable=false;
break;
}
case 104: // isyear
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getYear()==CMath.s_int(arg1.trim())))
returnable=true;
else
returnable=false;
break;
}
case 105: // isrlhour
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) == CMath.s_int(arg1.trim()))
returnable=true;
else
returnable=false;
break;
}
case 106: // isrlday
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if(Calendar.getInstance().get(Calendar.DATE) == CMath.s_int(arg1.trim()))
returnable=true;
else
returnable=false;
break;
}
case 107: // isrlmonth
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if(Calendar.getInstance().get(Calendar.MONTH)+1 == CMath.s_int(arg1.trim()))
returnable=true;
else
returnable=false;
break;
}
case 108: // isrlyear
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if(Calendar.getInstance().get(Calendar.YEAR) == CMath.s_int(arg1.trim()))
returnable=true;
else
returnable=false;
break;
}
case 45: // nummobsroom
{
if(tlen==1)
{
if(CMParms.numBits(funcParms)>2)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
else
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
}
int num=0;
int startbit=0;
if(lastKnownLocation!=null)
{
num=lastKnownLocation.numInhabitants();
if(signH.containsKey(tt[t+1]))
{
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
startbit++;
if(!name.equalsIgnoreCase("*"))
{
num=0;
MaskingLibrary.CompiledZMask MASK=null;
if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("="))))
{
final boolean usePreCompiled = (name.equals(tt[t+0]));
name=name.substring(4).trim();
name=name.substring(1).trim();
MASK=usePreCompiled?CMLib.masking().getPreCompiledMask(name): CMLib.masking().maskCompile(name);
}
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
{
final MOB M=lastKnownLocation.fetchInhabitant(i);
if(M==null)
continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.Name(),name)
||CMLib.english().containsString(M.displayText(),name))
num++;
}
}
}
}
else
if(!signH.containsKey(tt[t+0]))
{
logError(scripted,"NUMMOBSROOM","Syntax","No SIGN found: "+funcParms);
return returnable;
}
final String comp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+startbit]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+startbit+1]);
if(lastKnownLocation!=null)
returnable=simpleEval(scripted,""+num,arg2,comp,"NUMMOBSROOM");
break;
}
case 63: // numpcsroom
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Room R=lastKnownLocation;
if(R!=null)
{
int num=0;
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if((M!=null)&&(!M.isMonster()))
num++;
}
returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMPCSROOM");
}
break;
}
case 79: // numpcsarea
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
if(lastKnownLocation!=null)
{
int num=0;
for(final Session S : CMLib.sessions().localOnlineIterable())
{
if((S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea()))
num++;
}
returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMPCSAREA");
}
break;
}
case 115: // expertise
{
// mob ability type > 10
if(tlen==1)
tt=parseBits(eval,t,"ccccr"); /* tt[t+0] */
final Physical P=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp);
final MOB M;
if(P instanceof MOB)
M=(MOB)P;
else
{
returnable=false;
logError(scripted,"EXPLORED","Unknown MOB",tt[t+0]);
return returnable;
}
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Ability A=M.fetchAbility(arg2);
if(A==null)
A=getAbility(arg2);
if(A==null)
{
returnable=false;
logError(scripted,"EXPLORED","Unknown Ability on MOB '"+M.name()+"'",tt[t+1]);
return returnable;
}
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final ExpertiseLibrary.Flag experFlag = (ExpertiseLibrary.Flag)CMath.s_valueOf(ExpertiseLibrary.Flag.class, arg3.toUpperCase().trim());
if(experFlag == null)
{
returnable=false;
logError(scripted,"EXPLORED","Unknown Exper Flag",tt[t+2]);
return returnable;
}
final int num=CMLib.expertises().getExpertiseLevel(M, A.ID(), experFlag);
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final String arg5=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+4]);
if(lastKnownLocation!=null)
{
returnable=simpleEval(scripted,""+num,arg5,arg4,"EXPERTISE");
}
break;
}
case 77: // explored
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
{
logError(scripted,"EXPLORED","Unknown Code",whom);
return returnable;
}
Area A=null;
if(!where.equalsIgnoreCase("world"))
{
A=CMLib.map().getArea(where);
if(A==null)
{
final Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E2 != null)
A=CMLib.map().areaLocation(E2);
}
if(A==null)
{
logError(scripted,"EXPLORED","Unknown Area",where);
return returnable;
}
}
if(lastKnownLocation!=null)
{
int pct=0;
final MOB M=(MOB)E;
if(M.playerStats()!=null)
pct=M.playerStats().percentVisited(M,A);
returnable=simpleEval(scripted,""+pct,arg2,cmp,"EXPLORED");
}
break;
}
case 72: // faction
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp);
final Faction F=CMLib.factions().getFaction(arg1);
if((E==null)||(!(E instanceof MOB)))
{
logError(scripted,"FACTION","Unknown Code",whom);
return returnable;
}
if(F==null)
{
logError(scripted,"FACTION","Unknown Faction",arg1);
return returnable;
}
final MOB M=(MOB)E;
String value=null;
if(!M.hasFaction(F.factionID()))
value="";
else
{
final int myfac=M.fetchFaction(F.factionID());
if(CMath.isNumber(arg2.trim()))
value=Integer.toString(myfac);
else
{
final Faction.FRange FR=CMLib.factions().getRange(F.factionID(),myfac);
if(FR==null)
value="";
else
value=FR.name();
}
}
if(lastKnownLocation!=null)
returnable=simpleEval(scripted,value,arg2,cmp,"FACTION");
break;
}
case 46: // numitemsroom
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
int ct=0;
if(lastKnownLocation!=null)
{
for(int i=0;i<lastKnownLocation.numItems();i++)
{
final Item I=lastKnownLocation.getItem(i);
if((I!=null)&&(I.container()==null))
ct++;
}
}
returnable=simpleEval(scripted,""+ct,arg2,arg1,"NUMITEMSROOM");
break;
}
case 47: //mobitem
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
MOB M=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
M=lastKnownLocation.fetchInhabitant(arg1.trim());
}
Item which=null;
int ct=1;
if(M!=null)
{
for(int i=0;i<M.numItems();i++)
{
final Item I=M.getItem(i);
if((I!=null)&&(I.container()==null))
{
if(ct==CMath.s_int(arg2.trim()))
{
which = I;
break;
}
ct++;
}
}
}
if(which==null)
returnable=false;
else
returnable=(CMLib.english().containsString(which.name(),arg3)
||CMLib.english().containsString(which.Name(),arg3)
||CMLib.english().containsString(which.displayText(),arg3));
break;
}
case 49: // hastattoo
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HASTATTOO","Syntax",funcParms);
break;
}
else
if((E!=null)&&(E instanceof MOB))
returnable=(((MOB)E).findTattoo(arg2)!=null);
else
returnable=false;
break;
}
case 109: // hastattootime
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String cmp=tt[t+2];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HASTATTOO","Syntax",funcParms);
break;
}
else
if((E!=null)&&(E instanceof MOB))
{
final Tattoo T=((MOB)E).findTattoo(arg2);
if(T==null)
returnable=false;
else
returnable=simpleEval(scripted,""+T.getTickDown(),arg3,cmp,"ISTATTOOTIME");
}
else
returnable=false;
break;
}
case 99: // hasacctattoo
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HASACCTATTOO","Syntax",funcParms);
break;
}
else
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getAccount()!=null))
returnable=((MOB)E).playerStats().getAccount().findTattoo(arg2)!=null;
else
returnable=false;
break;
}
case 48: // numitemsmob
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
MOB which=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
which=lastKnownLocation.fetchInhabitant(arg1);
}
int ct=0;
if(which!=null)
{
for(int i=0;i<which.numItems();i++)
{
final Item I=which.getItem(i);
if((I!=null)&&(I.container()==null))
ct++;
}
}
returnable=simpleEval(scripted,""+ct,arg3,arg2,"NUMITEMSMOB");
break;
}
case 101: // numitemsshop
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
PhysicalAgent which=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
which=lastKnownLocation.fetchInhabitant(arg1);
if(which == null)
which=this.getArgumentItem(tt[t+0], source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(which == null)
which=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp);
}
int ct=0;
if(which!=null)
{
ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(which);
if((shopHere == null)&&(scripted instanceof Item))
shopHere=CMLib.coffeeShops().getShopKeeper(((Item)which).owner());
if((shopHere == null)&&(scripted instanceof MOB))
shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)which).location());
if(shopHere == null)
shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(shopHere!=null)
{
final CoffeeShop shop = shopHere.getShop();
if(shop != null)
{
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();i.next())
{
ct++;
}
}
}
}
returnable=simpleEval(scripted,""+ct,arg3,arg2,"NUMITEMSSHOP");
break;
}
case 100: // shopitem
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
PhysicalAgent where=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
where=lastKnownLocation.fetchInhabitant(arg1.trim());
if(where == null)
where=this.getArgumentItem(tt[t+0], source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(where == null)
where=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp);
}
Environmental which=null;
int ct=1;
if(where!=null)
{
ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where);
if((shopHere == null)&&(scripted instanceof Item))
shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner());
if((shopHere == null)&&(scripted instanceof MOB))
shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location());
if(shopHere == null)
shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(shopHere!=null)
{
final CoffeeShop shop = shopHere.getShop();
if(shop != null)
{
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();)
{
final Environmental E=i.next();
if(ct==CMath.s_int(arg2.trim()))
{
which = E;
break;
}
ct++;
}
}
}
if(which==null)
returnable=false;
else
{
returnable=(CMLib.english().containsString(which.name(),arg3)
||CMLib.english().containsString(which.Name(),arg3)
||CMLib.english().containsString(which.displayText(),arg3));
if(returnable)
setShopPrice(shopHere,which,tmp);
}
}
else
returnable=false;
break;
}
case 102: // shophas
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
PhysicalAgent where=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
where=lastKnownLocation.fetchInhabitant(arg1.trim());
if(where == null)
where=this.getArgumentItem(tt[t+0], source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(where == null)
where=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp);
}
returnable=false;
if(where!=null)
{
ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where);
if((shopHere == null)&&(scripted instanceof Item))
shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner());
if((shopHere == null)&&(scripted instanceof MOB))
shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location());
if(shopHere == null)
shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(shopHere!=null)
{
final CoffeeShop shop = shopHere.getShop();
if(shop != null)
{
final Environmental E=shop.getStock(arg2.trim(), null);
returnable = (E!=null);
if(returnable)
setShopPrice(shopHere,E,tmp);
}
}
}
break;
}
case 43: // roommob
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Environmental which=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
which=lastKnownLocation.fetchInhabitant(arg1.trim());
}
if(which==null)
returnable=false;
else
returnable=(CMLib.english().containsString(which.name(),arg2)
||CMLib.english().containsString(which.Name(),arg2)
||CMLib.english().containsString(which.displayText(),arg2));
break;
}
case 44: // roomitem
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Environmental which=null;
int ct=1;
if(lastKnownLocation!=null)
for(int i=0;i<lastKnownLocation.numItems();i++)
{
final Item I=lastKnownLocation.getItem(i);
if((I!=null)&&(I.container()==null))
{
if(ct==CMath.s_int(arg1.trim()))
{
which = I;
break;
}
ct++;
}
}
if(which==null)
returnable=false;
else
returnable=(CMLib.english().containsString(which.name(),arg2)
||CMLib.english().containsString(which.Name(),arg2)
||CMLib.english().containsString(which.displayText(),arg2));
break;
}
case 36: // ishere
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if((arg1.length()>0)&&(lastKnownLocation!=null))
returnable=((lastKnownLocation.findItem(arg1)!=null)||(lastKnownLocation.fetchInhabitant(arg1)!=null));
else
returnable=false;
break;
}
case 17: // inroom
{
if(tlen==1)
tt=parseSpecial3PartEval(eval,t);
String comp="==";
Environmental E=monster;
String arg2;
if(signH.containsKey(tt[t+1]))
{
E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
comp=tt[t+1];
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
}
else
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
Room R=null;
if(arg2.startsWith("$"))
R=CMLib.map().roomLocation(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(R==null)
R=getRoom(arg2,lastKnownLocation);
if(E==null)
returnable=false;
else
{
final Room R2=CMLib.map().roomLocation(E);
if((R==null)&&((arg2.length()==0)||(R2==null)))
returnable=true;
else
if((R==null)||(R2==null))
returnable=false;
else
returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"INROOM");
}
break;
}
case 90: // inarea
{
if(tlen==1)
tt=parseSpecial3PartEval(eval,t);
String comp="==";
Environmental E=monster;
String arg3;
if(signH.containsKey(tt[t+1]))
{
E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
comp=tt[t+1];
arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
}
else
arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
Room R=null;
if(arg3.startsWith("$"))
R=CMLib.map().roomLocation(this.getArgumentItem(arg3,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(R==null)
{
try
{
final String lnAstr=(lastKnownLocation!=null)?lastKnownLocation.getArea().Name():null;
if((lnAstr!=null)&&(lnAstr.equalsIgnoreCase(arg3)))
R=lastKnownLocation;
if(R==null)
{
for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();)
{
final Area A=a.nextElement();
if((A!=null)&&(A.Name().equalsIgnoreCase(arg3)))
{
if((lnAstr!=null)
&&(lnAstr.equals(A.Name())))
R=lastKnownLocation;
else
if(!A.isProperlyEmpty())
R=A.getRandomProperRoom();
}
}
}
if(R==null)
{
for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();)
{
final Area A=a.nextElement();
if((A!=null)&&(CMLib.english().containsString(A.Name(),arg3)))
{
if((lnAstr!=null)
&&(lnAstr.equals(A.Name())))
R=lastKnownLocation;
else
if(!A.isProperlyEmpty())
R=A.getRandomProperRoom();
}
}
}
}
catch (final NoSuchElementException nse)
{
}
}
if(R==null)
R=getRoom(arg3,lastKnownLocation);
if((R!=null)
&&(CMath.bset(R.getArea().flags(),Area.FLAG_INSTANCE_PARENT))
&&(lastKnownLocation!=null)
&&(lastKnownLocation.getArea()!=R.getArea())
&&(CMath.bset(lastKnownLocation.getArea().flags(),Area.FLAG_INSTANCE_CHILD))
&&(CMLib.map().getModelArea(lastKnownLocation.getArea())==R.getArea()))
R=lastKnownLocation;
if(E==null)
returnable=false;
else
{
final Room R2=CMLib.map().roomLocation(E);
if((R==null)&&((arg3.length()==0)||(R2==null)))
returnable=true;
else
if((R==null)||(R2==null))
returnable=false;
else
returnable=simpleEvalStr(scripted,R2.getArea().Name(),R.getArea().Name(),comp,"INAREA");
}
break;
}
case 89: // isrecall
{
if(tlen==1)
tt=parseSpecial3PartEval(eval,t);
String comp="==";
Environmental E=monster;
String arg2;
if(signH.containsKey(tt[t+1]))
{
E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
comp=tt[t+1];
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
}
else
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
Room R=null;
if(arg2.startsWith("$"))
R=CMLib.map().getStartRoom(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(R==null)
R=getRoom(arg2,lastKnownLocation);
if(E==null)
returnable=false;
else
{
final Room R2=CMLib.map().getStartRoom(E);
if((R==null)&&((arg2.length()==0)||(R2==null)))
returnable=true;
else
if((R==null)||(R2==null))
returnable=false;
else
returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"ISRECALL");
}
break;
}
case 37: // inlocale
{
if(tlen==1)
{
if(CMParms.numBits(funcParms)>1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
else
{
final int numBits=2;
String[] parsed=null;
if(CMParms.cleanBit(funcParms).equals(funcParms))
parsed=parseBits("'"+funcParms+"'"+CMStrings.repeat(" .",numBits-1),"cr");
else
parsed=parseBits(funcParms+CMStrings.repeat(" .",numBits-1),"cr");
tt=insertStringArray(tt,parsed,t);
eval[0]=tt;
}
}
String arg2=null;
Environmental E=monster;
if(tt[t+1].equals("."))
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
else
{
E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
}
if(E==null)
returnable=false;
else
if(arg2.length()==0)
returnable=true;
else
{
final Room R=CMLib.map().roomLocation(E);
if(R==null)
returnable=false;
else
if(CMClass.classID(R).toUpperCase().indexOf(arg2.toUpperCase())>=0)
returnable=true;
else
returnable=false;
}
break;
}
case 18: // sex
{
if(tlen==1)
tt=parseBits(eval,t,"CcR"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
String arg3=tt[t+2];
if(CMath.isNumber(arg3.trim()))
{
switch(CMath.s_int(arg3.trim()))
{
case 0:
arg3 = "NEUTER";
break;
case 1:
arg3 = "MALE";
break;
case 2:
arg3 = "FEMALE";
break;
}
}
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"SEX","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final String sex=(""+((char)((MOB)E).charStats().getStat(CharStats.STAT_GENDER))).toUpperCase();
if(arg2.equals("=="))
returnable=arg3.startsWith(sex);
else
if(arg2.equals("!="))
returnable=!arg3.startsWith(sex);
else
{
logError(scripted,"SEX","Syntax",funcParms);
return returnable;
}
}
break;
}
case 91: // datetime
{
if(tlen==1)
tt=parseBits(eval,t,"Ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=tt[t+2];
final int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.trim());
if(index<0)
logError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name());
else
if(CMLib.map().areaLocation(scripted)!=null)
{
String val=null;
switch(index)
{
case 2:
val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth();
break;
case 3:
val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth();
break;
case 4:
val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getMonth();
break;
case 5:
val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getYear();
break;
default:
val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getHourOfDay();
break;
}
returnable=simpleEval(scripted,val,arg3,arg2,"DATETIME");
}
break;
}
case 13: // stat
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=tt[t+2];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"STAT","Syntax",funcParms);
break;
}
if(E==null)
returnable=false;
else
{
final String val=getStatValue(E,arg2);
if(val==null)
{
logError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name());
break;
}
if(arg3.equals("=="))
returnable=val.equalsIgnoreCase(arg4);
else
if(arg3.equals("!="))
returnable=!val.equalsIgnoreCase(arg4);
else
returnable=simpleEval(scripted,val,arg4,arg3,"STAT");
}
break;
}
case 52: // gstat
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=tt[t+2];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"GSTAT","Syntax",funcParms);
break;
}
if(E==null)
returnable=false;
else
{
final String val=getGStatValue(E,arg2);
if(val==null)
{
logError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name());
break;
}
if(arg3.equals("=="))
returnable=val.equalsIgnoreCase(arg4);
else
if(arg3.equals("!="))
returnable=!val.equalsIgnoreCase(arg4);
else
returnable=simpleEval(scripted,val,arg4,arg3,"GSTAT");
}
break;
}
case 19: // position
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=tt[t+2];
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"POSITION","Syntax",funcParms);
return returnable;
}
if(P==null)
returnable=false;
else
{
String sex="STANDING";
if(CMLib.flags().isSleeping(P))
sex="SLEEPING";
else
if(CMLib.flags().isSitting(P))
sex="SITTING";
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"POSITION","Syntax",funcParms);
return returnable;
}
}
break;
}
case 20: // level
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"LEVEL","Syntax",funcParms);
return returnable;
}
if(P==null)
returnable=false;
else
{
final int val1=P.phyStats().level();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"LEVEL");
}
break;
}
case 80: // questpoints
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"QUESTPOINTS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final int val1=((MOB)E).getQuestPoint();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"QUESTPOINTS");
}
break;
}
case 83: // qvar
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String arg3=tt[t+2];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Quest Q=getQuest(arg1);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"QVAR","Syntax",funcParms);
return returnable;
}
if(Q==null)
returnable=false;
else
returnable=simpleEvalStr(scripted,Q.getStat(arg2),arg4,arg3,"QVAR");
break;
}
case 84: // math
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
if(!CMath.isMathExpression(arg1))
{
logError(scripted,"MATH","Syntax",funcParms);
return returnable;
}
if(!CMath.isMathExpression(arg3))
{
logError(scripted,"MATH","Syntax",funcParms);
return returnable;
}
returnable=simpleExpressionEval(scripted,arg1,arg3,arg2,"MATH");
break;
}
case 81: // trains
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"TRAINS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final int val1=((MOB)E).getTrains();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"TRAINS");
}
break;
}
case 82: // pracs
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"PRACS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final int val1=((MOB)E).getPractices();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"PRACS");
}
break;
}
case 66: // clanrank
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"CLANRANK","Syntax",funcParms);
return returnable;
}
if(!(E instanceof MOB))
returnable=false;
else
{
int val1=-1;
Clan C=CMLib.clans().findRivalrousClan((MOB)E);
if(C==null)
C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null;
if(C!=null)
val1=((MOB)E).getClanRole(C.clanID()).second.intValue();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"CLANRANK");
}
break;
}
case 64: // deity
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"DEITY","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final String sex=((MOB)E).getWorshipCharID();
if(arg2.equals("=="))
returnable=sex.equalsIgnoreCase(arg3);
else
if(arg2.equals("!="))
returnable=!sex.equalsIgnoreCase(arg3);
else
{
logError(scripted,"DEITY","Syntax",funcParms);
return returnable;
}
}
break;
}
case 68: // clandata
{
if(tlen==1)
tt=parseBits(eval,t,"cccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=tt[t+2];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"CLANDATA","Syntax",funcParms);
return returnable;
}
String clanID=null;
if((E!=null)&&(E instanceof MOB))
{
Clan C=CMLib.clans().findRivalrousClan((MOB)E);
if(C==null)
C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null;
if(C!=null)
clanID=C.clanID();
}
else
{
clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1);
if((scripted instanceof MOB)
&&(CMLib.clans().getClanAnyHost(clanID)==null))
{
final List<Pair<Clan,Integer>> Cs=CMLib.clans().getClansByCategory((MOB)scripted, clanID);
if((Cs!=null)&&(Cs.size()>0))
clanID=Cs.get(0).first.clanID();
}
}
final Clan C=CMLib.clans().findClan(clanID);
if(C!=null)
{
if(!C.isStat(arg2))
logError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable.");
else
{
final String whichVal=C.getStat(arg2).trim();
if(CMath.isNumber(whichVal)&&CMath.isNumber(arg4.trim()))
returnable=simpleEval(scripted,whichVal,arg4,arg3,"CLANDATA");
else
returnable=simpleEvalStr(scripted,whichVal,arg4,arg3,"CLANDATA");
}
}
break;
}
case 98: // clanqualifies
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"CLANQUALIFIES","Syntax",funcParms);
return returnable;
}
final Clan C=CMLib.clans().findClan(arg2);
if((C!=null)&&(E instanceof MOB))
{
final MOB mob=(MOB)E;
if(C.isOnlyFamilyApplicants()
&&(!CMLib.clans().isFamilyOfMembership(mob,C.getMemberList())))
returnable=false;
else
if(CMLib.clans().getClansByCategory(mob, C.getCategory()).size()>CMProps.getMaxClansThisCategory(C.getCategory()))
returnable=false;
if(returnable && (!CMLib.masking().maskCheck(C.getBasicRequirementMask(), mob, true)))
returnable=false;
else
if(returnable && (CMLib.masking().maskCheck(C.getAcceptanceSettings(),mob,true)))
returnable=false;
}
else
{
logError(scripted,"CLANQUALIFIES","Unknown clan "+arg2+" or "+arg1+" is not a mob",funcParms);
return returnable;
}
break;
}
case 65: // clan
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"CLAN","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
String clanID="";
Clan C=CMLib.clans().findRivalrousClan((MOB)E);
if(C==null)
C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null;
if(C!=null)
clanID=C.clanID();
if(arg2.equals("=="))
returnable=clanID.equalsIgnoreCase(arg3);
else
if(arg2.equals("!="))
returnable=!clanID.equalsIgnoreCase(arg3);
else
if(arg2.equals("in"))
returnable=((MOB)E).getClanRole(arg3)!=null;
else
if(arg2.equals("notin"))
returnable=((MOB)E).getClanRole(arg3)==null;
else
{
logError(scripted,"CLAN","Syntax",funcParms);
return returnable;
}
}
break;
}
case 88: // mood
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Physical P=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"MOOD","Syntax",funcParms);
return returnable;
}
if((P==null)||(!(P instanceof MOB)))
returnable=false;
else
{
final Ability moodA=P.fetchEffect("Mood");
if(moodA!=null)
{
final String sex=moodA.text();
if(arg2.equals("=="))
returnable=sex.equalsIgnoreCase(arg3);
else
if(arg2.equals("!="))
returnable=!sex.equalsIgnoreCase(arg3);
else
{
logError(scripted,"MOOD","Syntax",funcParms);
return returnable;
}
}
}
break;
}
case 21: // class
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"CLASS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final String sex=((MOB)E).charStats().displayClassName().toUpperCase();
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"CLASS","Syntax",funcParms);
return returnable;
}
}
break;
}
case 22: // baseclass
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"CLASS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final String sex=((MOB)E).charStats().getCurrentClass().baseClass().toUpperCase();
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"CLASS","Syntax",funcParms);
return returnable;
}
}
break;
}
case 23: // race
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"RACE","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final String sex=((MOB)E).charStats().raceName().toUpperCase();
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"RACE","Syntax",funcParms);
return returnable;
}
}
break;
}
case 24: //racecat
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"RACECAT","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final String sex=((MOB)E).charStats().getMyRace().racialCategory().toUpperCase();
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"RACECAT","Syntax",funcParms);
return returnable;
}
}
break;
}
case 25: // goldamt
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"GOLDAMT","Syntax",funcParms);
break;
}
if(E==null)
returnable=false;
else
{
int val1=0;
if(E instanceof MOB)
val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted)));
else
if(E instanceof Coins)
val1=(int)Math.round(((Coins)E).getTotalValue());
else
if(E instanceof Item)
val1=((Item)E).value();
else
{
logError(scripted,"GOLDAMT","Syntax",funcParms);
return returnable;
}
returnable=simpleEval(scripted,""+val1,arg3,arg2,"GOLDAMT");
}
break;
}
case 78: // exp
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"EXP","Syntax",funcParms);
break;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final int val1=((MOB)E).getExperience();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"EXP");
}
break;
}
case 76: // value
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String arg3=tt[t+2];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
if((arg2.length()==0)||(arg3.length()==0)||(arg4.length()==0))
{
logError(scripted,"VALUE","Syntax",funcParms);
break;
}
if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase()))
{
logError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency.");
break;
}
if(E==null)
returnable=false;
else
{
int val1=0;
if(E instanceof MOB)
val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2.toUpperCase()));
else
if(E instanceof Coins)
{
if(((Coins)E).getCurrency().equalsIgnoreCase(arg2))
val1=(int)Math.round(((Coins)E).getTotalValue());
}
else
if(E instanceof Item)
val1=((Item)E).value();
else
{
logError(scripted,"VALUE","Syntax",funcParms);
return returnable;
}
returnable=simpleEval(scripted,""+val1,arg4,arg3,"GOLDAMT");
}
break;
}
case 26: // objtype
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"OBJTYPE","Syntax",funcParms);
return returnable;
}
if(E==null)
returnable=false;
else
{
final String sex=CMClass.classID(E).toUpperCase();
if(arg2.equals("=="))
returnable=sex.indexOf(arg3)>=0;
else
if(arg2.equals("!="))
returnable=sex.indexOf(arg3)<0;
else
{
logError(scripted,"OBJTYPE","Syntax",funcParms);
return returnable;
}
}
break;
}
case 27: // var
{
if(tlen==1)
tt=parseBits(eval,t,"cCcr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=tt[t+2];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"VAR","Syntax",funcParms);
return returnable;
}
final String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS))
Log.debugOut("(VAR "+arg1+" "+arg2 +"["+val+"] "+arg3+" "+arg4);
if(arg3.equals("==")||arg3.equals("="))
returnable=val.equals(arg4);
else
if(arg3.equals("!=")||(arg3.contentEquals("<>")))
returnable=!val.equals(arg4);
else
if(arg3.equals(">"))
returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim());
else
if(arg3.equals("<"))
returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim());
else
if(arg3.equals(">="))
returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim());
else
if(arg3.equals("<="))
returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim());
else
{
logError(scripted,"VAR","Syntax",funcParms);
return returnable;
}
break;
}
case 41: // eval
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg3=tt[t+1];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
if(arg3.length()==0)
{
logError(scripted,"EVAL","Syntax",funcParms);
return returnable;
}
if(arg3.equals("=="))
returnable=val.equals(arg4);
else
if(arg3.equals("!="))
returnable=!val.equals(arg4);
else
if(arg3.equals(">"))
returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim());
else
if(arg3.equals("<"))
returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim());
else
if(arg3.equals(">="))
returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim());
else
if(arg3.equals("<="))
returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim());
else
{
logError(scripted,"EVAL","Syntax",funcParms);
return returnable;
}
break;
}
case 40: // number
{
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim();
boolean isnumber=(val.length()>0);
for(int i=0;i<val.length();i++)
{
if(!Character.isDigit(val.charAt(i)))
{
isnumber = false;
break;
}
}
returnable=isnumber;
break;
}
case 42: // randnum
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase().trim();
int arg1=0;
if(CMath.isMathExpression(arg1s.trim()))
arg1=CMath.s_parseIntExpression(arg1s.trim());
else
arg1=CMParms.parse(arg1s.trim()).size();
final String arg2=tt[t+1];
final String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]).trim();
int arg3=0;
if(CMath.isMathExpression(arg3s.trim()))
arg3=CMath.s_parseIntExpression(arg3s.trim());
else
arg3=CMParms.parse(arg3s.trim()).size();
arg1=CMLib.dice().roll(1,arg1,0);
returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RANDNUM");
break;
}
case 71: // rand0num
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase().trim();
int arg1=0;
if(CMath.isMathExpression(arg1s))
arg1=CMath.s_parseIntExpression(arg1s);
else
arg1=CMParms.parse(arg1s).size();
final String arg2=tt[t+1];
final String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]).trim();
int arg3=0;
if(CMath.isMathExpression(arg3s))
arg3=CMath.s_parseIntExpression(arg3s);
else
arg3=CMParms.parse(arg3s).size();
arg1=CMLib.dice().roll(1,arg1,-1);
returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RAND0NUM");
break;
}
case 53: // incontainer
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=tt[t+1];
final Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
if(E instanceof MOB)
{
if(arg2.length()==0)
returnable=(((MOB)E).riding()==null);
else
if(E2!=null)
returnable=(((MOB)E).riding()==E2);
else
returnable=false;
}
else
if(E instanceof Item)
{
if(arg2.length()==0)
returnable=(((Item)E).container()==null);
else
if(E2!=null)
returnable=(((Item)E).container()==E2);
else
returnable=false;
}
else
returnable=false;
break;
}
case 96: // iscontents
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp, tt[t+1]);
if(E==null)
returnable=false;
else
if(E instanceof Rideable)
{
if(arg2.length()==0)
returnable=((Rideable)E).numRiders()==0;
else
returnable=CMLib.english().fetchEnvironmental(new XVector<Rider>(((Rideable)E).riders()), arg2, false)!=null;
}
if(E instanceof Container)
{
if(arg2.length()==0)
returnable=!((Container)E).hasContent();
else
returnable=CMLib.english().fetchEnvironmental(((Container)E).getDeepContents(), arg2, false)!=null;
}
else
returnable=false;
break;
}
case 97: // wornon
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final PhysicalAgent E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp, tt[t+1]);
final String arg3=varify(source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp, tt[t+2]);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"WORNON","Syntax",funcParms);
return returnable;
}
final int wornLoc = CMParms.indexOf(Wearable.CODES.NAMESUP(), arg2.toUpperCase().trim());
returnable=false;
if(wornLoc<0)
logError(scripted,"EVAL","BAD WORNON LOCATION",arg2);
else
if(E instanceof MOB)
{
final List<Item> items=((MOB)E).fetchWornItems(Wearable.CODES.GET(wornLoc),(short)-2048,(short)0);
if((items.size()==0)&&(arg3.length()==0))
returnable=true;
else
returnable = CMLib.english().fetchEnvironmental(items, arg3, false)!=null;
}
break;
}
default:
logError(scripted,"EVAL","UNKNOWN",CMParms.toListString(tt));
return false;
}
pushEvalBoolean(stack,returnable);
while((t<tt.length)&&(!tt[t].equals(")")))
t++;
}
else
{
logError(scripted,"EVAL","SYNTAX","BAD CONJUCTOR "+tt[t]+": "+CMParms.toListString(tt));
return false;
}
}
if((stack.size()!=1)
||(!(stack.get(0) instanceof Boolean)))
{
logError(scripted,"EVAL","SYNTAX","Unmatched (: "+CMParms.toListString(tt));
return false;
}
return ((Boolean)stack.get(0)).booleanValue();
}
protected void setShopPrice(final ShopKeeper shopHere, final Environmental E, final Object[] tmp)
{
if(shopHere instanceof MOB)
{
final ShopKeeper.ShopPrice price = CMLib.coffeeShops().sellingPrice((MOB)shopHere, null, E, shopHere, shopHere.getShop(), true);
if(price.experiencePrice>0)
tmp[SPECIAL_9SHOPHASPRICE] = price.experiencePrice+"xp";
else
if(price.questPointPrice>0)
tmp[SPECIAL_9SHOPHASPRICE] = price.questPointPrice+"qp";
else
tmp[SPECIAL_9SHOPHASPRICE] = CMLib.beanCounter().abbreviatedPrice((MOB)shopHere,price.absoluteGoldPrice);
}
}
@Override
public String functify(final PhysicalAgent scripted,
final MOB source,
final Environmental target,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final String msg,
final Object[] tmp,
final String evaluable)
{
if(evaluable.length()==0)
return "";
final StringBuffer results = new StringBuffer("");
final int y=evaluable.indexOf('(');
final int z=evaluable.indexOf(')',y);
final String preFab=(y>=0)?evaluable.substring(0,y).toUpperCase().trim():"";
Integer funcCode=funcH.get(preFab);
if(funcCode==null)
funcCode=Integer.valueOf(0);
if((y<0)||(z<y))
{
logError(scripted,"()","Syntax",evaluable);
return "";
}
else
{
tickStatus=Tickable.STATUS_MISC2+funcCode.intValue();
final String funcParms=evaluable.substring(y+1,z).trim();
switch(funcCode.intValue())
{
case 1: // rand
{
results.append(CMLib.dice().rollPercentage());
break;
}
case 2: // has
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
ArrayList<Item> choices=new ArrayList<Item>();
if(E==null)
choices=new ArrayList<Item>();
else
if(E instanceof MOB)
{
for(int i=0;i<((MOB)E).numItems();i++)
{
final Item I=((MOB)E).getItem(i);
if((I!=null)&&(I.amWearingAt(Wearable.IN_INVENTORY))&&(I.container()==null))
choices.add(I);
}
}
else
if(E instanceof Item)
{
if(E instanceof Container)
choices.addAll(((Container)E).getDeepContents());
else
choices.add((Item)E);
}
else
if(E instanceof Room)
{
for(int i=0;i<((Room)E).numItems();i++)
{
final Item I=((Room)E).getItem(i);
if((I!=null)&&(I.container()==null))
choices.add(I);
}
}
if(choices.size()>0)
results.append(choices.get(CMLib.dice().roll(1,choices.size(),-1)).name());
break;
}
case 74: // hasnum
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1));
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((item.length()==0)||(E==null))
logError(scripted,"HASNUM","Syntax",funcParms);
else
{
Item I=null;
int num=0;
if(E instanceof MOB)
{
final MOB M=(MOB)E;
for(int i=0;i<M.numItems();i++)
{
I=M.getItem(i);
if(I==null)
break;
if((item.equalsIgnoreCase("all"))
||(CMLib.english().containsString(I.Name(),item)))
num++;
}
results.append(""+num);
}
else
if(E instanceof Item)
{
num=CMLib.english().containsString(E.name(),item)?1:0;
results.append(""+num);
}
else
if(E instanceof Room)
{
final Room R=(Room)E;
for(int i=0;i<R.numItems();i++)
{
I=R.getItem(i);
if(I==null)
break;
if((item.equalsIgnoreCase("all"))
||(CMLib.english().containsString(I.Name(),item)))
num++;
}
results.append(""+num);
}
}
break;
}
case 3: // worn
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
ArrayList<Item> choices=new ArrayList<Item>();
if(E==null)
choices=new ArrayList<Item>();
else
if(E instanceof MOB)
{
for(int i=0;i<((MOB)E).numItems();i++)
{
final Item I=((MOB)E).getItem(i);
if((I!=null)&&(!I.amWearingAt(Wearable.IN_INVENTORY))&&(I.container()==null))
choices.add(I);
}
}
else
if((E instanceof Item)&&(!(((Item)E).amWearingAt(Wearable.IN_INVENTORY))))
{
if(E instanceof Container)
choices.addAll(((Container)E).getDeepContents());
else
choices.add((Item)E);
}
if(choices.size()>0)
results.append(choices.get(CMLib.dice().roll(1,choices.size(),-1)).name());
break;
}
case 4: // isnpc
case 5: // ispc
results.append("[unimplemented function]");
break;
case 87: // isbirthday
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getBirthday()!=null))
{
final MOB mob=(MOB)E;
final TimeClock C=CMLib.time().localClock(mob.getStartRoom());
final int day=C.getDayOfMonth();
final int month=C.getMonth();
int year=C.getYear();
final int bday=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_DAY];
final int bmonth=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_MONTH];
if((month>bmonth)||((month==bmonth)&&(day>bday)))
year++;
final StringBuffer timeDesc=new StringBuffer("");
if(C.getDaysInWeek()>0)
{
long x=((long)year)*((long)C.getMonthsInYear())*C.getDaysInMonth();
x=x+((long)(bmonth-1))*((long)C.getDaysInMonth());
x=x+bmonth;
timeDesc.append(C.getWeekNames()[(int)(x%C.getDaysInWeek())]+", ");
}
timeDesc.append("the "+bday+CMath.numAppendage(bday));
timeDesc.append(" day of "+C.getMonthNames()[bmonth-1]);
if(C.getYearNames().length>0)
timeDesc.append(", "+CMStrings.replaceAll(C.getYearNames()[year%C.getYearNames().length],"#",""+year));
results.append(timeDesc.toString());
}
break;
}
case 6: // isgood
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB)))
{
final Faction.FRange FR=CMLib.factions().getRange(CMLib.factions().getAlignmentID(),((MOB)E).fetchFaction(CMLib.factions().getAlignmentID()));
if(FR!=null)
results.append(FR.name());
else
results.append(((MOB)E).fetchFaction(CMLib.factions().getAlignmentID()));
}
break;
}
case 8: // isevil
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB)))
results.append(CMLib.flags().getAlignmentName(E).toLowerCase());
break;
}
case 9: // isneutral
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB)))
results.append(((MOB)E).fetchFaction(CMLib.factions().getAlignmentID()));
break;
}
case 11: // isimmort
results.append("[unimplemented function]");
break;
case 54: // isalive
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead()))
results.append(((MOB)E).healthText(null));
else
if(E!=null)
results.append(E.name()+" is dead.");
break;
}
case 58: // isable
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead()))
{
final ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true);
if(X!=null)
{
final Pair<String,Integer> s=((MOB)E).fetchExpertise(X.ID());
if(s!=null)
results.append(s.getKey()+((s.getValue()!=null)?s.getValue().toString():""));
}
else
{
final Ability A=((MOB)E).findAbility(arg2);
if(A!=null)
results.append(""+A.proficiency());
}
}
break;
}
case 59: // isopen
{
final String arg1=CMParms.cleanBit(funcParms);
final int dir=CMLib.directions().getGoodDirectionCode(arg1);
boolean returnable=false;
if(dir<0)
{
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof Container))
returnable=((Container)E).isOpen();
else
if((E!=null)&&(E instanceof Exit))
returnable=((Exit)E).isOpen();
}
else
if(lastKnownLocation!=null)
{
final Exit E=lastKnownLocation.getExitInDir(dir);
if(E!=null)
returnable= E.isOpen();
}
results.append(""+returnable);
break;
}
case 60: // islocked
{
final String arg1=CMParms.cleanBit(funcParms);
final int dir=CMLib.directions().getGoodDirectionCode(arg1);
if(dir<0)
{
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof Container))
results.append(((Container)E).keyName());
else
if((E!=null)&&(E instanceof Exit))
results.append(((Exit)E).keyName());
}
else
if(lastKnownLocation!=null)
{
final Exit E=lastKnownLocation.getExitInDir(dir);
if(E!=null)
results.append(E.keyName());
}
break;
}
case 62: // callfunc
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0));
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
String found=null;
boolean validFunc=false;
final List<DVector> scripts=getScripts();
String trigger=null;
String[] ttrigger=null;
for(int v=0;v<scripts.size();v++)
{
final DVector script2=scripts.get(v);
if(script2.size()<1)
continue;
trigger=((String)script2.elementAt(0,1)).toUpperCase().trim();
ttrigger=(String[])script2.elementAt(0,2);
if(getTriggerCode(trigger,ttrigger)==17)
{
final String fnamed=CMParms.getCleanBit(trigger,1);
if(fnamed.equalsIgnoreCase(arg1))
{
validFunc=true;
found=
execute(scripted,
source,
target,
monster,
primaryItem,
secondaryItem,
script2,
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2),
tmp);
if(found==null)
found="";
break;
}
}
}
if(!validFunc)
logError(scripted,"CALLFUNC","Unknown","Function: "+arg1);
else
results.append(found);
break;
}
case 61: // strin
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0));
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
final List<String> V=CMParms.parse(arg1.toUpperCase());
results.append(V.indexOf(arg2.toUpperCase()));
break;
}
case 55: // ispkill
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
results.append("false");
else
if(((MOB)E).isAttributeSet(MOB.Attrib.PLAYERKILL))
results.append("true");
else
results.append("false");
break;
}
case 10: // isfight
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(((MOB)E).isInCombat()))
results.append(((MOB)E).getVictim().name());
break;
}
case 12: // ischarmed
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
final List<Ability> V=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING);
for(int v=0;v<V.size();v++)
results.append((V.get(v).name())+" ");
}
break;
}
case 15: // isfollow
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).amFollowing()!=null)
&&(((MOB)E).amFollowing().location()==lastKnownLocation))
results.append(((MOB)E).amFollowing().name());
break;
}
case 73: // isservant
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).getLiegeID()!=null)&&(((MOB)E).getLiegeID().length()>0))
results.append(((MOB)E).getLiegeID());
break;
}
case 95: // isspeaking
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
final MOB TM=(MOB)E;
final Language L=CMLib.utensils().getLanguageSpoken(TM);
if(L!=null)
results.append(L.Name());
else
results.append("Common");
}
break;
}
case 56: // name
case 7: // isname
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
results.append(E.name());
break;
}
case 75: // currency
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
results.append(CMLib.beanCounter().getCurrency(E));
break;
}
case 14: // affected
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E instanceof Physical)&&(((Physical)E).numEffects()>0))
results.append(((Physical)E).effects().nextElement().name());
break;
}
case 69: // isbehave
{
final String arg1=CMParms.cleanBit(funcParms);
final PhysicalAgent E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
for(final Enumeration<Behavior> e=E.behaviors();e.hasMoreElements();)
{
final Behavior B=e.nextElement();
if(B!=null)
results.append(B.ID()+" ");
}
}
break;
}
case 70: // ipaddress
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster()))
results.append(((MOB)E).session().getAddress());
break;
}
case 28: // questwinner
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster()))
{
for(int q=0;q<CMLib.quests().numQuests();q++)
{
final Quest Q=CMLib.quests().fetchQuest(q);
if((Q!=null)&&(Q.wasWinner(E.Name())))
results.append(Q.name()+" ");
}
}
break;
}
case 93: // questscripted
{
final String arg1=CMParms.cleanBit(funcParms);
final PhysicalAgent E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster()))
{
for(final Enumeration<ScriptingEngine> e=E.scripts();e.hasMoreElements();)
{
final ScriptingEngine SE=e.nextElement();
if((SE!=null)&&(SE.defaultQuestName()!=null)&&(SE.defaultQuestName().length()>0))
{
final Quest Q=CMLib.quests().fetchQuest(SE.defaultQuestName());
if(Q!=null)
results.append(Q.name()+" ");
else
results.append(SE.defaultQuestName()+" ");
}
}
for(final Enumeration<Behavior> e=E.behaviors();e.hasMoreElements();)
{
final Behavior B=e.nextElement();
if(B instanceof ScriptingEngine)
{
final ScriptingEngine SE=(ScriptingEngine)B;
if((SE.defaultQuestName()!=null)&&(SE.defaultQuestName().length()>0))
{
final Quest Q=CMLib.quests().fetchQuest(SE.defaultQuestName());
if(Q!=null)
results.append(Q.name()+" ");
else
results.append(SE.defaultQuestName()+" ");
}
}
}
}
break;
}
case 30: // questobj
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
if(questName.equals("*") && (this.defaultQuestName()!=null) && (this.defaultQuestName().length()>0))
questName = this.defaultQuestName();
final Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
final StringBuffer list=new StringBuffer("");
int num=1;
Environmental E=Q.getQuestItem(num);
while(E!=null)
{
if(E.Name().indexOf(' ')>=0)
list.append("\""+E.Name()+"\" ");
else
list.append(E.Name()+" ");
num++;
E=Q.getQuestItem(num);
}
results.append(list.toString().trim());
break;
}
case 94: // questroom
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
final Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
final StringBuffer list=new StringBuffer("");
int num=1;
Environmental E=Q.getQuestRoom(num);
while(E!=null)
{
final String roomID=CMLib.map().getExtendedRoomID((Room)E);
if(roomID.indexOf(' ')>=0)
list.append("\""+roomID+"\" ");
else
list.append(roomID+" ");
num++;
E=Q.getQuestRoom(num);
}
results.append(list.toString().trim());
break;
}
case 114: // questarea
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
final Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
final StringBuffer list=new StringBuffer("");
int num=1;
Environmental E=Q.getQuestRoom(num);
while(E!=null)
{
final String areaName=CMLib.map().areaLocation(E).name();
if(list.indexOf(areaName)<0)
{
if(areaName.indexOf(' ')>=0)
list.append("\""+areaName+"\" ");
else
list.append(areaName+" ");
}
num++;
E=Q.getQuestRoom(num);
}
results.append(list.toString().trim());
break;
}
case 29: // questmob
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
if(questName.equals("*") && (this.defaultQuestName()!=null) && (this.defaultQuestName().length()>0))
questName=this.defaultQuestName();
final Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
final StringBuffer list=new StringBuffer("");
int num=1;
Environmental E=Q.getQuestMob(num);
while(E!=null)
{
if(E.Name().indexOf(' ')>=0)
list.append("\""+E.Name()+"\" ");
else
list.append(E.Name()+" ");
num++;
E=Q.getQuestMob(num);
}
results.append(list.toString().trim());
break;
}
case 31: // isquestmobalive
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
final Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
final StringBuffer list=new StringBuffer("");
int num=1;
MOB E=Q.getQuestMob(num);
while(E!=null)
{
if(CMLib.flags().isInTheGame(E,true))
{
if(E.Name().indexOf(' ')>=0)
list.append("\""+E.Name()+"\" ");
else
list.append(E.Name()+" ");
}
num++;
E=Q.getQuestMob(num);
}
results.append(list.toString().trim());
break;
}
case 49: // hastattoo
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
for(final Enumeration<Tattoo> t = ((MOB)E).tattoos();t.hasMoreElements();)
results.append(t.nextElement().ID()).append(" ");
}
break;
}
case 109: // hastattootime
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
final Tattoo T=((MOB)E).findTattoo(arg2);
if(T!=null)
results.append(T.getTickDown());
}
break;
}
case 99: // hasacctattoo
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getAccount()!=null))
{
for(final Enumeration<Tattoo> t = ((MOB)E).playerStats().getAccount().tattoos();t.hasMoreElements();)
results.append(t.nextElement().ID()).append(" ");
}
break;
}
case 32: // nummobsinarea
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
int num=0;
MaskingLibrary.CompiledZMask MASK=null;
if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("="))))
{
arg1=arg1.substring(4).trim();
arg1=arg1.substring(1).trim();
MASK=CMLib.masking().maskCompile(arg1);
}
for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
final Room R=e.nextElement();
if(arg1.equals("*"))
num+=R.numInhabitants();
else
{
for(int m=0;m<R.numInhabitants();m++)
{
final MOB M=R.fetchInhabitant(m);
if(M==null)
continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.name(),arg1))
num++;
}
}
}
results.append(num);
break;
}
case 33: // nummobs
{
int num=0;
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
MaskingLibrary.CompiledZMask MASK=null;
if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("="))))
{
arg1=arg1.substring(4).trim();
arg1=arg1.substring(1).trim();
MASK=CMLib.masking().maskCompile(arg1);
}
try
{
for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();)
{
final Room R=e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
final MOB M=R.fetchInhabitant(m);
if(M==null)
continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.name(),arg1))
num++;
}
}
}
catch(final NoSuchElementException nse)
{
}
results.append(num);
break;
}
case 34: // numracesinarea
{
int num=0;
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
Room R=null;
MOB M=null;
for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
R=e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
M=R.fetchInhabitant(m);
if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1)))
num++;
}
}
results.append(num);
break;
}
case 35: // numraces
{
int num=0;
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
Room R=null;
MOB M=null;
try
{
for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();)
{
R=e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
M=R.fetchInhabitant(m);
if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1)))
num++;
}
}
}
catch (final NoSuchElementException nse)
{
}
results.append(num);
break;
}
case 112: // cansee
{
break;
}
case 113: // canhear
{
break;
}
case 111: // itemcount
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
int num=0;
if(E instanceof Container)
{
num++;
for(final Item I : ((Container)E).getContents())
num+=I.numberOfItems();
}
else
if(E instanceof Item)
num=((Item)E).numberOfItems();
else
if(E instanceof MOB)
{
for(final Enumeration<Item> i=((MOB)E).items();i.hasMoreElements();)
num += i.nextElement().numberOfItems();
}
else
if(E instanceof Room)
{
for(final Enumeration<Item> i=((Room)E).items();i.hasMoreElements();)
num += i.nextElement().numberOfItems();
}
else
if(E instanceof Area)
{
for(final Enumeration<Room> r=((Area)E).getFilledCompleteMap();r.hasMoreElements();)
{
for(final Enumeration<Item> i=r.nextElement().items();i.hasMoreElements();)
num += i.nextElement().numberOfItems();
}
}
results.append(""+num);
}
break;
}
case 16: // hitprcnt
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
final double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints());
final int val1=(int)Math.round(hitPctD*100.0);
results.append(val1);
}
break;
}
case 50: // isseason
{
if(monster.location()!=null)
results.append(monster.location().getArea().getTimeObj().getSeasonCode().toString());
break;
}
case 51: // isweather
{
if(monster.location()!=null)
results.append(Climate.WEATHER_DESCS[monster.location().getArea().getClimateObj().weatherType(monster.location())]);
break;
}
case 57: // ismoon
{
if(monster.location()!=null)
results.append(monster.location().getArea().getTimeObj().getMoonPhase(monster.location()).toString());
break;
}
case 38: // istime
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.getArea().getTimeObj().getTODCode().getDesc().toLowerCase());
break;
}
case 110: // ishour
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.getArea().getTimeObj().getHourOfDay());
break;
}
case 103: // ismonth
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.getArea().getTimeObj().getMonth());
break;
}
case 104: // isyear
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.getArea().getTimeObj().getYear());
break;
}
case 105: // isrlhour
{
if(lastKnownLocation!=null)
results.append(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));
break;
}
case 106: // isrlday
{
if(lastKnownLocation!=null)
results.append(Calendar.getInstance().get(Calendar.DATE));
break;
}
case 107: // isrlmonth
{
if(lastKnownLocation!=null)
results.append(Calendar.getInstance().get(Calendar.MONTH));
break;
}
case 108: // isrlyear
{
if(lastKnownLocation!=null)
results.append(Calendar.getInstance().get(Calendar.YEAR));
break;
}
case 39: // isday
{
if(lastKnownLocation!=null)
results.append(""+lastKnownLocation.getArea().getTimeObj().getDayOfMonth());
break;
}
case 43: // roommob
{
final String clean=CMParms.cleanBit(funcParms);
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,clean);
Environmental which=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
{
final Environmental E=this.getArgumentItem(clean, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(E!=null)
which=E;
else
which=lastKnownLocation.fetchInhabitant(arg1.trim());
}
if(which!=null)
{
final List<MOB> list=new ArrayList<MOB>();
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
{
final MOB M=lastKnownLocation.fetchInhabitant(i);
if(M!=null)
list.add(M);
}
results.append(CMLib.english().getContextName(list,which));
}
}
break;
}
case 44: // roomitem
{
final String clean=CMParms.cleanBit(funcParms);
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,clean);
Environmental which=null;
if(!CMath.isInteger(arg1))
which=this.getArgumentItem(clean, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
int ct=1;
if(lastKnownLocation!=null)
{
final List<Item> list=new ArrayList<Item>();
if(which == null)
{
for(int i=0;i<lastKnownLocation.numItems();i++)
{
final Item I=lastKnownLocation.getItem(i);
if((I!=null)&&(I.container()==null))
{
list.add(I);
if(ct==CMath.s_int(arg1.trim()))
{
which = I;
break;
}
ct++;
}
}
}
if(which!=null)
results.append(CMLib.english().getContextName(list,which));
}
break;
}
case 45: // nummobsroom
{
int num=0;
if(lastKnownLocation!=null)
{
num=lastKnownLocation.numInhabitants();
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if((name.length()>0)&&(!name.equalsIgnoreCase("*")))
{
num=0;
MaskingLibrary.CompiledZMask MASK=null;
if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("="))))
{
name=name.substring(4).trim();
name=name.substring(1).trim();
MASK=CMLib.masking().maskCompile(name);
}
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
{
final MOB M=lastKnownLocation.fetchInhabitant(i);
if(M==null)
continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.Name(),name)
||CMLib.english().containsString(M.displayText(),name))
num++;
}
}
}
results.append(""+num);
break;
}
case 63: // numpcsroom
{
final Room R=lastKnownLocation;
if(R!=null)
{
int num=0;
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if((M!=null)&&(!M.isMonster()))
num++;
}
results.append(""+num);
}
break;
}
case 115: // expertise
{
// mob ability type > 10
final String arg1=CMParms.getCleanBit(funcParms,0);
final Physical P=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
final MOB M;
if(P instanceof MOB)
{
M=(MOB)P;
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1));
Ability A=M.fetchAbility(arg2);
if(A==null)
A=getAbility(arg2);
if(A!=null)
{
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,1));
final ExpertiseLibrary.Flag experFlag = (ExpertiseLibrary.Flag)CMath.s_valueOf(ExpertiseLibrary.Flag.class, arg3.toUpperCase().trim());
if(experFlag != null)
results.append(""+CMLib.expertises().getExpertiseLevel(M, A.ID(), experFlag));
}
}
break;
}
case 79: // numpcsarea
{
if(lastKnownLocation!=null)
{
int num=0;
for(final Session S : CMLib.sessions().localOnlineIterable())
{
if((S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea()))
num++;
}
results.append(""+num);
}
break;
}
case 77: // explored
{
final String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0));
final String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1));
final Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
{
Area A=null;
if(!where.equalsIgnoreCase("world"))
{
A=CMLib.map().getArea(where);
if(A==null)
{
final Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E2!=null)
A=CMLib.map().areaLocation(E2);
}
}
if((lastKnownLocation!=null)
&&((A!=null)||(where.equalsIgnoreCase("world"))))
{
int pct=0;
final MOB M=(MOB)E;
if(M.playerStats()!=null)
pct=M.playerStats().percentVisited(M,A);
results.append(""+pct);
}
}
break;
}
case 72: // faction
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBit(funcParms,0);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
final Faction F=CMLib.factions().getFaction(arg2);
if(F==null)
logError(scripted,"FACTION","Unknown Faction",arg1);
else
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).hasFaction(F.factionID())))
{
final int value=((MOB)E).fetchFaction(F.factionID());
final Faction.FRange FR=CMLib.factions().getRange(F.factionID(),value);
if(FR!=null)
results.append(FR.name());
}
break;
}
case 46: // numitemsroom
{
int ct=0;
if(lastKnownLocation!=null)
for(int i=0;i<lastKnownLocation.numItems();i++)
{
final Item I=lastKnownLocation.getItem(i);
if((I!=null)&&(I.container()==null))
ct++;
}
results.append(""+ct);
break;
}
case 47: //mobitem
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0));
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
MOB M=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
M=lastKnownLocation.fetchInhabitant(arg1.trim());
}
Item which=null;
int ct=1;
if(M!=null)
{
for(int i=0;i<M.numItems();i++)
{
final Item I=M.getItem(i);
if((I!=null)&&(I.container()==null))
{
if(ct==CMath.s_int(arg2.trim()))
{
which = I;
break;
}
ct++;
}
}
}
if(which!=null)
results.append(which.name());
break;
}
case 100: // shopitem
{
final String arg1raw=CMParms.getCleanBit(funcParms,0);
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1raw);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
PhysicalAgent where=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
where=lastKnownLocation.fetchInhabitant(arg1.trim());
if(where == null)
where=this.getArgumentItem(arg1raw, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(where == null)
where=this.getArgumentMOB(arg1raw, source, monster, target, primaryItem, secondaryItem, msg, tmp);
}
Environmental which=null;
int ct=1;
if(where!=null)
{
ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where);
if((shopHere == null)&&(scripted instanceof Item))
shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner());
if((shopHere == null)&&(scripted instanceof MOB))
shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location());
if(shopHere == null)
shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(shopHere!=null)
{
final CoffeeShop shop = shopHere.getShop();
if(shop != null)
{
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();ct++)
{
final Environmental E=i.next();
if(ct==CMath.s_int(arg2.trim()))
{
which = E;
setShopPrice(shopHere,E,tmp);
break;
}
}
}
}
}
if(which!=null)
results.append(which.name());
break;
}
case 101: // numitemsshop
{
final String arg1raw = CMParms.cleanBit(funcParms);
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1raw);
PhysicalAgent which=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
which=lastKnownLocation.fetchInhabitant(arg1);
if(which == null)
which=this.getArgumentItem(arg1raw, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(which == null)
which=this.getArgumentMOB(arg1raw, source, monster, target, primaryItem, secondaryItem, msg, tmp);
}
int ct=0;
if(which!=null)
{
ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(which);
if((shopHere == null)&&(scripted instanceof Item))
shopHere=CMLib.coffeeShops().getShopKeeper(((Item)which).owner());
if((shopHere == null)&&(scripted instanceof MOB))
shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)which).location());
if(shopHere == null)
shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(shopHere!=null)
{
final CoffeeShop shop = shopHere.getShop();
if(shop != null)
{
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();i.next())
{
ct++;
}
}
}
}
results.append(""+ct);
break;
}
case 102: // shophas
{
final String arg1raw=CMParms.cleanBit(funcParms);
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1raw);
PhysicalAgent where=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
where=lastKnownLocation.fetchInhabitant(arg1.trim());
if(where == null)
where=this.getArgumentItem(arg1raw, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(where == null)
where=this.getArgumentMOB(arg1raw, source, monster, target, primaryItem, secondaryItem, msg, tmp);
}
if(where!=null)
{
ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where);
if((shopHere == null)&&(scripted instanceof Item))
shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner());
if((shopHere == null)&&(scripted instanceof MOB))
shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location());
if(shopHere == null)
shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(shopHere!=null)
{
final CoffeeShop shop = shopHere.getShop();
if(shop != null)
{
int ct=0;
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();i.next())
ct++;
final int which=CMLib.dice().roll(1, ct, -1);
ct=0;
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();ct++)
{
final Environmental E=i.next();
if(which == ct)
{
results.append(E.Name());
setShopPrice(shopHere,E,tmp);
break;
}
}
}
}
}
break;
}
case 48: // numitemsmob
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
MOB which=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
which=lastKnownLocation.fetchInhabitant(arg1);
}
int ct=0;
if(which!=null)
{
for(int i=0;i<which.numItems();i++)
{
final Item I=which.getItem(i);
if((I!=null)&&(I.container()==null))
ct++;
}
}
results.append(""+ct);
break;
}
case 36: // ishere
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.getArea().name());
break;
}
case 17: // inroom
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||arg1.length()==0)
results.append(CMLib.map().getExtendedRoomID(lastKnownLocation));
else
results.append(CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(E)));
break;
}
case 90: // inarea
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||arg1.length()==0)
results.append(lastKnownLocation==null?"Nowhere":lastKnownLocation.getArea().Name());
else
{
final Room R=CMLib.map().roomLocation(E);
results.append(R==null?"Nowhere":R.getArea().Name());
}
break;
}
case 89: // isrecall
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
results.append(CMLib.map().getExtendedRoomID(CMLib.map().getStartRoom(E)));
break;
}
case 37: // inlocale
{
final String parms=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if(parms.trim().length()==0)
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.name());
}
else
{
final Environmental E=getArgumentItem(parms,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
final Room R=CMLib.map().roomLocation(E);
if(R!=null)
results.append(R.name());
}
}
break;
}
case 18: // sex
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().genderName());
break;
}
case 91: // datetime
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.toUpperCase().trim());
if(index<0)
logError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name());
else
if(CMLib.map().areaLocation(scripted)!=null)
{
switch(index)
{
case 2:
results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth());
break;
case 3:
results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth());
break;
case 4:
results.append(CMLib.map().areaLocation(scripted).getTimeObj().getMonth());
break;
case 5:
results.append(CMLib.map().areaLocation(scripted).getTimeObj().getYear());
break;
default:
results.append(CMLib.map().areaLocation(scripted).getTimeObj().getHourOfDay()); break;
}
}
break;
}
case 13: // stat
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBitClean(funcParms,0);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
final String val=getStatValue(E,arg2);
if(val==null)
{
logError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name());
break;
}
results.append(val);
break;
}
break;
}
case 52: // gstat
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBitClean(funcParms,0);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
final String val=getGStatValue(E,arg2);
if(val==null)
{
logError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name());
break;
}
results.append(val);
break;
}
break;
}
case 19: // position
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P!=null)
{
final String sex;
if(CMLib.flags().isSleeping(P))
sex="SLEEPING";
else
if(CMLib.flags().isSitting(P))
sex="SITTING";
else
sex="STANDING";
results.append(sex);
break;
}
break;
}
case 20: // level
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P!=null)
results.append(P.phyStats().level());
break;
}
case 80: // questpoints
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
results.append(((MOB)E).getQuestPoint());
break;
}
case 83: // qvar
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
if((arg1.length()!=0)&&(arg2.length()!=0))
{
final Quest Q=getQuest(arg1);
if(Q!=null)
results.append(Q.getStat(arg2));
}
break;
}
case 84: // math
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
results.append(""+Math.round(CMath.s_parseMathExpression(arg1)));
break;
}
case 85: // islike
{
final String arg1=CMParms.cleanBit(funcParms);
results.append(CMLib.masking().maskDesc(arg1));
break;
}
case 86: // strcontains
{
results.append("[unimplemented function]");
break;
}
case 81: // trains
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
results.append(((MOB)E).getTrains());
break;
}
case 92: // isodd
{
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp ,CMParms.cleanBit(funcParms)).trim();
boolean isodd = false;
if( CMath.isLong( val ) )
{
isodd = (CMath.s_long(val) %2 == 1);
}
if( isodd )
{
results.append( CMath.s_long( val.trim() ) );
}
break;
}
case 82: // pracs
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
results.append(((MOB)E).getPractices());
break;
}
case 68: // clandata
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBitClean(funcParms,0);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String clanID=null;
if((E!=null)&&(E instanceof MOB))
{
Clan C=CMLib.clans().findRivalrousClan((MOB)E);
if(C==null)
C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null;
if(C!=null)
clanID=C.clanID();
}
else
clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1);
final Clan C=CMLib.clans().findClan(clanID);
if(C!=null)
{
if(!C.isStat(arg2))
logError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable.");
else
results.append(C.getStat(arg2));
}
break;
}
case 98: // clanqualifies
{
final String arg1=CMParms.cleanBit(funcParms);
Clan C=CMLib.clans().getClan(arg1);
if(C==null)
C=CMLib.clans().findClan(arg1);
if(C!=null)
{
if(C.getAcceptanceSettings().length()>0)
results.append(CMLib.masking().maskDesc(C.getAcceptanceSettings()));
if(C.getBasicRequirementMask().length()>0)
results.append(CMLib.masking().maskDesc(C.getBasicRequirementMask()));
if(C.isOnlyFamilyApplicants())
results.append("Must belong to the family.");
final int total=CMProps.getMaxClansThisCategory(C.getCategory());
if(C.getCategory().length()>0)
results.append("May belong to only "+total+" "+C.getCategory()+" clan. ");
else
results.append("May belong to only "+total+" standard clan. ");
}
break;
}
case 67: // hastitle
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()>0)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null))
{
final MOB M=(MOB)E;
results.append(M.playerStats().getActiveTitle());
}
break;
}
case 66: // clanrank
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
Clan C=null;
if(E instanceof MOB)
{
C=CMLib.clans().findRivalrousClan((MOB)E);
if(C==null)
C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null;
}
else
C=CMLib.clans().findClan(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1));
if(C!=null)
{
final Pair<Clan,Integer> p=((MOB)E).getClanRole(C.clanID());
if(p!=null)
results.append(p.second.toString());
}
break;
}
case 21: // class
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().displayClassName());
break;
}
case 64: // deity
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
final String sex=((MOB)E).getWorshipCharID();
results.append(sex);
}
break;
}
case 65: // clan
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
Clan C=CMLib.clans().findRivalrousClan((MOB)E);
if(C==null)
C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null;
if(C!=null)
results.append(C.clanID());
}
break;
}
case 88: // mood
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
{
final Ability moodA=((MOB)E).fetchEffect("Mood");
if(moodA!=null)
results.append(CMStrings.capitalizeAndLower(moodA.text()));
}
break;
}
case 22: // baseclass
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().getCurrentClass().baseClass());
break;
}
case 23: // race
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().raceName());
break;
}
case 24: //racecat
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().getMyRace().racialCategory());
break;
}
case 25: // goldamt
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
results.append(false);
else
{
int val1=0;
if(E instanceof MOB)
val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted)));
else
if(E instanceof Coins)
val1=(int)Math.round(((Coins)E).getTotalValue());
else
if(E instanceof Item)
val1=((Item)E).value();
else
{
logError(scripted,"GOLDAMT","Syntax",funcParms);
return results.toString();
}
results.append(val1);
}
break;
}
case 78: // exp
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
results.append(false);
else
{
int val1=0;
if(E instanceof MOB)
val1=((MOB)E).getExperience();
results.append(val1);
}
break;
}
case 76: // value
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBitClean(funcParms,0);
if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase()))
{
logError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency.");
return results.toString();
}
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
results.append(false);
else
{
int val1=0;
if(E instanceof MOB)
val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2));
else
if(E instanceof Coins)
{
if(((Coins)E).getCurrency().equalsIgnoreCase(arg2))
val1=(int)Math.round(((Coins)E).getTotalValue());
}
else
if(E instanceof Item)
val1=((Item)E).value();
else
{
logError(scripted,"GOLDAMT","Syntax",funcParms);
return results.toString();
}
results.append(val1);
}
break;
}
case 26: // objtype
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
final String sex=CMClass.classID(E).toLowerCase();
results.append(sex);
}
break;
}
case 53: // incontainer
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
if(E instanceof MOB)
{
if(((MOB)E).riding()!=null)
results.append(((MOB)E).riding().Name());
}
else
if(E instanceof Item)
{
if(((Item)E).riding()!=null)
results.append(((Item)E).riding().Name());
else
if(((Item)E).container()!=null)
results.append(((Item)E).container().Name());
else
if(E instanceof Container)
{
final List<Item> V=((Container)E).getDeepContents();
for(int v=0;v<V.size();v++)
results.append("\""+V.get(v).Name()+"\" ");
}
}
}
break;
}
case 27: // var
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBitClean(funcParms,0).toUpperCase();
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
results.append(val);
break;
}
case 41: // eval
results.append("[unimplemented function]");
break;
case 40: // number
{
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim();
boolean isnumber=(val.length()>0);
for(int i=0;i<val.length();i++)
{
if(!Character.isDigit(val.charAt(i)))
{
isnumber = false;
break;
}
}
if(isnumber)
results.append(CMath.s_long(val.trim()));
break;
}
case 42: // randnum
{
final String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toUpperCase();
int arg1=0;
if(CMath.isMathExpression(arg1String))
arg1=CMath.s_parseIntExpression(arg1String.trim());
else
arg1=CMParms.parse(arg1String.trim()).size();
results.append(CMLib.dice().roll(1,arg1,0));
break;
}
case 71: // rand0num
{
final String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toUpperCase();
int arg1=0;
if(CMath.isMathExpression(arg1String))
arg1=CMath.s_parseIntExpression(arg1String.trim());
else
arg1=CMParms.parse(arg1String.trim()).size();
results.append(CMLib.dice().roll(1,arg1,-1));
break;
}
case 96: // iscontents
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof Rideable)
{
for(final Enumeration<Rider> r=((Rideable)E).riders();r.hasMoreElements();)
results.append(CMParms.quoteIfNecessary(r.nextElement().name())).append(" ");
}
if(E instanceof Container)
{
for (final Item item : ((Container)E).getDeepContents())
results.append(CMParms.quoteIfNecessary(item.name())).append(" ");
}
break;
}
case 97: // wornon
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBitClean(funcParms,0).toUpperCase();
final PhysicalAgent E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
int wornLoc=-1;
if(arg2.length()>0)
wornLoc = CMParms.indexOf(Wearable.CODES.NAMESUP(), arg2.toUpperCase().trim());
if(wornLoc<0)
logError(scripted,"EVAL","BAD WORNON LOCATION",arg2);
else
if(E instanceof MOB)
{
final List<Item> items=((MOB)E).fetchWornItems(Wearable.CODES.GET(wornLoc),(short)-2048,(short)0);
for(final Item item : items)
results.append(CMParms.quoteIfNecessary(item.name())).append(" ");
}
break;
}
default:
logError(scripted,"Unknown Val",preFab,evaluable);
return results.toString();
}
}
return results.toString();
}
protected MOB getRandPC(final MOB monster, final Object[] tmp, final Room room)
{
if((tmp[SPECIAL_RANDPC]==null)||(tmp[SPECIAL_RANDPC]==monster))
{
MOB M=null;
if(room!=null)
{
final List<MOB> choices = new ArrayList<MOB>();
for(int p=0;p<room.numInhabitants();p++)
{
M=room.fetchInhabitant(p);
if((!M.isMonster())&&(M!=monster))
{
final HashSet<MOB> seen=new HashSet<MOB>();
while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M)))
{
seen.add(M);
M=M.amFollowing();
}
choices.add(M);
}
}
if(choices.size() > 0)
tmp[SPECIAL_RANDPC] = choices.get(CMLib.dice().roll(1,choices.size(),-1));
}
}
return (MOB)tmp[SPECIAL_RANDPC];
}
protected MOB getRandAnyone(final MOB monster, final Object[] tmp, final Room room)
{
if((tmp[SPECIAL_RANDANYONE]==null)||(tmp[SPECIAL_RANDANYONE]==monster))
{
MOB M=null;
if(room!=null)
{
final List<MOB> choices = new ArrayList<MOB>();
for(int p=0;p<room.numInhabitants();p++)
{
M=room.fetchInhabitant(p);
if(M!=monster)
{
final HashSet<MOB> seen=new HashSet<MOB>();
while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M)))
{
seen.add(M);
M=M.amFollowing();
}
choices.add(M);
}
}
if(choices.size() > 0)
tmp[SPECIAL_RANDANYONE] = choices.get(CMLib.dice().roll(1,choices.size(),-1));
}
}
return (MOB)tmp[SPECIAL_RANDANYONE];
}
protected DVector findFunc(String named)
{
if(named==null)
return null;
named=named.toUpperCase();
final List<DVector> scripts=getScripts();
for(int v=0;v<scripts.size();v++)
{
final DVector script2=scripts.get(v);
if(script2.size()<1)
continue;
final String trigger=((String)script2.elementAt(0,1)).toUpperCase().trim();
final String[] ttrigger=(String[])script2.elementAt(0,2);
if(getTriggerCode(trigger,ttrigger)==17) // function_prog
{
final String fnamed=CMParms.getCleanBit(trigger,1);
if(fnamed.equals(named))
return script2;
}
}
for(int v=0;v<scripts.size();v++)
{
final DVector script2=scripts.get(v);
if(script2.size()<1)
continue;
final String trigger=((String)script2.elementAt(0,1)).toUpperCase().trim();
if(trigger.equals(named)||trigger.equals(named+"_PROG"))
return script2;
}
return null;
}
@Override
public boolean isFunc(final String named)
{
return findFunc(named) != null;
}
@Override
public String callFunc(final String named, final String parms, final PhysicalAgent scripted, final MOB source, final Environmental target,
final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp)
{
final DVector script2 = findFunc(named);
if(script2 != null)
{
return execute(scripted, source, target, monster, primaryItem, secondaryItem, script2,
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,parms),tmp);
}
return null;
}
@Override
public String execute(final PhysicalAgent scripted,
final MOB source,
final Environmental target,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final DVector script,
final String msg,
final Object[] tmp)
{
return execute(scripted,source,target,monster,primaryItem,secondaryItem,script,msg,tmp,1);
}
public String execute(PhysicalAgent scripted,
MOB source,
Environmental target,
MOB monster,
Item primaryItem,
Item secondaryItem,
final DVector script,
String msg,
final Object[] tmp,
final int startLine)
{
tickStatus=Tickable.STATUS_START;
String s=null;
String[] tt=null;
String cmd=null;
final boolean traceDebugging=CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTTRACE);
if(traceDebugging && startLine == 1 && script.size()>0 && script.get(0, 1).toString().trim().length()>0)
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": * EXECUTE: "+script.get(0, 1).toString());
for(int si=startLine;si<script.size();si++)
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.length()==0)
continue;
if(traceDebugging)
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": "+s);
Integer methCode=methH.get(cmd);
if((methCode==null)&&(cmd.startsWith("MP")))
{
for(int i=0;i<methods.length;i++)
{
if(methods[i].startsWith(cmd))
methCode=Integer.valueOf(i);
}
}
if(methCode==null)
methCode=Integer.valueOf(0);
tickStatus=Tickable.STATUS_MISC3+methCode.intValue();
switch(methCode.intValue())
{
case 57: // <SCRIPT>
{
if(tt==null)
tt=parseBits(script,si,"C");
final StringBuffer jscript=new StringBuffer("");
while((++si)<script.size())
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.equals("</SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
break;
}
jscript.append(s+"\n");
}
if(CMSecurity.isApprovedJScript(jscript))
{
final Context cx = Context.enter();
try
{
final JScriptEvent scope = new JScriptEvent(this,scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp);
cx.initStandardObjects(scope);
final String[] names = { "host", "source", "target", "monster", "item", "item2", "message" ,"getVar", "setVar", "toJavaString", "getCMType"};
scope.defineFunctionProperties(names, JScriptEvent.class,
ScriptableObject.DONTENUM);
cx.evaluateString(scope, jscript.toString(),"<cmd>", 1, null);
}
catch(final Exception e)
{
Log.errOut("Scripting",scripted.name()+"/"+CMLib.map().getDescriptiveExtendedRoomID(lastKnownLocation)+"/JSCRIPT Error: "+e.getMessage());
}
Context.exit();
}
else
if(CMProps.getIntVar(CMProps.Int.JSCRIPTS)==CMSecurity.JSCRIPT_REQ_APPROVAL)
{
if(lastKnownLocation!=null)
lastKnownLocation.showHappens(CMMsg.MSG_OK_ACTION,L("A Javascript was not authorized. Contact an Admin to use MODIFY JSCRIPT to authorize this script."));
}
break;
}
case 19: // if
{
if(tt==null)
{
try
{
final String[] ttParms=parseEval(s.substring(2));
tt=new String[ttParms.length+1];
tt[0]="IF";
for(int i=0;i<ttParms.length;i++)
tt[i+1]=ttParms[i];
script.setElementAt(si,2,tt);
script.setElementAt(si, 3, new Triad<DVector,DVector,Integer>(null,null,null));
}
catch(final Exception e)
{
logError(scripted,"IF","Syntax",e.getMessage());
tickStatus=Tickable.STATUS_END;
return null;
}
}
final String[][] EVAL={tt};
final boolean condition=eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,EVAL,1);
if(EVAL[0]!=tt)
{
tt=EVAL[0];
script.setElementAt(si,2,tt);
}
boolean foundendif=false;
@SuppressWarnings({ "unchecked", "rawtypes" })
Triad<DVector,DVector,Integer> parsedBlocks = (Triad)script.elementAt(si, 3);
DVector subScript;
if(parsedBlocks==null)
{
Log.errOut("Null parsed blocks in "+s);
parsedBlocks = new Triad<DVector,DVector,Integer>(null,null,null);
script.setElementAt(si, 3, parsedBlocks);
subScript=null;
}
else
if(parsedBlocks.third != null)
{
if(condition)
subScript=parsedBlocks.first;
else
subScript=parsedBlocks.second;
si=parsedBlocks.third.intValue();
si--; // because we want to be pointing at the ENDIF with si++ happens below.
foundendif=true;
}
else
subScript=null;
int depth=0;
boolean ignoreUntilEndScript=false;
si++;
boolean positiveCondition=true;
while((si<script.size())
&&(!foundendif))
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.equals("<SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
ignoreUntilEndScript=true;
}
else
if(cmd.equals("</SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
ignoreUntilEndScript=false;
}
else
if(ignoreUntilEndScript)
{
}
else
if(cmd.equals("ENDIF")&&(depth==0))
{
if(tt==null)
tt=parseBits(script,si,"C");
parsedBlocks.third=Integer.valueOf(si);
foundendif=true;
break;
}
else
if(cmd.equals("ELSE")&&(depth==0))
{
positiveCondition=false;
if(s.substring(4).trim().length()>0)
logError(scripted,"ELSE","Syntax"," Decorated ELSE is now illegal!!");
else
if(tt==null)
tt=parseBits(script,si,"C");
}
else
{
if(cmd.equals("IF"))
depth++;
else
if(cmd.equals("ENDIF"))
{
if(tt==null)
tt=parseBits(script,si,"C");
depth--;
}
if(positiveCondition)
{
if(parsedBlocks.first==null)
{
parsedBlocks.first=new DVector(3);
parsedBlocks.first.addElement("",null,null);
}
if(condition)
subScript=parsedBlocks.first;
parsedBlocks.first.addSharedElements(script.elementsAt(si));
}
else
{
if(parsedBlocks.second==null)
{
parsedBlocks.second=new DVector(3);
parsedBlocks.second.addElement("",null,null);
}
if(!condition)
subScript=parsedBlocks.second;
parsedBlocks.second.addSharedElements(script.elementsAt(si));
}
}
si++;
}
if(!foundendif)
{
logError(scripted,"IF","Syntax"," Without ENDIF!");
tickStatus=Tickable.STATUS_END;
return null;
}
if((subScript != null)
&&(subScript.size()>1)
&&(subScript != script))
{
//source.tell(L("Starting @x1",conditionStr));
//for(int v=0;v<V.size();v++)
// source.tell(L("Statement @x1",((String)V.elementAt(v))));
final String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp);
if(response!=null)
{
tickStatus=Tickable.STATUS_END;
return response;
}
//source.tell(L("Stopping @x1",conditionStr));
}
break;
}
case 93: // "ENDIF", //93 JUST for catching errors...
logError(scripted,"ENDIF","Syntax"," Without IF ("+si+")!");
break;
case 94: //"ENDSWITCH", //94 JUST for catching errors...
logError(scripted,"ENDSWITCH","Syntax"," Without SWITCH ("+si+")!");
break;
case 95: //"NEXT", //95 JUST for catching errors...
logError(scripted,"NEXT","Syntax"," Without FOR ("+si+")!");
break;
case 96: //"CASE" //96 JUST for catching errors...
logError(scripted,"CASE","Syntax"," Without SWITCH ("+si+")!");
break;
case 97: //"DEFAULT" //97 JUST for catching errors...
logError(scripted,"DEFAULT","Syntax"," Without SWITCH ("+si+")!");
break;
case 70: // switch
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
if(script.elementAt(si, 3)==null)
script.setElementAt(si, 3, new Hashtable<String,Integer>());
}
@SuppressWarnings("unchecked")
final Map<String,Integer> skipSwitchMap=(Map<String,Integer>)script.elementAt(si, 3);
final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]).trim();
final DVector subScript=new DVector(3);
subScript.addElement("",null,null);
int depth=0;
boolean foundEndSwitch=false;
boolean ignoreUntilEndScript=false;
boolean inCase=false;
boolean matchedCase=false;
si++;
String s2=null;
if(skipSwitchMap.size()>0)
{
if(skipSwitchMap.containsKey(var.toUpperCase()))
{
inCase=true;
matchedCase=true;
si=skipSwitchMap.get(var.toUpperCase()).intValue();
si++;
}
else
if(skipSwitchMap.containsKey("$FIRSTVAR")) // first variable case
{
si=skipSwitchMap.get("$FIRSTVAR").intValue();
}
else
if(skipSwitchMap.containsKey("$DEFAULT")) // the "default" case
{
inCase=true;
matchedCase=true;
si=skipSwitchMap.get("$DEFAULT").intValue();
si++;
}
else
if(skipSwitchMap.containsKey("$ENDSWITCH")) // the "endswitch" case
{
foundEndSwitch=true;
si=skipSwitchMap.get("$ENDSWITCH").intValue();
}
}
while((si<script.size())
&&(!foundEndSwitch))
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.equals("<SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
ignoreUntilEndScript=true;
}
else
if(cmd.equals("</SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
ignoreUntilEndScript=false;
}
else
if(ignoreUntilEndScript)
{
// only applies when <SCRIPT> encountered.
}
else
if(cmd.equals("ENDSWITCH")&&(depth==0))
{
if(tt==null)
{
tt=parseBits(script,si,"C");
skipSwitchMap.put("$ENDSWITCH", Integer.valueOf(si));
}
foundEndSwitch=true;
break;
}
else
if(cmd.equals("CASE")&&(depth==0))
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
if(tt[1].indexOf('$')>=0)
{
if(!skipSwitchMap.containsKey("$FIRSTVAR"))
skipSwitchMap.put("$FIRSTVAR", Integer.valueOf(si));
}
else
if(!skipSwitchMap.containsKey(tt[1].toUpperCase()))
skipSwitchMap.put(tt[1].toUpperCase(), Integer.valueOf(si));
}
if(matchedCase
&&inCase
&&(skipSwitchMap.containsKey("$ENDSWITCH"))) // we're done
{
foundEndSwitch=true;
si=skipSwitchMap.get("$ENDSWITCH").intValue();
break; // this is important, otherwise si will get increment and screw stuff up
}
else
{
s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]).trim();
inCase=var.equalsIgnoreCase(s2);
matchedCase=matchedCase||inCase;
}
}
else
if(cmd.equals("DEFAULT")&&(depth==0))
{
if(tt==null)
{
tt=parseBits(script,si,"C");
if(!skipSwitchMap.containsKey("$DEFAULT"))
skipSwitchMap.put("$DEFAULT", Integer.valueOf(si));
}
if(matchedCase
&&inCase
&&(skipSwitchMap.containsKey("$ENDSWITCH"))) // we're done
{
foundEndSwitch=true;
si=skipSwitchMap.get("$ENDSWITCH").intValue();
break; // this is important, otherwise si will get increment and screw stuff up
}
else
inCase=!matchedCase;
}
else
{
if(inCase)
subScript.addSharedElements(script.elementsAt(si));
if(cmd.equals("SWITCH"))
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(script.elementAt(si, 3)==null)
script.setElementAt(si, 3, new Hashtable<String,Integer>());
}
depth++;
}
else
if(cmd.equals("ENDSWITCH"))
{
if(tt==null)
tt=parseBits(script,si,"C");
depth--;
}
}
si++;
}
if(!foundEndSwitch)
{
logError(scripted,"SWITCH","Syntax"," Without ENDSWITCH!");
tickStatus=Tickable.STATUS_END;
return null;
}
if(subScript.size()>1)
{
final String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp);
if(response!=null)
{
tickStatus=Tickable.STATUS_END;
return response;
}
}
break;
}
case 62: // for x = 1 to 100
{
if(tt==null)
{
tt=parseBits(script,si,"CcccCr");
if(tt==null)
return null;
}
if(tt[5].length()==0)
{
logError(scripted,"FOR","Syntax","5 parms required!");
tickStatus=Tickable.STATUS_END;
return null;
}
final String varStr=tt[1];
if((varStr.length()!=2)||(varStr.charAt(0)!='$')||(!Character.isDigit(varStr.charAt(1))))
{
logError(scripted,"FOR","Syntax","'"+varStr+"' is not a tmp var $1, $2..");
tickStatus=Tickable.STATUS_END;
return null;
}
final int whichVar=CMath.s_int(Character.toString(varStr.charAt(1)));
if((tmp[whichVar] instanceof String)
&&(((String)tmp[whichVar]).length()>0)
&&(CMath.isInteger(((String)tmp[whichVar]).trim())))
{
logError(scripted,"FOR","Syntax","'"+whichVar+"' is already in use! Use a different one!");
tickStatus=Tickable.STATUS_END;
return null;
}
if(!tt[2].equals("="))
{
logError(scripted,"FOR","Syntax","'"+s+"' is illegal for syntax!");
tickStatus=Tickable.STATUS_END;
return null;
}
int toAdd=0;
if(tt[4].equals("TO<"))
toAdd=-1;
else
if(tt[4].equals("TO>"))
toAdd=1;
else
if(!tt[4].equals("TO"))
{
logError(scripted,"FOR","Syntax","'"+s+"' is illegal for syntax!");
tickStatus=Tickable.STATUS_END;
return null;
}
final String from=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]).trim();
final String to=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[5]).trim();
if((!CMath.isInteger(from))||(!CMath.isInteger(to)))
{
logError(scripted,"FOR","Syntax","'"+from+"-"+to+"' is illegal range!");
tickStatus=Tickable.STATUS_END;
return null;
}
final DVector subScript=new DVector(3);
subScript.addElement("",null,null);
int depth=0;
boolean foundnext=false;
boolean ignoreUntilEndScript=false;
si++;
while(si<script.size())
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.equals("<SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
ignoreUntilEndScript=true;
}
else
if(cmd.equals("</SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
ignoreUntilEndScript=false;
}
else
if(ignoreUntilEndScript)
{
}
else
if(cmd.equals("NEXT")&&(depth==0))
{
if(tt==null)
tt=parseBits(script,si,"C");
foundnext=true;
break;
}
else
{
if(cmd.equals("FOR"))
{
if(tt==null)
tt=parseBits(script,si,"CcccCr");
depth++;
}
else
if(cmd.equals("NEXT"))
{
if(tt==null)
tt=parseBits(script,si,"C");
depth--;
}
subScript.addSharedElements(script.elementsAt(si));
}
si++;
}
if(!foundnext)
{
logError(scripted,"FOR","Syntax"," Without NEXT!");
tickStatus=Tickable.STATUS_END;
return null;
}
if(subScript.size()>1)
{
//source.tell(L("Starting @x1",conditionStr));
//for(int v=0;v<V.size();v++)
// source.tell(L("Statement @x1",((String)V.elementAt(v))));
final int fromInt=CMath.s_int(from);
int toInt=CMath.s_int(to);
final int increment=(toInt>=fromInt)?1:-1;
String response=null;
if(((increment>0)&&(fromInt<=(toInt+toAdd)))
||((increment<0)&&(fromInt>=(toInt+toAdd))))
{
toInt+=toAdd;
final long tm=System.currentTimeMillis()+(10 * 1000);
for(int forLoop=fromInt;forLoop!=toInt;forLoop+=increment)
{
tmp[whichVar]=""+forLoop;
response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp);
if(response!=null)
break;
if((System.currentTimeMillis()>tm) || (scripted.amDestroyed()))
{
logError(scripted,"FOR","Runtime","For loop violates 10 second rule: " +s);
break;
}
}
tmp[whichVar]=""+toInt;
if(response == null)
response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp);
else
if(response.equalsIgnoreCase("break"))
response=null;
}
if(response!=null)
{
tickStatus=Tickable.STATUS_END;
return response;
}
tmp[whichVar]=null;
//source.tell(L("Stopping @x1",conditionStr));
}
break;
}
case 50: // break;
if(tt==null)
tt=parseBits(script,si,"C");
tickStatus=Tickable.STATUS_END;
return "BREAK";
case 1: // mpasound
{
if(tt==null)
{
tt=parseBits(script,si,"Cp");
if(tt==null)
return null;
}
final String echo=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
//lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,echo);
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
final Room R2=lastKnownLocation.getRoomInDir(d);
final Exit E2=lastKnownLocation.getExitInDir(d);
if((R2!=null)&&(E2!=null)&&(E2.isOpen()))
R2.showOthers(monster,null,null,CMMsg.MSG_OK_ACTION,echo);
}
break;
}
case 4: // mpjunk
{
if(tt==null)
{
tt=parseBits(script,si,"CR");
if(tt==null)
return null;
}
if(tt[1].equals("ALL") && (monster!=null))
{
monster.delAllItems(true);
}
else
{
final Environmental E=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
Item I=null;
if(E instanceof Item)
I=(Item)E;
if((I==null)&&(monster!=null))
I=monster.findItem(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]));
if((I==null)&&(scripted instanceof Room))
I=((Room)scripted).findItem(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]));
if(I!=null)
I.destroy();
}
break;
}
case 2: // mpecho
{
if(tt==null)
{
tt=parseBits(script,si,"Cp");
if(tt==null)
return null;
}
if(lastKnownLocation!=null)
lastKnownLocation.show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]));
break;
}
case 13: // mpunaffect
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String which=tt[2];
if(newTarget!=null)
if(which.equalsIgnoreCase("all")||(which.length()==0))
{
for(int a=newTarget.numEffects()-1;a>=0;a--)
{
final Ability A=newTarget.fetchEffect(a);
if(A!=null)
A.unInvoke();
}
}
else
{
final Ability A2=findAbility(which);
if(A2!=null)
which=A2.ID();
final Ability A=newTarget.fetchEffect(which);
if(A!=null)
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" was MPUNAFFECTED by "+A.Name());
A.unInvoke();
if(newTarget.fetchEffect(which)==A)
newTarget.delEffect(A);
}
}
break;
}
case 3: // mpslay
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB))
CMLib.combat().postDeath(monster,(MOB)newTarget,null);
break;
}
case 73: // mpsetinternal
{
if(tt==null)
{
tt=parseBits(script,si,"CCr");
if(tt==null)
return null;
}
final String arg2=tt[1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if(arg2.equals("SCOPE"))
setVarScope(arg3);
else
if(arg2.equals("NODELAY"))
noDelay=CMath.s_bool(arg3);
else
if(arg2.equals("ACTIVETRIGGER")||arg2.equals("ACTIVETRIGGERS"))
alwaysTriggers=CMath.s_bool(arg3);
else
if(arg2.equals("DEFAULTQUEST"))
registerDefaultQuest(arg3);
else
if(arg2.equals("SAVABLE"))
setSavable(CMath.s_bool(arg3));
else
if(arg2.equals("PASSIVE"))
this.runInPassiveAreas = CMath.s_bool(arg3);
else
logError(scripted,"MPSETINTERNAL","Syntax","Unknown stat: "+arg2);
break;
}
case 74: // mpprompt
{
if(tt==null)
{
tt=parseBits(script,si,"CCCr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null)))
{
try
{
final String value=((MOB)newTarget).session().prompt(promptStr,120000);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS))
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+newTarget.Name()+"("+var+")="+value+"<");
setVar(newTarget.Name(),var,value);
}
catch(final Exception e)
{
return "";
}
}
break;
}
case 75: // mpconfirm
{
if(tt==null)
{
tt=parseBits(script,si,"CCCCr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String defaultVal=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
final String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]);
if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null)))
{
try
{
final String value=((MOB)newTarget).session().confirm(promptStr,defaultVal,60000)?"Y":"N";
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS))
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+newTarget.Name()+"("+var+")="+value+"<");
setVar(newTarget.Name(),var,value);
}
catch(final Exception e)
{
return "";
}
/*
* this is how to do non-blocking, which doesn't help stuff waiting
* for a response from the original execute method
final Session session = ((MOB)newTarget).session();
if(session != null)
{
try
{
final int lastLineNum=si;
final JScriptEvent continueEvent=new JScriptEvent(
this,
scripted,
source,
target,
monster,
primaryItem,
secondaryItem,
msg,
tmp);
((MOB)newTarget).session().prompt(new InputCallback(InputCallback.Type.PROMPT,"",0)
{
private final JScriptEvent event=continueEvent;
private final int lineNum=lastLineNum;
private final String scope=newTarget.Name();
private final String varName=var;
private final String promptStrMsg=promptStr;
private final DVector lastScript=script;
@Override
public void showPrompt()
{
session.promptPrint(promptStrMsg);
}
@Override
public void timedOut()
{
event.executeEvent(lastScript, lineNum+1);
}
@Override
public void callBack()
{
final String value=this.input;
if((value.trim().length()==0)||(value.indexOf('<')>=0))
return;
setVar(scope,varName,value);
event.executeEvent(lastScript, lineNum+1);
}
});
}
catch(final Exception e)
{
return "";
}
}
*/
}
break;
}
case 76: // mpchoose
{
if(tt==null)
{
tt=parseBits(script,si,"CCCCCr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String choices=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
final String defaultVal=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]);
final String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[5]);
if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null)))
{
try
{
final String value=((MOB)newTarget).session().choose(promptStr,choices,defaultVal,60000);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS))
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+newTarget.Name()+"("+var+")="+value+"<");
setVar(newTarget.Name(),var,value);
}
catch(final Exception e)
{
return "";
}
}
break;
}
case 16: // mpset
{
if(tt==null)
{
tt=parseBits(script,si,"CCcr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=tt[2];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if(newTarget!=null)
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" has "+arg2+" MPSETTED to "+arg3);
boolean found=false;
for(int i=0;i<newTarget.getStatCodes().length;i++)
{
if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1);
newTarget.setStat(arg2,arg3);
found=true;
break;
}
}
if((!found)&&(newTarget instanceof MOB))
{
final MOB M=(MOB)newTarget;
for(final int i : CharStats.CODES.ALLCODES())
{
if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(M.baseCharStats().getStat(i)+1);
if(arg3.equals("--"))
arg3=""+(M.baseCharStats().getStat(i)-1);
M.baseCharStats().setStat(i,CMath.s_int(arg3.trim()));
M.recoverCharStats();
if(arg2.equalsIgnoreCase("RACE"))
M.charStats().getMyRace().startRacing(M,false);
found=true;
break;
}
}
if(!found)
{
for(int i=0;i<M.curState().getStatCodes().length;i++)
{
if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1);
M.curState().setStat(arg2,arg3);
found=true;
break;
}
}
}
if(!found)
{
for(int i=0;i<M.basePhyStats().getStatCodes().length;i++)
{
if(M.basePhyStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))-1);
M.basePhyStats().setStat(arg2,arg3);
found=true;
break;
}
}
}
if((!found)&&(M.playerStats()!=null))
{
for(int i=0;i<M.playerStats().getStatCodes().length;i++)
{
if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1);
M.playerStats().setStat(arg2,arg3);
found=true;
break;
}
}
}
if((!found)&&(arg2.toUpperCase().startsWith("BASE")))
{
for(int i=0;i<M.baseState().getStatCodes().length;i++)
{
if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4)))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1);
M.baseState().setStat(arg2.substring(4),arg3);
found=true;
break;
}
}
}
if((!found)&&(arg2.toUpperCase().equals("STINK")))
{
found=true;
if(M.playerStats()!=null)
M.playerStats().setHygiene(Math.round(CMath.s_pct(arg3)*PlayerStats.HYGIENE_DELIMIT));
}
if((!found)
&&(CMath.s_valueOf(GenericBuilder.GenMOBBonusFakeStats.class,arg2.toUpperCase())!=null))
{
found=true;
CMLib.coffeeMaker().setAnyGenStat(M, arg2.toUpperCase(), arg3);
}
}
if((!found)
&&(newTarget instanceof Item))
{
if((!found)
&&(CMath.s_valueOf(GenericBuilder.GenItemBonusFakeStats.class,arg2.toUpperCase())!=null))
{
found=true;
CMLib.coffeeMaker().setAnyGenStat(newTarget, arg2.toUpperCase(), arg3);
}
}
if((!found)
&&(CMath.s_valueOf(GenericBuilder.GenPhysBonusFakeStats.class,arg2.toUpperCase())!=null))
{
found=true;
CMLib.coffeeMaker().setAnyGenStat(newTarget, arg2.toUpperCase(), arg3);
}
if(!found)
{
logError(scripted,"MPSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name());
break;
}
if(newTarget instanceof MOB)
((MOB)newTarget).recoverCharStats();
newTarget.recoverPhyStats();
if(newTarget instanceof MOB)
{
((MOB)newTarget).recoverMaxState();
if(arg2.equalsIgnoreCase("LEVEL"))
{
CMLib.leveler().fillOutMOB(((MOB)newTarget),((MOB)newTarget).basePhyStats().level());
((MOB)newTarget).recoverMaxState();
((MOB)newTarget).recoverCharStats();
((MOB)newTarget).recoverPhyStats();
((MOB)newTarget).resetToMaxState();
}
}
}
break;
}
case 63: // mpargset
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final String arg1=tt[1];
final String arg2=tt[2];
if((arg1.length()!=2)||(!arg1.startsWith("$")))
{
logError(scripted,"MPARGSET","Syntax","Mangled argument var: "+arg1+" for "+scripted.Name());
break;
}
Object O=getArgumentMOB(arg2,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(O==null)
O=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((O==null)
&&((arg2.length()!=2)
||(arg2.charAt(1)=='g')
||(!arg2.startsWith("$"))
||((!Character.isDigit(arg2.charAt(1)))
&&(!Character.isLetter(arg2.charAt(1))))))
O=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2);
final char c=arg1.charAt(1);
if(Character.isDigit(c))
{
if((O instanceof String)&&(((String)O).equalsIgnoreCase("null")))
O=null;
tmp[CMath.s_int(Character.toString(c))]=O;
}
else
{
switch(arg1.charAt(1))
{
case 'N':
case 'n':
if (O instanceof MOB)
source = (MOB) O;
break;
case 'B':
case 'b':
if (O instanceof Environmental)
lastLoaded = (Environmental) O;
break;
case 'I':
case 'i':
if (O instanceof PhysicalAgent)
scripted = (PhysicalAgent) O;
if (O instanceof MOB)
monster = (MOB) O;
break;
case 'T':
case 't':
if (O instanceof Environmental)
target = (Environmental) O;
break;
case 'O':
case 'o':
if (O instanceof Item)
primaryItem = (Item) O;
break;
case 'P':
case 'p':
if (O instanceof Item)
secondaryItem = (Item) O;
break;
case 'd':
case 'D':
if (O instanceof Room)
lastKnownLocation = (Room) O;
break;
case 'g':
case 'G':
if (O instanceof String)
msg = (String) O;
else
if((O instanceof Room)
&&((((Room)O).roomID().length()>0)
|| (!"".equals(CMLib.map().getExtendedRoomID((Room)O)))))
msg = CMLib.map().getExtendedRoomID((Room)O);
else
if(O instanceof CMObject)
msg=((CMObject)O).name();
else
msg=""+O;
break;
default:
logError(scripted, "MPARGSET", "Syntax", "Invalid argument var: " + arg1 + " for " + scripted.Name());
break;
}
}
break;
}
case 35: // mpgset
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=tt[2];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if(newTarget!=null)
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" has "+arg2+" MPGSETTED to "+arg3);
boolean found=false;
for(int i=0;i<newTarget.getStatCodes().length;i++)
{
if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1);
newTarget.setStat(newTarget.getStatCodes()[i],arg3);
found=true;
break;
}
}
if(!found)
{
if(newTarget instanceof MOB)
{
final GenericBuilder.GenMOBCode element = (GenericBuilder.GenMOBCode)CMath.s_valueOf(GenericBuilder.GenMOBCode.class,arg2.toUpperCase().trim());
if(element != null)
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,element.name()))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,element.name()))-1);
CMLib.coffeeMaker().setGenMobStat((MOB)newTarget,element.name(),arg3);
found=true;
}
if(!found)
{
final MOB M=(MOB)newTarget;
for(final int i : CharStats.CODES.ALLCODES())
{
if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(M.baseCharStats().getStat(i)+1);
if(arg3.equals("--"))
arg3=""+(M.baseCharStats().getStat(i)-1);
if((arg3.length()==1)&&(Character.isLetter(arg3.charAt(0))))
M.baseCharStats().setStat(i,arg3.charAt(0));
else
M.baseCharStats().setStat(i,CMath.s_int(arg3.trim()));
M.recoverCharStats();
if(arg2.equalsIgnoreCase("RACE"))
M.charStats().getMyRace().startRacing(M,false);
found=true;
break;
}
}
if(!found)
{
for(int i=0;i<M.curState().getStatCodes().length;i++)
{
if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1);
M.curState().setStat(arg2,arg3);
found=true;
break;
}
}
}
if(!found)
{
for(int i=0;i<M.basePhyStats().getStatCodes().length;i++)
{
if(M.basePhyStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))-1);
M.basePhyStats().setStat(arg2,arg3);
found=true;
break;
}
}
}
if((!found)&&(M.playerStats()!=null))
{
for(int i=0;i<M.playerStats().getStatCodes().length;i++)
{
if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1);
M.playerStats().setStat(arg2,arg3);
found=true;
break;
}
}
}
if((!found)&&(arg2.toUpperCase().startsWith("BASE")))
{
final String arg4=arg2.substring(4);
for(int i=0;i<M.baseState().getStatCodes().length;i++)
{
if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg4))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1);
M.baseState().setStat(arg4,arg3);
found=true;
break;
}
}
}
if((!found)&&(arg2.toUpperCase().equals("STINK")))
{
found=true;
if(M.playerStats()!=null)
M.playerStats().setHygiene(Math.round(CMath.s_pct(arg3)*PlayerStats.HYGIENE_DELIMIT));
}
}
}
}
else
if(newTarget instanceof Item)
{
final GenericBuilder.GenItemCode element = (GenericBuilder.GenItemCode)CMath.s_valueOf(GenericBuilder.GenItemCode.class,arg2.toUpperCase().trim());
if(element != null)
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,element.name()))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,element.name()))-1);
CMLib.coffeeMaker().setGenItemStat((Item)newTarget,element.name(),arg3);
found=true;
}
}
if((!found)
&&(newTarget instanceof Physical))
{
if(CMLib.coffeeMaker().isAnyGenStat(newTarget, arg2.toUpperCase()))
{
CMLib.coffeeMaker().setAnyGenStat(newTarget, arg2.toUpperCase(), arg3);
found=true;
}
}
if(!found)
{
logError(scripted,"MPGSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name());
break;
}
if(newTarget instanceof MOB)
((MOB)newTarget).recoverCharStats();
newTarget.recoverPhyStats();
if(newTarget instanceof MOB)
{
((MOB)newTarget).recoverMaxState();
if(arg2.equalsIgnoreCase("LEVEL"))
{
CMLib.leveler().fillOutMOB(((MOB)newTarget),((MOB)newTarget).basePhyStats().level());
((MOB)newTarget).recoverMaxState();
((MOB)newTarget).recoverCharStats();
((MOB)newTarget).recoverPhyStats();
((MOB)newTarget).resetToMaxState();
}
}
}
break;
}
case 11: // mpexp
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
int t=CMath.s_int(amtStr);
if((newTarget!=null)&&(newTarget instanceof MOB))
{
if((amtStr.endsWith("%"))
&&(((MOB)newTarget).getExpNeededLevel()<Integer.MAX_VALUE))
{
final int baseLevel=newTarget.basePhyStats().level();
final int lastLevelExpNeeded=(baseLevel<=1)?0:CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel-1);
final int thisLevelExpNeeded=CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel);
t=(int)Math.round(CMath.mul(thisLevelExpNeeded-lastLevelExpNeeded,
CMath.div(CMath.s_int(amtStr.substring(0,amtStr.length()-1)),100.0)));
}
if(t!=0)
CMLib.leveler().postExperience((MOB)newTarget,null,null,t,false);
}
break;
}
case 86: // mprpexp
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
int t=CMath.s_int(amtStr);
if((newTarget!=null)&&(newTarget instanceof MOB))
{
if((amtStr.endsWith("%"))
&&(((MOB)newTarget).getExpNeededLevel()<Integer.MAX_VALUE))
{
final int baseLevel=newTarget.basePhyStats().level();
final int lastLevelExpNeeded=(baseLevel<=1)?0:CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel-1);
final int thisLevelExpNeeded=CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel);
t=(int)Math.round(CMath.mul(thisLevelExpNeeded-lastLevelExpNeeded,
CMath.div(CMath.s_int(amtStr.substring(0,amtStr.length()-1)),100.0)));
}
if(t!=0)
CMLib.leveler().postRPExperience((MOB)newTarget,null,null,t,false);
}
break;
}
case 77: // mpmoney
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
Environmental newTarget=getArgumentMOB(tt[1],source,monster,scripted,primaryItem,secondaryItem,msg,tmp);
if(newTarget==null)
newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String amtStr=tt[2];
amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,amtStr).trim();
final boolean plus=!amtStr.startsWith("-");
if(amtStr.startsWith("+")||amtStr.startsWith("-"))
amtStr=amtStr.substring(1).trim();
final String currency = CMLib.english().parseNumPossibleGoldCurrency(source, amtStr);
final long amt = CMLib.english().parseNumPossibleGold(source, amtStr);
final double denomination = CMLib.english().parseNumPossibleGoldDenomination(source, currency, amtStr);
Container container = null;
if(newTarget instanceof Item)
{
container = (newTarget instanceof Container)?(Container)newTarget:null;
newTarget = ((Item)newTarget).owner();
}
if(newTarget instanceof MOB)
{
if(plus)
CMLib.beanCounter().giveSomeoneMoney((MOB)newTarget, currency, amt * denomination);
else
CMLib.beanCounter().subtractMoney((MOB)newTarget, currency, amt * denomination);
}
else
{
if(!(newTarget instanceof Room))
newTarget=lastKnownLocation;
if(plus)
CMLib.beanCounter().dropMoney((Room)newTarget, container, currency, amt * denomination);
else
CMLib.beanCounter().removeMoney((Room)newTarget, container, currency, amt * denomination);
}
break;
}
case 59: // mpquestpoints
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
if(newTarget instanceof MOB)
{
if(CMath.isNumber(val))
{
final int ival=CMath.s_int(val);
final int aval=ival-((MOB)newTarget).getQuestPoint();
((MOB)newTarget).setQuestPoint(CMath.s_int(val));
if(aval>0)
CMLib.players().bumpPrideStat((MOB)newTarget,PrideStat.QUESTPOINTS_EARNED, aval);
}
else
if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim())))
{
((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()+CMath.s_int(val.substring(2).trim()));
CMLib.players().bumpPrideStat((MOB)newTarget,PrideStat.QUESTPOINTS_EARNED, CMath.s_int(val.substring(2).trim()));
}
else
if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()-CMath.s_int(val.substring(2).trim()));
else
logError(scripted,"QUESTPOINTS","Syntax","Bad syntax "+val+" for "+scripted.Name());
}
break;
}
case 65: // MPQSET
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final String qstr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final PhysicalAgent obj=getArgumentItem(tt[3],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
final Quest Q=getQuest(qstr);
if(Q==null)
logError(scripted,"MPQSET","Syntax","Unknown quest "+qstr+" for "+scripted.Name());
else
if(var.equalsIgnoreCase("QUESTOBJ"))
{
if(obj==null)
logError(scripted,"MPQSET","Syntax","Unknown object "+tt[3]+" for "+scripted.Name());
else
{
obj.basePhyStats().setDisposition(obj.basePhyStats().disposition()|PhyStats.IS_UNSAVABLE);
obj.recoverPhyStats();
Q.runtimeRegisterObject(obj);
}
}
else
if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("ACCEPTED")))
CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTACCEPTED);
else
if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("SUCCESS")||val.equalsIgnoreCase("WON")))
CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTSUCCESS);
else
if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("FAILED")))
CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTFAILED);
else
{
if(val.equals("++"))
val=""+(CMath.s_int(Q.getStat(var))+1);
if(val.equals("--"))
val=""+(CMath.s_int(Q.getStat(var))-1);
Q.setStat(var,val);
}
break;
}
case 66: // MPLOG
{
if(tt==null)
{
tt=parseBits(script,si,"CCcr");
if(tt==null)
return null;
}
final String type=tt[1];
final String head=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if(type.startsWith("E"))
Log.errOut("Script","["+head+"] "+val);
else
if(type.startsWith("I")||type.startsWith("S"))
Log.infoOut("Script","["+head+"] "+val);
else
if(type.startsWith("D"))
Log.debugOut("Script","["+head+"] "+val);
else
logError(scripted,"MPLOG","Syntax","Unknown log type "+type+" for "+scripted.Name());
break;
}
case 67: // MPCHANNEL
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
String channel=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final boolean sysmsg=channel.startsWith("!");
if(sysmsg)
channel=channel.substring(1);
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if(CMLib.channels().getChannelCodeNumber(channel)<0)
logError(scripted,"MPCHANNEL","Syntax","Unknown channel "+channel+" for "+scripted.Name());
else
CMLib.commands().postChannel(monster,channel,val,sysmsg);
break;
}
case 68: // MPUNLOADSCRIPT
{
if(tt==null)
{
tt=parseBits(script,si,"Cc");
if(tt==null)
return null;
}
String scriptname=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
if(!new CMFile(Resources.makeFileResourceName(scriptname),null,CMFile.FLAG_FORCEALLOW).exists())
logError(scripted,"MPUNLOADSCRIPT","Runtime","File does not exist: "+Resources.makeFileResourceName(scriptname));
else
{
final ArrayList<String> delThese=new ArrayList<String>();
scriptname=scriptname.toUpperCase().trim();
final String parmname=scriptname;
for(final Iterator<String> k = Resources.findResourceKeys(parmname);k.hasNext();)
{
final String key=k.next();
if(key.startsWith("PARSEDPRG: ")&&(key.toUpperCase().endsWith(parmname)))
{
delThese.add(key);
}
}
for(int i=0;i<delThese.size();i++)
Resources.removeResource(delThese.get(i));
}
break;
}
case 60: // MPTRAINS
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
if(newTarget instanceof MOB)
{
if(CMath.isNumber(val))
((MOB)newTarget).setTrains(CMath.s_int(val));
else
if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()+CMath.s_int(val.substring(2).trim()));
else
if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()-CMath.s_int(val.substring(2).trim()));
else
logError(scripted,"TRAINS","Syntax","Bad syntax "+val+" for "+scripted.Name());
}
break;
}
case 61: // mppracs
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
if(newTarget instanceof MOB)
{
if(CMath.isNumber(val))
((MOB)newTarget).setPractices(CMath.s_int(val));
else
if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()+CMath.s_int(val.substring(2).trim()));
else
if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()-CMath.s_int(val.substring(2).trim()));
else
logError(scripted,"PRACS","Syntax","Bad syntax "+val+" for "+scripted.Name());
}
break;
}
case 5: // mpmload
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final ArrayList<Environmental> Ms=new ArrayList<Environmental>();
MOB m=CMClass.getMOB(name);
if(m!=null)
Ms.add(m);
if(lastKnownLocation!=null)
{
if(Ms.size()==0)
findSomethingCalledThis(name,monster,lastKnownLocation,Ms,true);
for(int i=0;i<Ms.size();i++)
{
if(Ms.get(i) instanceof MOB)
{
m=(MOB)((MOB)Ms.get(i)).copyOf();
m.text();
m.recoverPhyStats();
m.recoverCharStats();
m.resetToMaxState();
m.bringToLife(lastKnownLocation,true);
lastLoaded=m;
}
}
}
break;
}
case 6: // mpoload
{
//if not mob
Physical addHere;
if(scripted instanceof MOB)
addHere=monster;
else
if(scripted instanceof Item)
addHere=((Item)scripted).owner();
else
if(scripted instanceof Room)
addHere=scripted;
else
addHere=lastKnownLocation;
if(addHere!=null)
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
this.lastLoaded = null;
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final int containerIndex=name.toUpperCase().indexOf(" INTO ");
Container container=null;
if(containerIndex>=0)
{
final ArrayList<Environmental> containers=new ArrayList<Environmental>();
findSomethingCalledThis(name.substring(containerIndex+6).trim(),monster,lastKnownLocation,containers,false);
for(int c=0;c<containers.size();c++)
{
if((containers.get(c) instanceof Container)
&&(((Container)containers.get(c)).capacity()>0))
{
container=(Container)containers.get(c);
name=name.substring(0,containerIndex).trim();
break;
}
}
}
final long coins=CMLib.english().parseNumPossibleGold(null,name);
if(coins>0)
{
final String currency=CMLib.english().parseNumPossibleGoldCurrency(scripted,name);
final double denom=CMLib.english().parseNumPossibleGoldDenomination(scripted,currency,name);
final Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins);
if(addHere instanceof MOB)
((MOB)addHere).addItem(C);
else
if(addHere instanceof Room)
((Room)addHere).addItem(C, Expire.Monster_EQ);
C.putCoinsBack();
}
else
if(lastKnownLocation!=null)
{
final ArrayList<Environmental> Is=new ArrayList<Environmental>();
Item m=CMClass.getItem(name);
if(m!=null)
Is.add(m);
else
findSomethingCalledThis(name,monster,lastKnownLocation,Is,false);
for(int i=0;i<Is.size();i++)
{
if(Is.get(i) instanceof Item)
{
m=(Item)Is.get(i);
if((m!=null)
&&(!(m instanceof ArchonOnly)))
{
m=(Item)m.copyOf();
m.recoverPhyStats();
m.setContainer(container);
if(container instanceof MOB)
((MOB)container.owner()).addItem(m);
else
if(container instanceof Room)
((Room)container.owner()).addItem(m,ItemPossessor.Expire.Player_Drop);
else
if(addHere instanceof MOB)
((MOB)addHere).addItem(m);
else
if(addHere instanceof Room)
((Room)addHere).addItem(m, Expire.Monster_EQ);
lastLoaded=m;
}
}
}
if(addHere instanceof MOB)
{
((MOB)addHere).recoverCharStats();
((MOB)addHere).recoverMaxState();
}
addHere.recoverPhyStats();
lastKnownLocation.recoverRoomStats();
}
}
break;
}
case 41: // mpoloadroom
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
if(lastKnownLocation!=null)
{
final ArrayList<Environmental> Is=new ArrayList<Environmental>();
final int containerIndex=name.toUpperCase().indexOf(" INTO ");
Container container=null;
if(containerIndex>=0)
{
final ArrayList<Environmental> containers=new ArrayList<Environmental>();
findSomethingCalledThis(name.substring(containerIndex+6).trim(),null,lastKnownLocation,containers,false);
for(int c=0;c<containers.size();c++)
{
if((containers.get(c) instanceof Container)
&&(((Container)containers.get(c)).capacity()>0))
{
container=(Container)containers.get(c);
name=name.substring(0,containerIndex).trim();
break;
}
}
}
final long coins=CMLib.english().parseNumPossibleGold(null,name);
if(coins>0)
{
final String currency=CMLib.english().parseNumPossibleGoldCurrency(monster,name);
final double denom=CMLib.english().parseNumPossibleGoldDenomination(monster,currency,name);
final Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins);
Is.add(C);
}
else
{
final Item I=CMClass.getItem(name);
if(I!=null)
Is.add(I);
else
findSomethingCalledThis(name,monster,lastKnownLocation,Is,false);
}
for(int i=0;i<Is.size();i++)
{
if(Is.get(i) instanceof Item)
{
Item I=(Item)Is.get(i);
if((I!=null)
&&(!(I instanceof ArchonOnly)))
{
I=(Item)I.copyOf();
I.recoverPhyStats();
lastKnownLocation.addItem(I,ItemPossessor.Expire.Monster_EQ);
I.setContainer(container);
if(I instanceof Coins)
((Coins)I).putCoinsBack();
if(I instanceof RawMaterial)
((RawMaterial)I).rebundle();
lastLoaded=I;
}
}
}
lastKnownLocation.recoverRoomStats();
}
break;
}
case 84: // mpoloadshop
{
ShopKeeper addHere = CMLib.coffeeShops().getShopKeeper(scripted);
if((addHere == null)&&(scripted instanceof Item))
addHere=CMLib.coffeeShops().getShopKeeper(((Item)scripted).owner());
if((addHere == null)&&(scripted instanceof MOB))
addHere=CMLib.coffeeShops().getShopKeeper(((MOB)scripted).location());
if(addHere == null)
addHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(addHere!=null)
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
if(lastKnownLocation!=null)
{
final ArrayList<Environmental> Is=new ArrayList<Environmental>();
int price=-1;
if((price = name.indexOf(" PRICE="))>=0)
{
final String rest = name.substring(price+7).trim();
name=name.substring(0,price).trim();
if(CMath.isInteger(rest))
price=CMath.s_int(rest);
}
Item I=CMClass.getItem(name);
if(I!=null)
Is.add(I);
else
findSomethingCalledThis(name,monster,lastKnownLocation,Is,false);
for(int i=0;i<Is.size();i++)
{
if(Is.get(i) instanceof Item)
{
I=(Item)Is.get(i);
if((I!=null)
&&(!(I instanceof ArchonOnly)))
{
I=(Item)I.copyOf();
I.recoverPhyStats();
final CoffeeShop shop = addHere.getShop();
if(shop != null)
{
final Environmental E=shop.addStoreInventory(I,1,price);
if(E!=null)
setShopPrice(addHere, E, tmp);
}
I.destroy();
}
}
}
lastKnownLocation.recoverRoomStats();
}
}
break;
}
case 85: // mpmloadshop
{
ShopKeeper addHere = CMLib.coffeeShops().getShopKeeper(scripted);
if((addHere == null)&&(scripted instanceof Item))
addHere=CMLib.coffeeShops().getShopKeeper(((Item)scripted).owner());
if((addHere == null)&&(scripted instanceof MOB))
addHere=CMLib.coffeeShops().getShopKeeper(((MOB)scripted).location());
if(addHere == null)
addHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(addHere!=null)
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
this.lastLoaded = null;
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
int price=-1;
if((price = name.indexOf(" PRICE="))>=0)
{
final String rest = name.substring(price+7).trim();
name=name.substring(0,price).trim();
if(CMath.isInteger(rest))
price=CMath.s_int(rest);
}
final ArrayList<Environmental> Ms=new ArrayList<Environmental>();
MOB m=CMClass.getMOB(name);
if(m!=null)
Ms.add(m);
if(lastKnownLocation!=null)
{
if(Ms.size()==0)
findSomethingCalledThis(name,monster,lastKnownLocation,Ms,true);
for(int i=0;i<Ms.size();i++)
{
if(Ms.get(i) instanceof MOB)
{
m=(MOB)((MOB)Ms.get(i)).copyOf();
m.text();
m.recoverPhyStats();
m.recoverCharStats();
m.resetToMaxState();
final CoffeeShop shop = addHere.getShop();
if(shop != null)
{
final Environmental E=shop.addStoreInventory(m,1,price);
if(E!=null)
setShopPrice(addHere, E, tmp);
}
m.destroy();
}
}
}
}
break;
}
case 42: // mphide
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(newTarget!=null)
{
newTarget.basePhyStats().setDisposition(newTarget.basePhyStats().disposition()|PhyStats.IS_NOT_SEEN);
newTarget.recoverPhyStats();
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 58: // mpreset
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String arg=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
if(arg.equalsIgnoreCase("area"))
{
if(lastKnownLocation!=null)
CMLib.map().resetArea(lastKnownLocation.getArea());
}
else
if(arg.equalsIgnoreCase("room"))
{
if(lastKnownLocation!=null)
CMLib.map().resetRoom(lastKnownLocation, true);
}
else
{
final Room R=CMLib.map().getRoom(arg);
if(R!=null)
CMLib.map().resetRoom(R, true);
else
{
final Area A=CMLib.map().findArea(arg);
if(A!=null)
CMLib.map().resetArea(A);
else
{
final Physical newTarget=getArgumentItem(arg,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(newTarget == null)
logError(scripted,"MPRESET","Syntax","Unknown location or item: "+arg+" for "+scripted.Name());
else
if(newTarget instanceof Item)
{
final Item I=(Item)newTarget;
I.setContainer(null);
if(I.subjectToWearAndTear())
I.setUsesRemaining(100);
I.recoverPhyStats();
}
else
if(newTarget instanceof MOB)
{
final MOB M=(MOB)newTarget;
M.resetToMaxState();
M.recoverMaxState();
M.recoverCharStats();
M.recoverPhyStats();
}
}
}
}
break;
}
case 71: // mprejuv
{
if(tt==null)
{
final String rest=CMParms.getPastBitClean(s,1);
if(rest.equals("item")||rest.equals("items"))
tt=parseBits(script,si,"Ccr");
else
if(rest.equals("mob")||rest.equals("mobs"))
tt=parseBits(script,si,"Ccr");
else
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String next=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
String rest="";
if(tt.length>2)
rest=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
int tickID=-1;
if(rest.equalsIgnoreCase("item")||rest.equalsIgnoreCase("items"))
tickID=Tickable.TICKID_ROOM_ITEM_REJUV;
else
if(rest.equalsIgnoreCase("mob")||rest.equalsIgnoreCase("mobs"))
tickID=Tickable.TICKID_MOB;
if(next.equalsIgnoreCase("area"))
{
if(lastKnownLocation!=null)
for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
CMLib.threads().rejuv(e.nextElement(),tickID);
}
else
if(next.equalsIgnoreCase("room"))
{
if(lastKnownLocation!=null)
CMLib.threads().rejuv(lastKnownLocation,tickID);
}
else
{
final Room R=CMLib.map().getRoom(next);
if(R!=null)
CMLib.threads().rejuv(R,tickID);
else
{
final Area A=CMLib.map().findArea(next);
if(A!=null)
{
for(final Enumeration<Room> e=A.getProperMap();e.hasMoreElements();)
CMLib.threads().rejuv(e.nextElement(),tickID);
}
else
logError(scripted,"MPREJUV","Syntax","Unknown location: "+next+" for "+scripted.Name());
}
}
break;
}
case 56: // mpstop
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final List<MOB> V=new ArrayList<MOB>();
final String who=tt[1];
if(who.equalsIgnoreCase("all"))
{
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
V.add(lastKnownLocation.fetchInhabitant(i));
}
else
{
final Environmental newTarget=getArgumentItem(who,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(newTarget instanceof MOB)
V.add((MOB)newTarget);
}
for(int v=0;v<V.size();v++)
{
final Environmental newTarget=V.get(v);
if(newTarget instanceof MOB)
{
final MOB mob=(MOB)newTarget;
Ability A=null;
for(int a=mob.numEffects()-1;a>=0;a--)
{
A=mob.fetchEffect(a);
if((A!=null)
&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL)
&&(A.canBeUninvoked())
&&(!A.isAutoInvoked()))
A.unInvoke();
}
mob.makePeace(false);
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
}
break;
}
case 43: // mpunhide
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(CMath.bset(newTarget.basePhyStats().disposition(),PhyStats.IS_NOT_SEEN)))
{
newTarget.basePhyStats().setDisposition(newTarget.basePhyStats().disposition()-PhyStats.IS_NOT_SEEN);
newTarget.recoverPhyStats();
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 44: // mpopen
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget instanceof Exit)&&(((Exit)newTarget).hasADoor()))
{
final Exit E=(Exit)newTarget;
E.setDoorsNLocks(E.hasADoor(),true,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
else
if((newTarget instanceof Container)&&(((Container)newTarget).hasADoor()))
{
final Container E=(Container)newTarget;
E.setDoorsNLocks(E.hasADoor(),true,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 45: // mpclose
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget instanceof Exit)
&&(((Exit)newTarget).hasADoor())
&&(((Exit)newTarget).isOpen()))
{
final Exit E=(Exit)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
else
if((newTarget instanceof Container)
&&(((Container)newTarget).hasADoor())
&&(((Container)newTarget).isOpen()))
{
final Container E=(Container)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 46: // mplock
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget instanceof Exit)
&&(((Exit)newTarget).hasALock()))
{
final Exit E=(Exit)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),true,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
else
if((newTarget instanceof Container)
&&(((Container)newTarget).hasALock()))
{
final Container E=(Container)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),true,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 47: // mpunlock
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget instanceof Exit)
&&(((Exit)newTarget).isLocked()))
{
final Exit E=(Exit)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
else
if((newTarget instanceof Container)
&&(((Container)newTarget).isLocked()))
{
final Container E=(Container)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 48: // return
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
tickStatus=Tickable.STATUS_END;
return varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
case 87: // mea
case 7: // mpechoat
{
if(tt==null)
{
tt=parseBits(script,si,"Ccp");
if(tt==null)
return null;
}
final String parm=tt[1];
final Environmental newTarget=getArgumentMOB(parm,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null))
{
if(newTarget==monster)
lastKnownLocation.showSource(monster,null,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
else
lastKnownLocation.show(monster,newTarget,null,CMMsg.MSG_OK_ACTION,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]),CMMsg.NO_EFFECT,null);
}
else
if(parm.equalsIgnoreCase("world"))
{
lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();)
{
final Room R=e.nextElement();
if(R.numInhabitants()>0)
R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
}
}
else
if(parm.equalsIgnoreCase("area")&&(lastKnownLocation!=null))
{
lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
final Room R=e.nextElement();
if(R.numInhabitants()>0)
R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
}
}
else
if(CMLib.map().getRoom(parm)!=null)
CMLib.map().getRoom(parm).show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
else
if(CMLib.map().findArea(parm)!=null)
{
lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
for(final Enumeration<Room> e=CMLib.map().findArea(parm).getMetroMap();e.hasMoreElements();)
{
final Room R=e.nextElement();
if(R.numInhabitants()>0)
R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
}
}
break;
}
case 88: // mer
case 8: // mpechoaround
{
if(tt==null)
{
tt=parseBits(script,si,"Ccp");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null))
{
lastKnownLocation.showOthers((MOB)newTarget,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
}
break;
}
case 9: // mpcast
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final Physical newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
Ability A=null;
if(cast!=null)
A=findAbility(cast);
if((A==null)||(cast==null)||(cast.length()==0))
logError(scripted,"MPCAST","RunTime",cast+" is not a valid ability name.");
else
if((newTarget!=null)||(tt[2].length()==0))
{
A.setProficiency(100);
if((monster != scripted)
&&(monster!=null))
monster.resetToMaxState();
A.invoke(monster,newTarget,false,0);
}
break;
}
case 89: // mpcastext
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final Physical newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String args=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
Ability A=null;
if(cast!=null)
A=findAbility(cast);
if((A==null)||(cast==null)||(cast.length()==0))
logError(scripted,"MPCASTEXT","RunTime",cast+" is not a valid ability name.");
else
if(newTarget!=null)
{
A.setProficiency(100);
final List<String> commands = CMParms.parse(args);
if((monster != scripted)
&&(monster!=null))
monster.resetToMaxState();
A.invoke(monster, commands, newTarget, false, 0);
}
break;
}
case 30: // mpaffect
{
if(tt==null)
{
tt=parseBits(script,si,"Cccp");
if(tt==null)
return null;
}
final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final Physical newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
Ability A=null;
if(cast!=null)
A=findAbility(cast);
if((A==null)||(cast==null)||(cast.length()==0))
logError(scripted,"MPAFFECT","RunTime",cast+" is not a valid ability name.");
else
if(newTarget!=null)
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" was MPAFFECTED by "+A.Name());
A.setMiscText(m2);
if((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PROPERTY)
newTarget.addNonUninvokableEffect(A);
else
{
if((monster != scripted)
&&(monster!=null))
monster.resetToMaxState();
A.invoke(monster,CMParms.parse(m2),newTarget,true,0);
}
}
break;
}
case 80: // mpspeak
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final String language=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final Ability A=getAbility(language);
if((A instanceof Language)&&(newTarget instanceof MOB))
{
((Language)A).setProficiency(100);
((Language)A).autoInvocation((MOB)newTarget, false);
final Ability langA=((MOB)newTarget).fetchEffect(A.ID());
if(langA!=null)
{
if(((MOB)newTarget).isMonster())
langA.setProficiency(100);
langA.invoke((MOB)newTarget,CMParms.parse(""),(MOB)newTarget,false,0);
}
else
A.invoke((MOB)newTarget,CMParms.parse(""),(MOB)newTarget,false,0);
}
break;
}
case 81: // mpsetclan
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final PhysicalAgent newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String clan=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String roleStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
Clan C=CMLib.clans().getClan(clan);
if(C==null)
C=CMLib.clans().findClan(clan);
if((newTarget instanceof MOB)&&(C!=null))
{
int role=Integer.MIN_VALUE;
if(CMath.isInteger(roleStr))
role=CMath.s_int(roleStr);
else
for(int i=0;i<C.getRolesList().length;i++)
{
if(roleStr.equalsIgnoreCase(C.getRolesList()[i]))
role=i;
}
if(role!=Integer.MIN_VALUE)
{
if(((MOB)newTarget).isPlayer())
C.addMember((MOB)newTarget, role);
else
((MOB)newTarget).setClan(C.clanID(), role);
}
}
break;
}
case 31: // mpbehave
{
if(tt==null)
{
tt=parseBits(script,si,"Cccp");
if(tt==null)
return null;
}
String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final PhysicalAgent newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
Behavior B=null;
final Behavior B2=(cast==null)?null:CMClass.findBehavior(cast);
if(B2!=null)
cast=B2.ID();
if((cast!=null)&&(newTarget!=null))
{
B=newTarget.fetchBehavior(cast);
if(B==null)
B=CMClass.getBehavior(cast);
}
if((newTarget!=null)&&(B!=null))
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" was MPBEHAVED with "+B.name());
B.setParms(m2);
if(newTarget.fetchBehavior(B.ID())==null)
{
newTarget.addBehavior(B);
if((defaultQuestName()!=null)&&(defaultQuestName().length()>0))
B.registerDefaultQuest(defaultQuestName());
}
}
break;
}
case 72: // mpscript
{
if(tt==null)
{
tt=parseBits(script,si,"Ccp");
if(tt==null)
return null;
}
final PhysicalAgent newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
boolean proceed=true;
boolean savable=false;
boolean execute=false;
String scope=getVarScope();
while(proceed)
{
proceed=false;
if(m2.toUpperCase().startsWith("SAVABLE "))
{
savable=true;
m2=m2.substring(8).trim();
proceed=true;
}
else
if(m2.toUpperCase().startsWith("EXECUTE "))
{
execute=true;
m2=m2.substring(8).trim();
proceed=true;
}
else
if(m2.toUpperCase().startsWith("GLOBAL "))
{
scope="";
proceed=true;
m2=m2.substring(6).trim();
}
else
if(m2.toUpperCase().startsWith("INDIVIDUAL ")||m2.equals("*"))
{
scope="*";
proceed=true;
m2=m2.substring(10).trim();
}
}
if((newTarget!=null)&&(m2.length()>0))
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" was MPSCRIPTED: "+defaultQuestName);
final ScriptingEngine S=(ScriptingEngine)CMClass.getCommon("DefaultScriptingEngine");
S.setSavable(savable);
S.setVarScope(scope);
S.setScript(m2);
if((defaultQuestName()!=null)&&(defaultQuestName().length()>0))
S.registerDefaultQuest(defaultQuestName());
newTarget.addScript(S);
if(execute)
{
S.tick(newTarget,Tickable.TICKID_MOB);
for(int i=0;i<5;i++)
S.dequeResponses();
newTarget.delScript(S);
}
}
break;
}
case 32: // mpunbehave
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final PhysicalAgent newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(cast!=null))
{
Behavior B=CMClass.findBehavior(cast);
if(B!=null)
cast=B.ID();
B=newTarget.fetchBehavior(cast);
if(B!=null)
newTarget.delBehavior(B);
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())&&(B!=null))
Log.sysOut("Scripting",newTarget.Name()+" was MPUNBEHAVED with "+B.name());
}
break;
}
case 33: // mptattoo
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String tattooName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if((newTarget!=null)&&(tattooName.length()>0)&&(newTarget instanceof MOB))
{
final MOB themob=(MOB)newTarget;
final boolean tattooMinus=tattooName.startsWith("-");
if(tattooMinus)
tattooName=tattooName.substring(1);
final Tattoo pT=((Tattoo)CMClass.getCommon("DefaultTattoo")).parse(tattooName);
final Tattoo T=themob.findTattoo(pT.getTattooName());
if(T!=null)
{
if(tattooMinus)
themob.delTattoo(T);
}
else
if(!tattooMinus)
themob.addTattoo(pT);
}
break;
}
case 83: // mpacctattoo
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String tattooName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if((newTarget!=null)
&&(tattooName.length()>0)
&&(newTarget instanceof MOB)
&&(((MOB)newTarget).playerStats()!=null)
&&(((MOB)newTarget).playerStats().getAccount()!=null))
{
final Tattooable themob=((MOB)newTarget).playerStats().getAccount();
final boolean tattooMinus=tattooName.startsWith("-");
if(tattooMinus)
tattooName=tattooName.substring(1);
final Tattoo pT=((Tattoo)CMClass.getCommon("DefaultTattoo")).parse(tattooName);
final Tattoo T=themob.findTattoo(pT.getTattooName());
if(T!=null)
{
if(tattooMinus)
themob.delTattoo(T);
}
else
if(!tattooMinus)
themob.addTattoo(pT);
}
break;
}
case 92: // mpput
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(newTarget!=null)
{
if(tt[2].equalsIgnoreCase("NULL")||tt[2].equalsIgnoreCase("NONE"))
{
if(newTarget instanceof Item)
((Item)newTarget).setContainer(null);
if(newTarget instanceof Rider)
((Rider)newTarget).setRiding(null);
}
else
{
final Physical newContainer=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(newContainer!=null)
{
if((newTarget instanceof Item)
&&(newContainer instanceof Container))
((Item)newTarget).setContainer((Container)newContainer);
if((newTarget instanceof Rider)
&&(newContainer instanceof Rideable))
((Rider)newTarget).setRiding((Rideable)newContainer);
}
}
newTarget.recoverPhyStats();
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 55: // mpnotrigger
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final String trigger=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
int triggerCode=-1;
for(int i=0;i<progs.length;i++)
{
if(trigger.equalsIgnoreCase(progs[i]))
triggerCode=i+1;
}
if(triggerCode<=0)
logError(scripted,"MPNOTRIGGER","RunTime",trigger+" is not a valid trigger name.");
else
if(!CMath.isInteger(time.trim()))
logError(scripted,"MPNOTRIGGER","RunTime",time+" is not a valid milisecond time.");
else
{
noTrigger.remove(Integer.valueOf(triggerCode));
noTrigger.put(Integer.valueOf(triggerCode),Long.valueOf(System.currentTimeMillis()+CMath.s_long(time.trim())));
}
break;
}
case 54: // mpfaction
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String faction=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String range=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]).trim();
final Faction F=CMLib.factions().getFaction(faction);
if((newTarget!=null)&&(F!=null)&&(newTarget instanceof MOB))
{
final MOB themob=(MOB)newTarget;
int curFaction = themob.fetchFaction(F.factionID());
if((curFaction == Integer.MAX_VALUE)||(curFaction == Integer.MIN_VALUE))
curFaction = F.findDefault(themob);
if((range.startsWith("--"))&&(CMath.isInteger(range.substring(2).trim())))
{
final int amt=CMath.s_int(range.substring(2).trim());
if(amt < 0)
themob.tell(L("You gain @x1 faction with @x2.",""+(-amt),F.name()));
else
themob.tell(L("You lose @x1 faction with @x2.",""+amt,F.name()));
range=""+(curFaction-amt);
}
else
if((range.startsWith("+"))&&(CMath.isInteger(range.substring(1).trim())))
{
final int amt=CMath.s_int(range.substring(1).trim());
if(amt < 0)
themob.tell(L("You lose @x1 faction with @x2.",""+(-amt),F.name()));
else
themob.tell(L("You gain @x1 faction with @x2.",""+amt,F.name()));
range=""+(curFaction+amt);
}
else
if(CMath.isInteger(range))
themob.tell(L("Your faction with @x1 is now @x2.",F.name(),""+CMath.s_int(range.trim())));
if(CMath.isInteger(range))
themob.addFaction(F.factionID(),CMath.s_int(range.trim()));
else
{
Faction.FRange FR=null;
final Enumeration<Faction.FRange> e=CMLib.factions().getRanges(CMLib.factions().getAlignmentID());
if(e!=null)
for(;e.hasMoreElements();)
{
final Faction.FRange FR2=e.nextElement();
if(FR2.name().equalsIgnoreCase(range))
{
FR = FR2;
break;
}
}
if(FR==null)
logError(scripted,"MPFACTION","RunTime",range+" is not a valid range for "+F.name()+".");
else
{
themob.tell(L("Your faction with @x1 is now @x2.",F.name(),FR.name()));
themob.addFaction(F.factionID(),FR.low()+((FR.high()-FR.low())/2));
}
}
}
break;
}
case 49: // mptitle
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String titleStr=varify(monster, newTarget, scripted, monster, secondaryItem, secondaryItem, msg, tmp, tt[2]);
if((newTarget!=null)&&(titleStr.length()>0)&&(newTarget instanceof MOB))
{
final MOB themob=(MOB)newTarget;
final boolean tattooMinus=titleStr.startsWith("-");
if(tattooMinus)
titleStr=titleStr.substring(1);
if(themob.playerStats()!=null)
{
if(themob.playerStats().getTitles().contains(titleStr))
{
if(tattooMinus)
themob.playerStats().getTitles().remove(titleStr);
}
else
if(!tattooMinus)
themob.playerStats().getTitles().add(0,titleStr);
}
}
break;
}
case 10: // mpkill
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)
&&(newTarget instanceof MOB)
&&(monster!=null))
monster.setVictim((MOB)newTarget);
break;
}
case 51: // mpsetclandata
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String clanID=null;
if((newTarget!=null)&&(newTarget instanceof MOB))
{
Clan C=CMLib.clans().findRivalrousClan((MOB)newTarget);
if(C==null)
C=((MOB)newTarget).clans().iterator().hasNext()?((MOB)newTarget).clans().iterator().next().first:null;
if(C!=null)
clanID=C.clanID();
}
else
clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final String clanvar=tt[2];
final String clanval=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
final Clan C=CMLib.clans().getClan(clanID);
if(C!=null)
{
if(!C.isStat(clanvar))
logError(scripted,"MPSETCLANDATA","RunTime",clanvar+" is not a valid clan variable.");
else
{
C.setStat(clanvar,clanval.trim());
if(C.getStat(clanvar).equalsIgnoreCase(clanval))
C.update();
}
}
break;
}
case 52: // mpplayerclass
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB))
{
final List<String> V=CMParms.parse(tt[2]);
for(int i=0;i<V.size();i++)
{
if(CMath.isInteger(V.get(i).trim()))
((MOB)newTarget).baseCharStats().setClassLevel(((MOB)newTarget).baseCharStats().getCurrentClass(),CMath.s_int(V.get(i).trim()));
else
{
final CharClass C=CMClass.findCharClass(V.get(i));
if((C!=null)&&(C.availabilityCode()!=0))
((MOB)newTarget).baseCharStats().setCurrentClass(C);
}
}
((MOB)newTarget).recoverCharStats();
}
break;
}
case 12: // mppurge
{
if(lastKnownLocation!=null)
{
int flag=0;
if(tt==null)
{
final String s2=CMParms.getCleanBit(s,1).toLowerCase();
if(s2.equals("room"))
tt=parseBits(script,si,"Ccr");
else
if(s2.equals("my"))
tt=parseBits(script,si,"Ccr");
else
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
String s2=tt[1];
if(s2.equalsIgnoreCase("room"))
{
flag=1;
s2=tt[2];
}
else
if(s2.equalsIgnoreCase("my"))
{
flag=2;
s2=tt[2];
}
Environmental E=null;
if(s2.equalsIgnoreCase("self")||s2.equalsIgnoreCase("me"))
E=scripted;
else
if(flag==1)
{
s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s2);
E=lastKnownLocation.fetchFromRoomFavorItems(null,s2);
}
else
if(flag==2)
{
s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s2);
if(monster!=null)
E=monster.findItem(s2);
}
else
E=getArgumentItem(s2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
if(E instanceof MOB)
{
if(!((MOB)E).isMonster())
{
if(((MOB)E).getStartRoom()!=null)
((MOB)E).getStartRoom().bringMobHere((MOB)E,false);
((MOB)E).session().stopSession(false,false,false);
}
else
if(((MOB)E).getStartRoom()!=null)
((MOB)E).killMeDead(false);
else
((MOB)E).destroy();
}
else
if(E instanceof Item)
{
final ItemPossessor oE=((Item)E).owner();
((Item)E).destroy();
if(oE!=null)
oE.recoverPhyStats();
}
}
lastKnownLocation.recoverRoomStats();
}
break;
}
case 14: // mpgoto
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String roomID=tt[1].trim();
if((roomID.length()>0)&&(lastKnownLocation!=null))
{
Room goHere=null;
if(roomID.startsWith("$"))
goHere=CMLib.map().roomLocation(this.getArgumentItem(roomID,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(goHere==null)
goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomID),lastKnownLocation);
if(goHere!=null)
{
if(scripted instanceof MOB)
goHere.bringMobHere((MOB)scripted,true);
else
if(scripted instanceof Item)
goHere.moveItemTo((Item)scripted,ItemPossessor.Expire.Player_Drop,ItemPossessor.Move.Followers);
else
{
goHere.bringMobHere(monster,true);
if(!(scripted instanceof MOB))
goHere.delInhabitant(monster);
}
if(CMLib.map().roomLocation(scripted)==goHere)
lastKnownLocation=goHere;
}
}
break;
}
case 15: // mpat
if(lastKnownLocation!=null)
{
if(tt==null)
{
tt=parseBits(script,si,"Ccp");
if(tt==null)
return null;
}
final Room lastPlace=lastKnownLocation;
final String roomName=tt[1];
if(roomName.length()>0)
{
final String doWhat=tt[2].trim();
Room goHere=null;
if(roomName.startsWith("$"))
goHere=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(goHere==null)
goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation);
if(goHere!=null)
{
goHere.bringMobHere(monster,true);
final DVector subScript=new DVector(3);
subScript.addElement("",null,null);
subScript.addElement(doWhat,null,null);
lastKnownLocation=goHere;
execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp);
lastKnownLocation=lastPlace;
lastPlace.bringMobHere(monster,true);
if(!(scripted instanceof MOB))
{
goHere.delInhabitant(monster);
lastPlace.delInhabitant(monster);
}
}
}
}
break;
case 17: // mptransfer
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
String mobName=tt[1];
String roomName=tt[2].trim();
Room newRoom=null;
if(roomName.startsWith("$"))
newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if((roomName.length()==0)&&(lastKnownLocation!=null))
roomName=lastKnownLocation.roomID();
if(roomName.length()>0)
{
if(newRoom==null)
newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation);
if(newRoom!=null)
{
final ArrayList<Environmental> V=new ArrayList<Environmental>();
if(mobName.startsWith("$"))
{
final Environmental E=getArgumentItem(mobName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
V.add(E);
}
if(V.size()==0)
{
mobName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,mobName);
if(mobName.equalsIgnoreCase("all"))
{
if(lastKnownLocation!=null)
{
for(int x=0;x<lastKnownLocation.numInhabitants();x++)
{
final MOB m=lastKnownLocation.fetchInhabitant(x);
if((m!=null)&&(m!=monster)&&(!V.contains(m)))
V.add(m);
}
}
}
else
{
MOB findOne=null;
Area A=null;
if(findOne==null)
{
if(lastKnownLocation!=null)
{
findOne=lastKnownLocation.fetchInhabitant(mobName);
A=lastKnownLocation.getArea();
if((findOne!=null)&&(findOne!=monster))
V.add(findOne);
}
}
if(findOne==null)
{
findOne=CMLib.players().getPlayerAllHosts(mobName);
if((findOne!=null)&&(!CMLib.flags().isInTheGame(findOne,true)))
findOne=null;
if((findOne!=null)&&(findOne!=monster))
V.add(findOne);
}
if((findOne==null)&&(A!=null))
{
for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
findOne=R.fetchInhabitant(mobName);
if((findOne!=null)&&(findOne!=monster))
V.add(findOne);
}
}
}
}
for(int v=0;v<V.size();v++)
{
if(V.get(v) instanceof MOB)
{
final MOB mob=(MOB)V.get(v);
final Set<MOB> H=mob.getGroupMembers(new HashSet<MOB>());
for (final Object element : H)
{
final MOB M=(MOB)element;
if((!V.contains(M))&&(M.location()==mob.location()))
V.add(M);
}
}
}
for(int v=0;v<V.size();v++)
{
if(V.get(v) instanceof MOB)
{
final MOB follower=(MOB)V.get(v);
final Room thisRoom=follower.location();
final int dispmask=(PhyStats.IS_SLEEPING | PhyStats.IS_SITTING);
final int dispo1 = follower.basePhyStats().disposition() & dispmask;
final int dispo2 = follower.phyStats().disposition() & dispmask;
follower.basePhyStats().setDisposition(follower.basePhyStats().disposition() & (~dispmask));
follower.phyStats().setDisposition(follower.phyStats().disposition() & (~dispmask));
// scripting guide calls for NO text -- empty is probably req tho
final CMMsg enterMsg=CMClass.getMsg(follower,newRoom,null,CMMsg.MSG_ENTER|CMMsg.MASK_ALWAYS,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER," "+CMLib.protocol().msp("appear.wav",10));
final CMMsg leaveMsg=CMClass.getMsg(follower,thisRoom,null,CMMsg.MSG_LEAVE|CMMsg.MASK_ALWAYS," ");
if((thisRoom!=null)
&&thisRoom.okMessage(follower,leaveMsg)
&&newRoom.okMessage(follower,enterMsg))
{
final boolean alreadyHere = follower.location()==(Room)enterMsg.target();
if(follower.isInCombat())
{
CMLib.commands().postFlee(follower,("NOWHERE"));
follower.makePeace(true);
}
thisRoom.send(follower,leaveMsg);
if(!alreadyHere)
((Room)enterMsg.target()).bringMobHere(follower,false);
((Room)enterMsg.target()).send(follower,enterMsg);
follower.basePhyStats().setDisposition(follower.basePhyStats().disposition() | dispo1);
follower.phyStats().setDisposition(follower.phyStats().disposition() | dispo2);
if(!CMLib.flags().isSleeping(follower)
&&(!alreadyHere))
{
follower.tell(CMLib.lang().L("\n\r\n\r"));
CMLib.commands().postLook(follower,true);
}
}
else
{
follower.basePhyStats().setDisposition(follower.basePhyStats().disposition() | dispo1);
follower.phyStats().setDisposition(follower.phyStats().disposition() | dispo2);
}
}
else
if((V.get(v) instanceof Item)
&&(newRoom!=CMLib.map().roomLocation(V.get(v))))
newRoom.moveItemTo((Item)V.get(v),ItemPossessor.Expire.Player_Drop,ItemPossessor.Move.Followers);
if((V.get(v)==scripted)
&&(scripted instanceof Physical)
&&(newRoom.isHere(scripted)))
lastKnownLocation=newRoom;
}
}
}
break;
}
case 25: // mpbeacon
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final String roomName=tt[1];
Room newRoom=null;
if((roomName.length()>0)&&(lastKnownLocation!=null))
{
final String beacon=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if(roomName.startsWith("$"))
newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(newRoom==null)
newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation);
if(newRoom == null)
logError(scripted,"MPBEACON","RunTime",tt[1]+" is not a room.");
else
if(lastKnownLocation!=null)
{
final List<MOB> V=new ArrayList<MOB>();
if(beacon.equalsIgnoreCase("all"))
{
for(int x=0;x<lastKnownLocation.numInhabitants();x++)
{
final MOB m=lastKnownLocation.fetchInhabitant(x);
if((m!=null)&&(m!=monster)&&(!m.isMonster())&&(!V.contains(m)))
V.add(m);
}
}
else
{
final MOB findOne=lastKnownLocation.fetchInhabitant(beacon);
if((findOne!=null)&&(findOne!=monster)&&(!findOne.isMonster()))
V.add(findOne);
}
for(int v=0;v<V.size();v++)
{
final MOB follower=V.get(v);
if(!follower.isMonster())
follower.setStartRoom(newRoom);
}
}
}
break;
}
case 18: // mpforce
{
if(tt==null)
{
tt=parseBits(script,si,"Ccp");
if(tt==null)
return null;
}
final PhysicalAgent newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String force=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
if(newTarget!=null)
{
final DVector vscript=new DVector(3);
vscript.addElement("FUNCTION_PROG MPFORCE_"+System.currentTimeMillis()+Math.random(),null,null);
vscript.addElement(force,null,null);
// this can not be permanently parsed because it is variable
execute(newTarget, source, target, getMakeMOB(newTarget), primaryItem, secondaryItem, vscript, msg, tmp);
}
break;
}
case 79: // mppossess
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final PhysicalAgent newSource=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final PhysicalAgent newTarget=getArgumentMOB(tt[2],source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((!(newSource instanceof MOB))||(((MOB)newSource).isMonster()))
logError(scripted,"MPPOSSESS","RunTime",tt[1]+" is not a player.");
else
if((!(newTarget instanceof MOB))||(!((MOB)newTarget).isMonster())||CMSecurity.isASysOp((MOB)newTarget))
logError(scripted,"MPPOSSESS","RunTime",tt[2]+" is not a mob.");
else
{
final MOB mobM=(MOB)newSource;
final MOB targetM=(MOB)newTarget;
final Session S=mobM.session();
S.setMob(targetM);
targetM.setSession(S);
targetM.setSoulMate(mobM);
mobM.setSession(null);
}
break;
}
case 20: // mpsetvar
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
String which=tt[1];
final Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if(!which.equals("*"))
{
if(E==null)
which=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,which);
else
if(E instanceof Room)
which=CMLib.map().getExtendedRoomID((Room)E);
else
which=E.Name();
}
if((which.length()>0)&&(arg2.length()>0))
{
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS))
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+which+"("+arg2+")="+arg3+"<");
setVar(which,arg2,arg3);
}
break;
}
case 36: // mpsavevar
{
if(tt==null)
{
tt=parseBits(script,si,"CcR");
if(tt==null)
return null;
}
String which=tt[1];
String arg2=tt[2];
final Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
if((which.length()>0)&&(arg2.length()>0))
{
final PairList<String,String> vars=getScriptVarSet(which,arg2);
for(int v=0;v<vars.size();v++)
{
which=vars.elementAtFirst(v);
arg2=vars.elementAtSecond(v).toUpperCase();
@SuppressWarnings("unchecked")
final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+which);
String val="";
if(H!=null)
{
val=H.get(arg2);
if(val==null)
val="";
}
if(val.length()>0)
CMLib.database().DBReCreatePlayerData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2,val);
else
CMLib.database().DBDeletePlayerData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2);
}
}
break;
}
case 39: // mploadvar
{
if(tt==null)
{
tt=parseBits(script,si,"CcR");
if(tt==null)
return null;
}
String which=tt[1];
final String arg2=tt[2];
final Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()>0)
{
List<PlayerData> V=null;
which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
if(arg2.equals("*"))
V=CMLib.database().DBReadPlayerData(which,"SCRIPTABLEVARS");
else
V=CMLib.database().DBReadPlayerData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2);
if((V!=null)&&(V.size()>0))
for(int v=0;v<V.size();v++)
{
final DatabaseEngine.PlayerData VAR=V.get(v);
String varName=VAR.key();
if(varName.startsWith(which.toUpperCase()+"_SCRIPTABLEVARS_"))
varName=varName.substring((which+"_SCRIPTABLEVARS_").length());
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS))
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+which+"("+varName+")="+VAR.xml()+"<");
setVar(which,varName,VAR.xml());
}
}
break;
}
case 40: // MPM2I2M
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final String arg1=tt[1];
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
{
final String arg2=tt[2];
final String arg3=tt[3];
final CagedAnimal caged=(CagedAnimal)CMClass.getItem("GenCaged");
if(caged!=null)
{
((Item)caged).basePhyStats().setAbility(1);
((Item)caged).recoverPhyStats();
}
if((caged!=null)&&caged.cageMe((MOB)E)&&(lastKnownLocation!=null))
{
if(arg2.length()>0)
((Item)caged).setName(arg2);
if(arg3.length()>0)
((Item)caged).setDisplayText(arg3);
lastKnownLocation.addItem(caged,ItemPossessor.Expire.Player_Drop);
((MOB)E).killMeDead(false);
}
}
else
if(E instanceof CagedAnimal)
{
final MOB M=((CagedAnimal)E).unCageMe();
if((M!=null)&&(lastKnownLocation!=null))
{
M.bringToLife(lastKnownLocation,true);
((Item)E).destroy();
}
}
else
logError(scripted,"MPM2I2M","RunTime",arg1+" is not a mob or a caged item.");
break;
}
case 28: // mpdamage
{
if(tt==null)
{
tt=parseBits(script,si,"Ccccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]).toUpperCase();
if((newTarget!=null)&&(arg2.length()>0))
{
if(newTarget instanceof MOB)
{
final MOB deadM=(MOB)newTarget;
MOB killerM=(MOB)newTarget;
boolean me=false;
boolean kill=false;
int damageType = CMMsg.TYP_CAST_SPELL;
for(final String s4 : arg4.split(" "))
{
if(arg4.length()==0)
continue;
if(arg4.equals("MEKILL"))
{
me=true;
kill=true;
}
else
if(arg4.equals("ME"))
me=true;
else
if(arg4.equals("KILL"))
kill=true;
else
{
for(int i4=0;i4<CharStats.DEFAULT_STAT_MSG_MAP.length;i4++)
{
final int code4=CharStats.DEFAULT_STAT_MSG_MAP[i4];
if((code4>0)&&(CMMsg.TYPE_DESCS[code4&CMMsg.MINOR_MASK].equals(s4)))
{
damageType=code4;
break;
}
}
}
}
if(me)
killerM=monster;
final int min=CMath.s_int(arg2.trim());
int max=CMath.s_int(arg3.trim());
if(max<min)
max=min;
if(min>0)
{
int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min);
if((dmg>=deadM.curState().getHitPoints())
&&(!kill))
dmg=deadM.curState().getHitPoints()-1;
if(dmg>0)
CMLib.combat().postDamage(killerM,deadM,null,dmg,CMMsg.MASK_ALWAYS|damageType,-1,null);
}
}
else
if(newTarget instanceof Item)
{
final Item E=(Item)newTarget;
final int min=CMath.s_int(arg2.trim());
int max=CMath.s_int(arg3.trim());
if(max<min)
max=min;
if(min>0)
{
int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min);
boolean destroy=false;
if(E.subjectToWearAndTear())
{
if((dmg>=E.usesRemaining())&&(!arg4.equalsIgnoreCase("kill")))
dmg=E.usesRemaining()-1;
if(dmg>0)
E.setUsesRemaining(E.usesRemaining()-dmg);
if(E.usesRemaining()<=0)
destroy=true;
}
else
if(arg4.equalsIgnoreCase("kill"))
destroy=true;
if(destroy)
{
if(lastKnownLocation!=null)
lastKnownLocation.showHappens(CMMsg.MSG_OK_VISUAL,L("@x1 is destroyed!",E.name()));
E.destroy();
}
}
}
}
break;
}
case 78: // mpheal
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if((newTarget!=null)&&(arg2.length()>0))
{
if(newTarget instanceof MOB)
{
final MOB healedM=(MOB)newTarget;
final MOB healerM=(MOB)newTarget;
final int min=CMath.s_int(arg2.trim());
int max=CMath.s_int(arg3.trim());
if(max<min)
max=min;
if(min>0)
{
final int amt=(max==min)?min:CMLib.dice().roll(1,max-min,min);
if(amt>0)
CMLib.combat().postHealing(healerM,healedM,null,amt,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,null);
}
}
else
if(newTarget instanceof Item)
{
final Item E=(Item)newTarget;
final int min=CMath.s_int(arg2.trim());
int max=CMath.s_int(arg3.trim());
if(max<min)
max=min;
if(min>0)
{
final int amt=(max==min)?min:CMLib.dice().roll(1,max-min,min);
if(E.subjectToWearAndTear())
{
E.setUsesRemaining(E.usesRemaining()+amt);
if(E.usesRemaining()>100)
E.setUsesRemaining(100);
}
}
}
}
break;
}
case 90: // mplink
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final String dirWord=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final int dir=CMLib.directions().getGoodDirectionCode(dirWord);
if(dir < 0)
logError(scripted,"MPLINK","RunTime",dirWord+" is not a valid direction.");
else
{
final String roomID = varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final Room startR=(homeKnownLocation!=null)?homeKnownLocation:CMLib.map().getStartRoom(scripted);
final Room R=this.getRoom(roomID, lastKnownLocation);
if((R==null)||(lastKnownLocation==null)||(R.getArea()!=lastKnownLocation.getArea()))
logError(scripted,"MPLINK","RunTime",roomID+" is not a target room.");
else
if((startR!=null)&&(startR.getArea()!=lastKnownLocation.getArea()))
logError(scripted,"MPLINK","RunTime","mplink from "+roomID+" is an illegal source room.");
else
{
String exitID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
String nameArg=null;
final int x=exitID.indexOf(' ');
if(x>0)
{
nameArg=exitID.substring(x+1).trim();
exitID=exitID.substring(0,x);
}
final Exit E=CMClass.getExit(exitID);
if(E==null)
logError(scripted,"MPLINK","RunTime",exitID+" is not a exit class.");
else
if((lastKnownLocation.rawDoors()[dir]==null)
&&(lastKnownLocation.getRawExit(dir)==null))
{
lastKnownLocation.rawDoors()[dir]=R;
lastKnownLocation.setRawExit(dir, E);
E.basePhyStats().setSensesMask(E.basePhyStats().sensesMask()|PhyStats.SENSE_ITEMNOWISH);
E.setSavable(false);
E.recoverPhyStats();
if(nameArg!=null)
E.setName(nameArg);
}
}
}
break;
}
case 91: // mpunlink
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String dirWord=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final int dir=CMLib.directions().getGoodDirectionCode(dirWord);
if(dir < 0)
logError(scripted,"MPLINK","RunTime",dirWord+" is not a valid direction.");
else
if((lastKnownLocation==null)
||((lastKnownLocation.rawDoors()[dir]!=null)&&(lastKnownLocation.rawDoors()[dir].getArea()!=lastKnownLocation.getArea())))
logError(scripted,"MPLINK","RunTime",dirWord+" is a non-in-area direction.");
else
if((lastKnownLocation.getRawExit(dir)!=null)
&&(lastKnownLocation.getRawExit(dir).isSavable()
||(!CMath.bset(lastKnownLocation.getRawExit(dir).basePhyStats().sensesMask(), PhyStats.SENSE_ITEMNOWISH))))
logError(scripted,"MPLINK","RunTime",dirWord+" is not a legal unlinkable exit.");
else
{
lastKnownLocation.setRawExit(dir, null);
lastKnownLocation.rawDoors()[dir]=null;
}
break;
}
case 29: // mptrackto
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final Ability A=CMClass.getAbility("Skill_Track");
if(A!=null)
{
if((monster != scripted)
&&(monster!=null))
monster.resetToMaxState();
if(A.text().length()>0 && A.text().equalsIgnoreCase(arg1))
{
// already on the move
}
else
{
altStatusTickable=A;
A.invoke(monster,CMParms.parse(arg1),null,true,0);
altStatusTickable=null;
}
}
break;
}
case 53: // mpwalkto
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final Ability A=CMClass.getAbility("Skill_Track");
if(A!=null)
{
altStatusTickable=A;
if((monster != scripted)
&&(monster!=null))
monster.resetToMaxState();
A.invoke(monster,CMParms.parse(arg1+" LANDONLY"),null,true,0);
altStatusTickable=null;
}
break;
}
case 21: //MPENDQUEST
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final PhysicalAgent newTarget;
final String q=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim());
final Quest Q=getQuest(q);
if(Q!=null)
{
final CMMsg stopMsg=CMClass.getMsg(monster,null,null,CMMsg.NO_EFFECT,null,CMMsg.TYP_ENDQUEST,Q.name(),CMMsg.NO_EFFECT,null);
CMLib.map().sendGlobalMessage(monster, CMMsg.TYP_ENDQUEST, stopMsg);
Q.stopQuest();
CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTSTOP);
}
else
if((tt[1].length()>0)
&&(defaultQuestName!=null)
&&(defaultQuestName.length()>0)
&&((newTarget=getArgumentMOB(tt[1].trim(),source,monster,target,primaryItem,secondaryItem,msg,tmp))!=null))
{
for(int i=newTarget.numScripts()-1;i>=0;i--)
{
final ScriptingEngine S=newTarget.fetchScript(i);
if((S!=null)
&&(S.defaultQuestName()!=null)
&&(S.defaultQuestName().equalsIgnoreCase(defaultQuestName)))
{
newTarget.delScript(S);
S.endQuest(newTarget, (newTarget instanceof MOB)?((MOB)newTarget):monster, defaultQuestName);
}
}
}
else
if(q.length()>0)
{
boolean foundOne=false;
for(int i=scripted.numScripts()-1;i>=0;i--)
{
final ScriptingEngine S=scripted.fetchScript(i);
if((S!=null)
&&(S.defaultQuestName()!=null)
&&(S.defaultQuestName().equalsIgnoreCase(q)))
{
foundOne=true;
S.endQuest(scripted, monster, S.defaultQuestName());
scripted.delScript(S);
}
}
if((!foundOne)
&&((defaultQuestName==null)||(!defaultQuestName.equalsIgnoreCase(q))))
logError(scripted,"MPENDQUEST","Unknown","Quest: "+s);
}
break;
}
case 69: // MPSTEPQUEST
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String qName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim());
final Quest Q=getQuest(qName);
if(Q!=null)
Q.stepQuest();
else
logError(scripted,"MPSTEPQUEST","Unknown","Quest: "+s);
break;
}
case 23: //MPSTARTQUEST
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String qName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim());
final Quest Q=getQuest(qName);
if(Q!=null)
Q.startQuest();
else
logError(scripted,"MPSTARTQUEST","Unknown","Quest: "+s);
break;
}
case 64: //MPLOADQUESTOBJ
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final String questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim());
final Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"MPLOADQUESTOBJ","Unknown","Quest: "+questName);
break;
}
final Object O=Q.getDesignatedObject(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
if(O==null)
{
logError(scripted,"MPLOADQUESTOBJ","Unknown","Unknown var "+tt[2]+" for Quest: "+questName);
break;
}
final String varArg=tt[3];
if((varArg.length()!=2)||(!varArg.startsWith("$")))
{
logError(scripted,"MPLOADQUESTOBJ","Syntax","Invalid argument var: "+varArg+" for "+scripted.Name());
break;
}
final char c=varArg.charAt(1);
if(Character.isDigit(c))
tmp[CMath.s_int(Character.toString(c))]=O;
else
switch(c)
{
case 'N':
case 'n':
if (O instanceof MOB)
source = (MOB) O;
break;
case 'I':
case 'i':
if (O instanceof PhysicalAgent)
scripted = (PhysicalAgent) O;
if (O instanceof MOB)
monster = (MOB) O;
break;
case 'B':
case 'b':
if (O instanceof Environmental)
lastLoaded = (Environmental) O;
break;
case 'T':
case 't':
if (O instanceof Environmental)
target = (Environmental) O;
break;
case 'O':
case 'o':
if (O instanceof Item)
primaryItem = (Item) O;
break;
case 'P':
case 'p':
if (O instanceof Item)
secondaryItem = (Item) O;
break;
case 'd':
case 'D':
if (O instanceof Room)
lastKnownLocation = (Room) O;
break;
default:
logError(scripted, "MPLOADQUESTOBJ", "Syntax", "Invalid argument var: " + varArg + " for " + scripted.Name());
break;
}
break;
}
case 22: //MPQUESTWIN
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
String whoName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
MOB M=null;
if(lastKnownLocation!=null)
M=lastKnownLocation.fetchInhabitant(whoName);
if(M==null)
M=CMLib.players().getPlayerAllHosts(whoName);
if(M!=null)
whoName=M.Name();
if(whoName.length()>0)
{
final Quest Q=getQuest(tt[2]);
if(Q!=null)
{
if(M!=null)
{
CMLib.achievements().possiblyBumpAchievement(M, AchievementLibrary.Event.QUESTOR, 1, Q);
final CMMsg winMsg=CMClass.getMsg(M,null,null,CMMsg.NO_EFFECT,null,CMMsg.TYP_WINQUEST,Q.name(),CMMsg.NO_EFFECT,null);
CMLib.map().sendGlobalMessage(M, CMMsg.TYP_WINQUEST, winMsg);
}
Q.declareWinner(whoName);
CMLib.players().bumpPrideStat(M,AccountStats.PrideStat.QUESTS_COMPLETED, 1);
}
else
logError(scripted,"MPQUESTWIN","Unknown","Quest: "+s);
}
break;
}
case 24: // MPCALLFUNC
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
if(script.elementAt(si, 3) != null)
{
execute(scripted, source, target, monster, primaryItem, secondaryItem, (DVector)script.elementAt(si, 3),
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2].trim()),
tmp);
}
else
{
final String named=tt[1];
final String parms=tt[2].trim();
final DVector script2 = findFunc(named);
if(script2 != null)
{
script.setElementAt(si, 3, script2);
execute(scripted, source, target, monster, primaryItem, secondaryItem, script2,
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,parms),
tmp);
}
else
logError(scripted,"MPCALLFUNC","Unknown","Function: "+named);
}
break;
}
case 27: // MPWHILE
{
if(tt==null)
{
final ArrayList<String> V=new ArrayList<String>();
V.add("MPWHILE");
String conditionStr=(s.substring(7).trim());
if(!conditionStr.startsWith("("))
{
logError(scripted,"MPWHILE","Syntax"," NO Starting (: "+s);
break;
}
conditionStr=conditionStr.substring(1).trim();
int x=-1;
int depth=0;
for(int i=0;i<conditionStr.length();i++)
{
if(conditionStr.charAt(i)=='(')
depth++;
else
if((conditionStr.charAt(i)==')')&&((--depth)<0))
{
x=i;
break;
}
}
if(x<0)
{
logError(scripted,"MPWHILE","Syntax"," no closing ')': "+s);
break;
}
final String DO=conditionStr.substring(x+1).trim();
conditionStr=conditionStr.substring(0,x);
try
{
final String[] EVAL=parseEval(conditionStr);
V.add("(");
V.addAll(Arrays.asList(EVAL));
V.add(")");
V.add(DO);
tt=CMParms.toStringArray(V);
script.setElementAt(si,2,tt);
}
catch(final Exception e)
{
logError(scripted,"MPWHILE","Syntax",e.getMessage());
break;
}
if(tt==null)
return null;
}
int evalEnd=2;
int depth=0;
while((evalEnd<tt.length)&&((!tt[evalEnd].equals(")"))||(depth>0)))
{
if(tt[evalEnd].equals("("))
depth++;
else
if(tt[evalEnd].equals(")"))
depth--;
evalEnd++;
}
if(evalEnd==tt.length)
{
logError(scripted,"MPWHILE","Syntax"," no closing ')': "+s);
break;
}
final String[] EVAL=new String[evalEnd-2];
for(int y=2;y<evalEnd;y++)
EVAL[y-2]=tt[y];
String DO=tt[evalEnd+1];
String[] DOT=null;
final int doLen=(tt.length-evalEnd)-1;
if(doLen>1)
{
DOT=new String[doLen];
for(int y=0;y<DOT.length;y++)
{
DOT[y]=tt[evalEnd+y+1];
if(y>0)
DO+=" "+tt[evalEnd+y+1];
}
}
final String[][] EVALO={EVAL};
final DVector vscript=new DVector(3);
vscript.addElement("FUNCTION_PROG MPWHILE_"+Math.random(),null,null);
vscript.addElement(DO,DOT,null);
final long time=System.currentTimeMillis();
while((eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,EVALO,0))
&&((System.currentTimeMillis()-time)<4000)
&&(!scripted.amDestroyed()))
execute(scripted,source,target,monster,primaryItem,secondaryItem,vscript,msg,tmp);
if(vscript.elementAt(1,2)!=DOT)
{
final int oldDotLen=(DOT==null)?1:DOT.length;
final String[] newDOT=(String[])vscript.elementAt(1,2);
final String[] newTT=new String[tt.length-oldDotLen+newDOT.length];
int end=0;
for(end=0;end<tt.length-oldDotLen;end++)
newTT[end]=tt[end];
for(int y=0;y<newDOT.length;y++)
newTT[end+y]=newDOT[y];
tt=newTT;
script.setElementAt(si,2,tt);
}
if(EVALO[0]!=EVAL)
{
final Vector<String> lazyV=new Vector<String>();
lazyV.addElement("MPWHILE");
lazyV.addElement("(");
final String[] newEVAL=EVALO[0];
for (final String element : newEVAL)
lazyV.addElement(element);
for(int i=evalEnd;i<tt.length;i++)
lazyV.addElement(tt[i]);
tt=CMParms.toStringArray(lazyV);
script.setElementAt(si,2,tt);
}
if((System.currentTimeMillis()-time)>=4000)
{
logError(scripted,"MPWHILE","RunTime","4 second limit exceeded: "+s);
break;
}
break;
}
case 26: // MPALARM
{
if(tt==null)
{
tt=parseBits(script,si,"Ccp");
if(tt==null)
return null;
}
final String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final String parms=tt[2].trim();
if(CMath.s_int(time.trim())<=0)
{
logError(scripted,"MPALARM","Syntax","Bad time "+time);
break;
}
if(parms.length()==0)
{
logError(scripted,"MPALARM","Syntax","No command!");
break;
}
final DVector vscript=new DVector(3);
vscript.addElement("FUNCTION_PROG ALARM_"+time+Math.random(),null,null);
vscript.addElement(parms,null,null);
prequeResponse(scripted,source,target,monster,primaryItem,secondaryItem,vscript,CMath.s_int(time.trim()),msg);
break;
}
case 37: // mpenable
{
if(tt==null)
{
tt=parseBits(script,si,"Ccccp");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String p2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
final String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]);
Ability A=null;
if(cast!=null)
{
if(newTarget instanceof MOB)
A=((MOB)newTarget).fetchAbility(cast);
if(A==null)
A=getAbility(cast);
if(A==null)
{
final ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false);
if(D==null)
logError(scripted,"MPENABLE","Syntax","Unknown skill/expertise: "+cast);
else
if((newTarget!=null)&&(newTarget instanceof MOB))
((MOB)newTarget).addExpertise(D.ID());
}
}
if((newTarget!=null)
&&(A!=null)
&&(newTarget instanceof MOB))
{
if(!((MOB)newTarget).isMonster())
Log.sysOut("Scripting",newTarget.Name()+" was MPENABLED with "+A.Name());
if(p2.trim().startsWith("++"))
p2=""+(CMath.s_int(p2.trim().substring(2))+A.proficiency());
else
if(p2.trim().startsWith("--"))
p2=""+(A.proficiency()-CMath.s_int(p2.trim().substring(2)));
A.setProficiency(CMath.s_int(p2.trim()));
A.setMiscText(m2);
if(((MOB)newTarget).fetchAbility(A.ID())==null)
{
((MOB)newTarget).addAbility(A);
A.autoInvocation((MOB)newTarget, false);
}
}
break;
}
case 38: // mpdisable
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if((newTarget!=null)&&(newTarget instanceof MOB))
{
final Ability A=((MOB)newTarget).findAbility(cast);
if(A!=null)
((MOB)newTarget).delAbility(A);
if((!((MOB)newTarget).isMonster())&&(A!=null))
Log.sysOut("Scripting",newTarget.Name()+" was MPDISABLED with "+A.Name());
final ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false);
if((newTarget instanceof MOB)&&(D!=null))
((MOB)newTarget).delExpertise(D.ID());
}
break;
}
case Integer.MIN_VALUE:
logError(scripted,cmd.toUpperCase(),"Syntax","Unexpected prog start -- missing '~'?");
break;
default:
if(cmd.length()>0)
{
final Vector<String> V=CMParms.parse(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s));
if((V.size()>0)
&&(monster!=null))
monster.doCommand(V,MUDCmdProcessor.METAFLAG_MPFORCED);
}
break;
}
}
tickStatus=Tickable.STATUS_END;
return null;
}
protected static final Vector<DVector> empty=new ReadOnlyVector<DVector>();
@Override
public String getScriptResourceKey()
{
return scriptKey;
}
public void bumpUpCache(final String key)
{
if((key != null)
&& (key.length()>0)
&& (!key.equals("*")))
{
synchronized(counterCache)
{
if(!counterCache.containsKey(key))
counterCache.put(key, new AtomicInteger(0));
counterCache.get(key).addAndGet(1);
}
}
}
public void bumpUpCache()
{
synchronized(this)
{
final Object ref=cachedRef;
if((ref != this)
&&(this.scriptKey!=null)
&&(this.scriptKey.length()>0))
{
bumpUpCache(getScriptResourceKey());
bumpUpCache(scope);
bumpUpCache(defaultQuestName);
cachedRef=this;
}
}
}
public boolean bumpDownCache(final String key)
{
if((key != null)
&& (key.length()>0)
&& (!key.equals("*")))
{
if((key != null)
&&(key.length()>0)
&&(!key.equals("*")))
{
synchronized(counterCache)
{
if(counterCache.containsKey(key))
{
if(counterCache.get(key).addAndGet(-1) <= 0)
{
counterCache.remove(key);
return true;
}
}
}
}
}
return false;
}
protected void bumpDownCache()
{
synchronized(this)
{
final Object ref=cachedRef;
if(ref == this)
{
if(bumpDownCache(getScriptResourceKey()))
{
for(final Resources R : Resources.all())
R._removeResource(getScriptResourceKey());
}
if(bumpDownCache(scope))
{
for(final Resources R : Resources.all())
R._removeResource("VARSCOPE-"+scope.toUpperCase().trim());
}
if(bumpDownCache(defaultQuestName))
{
for(final Resources R : Resources.all())
R._removeResource("VARSCOPE-"+defaultQuestName.toUpperCase().trim());
}
}
}
}
@Override
protected void finalize() throws Throwable
{
bumpDownCache();
super.finalize();
}
protected List<DVector> getScripts()
{
if(CMSecurity.isDisabled(CMSecurity.DisFlag.SCRIPTABLE)||CMSecurity.isDisabled(CMSecurity.DisFlag.SCRIPTING))
return empty;
@SuppressWarnings("unchecked")
List<DVector> scripts=(List<DVector>)Resources.getResource(getScriptResourceKey());
if(scripts==null)
{
String scr=getScript();
scr=CMStrings.replaceAll(scr,"`","'");
scripts=parseScripts(scr);
Resources.submitResource(getScriptResourceKey(),scripts);
}
return scripts;
}
protected boolean match(final String str, final String patt)
{
if(patt.trim().equalsIgnoreCase("ALL"))
return true;
if(patt.length()==0)
return true;
if(str.length()==0)
return false;
if(str.equalsIgnoreCase(patt))
return true;
return false;
}
private Item makeCheapItem(final Environmental E)
{
Item product=null;
if(E instanceof Item)
product=(Item)E;
else
{
product=CMClass.getItem("StdItem");
product.setName(E.Name());
product.setDisplayText(E.displayText());
product.setDescription(E.description());
if(E instanceof Physical)
product.setBasePhyStats((PhyStats)((Physical)E).basePhyStats().copyOf());
product.recoverPhyStats();
}
return product;
}
@Override
public boolean okMessage(final Environmental host, final CMMsg msg)
{
if((!(host instanceof PhysicalAgent))||(msg.source()==null)||(recurseCounter.get()>2))
return true;
try
{
// atomic recurse counter
recurseCounter.addAndGet(1);
final PhysicalAgent affecting = (PhysicalAgent)host;
final List<DVector> scripts=getScripts();
DVector script=null;
boolean tryIt=false;
String trigger=null;
String[] t=null;
int triggerCode=0;
String str=null;
for(int v=0;v<scripts.size();v++)
{
tryIt=false;
script=scripts.get(v);
if(script.size()<1)
continue;
trigger=((String)script.elementAt(0,1)).toUpperCase().trim();
t=(String[])script.elementAt(0,2);
triggerCode=getTriggerCode(trigger,t);
switch(triggerCode)
{
case 51: // cmdfail_prog
if(canTrigger(51)
&&(msg.targetMessage()!=null))
{
if(t==null)
t=parseBits(script,0,"CCT");
if(t!=null)
{
final String command=t[1];
final int x=msg.targetMessage().indexOf(' ');
final String userCmd=(x<0)?msg.targetMessage():msg.targetMessage().substring(0,x).trim().toUpperCase();
if(command.toUpperCase().startsWith(userCmd))
{
str=(x<0)?"":msg.targetMessage().substring(x).trim().toUpperCase();
if(str == null)
break;
if((t[2].length()==0)||(t[2].equals("ALL")))
tryIt=true;
else
if((t[2].equals("P"))&&(t.length>3))
{
if(match(str.trim(),t[3]))
tryIt=true;
}
else
for(int i=2;i<t.length;i++)
{
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=(t[i].trim()+" "+str.trim()).trim();
tryIt=true;
break;
}
}
if(tryIt)
{
final MOB monster=getMakeMOB(affecting);
if(lastKnownLocation==null)
{
lastKnownLocation=msg.source().location();
if(homeKnownLocation==null)
homeKnownLocation=lastKnownLocation;
}
if((monster==null)||(monster.amDead())||(lastKnownLocation==null))
return true;
final Item defaultItem=(affecting instanceof Item)?(Item)affecting:null;
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null)
Tool=defaultItem;
String resp=null;
if(msg.target() instanceof MOB)
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs());
else
if(msg.target() instanceof Item)
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,str,newObjs());
else
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs());
if((resp!=null)&&(resp.equalsIgnoreCase("CANCEL")))
return false;
}
}
}
}
break;
case 42: // cnclmsg_prog
if(canTrigger(42))
{
if(t==null)
t=parseBits(script,0,"CCT");
if(t!=null)
{
final String command=t[1];
boolean chk=false;
final int x=command.indexOf('=');
if(x>0)
{
chk=true;
boolean minorOnly = false;
boolean majorOnly = false;
for(int i=0;i<x;i++)
{
switch(command.charAt(i))
{
case 'S':
if(majorOnly)
chk=chk&&msg.isSourceMajor(command.substring(x+1));
else
if(minorOnly)
chk=chk&&msg.isSourceMinor(command.substring(x+1));
else
chk=chk&&msg.isSource(command.substring(x+1));
break;
case 'T':
if(majorOnly)
chk=chk&&msg.isTargetMajor(command.substring(x+1));
else
if(minorOnly)
chk=chk&&msg.isTargetMinor(command.substring(x+1));
else
chk=chk&&msg.isTarget(command.substring(x+1));
break;
case 'O':
if(majorOnly)
chk=chk&&msg.isOthersMajor(command.substring(x+1));
else
if(minorOnly)
chk=chk&&msg.isOthersMinor(command.substring(x+1));
else
chk=chk&&msg.isOthers(command.substring(x+1));
break;
case '<':
minorOnly=true;
majorOnly=false;
break;
case '>':
majorOnly=true;
minorOnly=false;
break;
case '?':
majorOnly=false;
minorOnly=false;
break;
default:
chk=false;
break;
}
}
}
else
if(command.startsWith(">"))
{
final String cmd=command.substring(1);
chk=msg.isSourceMajor(cmd)||msg.isTargetMajor(cmd)||msg.isOthersMajor(cmd);
}
else
if(command.startsWith("<"))
{
final String cmd=command.substring(1);
chk=msg.isSourceMinor(cmd)||msg.isTargetMinor(cmd)||msg.isOthersMinor(cmd);
}
else
if(command.startsWith("?"))
{
final String cmd=command.substring(1);
chk=msg.isSource(cmd)||msg.isTarget(cmd)||msg.isOthers(cmd);
}
else
chk=msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command);
if(chk)
{
str="";
if((msg.source().session()!=null)&&(msg.source().session().getPreviousCMD()!=null))
str=" "+CMParms.combine(msg.source().session().getPreviousCMD(),0).toUpperCase()+" ";
if((t[2].length()==0)||(t[2].equals("ALL")))
tryIt=true;
else
if((t[2].equals("P"))&&(t.length>3))
{
if(match(str.trim(),t[3]))
tryIt=true;
}
else
for(int i=2;i<t.length;i++)
{
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=(t[i].trim()+" "+str.trim()).trim();
tryIt=true;
break;
}
}
}
}
}
break;
}
if(tryIt)
{
final MOB monster=getMakeMOB(affecting);
if(lastKnownLocation==null)
{
lastKnownLocation=msg.source().location();
if(homeKnownLocation==null)
homeKnownLocation=lastKnownLocation;
}
if((monster==null)||(monster.amDead())||(lastKnownLocation==null))
return true;
final Item defaultItem=(affecting instanceof Item)?(Item)affecting:null;
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null)
Tool=defaultItem;
String resp=null;
if(msg.target() instanceof MOB)
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs());
else
if(msg.target() instanceof Item)
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,str,newObjs());
else
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs());
if((resp!=null)&&(resp.equalsIgnoreCase("CANCEL")))
return false;
}
}
}
finally
{
recurseCounter.addAndGet(-1);
}
return true;
}
protected String standardTriggerCheck(final DVector script, String[] t, final Environmental E,
final PhysicalAgent scripted, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final Object[] tmp)
{
if(E==null)
return null;
final boolean[] dollarChecks;
if(t==null)
{
t=parseBits(script,0,"CT");
dollarChecks=new boolean[t.length];
for(int i=1;i<t.length;i++)
dollarChecks[i] = t[i].indexOf('$')>=0;
script.setElementAt(0, 3, dollarChecks);
}
else
dollarChecks=(boolean[])script.elementAt(0, 3);
final String NAME=E.Name().toUpperCase();
final String ID=E.ID().toUpperCase();
if((t[1].length()==0)
||(t[1].equals("ALL"))
||(t[1].equals("P")
&&(t.length==3)
&&((t[2].equalsIgnoreCase(NAME))
||(t[2].equalsIgnoreCase("ALL")))))
return t[1];
for(int i=1;i<t.length;i++)
{
final String word;
if (dollarChecks[i])
word=this.varify(source, target, scripted, monster, primaryItem, secondaryItem, NAME, tmp, t[i]);
else
word=t[i];
if(word.equals("P") && (i < t.length-1))
{
final String arg;
if (dollarChecks[i+1])
arg=this.varify(source, target, scripted, monster, primaryItem, secondaryItem, NAME, tmp, t[i+1]);
else
arg=t[i+1];
if( arg.equalsIgnoreCase(NAME)
|| arg.equalsIgnoreCase(ID)
|| arg.equalsIgnoreCase("ALL"))
return word;
i++;
}
else
if(((" "+NAME+" ").indexOf(" "+word+" ")>=0)
||(ID.equalsIgnoreCase(word))
||(word.equalsIgnoreCase("ALL")))
return word;
}
return null;
}
@Override
public void executeMsg(final Environmental host, final CMMsg msg)
{
if((!(host instanceof PhysicalAgent))||(msg.source()==null)||(recurseCounter.get() > 2))
return;
try
{
// atomic recurse counter
recurseCounter.addAndGet(1);
final PhysicalAgent affecting = (PhysicalAgent)host;
final MOB monster=getMakeMOB(affecting);
if(lastKnownLocation==null)
{
lastKnownLocation=msg.source().location();
if(homeKnownLocation==null)
homeKnownLocation=lastKnownLocation;
}
if((monster==null)||(monster.amDead())||(lastKnownLocation==null))
return;
final Item defaultItem=(affecting instanceof Item)?(Item)affecting:null;
MOB eventMob=monster;
if((defaultItem!=null)&&(defaultItem.owner() instanceof MOB))
eventMob=(MOB)defaultItem.owner();
final List<DVector> scripts=getScripts();
if(msg.amITarget(eventMob)
&&(!msg.amISource(monster))
&&(msg.targetMinor()==CMMsg.TYP_DAMAGE)
&&(msg.source()!=monster))
lastToHurtMe=msg.source();
DVector script=null;
String trigger=null;
String[] t=null;
for(int v=0;v<scripts.size();v++)
{
script=scripts.get(v);
if(script.size()<1)
continue;
trigger=((String)script.elementAt(0,1)).toUpperCase().trim();
t=(String[])script.elementAt(0,2);
final int triggerCode=getTriggerCode(trigger,t);
int targetMinorTrigger=-1;
switch(triggerCode)
{
case 1: // greet_prog
if((msg.targetMinor()==CMMsg.TYP_ENTER)
&&(msg.amITarget(lastKnownLocation))
&&(!msg.amISource(eventMob))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))
&&canTrigger(1)
&&((!(affecting instanceof MOB))||CMLib.flags().canSenseEnteringLeaving(msg.source(),(MOB)affecting)))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t);
return;
}
}
}
break;
case 45: // arrive_prog
if(((msg.targetMinor()==CMMsg.TYP_ENTER)||(msg.sourceMinor()==CMMsg.TYP_LIFE))
&&(msg.amISource(eventMob))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))
&&canTrigger(45))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
if((host instanceof Item)
&&(((Item)host).owner() instanceof MOB)
&&(msg.source()==((Item)host).owner()))
{
// this is to prevent excessive queing when a player is running full throttle with a scripted item
// that pays attention to where it is.
for(int i=que.size()-1;i>=0;i--)
{
try
{
if(que.get(i).scr == script)
que.remove(i);
}
catch(final Exception e)
{
}
}
}
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t);
return;
}
}
}
break;
case 2: // all_greet_prog
if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(2)
&&(msg.amITarget(lastKnownLocation))
&&(!msg.amISource(eventMob))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))
&&((!(affecting instanceof MOB)) ||CMLib.flags().canActAtAll(monster)))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t);
return;
}
}
}
break;
case 47: // speak_prog
if(((msg.sourceMinor()==CMMsg.TYP_SPEAK)||(msg.targetMinor()==CMMsg.TYP_SPEAK))&&canTrigger(47)
&&(msg.amISource(monster)||(!(affecting instanceof MOB)))
&&(!msg.othersMajor(CMMsg.MASK_CHANNEL))
&&((msg.sourceMessage()!=null)
||((msg.target()==monster)&&(msg.targetMessage()!=null)&&(msg.tool()==null)))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
if(t==null)
{
t=parseBits(script,0,"CT");
for(int i=0;i<t.length;i++)
{
if(t[i]!=null)
t[i]=t[i].replace('`', '\'');
}
}
String str=null;
if(msg.sourceMessage() != null)
str=CMStrings.getSayFromMessage(msg.sourceMessage().toUpperCase());
else
if(msg.targetMessage() != null)
str=CMStrings.getSayFromMessage(msg.targetMessage().toUpperCase());
else
if(msg.othersMessage() != null)
str=CMStrings.getSayFromMessage(msg.othersMessage().toUpperCase());
if(str != null)
{
str=(" "+str.replace('`', '\'')+" ").toUpperCase();
str=CMStrings.removeColors(str);
str=CMStrings.replaceAll(str,"\n\r"," ");
if((t[1].length()==0)||(t[1].equals("ALL")))
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t);
return;
}
else
if((t[1].equals("P"))&&(t.length>2))
{
if(match(str.trim(),t[2]))
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t);
return;
}
}
else
for(int i=1;i<t.length;i++)
{
final int x=str.indexOf(" "+t[i]+" ");
if(x>=0)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str.substring(x).trim(), t);
return;
}
}
}
}
break;
case 3: // speech_prog
if(((msg.sourceMinor()==CMMsg.TYP_SPEAK)||(msg.targetMinor()==CMMsg.TYP_SPEAK))&&canTrigger(3)
&&(!msg.amISource(monster))
&&(!msg.othersMajor(CMMsg.MASK_CHANNEL))
&&(((msg.othersMessage()!=null)&&((msg.tool()==null)||(!(msg.tool() instanceof Ability))||((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)!=Ability.ACODE_LANGUAGE)))
||((msg.target()==monster)&&(msg.targetMessage()!=null)&&(msg.tool()==null)))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
if(t==null)
{
t=parseBits(script,0,"CT");
for(int i=0;i<t.length;i++)
{
if(t[i]!=null)
t[i]=t[i].replace('`', '\'');
}
}
String str=null;
if(msg.othersMessage() != null)
str=CMStrings.getSayFromMessage(msg.othersMessage().toUpperCase());
else
if(msg.targetMessage() != null)
str=CMStrings.getSayFromMessage(msg.targetMessage().toUpperCase());
if(str != null)
{
str=(" "+str.replace('`', '\'')+" ").toUpperCase();
str=CMStrings.removeColors(str);
str=CMStrings.replaceAll(str,"\n\r"," ");
if((t[1].length()==0)||(t[1].equals("ALL")))
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t);
return;
}
else
if((t[1].equals("P"))&&(t.length>2))
{
if(match(str.trim(),t[2]))
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t);
return;
}
}
else
for(int i=1;i<t.length;i++)
{
final int x=str.indexOf(" "+t[i]+" ");
if(x>=0)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str.substring(x).trim(), t);
return;
}
}
}
}
break;
case 4: // give_prog
if((msg.targetMinor()==CMMsg.TYP_GIVE)
&&canTrigger(4)
&&((msg.amITarget(monster))
||(msg.tool()==affecting)
||(affecting instanceof Room)
||(affecting instanceof Area))
&&(!msg.amISource(monster))
&&(msg.tool() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.tool(), affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,check, t);
return;
}
}
break;
case 48: // giving_prog
if((msg.targetMinor()==CMMsg.TYP_GIVE)
&&canTrigger(48)
&&((msg.amISource(monster))
||(msg.tool()==affecting)
||(affecting instanceof Room)
||(affecting instanceof Area))
&&(msg.tool() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),msg.target(),monster,(Item)msg.tool(),defaultItem,t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.tool(),defaultItem,script,1,check, t);
return;
}
}
break;
case 49: // cast_prog
if((msg.tool() instanceof Ability)
&&canTrigger(49)
&&((msg.amITarget(monster))
||(affecting instanceof Room)
||(affecting instanceof Area))
&&(!msg.amISource(monster))
&&(msg.sourceMinor()!=CMMsg.TYP_TEACH)
&&(msg.sourceMinor()!=CMMsg.TYP_ITEMSGENERATED)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.tool(), affecting,msg.source(),monster,monster,defaultItem,null,t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,check, t);
return;
}
}
break;
case 50: // casting_prog
if((msg.tool() instanceof Ability)
&&canTrigger(50)
&&((msg.amISource(monster))
||(affecting instanceof Room)
||(affecting instanceof Area))
&&(msg.sourceMinor()!=CMMsg.TYP_TEACH)
&&(msg.sourceMinor()!=CMMsg.TYP_ITEMSGENERATED)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),msg.target(),monster,null,defaultItem,t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,check, t);
return;
}
}
break;
case 40: // llook_prog
if((msg.targetMinor()==CMMsg.TYP_EXAMINE)&&canTrigger(40)
&&(!msg.amISource(monster))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,defaultItem,null,t);
if(check!=null)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,check, t);
return;
}
}
break;
case 41: // execmsg_prog
if(canTrigger(41))
{
if(t==null)
t=parseBits(script,0,"CCT");
if(t!=null)
{
final String command=t[1];
boolean chk=false;
final int x=command.indexOf('=');
if(x>0)
{
chk=true;
boolean minorOnly = false;
boolean majorOnly = false;
for(int i=0;i<x;i++)
{
switch(command.charAt(i))
{
case 'S':
if(majorOnly)
chk=chk&&msg.isSourceMajor(command.substring(x+1));
else
if(minorOnly)
chk=chk&&msg.isSourceMinor(command.substring(x+1));
else
chk=chk&&msg.isSource(command.substring(x+1));
break;
case 'T':
if(majorOnly)
chk=chk&&msg.isTargetMajor(command.substring(x+1));
else
if(minorOnly)
chk=chk&&msg.isTargetMinor(command.substring(x+1));
else
chk=chk&&msg.isTarget(command.substring(x+1));
break;
case 'O':
if(majorOnly)
chk=chk&&msg.isOthersMajor(command.substring(x+1));
else
if(minorOnly)
chk=chk&&msg.isOthersMinor(command.substring(x+1));
else
chk=chk&&msg.isOthers(command.substring(x+1));
break;
case '<':
minorOnly=true;
majorOnly=false;
break;
case '>':
majorOnly=true;
minorOnly=false;
break;
case '?':
majorOnly=false;
minorOnly=false;
break;
default:
chk=false;
break;
}
}
}
else
if(command.startsWith(">"))
{
final String cmd=command.substring(1);
chk=msg.isSourceMajor(cmd)||msg.isTargetMajor(cmd)||msg.isOthersMajor(cmd);
}
else
if(command.startsWith("<"))
{
final String cmd=command.substring(1);
chk=msg.isSourceMinor(cmd)||msg.isTargetMinor(cmd)||msg.isOthersMinor(cmd);
}
else
if(command.startsWith("?"))
{
final String cmd=command.substring(1);
chk=msg.isSource(cmd)||msg.isTarget(cmd)||msg.isOthers(cmd);
}
else
chk=msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command);
if(chk)
{
String str="";
if((msg.source().session()!=null)&&(msg.source().session().getPreviousCMD()!=null))
str=" "+CMParms.combine(msg.source().session().getPreviousCMD(),0).toUpperCase()+" ";
boolean doIt=false;
if((t[2].length()==0)||(t[2].equals("ALL")))
doIt=true;
else
if((t[2].equals("P"))&&(t.length>3))
{
if(match(str.trim(),t[3]))
doIt=true;
}
else
for(int i=2;i<t.length;i++)
{
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=(t[i].trim()+" "+str.trim()).trim();
doIt=true;
break;
}
}
if(doIt)
{
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null)
Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
return;
}
}
}
}
break;
case 39: // look_prog
if((msg.targetMinor()==CMMsg.TYP_LOOK)&&canTrigger(39)
&&(!msg.amISource(monster))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,defaultItem,defaultItem,t);
if(check!=null)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,defaultItem,script,1,check, t);
return;
}
}
break;
case 20: // get_prog
if((msg.targetMinor()==CMMsg.TYP_GET)&&canTrigger(20)
&&(msg.amITarget(affecting)
||(affecting instanceof Room)
||(affecting instanceof Area)
||(affecting instanceof MOB))
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
Item checkInE=(Item)msg.target();
if((msg.tool() instanceof Item)
&&(((Item)msg.tool()).container()==msg.target()))
checkInE=(Item)msg.tool();
final String check=standardTriggerCheck(script,t,checkInE,affecting,msg.source(),msg.target(),monster,checkInE,defaultItem,t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
enqueResponse(affecting,msg.source(),msg.target(),monster,checkInE,defaultItem,script,1,check, t);
return;
}
}
break;
case 22: // drop_prog
if((msg.targetMinor()==CMMsg.TYP_DROP)&&canTrigger(22)
&&((msg.amITarget(affecting))
||(affecting instanceof Room)
||(affecting instanceof Area)
||(affecting instanceof MOB))
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
if(msg.target() instanceof Coins)
execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check, t);
return;
}
}
break;
case 24: // remove_prog
if((msg.targetMinor()==CMMsg.TYP_REMOVE)&&canTrigger(24)
&&((msg.amITarget(affecting))
||(affecting instanceof Room)
||(affecting instanceof Area)
||(affecting instanceof MOB))
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,t);
if(check!=null)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check, t);
return;
}
}
break;
case 34: // open_prog
if(targetMinorTrigger<0)
targetMinorTrigger=CMMsg.TYP_OPEN;
//$FALL-THROUGH$
case 35: // close_prog
if(targetMinorTrigger<0)
targetMinorTrigger=CMMsg.TYP_CLOSE;
//$FALL-THROUGH$
case 36: // lock_prog
if(targetMinorTrigger<0)
targetMinorTrigger=CMMsg.TYP_LOCK;
//$FALL-THROUGH$
case 37: // unlock_prog
{
if(targetMinorTrigger<0)
targetMinorTrigger=CMMsg.TYP_UNLOCK;
if((msg.targetMinor()==targetMinorTrigger)&&canTrigger(triggerCode)
&&((msg.amITarget(affecting))
||(affecting instanceof Room)
||(affecting instanceof Area)
||(affecting instanceof MOB))
&&(!msg.amISource(monster))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final Item I=(msg.target() instanceof Item)?(Item)msg.target():defaultItem;
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,I,defaultItem,t);
if(check!=null)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,I,defaultItem,script,1,check, t);
return;
}
}
break;
}
case 25: // consume_prog
if(((msg.targetMinor()==CMMsg.TYP_EAT)||(msg.targetMinor()==CMMsg.TYP_DRINK))
&&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB))
&&(!msg.amISource(monster))&&canTrigger(25)
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,t);
if(check!=null)
{
if((msg.target() == affecting)
&&(affecting instanceof Food))
execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check, t);
return;
}
}
break;
case 21: // put_prog
if((msg.targetMinor()==CMMsg.TYP_PUT)&&canTrigger(21)
&&((msg.amITarget(affecting))
||(affecting instanceof Room)
||(affecting instanceof Area)
||(affecting instanceof MOB))
&&(msg.tool() instanceof Item)
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room))
execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),script,1,check, t);
return;
}
}
break;
case 46: // putting_prog
if((msg.targetMinor()==CMMsg.TYP_PUT)&&canTrigger(46)
&&((msg.tool()==affecting)
||(affecting instanceof Room)
||(affecting instanceof Area)
||(affecting instanceof MOB))
&&(msg.tool() instanceof Item)
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room))
execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),script,1,check, t);
return;
}
}
break;
case 27: // buy_prog
if((msg.targetMinor()==CMMsg.TYP_BUY)&&canTrigger(27)
&&((!(affecting instanceof ShopKeeper))
||msg.amITarget(affecting))
&&(!msg.amISource(monster))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final Item chItem = (msg.tool() instanceof Item)?((Item)msg.tool()):null;
final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),monster,monster,chItem,chItem,t);
if(check!=null)
{
final Item product=makeCheapItem(msg.tool());
if((product instanceof Coins)
&&(product.owner() instanceof Room))
execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),monster,monster,product,product,script,1,check, t);
return;
}
}
break;
case 28: // sell_prog
if((msg.targetMinor()==CMMsg.TYP_SELL)&&canTrigger(28)
&&((msg.amITarget(affecting))||(!(affecting instanceof ShopKeeper)))
&&(!msg.amISource(monster))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final Item chItem = (msg.tool() instanceof Item)?((Item)msg.tool()):null;
final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),monster,monster,chItem,chItem,t);
if(check!=null)
{
final Item product=makeCheapItem(msg.tool());
if((product instanceof Coins)
&&(product.owner() instanceof Room))
execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,newObjs());
else
enqueResponse(affecting,msg.source(),monster,monster,product,product,script,1,check, t);
return;
}
}
break;
case 23: // wear_prog
if(((msg.targetMinor()==CMMsg.TYP_WEAR)
||(msg.targetMinor()==CMMsg.TYP_HOLD)
||(msg.targetMinor()==CMMsg.TYP_WIELD))
&&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB))
&&(!msg.amISource(monster))&&canTrigger(23)
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,t);
if(check!=null)
{
enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,check, t);
return;
}
}
break;
case 19: // bribe_prog
if((msg.targetMinor()==CMMsg.TYP_GIVE)
&&(msg.amITarget(eventMob)||(!(affecting instanceof MOB)))
&&(!msg.amISource(monster))&&canTrigger(19)
&&(msg.tool() instanceof Coins)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
if(t[1].startsWith("ANY")||t[1].startsWith("ALL"))
t[1]=t[1].trim();
else
if(!((Coins)msg.tool()).getCurrency().equals(CMLib.beanCounter().getCurrency(monster)))
break;
double d=0.0;
if(CMath.isDouble(t[1]))
d=CMath.s_double(t[1]);
else
d=CMath.s_int(t[1]);
if((((Coins)msg.tool()).getTotalValue()>=d)
||(t[1].equals("ALL"))
||(t[1].equals("ANY")))
{
enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,null, t);
return;
}
}
}
break;
case 8: // entry_prog
if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(8)
&&(msg.amISource(eventMob)
||(msg.target()==affecting)
||(msg.tool()==affecting)
||(affecting instanceof Item))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
final List<ScriptableResponse> V=new XVector<ScriptableResponse>(que);
ScriptableResponse SB=null;
String roomID=null;
if(msg.target()!=null)
roomID=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(msg.target()));
for(int q=0;q<V.size();q++)
{
SB=V.get(q);
if((SB.scr==script)&&(SB.s==msg.source()))
{
if(que.remove(SB))
execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs());
break;
}
}
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,roomID, t);
return;
}
}
}
break;
case 9: // exit_prog
if((msg.targetMinor()==CMMsg.TYP_LEAVE)&&canTrigger(9)
&&(msg.amITarget(lastKnownLocation))
&&(!msg.amISource(eventMob))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
final List<ScriptableResponse> V=new XVector<ScriptableResponse>(que);
ScriptableResponse SB=null;
String roomID=null;
if(msg.target()!=null)
roomID=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(msg.target()));
for(int q=0;q<V.size();q++)
{
SB=V.get(q);
if((SB.scr==script)&&(SB.s==msg.source()))
{
if(que.remove(SB))
execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs());
break;
}
}
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,roomID, t);
return;
}
}
}
break;
case 10: // death_prog
if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(10)
&&(msg.amISource(eventMob)||(!(affecting instanceof MOB))))
{
if(t==null)
t=parseBits(script,0,"C");
final MOB ded=msg.source();
MOB src=lastToHurtMe;
if(msg.tool() instanceof MOB)
src=(MOB)msg.tool();
if((src==null)||(src.location()!=monster.location()))
src=ded;
execute(affecting,src,ded,ded,defaultItem,null,script,null,newObjs());
return;
}
break;
case 44: // kill_prog
if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(44)
&&((msg.tool()==affecting)||(!(affecting instanceof MOB))))
{
if(t==null)
t=parseBits(script,0,"C");
final MOB ded=msg.source();
MOB src=lastToHurtMe;
if(msg.tool() instanceof MOB)
src=(MOB)msg.tool();
if((src==null)||(src.location()!=monster.location()))
src=ded;
execute(affecting,src,ded,ded,defaultItem,null,script,null,newObjs());
return;
}
break;
case 26: // damage_prog
if((msg.targetMinor()==CMMsg.TYP_DAMAGE)&&canTrigger(26)
&&(msg.amITarget(eventMob)||(msg.tool()==affecting)))
{
if(t==null)
t=parseBits(script,0,"C");
Item I=null;
if(msg.tool() instanceof Item)
I=(Item)msg.tool();
execute(affecting,msg.source(),msg.target(),eventMob,defaultItem,I,script,""+msg.value(),newObjs());
return;
}
break;
case 29: // login_prog
if(!registeredEvents.contains(Integer.valueOf(CMMsg.TYP_LOGIN)))
{
CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LOGIN);
registeredEvents.add(Integer.valueOf(CMMsg.TYP_LOGIN));
}
if((msg.sourceMinor()==CMMsg.TYP_LOGIN)&&canTrigger(29)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))
&&(!CMLib.flags().isCloaked(msg.source())))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t);
return;
}
}
}
break;
case 32: // level_prog
if(!registeredEvents.contains(Integer.valueOf(CMMsg.TYP_LEVEL)))
{
CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LEVEL);
registeredEvents.add(Integer.valueOf(CMMsg.TYP_LEVEL));
}
if((msg.sourceMinor()==CMMsg.TYP_LEVEL)&&canTrigger(32)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))
&&(msg.value() > msg.source().basePhyStats().level())
&&(!CMLib.flags().isCloaked(msg.source())))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
execute(affecting,msg.source(),monster,monster,defaultItem,null,script,null,t);
return;
}
}
}
break;
case 30: // logoff_prog
if((msg.sourceMinor()==CMMsg.TYP_QUIT)&&canTrigger(30)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))
&&((!CMLib.flags().isCloaked(msg.source()))||(!CMSecurity.isASysOp(msg.source()))))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t);
return;
}
}
}
break;
case 12: // mask_prog
{
if(!canTrigger(12))
break;
}
//$FALL-THROUGH$
case 18: // act_prog
if((msg.amISource(monster))
||((triggerCode==18)&&(!canTrigger(18))))
break;
//$FALL-THROUGH$
case 43: // imask_prog
if((triggerCode!=43)||(msg.amISource(monster)&&canTrigger(43)))
{
if(t==null)
{
t=parseBits(script,0,"CT");
for(int i=1;i<t.length;i++)
t[i]=CMLib.english().stripPunctuation(CMStrings.removeColors(t[i]));
}
boolean doIt=false;
String str=msg.othersMessage();
if(str==null)
str=msg.targetMessage();
if(str==null)
str=msg.sourceMessage();
if(str==null)
break;
str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false);
str=CMLib.english().stripPunctuation(CMStrings.removeColors(str));
str=" "+CMStrings.replaceAll(str,"\n\r"," ").toUpperCase().trim()+" ";
if((t[1].length()==0)||(t[1].equals("ALL")))
doIt=true;
else
if((t[1].equals("P"))&&(t.length>2))
{
if(match(str.trim(),t[2]))
doIt=true;
}
else
for(int i=1;i<t.length;i++)
{
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=t[i];
doIt=true;
break;
}
}
if(doIt)
{
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null)
Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
return;
}
}
break;
case 38: // social_prog
if(!msg.amISource(monster)
&&canTrigger(38)
&&(msg.tool() instanceof Social))
{
if(t==null)
t=parseBits(script,0,"CR");
if((t!=null)
&&((Social)msg.tool()).Name().toUpperCase().startsWith(t[1]))
{
final Item Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,msg.tool().Name(), t);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,msg.tool().Name(), t);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,msg.tool().Name(), t);
return;
}
}
break;
case 33: // channel_prog
if(!registeredEvents.contains(Integer.valueOf(CMMsg.TYP_CHANNEL)))
{
CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_CHANNEL);
registeredEvents.add(Integer.valueOf(CMMsg.TYP_CHANNEL));
}
if(!msg.amISource(monster)
&&(msg.othersMajor(CMMsg.MASK_CHANNEL))
&&canTrigger(33))
{
if(t==null)
t=parseBits(script,0,"CCT");
boolean doIt=false;
if(t!=null)
{
final String channel=t[1];
final int channelInt=msg.othersMinor()-CMMsg.TYP_CHANNEL;
String str=null;
final CMChannel officialChannel=CMLib.channels().getChannel(channelInt);
if(officialChannel==null)
Log.errOut("Script","Unknown channel for code '"+channelInt+"': "+msg.othersMessage());
else
if(channel.equalsIgnoreCase(officialChannel.name()))
{
str=msg.sourceMessage();
if(str==null)
str=msg.othersMessage();
if(str==null)
str=msg.targetMessage();
if(str==null)
break;
str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false).toUpperCase().trim();
int dex=str.indexOf("["+channel+"]");
if(dex>0)
str=str.substring(dex+2+channel.length()).trim();
else
{
dex=str.indexOf('\'');
final int edex=str.lastIndexOf('\'');
if(edex>dex)
str=str.substring(dex+1,edex);
}
str=" "+CMStrings.removeColors(str)+" ";
str=CMStrings.replaceAll(str,"\n\r"," ");
if((t[2].length()==0)||(t[2].equals("ALL")))
doIt=true;
else
if(t[2].equals("P")&&(t.length>2))
{
if(match(str.trim(),t[3]))
doIt=true;
}
else
for(int i=2;i<t.length;i++)
{
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=t[i];
doIt=true;
break;
}
}
}
if(doIt)
{
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null)
Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
return;
}
}
}
break;
case 31: // regmask_prog
if(!msg.amISource(monster)&&canTrigger(31))
{
boolean doIt=false;
String str=msg.othersMessage();
if(str==null)
str=msg.targetMessage();
if(str==null)
str=msg.sourceMessage();
if(str==null)
break;
str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false);
if(t==null)
t=parseBits(script,0,"Cp");
if(t!=null)
{
if(CMParms.getCleanBit(t[1],0).equalsIgnoreCase("p"))
doIt=str.trim().equals(t[1].substring(1).trim());
else
{
Pattern P=patterns.get(t[1]);
if(P==null)
{
P=Pattern.compile(t[1], Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
patterns.put(t[1],P);
}
final Matcher M=P.matcher(str);
doIt=M.find();
if(doIt)
str=str.substring(M.start()).trim();
}
}
if(doIt)
{
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null)
Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
return;
}
}
break;
}
}
}
finally
{
recurseCounter.addAndGet(-1);
}
}
protected int getTriggerCode(final String trigger, final String[] ttrigger)
{
final Integer I;
if((ttrigger!=null)&&(ttrigger.length>0))
I=progH.get(ttrigger[0]);
else
{
final int x=trigger.indexOf(' ');
if(x<0)
I=progH.get(trigger.toUpperCase().trim());
else
I=progH.get(trigger.substring(0,x).toUpperCase().trim());
}
if(I==null)
return 0;
return I.intValue();
}
@Override
public MOB getMakeMOB(final Tickable ticking)
{
MOB mob=null;
if(ticking instanceof MOB)
{
mob=(MOB)ticking;
if(!mob.amDead())
lastKnownLocation=mob.location();
}
else
if(ticking instanceof Environmental)
{
final Room R=CMLib.map().roomLocation((Environmental)ticking);
if(R!=null)
lastKnownLocation=R;
if((backupMOB==null)
||(backupMOB.amDestroyed())
||(backupMOB.amDead()))
{
backupMOB=CMClass.getMOB("StdMOB");
if(backupMOB!=null)
{
backupMOB.setName(ticking.name());
backupMOB.setDisplayText(L("@x1 is here.",ticking.name()));
backupMOB.setDescription("");
backupMOB.setAgeMinutes(-1);
mob=backupMOB;
if(backupMOB.location()!=lastKnownLocation)
backupMOB.setLocation(lastKnownLocation);
}
}
else
{
backupMOB.setAgeMinutes(-1);
mob=backupMOB;
if(backupMOB.location()!=lastKnownLocation)
{
backupMOB.setLocation(lastKnownLocation);
backupMOB.setName(ticking.name());
backupMOB.setDisplayText(L("@x1 is here.",ticking.name()));
}
}
}
return mob;
}
protected boolean canTrigger(final int triggerCode)
{
final Long L=noTrigger.get(Integer.valueOf(triggerCode));
if(L==null)
return true;
if(System.currentTimeMillis()<L.longValue())
return false;
noTrigger.remove(Integer.valueOf(triggerCode));
return true;
}
@Override
public boolean tick(final Tickable ticking, final int tickID)
{
final Item defaultItem=(ticking instanceof Item)?(Item)ticking:null;
final MOB mob;
synchronized(this) // supposedly this will cause a sync between cpus of the object
{
mob=getMakeMOB(ticking);
}
if((mob==null)||(lastKnownLocation==null))
{
altStatusTickable=null;
return true;
}
final PhysicalAgent affecting=(ticking instanceof PhysicalAgent)?((PhysicalAgent)ticking):null;
final List<DVector> scripts=getScripts();
if(!runInPassiveAreas)
{
final Area A=CMLib.map().areaLocation(ticking);
if((A!=null)&&(A.getAreaState() != Area.State.ACTIVE))
{
return true;
}
}
if(defaultItem != null)
{
final ItemPossessor poss=defaultItem.owner();
if(poss instanceof MOB)
{
final Room R=((MOB)poss).location();
if((R==null)||(R.numInhabitants()==0))
{
altStatusTickable=null;
return true;
}
}
}
int triggerCode=-1;
String trigger="";
String[] t=null;
for(int thisScriptIndex=0;thisScriptIndex<scripts.size();thisScriptIndex++)
{
final DVector script=scripts.get(thisScriptIndex);
if(script.size()<2)
continue;
trigger=((String)script.elementAt(0,1)).toUpperCase().trim();
t=(String[])script.elementAt(0,2);
triggerCode=getTriggerCode(trigger,t);
tickStatus=Tickable.STATUS_SCRIPT+triggerCode;
switch(triggerCode)
{
case 5: // rand_Prog
if((!mob.amDead())&&canTrigger(5))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
}
}
break;
case 16: // delay_prog
if((!mob.amDead())&&canTrigger(16))
{
int targetTick=-1;
final Integer thisScriptIndexI=Integer.valueOf(thisScriptIndex);
final int[] delayProgCounter;
synchronized(thisScriptIndexI)
{
if(delayTargetTimes.containsKey(thisScriptIndexI))
targetTick=delayTargetTimes.get(thisScriptIndexI).intValue();
else
{
if(t==null)
t=parseBits(script,0,"CCR");
if(t!=null)
{
final int low=CMath.s_int(t[1]);
int high=CMath.s_int(t[2]);
if(high<low)
high=low;
targetTick=CMLib.dice().roll(1,high-low+1,low-1);
delayTargetTimes.put(thisScriptIndexI,Integer.valueOf(targetTick));
}
}
if(delayProgCounters.containsKey(thisScriptIndexI))
delayProgCounter=delayProgCounters.get(thisScriptIndexI);
else
{
delayProgCounter=new int[]{0};
delayProgCounters.put(thisScriptIndexI,delayProgCounter);
}
}
boolean exec=false;
synchronized(delayProgCounter)
{
if(delayProgCounter[0]>=targetTick)
{
exec=true;
delayProgCounter[0]=0;
}
else
delayProgCounter[0]++;
}
if(exec)
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
}
break;
case 7: // fight_Prog
if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(7))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,newObjs());
}
}
else
if((ticking instanceof Item)
&&canTrigger(7)
&&(((Item)ticking).owner() instanceof MOB)
&&(((MOB)((Item)ticking).owner()).isInCombat()))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
final MOB M=(MOB)((Item)ticking).owner();
if(!M.amDead())
execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,newObjs());
}
}
}
break;
case 11: // hitprcnt_prog
if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(11))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
final int floor=(int)Math.round(CMath.mul(CMath.div(prcnt,100.0),mob.maxState().getHitPoints()));
if(mob.curState().getHitPoints()<=floor)
execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,newObjs());
}
}
else
if((ticking instanceof Item)
&&canTrigger(11)
&&(((Item)ticking).owner() instanceof MOB)
&&(((MOB)((Item)ticking).owner()).isInCombat()))
{
final MOB M=(MOB)((Item)ticking).owner();
if(!M.amDead())
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
final int floor=(int)Math.round(CMath.mul(CMath.div(prcnt,100.0),M.maxState().getHitPoints()));
if(M.curState().getHitPoints()<=floor)
execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,newObjs());
}
}
}
break;
case 6: // once_prog
if(!oncesDone.contains(script)&&canTrigger(6))
{
if(t==null)
t=parseBits(script,0,"C");
oncesDone.add(script);
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
}
break;
case 14: // time_prog
if((mob.location()!=null)
&&canTrigger(14)
&&(!mob.amDead()))
{
if(t==null)
t=parseBits(script,0,"CT");
int lastTimeProgDone=-1;
if(lastTimeProgsDone.containsKey(Integer.valueOf(thisScriptIndex)))
lastTimeProgDone=lastTimeProgsDone.get(Integer.valueOf(thisScriptIndex)).intValue();
final int time=mob.location().getArea().getTimeObj().getHourOfDay();
if((t!=null)&&(lastTimeProgDone!=time))
{
boolean done=false;
for(int i=1;i<t.length;i++)
{
if(time==CMath.s_int(t[i]))
{
done=true;
execute(affecting,mob,mob,mob,defaultItem,null,script,""+time,newObjs());
lastTimeProgsDone.remove(Integer.valueOf(thisScriptIndex));
lastTimeProgsDone.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(time));
break;
}
}
if(!done)
lastTimeProgsDone.remove(Integer.valueOf(thisScriptIndex));
}
}
break;
case 15: // day_prog
if((mob.location()!=null)&&canTrigger(15)
&&(!mob.amDead()))
{
if(t==null)
t=parseBits(script,0,"CT");
int lastDayProgDone=-1;
if(lastDayProgsDone.containsKey(Integer.valueOf(thisScriptIndex)))
lastDayProgDone=lastDayProgsDone.get(Integer.valueOf(thisScriptIndex)).intValue();
final int day=mob.location().getArea().getTimeObj().getDayOfMonth();
if((t!=null)&&(lastDayProgDone!=day))
{
boolean done=false;
for(int i=1;i<t.length;i++)
{
if(day==CMath.s_int(t[i]))
{
done=true;
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
lastDayProgsDone.remove(Integer.valueOf(thisScriptIndex));
lastDayProgsDone.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(day));
break;
}
}
if(!done)
lastDayProgsDone.remove(Integer.valueOf(thisScriptIndex));
}
}
break;
case 13: // quest_time_prog
if(!oncesDone.contains(script)&&canTrigger(13))
{
if(t==null)
t=parseBits(script,0,"CCC");
if(t!=null)
{
final Quest Q=getQuest(t[1]);
if((Q!=null)
&&(Q.running())
&&(!Q.stopping())
&&(Q.duration()!=0))
{
final int time=CMath.s_int(t[2]);
if(time>=Q.minsRemaining())
{
oncesDone.add(script);
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
}
}
}
}
break;
default:
break;
}
}
tickStatus=Tickable.STATUS_SCRIPT+100;
dequeResponses();
altStatusTickable=null;
return true;
}
@Override
public void initializeClass()
{
}
@Override
public int compareTo(final CMObject o)
{
return CMClass.classID(this).compareToIgnoreCase(CMClass.classID(o));
}
public void enqueResponse(final PhysicalAgent host,
final MOB source,
final Environmental target,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final DVector script,
final int ticks,
final String msg,
final String[] triggerStr)
{
if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED))
return;
if(que.size()>25)
{
this.logError(monster, "UNK", "SYS", "Attempt to enque more than 25 events (last was "+CMParms.toListString(triggerStr)+" ).");
que.clear();
}
if(noDelay)
execute(host,source,target,monster,primaryItem,secondaryItem,script,msg,newObjs());
else
que.add(new ScriptableResponse(host,source,target,monster,primaryItem,secondaryItem,script,ticks,msg));
}
public void prequeResponse(final PhysicalAgent host,
final MOB source,
final Environmental target,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final DVector script,
final int ticks,
final String msg)
{
if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED))
return;
if(que.size()>25)
{
this.logError(monster, "UNK", "SYS", "Attempt to pre que more than 25 events.");
que.clear();
}
que.add(0,new ScriptableResponse(host,source,target,monster,primaryItem,secondaryItem,script,ticks,msg));
}
@Override
public void dequeResponses()
{
try
{
tickStatus=Tickable.STATUS_SCRIPT+100;
for(int q=que.size()-1;q>=0;q--)
{
ScriptableResponse SB=null;
try
{
SB=que.get(q);
}
catch(final ArrayIndexOutOfBoundsException x)
{
continue;
}
if(SB.checkTimeToExecute())
{
execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs());
que.remove(SB);
}
}
}
catch (final Exception e)
{
Log.errOut("DefaultScriptingEngine", e);
}
}
public String L(final String str, final String ... xs)
{
return CMLib.lang().fullSessionTranslation(str, xs);
}
protected static class JScriptEvent extends ScriptableObject
{
@Override
public String getClassName()
{
return "JScriptEvent";
}
static final long serialVersionUID = 43;
final PhysicalAgent h;
final MOB s;
final Environmental t;
final MOB m;
final Item pi;
final Item si;
final Object[] objs;
Vector<String> scr;
final String message;
final DefaultScriptingEngine c;
public Environmental host()
{
return h;
}
public MOB source()
{
return s;
}
public Environmental target()
{
return t;
}
public MOB monster()
{
return m;
}
public Item item()
{
return pi;
}
public Item item2()
{
return si;
}
public String message()
{
return message;
}
public void setVar(final String host, final String var, final String value)
{
c.setVar(host,var.toUpperCase(),value);
}
public String getVar(final String host, final String var)
{
return c.getVar(host, var);
}
public String toJavaString(final Object O)
{
return Context.toString(O);
}
public String getCMType(final Object O)
{
if(O == null)
return "null";
final CMObjectType typ = CMClass.getObjectType(O);
if(typ == null)
return "unknown";
return typ.name().toLowerCase();
}
@Override
public Object get(final String name, final Scriptable start)
{
if (super.has(name, start))
return super.get(name, start);
if (methH.containsKey(name) || funcH.containsKey(name)
|| (name.endsWith("$")&&(funcH.containsKey(name.substring(0,name.length()-1)))))
{
return new Function()
{
@Override
public Object call(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args)
{
if(methH.containsKey(name))
{
final StringBuilder strb=new StringBuilder(name);
if(args.length==1)
strb.append(" ").append(String.valueOf(args[0]));
else
for(int i=0;i<args.length;i++)
{
if(i==args.length-1)
strb.append(" ").append(String.valueOf(args[i]));
else
strb.append(" ").append("'"+String.valueOf(args[i])+"'");
}
final DVector DV=new DVector(2);
DV.addElement("JS_PROG",null);
DV.addElement(strb.toString(),null);
return c.execute(h,s,t,m,pi,si,DV,message,objs);
}
if(name.endsWith("$"))
{
final StringBuilder strb=new StringBuilder(name.substring(0,name.length()-1)).append("(");
if(args.length==1)
strb.append(" ").append(String.valueOf(args[0]));
else
for(int i=0;i<args.length;i++)
{
if(i==args.length-1)
strb.append(" ").append(String.valueOf(args[i]));
else
strb.append(" ").append("'"+String.valueOf(args[i])+"'");
}
strb.append(" ) ");
return c.functify(h,s,t,m,pi,si,message,objs,strb.toString());
}
final String[] sargs=new String[args.length+3];
sargs[0]=name;
sargs[1]="(";
for(int i=0;i<args.length;i++)
sargs[i+2]=String.valueOf(args[i]);
sargs[sargs.length-1]=")";
final String[][] EVAL={sargs};
return Boolean.valueOf(c.eval(h,s,t,m,pi,si,message,objs,EVAL,0));
}
@Override
public void delete(final String arg0)
{
}
@Override
public void delete(final int arg0)
{
}
@Override
public Object get(final String arg0, final Scriptable arg1)
{
return null;
}
@Override
public Object get(final int arg0, final Scriptable arg1)
{
return null;
}
@Override
public String getClassName()
{
return null;
}
@Override
public Object getDefaultValue(final Class<?> arg0)
{
return null;
}
@Override
public Object[] getIds()
{
return null;
}
@Override
public Scriptable getParentScope()
{
return null;
}
@Override
public Scriptable getPrototype()
{
return null;
}
@Override
public boolean has(final String arg0, final Scriptable arg1)
{
return false;
}
@Override
public boolean has(final int arg0, final Scriptable arg1)
{
return false;
}
@Override
public boolean hasInstance(final Scriptable arg0)
{
return false;
}
@Override
public void put(final String arg0, final Scriptable arg1, final Object arg2)
{
}
@Override
public void put(final int arg0, final Scriptable arg1, final Object arg2)
{
}
@Override
public void setParentScope(final Scriptable arg0)
{
}
@Override
public void setPrototype(final Scriptable arg0)
{
}
@Override
public Scriptable construct(final Context arg0, final Scriptable arg1, final Object[] arg2)
{
return null;
}
};
}
return super.get(name, start);
}
public void executeEvent(final DVector script, final int lineNum)
{
c.execute(h, s, t, m, pi, si, script, message, objs, lineNum);
}
public JScriptEvent(final DefaultScriptingEngine scrpt,
final PhysicalAgent host,
final MOB source,
final Environmental target,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final String msg,
final Object[] tmp)
{
c=scrpt;
h=host;
s=source;
t=target;
m=monster;
pi=primaryItem;
si=secondaryItem;
message=msg;
objs=tmp;
}
}
}
|
com/planet_ink/coffee_mud/Common/DefaultScriptingEngine.java
|
package com.planet_ink.coffee_mud.Common;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Expire;
import com.planet_ink.coffee_mud.core.exceptions.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.CMClass.CMObjectType;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.AccountStats.PrideStat;
import com.planet_ink.coffee_mud.Common.interfaces.Session.InputCallback;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.ChannelsLibrary.CMChannel;
import com.planet_ink.coffee_mud.Libraries.interfaces.DatabaseEngine.PlayerData;
import com.planet_ink.coffee_mud.Libraries.interfaces.XMLLibrary.XMLTag;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import org.mozilla.javascript.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
Copyright 2008-2020 Bo Zimmerman
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.
*/
public class DefaultScriptingEngine implements ScriptingEngine
{
@Override
public String ID()
{
return "DefaultScriptingEngine";
}
@Override
public String name()
{
return "Default Scripting Engine";
}
protected static final Map<String,Integer> funcH = new Hashtable<String,Integer>();
protected static final Map<String,Integer> methH = new Hashtable<String,Integer>();
protected static final Map<String,Integer> progH = new Hashtable<String,Integer>();
protected static final Map<String,Integer> connH = new Hashtable<String,Integer>();
protected static final Map<String,Integer> gstatH = new Hashtable<String,Integer>();
protected static final Map<String,Integer> signH = new Hashtable<String,Integer>();
protected static final Map<String, AtomicInteger> counterCache= new Hashtable<String, AtomicInteger>();
protected static final Map<String, Pattern> patterns = new Hashtable<String, Pattern>();
protected boolean noDelay = CMSecurity.isDisabled(CMSecurity.DisFlag.SCRIPTABLEDELAY);
protected String scope = "";
protected int tickStatus = Tickable.STATUS_NOT;
protected boolean isSavable = true;
protected boolean alwaysTriggers = false;
protected MOB lastToHurtMe = null;
protected Room lastKnownLocation= null;
protected Room homeKnownLocation= null;
protected Tickable altStatusTickable= null;
protected List<DVector> oncesDone = new Vector<DVector>();
protected Map<Integer,Integer> delayTargetTimes = new Hashtable<Integer,Integer>();
protected Map<Integer,int[]> delayProgCounters= new Hashtable<Integer,int[]>();
protected Map<Integer,Integer> lastTimeProgsDone= new Hashtable<Integer,Integer>();
protected Map<Integer,Integer> lastDayProgsDone = new Hashtable<Integer,Integer>();
protected Set<Integer> registeredEvents = new HashSet<Integer>();
protected Map<Integer,Long> noTrigger = new Hashtable<Integer,Long>();
protected MOB backupMOB = null;
protected CMMsg lastMsg = null;
protected Resources resources = null;
protected Environmental lastLoaded = null;
protected String myScript = "";
protected String defaultQuestName = "";
protected String scriptKey = null;
protected boolean runInPassiveAreas= true;
protected boolean debugBadScripts = false;
protected List<ScriptableResponse>que = new Vector<ScriptableResponse>();
protected final AtomicInteger recurseCounter = new AtomicInteger();
protected volatile Object cachedRef = null;
public DefaultScriptingEngine()
{
super();
//CMClass.bumpCounter(this,CMClass.CMObjectType.COMMON);//removed for mem & perf
debugBadScripts=CMSecurity.isDebugging(CMSecurity.DbgFlag.BADSCRIPTS);
resources = Resources.instance();
}
@Override
public boolean isSavable()
{
return isSavable;
}
@Override
public void setSavable(final boolean truefalse)
{
isSavable = truefalse;
}
@Override
public String defaultQuestName()
{
return defaultQuestName;
}
protected Quest defaultQuest()
{
if(defaultQuestName.length()==0)
return null;
return CMLib.quests().fetchQuest(defaultQuestName);
}
@Override
public void setVarScope(final String newScope)
{
if((newScope==null)||(newScope.trim().length()==0)||newScope.equalsIgnoreCase("GLOBAL"))
{
scope="";
resources=Resources.instance();
}
else
scope=newScope.toUpperCase().trim();
if(scope.equalsIgnoreCase("*")||scope.equals("INDIVIDUAL"))
resources = Resources.newResources();
else
{
resources=(Resources)Resources.getResource("VARSCOPE-"+scope);
if(resources==null)
{
resources = Resources.newResources();
Resources.submitResource("VARSCOPE-"+scope,resources);
}
if(cachedRef==this)
bumpUpCache(scope);
}
}
@Override
public String getVarScope()
{
return scope;
}
protected Object[] newObjs()
{
return new Object[ScriptingEngine.SPECIAL_NUM_OBJECTS];
}
@Override
public String getLocalVarXML()
{
if((scope==null)||(scope.length()==0))
return "";
final StringBuffer str=new StringBuffer("");
for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();)
{
final String key=k.next();
if(key.startsWith("SCRIPTVAR-"))
{
str.append("<"+key.substring(10)+">");
@SuppressWarnings("unchecked")
final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource(key);
for(final Enumeration<String> e=H.keys();e.hasMoreElements();)
{
final String vn=e.nextElement();
final String val=H.get(vn);
str.append("<"+vn+">"+CMLib.xml().parseOutAngleBrackets(val)+"</"+vn+">");
}
str.append("</"+key.substring(10)+">");
}
}
return str.toString();
}
@Override
public void setLocalVarXML(final String xml)
{
for(final Iterator<String> k = Resources.findResourceKeys("SCRIPTVAR-");k.hasNext();)
{
final String key=k.next();
if(key.startsWith("SCRIPTVAR-"))
resources._removeResource(key);
}
final List<XMLLibrary.XMLTag> V=CMLib.xml().parseAllXML(xml);
for(int v=0;v<V.size();v++)
{
final XMLTag piece=V.get(v);
if((piece.contents()!=null)&&(piece.contents().size()>0))
{
final String kkey="SCRIPTVAR-"+piece.tag();
final Hashtable<String,String> H=new Hashtable<String,String>();
for(int c=0;c<piece.contents().size();c++)
{
final XMLTag piece2=piece.contents().get(c);
H.put(piece2.tag(),piece2.value());
}
resources._submitResource(kkey,H);
}
}
}
private Quest getQuest(final String named)
{
if((defaultQuestName.length()>0)
&&(named.equals("*")||named.equalsIgnoreCase(defaultQuestName)))
return defaultQuest();
Quest Q=null;
for(int i=0;i<CMLib.quests().numQuests();i++)
{
try
{
Q = CMLib.quests().fetchQuest(i);
}
catch (final Exception e)
{
}
if(Q!=null)
{
if(Q.name().equalsIgnoreCase(named))
{
if(Q.running())
return Q;
}
}
}
return CMLib.quests().fetchQuest(named);
}
@Override
public int getTickStatus()
{
final Tickable T=altStatusTickable;
if(T!=null)
return T.getTickStatus();
return tickStatus;
}
@Override
public void registerDefaultQuest(final String qName)
{
if((qName==null)||(qName.trim().length()==0))
defaultQuestName="";
else
{
defaultQuestName=qName.trim();
if(cachedRef==this)
bumpUpCache(defaultQuestName);
}
}
@Override
public CMObject newInstance()
{
try
{
return this.getClass().newInstance();
}
catch(final Exception e)
{
Log.errOut(ID(),e);
}
return new DefaultScriptingEngine();
}
@Override
public CMObject copyOf()
{
try
{
final DefaultScriptingEngine S=(DefaultScriptingEngine)this.clone();
//CMClass.bumpCounter(S,CMClass.CMObjectType.COMMON);//removed for mem & perf
S.reset();
return S;
}
catch(final CloneNotSupportedException e)
{
return new DefaultScriptingEngine();
}
}
/*
protected void finalize()
{
CMClass.unbumpCounter(this, CMClass.CMObjectType.COMMON);
}// removed for mem & perf
*/
/*
* c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger
*/
protected String[] parseBits(final DVector script, final int row, final String instructions)
{
final String line=(String)script.elementAt(row,1);
final String[] newLine=parseBits(line,instructions);
script.setElementAt(row,2,newLine);
return newLine;
}
protected String[] parseSpecial3PartEval(final String[][] eval, final int t)
{
String[] tt=eval[0];
final String funcParms=tt[t];
final String[] tryTT=parseBits(funcParms,"ccr");
if(signH.containsKey(tryTT[1]))
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
else
{
String[] parsed=null;
if(CMParms.cleanBit(funcParms).equals(funcParms))
parsed=parseBits("'"+funcParms+"' . .","cr");
else
parsed=parseBits(funcParms+" . .","cr");
tt=insertStringArray(tt,parsed,t);
eval[0]=tt;
}
return tt;
}
/*
* c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger
*/
protected String[] parseBits(String line, final String instructions)
{
String[] newLine=new String[instructions.length()];
for(int i=0;i<instructions.length();i++)
{
switch(instructions.charAt(i))
{
case 'c':
newLine[i] = CMParms.getCleanBit(line, i);
break;
case 'C':
newLine[i] = CMParms.getCleanBit(line, i).toUpperCase().trim();
break;
case 'r':
newLine[i] = CMParms.getPastBitClean(line, i - 1);
break;
case 'R':
newLine[i] = CMParms.getPastBitClean(line, i - 1).toUpperCase().trim();
break;
case 'p':
newLine[i] = CMParms.getPastBit(line, i - 1);
break;
case 'P':
newLine[i] = CMParms.getPastBit(line, i - 1).toUpperCase().trim();
break;
case 'S':
line = line.toUpperCase();
//$FALL-THROUGH$
case 's':
{
final String s = CMParms.getPastBit(line, i - 1);
final int numBits = CMParms.numBits(s);
final String[] newNewLine = new String[newLine.length - 1 + numBits];
for (int x = 0; x < i; x++)
newNewLine[x] = newLine[x];
for (int x = 0; x < numBits; x++)
newNewLine[i + x] = CMParms.getCleanBit(s, i - 1);
newLine = newNewLine;
i = instructions.length();
break;
}
case 'T':
line = line.toUpperCase();
//$FALL-THROUGH$
case 't':
{
final String s = CMParms.getPastBit(line, i - 1);
String[] newNewLine = null;
if (CMParms.getCleanBit(s, 0).equalsIgnoreCase("P"))
{
newNewLine = new String[newLine.length + 1];
for (int x = 0; x < i; x++)
newNewLine[x] = newLine[x];
newNewLine[i] = "P";
newNewLine[i + 1] = CMParms.getPastBitClean(s, 0);
}
else
{
final int numNewBits = (s.trim().length() == 0) ? 1 : CMParms.numBits(s);
newNewLine = new String[newLine.length - 1 + numNewBits];
for (int x = 0; x < i; x++)
newNewLine[x] = newLine[x];
for (int x = 0; x < numNewBits; x++)
newNewLine[i + x] = CMParms.getCleanBit(s, x);
}
newLine = newNewLine;
i = instructions.length();
break;
}
}
}
return newLine;
}
protected String[] insertStringArray(final String[] oldS, final String[] inS, final int where)
{
final String[] newLine=new String[oldS.length+inS.length-1];
for(int i=0;i<where;i++)
newLine[i]=oldS[i];
for(int i=0;i<inS.length;i++)
newLine[where+i]=inS[i];
for(int i=where+1;i<oldS.length;i++)
newLine[inS.length+i-1]=oldS[i];
return newLine;
}
/*
* c=clean bit, r=pastbitclean, p=pastbit, s=remaining clean bits, t=trigger
*/
protected String[] parseBits(final String[][] oldBits, final int start, final String instructions)
{
final String[] tt=oldBits[0];
final String parseMe=tt[start];
final String[] parsed=parseBits(parseMe,instructions);
if(parsed.length==1)
{
tt[start]=parsed[0];
return tt;
}
final String[] newLine=insertStringArray(tt,parsed,start);
oldBits[0]=newLine;
return newLine;
}
@Override
public boolean endQuest(final PhysicalAgent hostObj, final MOB mob, final String quest)
{
if(mob!=null)
{
final List<DVector> scripts=getScripts();
if(!mob.amDead())
{
lastKnownLocation=mob.location();
if(homeKnownLocation==null)
homeKnownLocation=lastKnownLocation;
}
String trigger="";
String[] tt=null;
for(int v=0;v<scripts.size();v++)
{
final DVector script=scripts.get(v);
if(script.size()>0)
{
trigger=((String)script.elementAt(0,1)).toUpperCase().trim();
tt=(String[])script.elementAt(0,2);
if((getTriggerCode(trigger,tt)==13) //questtimeprog quest_time_prog
&&(!oncesDone.contains(script)))
{
if(tt==null)
tt=parseBits(script,0,"CCC");
if((tt!=null)
&&((tt[1].equals(quest)||(tt[1].equals("*"))))
&&(CMath.s_int(tt[2])<0))
{
oncesDone.add(script);
execute(hostObj,mob,mob,mob,null,null,script,null,newObjs());
return true;
}
}
}
}
}
return false;
}
@Override
public List<String> externalFiles()
{
final Vector<String> xmlfiles=new Vector<String>();
parseLoads(getScript(), 0, xmlfiles, null);
return xmlfiles;
}
protected String getVarHost(final Environmental E,
String rawHost,
final MOB source,
final Environmental target,
final PhysicalAgent scripted,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final String msg,
final Object[] tmp)
{
if(!rawHost.equals("*"))
{
if(E==null)
rawHost=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,rawHost);
else
if(E instanceof Room)
rawHost=CMLib.map().getExtendedRoomID((Room)E);
else
rawHost=E.Name();
}
return rawHost;
}
@SuppressWarnings("unchecked")
@Override
public boolean isVar(final String host, String var)
{
if(host.equalsIgnoreCase("*"))
{
String val=null;
Hashtable<String,String> H=null;
String key=null;
var=var.toUpperCase();
for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();)
{
key=k.next();
if(key.startsWith("SCRIPTVAR-"))
{
H=(Hashtable<String,String>)resources._getResource(key);
val=H.get(var);
if(val!=null)
return true;
}
}
return false;
}
final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+host);
String val=null;
if(H!=null)
val=H.get(var.toUpperCase());
return (val!=null);
}
public String getVar(final Environmental E, final String rawHost, final String var, final MOB source, final Environmental target,
final PhysicalAgent scripted, final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg,
final Object[] tmp)
{
return getVar(getVarHost(E,rawHost,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp),var);
}
@Override
public String getVar(final String host, final String var)
{
String varVal = getVar(resources,host,var,null);
if(varVal != null)
return varVal;
if((this.defaultQuestName!=null)&&(this.defaultQuestName.length()>0))
{
final Resources questResources=(Resources)Resources.getResource("VARSCOPE-"+this.defaultQuestName);
if((questResources != null)&&(resources!=questResources))
{
varVal = getVar(questResources,host,var,null);
if(varVal != null)
return varVal;
}
}
if(resources == Resources.instance())
return "";
return getVar(Resources.instance(),host,var,"");
}
@SuppressWarnings("unchecked")
public String getVar(final Resources resources, final String host, String var, final String defaultVal)
{
if(host.equalsIgnoreCase("*"))
{
if(var.equals("COFFEEMUD_SYSTEM_INTERNAL_NONFILENAME_SCRIPT"))
{
final StringBuffer str=new StringBuffer("");
parseLoads(getScript(),0,null,str);
return str.toString();
}
String val=null;
Hashtable<String,String> H=null;
String key=null;
var=var.toUpperCase();
for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();)
{
key=k.next();
if(key.startsWith("SCRIPTVAR-"))
{
H=(Hashtable<String,String>)resources._getResource(key);
val=H.get(var);
if(val!=null)
return val;
}
}
return defaultVal;
}
Resources.instance();
final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+host);
String val=null;
if(H!=null)
val=H.get(var.toUpperCase());
else
if((defaultQuestName!=null)&&(defaultQuestName.length()>0))
{
final MOB M=CMLib.players().getPlayerAllHosts(host);
if(M!=null)
{
for(final Enumeration<ScriptingEngine> e=M.scripts();e.hasMoreElements();)
{
final ScriptingEngine SE=e.nextElement();
if((SE!=null)
&&(SE!=this)
&&(defaultQuestName.equalsIgnoreCase(SE.defaultQuestName()))
&&(SE.isVar(host,var)))
return SE.getVar(host,var);
}
}
}
if(val==null)
return defaultVal;
return val;
}
private StringBuffer getResourceFileData(final String named, final boolean showErrors)
{
final Quest Q=getQuest("*");
if(Q!=null)
return Q.getResourceFileData(named, showErrors);
return new CMFile(Resources.makeFileResourceName(named),null,CMFile.FLAG_LOGERRORS).text();
}
@Override
public String getScript()
{
return myScript;
}
public void reset()
{
que = new Vector<ScriptableResponse>();
lastToHurtMe = null;
lastKnownLocation= null;
homeKnownLocation=null;
altStatusTickable= null;
oncesDone = new Vector<DVector>();
delayTargetTimes = new Hashtable<Integer,Integer>();
delayProgCounters= new Hashtable<Integer,int[]>();
lastTimeProgsDone= new Hashtable<Integer,Integer>();
lastDayProgsDone = new Hashtable<Integer,Integer>();
registeredEvents = new HashSet<Integer>();
noTrigger = new Hashtable<Integer,Long>();
backupMOB = null;
lastMsg = null;
bumpUpCache();
}
@Override
public void setScript(String newParms)
{
newParms=CMStrings.replaceAll(newParms,"'","`");
if(newParms.startsWith("+"))
{
final String superParms=getScript();
Resources.removeResource(getScriptResourceKey());
newParms=superParms+";"+newParms.substring(1);
}
myScript=newParms;
if(myScript.length()>100)
scriptKey="PARSEDPRG: "+myScript.substring(0,100)+myScript.length()+myScript.hashCode();
else
scriptKey="PARSEDPRG: "+myScript;
reset();
}
public boolean isFreeToBeTriggered(final Tickable affecting)
{
if(alwaysTriggers)
return CMLib.flags().canActAtAll(affecting);
else
return CMLib.flags().canFreelyBehaveNormal(affecting);
}
protected String parseLoads(final String text, final int depth, final Vector<String> filenames, final StringBuffer nonFilenameScript)
{
final StringBuffer results=new StringBuffer("");
String parse=text;
if(depth>10) return ""; // no including off to infinity
String p=null;
while(parse.length()>0)
{
final int y=parse.toUpperCase().indexOf("LOAD=");
if(y>=0)
{
p=parse.substring(0,y).trim();
if((!p.endsWith(";"))
&&(!p.endsWith("\n"))
&&(!p.endsWith("~"))
&&(!p.endsWith("\r"))
&&(p.length()>0))
{
if(nonFilenameScript!=null)
nonFilenameScript.append(parse.substring(0,y+1));
results.append(parse.substring(0,y+1));
parse=parse.substring(y+1);
continue;
}
results.append(p+"\n");
int z=parse.indexOf('~',y);
while((z>0)&&(parse.charAt(z-1)=='\\'))
z=parse.indexOf('~',z+1);
if(z>0)
{
final String filename=parse.substring(y+5,z).trim();
parse=parse.substring(z+1);
if((filenames!=null)&&(!filenames.contains(filename)))
filenames.addElement(filename);
results.append(parseLoads(getResourceFileData(filename, true).toString(),depth+1,filenames,null));
}
else
{
final String filename=parse.substring(y+5).trim();
if((filenames!=null)&&(!filenames.contains(filename)))
filenames.addElement(filename);
results.append(parseLoads(getResourceFileData(filename, true).toString(),depth+1,filenames,null));
break;
}
}
else
{
if(nonFilenameScript!=null)
nonFilenameScript.append(parse);
results.append(parse);
break;
}
}
return results.toString();
}
protected void buildHashes()
{
if(funcH.size()==0)
{
synchronized(funcH)
{
if(funcH.size()==0)
{
for(int i=0;i<funcs.length;i++)
funcH.put(funcs[i],Integer.valueOf(i+1));
for(int i=0;i<methods.length;i++)
methH.put(methods[i],Integer.valueOf(i+1));
for(int i=0;i<progs.length;i++)
progH.put(progs[i],Integer.valueOf(i+1));
for(int i=0;i<progs.length;i++)
methH.put(progs[i],Integer.valueOf(Integer.MIN_VALUE));
for(int i=0;i<CONNECTORS.length;i++)
connH.put(CONNECTORS[i],Integer.valueOf(i));
for(int i=0;i<SIGNS.length;i++)
signH.put(SIGNS[i],Integer.valueOf(i));
}
}
}
}
protected List<DVector> parseScripts(String text)
{
buildHashes();
while((text.length()>0)
&&(Character.isWhitespace(text.charAt(0))))
text=text.substring(1);
boolean staticSet=false;
if((text.length()>10)
&&(text.substring(0,10).toUpperCase().startsWith("STATIC=")))
{
staticSet=true;
text=text.substring(7);
}
text=parseLoads(text,0,null,null);
if(staticSet)
{
text=CMStrings.replaceAll(text,"'","`");
myScript=text;
reset();
}
final List<List<String>> V = CMParms.parseDoubleDelimited(text,'~',';');
final Vector<DVector> V2=new Vector<DVector>(3);
for(final List<String> ls : V)
{
final DVector DV=new DVector(3);
for(final String s : ls)
DV.addElement(s,null,null);
V2.add(DV);
}
return V2;
}
protected Room getRoom(final String thisName, final Room imHere)
{
if(thisName.length()==0)
return null;
if(imHere!=null)
{
if(imHere.roomID().equalsIgnoreCase(thisName))
return imHere;
if((thisName.startsWith("#"))&&(CMath.isLong(thisName.substring(1))))
return CMLib.map().getRoom(imHere.getArea().Name()+thisName);
if(Character.isDigit(thisName.charAt(0))&&(CMath.isLong(thisName)))
return CMLib.map().getRoom(imHere.getArea().Name()+"#"+thisName);
}
final Room room=CMLib.map().getRoom(thisName);
if((room!=null)&&(room.roomID().equalsIgnoreCase(thisName)))
{
if(CMath.bset(room.getArea().flags(),Area.FLAG_INSTANCE_PARENT)
&&(imHere!=null)
&&(CMath.bset(imHere.getArea().flags(),Area.FLAG_INSTANCE_CHILD))
&&(imHere.getArea().Name().endsWith("_"+room.getArea().Name()))
&&(thisName.indexOf('#')>=0))
{
final Room otherRoom=CMLib.map().getRoom(imHere.getArea().Name()+thisName.substring(thisName.indexOf('#')));
if((otherRoom!=null)&&(otherRoom.roomID().endsWith(thisName)))
return otherRoom;
}
return room;
}
List<Room> rooms=new Vector<Room>(1);
if((imHere!=null)&&(imHere.getArea()!=null))
rooms=CMLib.map().findAreaRoomsLiberally(null, imHere.getArea(), thisName, "RIEPM",100);
if(rooms.size()==0)
{
if(debugBadScripts)
Log.debugOut("ScriptingEngine","World room search called for: "+thisName);
rooms=CMLib.map().findWorldRoomsLiberally(null,thisName, "RIEPM",100,2000);
}
if(rooms.size()>0)
return rooms.get(CMLib.dice().roll(1,rooms.size(),-1));
if(room == null)
{
final int x=thisName.indexOf('@');
if(x>0)
{
Room R=CMLib.map().getRoom(thisName.substring(x+1));
if((R==null)||(R==imHere))
{
final Area A=CMLib.map().getArea(thisName.substring(x+1));
R=(A!=null)?A.getRandomMetroRoom():null;
}
if((R!=null)&&(R!=imHere))
return getRoom(thisName.substring(0,x),R);
}
}
return room;
}
protected void logError(final Environmental scripted, final String cmdName, final String errType, final String errMsg)
{
if(scripted!=null)
{
final Room R=CMLib.map().roomLocation(scripted);
String scriptFiles=CMParms.toListString(externalFiles());
if((scriptFiles == null)||(scriptFiles.trim().length()==0))
scriptFiles=CMStrings.limit(this.getScript(),80);
if((scriptFiles == null)||(scriptFiles.trim().length()==0))
Log.errOut(new Exception("Scripting Error"));
if((scriptFiles == null)||(scriptFiles.trim().length()==0))
scriptFiles=getScriptResourceKey();
Log.errOut("Scripting",scripted.name()+"/"+CMLib.map().getDescriptiveExtendedRoomID(R)+"/"+ cmdName+"/"+errType+"/"+errMsg+"/"+scriptFiles);
if(R!=null)
R.showHappens(CMMsg.MSG_OK_VISUAL,L("Scripting Error: @x1/@x2/@x3/@x4/@x5/@x6",scripted.name(),CMLib.map().getExtendedRoomID(R),cmdName,errType,errMsg,scriptFiles));
}
else
Log.errOut("Scripting","*/*/"+CMParms.toListString(externalFiles())+"/"+cmdName+"/"+errType+"/"+errMsg);
}
protected boolean simpleEvalStr(final Environmental scripted, final String arg1, final String arg2, final String cmp, final String cmdName)
{
final int x=arg1.compareToIgnoreCase(arg2);
final Integer SIGN=signH.get(cmp);
if(SIGN==null)
{
logError(scripted,cmdName,"Syntax",arg1+" "+cmp+" "+arg2);
return false;
}
switch(SIGN.intValue())
{
case SIGN_EQUL:
return (x == 0);
case SIGN_EQGT:
case SIGN_GTEQ:
return (x == 0) || (x > 0);
case SIGN_EQLT:
case SIGN_LTEQ:
return (x == 0) || (x < 0);
case SIGN_GRAT:
return (x > 0);
case SIGN_LEST:
return (x < 0);
case SIGN_NTEQ:
return (x != 0);
default:
return (x == 0);
}
}
protected boolean simpleEval(final Environmental scripted, final String arg1, final String arg2, final String cmp, final String cmdName)
{
final long val1=CMath.s_long(arg1.trim());
final long val2=CMath.s_long(arg2.trim());
final Integer SIGN=signH.get(cmp);
if(SIGN==null)
{
logError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2);
return false;
}
switch(SIGN.intValue())
{
case SIGN_EQUL:
return (val1 == val2);
case SIGN_EQGT:
case SIGN_GTEQ:
return val1 >= val2;
case SIGN_EQLT:
case SIGN_LTEQ:
return val1 <= val2;
case SIGN_GRAT:
return (val1 > val2);
case SIGN_LEST:
return (val1 < val2);
case SIGN_NTEQ:
return (val1 != val2);
default:
return (val1 == val2);
}
}
protected boolean simpleExpressionEval(final Environmental scripted, final String arg1, final String arg2, final String cmp, final String cmdName)
{
final double val1=CMath.s_parseMathExpression(arg1.trim());
final double val2=CMath.s_parseMathExpression(arg2.trim());
final Integer SIGN=signH.get(cmp);
if(SIGN==null)
{
logError(scripted,cmdName,"Syntax",val1+" "+cmp+" "+val2);
return false;
}
switch(SIGN.intValue())
{
case SIGN_EQUL:
return (val1 == val2);
case SIGN_EQGT:
case SIGN_GTEQ:
return val1 >= val2;
case SIGN_EQLT:
case SIGN_LTEQ:
return val1 <= val2;
case SIGN_GRAT:
return (val1 > val2);
case SIGN_LEST:
return (val1 < val2);
case SIGN_NTEQ:
return (val1 != val2);
default:
return (val1 == val2);
}
}
protected List<MOB> loadMobsFromFile(final Environmental scripted, String filename)
{
filename=filename.trim();
@SuppressWarnings("unchecked")
List<MOB> monsters=(List<MOB>)Resources.getResource("RANDOMMONSTERS-"+filename);
if(monsters!=null)
return monsters;
final StringBuffer buf=getResourceFileData(filename, true);
String thangName="null";
final Room R=CMLib.map().roomLocation(scripted);
if(R!=null)
thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted);
else
if(scripted!=null)
thangName=scripted.name();
if((buf==null)||(buf.length()<20))
{
logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName);
return null;
}
final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString());
monsters=new Vector<MOB>();
if(xml!=null)
{
if(CMLib.xml().getContentsFromPieces(xml,"MOBS")!=null)
{
final String error=CMLib.coffeeMaker().addMOBsFromXML(xml,monsters,null);
if(error.length()>0)
{
logError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"'");
return null;
}
if(monsters.size()<=0)
{
logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'");
return null;
}
Resources.submitResource("RANDOMMONSTERS-"+filename,monsters);
for(final Object O : monsters)
{
if(O instanceof MOB)
CMLib.threads().deleteAllTicks((MOB)O);
}
}
else
{
logError(scripted,"XMLLOAD","?","No MOBs in XML file: '"+filename+"' in "+thangName);
return null;
}
}
else
{
logError(scripted,"XMLLOAD","?","Invalid XML file: '"+filename+"' in "+thangName);
return null;
}
return monsters;
}
protected List<MOB> generateMobsFromFile(final Environmental scripted, String filename, final String tagName, final String rest)
{
filename=filename.trim();
@SuppressWarnings("unchecked")
List<MOB> monsters=(List<MOB>)Resources.getResource("RANDOMGENMONSTERS-"+filename+"."+tagName+"-"+rest);
if(monsters!=null)
return monsters;
final StringBuffer buf=getResourceFileData(filename, true);
String thangName="null";
final Room R=CMLib.map().roomLocation(scripted);
if(R!=null)
thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted);
else
if(scripted!=null)
thangName=scripted.name();
if((buf==null)||(buf.length()<20))
{
logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName);
return null;
}
final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString());
monsters=new Vector<MOB>();
if(xml!=null)
{
if(CMLib.xml().getContentsFromPieces(xml,"AREADATA")!=null)
{
final Hashtable<String,Object> definedIDs = new Hashtable<String,Object>();
final Map<String,String> eqParms=new HashMap<String,String>();
eqParms.putAll(CMParms.parseEQParms(rest.trim()));
final String idName=tagName.toUpperCase();
try
{
CMLib.percolator().buildDefinedIDSet(xml,definedIDs, new TreeSet<String>());
if((!(definedIDs.get(idName) instanceof XMLTag))
||(!((XMLTag)definedIDs.get(idName)).tag().equalsIgnoreCase("MOB")))
{
logError(scripted,"XMLLOAD","?","Non-MOB tag '"+idName+"' for XML file: '"+filename+"' in "+thangName);
return null;
}
final XMLTag piece=(XMLTag)definedIDs.get(idName);
definedIDs.putAll(eqParms);
try
{
CMLib.percolator().checkRequirements(piece, definedIDs);
}
catch(final CMException cme)
{
logError(scripted,"XMLLOAD","?","Required ids for "+idName+" were missing for XML file: '"+filename+"' in "+thangName+": "+cme.getMessage());
return null;
}
CMLib.percolator().preDefineReward(piece, definedIDs);
CMLib.percolator().defineReward(piece,definedIDs);
monsters.addAll(CMLib.percolator().findMobs(piece, definedIDs));
CMLib.percolator().postProcess(definedIDs);
if(monsters.size()<=0)
{
logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'");
return null;
}
Resources.submitResource("RANDOMGENMONSTERS-"+filename+"."+tagName+"-"+rest,monsters);
}
catch(final CMException cex)
{
logError(scripted,"XMLLOAD","?","Unable to generate "+idName+" from XML file: '"+filename+"' in "+thangName+": "+cex.getMessage());
return null;
}
}
else
{
logError(scripted,"XMLLOAD","?","Invalid GEN XML file: '"+filename+"' in "+thangName);
return null;
}
}
else
{
logError(scripted,"XMLLOAD","?","Empty or Invalid XML file: '"+filename+"' in "+thangName);
return null;
}
return monsters;
}
protected List<Item> loadItemsFromFile(final Environmental scripted, String filename)
{
filename=filename.trim();
@SuppressWarnings("unchecked")
List<Item> items=(List<Item>)Resources.getResource("RANDOMITEMS-"+filename);
if(items!=null)
return items;
final StringBuffer buf=getResourceFileData(filename, true);
String thangName="null";
final Room R=CMLib.map().roomLocation(scripted);
if(R!=null)
thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted);
else
if(scripted!=null)
thangName=scripted.name();
if((buf==null)||(buf.length()<20))
{
logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName);
return null;
}
items=new Vector<Item>();
final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString());
if(xml!=null)
{
if(CMLib.xml().getContentsFromPieces(xml,"ITEMS")!=null)
{
final String error=CMLib.coffeeMaker().addItemsFromXML(buf.toString(),items,null);
if(error.length()>0)
{
logError(scripted,"XMLLOAD","?","Error in XML file: '"+filename+"' in "+thangName);
return null;
}
if(items.size()<=0)
{
logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"'");
return null;
}
for(final Object O : items)
{
if(O instanceof Item)
CMLib.threads().deleteTick((Item)O, -1);
}
Resources.submitResource("RANDOMITEMS-"+filename,items);
}
else
{
logError(scripted,"XMLLOAD","?","No ITEMS in XML file: '"+filename+"' in "+thangName);
return null;
}
}
else
{
logError(scripted,"XMLLOAD","?","Empty or invalid XML file: '"+filename+"' in "+thangName);
return null;
}
return items;
}
protected List<Item> generateItemsFromFile(final Environmental scripted, String filename, final String tagName, final String rest)
{
filename=filename.trim();
@SuppressWarnings("unchecked")
List<Item> items=(List<Item>)Resources.getResource("RANDOMGENITEMS-"+filename+"."+tagName+"-"+rest);
if(items!=null)
return items;
final StringBuffer buf=getResourceFileData(filename, true);
String thangName="null";
final Room R=CMLib.map().roomLocation(scripted);
if(R!=null)
thangName=scripted.name()+" at "+CMLib.map().getExtendedRoomID((Room)scripted);
else
if(scripted!=null)
thangName=scripted.name();
if((buf==null)||(buf.length()<20))
{
logError(scripted,"XMLLOAD","?","Unknown XML file: '"+filename+"' in "+thangName);
return null;
}
items=new Vector<Item>();
final List<XMLLibrary.XMLTag> xml=CMLib.xml().parseAllXML(buf.toString());
if(xml!=null)
{
if(CMLib.xml().getContentsFromPieces(xml,"AREADATA")!=null)
{
final Hashtable<String,Object> definedIDs = new Hashtable<String,Object>();
final Map<String,String> eqParms=new HashMap<String,String>();
eqParms.putAll(CMParms.parseEQParms(rest.trim()));
final String idName=tagName.toUpperCase();
try
{
CMLib.percolator().buildDefinedIDSet(xml,definedIDs, new TreeSet<String>());
if((!(definedIDs.get(idName) instanceof XMLTag))
||(!((XMLTag)definedIDs.get(idName)).tag().equalsIgnoreCase("ITEM")))
{
logError(scripted,"XMLLOAD","?","Non-ITEM tag '"+idName+"' for XML file: '"+filename+"' in "+thangName);
return null;
}
final XMLTag piece=(XMLTag)definedIDs.get(idName);
definedIDs.putAll(eqParms);
try
{
CMLib.percolator().checkRequirements(piece, definedIDs);
}
catch(final CMException cme)
{
logError(scripted,"XMLLOAD","?","Required ids for "+idName+" were missing for XML file: '"+filename+"' in "+thangName+": "+cme.getMessage());
return null;
}
CMLib.percolator().preDefineReward(piece, definedIDs);
CMLib.percolator().defineReward(piece,definedIDs);
items.addAll(CMLib.percolator().findItems(piece, definedIDs));
CMLib.percolator().postProcess(definedIDs);
if(items.size()<=0)
{
logError(scripted,"XMLLOAD","?","Empty XML file: '"+filename+"' in "+thangName);
return null;
}
Resources.submitResource("RANDOMGENITEMS-"+filename+"."+tagName+"-"+rest,items);
}
catch(final CMException cex)
{
logError(scripted,"XMLLOAD","?","Unable to generate "+idName+" from XML file: '"+filename+"' in "+thangName+": "+cex.getMessage());
return null;
}
}
else
{
logError(scripted,"XMLLOAD","?","Not a GEN XML file: '"+filename+"' in "+thangName);
return null;
}
}
else
{
logError(scripted,"XMLLOAD","?","Empty or Invalid XML file: '"+filename+"' in "+thangName);
return null;
}
return items;
}
@SuppressWarnings("unchecked")
protected Environmental findSomethingCalledThis(final String thisName, final MOB meMOB, final Room imHere, List<Environmental> OBJS, final boolean mob)
{
if(thisName.length()==0)
return null;
Environmental thing=null;
Environmental areaThing=null;
if(thisName.toUpperCase().trim().startsWith("FROMFILE "))
{
try
{
List<? extends Environmental> V=null;
if(mob)
V=loadMobsFromFile(null,CMParms.getCleanBit(thisName,1));
else
V=loadItemsFromFile(null,CMParms.getCleanBit(thisName,1));
if(V!=null)
{
final String name=CMParms.getPastBitClean(thisName,1);
if(name.equalsIgnoreCase("ALL"))
OBJS=(List<Environmental>)V;
else
if(name.equalsIgnoreCase("ANY"))
{
if(V.size()>0)
areaThing=V.get(CMLib.dice().roll(1,V.size(),-1));
}
else
{
areaThing=CMLib.english().fetchEnvironmental(V,name,true);
if(areaThing==null)
areaThing=CMLib.english().fetchEnvironmental(V,name,false);
}
}
}
catch(final Exception e)
{
}
}
else
if(thisName.toUpperCase().trim().startsWith("FROMGENFILE "))
{
try
{
List<? extends Environmental> V=null;
final String filename=CMParms.getCleanBit(thisName, 1);
final String name=CMParms.getCleanBit(thisName, 2);
final String tagName=CMParms.getCleanBit(thisName, 3);
final String theRest=CMParms.getPastBitClean(thisName,3);
if(mob)
V=generateMobsFromFile(null,filename, tagName, theRest);
else
V=generateItemsFromFile(null,filename, tagName, theRest);
if(V!=null)
{
if(name.equalsIgnoreCase("ALL"))
OBJS=(List<Environmental>)V;
else
if(name.equalsIgnoreCase("ANY"))
{
if(V.size()>0)
areaThing=V.get(CMLib.dice().roll(1,V.size(),-1));
}
else
{
areaThing=CMLib.english().fetchEnvironmental(V,name,true);
if(areaThing==null)
areaThing=CMLib.english().fetchEnvironmental(V,name,false);
}
}
}
catch(final Exception e)
{
}
}
else
{
if(!mob)
areaThing=(meMOB!=null)?meMOB.findItem(thisName):null;
try
{
if(areaThing==null)
{
final Area A=imHere.getArea();
final Vector<Environmental> all=new Vector<Environmental>();
if(mob)
{
all.addAll(CMLib.map().findInhabitants(A.getProperMap(),null,thisName,100));
if(all.size()==0)
all.addAll(CMLib.map().findShopStock(A.getProperMap(), null, thisName,100));
for(int a=all.size()-1;a>=0;a--)
{
if(!(all.elementAt(a) instanceof MOB))
all.removeElementAt(a);
}
if(all.size()>0)
areaThing=all.elementAt(CMLib.dice().roll(1,all.size(),-1));
else
{
all.addAll(CMLib.map().findInhabitantsFavorExact(CMLib.map().rooms(),null,thisName,false,100));
if(all.size()==0)
all.addAll(CMLib.map().findShopStock(CMLib.map().rooms(), null, thisName,100));
for(int a=all.size()-1;a>=0;a--)
{
if(!(all.elementAt(a) instanceof MOB))
all.removeElementAt(a);
}
if(all.size()>0)
thing=all.elementAt(CMLib.dice().roll(1,all.size(),-1));
}
}
if(all.size()==0)
{
all.addAll(CMLib.map().findRoomItems(A.getProperMap(), null,thisName,true,100));
if(all.size()==0)
all.addAll(CMLib.map().findInventory(A.getProperMap(), null,thisName,100));
if(all.size()==0)
all.addAll(CMLib.map().findShopStock(A.getProperMap(), null,thisName,100));
if(all.size()>0)
areaThing=all.elementAt(CMLib.dice().roll(1,all.size(),-1));
else
{
all.addAll(CMLib.map().findRoomItems(CMLib.map().rooms(), null,thisName,true,100));
if(all.size()==0)
all.addAll(CMLib.map().findInventory(CMLib.map().rooms(), null,thisName,100));
if(all.size()==0)
all.addAll(CMLib.map().findShopStock(CMLib.map().rooms(), null,thisName,100));
if(all.size()>0)
thing=all.elementAt(CMLib.dice().roll(1,all.size(),-1));
}
}
}
}
catch(final NoSuchElementException nse)
{
}
}
if(areaThing!=null)
OBJS.add(areaThing);
else
if(thing!=null)
OBJS.add(thing);
if(OBJS.size()>0)
return OBJS.get(0);
return null;
}
protected PhysicalAgent getArgumentMOB(final String str,
final MOB source,
final MOB monster,
final Environmental target,
final Item primaryItem,
final Item secondaryItem,
final String msg,
final Object[] tmp)
{
return getArgumentItem(str,source,monster,monster,target,primaryItem,secondaryItem,msg,tmp);
}
protected PhysicalAgent getArgumentItem(String str,
final MOB source,
final MOB monster,
final PhysicalAgent scripted,
final Environmental target,
final Item primaryItem,
final Item secondaryItem,
final String msg,
final Object[] tmp)
{
if(str.length()<2)
return null;
if(str.charAt(0)=='$')
{
if(Character.isDigit(str.charAt(1)))
{
Object O=tmp[CMath.s_int(Character.toString(str.charAt(1)))];
if(O instanceof PhysicalAgent)
return (PhysicalAgent)O;
else
if((O instanceof List)&&(str.length()>3)&&(str.charAt(2)=='.'))
{
final List<?> V=(List<?>)O;
String back=str.substring(2);
if(back.charAt(1)=='$')
back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back);
if((back.length()>1)&&Character.isDigit(back.charAt(1)))
{
int x=1;
while((x<back.length())&&(Character.isDigit(back.charAt(x))))
x++;
final int y=CMath.s_int(back.substring(1,x).trim());
if((V.size()>0)&&(y>=0))
{
if(y>=V.size())
return null;
O=V.get(y);
if(O instanceof PhysicalAgent)
return (PhysicalAgent)O;
}
str=O.toString(); // will fall through
}
}
else
if(O!=null)
str=O.toString(); // will fall through
else
return null;
}
else
switch(str.charAt(1))
{
case 'a':
return (lastKnownLocation != null) ? lastKnownLocation.getArea() : null;
case 'B':
case 'b':
return (lastLoaded instanceof PhysicalAgent) ? (PhysicalAgent) lastLoaded : null;
case 'N':
case 'n':
return ((source == backupMOB) && (backupMOB != null) && (monster != scripted)) ? scripted : source;
case 'I':
case 'i':
return scripted;
case 'T':
case 't':
return ((target == backupMOB) && (backupMOB != null) && (monster != scripted))
? scripted : (target instanceof PhysicalAgent) ? (PhysicalAgent) target : null;
case 'O':
case 'o':
return primaryItem;
case 'P':
case 'p':
return secondaryItem;
case 'd':
case 'D':
return lastKnownLocation;
case 'F':
case 'f':
if ((monster != null) && (monster.amFollowing() != null))
return monster.amFollowing();
return null;
case 'r':
case 'R':
return getRandPC(monster, tmp, lastKnownLocation);
case 'c':
case 'C':
return getRandAnyone(monster, tmp, lastKnownLocation);
case 'w':
return primaryItem != null ? primaryItem.owner() : null;
case 'W':
return secondaryItem != null ? secondaryItem.owner() : null;
case 'x':
case 'X':
if (lastKnownLocation != null)
{
if ((str.length() > 2) && (CMLib.directions().getGoodDirectionCode("" + str.charAt(2)) >= 0))
return lastKnownLocation.getExitInDir(CMLib.directions().getGoodDirectionCode("" + str.charAt(2)));
int i = 0;
Exit E = null;
while (((++i) < 100) || (E != null))
E = lastKnownLocation.getExitInDir(CMLib.dice().roll(1, Directions.NUM_DIRECTIONS(), -1));
return E;
}
return null;
case '[':
{
final int x = str.substring(2).indexOf(']');
if (x >= 0)
{
String mid = str.substring(2).substring(0, x);
final int y = mid.indexOf(' ');
if (y > 0)
{
final int num = CMath.s_int(mid.substring(0, y).trim());
mid = mid.substring(y + 1).trim();
final Quest Q = getQuest(mid);
if (Q != null)
return Q.getQuestItem(num);
}
}
break;
}
case '{':
{
final int x = str.substring(2).indexOf('}');
if (x >= 0)
{
String mid = str.substring(2).substring(0, x).trim();
final int y = mid.indexOf(' ');
if (y > 0)
{
final int num = CMath.s_int(mid.substring(0, y).trim());
mid = mid.substring(y + 1).trim();
final Quest Q = getQuest(mid);
if (Q != null)
{
final MOB M=Q.getQuestMob(num);
return M;
}
}
}
break;
}
}
}
if(lastKnownLocation!=null)
{
str=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,str);
Environmental E=null;
if(str.indexOf('#')>0)
E=CMLib.map().getRoom(str);
if(E==null)
E=lastKnownLocation.fetchFromRoomFavorMOBs(null,str);
if(E==null)
E=lastKnownLocation.fetchFromMOBRoomFavorsItems(monster,null,str,Wearable.FILTER_ANY);
if(E==null)
E=lastKnownLocation.findItem(str);
if((E==null)&&(monster!=null))
E=monster.findItem(str);
if(E==null)
E=CMLib.players().getPlayerAllHosts(str);
if((E==null)&&(source!=null))
E=source.findItem(str);
if(E instanceof PhysicalAgent)
return (PhysicalAgent)E;
}
return null;
}
private String makeNamedString(final Object O)
{
if(O instanceof List)
return makeParsableString((List<?>)O);
else
if(O instanceof Room)
return ((Room)O).displayText(null);
else
if(O instanceof Environmental)
return ((Environmental)O).Name();
else
if(O!=null)
return O.toString();
return "";
}
private String makeParsableString(final List<?> V)
{
if((V==null)||(V.size()==0))
return "";
if(V.get(0) instanceof String)
return CMParms.combineQuoted(V,0);
final StringBuffer ret=new StringBuffer("");
String S=null;
for(int v=0;v<V.size();v++)
{
S=makeNamedString(V.get(v)).trim();
if(S.length()==0)
ret.append("? ");
else
if(S.indexOf(' ')>=0)
ret.append("\""+S+"\" ");
else
ret.append(S+" ");
}
return ret.toString();
}
@Override
public String varify(final MOB source,
final Environmental target,
final PhysicalAgent scripted,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final String msg,
final Object[] tmp,
String varifyable)
{
int t=varifyable.indexOf('$');
if((monster!=null)&&(monster.location()!=null))
lastKnownLocation=monster.location();
if(lastKnownLocation==null)
{
lastKnownLocation=source.location();
if(homeKnownLocation==null)
homeKnownLocation=lastKnownLocation;
}
else
if(homeKnownLocation==null)
homeKnownLocation=lastKnownLocation;
MOB randMOB=null;
while((t>=0)&&(t<varifyable.length()-1))
{
final char c=varifyable.charAt(t+1);
String middle="";
final String front=varifyable.substring(0,t);
String back=varifyable.substring(t+2);
if(Character.isDigit(c))
middle=makeNamedString(tmp[CMath.s_int(Character.toString(c))]);
else
switch(c)
{
case '@':
if ((t < varifyable.length() - 2)
&& (Character.isLetter(varifyable.charAt(t + 2))||Character.isDigit(varifyable.charAt(t + 2))))
{
final Environmental E = getArgumentItem("$" + varifyable.charAt(t + 2),
source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(back.length()>0)
back=back.substring(1);
middle = (E == null) ? "null" : "" + E;
}
break;
case 'a':
if (lastKnownLocation != null)
middle = lastKnownLocation.getArea().name();
break;
// case 'a':
case 'A':
// unnecessary, since, in coffeemud, this is part of the
// name
break;
case 'b':
middle = lastLoaded != null ? lastLoaded.name() : "";
break;
case 'B':
middle = lastLoaded != null ? lastLoaded.displayText() : "";
break;
case 'c':
case 'C':
randMOB = getRandAnyone(monster, tmp, lastKnownLocation);
if (randMOB != null)
middle = randMOB.name();
break;
case 'd':
middle = (lastKnownLocation != null) ? lastKnownLocation.displayText(monster) : "";
break;
case 'D':
middle = (lastKnownLocation != null) ? lastKnownLocation.description(monster) : "";
break;
case 'e':
if (source != null)
middle = source.charStats().heshe();
break;
case 'E':
if ((target != null) && (target instanceof MOB))
middle = ((MOB) target).charStats().heshe();
break;
case 'f':
if ((monster != null) && (monster.amFollowing() != null))
middle = monster.amFollowing().name();
break;
case 'F':
if ((monster != null) && (monster.amFollowing() != null))
middle = monster.amFollowing().charStats().heshe();
break;
case 'g':
middle = ((msg == null) ? "" : msg.toLowerCase());
break;
case 'G':
middle = ((msg == null) ? "" : msg);
break;
case 'h':
if (monster != null)
middle = monster.charStats().himher();
break;
case 'H':
randMOB = getRandPC(monster, tmp, lastKnownLocation);
if (randMOB != null)
middle = randMOB.charStats().himher();
break;
case 'i':
if (monster != null)
middle = monster.name();
break;
case 'I':
if (monster != null)
middle = monster.displayText();
break;
case 'j':
if (monster != null)
middle = monster.charStats().heshe();
break;
case 'J':
randMOB = getRandPC(monster, tmp, lastKnownLocation);
if (randMOB != null)
middle = randMOB.charStats().heshe();
break;
case 'k':
if (monster != null)
middle = monster.charStats().hisher();
break;
case 'K':
randMOB = getRandPC(monster, tmp, lastKnownLocation);
if (randMOB != null)
middle = randMOB.charStats().hisher();
break;
case 'l':
if (lastKnownLocation != null)
{
final StringBuffer str = new StringBuffer("");
for (int i = 0; i < lastKnownLocation.numInhabitants(); i++)
{
final MOB M = lastKnownLocation.fetchInhabitant(i);
if ((M != null) && (M != monster) && (CMLib.flags().canBeSeenBy(M, monster)))
str.append("\"" + M.name() + "\" ");
}
middle = str.toString();
}
break;
case 'L':
if (lastKnownLocation != null)
{
final StringBuffer str = new StringBuffer("");
for (int i = 0; i < lastKnownLocation.numItems(); i++)
{
final Item I = lastKnownLocation.getItem(i);
if ((I != null) && (I.container() == null) && (CMLib.flags().canBeSeenBy(I, monster)))
str.append("\"" + I.name() + "\" ");
}
middle = str.toString();
}
break;
case 'm':
if (source != null)
middle = source.charStats().hisher();
break;
case 'M':
if ((target != null) && (target instanceof MOB))
middle = ((MOB) target).charStats().hisher();
break;
case 'n':
case 'N':
if (source != null)
middle = source.name();
break;
case 'o':
case 'O':
if (primaryItem != null)
middle = primaryItem.name();
break;
case 'p':
case 'P':
if (secondaryItem != null)
middle = secondaryItem.name();
break;
case 'r':
case 'R':
randMOB = getRandPC(monster, tmp, lastKnownLocation);
if (randMOB != null)
middle = randMOB.name();
break;
case 's':
if (source != null)
middle = source.charStats().himher();
break;
case 'S':
if ((target != null) && (target instanceof MOB))
middle = ((MOB) target).charStats().himher();
break;
case 't':
case 'T':
if (target != null)
middle = target.name();
break;
case 'w':
middle = primaryItem != null ? primaryItem.owner().Name() : middle;
break;
case 'W':
middle = secondaryItem != null ? secondaryItem.owner().Name() : middle;
break;
case 'x':
case 'X':
if (lastKnownLocation != null)
{
middle = "";
Exit E = null;
int dir = -1;
if ((t < varifyable.length() - 2) && (CMLib.directions().getGoodDirectionCode("" + varifyable.charAt(t + 2)) >= 0))
{
dir = CMLib.directions().getGoodDirectionCode("" + varifyable.charAt(t + 2));
E = lastKnownLocation.getExitInDir(dir);
}
else
{
int i = 0;
while (((++i) < 100) || (E != null))
{
dir = CMLib.dice().roll(1, Directions.NUM_DIRECTIONS(), -1);
E = lastKnownLocation.getExitInDir(dir);
}
}
if ((dir >= 0) && (E != null))
{
if (c == 'x')
middle = CMLib.directions().getDirectionName(dir);
else
middle = E.name();
}
}
break;
case 'y':
if (source != null)
middle = source.charStats().sirmadam();
break;
case 'Y':
if ((target != null) && (target instanceof MOB))
middle = ((MOB) target).charStats().sirmadam();
break;
case '<':
{
final int x = back.indexOf('>');
if (x >= 0)
{
String mid = back.substring(0, x);
final int y = mid.indexOf(' ');
Environmental E = null;
String arg1 = "";
if (y >= 0)
{
arg1 = mid.substring(0, y).trim();
E = getArgumentItem(arg1, source, monster, monster, target, primaryItem, secondaryItem, msg, tmp);
mid = mid.substring(y + 1).trim();
}
if (arg1.length() > 0)
middle = getVar(E, arg1, mid, source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp);
back = back.substring(x + 1);
}
break;
}
case '[':
{
middle = "";
final int x = back.indexOf(']');
if (x >= 0)
{
String mid = back.substring(0, x);
final int y = mid.indexOf(' ');
if (y > 0)
{
final int num = CMath.s_int(mid.substring(0, y).trim());
mid = mid.substring(y + 1).trim();
final Quest Q = getQuest(mid);
if (Q != null)
middle = Q.getQuestItemName(num);
}
back = back.substring(x + 1);
}
break;
}
case '{':
{
middle = "";
final int x = back.indexOf('}');
if (x >= 0)
{
String mid = back.substring(0, x).trim();
final int y = mid.indexOf(' ');
if (y > 0)
{
final int num = CMath.s_int(mid.substring(0, y).trim());
mid = mid.substring(y + 1).trim();
final Quest Q = getQuest(mid);
if (Q != null)
middle = Q.getQuestMobName(num);
}
back = back.substring(x + 1);
}
break;
}
case '%':
{
middle = "";
final int x = back.indexOf('%');
if (x >= 0)
{
middle = functify(scripted, source, target, monster, primaryItem, secondaryItem, msg, tmp, back.substring(0, x).trim());
back = back.substring(x + 1);
}
break;
}
}
if((back.startsWith("."))
&&(back.length()>1))
{
if(back.charAt(1)=='$')
back=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,back);
if(back.startsWith(".LENGTH#"))
{
middle=""+CMParms.parse(middle).size();
back=back.substring(8);
}
else
if((back.length()>1)&&Character.isDigit(back.charAt(1)))
{
int x=1;
while((x<back.length())
&&(Character.isDigit(back.charAt(x))))
x++;
final int y=CMath.s_int(back.substring(1,x).trim());
back=back.substring(x);
final boolean rest=back.startsWith("..");
if(rest)
back=back.substring(2);
final Vector<String> V=CMParms.parse(middle);
if((V.size()>0)&&(y>=0))
{
if(y>=V.size())
middle="";
else
if(rest)
middle=CMParms.combine(V,y);
else
middle=V.elementAt(y);
}
}
}
varifyable=front+middle+back;
t=varifyable.indexOf('$');
}
return varifyable;
}
protected PairList<String,String> getScriptVarSet(final String mobname, final String varname)
{
final PairList<String,String> set=new PairVector<String,String>();
if(mobname.equals("*"))
{
for(final Iterator<String> k = resources._findResourceKeys("SCRIPTVAR-");k.hasNext();)
{
final String key=k.next();
if(key.startsWith("SCRIPTVAR-"))
{
@SuppressWarnings("unchecked")
final Hashtable<String,?> H=(Hashtable<String,?>)resources._getResource(key);
if(varname.equals("*"))
{
if(H!=null)
{
for(final Enumeration<String> e=H.keys();e.hasMoreElements();)
{
final String vn=e.nextElement();
set.add(key.substring(10),vn);
}
}
}
else
set.add(key.substring(10),varname);
}
}
}
else
{
@SuppressWarnings("unchecked")
final Hashtable<String,?> H=(Hashtable<String,?>)resources._getResource("SCRIPTVAR-"+mobname);
if(varname.equals("*"))
{
if(H!=null)
{
for(final Enumeration<String> e=H.keys();e.hasMoreElements();)
{
final String vn=e.nextElement();
set.add(mobname,vn);
}
}
}
else
set.add(mobname,varname);
}
return set;
}
protected String getStatValue(final Environmental E, final String arg2)
{
boolean found=false;
String val="";
final String uarg2=arg2.toUpperCase().trim();
for(int i=0;i<E.getStatCodes().length;i++)
{
if(E.getStatCodes()[i].equals(uarg2))
{
val=E.getStat(uarg2);
found=true;
break;
}
}
if((!found)&&(E instanceof MOB))
{
final MOB M=(MOB)E;
for(final int i : CharStats.CODES.ALLCODES())
{
if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2))
{
val=""+M.charStats().getStat(CharStats.CODES.NAME(i)); //yes, this is right
found=true;
break;
}
}
if(!found)
{
for(int i=0;i<M.curState().getStatCodes().length;i++)
{
if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=M.curState().getStat(M.curState().getStatCodes()[i]);
found=true;
break;
}
}
}
if(!found)
{
for(int i=0;i<M.phyStats().getStatCodes().length;i++)
{
if(M.phyStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=M.phyStats().getStat(M.phyStats().getStatCodes()[i]);
found=true;
break;
}
}
}
if((!found)&&(M.playerStats()!=null))
{
for(int i=0;i<M.playerStats().getStatCodes().length;i++)
{
if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]);
found=true;
break;
}
}
}
if((!found)&&(uarg2.startsWith("BASE")))
{
for(int i=0;i<M.baseState().getStatCodes().length;i++)
{
if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4)))
{
val=M.baseState().getStat(M.baseState().getStatCodes()[i]);
found=true;
break;
}
}
}
if((!found)&&(uarg2.equals("STINK")))
{
found=true;
val=CMath.toPct(M.playerStats().getHygiene()/PlayerStats.HYGIENE_DELIMIT);
}
if((!found)
&&(CMath.s_valueOf(GenericBuilder.GenMOBBonusFakeStats.class,uarg2)!=null))
{
found=true;
val=CMLib.coffeeMaker().getAnyGenStat(M, uarg2);
}
}
if((!found)
&&(E instanceof Item)
&&(CMath.s_valueOf(GenericBuilder.GenItemBonusFakeStats.class,uarg2)!=null))
{
found=true;
val=CMLib.coffeeMaker().getAnyGenStat((Item)E, uarg2);
}
if((!found)
&&(E instanceof Physical)
&&(CMath.s_valueOf(GenericBuilder.GenPhysBonusFakeStats.class,uarg2)!=null))
{
found=true;
val=CMLib.coffeeMaker().getAnyGenStat((Physical)E, uarg2);
}
if(!found)
return null;
return val;
}
protected String getGStatValue(final Environmental E, String arg2)
{
if(E==null)
return null;
boolean found=false;
String val="";
for(int i=0;i<E.getStatCodes().length;i++)
{
if(E.getStatCodes()[i].equalsIgnoreCase(arg2))
{
val=E.getStat(arg2);
found=true; break;
}
}
if(!found)
if(E instanceof MOB)
{
arg2=arg2.toUpperCase().trim();
final GenericBuilder.GenMOBCode element = (GenericBuilder.GenMOBCode)CMath.s_valueOf(GenericBuilder.GenMOBCode.class,arg2);
if(element != null)
{
val=CMLib.coffeeMaker().getGenMobStat((MOB)E,element.name());
found=true;
}
if(!found)
{
final MOB M=(MOB)E;
for(final int i : CharStats.CODES.ALLCODES())
{
if(CharStats.CODES.NAME(i).equals(arg2)||CharStats.CODES.DESC(i).equals(arg2))
{
val=""+M.charStats().getStat(CharStats.CODES.NAME(i));
found=true;
break;
}
}
if(!found)
{
for(int i=0;i<M.curState().getStatCodes().length;i++)
{
if(M.curState().getStatCodes()[i].equals(arg2))
{
val=M.curState().getStat(M.curState().getStatCodes()[i]);
found=true;
break;
}
}
}
if(!found)
{
for(int i=0;i<M.phyStats().getStatCodes().length;i++)
{
if(M.phyStats().getStatCodes()[i].equals(arg2))
{
val=M.phyStats().getStat(M.phyStats().getStatCodes()[i]);
found=true;
break;
}
}
}
if((!found)&&(M.playerStats()!=null))
{
for(int i=0;i<M.playerStats().getStatCodes().length;i++)
{
if(M.playerStats().getStatCodes()[i].equals(arg2))
{
val=M.playerStats().getStat(M.playerStats().getStatCodes()[i]);
found=true;
break;
}
}
}
if((!found)&&(arg2.startsWith("BASE")))
{
final String arg4=arg2.substring(4);
for(int i=0;i<M.baseState().getStatCodes().length;i++)
{
if(M.baseState().getStatCodes()[i].equals(arg4))
{
val=M.baseState().getStat(M.baseState().getStatCodes()[i]);
found=true;
break;
}
}
if(!found)
{
for(final int i : CharStats.CODES.ALLCODES())
{
if(CharStats.CODES.NAME(i).equals(arg4)||CharStats.CODES.DESC(i).equals(arg4))
{
val=""+M.baseCharStats().getStat(CharStats.CODES.NAME(i));
found=true;
break;
}
}
}
}
if((!found)&&(arg2.equals("STINK")))
{
found=true;
val=CMath.toPct(M.playerStats().getHygiene()/PlayerStats.HYGIENE_DELIMIT);
}
}
}
else
if(E instanceof Item)
{
final GenericBuilder.GenItemCode code = (GenericBuilder.GenItemCode)CMath.s_valueOf(GenericBuilder.GenItemCode.class, arg2.toUpperCase().trim());
if(code != null)
{
val=CMLib.coffeeMaker().getGenItemStat((Item)E,code.name());
found=true;
}
}
if((!found)
&&(E instanceof Physical))
{
if(CMLib.coffeeMaker().isAnyGenStat((Physical)E, arg2.toUpperCase().trim()))
return CMLib.coffeeMaker().getAnyGenStat((Physical)E, arg2.toUpperCase().trim());
if((!found)&&(arg2.startsWith("BASE")))
{
final String arg4=arg2.substring(4);
for(int i=0;i<((Physical)E).basePhyStats().getStatCodes().length;i++)
{
if(((Physical)E).basePhyStats().getStatCodes()[i].equals(arg4))
{
val=((Physical)E).basePhyStats().getStat(((Physical)E).basePhyStats().getStatCodes()[i]);
found=true;
break;
}
}
}
}
if(found)
return val;
return null;
}
protected List<Ability> getQuestAbilities()
{
final List<Ability> able=new ArrayList<Ability>();
final Quest Q=defaultQuest();
if(Q!=null)
{
final Ability A=(Ability)Q.getDesignatedObject("ABILITY");
if(A!=null)
able.add(A);
@SuppressWarnings("unchecked")
final
List<Ability> grp=(List<Ability>)Q.getDesignatedObject("ABILITYGROUP");
if(grp != null)
able.addAll(grp);
final Object O=Q.getDesignatedObject("TOOL");
if(O instanceof Ability)
able.add((Ability)O);
@SuppressWarnings("unchecked")
final
List<Object> grp2=(List<Object>)Q.getDesignatedObject("TOOLGROUP");
if(grp2 != null)
{
for(final Object O1 : grp2)
{
if(O1 instanceof Ability)
able.add((Ability)O1);
}
}
}
return able;
}
protected Ability getAbility(final String arg)
{
if((arg==null)||(arg.length()==0))
return null;
Ability A;
A=CMClass.getAbility(arg);
if(A!=null)
return A;
for(final Ability A1 : getQuestAbilities())
{
if(A1.ID().equalsIgnoreCase(arg))
return (Ability)A1.copyOf();
}
return null;
}
protected Ability findAbility(final String arg)
{
if((arg==null)||(arg.length()==0))
return null;
Ability A;
A=CMClass.findAbility(arg);
if(A!=null)
return A;
final List<Ability> ableV=getQuestAbilities();
A=(Ability)CMLib.english().fetchEnvironmental(ableV,arg,true);
if(A==null)
A=(Ability)CMLib.english().fetchEnvironmental(ableV,arg,false);
if(A!=null)
return (Ability)A.copyOf();
return null;
}
@Override
public void setVar(final String baseName, String key, String val)
{
final PairList<String,String> vars=getScriptVarSet(baseName,key);
for(int v=0;v<vars.size();v++)
{
final String name=vars.elementAtFirst(v);
key=vars.elementAtSecond(v).toUpperCase();
@SuppressWarnings("unchecked")
Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+name);
if((H==null)&&(defaultQuestName!=null)&&(defaultQuestName.length()>0))
{
final MOB M=CMLib.players().getPlayerAllHosts(name);
if(M!=null)
{
for(final Enumeration<ScriptingEngine> e=M.scripts();e.hasMoreElements();)
{
final ScriptingEngine SE=e.nextElement();
if((SE!=null)
&&(SE!=this)
&&(defaultQuestName.equalsIgnoreCase(SE.defaultQuestName()))
&&(SE.isVar(name,key)))
{
SE.setVar(name,key,val);
return;
}
}
}
}
if(H==null)
{
if(val.length()==0)
continue;
H=new Hashtable<String,String>();
resources._submitResource("SCRIPTVAR-"+name,H);
}
if(val.length()>0)
{
switch(val.charAt(0))
{
case '+':
if(val.equals("++"))
{
String num=H.get(key);
if(num==null)
num="0";
val=Integer.toString(CMath.s_int(num.trim())+1);
}
else
{
String num=H.get(key);
// add via +number form
if(CMath.isNumber(val.substring(1).trim()))
{
if(num==null)
num="0";
val=val.substring(1);
final int amount=CMath.s_int(val.trim());
val=Integer.toString(CMath.s_int(num.trim())+amount);
}
else
if((num!=null)&&(CMath.isNumber(num)))
val=num;
}
break;
case '-':
if(val.equals("--"))
{
String num=H.get(key);
if(num==null)
num="0";
val=Integer.toString(CMath.s_int(num.trim())-1);
}
else
{
// subtract -number form
String num=H.get(key);
if(CMath.isNumber(val.substring(1).trim()))
{
val=val.substring(1);
final int amount=CMath.s_int(val.trim());
if(num==null)
num="0";
val=Integer.toString(CMath.s_int(num.trim())-amount);
}
else
if((num!=null)&&(CMath.isNumber(num)))
val=num;
}
break;
case '*':
{
// multiply via *number form
String num=H.get(key);
if(CMath.isNumber(val.substring(1).trim()))
{
val=val.substring(1);
final int amount=CMath.s_int(val.trim());
if(num==null)
num="0";
val=Integer.toString(CMath.s_int(num.trim())*amount);
}
else
if((num!=null)&&(CMath.isNumber(num)))
val=num;
break;
}
case '/':
{
// divide /number form
String num=H.get(key);
if(CMath.isNumber(val.substring(1).trim()))
{
val=val.substring(1);
final int amount=CMath.s_int(val.trim());
if(num==null)
num="0";
if(amount==0)
Log.errOut("Scripting","Scripting SetVar error: Division by 0: "+name+"/"+key+"="+val);
else
val=Integer.toString(CMath.s_int(num.trim())/amount);
}
else
if((num!=null)&&(CMath.isNumber(num)))
val=num;
break;
}
default:
break;
}
}
if(H.containsKey(key))
H.remove(key);
if(val.trim().length()>0)
H.put(key,val);
if(H.size()==0)
resources._removeResource("SCRIPTVAR-"+name);
}
}
@Override
public String[] parseEval(final String evaluable) throws ScriptParseException
{
final int STATE_MAIN=0;
final int STATE_INFUNCTION=1;
final int STATE_INFUNCQUOTE=2;
final int STATE_POSTFUNCTION=3;
final int STATE_POSTFUNCEVAL=4;
final int STATE_POSTFUNCQUOTE=5;
final int STATE_MAYFUNCTION=6;
buildHashes();
final List<String> V=new ArrayList<String>();
if((evaluable==null)||(evaluable.trim().length()==0))
return new String[]{};
final char[] evalC=evaluable.toCharArray();
int state=0;
int dex=0;
char lastQuote='\0';
String s=null;
int depth=0;
for(int c=0;c<evalC.length;c++)
{
switch(state)
{
case STATE_MAIN:
{
if(Character.isWhitespace(evalC[c]))
{
s=new String(evalC,dex,c-dex).trim();
if(s.length()>0)
{
s=s.toUpperCase();
V.add(s);
dex=c+1;
if(funcH.containsKey(s))
state=STATE_MAYFUNCTION;
else
if(!connH.containsKey(s))
throw new ScriptParseException("Unknown keyword: "+s);
}
}
else
if(Character.isLetter(evalC[c])
||(Character.isDigit(evalC[c])
&&(c>0)&&Character.isLetter(evalC[c-1])
&&(c<evalC.length-1)
&&Character.isLetter(evalC[c+1])))
{ /* move along */
}
else
{
switch(evalC[c])
{
case '!':
{
if(c==evalC.length-1)
throw new ScriptParseException("Bad Syntax on last !");
V.add("NOT");
dex=c+1;
break;
}
case '(':
{
s=new String(evalC,dex,c-dex).trim();
if(s.length()>0)
{
s=s.toUpperCase();
V.add(s);
V.add("(");
dex=c+1;
if(funcH.containsKey(s))
state=STATE_INFUNCTION;
else
if(connH.containsKey(s))
state=STATE_MAIN;
else
throw new ScriptParseException("Unknown keyword: "+s);
}
else
{
V.add("(");
depth++;
dex=c+1;
}
break;
}
case ')':
s=new String(evalC,dex,c-dex).trim();
if(s.length()>0)
throw new ScriptParseException("Bad syntax before ) at: "+s);
if(depth==0)
throw new ScriptParseException("Unmatched ) character");
V.add(")");
depth--;
dex=c+1;
break;
default:
throw new ScriptParseException("Unknown character at: "+new String(evalC,dex,c-dex+1).trim()+": "+evaluable);
}
}
break;
}
case STATE_MAYFUNCTION:
{
if(evalC[c]=='(')
{
V.add("(");
dex=c+1;
state=STATE_INFUNCTION;
}
else
if(!Character.isWhitespace(evalC[c]))
throw new ScriptParseException("Expected ( at "+evalC[c]+": "+evaluable);
break;
}
case STATE_POSTFUNCTION:
{
if(!Character.isWhitespace(evalC[c]))
{
switch(evalC[c])
{
case '=':
case '>':
case '<':
case '!':
{
if(c==evalC.length-1)
throw new ScriptParseException("Bad Syntax on last "+evalC[c]);
if(!Character.isWhitespace(evalC[c+1]))
{
s=new String(evalC,c,2);
if((!signH.containsKey(s))&&(evalC[c]!='!'))
s=""+evalC[c];
}
else
s=""+evalC[c];
if(!signH.containsKey(s))
{
c=dex-1;
state=STATE_MAIN;
break;
}
V.add(s);
dex=c+(s.length());
c=c+(s.length()-1);
state=STATE_POSTFUNCEVAL;
break;
}
default:
c=dex-1;
state=STATE_MAIN;
break;
}
}
break;
}
case STATE_INFUNCTION:
{
if(evalC[c]==')')
{
V.add(new String(evalC,dex,c-dex));
V.add(")");
dex=c+1;
state=STATE_POSTFUNCTION;
}
else
if((evalC[c]=='\'')||(evalC[c]=='`'))
{
lastQuote=evalC[c];
state=STATE_INFUNCQUOTE;
}
break;
}
case STATE_INFUNCQUOTE:
{
if((evalC[c]==lastQuote)
&&((c==evalC.length-1)
||((!Character.isLetter(evalC[c-1]))
||(!Character.isLetter(evalC[c+1])))))
state=STATE_INFUNCTION;
break;
}
case STATE_POSTFUNCQUOTE:
{
if(evalC[c]==lastQuote)
{
if((V.size()>2)
&&(signH.containsKey(V.get(V.size()-1)))
&&(V.get(V.size()-2).equals(")")))
{
final String sign=V.get(V.size()-1);
V.remove(V.size()-1);
V.remove(V.size()-1);
final String prev=V.get(V.size()-1);
if(prev.equals("("))
s=sign+" "+new String(evalC,dex+1,c-dex);
else
{
V.remove(V.size()-1);
s=prev+" "+sign+" "+new String(evalC,dex+1,c-dex);
}
V.add(s);
V.add(")");
dex=c+1;
state=STATE_MAIN;
}
else
throw new ScriptParseException("Bad postfunc Eval somewhere");
}
break;
}
case STATE_POSTFUNCEVAL:
{
if(Character.isWhitespace(evalC[c]))
{
s=new String(evalC,dex,c-dex).trim();
if(s.length()>0)
{
if((V.size()>1)
&&(signH.containsKey(V.get(V.size()-1)))
&&(V.get(V.size()-2).equals(")")))
{
final String sign=V.get(V.size()-1);
V.remove(V.size()-1);
V.remove(V.size()-1);
final String prev=V.get(V.size()-1);
if(prev.equals("("))
s=sign+" "+new String(evalC,dex+1,c-dex);
else
{
V.remove(V.size()-1);
s=prev+" "+sign+" "+new String(evalC,dex+1,c-dex);
}
V.add(s);
V.add(")");
dex=c+1;
state=STATE_MAIN;
}
else
throw new ScriptParseException("Bad postfunc Eval somewhere");
}
}
else
if(Character.isLetterOrDigit(evalC[c]))
{ /* move along */
}
else
if((evalC[c]=='\'')||(evalC[c]=='`'))
{
s=new String(evalC,dex,c-dex).trim();
if(s.length()==0)
{
lastQuote=evalC[c];
state=STATE_POSTFUNCQUOTE;
}
}
break;
}
}
}
if((state==STATE_POSTFUNCQUOTE)
||(state==STATE_INFUNCQUOTE))
throw new ScriptParseException("Unclosed "+lastQuote+" in "+evaluable);
if(depth>0)
throw new ScriptParseException("Unclosed ( in "+evaluable);
return CMParms.toStringArray(V);
}
public void pushEvalBoolean(final List<Object> stack, boolean trueFalse)
{
if(stack.size()>0)
{
final Object O=stack.get(stack.size()-1);
if(O instanceof Integer)
{
final int connector=((Integer)O).intValue();
stack.remove(stack.size()-1);
if((stack.size()>0)
&&((stack.get(stack.size()-1) instanceof Boolean)))
{
final boolean preTrueFalse=((Boolean)stack.get(stack.size()-1)).booleanValue();
stack.remove(stack.size()-1);
switch(connector)
{
case CONNECTOR_AND:
trueFalse = preTrueFalse && trueFalse;
break;
case CONNECTOR_OR:
trueFalse = preTrueFalse || trueFalse;
break;
case CONNECTOR_ANDNOT:
trueFalse = preTrueFalse && (!trueFalse);
break;
case CONNECTOR_NOT:
case CONNECTOR_ORNOT:
trueFalse = preTrueFalse || (!trueFalse);
break;
}
}
else
switch(connector)
{
case CONNECTOR_ANDNOT:
case CONNECTOR_NOT:
case CONNECTOR_ORNOT:
trueFalse = !trueFalse;
break;
default:
break;
}
}
else
if(O instanceof Boolean)
{
final boolean preTrueFalse=((Boolean)stack.get(stack.size()-1)).booleanValue();
stack.remove(stack.size()-1);
trueFalse=preTrueFalse&&trueFalse;
}
}
stack.add(trueFalse?Boolean.TRUE:Boolean.FALSE);
}
/**
* Returns the index, in the given string vector, of the given string, starting
* from the given index. If the string to search for contains more than one
* "word", where a word is defined in space-delimited terms respecting double-quotes,
* then it will return the index at which all the words in the parsed search string
* are found in the given string list.
* @param V the string list to search in
* @param str the string to search for
* @param start the index to start at (0 is good)
* @return the index at which the search string was found in the string list, or -1
*/
private static int strIndex(final Vector<String> V, final String str, final int start)
{
int x=V.indexOf(str,start);
if(x>=0)
return x;
final List<String> V2=CMParms.parse(str);
if(V2.size()==0)
return -1;
x=V.indexOf(V2.get(0),start);
boolean found=false;
while((x>=0)&&((x+V2.size())<=V.size())&&(!found))
{
found=true;
for(int v2=1;v2<V2.size();v2++)
{
if(!V.get(x+v2).equals(V2.get(v2)))
{
found=false;
break;
}
}
if(!found)
x=V.indexOf(V2.get(0),x+1);
}
if(found)
return x;
return -1;
}
/**
* Weird method. Accepts a string list, a combiner (see below), a string buffer to search for,
* and a previously found index. The stringbuffer is always cleared during this call.
* If the stringbuffer was empty, the previous found index is returned. Otherwise:
* If the combiner is '&', the first index of the given stringbuffer in the string list is returned (or -1).
* If the combiner is '|', the previous index is returned if it was found, otherwise the first index
* of the given stringbuffer in the string list is returned (or -1).
* If the combiner is '>', then the previous index is returned if it was not found (-1), otherwise the
* next highest found stringbuffer since the last string list search is returned, or (-1) if no more found.
* If the combiner is '<', then the previous index is returned if it was not found (-1), otherwise the
* first found stringbuffer index is returned if it is lower than the previously found index.
* Other combiners return -1.
* @param V the string list to search
* @param combiner the combiner, either &,|,<,or >.
* @param buf the stringbuffer to search for, which is always cleared
* @param lastIndex the previously found index
* @return the result of the search
*/
private static int stringContains(final Vector<String> V, final char combiner, final StringBuffer buf, int lastIndex)
{
final String str=buf.toString().trim();
if(str.length()==0)
return lastIndex;
buf.setLength(0);
switch (combiner)
{
case '&':
lastIndex = strIndex(V, str, 0);
return lastIndex;
case '|':
if (lastIndex >= 0)
return lastIndex;
return strIndex(V, str, 0);
case '>':
if (lastIndex < 0)
return lastIndex;
return strIndex(V, str, lastIndex + 1);
case '<':
{
if (lastIndex < 0)
return lastIndex;
final int newIndex = strIndex(V, str, 0);
if (newIndex < lastIndex)
return newIndex;
return -1;
}
}
return -1;
}
/**
* Main workhorse of the stringcontains mobprog function.
* @param V parsed string to search
* @param str the coded search function
* @param index a 1-dim array of the index in the coded search str to start the search at
* @param depth the number of close parenthesis to expect
* @return the last index in the coded search function evaluated
*/
private static int stringContains(final Vector<String> V, final char[] str, final int[] index, final int depth)
{
final StringBuffer buf=new StringBuffer("");
int lastIndex=0;
boolean quoteMode=false;
char combiner='&';
for(int i=index[0];i<str.length;i++)
{
switch(str[i])
{
case ')':
if((depth>0)&&(!quoteMode))
{
index[0]=i;
return stringContains(V,combiner,buf,lastIndex);
}
buf.append(str[i]);
break;
case ' ':
buf.append(str[i]);
break;
case '&':
case '|':
case '>':
case '<':
if(quoteMode)
buf.append(str[i]);
else
{
lastIndex=stringContains(V,combiner,buf,lastIndex);
combiner=str[i];
}
break;
case '(':
if(!quoteMode)
{
lastIndex=stringContains(V,combiner,buf,lastIndex);
index[0]=i+1;
final int newIndex=stringContains(V,str,index,depth+1);
i=index[0];
switch(combiner)
{
case '&':
if((lastIndex<0)||(newIndex<0))
lastIndex=-1;
break;
case '|':
if(newIndex>=0)
lastIndex=newIndex;
break;
case '>':
if(newIndex<=lastIndex)
lastIndex=-1;
else
lastIndex=newIndex;
break;
case '<':
if((newIndex<0)||(newIndex>=lastIndex))
lastIndex=-1;
else
lastIndex=newIndex;
break;
}
}
else
buf.append(str[i]);
break;
case '\"':
quoteMode=(!quoteMode);
break;
case '\\':
if(i<str.length-1)
{
buf.append(str[i+1]);
i++;
}
break;
default:
if(Character.isLetter(str[i]))
buf.append(Character.toLowerCase(str[i]));
else
buf.append(str[i]);
break;
}
}
return stringContains(V,combiner,buf,lastIndex);
}
/**
* As the name implies, this is the implementation of the stringcontains mobprog function
* @param str1 the string to search in
* @param str2 the coded search expression
* @return the index of the found string in the first string
*/
protected final static int stringContainsFunctionImpl(final String str1, final String str2)
{
final StringBuffer buf1=new StringBuffer(str1.toLowerCase());
for(int i=buf1.length()-1;i>=0;i--)
{
switch(buf1.charAt(i))
{
case ' ':
case '\"':
case '`':
break;
case '\'':
buf1.setCharAt(i, '`');
break;
default:
if(!Character.isLetterOrDigit(buf1.charAt(i)))
buf1.setCharAt(i,' ');
break;
}
}
final StringBuffer buf2=new StringBuffer(str2.toLowerCase());
for(int i=buf2.length()-1;i>=0;i--)
{
switch(buf2.charAt(i))
{
case ' ':
case '\"':
case '`':
break;
case '\'':
buf2.setCharAt(i, '`');
break;
case ')': case '(': case '|': case '>': case '<':
// these are the actual control codes for strcontains
break;
default:
if(!Character.isLetterOrDigit(buf2.charAt(i)))
buf2.setCharAt(i,' ');
break;
}
}
final Vector<String> V=CMParms.parse(buf1.toString());
return stringContains(V,buf2.toString().toCharArray(),new int[]{0},0);
}
@Override
public boolean eval(final PhysicalAgent scripted,
final MOB source,
final Environmental target,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final String msg,
Object[] tmp,
final String[][] eval,
final int startEval)
{
String[] tt=eval[0];
if(tmp == null)
tmp = newObjs();
final List<Object> stack=new ArrayList<Object>();
for(int t=startEval;t<tt.length;t++)
{
if(tt[t].equals("("))
stack.add(tt[t]);
else
if(tt[t].equals(")"))
{
if(stack.size()>0)
{
if((!(stack.get(stack.size()-1) instanceof Boolean))
||(stack.size()==1)
||(!(stack.get(stack.size()-2)).equals("(")))
{
logError(scripted,"EVAL","SYNTAX",") Format error: "+CMParms.toListString(tt));
return false;
}
final boolean b=((Boolean)stack.get(stack.size()-1)).booleanValue();
stack.remove(stack.size()-1);
stack.remove(stack.size()-1);
pushEvalBoolean(stack,b);
}
}
else
if(connH.containsKey(tt[t]))
{
Integer curr=connH.get(tt[t]);
if((stack.size()>0)
&&(stack.get(stack.size()-1) instanceof Integer))
{
final int old=((Integer)stack.get(stack.size()-1)).intValue();
stack.remove(stack.size()-1);
curr=Integer.valueOf(CONNECTOR_MAP[old][curr.intValue()]);
}
stack.add(curr);
}
else
if(funcH.containsKey(tt[t]))
{
final Integer funcCode=funcH.get(tt[t]);
if((t==tt.length-1)
||(!tt[t+1].equals("(")))
{
logError(scripted,"EVAL","SYNTAX","No ( for fuction "+tt[t]+": "+CMParms.toListString(tt));
return false;
}
t+=2;
int tlen=0;
while(((t+tlen)<tt.length)&&(!tt[t+tlen].equals(")")))
tlen++;
if((t+tlen)==tt.length)
{
logError(scripted,"EVAL","SYNTAX","No ) for fuction "+tt[t-1]+": "+CMParms.toListString(tt));
return false;
}
tickStatus=Tickable.STATUS_MISC+funcCode.intValue();
final String funcParms=tt[t];
boolean returnable=false;
switch(funcCode.intValue())
{
case 1: // rand
{
String num=funcParms;
if(num.endsWith("%"))
num=num.substring(0,num.length()-1);
final int arg=CMath.s_int(num);
if(CMLib.dice().rollPercentage()<arg)
returnable=true;
else
returnable=false;
break;
}
case 2: // has
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HAS","Syntax","'"+eval[0][t]+"' in "+CMParms.toListString(eval[0]));
return returnable;
}
if(E==null)
returnable=false;
else
{
if((E instanceof MOB)
&&(((MOB)E).findItem(arg2)!=null))
returnable = true;
else
if((E instanceof Room)
&&(((Room)E).findItem(arg2)!=null))
returnable=true;
else
{
final Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
{
if(E2!=null)
returnable=((MOB)E).isMine(E2);
else
returnable=(((MOB)E).findItem(arg2)!=null);
}
else
if(E instanceof Item)
returnable=CMLib.english().containsString(E.name(),arg2);
else
if(E instanceof Room)
{
if(E2 instanceof Item)
returnable=((Room)E).isContent((Item)E2);
else
returnable=(((Room)E).findItem(null,arg2)!=null);
}
else
returnable=false;
}
}
break;
}
case 74: // hasnum
{
if (tlen == 1)
tt = parseBits(eval, t, "cccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String cmp=tt[t+2];
final String value=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((value.length()==0)||(item.length()==0)||(cmp.length()==0))
{
logError(scripted,"HASNUM","Syntax",funcParms);
return returnable;
}
Item I=null;
int num=0;
if(E==null)
returnable=false;
else
if(E instanceof MOB)
{
final MOB M=(MOB)E;
for(int i=0;i<M.numItems();i++)
{
I=M.getItem(i);
if(I==null)
break;
if((item.equalsIgnoreCase("all"))
||(CMLib.english().containsString(I.Name(),item)))
num++;
}
returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM");
}
else
if(E instanceof Item)
{
num=CMLib.english().containsString(E.name(),item)?1:0;
returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM");
}
else
if(E instanceof Room)
{
final Room R=(Room)E;
for(int i=0;i<R.numItems();i++)
{
I=R.getItem(i);
if(I==null)
break;
if((item.equalsIgnoreCase("all"))
||(CMLib.english().containsString(I.Name(),item)))
num++;
}
returnable=simpleEval(scripted,""+num,value,cmp,"HASNUM");
}
else
returnable=false;
break;
}
case 67: // hastitle
{
if (tlen == 1)
tt = parseBits(eval, t, "cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HASTITLE","Syntax",funcParms);
return returnable;
}
if(E instanceof MOB)
{
final MOB M=(MOB)E;
returnable=(M.playerStats()!=null)&&(M.playerStats().getTitles().contains(arg2));
}
else
returnable=false;
break;
}
case 3: // worn
{
if (tlen == 1)
tt = parseBits(eval, t, "cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"WORN","Syntax",funcParms);
return returnable;
}
if(E==null)
returnable=false;
else
if(E instanceof MOB)
returnable=(((MOB)E).fetchItem(null,Wearable.FILTER_WORNONLY,arg2)!=null);
else
if(E instanceof Item)
returnable=(CMLib.english().containsString(E.name(),arg2)&&(!((Item)E).amWearingAt(Wearable.IN_INVENTORY)));
else
returnable=false;
break;
}
case 4: // isnpc
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=((MOB)E).isMonster();
break;
}
case 87: // isbirthday
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final MOB mob=(MOB)E;
if(mob.playerStats()==null)
returnable=false;
else
{
final TimeClock C=CMLib.time().localClock(mob.getStartRoom());
final int month=C.getMonth();
final int day=C.getDayOfMonth();
final int bday=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_DAY];
final int bmonth=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_MONTH];
if((C.getYear()==mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_LASTYEARCELEBRATED])
&&((month==bmonth)&&(day==bday)))
returnable=true;
else
returnable=false;
}
}
break;
}
case 5: // ispc
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=!((MOB)E).isMonster();
break;
}
case 6: // isgood
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
returnable=CMLib.flags().isGood(P);
break;
}
case 8: // isevil
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
returnable=CMLib.flags().isEvil(P);
break;
}
case 9: // isneutral
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
returnable=CMLib.flags().isNeutral(P);
break;
}
case 54: // isalive
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead()))
returnable=true;
else
returnable=false;
break;
}
case 58: // isable
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead()))
{
final ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true);
if(X!=null)
returnable=((MOB)E).fetchExpertise(X.ID())!=null;
else
returnable=((MOB)E).findAbility(arg2)!=null;
}
else
returnable=false;
break;
}
case 112: // cansee
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final PhysicalAgent MP=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(!(MP instanceof MOB))
returnable=false;
else
{
final MOB M=(MOB)MP;
final Physical P=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
returnable=CMLib.flags().canBeSeenBy(P, M);
}
break;
}
case 113: // canhear
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final PhysicalAgent MP=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(!(MP instanceof MOB))
returnable=false;
else
{
final MOB M=(MOB)MP;
final Physical P=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
returnable=CMLib.flags().canBeHeardMovingBy(P, M);
}
break;
}
case 59: // isopen
{
final String arg1=CMParms.cleanBit(funcParms);
final int dir=CMLib.directions().getGoodDirectionCode(arg1);
returnable=false;
if(dir<0)
{
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof Container))
returnable=((Container)E).isOpen();
else
if((E!=null)&&(E instanceof Exit))
returnable=((Exit)E).isOpen();
}
else
if(lastKnownLocation!=null)
{
final Exit E=lastKnownLocation.getExitInDir(dir);
if(E!=null)
returnable= E.isOpen();
}
break;
}
case 60: // islocked
{
final String arg1=CMParms.cleanBit(funcParms);
final int dir=CMLib.directions().getGoodDirectionCode(arg1);
returnable=false;
if(dir<0)
{
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof Container))
returnable=((Container)E).isLocked();
else
if((E!=null)&&(E instanceof Exit))
returnable=((Exit)E).isLocked();
}
else
if(lastKnownLocation!=null)
{
final Exit E=lastKnownLocation.getExitInDir(dir);
if(E!=null)
returnable= E.isLocked();
}
break;
}
case 10: // isfight
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=((MOB)E).isInCombat();
break;
}
case 11: // isimmort
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=CMSecurity.isAllowed(((MOB)E),lastKnownLocation,CMSecurity.SecFlag.IMMORT);
break;
}
case 12: // ischarmed
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
returnable=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING).size()>0;
break;
}
case 15: // isfollow
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
if(((MOB)E).amFollowing()==null)
returnable=false;
else
if(((MOB)E).amFollowing().location()!=lastKnownLocation)
returnable=false;
else
returnable=true;
break;
}
case 73: // isservant
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB))||(lastKnownLocation==null))
returnable=false;
else
if((((MOB)E).getLiegeID()==null)||(((MOB)E).getLiegeID().length()==0))
returnable=false;
else
if(lastKnownLocation.fetchInhabitant("$"+((MOB)E).getLiegeID()+"$")==null)
returnable=false;
else
returnable=true;
break;
}
case 95: // isspeaking
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB))||(lastKnownLocation==null))
returnable=false;
else
{
final MOB TM=(MOB)E;
final Language L=CMLib.utensils().getLanguageSpoken(TM);
if((L!=null)
&&(!L.ID().equalsIgnoreCase("Common"))
&&(L.ID().equalsIgnoreCase(arg2)||L.Name().equalsIgnoreCase(arg2)||arg2.equalsIgnoreCase("any")))
returnable=true;
else
if(arg2.equalsIgnoreCase("common")||arg2.equalsIgnoreCase("none"))
returnable=true;
else
returnable=false;
}
break;
}
case 55: // ispkill
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
if(((MOB)E).isAttributeSet(MOB.Attrib.PLAYERKILL))
returnable=true;
else
returnable=false;
break;
}
case 7: // isname
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=CMLib.english().containsString(E.name(),arg2);
break;
}
case 56: // name
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=simpleEvalStr(scripted,E.Name(),arg3,arg2,"NAME");
break;
}
case 75: // currency
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=simpleEvalStr(scripted,CMLib.beanCounter().getCurrency(E),arg3,arg2,"CURRENCY");
break;
}
case 61: // strin
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2;
if(tt[t+1].equals("$$r"))
arg2=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(monster));
else
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final List<String> V=CMParms.parse(arg1.toUpperCase());
returnable=V.contains(arg2.toUpperCase());
break;
}
case 62: // callfunc
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
String found=null;
boolean validFunc=false;
final List<DVector> scripts=getScripts();
String trigger=null;
String[] ttrigger=null;
for(int v=0;v<scripts.size();v++)
{
final DVector script2=scripts.get(v);
if(script2.size()<1)
continue;
trigger=((String)script2.elementAt(0,1)).toUpperCase().trim();
ttrigger=(String[])script2.elementAt(0,2);
if(getTriggerCode(trigger,ttrigger)==17)
{
final String fnamed=
(ttrigger!=null)
?ttrigger[1]
:CMParms.getCleanBit(trigger,1);
if(fnamed.equalsIgnoreCase(arg1))
{
validFunc=true;
found=
execute(scripted,
source,
target,
monster,
primaryItem,
secondaryItem,
script2,
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2),
tmp);
if(found==null)
found="";
break;
}
}
}
if(!validFunc)
logError(scripted,"CALLFUNC","Unknown","Function: "+arg1);
else
if(found!=null)
{
final String resp=found.trim().toLowerCase();
if(resp.equals("cancel"))
returnable=false;
else
returnable=resp.length()!=0;
}
else
returnable=false;
break;
}
case 14: // affected
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
{
final Ability A=findAbility(arg2);
if((A==null)||(arg2==null)||(arg2.length()==0))
logError(scripted,"AFFECTED","RunTime",arg2+" is not a valid ability name.");
else
if(A!=null)
arg2=A.ID();
returnable=(P.fetchEffect(arg2)!=null);
}
break;
}
case 69: // isbehave
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final PhysicalAgent P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P==null)
returnable=false;
else
{
final Behavior B=CMClass.findBehavior(arg2);
if(B!=null)
arg2=B.ID();
returnable=(P.fetchBehavior(arg2)!=null);
}
break;
}
case 70: // ipaddress
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB))||(((MOB)E).isMonster()))
returnable=false;
else
returnable=simpleEvalStr(scripted,((MOB)E).session().getAddress(),arg3,arg2,"ADDRESS");
break;
}
case 28: // questwinner
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
arg1=E.Name();
if(arg2.equalsIgnoreCase("previous"))
{
returnable=true;
final String quest=defaultQuestName();
if((quest!=null)
&&(quest.length()>0))
{
ScriptingEngine prevE=null;
final List<ScriptingEngine> list=new LinkedList<ScriptingEngine>();
for(final Enumeration<ScriptingEngine> e = scripted.scripts();e.hasMoreElements();)
list.add(e.nextElement());
for(final Enumeration<Behavior> b=scripted.behaviors();b.hasMoreElements();)
{
final Behavior B=b.nextElement();
if(B instanceof ScriptingEngine)
list.add((ScriptingEngine)B);
}
for(final ScriptingEngine engine : list)
{
if((engine!=null)
&&(engine.defaultQuestName()!=null)
&&(engine.defaultQuestName().length()>0))
{
if(engine == this)
{
if(prevE != null)
{
final Quest Q=CMLib.quests().fetchQuest(prevE.defaultQuestName());
if(Q != null)
returnable=Q.wasWinner(arg1);
}
break;
}
prevE=engine;
}
}
}
}
else
{
final Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
returnable=Q.wasWinner(arg1);
}
break;
}
case 93: // questscripted
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final PhysicalAgent E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=tt[t+1];
if(arg2.equalsIgnoreCase("ALL"))
{
returnable=false;
for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();)
{
final Quest Q=q.nextElement();
if(Q.running())
{
if(E!=null)
{
for(final Enumeration<ScriptingEngine> e=E.scripts();e.hasMoreElements();)
{
final ScriptingEngine SE=e.nextElement();
if((SE!=null)&&(SE.defaultQuestName().equalsIgnoreCase(Q.name())))
returnable=true;
}
for(final Enumeration<Behavior> b=E.behaviors();b.hasMoreElements();)
{
final Behavior B=b.nextElement();
if(B instanceof ScriptingEngine)
{
final ScriptingEngine SE=(ScriptingEngine)B;
if((SE.defaultQuestName().equalsIgnoreCase(Q.name())))
returnable=true;
}
}
}
}
}
}
else
{
final Quest Q=getQuest(arg2);
returnable=false;
if((Q!=null)&&(E!=null))
{
for(final Enumeration<ScriptingEngine> e=E.scripts();e.hasMoreElements();)
{
final ScriptingEngine SE=e.nextElement();
if((SE!=null)&&(SE.defaultQuestName().equalsIgnoreCase(Q.name())))
returnable=true;
}
for(final Enumeration<Behavior> b=E.behaviors();b.hasMoreElements();)
{
final Behavior B=b.nextElement();
if(B instanceof ScriptingEngine)
{
final ScriptingEngine SE=(ScriptingEngine)B;
if((SE.defaultQuestName().equalsIgnoreCase(Q.name())))
returnable=true;
}
}
}
}
break;
}
case 94: // questroom
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
final Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
returnable=(Q.getQuestRoomIndex(arg1)>=0);
break;
}
case 114: // questarea
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
final Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
{
int num=1;
Environmental E=Q.getQuestRoom(num);
returnable = false;
final Area parent=CMLib.map().getArea(arg1);
if(parent == null)
logError(scripted,"QUESTAREA","NoArea",funcParms);
else
while(E!=null)
{
final Area A=CMLib.map().areaLocation(E);
if((A==parent)||(parent.isChild(A))||(A.isChild(parent)))
{
returnable=true;
break;
}
num++;
E=Q.getQuestRoom(num);
}
}
break;
}
case 29: // questmob
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
final PhysicalAgent E=getArgumentMOB(tt[t+0],source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.equalsIgnoreCase("ALL"))
{
returnable=false;
for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();)
{
final Quest Q=q.nextElement();
if(Q.running())
{
if(E!=null)
{
if(Q.isObjectInUse(E))
{
returnable=true;
break;
}
}
else
if(Q.getQuestMobIndex(arg1)>=0)
{
returnable=true;
break;
}
}
}
}
else
{
final Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
returnable=(Q.getQuestMobIndex(arg1)>=0);
}
break;
}
case 31: // isquestmobalive
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
if(arg2.equalsIgnoreCase("ALL"))
{
returnable=false;
for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();)
{
final Quest Q=q.nextElement();
if(Q.running())
{
MOB M=null;
if(CMath.s_int(arg1.trim())>0)
M=Q.getQuestMob(CMath.s_int(arg1.trim()));
else
M=Q.getQuestMob(Q.getQuestMobIndex(arg1));
if(M!=null)
{
returnable=!M.amDead();
break;
}
}
}
}
else
{
final Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
{
MOB M=null;
if(CMath.s_int(arg1.trim())>0)
M=Q.getQuestMob(CMath.s_int(arg1.trim()));
else
M=Q.getQuestMob(Q.getQuestMobIndex(arg1));
if(M==null)
returnable=false;
else
returnable=!M.amDead();
}
}
break;
}
case 111: // itemcount
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
if(arg2.length()==0)
{
logError(scripted,"ITEMCOUNT","Syntax",funcParms);
return returnable;
}
if(E==null)
returnable=false;
else
{
int num=0;
if(E instanceof Container)
{
num++;
for(final Item I : ((Container)E).getContents())
num+=I.numberOfItems();
}
else
if(E instanceof Item)
num=((Item)E).numberOfItems();
else
if(E instanceof MOB)
{
for(final Enumeration<Item> i=((MOB)E).items();i.hasMoreElements();)
num += i.nextElement().numberOfItems();
}
else
if(E instanceof Room)
{
for(final Enumeration<Item> i=((Room)E).items();i.hasMoreElements();)
num += i.nextElement().numberOfItems();
}
else
if(E instanceof Area)
{
for(final Enumeration<Room> r=((Area)E).getFilledCompleteMap();r.hasMoreElements();)
{
for(final Enumeration<Item> i=r.nextElement().items();i.hasMoreElements();)
num += i.nextElement().numberOfItems();
}
}
else
returnable=false;
returnable=simpleEval(scripted,""+num,arg3,arg2,"ITEMCOUNT");
}
break;
}
case 32: // nummobsinarea
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase();
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
int num=0;
MaskingLibrary.CompiledZMask MASK=null;
if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("="))))
{
arg1=arg1.substring(4).trim();
arg1=arg1.substring(1).trim();
MASK=CMLib.masking().maskCompile(arg1);
}
for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
final Room R=e.nextElement();
if(arg1.equals("*"))
num+=R.numInhabitants();
else
{
for(int m=0;m<R.numInhabitants();m++)
{
final MOB M=R.fetchInhabitant(m);
if(M==null)
continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.name(),arg1))
num++;
}
}
}
returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBSINAREA");
break;
}
case 33: // nummobs
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase();
final String arg2=tt[t+1];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
int num=0;
MaskingLibrary.CompiledZMask MASK=null;
if((arg3.toUpperCase().startsWith("MASK")&&(arg3.substring(4).trim().startsWith("="))))
{
arg3=arg3.substring(4).trim();
arg3=arg3.substring(1).trim();
MASK=CMLib.masking().maskCompile(arg3);
}
try
{
for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();)
{
final Room R=e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
final MOB M=R.fetchInhabitant(m);
if(M==null)
continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.name(),arg1))
num++;
}
}
}
catch (final NoSuchElementException nse)
{
}
returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMMOBS");
break;
}
case 34: // numracesinarea
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase();
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
int num=0;
Room R=null;
MOB M=null;
for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
R=e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
M=R.fetchInhabitant(m);
if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1)))
num++;
}
}
returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACESINAREA");
break;
}
case 35: // numraces
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase();
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
int num=0;
try
{
for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();)
{
final Room R=e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
final MOB M=R.fetchInhabitant(m);
if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1)))
num++;
}
}
}
catch (final NoSuchElementException nse)
{
}
returnable=simpleEval(scripted,""+num,arg3,arg2,"NUMRACES");
break;
}
case 30: // questobj
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
final PhysicalAgent E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.equalsIgnoreCase("ALL"))
{
returnable=false;
for(final Enumeration<Quest> q=CMLib.quests().enumQuests();q.hasMoreElements();)
{
final Quest Q=q.nextElement();
if(Q.running())
{
if(E!=null)
{
if(Q.isObjectInUse(E))
{
returnable=true;
break;
}
}
else
if(Q.getQuestItemIndex(arg1)>=0)
{
returnable=true;
break;
}
}
}
}
else
{
final Quest Q=getQuest(arg2);
if(Q==null)
returnable=false;
else
returnable=(Q.getQuestItemIndex(arg1)>=0);
}
break;
}
case 85: // islike
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
returnable=CMLib.masking().maskCheck(arg2, E,false);
break;
}
case 86: // strcontains
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
returnable=stringContainsFunctionImpl(arg1,arg2)>=0;
break;
}
case 92: // isodd
{
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim();
boolean isodd = false;
if( CMath.isLong( val ) )
{
isodd = (CMath.s_long(val) %2 == 1);
}
returnable = isodd;
break;
}
case 16: // hitprcnt
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"HITPRCNT","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints());
final int val1=(int)Math.round(hitPctD*100.0);
returnable=simpleEval(scripted,""+val1,arg3,arg2,"HITPRCNT");
}
break;
}
case 50: // isseason
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
returnable=false;
if(monster.location()!=null)
{
arg1=arg1.toUpperCase();
for(final TimeClock.Season season : TimeClock.Season.values())
{
if(season.toString().startsWith(arg1.toUpperCase())
&&(monster.location().getArea().getTimeObj().getSeasonCode()==season))
{
returnable=true;
break;
}
}
}
break;
}
case 51: // isweather
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
returnable=false;
if(monster.location()!=null)
for(int a=0;a<Climate.WEATHER_DESCS.length;a++)
{
if((Climate.WEATHER_DESCS[a]).startsWith(arg1.toUpperCase())
&&(monster.location().getArea().getClimateObj().weatherType(monster.location())==a))
{
returnable = true;
break;
}
}
break;
}
case 57: // ismoon
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
returnable=false;
if(monster.location()!=null)
{
if(arg1.length()==0)
returnable=monster.location().getArea().getClimateObj().canSeeTheStars(monster.location());
else
{
arg1=arg1.toUpperCase();
for(final TimeClock.MoonPhase phase : TimeClock.MoonPhase.values())
{
if(phase.toString().startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getMoonPhase(monster.location())==phase))
{
returnable=true;
break;
}
}
}
}
break;
}
case 110: // ishour
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toLowerCase().trim();
if(monster.location()==null)
returnable=false;
else
if((monster.location().getArea().getTimeObj().getHourOfDay()==CMath.s_int(arg1)))
returnable=true;
else
returnable=false;
break;
}
case 38: // istime
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toLowerCase().trim();
if(monster.location()==null)
returnable=false;
else
if(("daytime").startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.DAY))
returnable=true;
else
if(("dawn").startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.DAWN))
returnable=true;
else
if(("dusk").startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.DUSK))
returnable=true;
else
if(("nighttime").startsWith(arg1)
&&(monster.location().getArea().getTimeObj().getTODCode()==TimeClock.TimeOfDay.NIGHT))
returnable=true;
else
if((monster.location().getArea().getTimeObj().getHourOfDay()==CMath.s_int(arg1)))
returnable=true;
else
returnable=false;
break;
}
case 39: // isday
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getDayOfMonth()==CMath.s_int(arg1.trim())))
returnable=true;
else
returnable=false;
break;
}
case 103: // ismonth
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getMonth()==CMath.s_int(arg1.trim())))
returnable=true;
else
returnable=false;
break;
}
case 104: // isyear
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if((monster.location()!=null)&&(monster.location().getArea().getTimeObj().getYear()==CMath.s_int(arg1.trim())))
returnable=true;
else
returnable=false;
break;
}
case 105: // isrlhour
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) == CMath.s_int(arg1.trim()))
returnable=true;
else
returnable=false;
break;
}
case 106: // isrlday
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if(Calendar.getInstance().get(Calendar.DATE) == CMath.s_int(arg1.trim()))
returnable=true;
else
returnable=false;
break;
}
case 107: // isrlmonth
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if(Calendar.getInstance().get(Calendar.MONTH)+1 == CMath.s_int(arg1.trim()))
returnable=true;
else
returnable=false;
break;
}
case 108: // isrlyear
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if(Calendar.getInstance().get(Calendar.YEAR) == CMath.s_int(arg1.trim()))
returnable=true;
else
returnable=false;
break;
}
case 45: // nummobsroom
{
if(tlen==1)
{
if(CMParms.numBits(funcParms)>2)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
else
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
}
int num=0;
int startbit=0;
if(lastKnownLocation!=null)
{
num=lastKnownLocation.numInhabitants();
if(signH.containsKey(tt[t+1]))
{
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
startbit++;
if(!name.equalsIgnoreCase("*"))
{
num=0;
MaskingLibrary.CompiledZMask MASK=null;
if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("="))))
{
final boolean usePreCompiled = (name.equals(tt[t+0]));
name=name.substring(4).trim();
name=name.substring(1).trim();
MASK=usePreCompiled?CMLib.masking().getPreCompiledMask(name): CMLib.masking().maskCompile(name);
}
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
{
final MOB M=lastKnownLocation.fetchInhabitant(i);
if(M==null)
continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.Name(),name)
||CMLib.english().containsString(M.displayText(),name))
num++;
}
}
}
}
else
if(!signH.containsKey(tt[t+0]))
{
logError(scripted,"NUMMOBSROOM","Syntax","No SIGN found: "+funcParms);
return returnable;
}
final String comp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+startbit]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+startbit+1]);
if(lastKnownLocation!=null)
returnable=simpleEval(scripted,""+num,arg2,comp,"NUMMOBSROOM");
break;
}
case 63: // numpcsroom
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Room R=lastKnownLocation;
if(R!=null)
{
int num=0;
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if((M!=null)&&(!M.isMonster()))
num++;
}
returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMPCSROOM");
}
break;
}
case 79: // numpcsarea
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
if(lastKnownLocation!=null)
{
int num=0;
for(final Session S : CMLib.sessions().localOnlineIterable())
{
if((S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea()))
num++;
}
returnable=simpleEval(scripted,""+num,arg2,arg1,"NUMPCSAREA");
}
break;
}
case 115: // expertise
{
// mob ability type > 10
if(tlen==1)
tt=parseBits(eval,t,"ccccr"); /* tt[t+0] */
final Physical P=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp);
final MOB M;
if(P instanceof MOB)
M=(MOB)P;
else
{
returnable=false;
logError(scripted,"EXPLORED","Unknown MOB",tt[t+0]);
return returnable;
}
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Ability A=M.fetchAbility(arg2);
if(A==null)
A=getAbility(arg2);
if(A==null)
{
returnable=false;
logError(scripted,"EXPLORED","Unknown Ability on MOB '"+M.name()+"'",tt[t+1]);
return returnable;
}
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final ExpertiseLibrary.Flag experFlag = (ExpertiseLibrary.Flag)CMath.s_valueOf(ExpertiseLibrary.Flag.class, arg3.toUpperCase().trim());
if(experFlag == null)
{
returnable=false;
logError(scripted,"EXPLORED","Unknown Exper Flag",tt[t+2]);
return returnable;
}
final int num=CMLib.expertises().getExpertiseLevel(M, A.ID(), experFlag);
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final String arg5=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+4]);
if(lastKnownLocation!=null)
{
returnable=simpleEval(scripted,""+num,arg5,arg4,"EXPERTISE");
}
break;
}
case 77: // explored
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
{
logError(scripted,"EXPLORED","Unknown Code",whom);
return returnable;
}
Area A=null;
if(!where.equalsIgnoreCase("world"))
{
A=CMLib.map().getArea(where);
if(A==null)
{
final Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E2 != null)
A=CMLib.map().areaLocation(E2);
}
if(A==null)
{
logError(scripted,"EXPLORED","Unknown Area",where);
return returnable;
}
}
if(lastKnownLocation!=null)
{
int pct=0;
final MOB M=(MOB)E;
if(M.playerStats()!=null)
pct=M.playerStats().percentVisited(M,A);
returnable=simpleEval(scripted,""+pct,arg2,cmp,"EXPLORED");
}
break;
}
case 72: // faction
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String cmp=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp);
final Faction F=CMLib.factions().getFaction(arg1);
if((E==null)||(!(E instanceof MOB)))
{
logError(scripted,"FACTION","Unknown Code",whom);
return returnable;
}
if(F==null)
{
logError(scripted,"FACTION","Unknown Faction",arg1);
return returnable;
}
final MOB M=(MOB)E;
String value=null;
if(!M.hasFaction(F.factionID()))
value="";
else
{
final int myfac=M.fetchFaction(F.factionID());
if(CMath.isNumber(arg2.trim()))
value=Integer.toString(myfac);
else
{
final Faction.FRange FR=CMLib.factions().getRange(F.factionID(),myfac);
if(FR==null)
value="";
else
value=FR.name();
}
}
if(lastKnownLocation!=null)
returnable=simpleEval(scripted,value,arg2,cmp,"FACTION");
break;
}
case 46: // numitemsroom
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
int ct=0;
if(lastKnownLocation!=null)
{
for(int i=0;i<lastKnownLocation.numItems();i++)
{
final Item I=lastKnownLocation.getItem(i);
if((I!=null)&&(I.container()==null))
ct++;
}
}
returnable=simpleEval(scripted,""+ct,arg2,arg1,"NUMITEMSROOM");
break;
}
case 47: //mobitem
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
MOB M=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
M=lastKnownLocation.fetchInhabitant(arg1.trim());
}
Item which=null;
int ct=1;
if(M!=null)
{
for(int i=0;i<M.numItems();i++)
{
final Item I=M.getItem(i);
if((I!=null)&&(I.container()==null))
{
if(ct==CMath.s_int(arg2.trim()))
{
which = I;
break;
}
ct++;
}
}
}
if(which==null)
returnable=false;
else
returnable=(CMLib.english().containsString(which.name(),arg3)
||CMLib.english().containsString(which.Name(),arg3)
||CMLib.english().containsString(which.displayText(),arg3));
break;
}
case 49: // hastattoo
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HASTATTOO","Syntax",funcParms);
break;
}
else
if((E!=null)&&(E instanceof MOB))
returnable=(((MOB)E).findTattoo(arg2)!=null);
else
returnable=false;
break;
}
case 109: // hastattootime
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String cmp=tt[t+2];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HASTATTOO","Syntax",funcParms);
break;
}
else
if((E!=null)&&(E instanceof MOB))
{
final Tattoo T=((MOB)E).findTattoo(arg2);
if(T==null)
returnable=false;
else
returnable=simpleEval(scripted,""+T.getTickDown(),arg3,cmp,"ISTATTOOTIME");
}
else
returnable=false;
break;
}
case 99: // hasacctattoo
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"HASACCTATTOO","Syntax",funcParms);
break;
}
else
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getAccount()!=null))
returnable=((MOB)E).playerStats().getAccount().findTattoo(arg2)!=null;
else
returnable=false;
break;
}
case 48: // numitemsmob
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
MOB which=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
which=lastKnownLocation.fetchInhabitant(arg1);
}
int ct=0;
if(which!=null)
{
for(int i=0;i<which.numItems();i++)
{
final Item I=which.getItem(i);
if((I!=null)&&(I.container()==null))
ct++;
}
}
returnable=simpleEval(scripted,""+ct,arg3,arg2,"NUMITEMSMOB");
break;
}
case 101: // numitemsshop
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
PhysicalAgent which=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
which=lastKnownLocation.fetchInhabitant(arg1);
if(which == null)
which=this.getArgumentItem(tt[t+0], source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(which == null)
which=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp);
}
int ct=0;
if(which!=null)
{
ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(which);
if((shopHere == null)&&(scripted instanceof Item))
shopHere=CMLib.coffeeShops().getShopKeeper(((Item)which).owner());
if((shopHere == null)&&(scripted instanceof MOB))
shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)which).location());
if(shopHere == null)
shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(shopHere!=null)
{
final CoffeeShop shop = shopHere.getShop();
if(shop != null)
{
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();i.next())
{
ct++;
}
}
}
}
returnable=simpleEval(scripted,""+ct,arg3,arg2,"NUMITEMSSHOP");
break;
}
case 100: // shopitem
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
PhysicalAgent where=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
where=lastKnownLocation.fetchInhabitant(arg1.trim());
if(where == null)
where=this.getArgumentItem(tt[t+0], source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(where == null)
where=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp);
}
Environmental which=null;
int ct=1;
if(where!=null)
{
ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where);
if((shopHere == null)&&(scripted instanceof Item))
shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner());
if((shopHere == null)&&(scripted instanceof MOB))
shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location());
if(shopHere == null)
shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(shopHere!=null)
{
final CoffeeShop shop = shopHere.getShop();
if(shop != null)
{
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();)
{
final Environmental E=i.next();
if(ct==CMath.s_int(arg2.trim()))
{
which = E;
break;
}
ct++;
}
}
}
if(which==null)
returnable=false;
else
{
returnable=(CMLib.english().containsString(which.name(),arg3)
||CMLib.english().containsString(which.Name(),arg3)
||CMLib.english().containsString(which.displayText(),arg3));
if(returnable)
setShopPrice(shopHere,which,tmp);
}
}
else
returnable=false;
break;
}
case 102: // shophas
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
PhysicalAgent where=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
where=lastKnownLocation.fetchInhabitant(arg1.trim());
if(where == null)
where=this.getArgumentItem(tt[t+0], source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(where == null)
where=this.getArgumentMOB(tt[t+0], source, monster, target, primaryItem, secondaryItem, msg, tmp);
}
returnable=false;
if(where!=null)
{
ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where);
if((shopHere == null)&&(scripted instanceof Item))
shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner());
if((shopHere == null)&&(scripted instanceof MOB))
shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location());
if(shopHere == null)
shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(shopHere!=null)
{
final CoffeeShop shop = shopHere.getShop();
if(shop != null)
{
final Environmental E=shop.getStock(arg2.trim(), null);
returnable = (E!=null);
if(returnable)
setShopPrice(shopHere,E,tmp);
}
}
}
break;
}
case 43: // roommob
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Environmental which=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
which=lastKnownLocation.fetchInhabitant(arg1.trim());
}
if(which==null)
returnable=false;
else
returnable=(CMLib.english().containsString(which.name(),arg2)
||CMLib.english().containsString(which.Name(),arg2)
||CMLib.english().containsString(which.displayText(),arg2));
break;
}
case 44: // roomitem
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
Environmental which=null;
int ct=1;
if(lastKnownLocation!=null)
for(int i=0;i<lastKnownLocation.numItems();i++)
{
final Item I=lastKnownLocation.getItem(i);
if((I!=null)&&(I.container()==null))
{
if(ct==CMath.s_int(arg1.trim()))
{
which = I;
break;
}
ct++;
}
}
if(which==null)
returnable=false;
else
returnable=(CMLib.english().containsString(which.name(),arg2)
||CMLib.english().containsString(which.Name(),arg2)
||CMLib.english().containsString(which.displayText(),arg2));
break;
}
case 36: // ishere
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if((arg1.length()>0)&&(lastKnownLocation!=null))
returnable=((lastKnownLocation.findItem(arg1)!=null)||(lastKnownLocation.fetchInhabitant(arg1)!=null));
else
returnable=false;
break;
}
case 17: // inroom
{
if(tlen==1)
tt=parseSpecial3PartEval(eval,t);
String comp="==";
Environmental E=monster;
String arg2;
if(signH.containsKey(tt[t+1]))
{
E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
comp=tt[t+1];
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
}
else
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
Room R=null;
if(arg2.startsWith("$"))
R=CMLib.map().roomLocation(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(R==null)
R=getRoom(arg2,lastKnownLocation);
if(E==null)
returnable=false;
else
{
final Room R2=CMLib.map().roomLocation(E);
if((R==null)&&((arg2.length()==0)||(R2==null)))
returnable=true;
else
if((R==null)||(R2==null))
returnable=false;
else
returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"INROOM");
}
break;
}
case 90: // inarea
{
if(tlen==1)
tt=parseSpecial3PartEval(eval,t);
String comp="==";
Environmental E=monster;
String arg3;
if(signH.containsKey(tt[t+1]))
{
E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
comp=tt[t+1];
arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
}
else
arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
Room R=null;
if(arg3.startsWith("$"))
R=CMLib.map().roomLocation(this.getArgumentItem(arg3,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(R==null)
{
try
{
final String lnAstr=(lastKnownLocation!=null)?lastKnownLocation.getArea().Name():null;
if((lnAstr!=null)&&(lnAstr.equalsIgnoreCase(arg3)))
R=lastKnownLocation;
if(R==null)
{
for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();)
{
final Area A=a.nextElement();
if((A!=null)&&(A.Name().equalsIgnoreCase(arg3)))
{
if((lnAstr!=null)
&&(lnAstr.equals(A.Name())))
R=lastKnownLocation;
else
if(!A.isProperlyEmpty())
R=A.getRandomProperRoom();
}
}
}
if(R==null)
{
for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();)
{
final Area A=a.nextElement();
if((A!=null)&&(CMLib.english().containsString(A.Name(),arg3)))
{
if((lnAstr!=null)
&&(lnAstr.equals(A.Name())))
R=lastKnownLocation;
else
if(!A.isProperlyEmpty())
R=A.getRandomProperRoom();
}
}
}
}
catch (final NoSuchElementException nse)
{
}
}
if(R==null)
R=getRoom(arg3,lastKnownLocation);
if((R!=null)
&&(CMath.bset(R.getArea().flags(),Area.FLAG_INSTANCE_PARENT))
&&(lastKnownLocation!=null)
&&(lastKnownLocation.getArea()!=R.getArea())
&&(CMath.bset(lastKnownLocation.getArea().flags(),Area.FLAG_INSTANCE_CHILD))
&&(CMLib.map().getModelArea(lastKnownLocation.getArea())==R.getArea()))
R=lastKnownLocation;
if(E==null)
returnable=false;
else
{
final Room R2=CMLib.map().roomLocation(E);
if((R==null)&&((arg3.length()==0)||(R2==null)))
returnable=true;
else
if((R==null)||(R2==null))
returnable=false;
else
returnable=simpleEvalStr(scripted,R2.getArea().Name(),R.getArea().Name(),comp,"INAREA");
}
break;
}
case 89: // isrecall
{
if(tlen==1)
tt=parseSpecial3PartEval(eval,t);
String comp="==";
Environmental E=monster;
String arg2;
if(signH.containsKey(tt[t+1]))
{
E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
comp=tt[t+1];
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
}
else
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
Room R=null;
if(arg2.startsWith("$"))
R=CMLib.map().getStartRoom(this.getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(R==null)
R=getRoom(arg2,lastKnownLocation);
if(E==null)
returnable=false;
else
{
final Room R2=CMLib.map().getStartRoom(E);
if((R==null)&&((arg2.length()==0)||(R2==null)))
returnable=true;
else
if((R==null)||(R2==null))
returnable=false;
else
returnable=simpleEvalStr(scripted,CMLib.map().getExtendedRoomID(R2),CMLib.map().getExtendedRoomID(R),comp,"ISRECALL");
}
break;
}
case 37: // inlocale
{
if(tlen==1)
{
if(CMParms.numBits(funcParms)>1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
else
{
final int numBits=2;
String[] parsed=null;
if(CMParms.cleanBit(funcParms).equals(funcParms))
parsed=parseBits("'"+funcParms+"'"+CMStrings.repeat(" .",numBits-1),"cr");
else
parsed=parseBits(funcParms+CMStrings.repeat(" .",numBits-1),"cr");
tt=insertStringArray(tt,parsed,t);
eval[0]=tt;
}
}
String arg2=null;
Environmental E=monster;
if(tt[t+1].equals("."))
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
else
{
E=getArgumentItem(tt[t+0],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
}
if(E==null)
returnable=false;
else
if(arg2.length()==0)
returnable=true;
else
{
final Room R=CMLib.map().roomLocation(E);
if(R==null)
returnable=false;
else
if(CMClass.classID(R).toUpperCase().indexOf(arg2.toUpperCase())>=0)
returnable=true;
else
returnable=false;
}
break;
}
case 18: // sex
{
if(tlen==1)
tt=parseBits(eval,t,"CcR"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
String arg3=tt[t+2];
if(CMath.isNumber(arg3.trim()))
{
switch(CMath.s_int(arg3.trim()))
{
case 0:
arg3 = "NEUTER";
break;
case 1:
arg3 = "MALE";
break;
case 2:
arg3 = "FEMALE";
break;
}
}
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"SEX","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final String sex=(""+((char)((MOB)E).charStats().getStat(CharStats.STAT_GENDER))).toUpperCase();
if(arg2.equals("=="))
returnable=arg3.startsWith(sex);
else
if(arg2.equals("!="))
returnable=!arg3.startsWith(sex);
else
{
logError(scripted,"SEX","Syntax",funcParms);
return returnable;
}
}
break;
}
case 91: // datetime
{
if(tlen==1)
tt=parseBits(eval,t,"Ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=tt[t+2];
final int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.trim());
if(index<0)
logError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name());
else
if(CMLib.map().areaLocation(scripted)!=null)
{
String val=null;
switch(index)
{
case 2:
val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth();
break;
case 3:
val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth();
break;
case 4:
val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getMonth();
break;
case 5:
val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getYear();
break;
default:
val = "" + CMLib.map().areaLocation(scripted).getTimeObj().getHourOfDay();
break;
}
returnable=simpleEval(scripted,val,arg3,arg2,"DATETIME");
}
break;
}
case 13: // stat
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=tt[t+2];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"STAT","Syntax",funcParms);
break;
}
if(E==null)
returnable=false;
else
{
final String val=getStatValue(E,arg2);
if(val==null)
{
logError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name());
break;
}
if(arg3.equals("=="))
returnable=val.equalsIgnoreCase(arg4);
else
if(arg3.equals("!="))
returnable=!val.equalsIgnoreCase(arg4);
else
returnable=simpleEval(scripted,val,arg4,arg3,"STAT");
}
break;
}
case 52: // gstat
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=tt[t+2];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"GSTAT","Syntax",funcParms);
break;
}
if(E==null)
returnable=false;
else
{
final String val=getGStatValue(E,arg2);
if(val==null)
{
logError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name());
break;
}
if(arg3.equals("=="))
returnable=val.equalsIgnoreCase(arg4);
else
if(arg3.equals("!="))
returnable=!val.equalsIgnoreCase(arg4);
else
returnable=simpleEval(scripted,val,arg4,arg3,"GSTAT");
}
break;
}
case 19: // position
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=tt[t+2];
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"POSITION","Syntax",funcParms);
return returnable;
}
if(P==null)
returnable=false;
else
{
String sex="STANDING";
if(CMLib.flags().isSleeping(P))
sex="SLEEPING";
else
if(CMLib.flags().isSitting(P))
sex="SITTING";
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"POSITION","Syntax",funcParms);
return returnable;
}
}
break;
}
case 20: // level
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"LEVEL","Syntax",funcParms);
return returnable;
}
if(P==null)
returnable=false;
else
{
final int val1=P.phyStats().level();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"LEVEL");
}
break;
}
case 80: // questpoints
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"QUESTPOINTS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final int val1=((MOB)E).getQuestPoint();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"QUESTPOINTS");
}
break;
}
case 83: // qvar
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String arg3=tt[t+2];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Quest Q=getQuest(arg1);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"QVAR","Syntax",funcParms);
return returnable;
}
if(Q==null)
returnable=false;
else
returnable=simpleEvalStr(scripted,Q.getStat(arg2),arg4,arg3,"QVAR");
break;
}
case 84: // math
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
if(!CMath.isMathExpression(arg1))
{
logError(scripted,"MATH","Syntax",funcParms);
return returnable;
}
if(!CMath.isMathExpression(arg3))
{
logError(scripted,"MATH","Syntax",funcParms);
return returnable;
}
returnable=simpleExpressionEval(scripted,arg1,arg3,arg2,"MATH");
break;
}
case 81: // trains
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"TRAINS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final int val1=((MOB)E).getTrains();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"TRAINS");
}
break;
}
case 82: // pracs
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"PRACS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final int val1=((MOB)E).getPractices();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"PRACS");
}
break;
}
case 66: // clanrank
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"CLANRANK","Syntax",funcParms);
return returnable;
}
if(!(E instanceof MOB))
returnable=false;
else
{
int val1=-1;
Clan C=CMLib.clans().findRivalrousClan((MOB)E);
if(C==null)
C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null;
if(C!=null)
val1=((MOB)E).getClanRole(C.clanID()).second.intValue();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"CLANRANK");
}
break;
}
case 64: // deity
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"DEITY","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final String sex=((MOB)E).getWorshipCharID();
if(arg2.equals("=="))
returnable=sex.equalsIgnoreCase(arg3);
else
if(arg2.equals("!="))
returnable=!sex.equalsIgnoreCase(arg3);
else
{
logError(scripted,"DEITY","Syntax",funcParms);
return returnable;
}
}
break;
}
case 68: // clandata
{
if(tlen==1)
tt=parseBits(eval,t,"cccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=tt[t+2];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"CLANDATA","Syntax",funcParms);
return returnable;
}
String clanID=null;
if((E!=null)&&(E instanceof MOB))
{
Clan C=CMLib.clans().findRivalrousClan((MOB)E);
if(C==null)
C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null;
if(C!=null)
clanID=C.clanID();
}
else
{
clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1);
if((scripted instanceof MOB)
&&(CMLib.clans().getClanAnyHost(clanID)==null))
{
final List<Pair<Clan,Integer>> Cs=CMLib.clans().getClansByCategory((MOB)scripted, clanID);
if((Cs!=null)&&(Cs.size()>0))
clanID=Cs.get(0).first.clanID();
}
}
final Clan C=CMLib.clans().findClan(clanID);
if(C!=null)
{
if(!C.isStat(arg2))
logError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable.");
else
{
final String whichVal=C.getStat(arg2).trim();
if(CMath.isNumber(whichVal)&&CMath.isNumber(arg4.trim()))
returnable=simpleEval(scripted,whichVal,arg4,arg3,"CLANDATA");
else
returnable=simpleEvalStr(scripted,whichVal,arg4,arg3,"CLANDATA");
}
}
break;
}
case 98: // clanqualifies
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"CLANQUALIFIES","Syntax",funcParms);
return returnable;
}
final Clan C=CMLib.clans().findClan(arg2);
if((C!=null)&&(E instanceof MOB))
{
final MOB mob=(MOB)E;
if(C.isOnlyFamilyApplicants()
&&(!CMLib.clans().isFamilyOfMembership(mob,C.getMemberList())))
returnable=false;
else
if(CMLib.clans().getClansByCategory(mob, C.getCategory()).size()>CMProps.getMaxClansThisCategory(C.getCategory()))
returnable=false;
if(returnable && (!CMLib.masking().maskCheck(C.getBasicRequirementMask(), mob, true)))
returnable=false;
else
if(returnable && (CMLib.masking().maskCheck(C.getAcceptanceSettings(),mob,true)))
returnable=false;
}
else
{
logError(scripted,"CLANQUALIFIES","Unknown clan "+arg2+" or "+arg1+" is not a mob",funcParms);
return returnable;
}
break;
}
case 65: // clan
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"CLAN","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
String clanID="";
Clan C=CMLib.clans().findRivalrousClan((MOB)E);
if(C==null)
C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null;
if(C!=null)
clanID=C.clanID();
if(arg2.equals("=="))
returnable=clanID.equalsIgnoreCase(arg3);
else
if(arg2.equals("!="))
returnable=!clanID.equalsIgnoreCase(arg3);
else
if(arg2.equals("in"))
returnable=((MOB)E).getClanRole(arg3)!=null;
else
if(arg2.equals("notin"))
returnable=((MOB)E).getClanRole(arg3)==null;
else
{
logError(scripted,"CLAN","Syntax",funcParms);
return returnable;
}
}
break;
}
case 88: // mood
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Physical P=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()==0)
{
logError(scripted,"MOOD","Syntax",funcParms);
return returnable;
}
if((P==null)||(!(P instanceof MOB)))
returnable=false;
else
{
final Ability moodA=P.fetchEffect("Mood");
if(moodA!=null)
{
final String sex=moodA.text();
if(arg2.equals("=="))
returnable=sex.equalsIgnoreCase(arg3);
else
if(arg2.equals("!="))
returnable=!sex.equalsIgnoreCase(arg3);
else
{
logError(scripted,"MOOD","Syntax",funcParms);
return returnable;
}
}
}
break;
}
case 21: // class
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"CLASS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final String sex=((MOB)E).charStats().displayClassName().toUpperCase();
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"CLASS","Syntax",funcParms);
return returnable;
}
}
break;
}
case 22: // baseclass
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"CLASS","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final String sex=((MOB)E).charStats().getCurrentClass().baseClass().toUpperCase();
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"CLASS","Syntax",funcParms);
return returnable;
}
}
break;
}
case 23: // race
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"RACE","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final String sex=((MOB)E).charStats().raceName().toUpperCase();
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"RACE","Syntax",funcParms);
return returnable;
}
}
break;
}
case 24: //racecat
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"RACECAT","Syntax",funcParms);
return returnable;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final String sex=((MOB)E).charStats().getMyRace().racialCategory().toUpperCase();
if(arg2.equals("=="))
returnable=sex.startsWith(arg3);
else
if(arg2.equals("!="))
returnable=!sex.startsWith(arg3);
else
{
logError(scripted,"RACECAT","Syntax",funcParms);
return returnable;
}
}
break;
}
case 25: // goldamt
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"GOLDAMT","Syntax",funcParms);
break;
}
if(E==null)
returnable=false;
else
{
int val1=0;
if(E instanceof MOB)
val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted)));
else
if(E instanceof Coins)
val1=(int)Math.round(((Coins)E).getTotalValue());
else
if(E instanceof Item)
val1=((Item)E).value();
else
{
logError(scripted,"GOLDAMT","Syntax",funcParms);
return returnable;
}
returnable=simpleEval(scripted,""+val1,arg3,arg2,"GOLDAMT");
}
break;
}
case 78: // exp
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"EXP","Syntax",funcParms);
break;
}
if((E==null)||(!(E instanceof MOB)))
returnable=false;
else
{
final int val1=((MOB)E).getExperience();
returnable=simpleEval(scripted,""+val1,arg3,arg2,"EXP");
}
break;
}
case 76: // value
{
if(tlen==1)
tt=parseBits(eval,t,"cccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+1]);
final String arg3=tt[t+2];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
if((arg2.length()==0)||(arg3.length()==0)||(arg4.length()==0))
{
logError(scripted,"VALUE","Syntax",funcParms);
break;
}
if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase()))
{
logError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency.");
break;
}
if(E==null)
returnable=false;
else
{
int val1=0;
if(E instanceof MOB)
val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2.toUpperCase()));
else
if(E instanceof Coins)
{
if(((Coins)E).getCurrency().equalsIgnoreCase(arg2))
val1=(int)Math.round(((Coins)E).getTotalValue());
}
else
if(E instanceof Item)
val1=((Item)E).value();
else
{
logError(scripted,"VALUE","Syntax",funcParms);
return returnable;
}
returnable=simpleEval(scripted,""+val1,arg4,arg3,"GOLDAMT");
}
break;
}
case 26: // objtype
{
if(tlen==1)
tt=parseBits(eval,t,"ccR"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"OBJTYPE","Syntax",funcParms);
return returnable;
}
if(E==null)
returnable=false;
else
{
final String sex=CMClass.classID(E).toUpperCase();
if(arg2.equals("=="))
returnable=sex.indexOf(arg3)>=0;
else
if(arg2.equals("!="))
returnable=sex.indexOf(arg3)<0;
else
{
logError(scripted,"OBJTYPE","Syntax",funcParms);
return returnable;
}
}
break;
}
case 27: // var
{
if(tlen==1)
tt=parseBits(eval,t,"cCcr"); /* tt[t+0] */
final String arg1=tt[t+0];
final String arg2=tt[t+1];
final String arg3=tt[t+2];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+3]);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"VAR","Syntax",funcParms);
return returnable;
}
final String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS))
Log.debugOut("(VAR "+arg1+" "+arg2 +"["+val+"] "+arg3+" "+arg4);
if(arg3.equals("==")||arg3.equals("="))
returnable=val.equals(arg4);
else
if(arg3.equals("!=")||(arg3.contentEquals("<>")))
returnable=!val.equals(arg4);
else
if(arg3.equals(">"))
returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim());
else
if(arg3.equals("<"))
returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim());
else
if(arg3.equals(">="))
returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim());
else
if(arg3.equals("<="))
returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim());
else
{
logError(scripted,"VAR","Syntax",funcParms);
return returnable;
}
break;
}
case 41: // eval
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]);
final String arg3=tt[t+1];
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]);
if(arg3.length()==0)
{
logError(scripted,"EVAL","Syntax",funcParms);
return returnable;
}
if(arg3.equals("=="))
returnable=val.equals(arg4);
else
if(arg3.equals("!="))
returnable=!val.equals(arg4);
else
if(arg3.equals(">"))
returnable=CMath.s_int(val.trim())>CMath.s_int(arg4.trim());
else
if(arg3.equals("<"))
returnable=CMath.s_int(val.trim())<CMath.s_int(arg4.trim());
else
if(arg3.equals(">="))
returnable=CMath.s_int(val.trim())>=CMath.s_int(arg4.trim());
else
if(arg3.equals("<="))
returnable=CMath.s_int(val.trim())<=CMath.s_int(arg4.trim());
else
{
logError(scripted,"EVAL","Syntax",funcParms);
return returnable;
}
break;
}
case 40: // number
{
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim();
boolean isnumber=(val.length()>0);
for(int i=0;i<val.length();i++)
{
if(!Character.isDigit(val.charAt(i)))
{
isnumber = false;
break;
}
}
returnable=isnumber;
break;
}
case 42: // randnum
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase().trim();
int arg1=0;
if(CMath.isMathExpression(arg1s.trim()))
arg1=CMath.s_parseIntExpression(arg1s.trim());
else
arg1=CMParms.parse(arg1s.trim()).size();
final String arg2=tt[t+1];
final String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]).trim();
int arg3=0;
if(CMath.isMathExpression(arg3s.trim()))
arg3=CMath.s_parseIntExpression(arg3s.trim());
else
arg3=CMParms.parse(arg3s.trim()).size();
arg1=CMLib.dice().roll(1,arg1,0);
returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RANDNUM");
break;
}
case 71: // rand0num
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+0]).toUpperCase().trim();
int arg1=0;
if(CMath.isMathExpression(arg1s))
arg1=CMath.s_parseIntExpression(arg1s);
else
arg1=CMParms.parse(arg1s).size();
final String arg2=tt[t+1];
final String arg3s=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[t+2]).trim();
int arg3=0;
if(CMath.isMathExpression(arg3s))
arg3=CMath.s_parseIntExpression(arg3s);
else
arg3=CMParms.parse(arg3s).size();
arg1=CMLib.dice().roll(1,arg1,-1);
returnable=simpleEval(scripted,""+arg1,""+arg3,arg2,"RAND0NUM");
break;
}
case 53: // incontainer
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=tt[t+1];
final Environmental E2=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
returnable=false;
else
if(E instanceof MOB)
{
if(arg2.length()==0)
returnable=(((MOB)E).riding()==null);
else
if(E2!=null)
returnable=(((MOB)E).riding()==E2);
else
returnable=false;
}
else
if(E instanceof Item)
{
if(arg2.length()==0)
returnable=(((Item)E).container()==null);
else
if(E2!=null)
returnable=(((Item)E).container()==E2);
else
returnable=false;
}
else
returnable=false;
break;
}
case 96: // iscontents
{
if(tlen==1)
tt=parseBits(eval,t,"cr"); /* tt[t+0] */
final String arg1=tt[t+0];
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp, tt[t+1]);
if(E==null)
returnable=false;
else
if(E instanceof Rideable)
{
if(arg2.length()==0)
returnable=((Rideable)E).numRiders()==0;
else
returnable=CMLib.english().fetchEnvironmental(new XVector<Rider>(((Rideable)E).riders()), arg2, false)!=null;
}
if(E instanceof Container)
{
if(arg2.length()==0)
returnable=!((Container)E).hasContent();
else
returnable=CMLib.english().fetchEnvironmental(((Container)E).getDeepContents(), arg2, false)!=null;
}
else
returnable=false;
break;
}
case 97: // wornon
{
if(tlen==1)
tt=parseBits(eval,t,"ccr"); /* tt[t+0] */
final String arg1=tt[t+0];
final PhysicalAgent E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp, tt[t+1]);
final String arg3=varify(source, target, scripted, monster, primaryItem, secondaryItem, msg, tmp, tt[t+2]);
if((arg2.length()==0)||(arg3.length()==0))
{
logError(scripted,"WORNON","Syntax",funcParms);
return returnable;
}
final int wornLoc = CMParms.indexOf(Wearable.CODES.NAMESUP(), arg2.toUpperCase().trim());
returnable=false;
if(wornLoc<0)
logError(scripted,"EVAL","BAD WORNON LOCATION",arg2);
else
if(E instanceof MOB)
{
final List<Item> items=((MOB)E).fetchWornItems(Wearable.CODES.GET(wornLoc),(short)-2048,(short)0);
if((items.size()==0)&&(arg3.length()==0))
returnable=true;
else
returnable = CMLib.english().fetchEnvironmental(items, arg3, false)!=null;
}
break;
}
default:
logError(scripted,"EVAL","UNKNOWN",CMParms.toListString(tt));
return false;
}
pushEvalBoolean(stack,returnable);
while((t<tt.length)&&(!tt[t].equals(")")))
t++;
}
else
{
logError(scripted,"EVAL","SYNTAX","BAD CONJUCTOR "+tt[t]+": "+CMParms.toListString(tt));
return false;
}
}
if((stack.size()!=1)
||(!(stack.get(0) instanceof Boolean)))
{
logError(scripted,"EVAL","SYNTAX","Unmatched (: "+CMParms.toListString(tt));
return false;
}
return ((Boolean)stack.get(0)).booleanValue();
}
protected void setShopPrice(final ShopKeeper shopHere, final Environmental E, final Object[] tmp)
{
if(shopHere instanceof MOB)
{
final ShopKeeper.ShopPrice price = CMLib.coffeeShops().sellingPrice((MOB)shopHere, null, E, shopHere, shopHere.getShop(), true);
if(price.experiencePrice>0)
tmp[SPECIAL_9SHOPHASPRICE] = price.experiencePrice+"xp";
else
if(price.questPointPrice>0)
tmp[SPECIAL_9SHOPHASPRICE] = price.questPointPrice+"qp";
else
tmp[SPECIAL_9SHOPHASPRICE] = CMLib.beanCounter().abbreviatedPrice((MOB)shopHere,price.absoluteGoldPrice);
}
}
@Override
public String functify(final PhysicalAgent scripted,
final MOB source,
final Environmental target,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final String msg,
final Object[] tmp,
final String evaluable)
{
if(evaluable.length()==0)
return "";
final StringBuffer results = new StringBuffer("");
final int y=evaluable.indexOf('(');
final int z=evaluable.indexOf(')',y);
final String preFab=(y>=0)?evaluable.substring(0,y).toUpperCase().trim():"";
Integer funcCode=funcH.get(preFab);
if(funcCode==null)
funcCode=Integer.valueOf(0);
if((y<0)||(z<y))
{
logError(scripted,"()","Syntax",evaluable);
return "";
}
else
{
tickStatus=Tickable.STATUS_MISC2+funcCode.intValue();
final String funcParms=evaluable.substring(y+1,z).trim();
switch(funcCode.intValue())
{
case 1: // rand
{
results.append(CMLib.dice().rollPercentage());
break;
}
case 2: // has
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
ArrayList<Item> choices=new ArrayList<Item>();
if(E==null)
choices=new ArrayList<Item>();
else
if(E instanceof MOB)
{
for(int i=0;i<((MOB)E).numItems();i++)
{
final Item I=((MOB)E).getItem(i);
if((I!=null)&&(I.amWearingAt(Wearable.IN_INVENTORY))&&(I.container()==null))
choices.add(I);
}
}
else
if(E instanceof Item)
{
if(E instanceof Container)
choices.addAll(((Container)E).getDeepContents());
else
choices.add((Item)E);
}
else
if(E instanceof Room)
{
for(int i=0;i<((Room)E).numItems();i++)
{
final Item I=((Room)E).getItem(i);
if((I!=null)&&(I.container()==null))
choices.add(I);
}
}
if(choices.size()>0)
results.append(choices.get(CMLib.dice().roll(1,choices.size(),-1)).name());
break;
}
case 74: // hasnum
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String item=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1));
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((item.length()==0)||(E==null))
logError(scripted,"HASNUM","Syntax",funcParms);
else
{
Item I=null;
int num=0;
if(E instanceof MOB)
{
final MOB M=(MOB)E;
for(int i=0;i<M.numItems();i++)
{
I=M.getItem(i);
if(I==null)
break;
if((item.equalsIgnoreCase("all"))
||(CMLib.english().containsString(I.Name(),item)))
num++;
}
results.append(""+num);
}
else
if(E instanceof Item)
{
num=CMLib.english().containsString(E.name(),item)?1:0;
results.append(""+num);
}
else
if(E instanceof Room)
{
final Room R=(Room)E;
for(int i=0;i<R.numItems();i++)
{
I=R.getItem(i);
if(I==null)
break;
if((item.equalsIgnoreCase("all"))
||(CMLib.english().containsString(I.Name(),item)))
num++;
}
results.append(""+num);
}
}
break;
}
case 3: // worn
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
ArrayList<Item> choices=new ArrayList<Item>();
if(E==null)
choices=new ArrayList<Item>();
else
if(E instanceof MOB)
{
for(int i=0;i<((MOB)E).numItems();i++)
{
final Item I=((MOB)E).getItem(i);
if((I!=null)&&(!I.amWearingAt(Wearable.IN_INVENTORY))&&(I.container()==null))
choices.add(I);
}
}
else
if((E instanceof Item)&&(!(((Item)E).amWearingAt(Wearable.IN_INVENTORY))))
{
if(E instanceof Container)
choices.addAll(((Container)E).getDeepContents());
else
choices.add((Item)E);
}
if(choices.size()>0)
results.append(choices.get(CMLib.dice().roll(1,choices.size(),-1)).name());
break;
}
case 4: // isnpc
case 5: // ispc
results.append("[unimplemented function]");
break;
case 87: // isbirthday
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getBirthday()!=null))
{
final MOB mob=(MOB)E;
final TimeClock C=CMLib.time().localClock(mob.getStartRoom());
final int day=C.getDayOfMonth();
final int month=C.getMonth();
int year=C.getYear();
final int bday=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_DAY];
final int bmonth=mob.playerStats().getBirthday()[PlayerStats.BIRTHDEX_MONTH];
if((month>bmonth)||((month==bmonth)&&(day>bday)))
year++;
final StringBuffer timeDesc=new StringBuffer("");
if(C.getDaysInWeek()>0)
{
long x=((long)year)*((long)C.getMonthsInYear())*C.getDaysInMonth();
x=x+((long)(bmonth-1))*((long)C.getDaysInMonth());
x=x+bmonth;
timeDesc.append(C.getWeekNames()[(int)(x%C.getDaysInWeek())]+", ");
}
timeDesc.append("the "+bday+CMath.numAppendage(bday));
timeDesc.append(" day of "+C.getMonthNames()[bmonth-1]);
if(C.getYearNames().length>0)
timeDesc.append(", "+CMStrings.replaceAll(C.getYearNames()[year%C.getYearNames().length],"#",""+year));
results.append(timeDesc.toString());
}
break;
}
case 6: // isgood
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB)))
{
final Faction.FRange FR=CMLib.factions().getRange(CMLib.factions().getAlignmentID(),((MOB)E).fetchFaction(CMLib.factions().getAlignmentID()));
if(FR!=null)
results.append(FR.name());
else
results.append(((MOB)E).fetchFaction(CMLib.factions().getAlignmentID()));
}
break;
}
case 8: // isevil
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB)))
results.append(CMLib.flags().getAlignmentName(E).toLowerCase());
break;
}
case 9: // isneutral
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB)))
results.append(((MOB)E).fetchFaction(CMLib.factions().getAlignmentID()));
break;
}
case 11: // isimmort
results.append("[unimplemented function]");
break;
case 54: // isalive
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead()))
results.append(((MOB)E).healthText(null));
else
if(E!=null)
results.append(E.name()+" is dead.");
break;
}
case 58: // isable
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
if((E!=null)&&((E instanceof MOB))&&(!((MOB)E).amDead()))
{
final ExpertiseLibrary X=(ExpertiseLibrary)CMLib.expertises().findDefinition(arg2,true);
if(X!=null)
{
final Pair<String,Integer> s=((MOB)E).fetchExpertise(X.ID());
if(s!=null)
results.append(s.getKey()+((s.getValue()!=null)?s.getValue().toString():""));
}
else
{
final Ability A=((MOB)E).findAbility(arg2);
if(A!=null)
results.append(""+A.proficiency());
}
}
break;
}
case 59: // isopen
{
final String arg1=CMParms.cleanBit(funcParms);
final int dir=CMLib.directions().getGoodDirectionCode(arg1);
boolean returnable=false;
if(dir<0)
{
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof Container))
returnable=((Container)E).isOpen();
else
if((E!=null)&&(E instanceof Exit))
returnable=((Exit)E).isOpen();
}
else
if(lastKnownLocation!=null)
{
final Exit E=lastKnownLocation.getExitInDir(dir);
if(E!=null)
returnable= E.isOpen();
}
results.append(""+returnable);
break;
}
case 60: // islocked
{
final String arg1=CMParms.cleanBit(funcParms);
final int dir=CMLib.directions().getGoodDirectionCode(arg1);
if(dir<0)
{
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof Container))
results.append(((Container)E).keyName());
else
if((E!=null)&&(E instanceof Exit))
results.append(((Exit)E).keyName());
}
else
if(lastKnownLocation!=null)
{
final Exit E=lastKnownLocation.getExitInDir(dir);
if(E!=null)
results.append(E.keyName());
}
break;
}
case 62: // callfunc
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0));
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
String found=null;
boolean validFunc=false;
final List<DVector> scripts=getScripts();
String trigger=null;
String[] ttrigger=null;
for(int v=0;v<scripts.size();v++)
{
final DVector script2=scripts.get(v);
if(script2.size()<1)
continue;
trigger=((String)script2.elementAt(0,1)).toUpperCase().trim();
ttrigger=(String[])script2.elementAt(0,2);
if(getTriggerCode(trigger,ttrigger)==17)
{
final String fnamed=CMParms.getCleanBit(trigger,1);
if(fnamed.equalsIgnoreCase(arg1))
{
validFunc=true;
found=
execute(scripted,
source,
target,
monster,
primaryItem,
secondaryItem,
script2,
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2),
tmp);
if(found==null)
found="";
break;
}
}
}
if(!validFunc)
logError(scripted,"CALLFUNC","Unknown","Function: "+arg1);
else
results.append(found);
break;
}
case 61: // strin
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0));
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
final List<String> V=CMParms.parse(arg1.toUpperCase());
results.append(V.indexOf(arg2.toUpperCase()));
break;
}
case 55: // ispkill
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||(!(E instanceof MOB)))
results.append("false");
else
if(((MOB)E).isAttributeSet(MOB.Attrib.PLAYERKILL))
results.append("true");
else
results.append("false");
break;
}
case 10: // isfight
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&((E instanceof MOB))&&(((MOB)E).isInCombat()))
results.append(((MOB)E).getVictim().name());
break;
}
case 12: // ischarmed
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
final List<Ability> V=CMLib.flags().flaggedAffects(E,Ability.FLAG_CHARMING);
for(int v=0;v<V.size();v++)
results.append((V.get(v).name())+" ");
}
break;
}
case 15: // isfollow
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).amFollowing()!=null)
&&(((MOB)E).amFollowing().location()==lastKnownLocation))
results.append(((MOB)E).amFollowing().name());
break;
}
case 73: // isservant
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).getLiegeID()!=null)&&(((MOB)E).getLiegeID().length()>0))
results.append(((MOB)E).getLiegeID());
break;
}
case 95: // isspeaking
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
final MOB TM=(MOB)E;
final Language L=CMLib.utensils().getLanguageSpoken(TM);
if(L!=null)
results.append(L.Name());
else
results.append("Common");
}
break;
}
case 56: // name
case 7: // isname
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
results.append(E.name());
break;
}
case 75: // currency
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
results.append(CMLib.beanCounter().getCurrency(E));
break;
}
case 14: // affected
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E instanceof Physical)&&(((Physical)E).numEffects()>0))
results.append(((Physical)E).effects().nextElement().name());
break;
}
case 69: // isbehave
{
final String arg1=CMParms.cleanBit(funcParms);
final PhysicalAgent E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
for(final Enumeration<Behavior> e=E.behaviors();e.hasMoreElements();)
{
final Behavior B=e.nextElement();
if(B!=null)
results.append(B.ID()+" ");
}
}
break;
}
case 70: // ipaddress
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster()))
results.append(((MOB)E).session().getAddress());
break;
}
case 28: // questwinner
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster()))
{
for(int q=0;q<CMLib.quests().numQuests();q++)
{
final Quest Q=CMLib.quests().fetchQuest(q);
if((Q!=null)&&(Q.wasWinner(E.Name())))
results.append(Q.name()+" ");
}
}
break;
}
case 93: // questscripted
{
final String arg1=CMParms.cleanBit(funcParms);
final PhysicalAgent E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(!((MOB)E).isMonster()))
{
for(final Enumeration<ScriptingEngine> e=E.scripts();e.hasMoreElements();)
{
final ScriptingEngine SE=e.nextElement();
if((SE!=null)&&(SE.defaultQuestName()!=null)&&(SE.defaultQuestName().length()>0))
{
final Quest Q=CMLib.quests().fetchQuest(SE.defaultQuestName());
if(Q!=null)
results.append(Q.name()+" ");
else
results.append(SE.defaultQuestName()+" ");
}
}
for(final Enumeration<Behavior> e=E.behaviors();e.hasMoreElements();)
{
final Behavior B=e.nextElement();
if(B instanceof ScriptingEngine)
{
final ScriptingEngine SE=(ScriptingEngine)B;
if((SE.defaultQuestName()!=null)&&(SE.defaultQuestName().length()>0))
{
final Quest Q=CMLib.quests().fetchQuest(SE.defaultQuestName());
if(Q!=null)
results.append(Q.name()+" ");
else
results.append(SE.defaultQuestName()+" ");
}
}
}
}
break;
}
case 30: // questobj
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
if(questName.equals("*") && (this.defaultQuestName()!=null) && (this.defaultQuestName().length()>0))
questName = this.defaultQuestName();
final Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
final StringBuffer list=new StringBuffer("");
int num=1;
Environmental E=Q.getQuestItem(num);
while(E!=null)
{
if(E.Name().indexOf(' ')>=0)
list.append("\""+E.Name()+"\" ");
else
list.append(E.Name()+" ");
num++;
E=Q.getQuestItem(num);
}
results.append(list.toString().trim());
break;
}
case 94: // questroom
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
final Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
final StringBuffer list=new StringBuffer("");
int num=1;
Environmental E=Q.getQuestRoom(num);
while(E!=null)
{
final String roomID=CMLib.map().getExtendedRoomID((Room)E);
if(roomID.indexOf(' ')>=0)
list.append("\""+roomID+"\" ");
else
list.append(roomID+" ");
num++;
E=Q.getQuestRoom(num);
}
results.append(list.toString().trim());
break;
}
case 114: // questarea
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
final Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
final StringBuffer list=new StringBuffer("");
int num=1;
Environmental E=Q.getQuestRoom(num);
while(E!=null)
{
final String areaName=CMLib.map().areaLocation(E).name();
if(list.indexOf(areaName)<0)
{
if(areaName.indexOf(' ')>=0)
list.append("\""+areaName+"\" ");
else
list.append(areaName+" ");
}
num++;
E=Q.getQuestRoom(num);
}
results.append(list.toString().trim());
break;
}
case 29: // questmob
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
if(questName.equals("*") && (this.defaultQuestName()!=null) && (this.defaultQuestName().length()>0))
questName=this.defaultQuestName();
final Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
final StringBuffer list=new StringBuffer("");
int num=1;
Environmental E=Q.getQuestMob(num);
while(E!=null)
{
if(E.Name().indexOf(' ')>=0)
list.append("\""+E.Name()+"\" ");
else
list.append(E.Name()+" ");
num++;
E=Q.getQuestMob(num);
}
results.append(list.toString().trim());
break;
}
case 31: // isquestmobalive
{
String questName=CMParms.cleanBit(funcParms);
questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,questName);
final Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"QUESTOBJ","Unknown","Quest: "+questName);
break;
}
final StringBuffer list=new StringBuffer("");
int num=1;
MOB E=Q.getQuestMob(num);
while(E!=null)
{
if(CMLib.flags().isInTheGame(E,true))
{
if(E.Name().indexOf(' ')>=0)
list.append("\""+E.Name()+"\" ");
else
list.append(E.Name()+" ");
}
num++;
E=Q.getQuestMob(num);
}
results.append(list.toString().trim());
break;
}
case 49: // hastattoo
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
for(final Enumeration<Tattoo> t = ((MOB)E).tattoos();t.hasMoreElements();)
results.append(t.nextElement().ID()).append(" ");
}
break;
}
case 109: // hastattootime
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
final Tattoo T=((MOB)E).findTattoo(arg2);
if(T!=null)
results.append(T.getTickDown());
}
break;
}
case 99: // hasacctattoo
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null)&&(((MOB)E).playerStats().getAccount()!=null))
{
for(final Enumeration<Tattoo> t = ((MOB)E).playerStats().getAccount().tattoos();t.hasMoreElements();)
results.append(t.nextElement().ID()).append(" ");
}
break;
}
case 32: // nummobsinarea
{
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
int num=0;
MaskingLibrary.CompiledZMask MASK=null;
if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("="))))
{
arg1=arg1.substring(4).trim();
arg1=arg1.substring(1).trim();
MASK=CMLib.masking().maskCompile(arg1);
}
for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
final Room R=e.nextElement();
if(arg1.equals("*"))
num+=R.numInhabitants();
else
{
for(int m=0;m<R.numInhabitants();m++)
{
final MOB M=R.fetchInhabitant(m);
if(M==null)
continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.name(),arg1))
num++;
}
}
}
results.append(num);
break;
}
case 33: // nummobs
{
int num=0;
String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
MaskingLibrary.CompiledZMask MASK=null;
if((arg1.toUpperCase().startsWith("MASK")&&(arg1.substring(4).trim().startsWith("="))))
{
arg1=arg1.substring(4).trim();
arg1=arg1.substring(1).trim();
MASK=CMLib.masking().maskCompile(arg1);
}
try
{
for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();)
{
final Room R=e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
final MOB M=R.fetchInhabitant(m);
if(M==null)
continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.name(),arg1))
num++;
}
}
}
catch(final NoSuchElementException nse)
{
}
results.append(num);
break;
}
case 34: // numracesinarea
{
int num=0;
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
Room R=null;
MOB M=null;
for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
R=e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
M=R.fetchInhabitant(m);
if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1)))
num++;
}
}
results.append(num);
break;
}
case 35: // numraces
{
int num=0;
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
Room R=null;
MOB M=null;
try
{
for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();)
{
R=e.nextElement();
for(int m=0;m<R.numInhabitants();m++)
{
M=R.fetchInhabitant(m);
if((M!=null)&&(M.charStats().raceName().equalsIgnoreCase(arg1)))
num++;
}
}
}
catch (final NoSuchElementException nse)
{
}
results.append(num);
break;
}
case 112: // cansee
{
break;
}
case 113: // canhear
{
break;
}
case 111: // itemcount
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
int num=0;
if(E instanceof Container)
{
num++;
for(final Item I : ((Container)E).getContents())
num+=I.numberOfItems();
}
else
if(E instanceof Item)
num=((Item)E).numberOfItems();
else
if(E instanceof MOB)
{
for(final Enumeration<Item> i=((MOB)E).items();i.hasMoreElements();)
num += i.nextElement().numberOfItems();
}
else
if(E instanceof Room)
{
for(final Enumeration<Item> i=((Room)E).items();i.hasMoreElements();)
num += i.nextElement().numberOfItems();
}
else
if(E instanceof Area)
{
for(final Enumeration<Room> r=((Area)E).getFilledCompleteMap();r.hasMoreElements();)
{
for(final Enumeration<Item> i=r.nextElement().items();i.hasMoreElements();)
num += i.nextElement().numberOfItems();
}
}
results.append(""+num);
}
break;
}
case 16: // hitprcnt
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
final double hitPctD=CMath.div(((MOB)E).curState().getHitPoints(),((MOB)E).maxState().getHitPoints());
final int val1=(int)Math.round(hitPctD*100.0);
results.append(val1);
}
break;
}
case 50: // isseason
{
if(monster.location()!=null)
results.append(monster.location().getArea().getTimeObj().getSeasonCode().toString());
break;
}
case 51: // isweather
{
if(monster.location()!=null)
results.append(Climate.WEATHER_DESCS[monster.location().getArea().getClimateObj().weatherType(monster.location())]);
break;
}
case 57: // ismoon
{
if(monster.location()!=null)
results.append(monster.location().getArea().getTimeObj().getMoonPhase(monster.location()).toString());
break;
}
case 38: // istime
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.getArea().getTimeObj().getTODCode().getDesc().toLowerCase());
break;
}
case 110: // ishour
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.getArea().getTimeObj().getHourOfDay());
break;
}
case 103: // ismonth
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.getArea().getTimeObj().getMonth());
break;
}
case 104: // isyear
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.getArea().getTimeObj().getYear());
break;
}
case 105: // isrlhour
{
if(lastKnownLocation!=null)
results.append(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));
break;
}
case 106: // isrlday
{
if(lastKnownLocation!=null)
results.append(Calendar.getInstance().get(Calendar.DATE));
break;
}
case 107: // isrlmonth
{
if(lastKnownLocation!=null)
results.append(Calendar.getInstance().get(Calendar.MONTH));
break;
}
case 108: // isrlyear
{
if(lastKnownLocation!=null)
results.append(Calendar.getInstance().get(Calendar.YEAR));
break;
}
case 39: // isday
{
if(lastKnownLocation!=null)
results.append(""+lastKnownLocation.getArea().getTimeObj().getDayOfMonth());
break;
}
case 43: // roommob
{
final String clean=CMParms.cleanBit(funcParms);
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,clean);
Environmental which=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
{
final Environmental E=this.getArgumentItem(clean, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(E!=null)
which=E;
else
which=lastKnownLocation.fetchInhabitant(arg1.trim());
}
if(which!=null)
{
final List<MOB> list=new ArrayList<MOB>();
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
{
final MOB M=lastKnownLocation.fetchInhabitant(i);
if(M!=null)
list.add(M);
}
results.append(CMLib.english().getContextName(list,which));
}
}
break;
}
case 44: // roomitem
{
final String clean=CMParms.cleanBit(funcParms);
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,clean);
Environmental which=null;
if(!CMath.isInteger(arg1))
which=this.getArgumentItem(clean, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
int ct=1;
if(lastKnownLocation!=null)
{
final List<Item> list=new ArrayList<Item>();
if(which == null)
{
for(int i=0;i<lastKnownLocation.numItems();i++)
{
final Item I=lastKnownLocation.getItem(i);
if((I!=null)&&(I.container()==null))
{
list.add(I);
if(ct==CMath.s_int(arg1.trim()))
{
which = I;
break;
}
ct++;
}
}
}
if(which!=null)
results.append(CMLib.english().getContextName(list,which));
}
break;
}
case 45: // nummobsroom
{
int num=0;
if(lastKnownLocation!=null)
{
num=lastKnownLocation.numInhabitants();
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if((name.length()>0)&&(!name.equalsIgnoreCase("*")))
{
num=0;
MaskingLibrary.CompiledZMask MASK=null;
if((name.toUpperCase().startsWith("MASK")&&(name.substring(4).trim().startsWith("="))))
{
name=name.substring(4).trim();
name=name.substring(1).trim();
MASK=CMLib.masking().maskCompile(name);
}
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
{
final MOB M=lastKnownLocation.fetchInhabitant(i);
if(M==null)
continue;
if(MASK!=null)
{
if(CMLib.masking().maskCheck(MASK,M,true))
num++;
}
else
if(CMLib.english().containsString(M.Name(),name)
||CMLib.english().containsString(M.displayText(),name))
num++;
}
}
}
results.append(""+num);
break;
}
case 63: // numpcsroom
{
final Room R=lastKnownLocation;
if(R!=null)
{
int num=0;
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if((M!=null)&&(!M.isMonster()))
num++;
}
results.append(""+num);
}
break;
}
case 115: // expertise
{
// mob ability type > 10
final String arg1=CMParms.getCleanBit(funcParms,0);
final Physical P=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
final MOB M;
if(P instanceof MOB)
{
M=(MOB)P;
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1));
Ability A=M.fetchAbility(arg2);
if(A==null)
A=getAbility(arg2);
if(A!=null)
{
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,1));
final ExpertiseLibrary.Flag experFlag = (ExpertiseLibrary.Flag)CMath.s_valueOf(ExpertiseLibrary.Flag.class, arg3.toUpperCase().trim());
if(experFlag != null)
results.append(""+CMLib.expertises().getExpertiseLevel(M, A.ID(), experFlag));
}
}
break;
}
case 79: // numpcsarea
{
if(lastKnownLocation!=null)
{
int num=0;
for(final Session S : CMLib.sessions().localOnlineIterable())
{
if((S.mob().location()!=null)&&(S.mob().location().getArea()==lastKnownLocation.getArea()))
num++;
}
results.append(""+num);
}
break;
}
case 77: // explored
{
final String whom=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0));
final String where=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,1));
final Environmental E=getArgumentMOB(whom,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
{
Area A=null;
if(!where.equalsIgnoreCase("world"))
{
A=CMLib.map().getArea(where);
if(A==null)
{
final Environmental E2=getArgumentItem(where,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E2!=null)
A=CMLib.map().areaLocation(E2);
}
}
if((lastKnownLocation!=null)
&&((A!=null)||(where.equalsIgnoreCase("world"))))
{
int pct=0;
final MOB M=(MOB)E;
if(M.playerStats()!=null)
pct=M.playerStats().percentVisited(M,A);
results.append(""+pct);
}
}
break;
}
case 72: // faction
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBit(funcParms,0);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
final Faction F=CMLib.factions().getFaction(arg2);
if(F==null)
logError(scripted,"FACTION","Unknown Faction",arg1);
else
if((E!=null)&&(E instanceof MOB)&&(((MOB)E).hasFaction(F.factionID())))
{
final int value=((MOB)E).fetchFaction(F.factionID());
final Faction.FRange FR=CMLib.factions().getRange(F.factionID(),value);
if(FR!=null)
results.append(FR.name());
}
break;
}
case 46: // numitemsroom
{
int ct=0;
if(lastKnownLocation!=null)
for(int i=0;i<lastKnownLocation.numItems();i++)
{
final Item I=lastKnownLocation.getItem(i);
if((I!=null)&&(I.container()==null))
ct++;
}
results.append(""+ct);
break;
}
case 47: //mobitem
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getCleanBit(funcParms,0));
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
MOB M=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
M=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
M=lastKnownLocation.fetchInhabitant(arg1.trim());
}
Item which=null;
int ct=1;
if(M!=null)
{
for(int i=0;i<M.numItems();i++)
{
final Item I=M.getItem(i);
if((I!=null)&&(I.container()==null))
{
if(ct==CMath.s_int(arg2.trim()))
{
which = I;
break;
}
ct++;
}
}
}
if(which!=null)
results.append(which.name());
break;
}
case 100: // shopitem
{
final String arg1raw=CMParms.getCleanBit(funcParms,0);
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1raw);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
PhysicalAgent where=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
where=lastKnownLocation.fetchInhabitant(arg1.trim());
if(where == null)
where=this.getArgumentItem(arg1raw, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(where == null)
where=this.getArgumentMOB(arg1raw, source, monster, target, primaryItem, secondaryItem, msg, tmp);
}
Environmental which=null;
int ct=1;
if(where!=null)
{
ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where);
if((shopHere == null)&&(scripted instanceof Item))
shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner());
if((shopHere == null)&&(scripted instanceof MOB))
shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location());
if(shopHere == null)
shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(shopHere!=null)
{
final CoffeeShop shop = shopHere.getShop();
if(shop != null)
{
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();ct++)
{
final Environmental E=i.next();
if(ct==CMath.s_int(arg2.trim()))
{
which = E;
setShopPrice(shopHere,E,tmp);
break;
}
}
}
}
}
if(which!=null)
results.append(which.name());
break;
}
case 101: // numitemsshop
{
final String arg1raw = CMParms.cleanBit(funcParms);
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1raw);
PhysicalAgent which=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
which=lastKnownLocation.fetchInhabitant(arg1);
if(which == null)
which=this.getArgumentItem(arg1raw, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(which == null)
which=this.getArgumentMOB(arg1raw, source, monster, target, primaryItem, secondaryItem, msg, tmp);
}
int ct=0;
if(which!=null)
{
ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(which);
if((shopHere == null)&&(scripted instanceof Item))
shopHere=CMLib.coffeeShops().getShopKeeper(((Item)which).owner());
if((shopHere == null)&&(scripted instanceof MOB))
shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)which).location());
if(shopHere == null)
shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(shopHere!=null)
{
final CoffeeShop shop = shopHere.getShop();
if(shop != null)
{
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();i.next())
{
ct++;
}
}
}
}
results.append(""+ct);
break;
}
case 102: // shophas
{
final String arg1raw=CMParms.cleanBit(funcParms);
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1raw);
PhysicalAgent where=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
where=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
where=lastKnownLocation.fetchInhabitant(arg1.trim());
if(where == null)
where=this.getArgumentItem(arg1raw, source, monster, scripted, target, primaryItem, secondaryItem, msg, tmp);
if(where == null)
where=this.getArgumentMOB(arg1raw, source, monster, target, primaryItem, secondaryItem, msg, tmp);
}
if(where!=null)
{
ShopKeeper shopHere = CMLib.coffeeShops().getShopKeeper(where);
if((shopHere == null)&&(scripted instanceof Item))
shopHere=CMLib.coffeeShops().getShopKeeper(((Item)where).owner());
if((shopHere == null)&&(scripted instanceof MOB))
shopHere=CMLib.coffeeShops().getShopKeeper(((MOB)where).location());
if(shopHere == null)
shopHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(shopHere!=null)
{
final CoffeeShop shop = shopHere.getShop();
if(shop != null)
{
int ct=0;
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();i.next())
ct++;
final int which=CMLib.dice().roll(1, ct, -1);
ct=0;
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();ct++)
{
final Environmental E=i.next();
if(which == ct)
{
results.append(E.Name());
setShopPrice(shopHere,E,tmp);
break;
}
}
}
}
}
break;
}
case 48: // numitemsmob
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
MOB which=null;
if(lastKnownLocation!=null)
{
if(CMath.isInteger(arg1.trim()))
which=lastKnownLocation.fetchInhabitant(CMath.s_int(arg1.trim())-1);
else
which=lastKnownLocation.fetchInhabitant(arg1);
}
int ct=0;
if(which!=null)
{
for(int i=0;i<which.numItems();i++)
{
final Item I=which.getItem(i);
if((I!=null)&&(I.container()==null))
ct++;
}
}
results.append(""+ct);
break;
}
case 36: // ishere
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.getArea().name());
break;
}
case 17: // inroom
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||arg1.length()==0)
results.append(CMLib.map().getExtendedRoomID(lastKnownLocation));
else
results.append(CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(E)));
break;
}
case 90: // inarea
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((E==null)||arg1.length()==0)
results.append(lastKnownLocation==null?"Nowhere":lastKnownLocation.getArea().Name());
else
{
final Room R=CMLib.map().roomLocation(E);
results.append(R==null?"Nowhere":R.getArea().Name());
}
break;
}
case 89: // isrecall
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
results.append(CMLib.map().getExtendedRoomID(CMLib.map().getStartRoom(E)));
break;
}
case 37: // inlocale
{
final String parms=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
if(parms.trim().length()==0)
{
if(lastKnownLocation!=null)
results.append(lastKnownLocation.name());
}
else
{
final Environmental E=getArgumentItem(parms,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
final Room R=CMLib.map().roomLocation(E);
if(R!=null)
results.append(R.name());
}
}
break;
}
case 18: // sex
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().genderName());
break;
}
case 91: // datetime
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final int index=CMParms.indexOf(ScriptingEngine.DATETIME_ARGS,arg1.toUpperCase().trim());
if(index<0)
logError(scripted,"DATETIME","Syntax","Unknown arg: "+arg1+" for "+scripted.name());
else
if(CMLib.map().areaLocation(scripted)!=null)
{
switch(index)
{
case 2:
results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth());
break;
case 3:
results.append(CMLib.map().areaLocation(scripted).getTimeObj().getDayOfMonth());
break;
case 4:
results.append(CMLib.map().areaLocation(scripted).getTimeObj().getMonth());
break;
case 5:
results.append(CMLib.map().areaLocation(scripted).getTimeObj().getYear());
break;
default:
results.append(CMLib.map().areaLocation(scripted).getTimeObj().getHourOfDay()); break;
}
}
break;
}
case 13: // stat
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBitClean(funcParms,0);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
final String val=getStatValue(E,arg2);
if(val==null)
{
logError(scripted,"STAT","Syntax","Unknown stat: "+arg2+" for "+E.name());
break;
}
results.append(val);
break;
}
break;
}
case 52: // gstat
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBitClean(funcParms,0);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
final String val=getGStatValue(E,arg2);
if(val==null)
{
logError(scripted,"GSTAT","Syntax","Unknown stat: "+arg2+" for "+E.name());
break;
}
results.append(val);
break;
}
break;
}
case 19: // position
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P!=null)
{
final String sex;
if(CMLib.flags().isSleeping(P))
sex="SLEEPING";
else
if(CMLib.flags().isSitting(P))
sex="SITTING";
else
sex="STANDING";
results.append(sex);
break;
}
break;
}
case 20: // level
{
final String arg1=CMParms.cleanBit(funcParms);
final Physical P=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(P!=null)
results.append(P.phyStats().level());
break;
}
case 80: // questpoints
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
results.append(((MOB)E).getQuestPoint());
break;
}
case 83: // qvar
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
if((arg1.length()!=0)&&(arg2.length()!=0))
{
final Quest Q=getQuest(arg1);
if(Q!=null)
results.append(Q.getStat(arg2));
}
break;
}
case 84: // math
{
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms));
results.append(""+Math.round(CMath.s_parseMathExpression(arg1)));
break;
}
case 85: // islike
{
final String arg1=CMParms.cleanBit(funcParms);
results.append(CMLib.masking().maskDesc(arg1));
break;
}
case 86: // strcontains
{
results.append("[unimplemented function]");
break;
}
case 81: // trains
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
results.append(((MOB)E).getTrains());
break;
}
case 92: // isodd
{
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp ,CMParms.cleanBit(funcParms)).trim();
boolean isodd = false;
if( CMath.isLong( val ) )
{
isodd = (CMath.s_long(val) %2 == 1);
}
if( isodd )
{
results.append( CMath.s_long( val.trim() ) );
}
break;
}
case 82: // pracs
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
results.append(((MOB)E).getPractices());
break;
}
case 68: // clandata
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBitClean(funcParms,0);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String clanID=null;
if((E!=null)&&(E instanceof MOB))
{
Clan C=CMLib.clans().findRivalrousClan((MOB)E);
if(C==null)
C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null;
if(C!=null)
clanID=C.clanID();
}
else
clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1);
final Clan C=CMLib.clans().findClan(clanID);
if(C!=null)
{
if(!C.isStat(arg2))
logError(scripted,"CLANDATA","RunTime",arg2+" is not a valid clan variable.");
else
results.append(C.getStat(arg2));
}
break;
}
case 98: // clanqualifies
{
final String arg1=CMParms.cleanBit(funcParms);
Clan C=CMLib.clans().getClan(arg1);
if(C==null)
C=CMLib.clans().findClan(arg1);
if(C!=null)
{
if(C.getAcceptanceSettings().length()>0)
results.append(CMLib.masking().maskDesc(C.getAcceptanceSettings()));
if(C.getBasicRequirementMask().length()>0)
results.append(CMLib.masking().maskDesc(C.getBasicRequirementMask()));
if(C.isOnlyFamilyApplicants())
results.append("Must belong to the family.");
final int total=CMProps.getMaxClansThisCategory(C.getCategory());
if(C.getCategory().length()>0)
results.append("May belong to only "+total+" "+C.getCategory()+" clan. ");
else
results.append("May belong to only "+total+" standard clan. ");
}
break;
}
case 67: // hastitle
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.getPastBitClean(funcParms,0));
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((arg2.length()>0)&&(E instanceof MOB)&&(((MOB)E).playerStats()!=null))
{
final MOB M=(MOB)E;
results.append(M.playerStats().getActiveTitle());
}
break;
}
case 66: // clanrank
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
Clan C=null;
if(E instanceof MOB)
{
C=CMLib.clans().findRivalrousClan((MOB)E);
if(C==null)
C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null;
}
else
C=CMLib.clans().findClan(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg1));
if(C!=null)
{
final Pair<Clan,Integer> p=((MOB)E).getClanRole(C.clanID());
if(p!=null)
results.append(p.second.toString());
}
break;
}
case 21: // class
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().displayClassName());
break;
}
case 64: // deity
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
final String sex=((MOB)E).getWorshipCharID();
results.append(sex);
}
break;
}
case 65: // clan
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
{
Clan C=CMLib.clans().findRivalrousClan((MOB)E);
if(C==null)
C=((MOB)E).clans().iterator().hasNext()?((MOB)E).clans().iterator().next().first:null;
if(C!=null)
results.append(C.clanID());
}
break;
}
case 88: // mood
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
{
final Ability moodA=((MOB)E).fetchEffect("Mood");
if(moodA!=null)
results.append(CMStrings.capitalizeAndLower(moodA.text()));
}
break;
}
case 22: // baseclass
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().getCurrentClass().baseClass());
break;
}
case 23: // race
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().raceName());
break;
}
case 24: //racecat
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((E!=null)&&(E instanceof MOB))
results.append(((MOB)E).charStats().getMyRace().racialCategory());
break;
}
case 25: // goldamt
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
results.append(false);
else
{
int val1=0;
if(E instanceof MOB)
val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,CMLib.beanCounter().getCurrency(scripted)));
else
if(E instanceof Coins)
val1=(int)Math.round(((Coins)E).getTotalValue());
else
if(E instanceof Item)
val1=((Item)E).value();
else
{
logError(scripted,"GOLDAMT","Syntax",funcParms);
return results.toString();
}
results.append(val1);
}
break;
}
case 78: // exp
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
results.append(false);
else
{
int val1=0;
if(E instanceof MOB)
val1=((MOB)E).getExperience();
results.append(val1);
}
break;
}
case 76: // value
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBitClean(funcParms,0);
if(!CMLib.beanCounter().getAllCurrencies().contains(arg2.toUpperCase()))
{
logError(scripted,"VALUE","Syntax",arg2+" is not a valid designated currency.");
return results.toString();
}
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E==null)
results.append(false);
else
{
int val1=0;
if(E instanceof MOB)
val1=(int)Math.round(CMLib.beanCounter().getTotalAbsoluteValue((MOB)E,arg2));
else
if(E instanceof Coins)
{
if(((Coins)E).getCurrency().equalsIgnoreCase(arg2))
val1=(int)Math.round(((Coins)E).getTotalValue());
}
else
if(E instanceof Item)
val1=((Item)E).value();
else
{
logError(scripted,"GOLDAMT","Syntax",funcParms);
return results.toString();
}
results.append(val1);
}
break;
}
case 26: // objtype
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
final String sex=CMClass.classID(E).toLowerCase();
results.append(sex);
}
break;
}
case 53: // incontainer
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
if(E instanceof MOB)
{
if(((MOB)E).riding()!=null)
results.append(((MOB)E).riding().Name());
}
else
if(E instanceof Item)
{
if(((Item)E).riding()!=null)
results.append(((Item)E).riding().Name());
else
if(((Item)E).container()!=null)
results.append(((Item)E).container().Name());
else
if(E instanceof Container)
{
final List<Item> V=((Container)E).getDeepContents();
for(int v=0;v<V.size();v++)
results.append("\""+V.get(v).Name()+"\" ");
}
}
}
break;
}
case 27: // var
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBitClean(funcParms,0).toUpperCase();
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String val=getVar(E,arg1,arg2,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
results.append(val);
break;
}
case 41: // eval
results.append("[unimplemented function]");
break;
case 40: // number
{
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).trim();
boolean isnumber=(val.length()>0);
for(int i=0;i<val.length();i++)
{
if(!Character.isDigit(val.charAt(i)))
{
isnumber = false;
break;
}
}
if(isnumber)
results.append(CMath.s_long(val.trim()));
break;
}
case 42: // randnum
{
final String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toUpperCase();
int arg1=0;
if(CMath.isMathExpression(arg1String))
arg1=CMath.s_parseIntExpression(arg1String.trim());
else
arg1=CMParms.parse(arg1String.trim()).size();
results.append(CMLib.dice().roll(1,arg1,0));
break;
}
case 71: // rand0num
{
final String arg1String=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,CMParms.cleanBit(funcParms)).toUpperCase();
int arg1=0;
if(CMath.isMathExpression(arg1String))
arg1=CMath.s_parseIntExpression(arg1String.trim());
else
arg1=CMParms.parse(arg1String.trim()).size();
results.append(CMLib.dice().roll(1,arg1,-1));
break;
}
case 96: // iscontents
{
final String arg1=CMParms.cleanBit(funcParms);
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof Rideable)
{
for(final Enumeration<Rider> r=((Rideable)E).riders();r.hasMoreElements();)
results.append(CMParms.quoteIfNecessary(r.nextElement().name())).append(" ");
}
if(E instanceof Container)
{
for (final Item item : ((Container)E).getDeepContents())
results.append(CMParms.quoteIfNecessary(item.name())).append(" ");
}
break;
}
case 97: // wornon
{
final String arg1=CMParms.getCleanBit(funcParms,0);
final String arg2=CMParms.getPastBitClean(funcParms,0).toUpperCase();
final PhysicalAgent E=getArgumentMOB(arg1,source,monster,target,primaryItem,secondaryItem,msg,tmp);
int wornLoc=-1;
if(arg2.length()>0)
wornLoc = CMParms.indexOf(Wearable.CODES.NAMESUP(), arg2.toUpperCase().trim());
if(wornLoc<0)
logError(scripted,"EVAL","BAD WORNON LOCATION",arg2);
else
if(E instanceof MOB)
{
final List<Item> items=((MOB)E).fetchWornItems(Wearable.CODES.GET(wornLoc),(short)-2048,(short)0);
for(final Item item : items)
results.append(CMParms.quoteIfNecessary(item.name())).append(" ");
}
break;
}
default:
logError(scripted,"Unknown Val",preFab,evaluable);
return results.toString();
}
}
return results.toString();
}
protected MOB getRandPC(final MOB monster, final Object[] tmp, final Room room)
{
if((tmp[SPECIAL_RANDPC]==null)||(tmp[SPECIAL_RANDPC]==monster))
{
MOB M=null;
if(room!=null)
{
final List<MOB> choices = new ArrayList<MOB>();
for(int p=0;p<room.numInhabitants();p++)
{
M=room.fetchInhabitant(p);
if((!M.isMonster())&&(M!=monster))
{
final HashSet<MOB> seen=new HashSet<MOB>();
while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M)))
{
seen.add(M);
M=M.amFollowing();
}
choices.add(M);
}
}
if(choices.size() > 0)
tmp[SPECIAL_RANDPC] = choices.get(CMLib.dice().roll(1,choices.size(),-1));
}
}
return (MOB)tmp[SPECIAL_RANDPC];
}
protected MOB getRandAnyone(final MOB monster, final Object[] tmp, final Room room)
{
if((tmp[SPECIAL_RANDANYONE]==null)||(tmp[SPECIAL_RANDANYONE]==monster))
{
MOB M=null;
if(room!=null)
{
final List<MOB> choices = new ArrayList<MOB>();
for(int p=0;p<room.numInhabitants();p++)
{
M=room.fetchInhabitant(p);
if(M!=monster)
{
final HashSet<MOB> seen=new HashSet<MOB>();
while((M.amFollowing()!=null)&&(!M.amFollowing().isMonster())&&(!seen.contains(M)))
{
seen.add(M);
M=M.amFollowing();
}
choices.add(M);
}
}
if(choices.size() > 0)
tmp[SPECIAL_RANDANYONE] = choices.get(CMLib.dice().roll(1,choices.size(),-1));
}
}
return (MOB)tmp[SPECIAL_RANDANYONE];
}
protected DVector findFunc(String named)
{
if(named==null)
return null;
named=named.toUpperCase();
final List<DVector> scripts=getScripts();
for(int v=0;v<scripts.size();v++)
{
final DVector script2=scripts.get(v);
if(script2.size()<1)
continue;
final String trigger=((String)script2.elementAt(0,1)).toUpperCase().trim();
final String[] ttrigger=(String[])script2.elementAt(0,2);
if(getTriggerCode(trigger,ttrigger)==17) // function_prog
{
final String fnamed=CMParms.getCleanBit(trigger,1);
if(fnamed.equals(named))
return script2;
}
}
for(int v=0;v<scripts.size();v++)
{
final DVector script2=scripts.get(v);
if(script2.size()<1)
continue;
final String trigger=((String)script2.elementAt(0,1)).toUpperCase().trim();
if(trigger.equals(named)||trigger.equals(named+"_PROG"))
return script2;
}
return null;
}
@Override
public boolean isFunc(final String named)
{
return findFunc(named) != null;
}
@Override
public String callFunc(final String named, final String parms, final PhysicalAgent scripted, final MOB source, final Environmental target,
final MOB monster, final Item primaryItem, final Item secondaryItem, final String msg, final Object[] tmp)
{
final DVector script2 = findFunc(named);
if(script2 != null)
{
return execute(scripted, source, target, monster, primaryItem, secondaryItem, script2,
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,parms),tmp);
}
return null;
}
@Override
public String execute(final PhysicalAgent scripted,
final MOB source,
final Environmental target,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final DVector script,
final String msg,
final Object[] tmp)
{
return execute(scripted,source,target,monster,primaryItem,secondaryItem,script,msg,tmp,1);
}
public String execute(PhysicalAgent scripted,
MOB source,
Environmental target,
MOB monster,
Item primaryItem,
Item secondaryItem,
final DVector script,
String msg,
final Object[] tmp,
final int startLine)
{
tickStatus=Tickable.STATUS_START;
String s=null;
String[] tt=null;
String cmd=null;
final boolean traceDebugging=CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTTRACE);
if(traceDebugging && startLine == 1 && script.size()>0 && script.get(0, 1).toString().trim().length()>0)
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": * EXECUTE: "+script.get(0, 1).toString());
for(int si=startLine;si<script.size();si++)
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.length()==0)
continue;
if(traceDebugging)
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": "+s);
Integer methCode=methH.get(cmd);
if((methCode==null)&&(cmd.startsWith("MP")))
{
for(int i=0;i<methods.length;i++)
{
if(methods[i].startsWith(cmd))
methCode=Integer.valueOf(i);
}
}
if(methCode==null)
methCode=Integer.valueOf(0);
tickStatus=Tickable.STATUS_MISC3+methCode.intValue();
switch(methCode.intValue())
{
case 57: // <SCRIPT>
{
if(tt==null)
tt=parseBits(script,si,"C");
final StringBuffer jscript=new StringBuffer("");
while((++si)<script.size())
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.equals("</SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
break;
}
jscript.append(s+"\n");
}
if(CMSecurity.isApprovedJScript(jscript))
{
final Context cx = Context.enter();
try
{
final JScriptEvent scope = new JScriptEvent(this,scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp);
cx.initStandardObjects(scope);
final String[] names = { "host", "source", "target", "monster", "item", "item2", "message" ,"getVar", "setVar", "toJavaString", "getCMType"};
scope.defineFunctionProperties(names, JScriptEvent.class,
ScriptableObject.DONTENUM);
cx.evaluateString(scope, jscript.toString(),"<cmd>", 1, null);
}
catch(final Exception e)
{
Log.errOut("Scripting",scripted.name()+"/"+CMLib.map().getDescriptiveExtendedRoomID(lastKnownLocation)+"/JSCRIPT Error: "+e.getMessage());
}
Context.exit();
}
else
if(CMProps.getIntVar(CMProps.Int.JSCRIPTS)==CMSecurity.JSCRIPT_REQ_APPROVAL)
{
if(lastKnownLocation!=null)
lastKnownLocation.showHappens(CMMsg.MSG_OK_ACTION,L("A Javascript was not authorized. Contact an Admin to use MODIFY JSCRIPT to authorize this script."));
}
break;
}
case 19: // if
{
if(tt==null)
{
try
{
final String[] ttParms=parseEval(s.substring(2));
tt=new String[ttParms.length+1];
tt[0]="IF";
for(int i=0;i<ttParms.length;i++)
tt[i+1]=ttParms[i];
script.setElementAt(si,2,tt);
script.setElementAt(si, 3, new Triad<DVector,DVector,Integer>(null,null,null));
}
catch(final Exception e)
{
logError(scripted,"IF","Syntax",e.getMessage());
tickStatus=Tickable.STATUS_END;
return null;
}
}
final String[][] EVAL={tt};
final boolean condition=eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,EVAL,1);
if(EVAL[0]!=tt)
{
tt=EVAL[0];
script.setElementAt(si,2,tt);
}
boolean foundendif=false;
@SuppressWarnings({ "unchecked", "rawtypes" })
Triad<DVector,DVector,Integer> parsedBlocks = (Triad)script.elementAt(si, 3);
DVector subScript;
if(parsedBlocks==null)
{
Log.errOut("Null parsed blocks in "+s);
parsedBlocks = new Triad<DVector,DVector,Integer>(null,null,null);
script.setElementAt(si, 3, parsedBlocks);
subScript=null;
}
else
if(parsedBlocks.third != null)
{
if(condition)
subScript=parsedBlocks.first;
else
subScript=parsedBlocks.second;
si=parsedBlocks.third.intValue();
si--; // because we want to be pointing at the ENDIF with si++ happens below.
foundendif=true;
}
else
subScript=null;
int depth=0;
boolean ignoreUntilEndScript=false;
si++;
boolean positiveCondition=true;
while((si<script.size())
&&(!foundendif))
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.equals("<SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
ignoreUntilEndScript=true;
}
else
if(cmd.equals("</SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
ignoreUntilEndScript=false;
}
else
if(ignoreUntilEndScript)
{
}
else
if(cmd.equals("ENDIF")&&(depth==0))
{
if(tt==null)
tt=parseBits(script,si,"C");
parsedBlocks.third=Integer.valueOf(si);
foundendif=true;
break;
}
else
if(cmd.equals("ELSE")&&(depth==0))
{
positiveCondition=false;
if(s.substring(4).trim().length()>0)
logError(scripted,"ELSE","Syntax"," Decorated ELSE is now illegal!!");
else
if(tt==null)
tt=parseBits(script,si,"C");
}
else
{
if(cmd.equals("IF"))
depth++;
else
if(cmd.equals("ENDIF"))
{
if(tt==null)
tt=parseBits(script,si,"C");
depth--;
}
if(positiveCondition)
{
if(parsedBlocks.first==null)
{
parsedBlocks.first=new DVector(3);
parsedBlocks.first.addElement("",null,null);
}
if(condition)
subScript=parsedBlocks.first;
parsedBlocks.first.addSharedElements(script.elementsAt(si));
}
else
{
if(parsedBlocks.second==null)
{
parsedBlocks.second=new DVector(3);
parsedBlocks.second.addElement("",null,null);
}
if(!condition)
subScript=parsedBlocks.second;
parsedBlocks.second.addSharedElements(script.elementsAt(si));
}
}
si++;
}
if(!foundendif)
{
logError(scripted,"IF","Syntax"," Without ENDIF!");
tickStatus=Tickable.STATUS_END;
return null;
}
if((subScript != null)
&&(subScript.size()>1)
&&(subScript != script))
{
//source.tell(L("Starting @x1",conditionStr));
//for(int v=0;v<V.size();v++)
// source.tell(L("Statement @x1",((String)V.elementAt(v))));
final String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp);
if(response!=null)
{
tickStatus=Tickable.STATUS_END;
return response;
}
//source.tell(L("Stopping @x1",conditionStr));
}
break;
}
case 93: // "ENDIF", //93 JUST for catching errors...
logError(scripted,"ENDIF","Syntax"," Without IF ("+si+")!");
break;
case 94: //"ENDSWITCH", //94 JUST for catching errors...
logError(scripted,"ENDSWITCH","Syntax"," Without SWITCH ("+si+")!");
break;
case 95: //"NEXT", //95 JUST for catching errors...
logError(scripted,"NEXT","Syntax"," Without FOR ("+si+")!");
break;
case 96: //"CASE" //96 JUST for catching errors...
logError(scripted,"CASE","Syntax"," Without SWITCH ("+si+")!");
break;
case 97: //"DEFAULT" //97 JUST for catching errors...
logError(scripted,"DEFAULT","Syntax"," Without SWITCH ("+si+")!");
break;
case 70: // switch
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
if(script.elementAt(si, 3)==null)
script.setElementAt(si, 3, new Hashtable<String,Integer>());
}
@SuppressWarnings("unchecked")
final Map<String,Integer> skipSwitchMap=(Map<String,Integer>)script.elementAt(si, 3);
final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]).trim();
final DVector subScript=new DVector(3);
subScript.addElement("",null,null);
int depth=0;
boolean foundEndSwitch=false;
boolean ignoreUntilEndScript=false;
boolean inCase=false;
boolean matchedCase=false;
si++;
String s2=null;
if(skipSwitchMap.size()>0)
{
if(skipSwitchMap.containsKey(var.toUpperCase()))
{
inCase=true;
matchedCase=true;
si=skipSwitchMap.get(var.toUpperCase()).intValue();
si++;
}
else
if(skipSwitchMap.containsKey("$FIRSTVAR")) // first variable case
{
si=skipSwitchMap.get("$FIRSTVAR").intValue();
}
else
if(skipSwitchMap.containsKey("$DEFAULT")) // the "default" case
{
inCase=true;
matchedCase=true;
si=skipSwitchMap.get("$DEFAULT").intValue();
si++;
}
else
if(skipSwitchMap.containsKey("$ENDSWITCH")) // the "endswitch" case
{
foundEndSwitch=true;
si=skipSwitchMap.get("$ENDSWITCH").intValue();
}
}
while((si<script.size())
&&(!foundEndSwitch))
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.equals("<SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
ignoreUntilEndScript=true;
}
else
if(cmd.equals("</SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
ignoreUntilEndScript=false;
}
else
if(ignoreUntilEndScript)
{
// only applies when <SCRIPT> encountered.
}
else
if(cmd.equals("ENDSWITCH")&&(depth==0))
{
if(tt==null)
{
tt=parseBits(script,si,"C");
skipSwitchMap.put("$ENDSWITCH", Integer.valueOf(si));
}
foundEndSwitch=true;
break;
}
else
if(cmd.equals("CASE")&&(depth==0))
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
if(tt[1].indexOf('$')>=0)
{
if(!skipSwitchMap.containsKey("$FIRSTVAR"))
skipSwitchMap.put("$FIRSTVAR", Integer.valueOf(si));
}
else
if(!skipSwitchMap.containsKey(tt[1].toUpperCase()))
skipSwitchMap.put(tt[1].toUpperCase(), Integer.valueOf(si));
}
if(matchedCase
&&inCase
&&(skipSwitchMap.containsKey("$ENDSWITCH"))) // we're done
{
foundEndSwitch=true;
si=skipSwitchMap.get("$ENDSWITCH").intValue();
break; // this is important, otherwise si will get increment and screw stuff up
}
else
{
s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]).trim();
inCase=var.equalsIgnoreCase(s2);
matchedCase=matchedCase||inCase;
}
}
else
if(cmd.equals("DEFAULT")&&(depth==0))
{
if(tt==null)
{
tt=parseBits(script,si,"C");
if(!skipSwitchMap.containsKey("$DEFAULT"))
skipSwitchMap.put("$DEFAULT", Integer.valueOf(si));
}
if(matchedCase
&&inCase
&&(skipSwitchMap.containsKey("$ENDSWITCH"))) // we're done
{
foundEndSwitch=true;
si=skipSwitchMap.get("$ENDSWITCH").intValue();
break; // this is important, otherwise si will get increment and screw stuff up
}
else
inCase=!matchedCase;
}
else
{
if(inCase)
subScript.addSharedElements(script.elementsAt(si));
if(cmd.equals("SWITCH"))
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(script.elementAt(si, 3)==null)
script.setElementAt(si, 3, new Hashtable<String,Integer>());
}
depth++;
}
else
if(cmd.equals("ENDSWITCH"))
{
if(tt==null)
tt=parseBits(script,si,"C");
depth--;
}
}
si++;
}
if(!foundEndSwitch)
{
logError(scripted,"SWITCH","Syntax"," Without ENDSWITCH!");
tickStatus=Tickable.STATUS_END;
return null;
}
if(subScript.size()>1)
{
final String response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp);
if(response!=null)
{
tickStatus=Tickable.STATUS_END;
return response;
}
}
break;
}
case 62: // for x = 1 to 100
{
if(tt==null)
{
tt=parseBits(script,si,"CcccCr");
if(tt==null)
return null;
}
if(tt[5].length()==0)
{
logError(scripted,"FOR","Syntax","5 parms required!");
tickStatus=Tickable.STATUS_END;
return null;
}
final String varStr=tt[1];
if((varStr.length()!=2)||(varStr.charAt(0)!='$')||(!Character.isDigit(varStr.charAt(1))))
{
logError(scripted,"FOR","Syntax","'"+varStr+"' is not a tmp var $1, $2..");
tickStatus=Tickable.STATUS_END;
return null;
}
final int whichVar=CMath.s_int(Character.toString(varStr.charAt(1)));
if((tmp[whichVar] instanceof String)
&&(((String)tmp[whichVar]).length()>0)
&&(CMath.isInteger(((String)tmp[whichVar]).trim())))
{
logError(scripted,"FOR","Syntax","'"+whichVar+"' is already in use! Use a different one!");
tickStatus=Tickable.STATUS_END;
return null;
}
if(!tt[2].equals("="))
{
logError(scripted,"FOR","Syntax","'"+s+"' is illegal for syntax!");
tickStatus=Tickable.STATUS_END;
return null;
}
int toAdd=0;
if(tt[4].equals("TO<"))
toAdd=-1;
else
if(tt[4].equals("TO>"))
toAdd=1;
else
if(!tt[4].equals("TO"))
{
logError(scripted,"FOR","Syntax","'"+s+"' is illegal for syntax!");
tickStatus=Tickable.STATUS_END;
return null;
}
final String from=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]).trim();
final String to=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[5]).trim();
if((!CMath.isInteger(from))||(!CMath.isInteger(to)))
{
logError(scripted,"FOR","Syntax","'"+from+"-"+to+"' is illegal range!");
tickStatus=Tickable.STATUS_END;
return null;
}
final DVector subScript=new DVector(3);
subScript.addElement("",null,null);
int depth=0;
boolean foundnext=false;
boolean ignoreUntilEndScript=false;
si++;
while(si<script.size())
{
s=((String)script.elementAt(si,1)).trim();
tt=(String[])script.elementAt(si,2);
if(tt!=null)
cmd=tt[0];
else
cmd=CMParms.getCleanBit(s,0).toUpperCase();
if(cmd.equals("<SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
ignoreUntilEndScript=true;
}
else
if(cmd.equals("</SCRIPT>"))
{
if(tt==null)
tt=parseBits(script,si,"C");
ignoreUntilEndScript=false;
}
else
if(ignoreUntilEndScript)
{
}
else
if(cmd.equals("NEXT")&&(depth==0))
{
if(tt==null)
tt=parseBits(script,si,"C");
foundnext=true;
break;
}
else
{
if(cmd.equals("FOR"))
{
if(tt==null)
tt=parseBits(script,si,"CcccCr");
depth++;
}
else
if(cmd.equals("NEXT"))
{
if(tt==null)
tt=parseBits(script,si,"C");
depth--;
}
subScript.addSharedElements(script.elementsAt(si));
}
si++;
}
if(!foundnext)
{
logError(scripted,"FOR","Syntax"," Without NEXT!");
tickStatus=Tickable.STATUS_END;
return null;
}
if(subScript.size()>1)
{
//source.tell(L("Starting @x1",conditionStr));
//for(int v=0;v<V.size();v++)
// source.tell(L("Statement @x1",((String)V.elementAt(v))));
final int fromInt=CMath.s_int(from);
int toInt=CMath.s_int(to);
final int increment=(toInt>=fromInt)?1:-1;
String response=null;
if(((increment>0)&&(fromInt<=(toInt+toAdd)))
||((increment<0)&&(fromInt>=(toInt+toAdd))))
{
toInt+=toAdd;
final long tm=System.currentTimeMillis()+(10 * 1000);
for(int forLoop=fromInt;forLoop!=toInt;forLoop+=increment)
{
tmp[whichVar]=""+forLoop;
response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp);
if(response!=null)
break;
if((System.currentTimeMillis()>tm) || (scripted.amDestroyed()))
{
logError(scripted,"FOR","Runtime","For loop violates 10 second rule: " +s);
break;
}
}
tmp[whichVar]=""+toInt;
if(response == null)
response=execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp);
else
if(response.equalsIgnoreCase("break"))
response=null;
}
if(response!=null)
{
tickStatus=Tickable.STATUS_END;
return response;
}
tmp[whichVar]=null;
//source.tell(L("Stopping @x1",conditionStr));
}
break;
}
case 50: // break;
if(tt==null)
tt=parseBits(script,si,"C");
tickStatus=Tickable.STATUS_END;
return "BREAK";
case 1: // mpasound
{
if(tt==null)
{
tt=parseBits(script,si,"Cp");
if(tt==null)
return null;
}
final String echo=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
//lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,echo);
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
{
final Room R2=lastKnownLocation.getRoomInDir(d);
final Exit E2=lastKnownLocation.getExitInDir(d);
if((R2!=null)&&(E2!=null)&&(E2.isOpen()))
R2.showOthers(monster,null,null,CMMsg.MSG_OK_ACTION,echo);
}
break;
}
case 4: // mpjunk
{
if(tt==null)
{
tt=parseBits(script,si,"CR");
if(tt==null)
return null;
}
if(tt[1].equals("ALL") && (monster!=null))
{
monster.delAllItems(true);
}
else
{
final Environmental E=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
Item I=null;
if(E instanceof Item)
I=(Item)E;
if((I==null)&&(monster!=null))
I=monster.findItem(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]));
if((I==null)&&(scripted instanceof Room))
I=((Room)scripted).findItem(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]));
if(I!=null)
I.destroy();
}
break;
}
case 2: // mpecho
{
if(tt==null)
{
tt=parseBits(script,si,"Cp");
if(tt==null)
return null;
}
if(lastKnownLocation!=null)
lastKnownLocation.show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]));
break;
}
case 13: // mpunaffect
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String which=tt[2];
if(newTarget!=null)
if(which.equalsIgnoreCase("all")||(which.length()==0))
{
for(int a=newTarget.numEffects()-1;a>=0;a--)
{
final Ability A=newTarget.fetchEffect(a);
if(A!=null)
A.unInvoke();
}
}
else
{
final Ability A2=findAbility(which);
if(A2!=null)
which=A2.ID();
final Ability A=newTarget.fetchEffect(which);
if(A!=null)
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" was MPUNAFFECTED by "+A.Name());
A.unInvoke();
if(newTarget.fetchEffect(which)==A)
newTarget.delEffect(A);
}
}
break;
}
case 3: // mpslay
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB))
CMLib.combat().postDeath(monster,(MOB)newTarget,null);
break;
}
case 73: // mpsetinternal
{
if(tt==null)
{
tt=parseBits(script,si,"CCr");
if(tt==null)
return null;
}
final String arg2=tt[1];
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if(arg2.equals("SCOPE"))
setVarScope(arg3);
else
if(arg2.equals("NODELAY"))
noDelay=CMath.s_bool(arg3);
else
if(arg2.equals("ACTIVETRIGGER")||arg2.equals("ACTIVETRIGGERS"))
alwaysTriggers=CMath.s_bool(arg3);
else
if(arg2.equals("DEFAULTQUEST"))
registerDefaultQuest(arg3);
else
if(arg2.equals("SAVABLE"))
setSavable(CMath.s_bool(arg3));
else
if(arg2.equals("PASSIVE"))
this.runInPassiveAreas = CMath.s_bool(arg3);
else
logError(scripted,"MPSETINTERNAL","Syntax","Unknown stat: "+arg2);
break;
}
case 74: // mpprompt
{
if(tt==null)
{
tt=parseBits(script,si,"CCCr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null)))
{
try
{
final String value=((MOB)newTarget).session().prompt(promptStr,120000);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS))
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+newTarget.Name()+"("+var+")="+value+"<");
setVar(newTarget.Name(),var,value);
}
catch(final Exception e)
{
return "";
}
}
break;
}
case 75: // mpconfirm
{
if(tt==null)
{
tt=parseBits(script,si,"CCCCr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String defaultVal=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
final String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]);
if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null)))
{
try
{
final String value=((MOB)newTarget).session().confirm(promptStr,defaultVal,60000)?"Y":"N";
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS))
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+newTarget.Name()+"("+var+")="+value+"<");
setVar(newTarget.Name(),var,value);
}
catch(final Exception e)
{
return "";
}
/*
* this is how to do non-blocking, which doesn't help stuff waiting
* for a response from the original execute method
final Session session = ((MOB)newTarget).session();
if(session != null)
{
try
{
final int lastLineNum=si;
final JScriptEvent continueEvent=new JScriptEvent(
this,
scripted,
source,
target,
monster,
primaryItem,
secondaryItem,
msg,
tmp);
((MOB)newTarget).session().prompt(new InputCallback(InputCallback.Type.PROMPT,"",0)
{
private final JScriptEvent event=continueEvent;
private final int lineNum=lastLineNum;
private final String scope=newTarget.Name();
private final String varName=var;
private final String promptStrMsg=promptStr;
private final DVector lastScript=script;
@Override
public void showPrompt()
{
session.promptPrint(promptStrMsg);
}
@Override
public void timedOut()
{
event.executeEvent(lastScript, lineNum+1);
}
@Override
public void callBack()
{
final String value=this.input;
if((value.trim().length()==0)||(value.indexOf('<')>=0))
return;
setVar(scope,varName,value);
event.executeEvent(lastScript, lineNum+1);
}
});
}
catch(final Exception e)
{
return "";
}
}
*/
}
break;
}
case 76: // mpchoose
{
if(tt==null)
{
tt=parseBits(script,si,"CCCCCr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String choices=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
final String defaultVal=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]);
final String promptStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[5]);
if((newTarget!=null)&&(newTarget instanceof MOB)&&((((MOB)newTarget).session()!=null)))
{
try
{
final String value=((MOB)newTarget).session().choose(promptStr,choices,defaultVal,60000);
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS))
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+newTarget.Name()+"("+var+")="+value+"<");
setVar(newTarget.Name(),var,value);
}
catch(final Exception e)
{
return "";
}
}
break;
}
case 16: // mpset
{
if(tt==null)
{
tt=parseBits(script,si,"CCcr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=tt[2];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if(newTarget!=null)
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" has "+arg2+" MPSETTED to "+arg3);
boolean found=false;
for(int i=0;i<newTarget.getStatCodes().length;i++)
{
if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1);
newTarget.setStat(arg2,arg3);
found=true;
break;
}
}
if((!found)&&(newTarget instanceof MOB))
{
final MOB M=(MOB)newTarget;
for(final int i : CharStats.CODES.ALLCODES())
{
if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(M.baseCharStats().getStat(i)+1);
if(arg3.equals("--"))
arg3=""+(M.baseCharStats().getStat(i)-1);
M.baseCharStats().setStat(i,CMath.s_int(arg3.trim()));
M.recoverCharStats();
if(arg2.equalsIgnoreCase("RACE"))
M.charStats().getMyRace().startRacing(M,false);
found=true;
break;
}
}
if(!found)
{
for(int i=0;i<M.curState().getStatCodes().length;i++)
{
if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1);
M.curState().setStat(arg2,arg3);
found=true;
break;
}
}
}
if(!found)
{
for(int i=0;i<M.basePhyStats().getStatCodes().length;i++)
{
if(M.basePhyStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))-1);
M.basePhyStats().setStat(arg2,arg3);
found=true;
break;
}
}
}
if((!found)&&(M.playerStats()!=null))
{
for(int i=0;i<M.playerStats().getStatCodes().length;i++)
{
if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1);
M.playerStats().setStat(arg2,arg3);
found=true;
break;
}
}
}
if((!found)&&(arg2.toUpperCase().startsWith("BASE")))
{
for(int i=0;i<M.baseState().getStatCodes().length;i++)
{
if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg2.substring(4)))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1);
M.baseState().setStat(arg2.substring(4),arg3);
found=true;
break;
}
}
}
if((!found)&&(arg2.toUpperCase().equals("STINK")))
{
found=true;
if(M.playerStats()!=null)
M.playerStats().setHygiene(Math.round(CMath.s_pct(arg3)*PlayerStats.HYGIENE_DELIMIT));
}
if((!found)
&&(CMath.s_valueOf(GenericBuilder.GenMOBBonusFakeStats.class,arg2.toUpperCase())!=null))
{
found=true;
CMLib.coffeeMaker().setAnyGenStat(M, arg2.toUpperCase(), arg3);
}
}
if((!found)
&&(newTarget instanceof Item))
{
if((!found)
&&(CMath.s_valueOf(GenericBuilder.GenItemBonusFakeStats.class,arg2.toUpperCase())!=null))
{
found=true;
CMLib.coffeeMaker().setAnyGenStat(newTarget, arg2.toUpperCase(), arg3);
}
}
if((!found)
&&(CMath.s_valueOf(GenericBuilder.GenPhysBonusFakeStats.class,arg2.toUpperCase())!=null))
{
found=true;
CMLib.coffeeMaker().setAnyGenStat(newTarget, arg2.toUpperCase(), arg3);
}
if(!found)
{
logError(scripted,"MPSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name());
break;
}
if(newTarget instanceof MOB)
((MOB)newTarget).recoverCharStats();
newTarget.recoverPhyStats();
if(newTarget instanceof MOB)
{
((MOB)newTarget).recoverMaxState();
if(arg2.equalsIgnoreCase("LEVEL"))
{
CMLib.leveler().fillOutMOB(((MOB)newTarget),((MOB)newTarget).basePhyStats().level());
((MOB)newTarget).recoverMaxState();
((MOB)newTarget).recoverCharStats();
((MOB)newTarget).recoverPhyStats();
((MOB)newTarget).resetToMaxState();
}
}
}
break;
}
case 63: // mpargset
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final String arg1=tt[1];
final String arg2=tt[2];
if((arg1.length()!=2)||(!arg1.startsWith("$")))
{
logError(scripted,"MPARGSET","Syntax","Mangled argument var: "+arg1+" for "+scripted.Name());
break;
}
Object O=getArgumentMOB(arg2,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if(O==null)
O=getArgumentItem(arg2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((O==null)
&&((arg2.length()!=2)
||(arg2.charAt(1)=='g')
||(!arg2.startsWith("$"))
||((!Character.isDigit(arg2.charAt(1)))
&&(!Character.isLetter(arg2.charAt(1))))))
O=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,arg2);
final char c=arg1.charAt(1);
if(Character.isDigit(c))
{
if((O instanceof String)&&(((String)O).equalsIgnoreCase("null")))
O=null;
tmp[CMath.s_int(Character.toString(c))]=O;
}
else
{
switch(arg1.charAt(1))
{
case 'N':
case 'n':
if (O instanceof MOB)
source = (MOB) O;
break;
case 'B':
case 'b':
if (O instanceof Environmental)
lastLoaded = (Environmental) O;
break;
case 'I':
case 'i':
if (O instanceof PhysicalAgent)
scripted = (PhysicalAgent) O;
if (O instanceof MOB)
monster = (MOB) O;
break;
case 'T':
case 't':
if (O instanceof Environmental)
target = (Environmental) O;
break;
case 'O':
case 'o':
if (O instanceof Item)
primaryItem = (Item) O;
break;
case 'P':
case 'p':
if (O instanceof Item)
secondaryItem = (Item) O;
break;
case 'd':
case 'D':
if (O instanceof Room)
lastKnownLocation = (Room) O;
break;
case 'g':
case 'G':
if (O instanceof String)
msg = (String) O;
else
if((O instanceof Room)
&&((((Room)O).roomID().length()>0)
|| (!"".equals(CMLib.map().getExtendedRoomID((Room)O)))))
msg = CMLib.map().getExtendedRoomID((Room)O);
else
if(O instanceof CMObject)
msg=((CMObject)O).name();
else
msg=""+O;
break;
default:
logError(scripted, "MPARGSET", "Syntax", "Invalid argument var: " + arg1 + " for " + scripted.Name());
break;
}
}
break;
}
case 35: // mpgset
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=tt[2];
String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if(newTarget!=null)
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" has "+arg2+" MPGSETTED to "+arg3);
boolean found=false;
for(int i=0;i<newTarget.getStatCodes().length;i++)
{
if(newTarget.getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(newTarget.getStat(newTarget.getStatCodes()[i]))-1);
newTarget.setStat(newTarget.getStatCodes()[i],arg3);
found=true;
break;
}
}
if(!found)
{
if(newTarget instanceof MOB)
{
final GenericBuilder.GenMOBCode element = (GenericBuilder.GenMOBCode)CMath.s_valueOf(GenericBuilder.GenMOBCode.class,arg2.toUpperCase().trim());
if(element != null)
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,element.name()))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenMobStat((MOB)newTarget,element.name()))-1);
CMLib.coffeeMaker().setGenMobStat((MOB)newTarget,element.name(),arg3);
found=true;
}
if(!found)
{
final MOB M=(MOB)newTarget;
for(final int i : CharStats.CODES.ALLCODES())
{
if(CharStats.CODES.NAME(i).equalsIgnoreCase(arg2)||CharStats.CODES.DESC(i).equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(M.baseCharStats().getStat(i)+1);
if(arg3.equals("--"))
arg3=""+(M.baseCharStats().getStat(i)-1);
if((arg3.length()==1)&&(Character.isLetter(arg3.charAt(0))))
M.baseCharStats().setStat(i,arg3.charAt(0));
else
M.baseCharStats().setStat(i,CMath.s_int(arg3.trim()));
M.recoverCharStats();
if(arg2.equalsIgnoreCase("RACE"))
M.charStats().getMyRace().startRacing(M,false);
found=true;
break;
}
}
if(!found)
{
for(int i=0;i<M.curState().getStatCodes().length;i++)
{
if(M.curState().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.curState().getStat(M.curState().getStatCodes()[i]))-1);
M.curState().setStat(arg2,arg3);
found=true;
break;
}
}
}
if(!found)
{
for(int i=0;i<M.basePhyStats().getStatCodes().length;i++)
{
if(M.basePhyStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.basePhyStats().getStat(M.basePhyStats().getStatCodes()[i]))-1);
M.basePhyStats().setStat(arg2,arg3);
found=true;
break;
}
}
}
if((!found)&&(M.playerStats()!=null))
{
for(int i=0;i<M.playerStats().getStatCodes().length;i++)
{
if(M.playerStats().getStatCodes()[i].equalsIgnoreCase(arg2))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.playerStats().getStat(M.playerStats().getStatCodes()[i]))-1);
M.playerStats().setStat(arg2,arg3);
found=true;
break;
}
}
}
if((!found)&&(arg2.toUpperCase().startsWith("BASE")))
{
final String arg4=arg2.substring(4);
for(int i=0;i<M.baseState().getStatCodes().length;i++)
{
if(M.baseState().getStatCodes()[i].equalsIgnoreCase(arg4))
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(M.baseState().getStat(M.baseState().getStatCodes()[i]))-1);
M.baseState().setStat(arg4,arg3);
found=true;
break;
}
}
}
if((!found)&&(arg2.toUpperCase().equals("STINK")))
{
found=true;
if(M.playerStats()!=null)
M.playerStats().setHygiene(Math.round(CMath.s_pct(arg3)*PlayerStats.HYGIENE_DELIMIT));
}
}
}
}
else
if(newTarget instanceof Item)
{
final GenericBuilder.GenItemCode element = (GenericBuilder.GenItemCode)CMath.s_valueOf(GenericBuilder.GenItemCode.class,arg2.toUpperCase().trim());
if(element != null)
{
if(arg3.equals("++"))
arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,element.name()))+1);
if(arg3.equals("--"))
arg3=""+(CMath.s_int(CMLib.coffeeMaker().getGenItemStat((Item)newTarget,element.name()))-1);
CMLib.coffeeMaker().setGenItemStat((Item)newTarget,element.name(),arg3);
found=true;
}
}
if((!found)
&&(newTarget instanceof Physical))
{
if(CMLib.coffeeMaker().isAnyGenStat(newTarget, arg2.toUpperCase()))
{
CMLib.coffeeMaker().setAnyGenStat(newTarget, arg2.toUpperCase(), arg3);
found=true;
}
}
if(!found)
{
logError(scripted,"MPGSET","Syntax","Unknown stat: "+arg2+" for "+newTarget.Name());
break;
}
if(newTarget instanceof MOB)
((MOB)newTarget).recoverCharStats();
newTarget.recoverPhyStats();
if(newTarget instanceof MOB)
{
((MOB)newTarget).recoverMaxState();
if(arg2.equalsIgnoreCase("LEVEL"))
{
CMLib.leveler().fillOutMOB(((MOB)newTarget),((MOB)newTarget).basePhyStats().level());
((MOB)newTarget).recoverMaxState();
((MOB)newTarget).recoverCharStats();
((MOB)newTarget).recoverPhyStats();
((MOB)newTarget).resetToMaxState();
}
}
}
break;
}
case 11: // mpexp
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
int t=CMath.s_int(amtStr);
if((newTarget!=null)&&(newTarget instanceof MOB))
{
if((amtStr.endsWith("%"))
&&(((MOB)newTarget).getExpNeededLevel()<Integer.MAX_VALUE))
{
final int baseLevel=newTarget.basePhyStats().level();
final int lastLevelExpNeeded=(baseLevel<=1)?0:CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel-1);
final int thisLevelExpNeeded=CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel);
t=(int)Math.round(CMath.mul(thisLevelExpNeeded-lastLevelExpNeeded,
CMath.div(CMath.s_int(amtStr.substring(0,amtStr.length()-1)),100.0)));
}
if(t!=0)
CMLib.leveler().postExperience((MOB)newTarget,null,null,t,false);
}
break;
}
case 86: // mprpexp
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
int t=CMath.s_int(amtStr);
if((newTarget!=null)&&(newTarget instanceof MOB))
{
if((amtStr.endsWith("%"))
&&(((MOB)newTarget).getExpNeededLevel()<Integer.MAX_VALUE))
{
final int baseLevel=newTarget.basePhyStats().level();
final int lastLevelExpNeeded=(baseLevel<=1)?0:CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel-1);
final int thisLevelExpNeeded=CMLib.leveler().getLevelExperience((MOB)newTarget, baseLevel);
t=(int)Math.round(CMath.mul(thisLevelExpNeeded-lastLevelExpNeeded,
CMath.div(CMath.s_int(amtStr.substring(0,amtStr.length()-1)),100.0)));
}
if(t!=0)
CMLib.leveler().postRPExperience((MOB)newTarget,null,null,t,false);
}
break;
}
case 77: // mpmoney
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
Environmental newTarget=getArgumentMOB(tt[1],source,monster,scripted,primaryItem,secondaryItem,msg,tmp);
if(newTarget==null)
newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String amtStr=tt[2];
amtStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,amtStr).trim();
final boolean plus=!amtStr.startsWith("-");
if(amtStr.startsWith("+")||amtStr.startsWith("-"))
amtStr=amtStr.substring(1).trim();
final String currency = CMLib.english().parseNumPossibleGoldCurrency(source, amtStr);
final long amt = CMLib.english().parseNumPossibleGold(source, amtStr);
final double denomination = CMLib.english().parseNumPossibleGoldDenomination(source, currency, amtStr);
Container container = null;
if(newTarget instanceof Item)
{
container = (newTarget instanceof Container)?(Container)newTarget:null;
newTarget = ((Item)newTarget).owner();
}
if(newTarget instanceof MOB)
{
if(plus)
CMLib.beanCounter().giveSomeoneMoney((MOB)newTarget, currency, amt * denomination);
else
CMLib.beanCounter().subtractMoney((MOB)newTarget, currency, amt * denomination);
}
else
{
if(!(newTarget instanceof Room))
newTarget=lastKnownLocation;
if(plus)
CMLib.beanCounter().dropMoney((Room)newTarget, container, currency, amt * denomination);
else
CMLib.beanCounter().removeMoney((Room)newTarget, container, currency, amt * denomination);
}
break;
}
case 59: // mpquestpoints
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
if(newTarget instanceof MOB)
{
if(CMath.isNumber(val))
{
final int ival=CMath.s_int(val);
final int aval=ival-((MOB)newTarget).getQuestPoint();
((MOB)newTarget).setQuestPoint(CMath.s_int(val));
if(aval>0)
CMLib.players().bumpPrideStat((MOB)newTarget,PrideStat.QUESTPOINTS_EARNED, aval);
}
else
if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim())))
{
((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()+CMath.s_int(val.substring(2).trim()));
CMLib.players().bumpPrideStat((MOB)newTarget,PrideStat.QUESTPOINTS_EARNED, CMath.s_int(val.substring(2).trim()));
}
else
if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setQuestPoint(((MOB)newTarget).getQuestPoint()-CMath.s_int(val.substring(2).trim()));
else
logError(scripted,"QUESTPOINTS","Syntax","Bad syntax "+val+" for "+scripted.Name());
}
break;
}
case 65: // MPQSET
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final String qstr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final String var=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final PhysicalAgent obj=getArgumentItem(tt[3],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
final Quest Q=getQuest(qstr);
if(Q==null)
logError(scripted,"MPQSET","Syntax","Unknown quest "+qstr+" for "+scripted.Name());
else
if(var.equalsIgnoreCase("QUESTOBJ"))
{
if(obj==null)
logError(scripted,"MPQSET","Syntax","Unknown object "+tt[3]+" for "+scripted.Name());
else
{
obj.basePhyStats().setDisposition(obj.basePhyStats().disposition()|PhyStats.IS_UNSAVABLE);
obj.recoverPhyStats();
Q.runtimeRegisterObject(obj);
}
}
else
if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("ACCEPTED")))
CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTACCEPTED);
else
if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("SUCCESS")||val.equalsIgnoreCase("WON")))
CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTSUCCESS);
else
if(var.equalsIgnoreCase("STATISTICS")&&(val.equalsIgnoreCase("FAILED")))
CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTFAILED);
else
{
if(val.equals("++"))
val=""+(CMath.s_int(Q.getStat(var))+1);
if(val.equals("--"))
val=""+(CMath.s_int(Q.getStat(var))-1);
Q.setStat(var,val);
}
break;
}
case 66: // MPLOG
{
if(tt==null)
{
tt=parseBits(script,si,"CCcr");
if(tt==null)
return null;
}
final String type=tt[1];
final String head=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if(type.startsWith("E"))
Log.errOut("Script","["+head+"] "+val);
else
if(type.startsWith("I")||type.startsWith("S"))
Log.infoOut("Script","["+head+"] "+val);
else
if(type.startsWith("D"))
Log.debugOut("Script","["+head+"] "+val);
else
logError(scripted,"MPLOG","Syntax","Unknown log type "+type+" for "+scripted.Name());
break;
}
case 67: // MPCHANNEL
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
String channel=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final boolean sysmsg=channel.startsWith("!");
if(sysmsg)
channel=channel.substring(1);
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if(CMLib.channels().getChannelCodeNumber(channel)<0)
logError(scripted,"MPCHANNEL","Syntax","Unknown channel "+channel+" for "+scripted.Name());
else
CMLib.commands().postChannel(monster,channel,val,sysmsg);
break;
}
case 68: // MPUNLOADSCRIPT
{
if(tt==null)
{
tt=parseBits(script,si,"Cc");
if(tt==null)
return null;
}
String scriptname=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
if(!new CMFile(Resources.makeFileResourceName(scriptname),null,CMFile.FLAG_FORCEALLOW).exists())
logError(scripted,"MPUNLOADSCRIPT","Runtime","File does not exist: "+Resources.makeFileResourceName(scriptname));
else
{
final ArrayList<String> delThese=new ArrayList<String>();
scriptname=scriptname.toUpperCase().trim();
final String parmname=scriptname;
for(final Iterator<String> k = Resources.findResourceKeys(parmname);k.hasNext();)
{
final String key=k.next();
if(key.startsWith("PARSEDPRG: ")&&(key.toUpperCase().endsWith(parmname)))
{
delThese.add(key);
}
}
for(int i=0;i<delThese.size();i++)
Resources.removeResource(delThese.get(i));
}
break;
}
case 60: // MPTRAINS
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
if(newTarget instanceof MOB)
{
if(CMath.isNumber(val))
((MOB)newTarget).setTrains(CMath.s_int(val));
else
if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()+CMath.s_int(val.substring(2).trim()));
else
if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setTrains(((MOB)newTarget).getTrains()-CMath.s_int(val.substring(2).trim()));
else
logError(scripted,"TRAINS","Syntax","Bad syntax "+val+" for "+scripted.Name());
}
break;
}
case 61: // mppracs
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String val=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
if(newTarget instanceof MOB)
{
if(CMath.isNumber(val))
((MOB)newTarget).setPractices(CMath.s_int(val));
else
if(val.startsWith("++")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()+CMath.s_int(val.substring(2).trim()));
else
if(val.startsWith("--")&&(CMath.isNumber(val.substring(2).trim())))
((MOB)newTarget).setPractices(((MOB)newTarget).getPractices()-CMath.s_int(val.substring(2).trim()));
else
logError(scripted,"PRACS","Syntax","Bad syntax "+val+" for "+scripted.Name());
}
break;
}
case 5: // mpmload
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final ArrayList<Environmental> Ms=new ArrayList<Environmental>();
MOB m=CMClass.getMOB(name);
if(m!=null)
Ms.add(m);
if(lastKnownLocation!=null)
{
if(Ms.size()==0)
findSomethingCalledThis(name,monster,lastKnownLocation,Ms,true);
for(int i=0;i<Ms.size();i++)
{
if(Ms.get(i) instanceof MOB)
{
m=(MOB)((MOB)Ms.get(i)).copyOf();
m.text();
m.recoverPhyStats();
m.recoverCharStats();
m.resetToMaxState();
m.bringToLife(lastKnownLocation,true);
lastLoaded=m;
}
}
}
break;
}
case 6: // mpoload
{
//if not mob
Physical addHere;
if(scripted instanceof MOB)
addHere=monster;
else
if(scripted instanceof Item)
addHere=((Item)scripted).owner();
else
if(scripted instanceof Room)
addHere=scripted;
else
addHere=lastKnownLocation;
if(addHere!=null)
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
this.lastLoaded = null;
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final int containerIndex=name.toUpperCase().indexOf(" INTO ");
Container container=null;
if(containerIndex>=0)
{
final ArrayList<Environmental> containers=new ArrayList<Environmental>();
findSomethingCalledThis(name.substring(containerIndex+6).trim(),monster,lastKnownLocation,containers,false);
for(int c=0;c<containers.size();c++)
{
if((containers.get(c) instanceof Container)
&&(((Container)containers.get(c)).capacity()>0))
{
container=(Container)containers.get(c);
name=name.substring(0,containerIndex).trim();
break;
}
}
}
final long coins=CMLib.english().parseNumPossibleGold(null,name);
if(coins>0)
{
final String currency=CMLib.english().parseNumPossibleGoldCurrency(scripted,name);
final double denom=CMLib.english().parseNumPossibleGoldDenomination(scripted,currency,name);
final Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins);
if(addHere instanceof MOB)
((MOB)addHere).addItem(C);
else
if(addHere instanceof Room)
((Room)addHere).addItem(C, Expire.Monster_EQ);
C.putCoinsBack();
}
else
if(lastKnownLocation!=null)
{
final ArrayList<Environmental> Is=new ArrayList<Environmental>();
Item m=CMClass.getItem(name);
if(m!=null)
Is.add(m);
else
findSomethingCalledThis(name,monster,lastKnownLocation,Is,false);
for(int i=0;i<Is.size();i++)
{
if(Is.get(i) instanceof Item)
{
m=(Item)Is.get(i);
if((m!=null)
&&(!(m instanceof ArchonOnly)))
{
m=(Item)m.copyOf();
m.recoverPhyStats();
m.setContainer(container);
if(container instanceof MOB)
((MOB)container.owner()).addItem(m);
else
if(container instanceof Room)
((Room)container.owner()).addItem(m,ItemPossessor.Expire.Player_Drop);
else
if(addHere instanceof MOB)
((MOB)addHere).addItem(m);
else
if(addHere instanceof Room)
((Room)addHere).addItem(m, Expire.Monster_EQ);
lastLoaded=m;
}
}
}
if(addHere instanceof MOB)
{
((MOB)addHere).recoverCharStats();
((MOB)addHere).recoverMaxState();
}
addHere.recoverPhyStats();
lastKnownLocation.recoverRoomStats();
}
}
break;
}
case 41: // mpoloadroom
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
if(lastKnownLocation!=null)
{
final ArrayList<Environmental> Is=new ArrayList<Environmental>();
final int containerIndex=name.toUpperCase().indexOf(" INTO ");
Container container=null;
if(containerIndex>=0)
{
final ArrayList<Environmental> containers=new ArrayList<Environmental>();
findSomethingCalledThis(name.substring(containerIndex+6).trim(),null,lastKnownLocation,containers,false);
for(int c=0;c<containers.size();c++)
{
if((containers.get(c) instanceof Container)
&&(((Container)containers.get(c)).capacity()>0))
{
container=(Container)containers.get(c);
name=name.substring(0,containerIndex).trim();
break;
}
}
}
final long coins=CMLib.english().parseNumPossibleGold(null,name);
if(coins>0)
{
final String currency=CMLib.english().parseNumPossibleGoldCurrency(monster,name);
final double denom=CMLib.english().parseNumPossibleGoldDenomination(monster,currency,name);
final Coins C=CMLib.beanCounter().makeCurrency(currency,denom,coins);
Is.add(C);
}
else
{
final Item I=CMClass.getItem(name);
if(I!=null)
Is.add(I);
else
findSomethingCalledThis(name,monster,lastKnownLocation,Is,false);
}
for(int i=0;i<Is.size();i++)
{
if(Is.get(i) instanceof Item)
{
Item I=(Item)Is.get(i);
if((I!=null)
&&(!(I instanceof ArchonOnly)))
{
I=(Item)I.copyOf();
I.recoverPhyStats();
lastKnownLocation.addItem(I,ItemPossessor.Expire.Monster_EQ);
I.setContainer(container);
if(I instanceof Coins)
((Coins)I).putCoinsBack();
if(I instanceof RawMaterial)
((RawMaterial)I).rebundle();
lastLoaded=I;
}
}
}
lastKnownLocation.recoverRoomStats();
}
break;
}
case 84: // mpoloadshop
{
ShopKeeper addHere = CMLib.coffeeShops().getShopKeeper(scripted);
if((addHere == null)&&(scripted instanceof Item))
addHere=CMLib.coffeeShops().getShopKeeper(((Item)scripted).owner());
if((addHere == null)&&(scripted instanceof MOB))
addHere=CMLib.coffeeShops().getShopKeeper(((MOB)scripted).location());
if(addHere == null)
addHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(addHere!=null)
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
if(lastKnownLocation!=null)
{
final ArrayList<Environmental> Is=new ArrayList<Environmental>();
int price=-1;
if((price = name.indexOf(" PRICE="))>=0)
{
final String rest = name.substring(price+7).trim();
name=name.substring(0,price).trim();
if(CMath.isInteger(rest))
price=CMath.s_int(rest);
}
Item I=CMClass.getItem(name);
if(I!=null)
Is.add(I);
else
findSomethingCalledThis(name,monster,lastKnownLocation,Is,false);
for(int i=0;i<Is.size();i++)
{
if(Is.get(i) instanceof Item)
{
I=(Item)Is.get(i);
if((I!=null)
&&(!(I instanceof ArchonOnly)))
{
I=(Item)I.copyOf();
I.recoverPhyStats();
final CoffeeShop shop = addHere.getShop();
if(shop != null)
{
final Environmental E=shop.addStoreInventory(I,1,price);
if(E!=null)
setShopPrice(addHere, E, tmp);
}
I.destroy();
}
}
}
lastKnownLocation.recoverRoomStats();
}
}
break;
}
case 85: // mpmloadshop
{
ShopKeeper addHere = CMLib.coffeeShops().getShopKeeper(scripted);
if((addHere == null)&&(scripted instanceof Item))
addHere=CMLib.coffeeShops().getShopKeeper(((Item)scripted).owner());
if((addHere == null)&&(scripted instanceof MOB))
addHere=CMLib.coffeeShops().getShopKeeper(((MOB)scripted).location());
if(addHere == null)
addHere=CMLib.coffeeShops().getShopKeeper(lastKnownLocation);
if(addHere!=null)
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
this.lastLoaded = null;
String name=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
int price=-1;
if((price = name.indexOf(" PRICE="))>=0)
{
final String rest = name.substring(price+7).trim();
name=name.substring(0,price).trim();
if(CMath.isInteger(rest))
price=CMath.s_int(rest);
}
final ArrayList<Environmental> Ms=new ArrayList<Environmental>();
MOB m=CMClass.getMOB(name);
if(m!=null)
Ms.add(m);
if(lastKnownLocation!=null)
{
if(Ms.size()==0)
findSomethingCalledThis(name,monster,lastKnownLocation,Ms,true);
for(int i=0;i<Ms.size();i++)
{
if(Ms.get(i) instanceof MOB)
{
m=(MOB)((MOB)Ms.get(i)).copyOf();
m.text();
m.recoverPhyStats();
m.recoverCharStats();
m.resetToMaxState();
final CoffeeShop shop = addHere.getShop();
if(shop != null)
{
final Environmental E=shop.addStoreInventory(m,1,price);
if(E!=null)
setShopPrice(addHere, E, tmp);
}
m.destroy();
}
}
}
}
break;
}
case 42: // mphide
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(newTarget!=null)
{
newTarget.basePhyStats().setDisposition(newTarget.basePhyStats().disposition()|PhyStats.IS_NOT_SEEN);
newTarget.recoverPhyStats();
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 58: // mpreset
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String arg=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
if(arg.equalsIgnoreCase("area"))
{
if(lastKnownLocation!=null)
CMLib.map().resetArea(lastKnownLocation.getArea());
}
else
if(arg.equalsIgnoreCase("room"))
{
if(lastKnownLocation!=null)
CMLib.map().resetRoom(lastKnownLocation, true);
}
else
{
final Room R=CMLib.map().getRoom(arg);
if(R!=null)
CMLib.map().resetRoom(R, true);
else
{
final Area A=CMLib.map().findArea(arg);
if(A!=null)
CMLib.map().resetArea(A);
else
{
final Physical newTarget=getArgumentItem(arg,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(newTarget == null)
logError(scripted,"MPRESET","Syntax","Unknown location or item: "+arg+" for "+scripted.Name());
else
if(newTarget instanceof Item)
{
final Item I=(Item)newTarget;
I.setContainer(null);
if(I.subjectToWearAndTear())
I.setUsesRemaining(100);
I.recoverPhyStats();
}
else
if(newTarget instanceof MOB)
{
final MOB M=(MOB)newTarget;
M.resetToMaxState();
M.recoverMaxState();
M.recoverCharStats();
M.recoverPhyStats();
}
}
}
}
break;
}
case 71: // mprejuv
{
if(tt==null)
{
final String rest=CMParms.getPastBitClean(s,1);
if(rest.equals("item")||rest.equals("items"))
tt=parseBits(script,si,"Ccr");
else
if(rest.equals("mob")||rest.equals("mobs"))
tt=parseBits(script,si,"Ccr");
else
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String next=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
String rest="";
if(tt.length>2)
rest=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
int tickID=-1;
if(rest.equalsIgnoreCase("item")||rest.equalsIgnoreCase("items"))
tickID=Tickable.TICKID_ROOM_ITEM_REJUV;
else
if(rest.equalsIgnoreCase("mob")||rest.equalsIgnoreCase("mobs"))
tickID=Tickable.TICKID_MOB;
if(next.equalsIgnoreCase("area"))
{
if(lastKnownLocation!=null)
for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
CMLib.threads().rejuv(e.nextElement(),tickID);
}
else
if(next.equalsIgnoreCase("room"))
{
if(lastKnownLocation!=null)
CMLib.threads().rejuv(lastKnownLocation,tickID);
}
else
{
final Room R=CMLib.map().getRoom(next);
if(R!=null)
CMLib.threads().rejuv(R,tickID);
else
{
final Area A=CMLib.map().findArea(next);
if(A!=null)
{
for(final Enumeration<Room> e=A.getProperMap();e.hasMoreElements();)
CMLib.threads().rejuv(e.nextElement(),tickID);
}
else
logError(scripted,"MPREJUV","Syntax","Unknown location: "+next+" for "+scripted.Name());
}
}
break;
}
case 56: // mpstop
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final List<MOB> V=new ArrayList<MOB>();
final String who=tt[1];
if(who.equalsIgnoreCase("all"))
{
for(int i=0;i<lastKnownLocation.numInhabitants();i++)
V.add(lastKnownLocation.fetchInhabitant(i));
}
else
{
final Environmental newTarget=getArgumentItem(who,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(newTarget instanceof MOB)
V.add((MOB)newTarget);
}
for(int v=0;v<V.size();v++)
{
final Environmental newTarget=V.get(v);
if(newTarget instanceof MOB)
{
final MOB mob=(MOB)newTarget;
Ability A=null;
for(int a=mob.numEffects()-1;a>=0;a--)
{
A=mob.fetchEffect(a);
if((A!=null)
&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL)
&&(A.canBeUninvoked())
&&(!A.isAutoInvoked()))
A.unInvoke();
}
mob.makePeace(false);
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
}
break;
}
case 43: // mpunhide
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(CMath.bset(newTarget.basePhyStats().disposition(),PhyStats.IS_NOT_SEEN)))
{
newTarget.basePhyStats().setDisposition(newTarget.basePhyStats().disposition()-PhyStats.IS_NOT_SEEN);
newTarget.recoverPhyStats();
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 44: // mpopen
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget instanceof Exit)&&(((Exit)newTarget).hasADoor()))
{
final Exit E=(Exit)newTarget;
E.setDoorsNLocks(E.hasADoor(),true,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
else
if((newTarget instanceof Container)&&(((Container)newTarget).hasADoor()))
{
final Container E=(Container)newTarget;
E.setDoorsNLocks(E.hasADoor(),true,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 45: // mpclose
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget instanceof Exit)
&&(((Exit)newTarget).hasADoor())
&&(((Exit)newTarget).isOpen()))
{
final Exit E=(Exit)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
else
if((newTarget instanceof Container)
&&(((Container)newTarget).hasADoor())
&&(((Container)newTarget).isOpen()))
{
final Container E=(Container)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 46: // mplock
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget instanceof Exit)
&&(((Exit)newTarget).hasALock()))
{
final Exit E=(Exit)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),true,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
else
if((newTarget instanceof Container)
&&(((Container)newTarget).hasALock()))
{
final Container E=(Container)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),true,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 47: // mpunlock
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget instanceof Exit)
&&(((Exit)newTarget).isLocked()))
{
final Exit E=(Exit)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
else
if((newTarget instanceof Container)
&&(((Container)newTarget).isLocked()))
{
final Container E=(Container)newTarget;
E.setDoorsNLocks(E.hasADoor(),false,E.defaultsClosed(),E.hasALock(),false,E.defaultsLocked());
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 48: // return
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
tickStatus=Tickable.STATUS_END;
return varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
case 87: // mea
case 7: // mpechoat
{
if(tt==null)
{
tt=parseBits(script,si,"Ccp");
if(tt==null)
return null;
}
final String parm=tt[1];
final Environmental newTarget=getArgumentMOB(parm,source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null))
{
if(newTarget==monster)
lastKnownLocation.showSource(monster,null,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
else
lastKnownLocation.show(monster,newTarget,null,CMMsg.MSG_OK_ACTION,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]),CMMsg.NO_EFFECT,null);
}
else
if(parm.equalsIgnoreCase("world"))
{
lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
for(final Enumeration<Room> e=CMLib.map().rooms();e.hasMoreElements();)
{
final Room R=e.nextElement();
if(R.numInhabitants()>0)
R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
}
}
else
if(parm.equalsIgnoreCase("area")&&(lastKnownLocation!=null))
{
lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
for(final Enumeration<Room> e=lastKnownLocation.getArea().getProperMap();e.hasMoreElements();)
{
final Room R=e.nextElement();
if(R.numInhabitants()>0)
R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
}
}
else
if(CMLib.map().getRoom(parm)!=null)
CMLib.map().getRoom(parm).show(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
else
if(CMLib.map().findArea(parm)!=null)
{
lastKnownLocation.showSource(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
for(final Enumeration<Room> e=CMLib.map().findArea(parm).getMetroMap();e.hasMoreElements();)
{
final Room R=e.nextElement();
if(R.numInhabitants()>0)
R.showOthers(monster,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
}
}
break;
}
case 88: // mer
case 8: // mpechoaround
{
if(tt==null)
{
tt=parseBits(script,si,"Ccp");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB)&&(lastKnownLocation!=null))
{
lastKnownLocation.showOthers((MOB)newTarget,null,CMMsg.MSG_OK_ACTION,varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
}
break;
}
case 9: // mpcast
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final Physical newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
Ability A=null;
if(cast!=null)
A=findAbility(cast);
if((A==null)||(cast==null)||(cast.length()==0))
logError(scripted,"MPCAST","RunTime",cast+" is not a valid ability name.");
else
if((newTarget!=null)||(tt[2].length()==0))
{
A.setProficiency(100);
if((monster != scripted)
&&(monster!=null))
monster.resetToMaxState();
A.invoke(monster,newTarget,false,0);
}
break;
}
case 89: // mpcastext
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final Physical newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String args=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
Ability A=null;
if(cast!=null)
A=findAbility(cast);
if((A==null)||(cast==null)||(cast.length()==0))
logError(scripted,"MPCASTEXT","RunTime",cast+" is not a valid ability name.");
else
if(newTarget!=null)
{
A.setProficiency(100);
final List<String> commands = CMParms.parse(args);
if((monster != scripted)
&&(monster!=null))
monster.resetToMaxState();
A.invoke(monster, commands, newTarget, false, 0);
}
break;
}
case 30: // mpaffect
{
if(tt==null)
{
tt=parseBits(script,si,"Cccp");
if(tt==null)
return null;
}
final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final Physical newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
Ability A=null;
if(cast!=null)
A=findAbility(cast);
if((A==null)||(cast==null)||(cast.length()==0))
logError(scripted,"MPAFFECT","RunTime",cast+" is not a valid ability name.");
else
if(newTarget!=null)
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" was MPAFFECTED by "+A.Name());
A.setMiscText(m2);
if((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_PROPERTY)
newTarget.addNonUninvokableEffect(A);
else
{
if((monster != scripted)
&&(monster!=null))
monster.resetToMaxState();
A.invoke(monster,CMParms.parse(m2),newTarget,true,0);
}
}
break;
}
case 80: // mpspeak
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final String language=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final Ability A=getAbility(language);
if((A instanceof Language)&&(newTarget instanceof MOB))
{
((Language)A).setProficiency(100);
((Language)A).autoInvocation((MOB)newTarget, false);
final Ability langA=((MOB)newTarget).fetchEffect(A.ID());
if(langA!=null)
{
if(((MOB)newTarget).isMonster())
langA.setProficiency(100);
langA.invoke((MOB)newTarget,CMParms.parse(""),(MOB)newTarget,false,0);
}
else
A.invoke((MOB)newTarget,CMParms.parse(""),(MOB)newTarget,false,0);
}
break;
}
case 81: // mpsetclan
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final PhysicalAgent newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String clan=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String roleStr=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
Clan C=CMLib.clans().getClan(clan);
if(C==null)
C=CMLib.clans().findClan(clan);
if((newTarget instanceof MOB)&&(C!=null))
{
int role=Integer.MIN_VALUE;
if(CMath.isInteger(roleStr))
role=CMath.s_int(roleStr);
else
for(int i=0;i<C.getRolesList().length;i++)
{
if(roleStr.equalsIgnoreCase(C.getRolesList()[i]))
role=i;
}
if(role!=Integer.MIN_VALUE)
{
if(((MOB)newTarget).isPlayer())
C.addMember((MOB)newTarget, role);
else
((MOB)newTarget).setClan(C.clanID(), role);
}
}
break;
}
case 31: // mpbehave
{
if(tt==null)
{
tt=parseBits(script,si,"Cccp");
if(tt==null)
return null;
}
String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final PhysicalAgent newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
Behavior B=null;
final Behavior B2=(cast==null)?null:CMClass.findBehavior(cast);
if(B2!=null)
cast=B2.ID();
if((cast!=null)&&(newTarget!=null))
{
B=newTarget.fetchBehavior(cast);
if(B==null)
B=CMClass.getBehavior(cast);
}
if((newTarget!=null)&&(B!=null))
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" was MPBEHAVED with "+B.name());
B.setParms(m2);
if(newTarget.fetchBehavior(B.ID())==null)
{
newTarget.addBehavior(B);
if((defaultQuestName()!=null)&&(defaultQuestName().length()>0))
B.registerDefaultQuest(defaultQuestName());
}
}
break;
}
case 72: // mpscript
{
if(tt==null)
{
tt=parseBits(script,si,"Ccp");
if(tt==null)
return null;
}
final PhysicalAgent newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
boolean proceed=true;
boolean savable=false;
boolean execute=false;
String scope=getVarScope();
while(proceed)
{
proceed=false;
if(m2.toUpperCase().startsWith("SAVABLE "))
{
savable=true;
m2=m2.substring(8).trim();
proceed=true;
}
else
if(m2.toUpperCase().startsWith("EXECUTE "))
{
execute=true;
m2=m2.substring(8).trim();
proceed=true;
}
else
if(m2.toUpperCase().startsWith("GLOBAL "))
{
scope="";
proceed=true;
m2=m2.substring(6).trim();
}
else
if(m2.toUpperCase().startsWith("INDIVIDUAL ")||m2.equals("*"))
{
scope="*";
proceed=true;
m2=m2.substring(10).trim();
}
}
if((newTarget!=null)&&(m2.length()>0))
{
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster()))
Log.sysOut("Scripting",newTarget.Name()+" was MPSCRIPTED: "+defaultQuestName);
final ScriptingEngine S=(ScriptingEngine)CMClass.getCommon("DefaultScriptingEngine");
S.setSavable(savable);
S.setVarScope(scope);
S.setScript(m2);
if((defaultQuestName()!=null)&&(defaultQuestName().length()>0))
S.registerDefaultQuest(defaultQuestName());
newTarget.addScript(S);
if(execute)
{
S.tick(newTarget,Tickable.TICKID_MOB);
for(int i=0;i<5;i++)
S.dequeResponses();
newTarget.delScript(S);
}
}
break;
}
case 32: // mpunbehave
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final PhysicalAgent newTarget=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(cast!=null))
{
Behavior B=CMClass.findBehavior(cast);
if(B!=null)
cast=B.ID();
B=newTarget.fetchBehavior(cast);
if(B!=null)
newTarget.delBehavior(B);
if((newTarget instanceof MOB)&&(!((MOB)newTarget).isMonster())&&(B!=null))
Log.sysOut("Scripting",newTarget.Name()+" was MPUNBEHAVED with "+B.name());
}
break;
}
case 33: // mptattoo
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String tattooName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if((newTarget!=null)&&(tattooName.length()>0)&&(newTarget instanceof MOB))
{
final MOB themob=(MOB)newTarget;
final boolean tattooMinus=tattooName.startsWith("-");
if(tattooMinus)
tattooName=tattooName.substring(1);
final Tattoo pT=((Tattoo)CMClass.getCommon("DefaultTattoo")).parse(tattooName);
final Tattoo T=themob.findTattoo(pT.getTattooName());
if(T!=null)
{
if(tattooMinus)
themob.delTattoo(T);
}
else
if(!tattooMinus)
themob.addTattoo(pT);
}
break;
}
case 83: // mpacctattoo
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String tattooName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if((newTarget!=null)
&&(tattooName.length()>0)
&&(newTarget instanceof MOB)
&&(((MOB)newTarget).playerStats()!=null)
&&(((MOB)newTarget).playerStats().getAccount()!=null))
{
final Tattooable themob=((MOB)newTarget).playerStats().getAccount();
final boolean tattooMinus=tattooName.startsWith("-");
if(tattooMinus)
tattooName=tattooName.substring(1);
final Tattoo pT=((Tattoo)CMClass.getCommon("DefaultTattoo")).parse(tattooName);
final Tattoo T=themob.findTattoo(pT.getTattooName());
if(T!=null)
{
if(tattooMinus)
themob.delTattoo(T);
}
else
if(!tattooMinus)
themob.addTattoo(pT);
}
break;
}
case 92: // mpput
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Physical newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(newTarget!=null)
{
if(tt[2].equalsIgnoreCase("NULL")||tt[2].equalsIgnoreCase("NONE"))
{
if(newTarget instanceof Item)
((Item)newTarget).setContainer(null);
if(newTarget instanceof Rider)
((Rider)newTarget).setRiding(null);
}
else
{
final Physical newContainer=getArgumentItem(tt[2],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(newContainer!=null)
{
if((newTarget instanceof Item)
&&(newContainer instanceof Container))
((Item)newTarget).setContainer((Container)newContainer);
if((newTarget instanceof Rider)
&&(newContainer instanceof Rideable))
((Rider)newTarget).setRiding((Rideable)newContainer);
}
}
newTarget.recoverPhyStats();
if(lastKnownLocation!=null)
lastKnownLocation.recoverRoomStats();
}
break;
}
case 55: // mpnotrigger
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final String trigger=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
int triggerCode=-1;
for(int i=0;i<progs.length;i++)
{
if(trigger.equalsIgnoreCase(progs[i]))
triggerCode=i+1;
}
if(triggerCode<=0)
logError(scripted,"MPNOTRIGGER","RunTime",trigger+" is not a valid trigger name.");
else
if(!CMath.isInteger(time.trim()))
logError(scripted,"MPNOTRIGGER","RunTime",time+" is not a valid milisecond time.");
else
{
noTrigger.remove(Integer.valueOf(triggerCode));
noTrigger.put(Integer.valueOf(triggerCode),Long.valueOf(System.currentTimeMillis()+CMath.s_long(time.trim())));
}
break;
}
case 54: // mpfaction
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String faction=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String range=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]).trim();
final Faction F=CMLib.factions().getFaction(faction);
if((newTarget!=null)&&(F!=null)&&(newTarget instanceof MOB))
{
final MOB themob=(MOB)newTarget;
int curFaction = themob.fetchFaction(F.factionID());
if((curFaction == Integer.MAX_VALUE)||(curFaction == Integer.MIN_VALUE))
curFaction = F.findDefault(themob);
if((range.startsWith("--"))&&(CMath.isInteger(range.substring(2).trim())))
{
final int amt=CMath.s_int(range.substring(2).trim());
if(amt < 0)
themob.tell(L("You gain @x1 faction with @x2.",""+(-amt),F.name()));
else
themob.tell(L("You lose @x1 faction with @x2.",""+amt,F.name()));
range=""+(curFaction-amt);
}
else
if((range.startsWith("+"))&&(CMath.isInteger(range.substring(1).trim())))
{
final int amt=CMath.s_int(range.substring(1).trim());
if(amt < 0)
themob.tell(L("You lose @x1 faction with @x2.",""+(-amt),F.name()));
else
themob.tell(L("You gain @x1 faction with @x2.",""+amt,F.name()));
range=""+(curFaction+amt);
}
else
if(CMath.isInteger(range))
themob.tell(L("Your faction with @x1 is now @x2.",F.name(),""+CMath.s_int(range.trim())));
if(CMath.isInteger(range))
themob.addFaction(F.factionID(),CMath.s_int(range.trim()));
else
{
Faction.FRange FR=null;
final Enumeration<Faction.FRange> e=CMLib.factions().getRanges(CMLib.factions().getAlignmentID());
if(e!=null)
for(;e.hasMoreElements();)
{
final Faction.FRange FR2=e.nextElement();
if(FR2.name().equalsIgnoreCase(range))
{
FR = FR2;
break;
}
}
if(FR==null)
logError(scripted,"MPFACTION","RunTime",range+" is not a valid range for "+F.name()+".");
else
{
themob.tell(L("Your faction with @x1 is now @x2.",F.name(),FR.name()));
themob.addFaction(F.factionID(),FR.low()+((FR.high()-FR.low())/2));
}
}
}
break;
}
case 49: // mptitle
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String titleStr=varify(monster, newTarget, scripted, monster, secondaryItem, secondaryItem, msg, tmp, tt[2]);
if((newTarget!=null)&&(titleStr.length()>0)&&(newTarget instanceof MOB))
{
final MOB themob=(MOB)newTarget;
final boolean tattooMinus=titleStr.startsWith("-");
if(tattooMinus)
titleStr=titleStr.substring(1);
if(themob.playerStats()!=null)
{
if(themob.playerStats().getTitles().contains(titleStr))
{
if(tattooMinus)
themob.playerStats().getTitles().remove(titleStr);
}
else
if(!tattooMinus)
themob.playerStats().getTitles().add(0,titleStr);
}
}
break;
}
case 10: // mpkill
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)
&&(newTarget instanceof MOB)
&&(monster!=null))
monster.setVictim((MOB)newTarget);
break;
}
case 51: // mpsetclandata
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
String clanID=null;
if((newTarget!=null)&&(newTarget instanceof MOB))
{
Clan C=CMLib.clans().findRivalrousClan((MOB)newTarget);
if(C==null)
C=((MOB)newTarget).clans().iterator().hasNext()?((MOB)newTarget).clans().iterator().next().first:null;
if(C!=null)
clanID=C.clanID();
}
else
clanID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final String clanvar=tt[2];
final String clanval=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
final Clan C=CMLib.clans().getClan(clanID);
if(C!=null)
{
if(!C.isStat(clanvar))
logError(scripted,"MPSETCLANDATA","RunTime",clanvar+" is not a valid clan variable.");
else
{
C.setStat(clanvar,clanval.trim());
if(C.getStat(clanvar).equalsIgnoreCase(clanval))
C.update();
}
}
break;
}
case 52: // mpplayerclass
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if((newTarget!=null)&&(newTarget instanceof MOB))
{
final List<String> V=CMParms.parse(tt[2]);
for(int i=0;i<V.size();i++)
{
if(CMath.isInteger(V.get(i).trim()))
((MOB)newTarget).baseCharStats().setClassLevel(((MOB)newTarget).baseCharStats().getCurrentClass(),CMath.s_int(V.get(i).trim()));
else
{
final CharClass C=CMClass.findCharClass(V.get(i));
if((C!=null)&&(C.availabilityCode()!=0))
((MOB)newTarget).baseCharStats().setCurrentClass(C);
}
}
((MOB)newTarget).recoverCharStats();
}
break;
}
case 12: // mppurge
{
if(lastKnownLocation!=null)
{
int flag=0;
if(tt==null)
{
final String s2=CMParms.getCleanBit(s,1).toLowerCase();
if(s2.equals("room"))
tt=parseBits(script,si,"Ccr");
else
if(s2.equals("my"))
tt=parseBits(script,si,"Ccr");
else
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
String s2=tt[1];
if(s2.equalsIgnoreCase("room"))
{
flag=1;
s2=tt[2];
}
else
if(s2.equalsIgnoreCase("my"))
{
flag=2;
s2=tt[2];
}
Environmental E=null;
if(s2.equalsIgnoreCase("self")||s2.equalsIgnoreCase("me"))
E=scripted;
else
if(flag==1)
{
s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s2);
E=lastKnownLocation.fetchFromRoomFavorItems(null,s2);
}
else
if(flag==2)
{
s2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s2);
if(monster!=null)
E=monster.findItem(s2);
}
else
E=getArgumentItem(s2,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
{
if(E instanceof MOB)
{
if(!((MOB)E).isMonster())
{
if(((MOB)E).getStartRoom()!=null)
((MOB)E).getStartRoom().bringMobHere((MOB)E,false);
((MOB)E).session().stopSession(false,false,false);
}
else
if(((MOB)E).getStartRoom()!=null)
((MOB)E).killMeDead(false);
else
((MOB)E).destroy();
}
else
if(E instanceof Item)
{
final ItemPossessor oE=((Item)E).owner();
((Item)E).destroy();
if(oE!=null)
oE.recoverPhyStats();
}
}
lastKnownLocation.recoverRoomStats();
}
break;
}
case 14: // mpgoto
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String roomID=tt[1].trim();
if((roomID.length()>0)&&(lastKnownLocation!=null))
{
Room goHere=null;
if(roomID.startsWith("$"))
goHere=CMLib.map().roomLocation(this.getArgumentItem(roomID,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(goHere==null)
goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomID),lastKnownLocation);
if(goHere!=null)
{
if(scripted instanceof MOB)
goHere.bringMobHere((MOB)scripted,true);
else
if(scripted instanceof Item)
goHere.moveItemTo((Item)scripted,ItemPossessor.Expire.Player_Drop,ItemPossessor.Move.Followers);
else
{
goHere.bringMobHere(monster,true);
if(!(scripted instanceof MOB))
goHere.delInhabitant(monster);
}
if(CMLib.map().roomLocation(scripted)==goHere)
lastKnownLocation=goHere;
}
}
break;
}
case 15: // mpat
if(lastKnownLocation!=null)
{
if(tt==null)
{
tt=parseBits(script,si,"Ccp");
if(tt==null)
return null;
}
final Room lastPlace=lastKnownLocation;
final String roomName=tt[1];
if(roomName.length()>0)
{
final String doWhat=tt[2].trim();
Room goHere=null;
if(roomName.startsWith("$"))
goHere=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(goHere==null)
goHere=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation);
if(goHere!=null)
{
goHere.bringMobHere(monster,true);
final DVector subScript=new DVector(3);
subScript.addElement("",null,null);
subScript.addElement(doWhat,null,null);
lastKnownLocation=goHere;
execute(scripted,source,target,monster,primaryItem,secondaryItem,subScript,msg,tmp);
lastKnownLocation=lastPlace;
lastPlace.bringMobHere(monster,true);
if(!(scripted instanceof MOB))
{
goHere.delInhabitant(monster);
lastPlace.delInhabitant(monster);
}
}
}
}
break;
case 17: // mptransfer
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
String mobName=tt[1];
String roomName=tt[2].trim();
Room newRoom=null;
if(roomName.startsWith("$"))
newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if((roomName.length()==0)&&(lastKnownLocation!=null))
roomName=lastKnownLocation.roomID();
if(roomName.length()>0)
{
if(newRoom==null)
newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation);
if(newRoom!=null)
{
final ArrayList<Environmental> V=new ArrayList<Environmental>();
if(mobName.startsWith("$"))
{
final Environmental E=getArgumentItem(mobName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E!=null)
V.add(E);
}
if(V.size()==0)
{
mobName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,mobName);
if(mobName.equalsIgnoreCase("all"))
{
if(lastKnownLocation!=null)
{
for(int x=0;x<lastKnownLocation.numInhabitants();x++)
{
final MOB m=lastKnownLocation.fetchInhabitant(x);
if((m!=null)&&(m!=monster)&&(!V.contains(m)))
V.add(m);
}
}
}
else
{
MOB findOne=null;
Area A=null;
if(findOne==null)
{
if(lastKnownLocation!=null)
{
findOne=lastKnownLocation.fetchInhabitant(mobName);
A=lastKnownLocation.getArea();
if((findOne!=null)&&(findOne!=monster))
V.add(findOne);
}
}
if(findOne==null)
{
findOne=CMLib.players().getPlayerAllHosts(mobName);
if((findOne!=null)&&(!CMLib.flags().isInTheGame(findOne,true)))
findOne=null;
if((findOne!=null)&&(findOne!=monster))
V.add(findOne);
}
if((findOne==null)&&(A!=null))
{
for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();)
{
final Room R=r.nextElement();
findOne=R.fetchInhabitant(mobName);
if((findOne!=null)&&(findOne!=monster))
V.add(findOne);
}
}
}
}
for(int v=0;v<V.size();v++)
{
if(V.get(v) instanceof MOB)
{
final MOB mob=(MOB)V.get(v);
final Set<MOB> H=mob.getGroupMembers(new HashSet<MOB>());
for (final Object element : H)
{
final MOB M=(MOB)element;
if((!V.contains(M))&&(M.location()==mob.location()))
V.add(M);
}
}
}
for(int v=0;v<V.size();v++)
{
if(V.get(v) instanceof MOB)
{
final MOB follower=(MOB)V.get(v);
final Room thisRoom=follower.location();
final int dispmask=(PhyStats.IS_SLEEPING | PhyStats.IS_SITTING);
final int dispo1 = follower.basePhyStats().disposition() & dispmask;
final int dispo2 = follower.phyStats().disposition() & dispmask;
follower.basePhyStats().setDisposition(follower.basePhyStats().disposition() & (~dispmask));
follower.phyStats().setDisposition(follower.phyStats().disposition() & (~dispmask));
// scripting guide calls for NO text -- empty is probably req tho
final CMMsg enterMsg=CMClass.getMsg(follower,newRoom,null,CMMsg.MSG_ENTER|CMMsg.MASK_ALWAYS,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER," "+CMLib.protocol().msp("appear.wav",10));
final CMMsg leaveMsg=CMClass.getMsg(follower,thisRoom,null,CMMsg.MSG_LEAVE|CMMsg.MASK_ALWAYS," ");
if((thisRoom!=null)
&&thisRoom.okMessage(follower,leaveMsg)
&&newRoom.okMessage(follower,enterMsg))
{
final boolean alreadyHere = follower.location()==(Room)enterMsg.target();
if(follower.isInCombat())
{
CMLib.commands().postFlee(follower,("NOWHERE"));
follower.makePeace(true);
}
thisRoom.send(follower,leaveMsg);
if(!alreadyHere)
((Room)enterMsg.target()).bringMobHere(follower,false);
((Room)enterMsg.target()).send(follower,enterMsg);
follower.basePhyStats().setDisposition(follower.basePhyStats().disposition() | dispo1);
follower.phyStats().setDisposition(follower.phyStats().disposition() | dispo2);
if(!CMLib.flags().isSleeping(follower)
&&(!alreadyHere))
{
follower.tell(CMLib.lang().L("\n\r\n\r"));
CMLib.commands().postLook(follower,true);
}
}
else
{
follower.basePhyStats().setDisposition(follower.basePhyStats().disposition() | dispo1);
follower.phyStats().setDisposition(follower.phyStats().disposition() | dispo2);
}
}
else
if((V.get(v) instanceof Item)
&&(newRoom!=CMLib.map().roomLocation(V.get(v))))
newRoom.moveItemTo((Item)V.get(v),ItemPossessor.Expire.Player_Drop,ItemPossessor.Move.Followers);
if((V.get(v)==scripted)
&&(scripted instanceof Physical)
&&(newRoom.isHere(scripted)))
lastKnownLocation=newRoom;
}
}
}
break;
}
case 25: // mpbeacon
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final String roomName=tt[1];
Room newRoom=null;
if((roomName.length()>0)&&(lastKnownLocation!=null))
{
final String beacon=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if(roomName.startsWith("$"))
newRoom=CMLib.map().roomLocation(this.getArgumentItem(roomName,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp));
if(newRoom==null)
newRoom=getRoom(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,roomName),lastKnownLocation);
if(newRoom == null)
logError(scripted,"MPBEACON","RunTime",tt[1]+" is not a room.");
else
if(lastKnownLocation!=null)
{
final List<MOB> V=new ArrayList<MOB>();
if(beacon.equalsIgnoreCase("all"))
{
for(int x=0;x<lastKnownLocation.numInhabitants();x++)
{
final MOB m=lastKnownLocation.fetchInhabitant(x);
if((m!=null)&&(m!=monster)&&(!m.isMonster())&&(!V.contains(m)))
V.add(m);
}
}
else
{
final MOB findOne=lastKnownLocation.fetchInhabitant(beacon);
if((findOne!=null)&&(findOne!=monster)&&(!findOne.isMonster()))
V.add(findOne);
}
for(int v=0;v<V.size();v++)
{
final MOB follower=V.get(v);
if(!follower.isMonster())
follower.setStartRoom(newRoom);
}
}
}
break;
}
case 18: // mpforce
{
if(tt==null)
{
tt=parseBits(script,si,"Ccp");
if(tt==null)
return null;
}
final PhysicalAgent newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String force=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]).trim();
if(newTarget!=null)
{
final DVector vscript=new DVector(3);
vscript.addElement("FUNCTION_PROG MPFORCE_"+System.currentTimeMillis()+Math.random(),null,null);
vscript.addElement(force,null,null);
// this can not be permanently parsed because it is variable
execute(newTarget, source, target, getMakeMOB(newTarget), primaryItem, secondaryItem, vscript, msg, tmp);
}
break;
}
case 79: // mppossess
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final PhysicalAgent newSource=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final PhysicalAgent newTarget=getArgumentMOB(tt[2],source,monster,target,primaryItem,secondaryItem,msg,tmp);
if((!(newSource instanceof MOB))||(((MOB)newSource).isMonster()))
logError(scripted,"MPPOSSESS","RunTime",tt[1]+" is not a player.");
else
if((!(newTarget instanceof MOB))||(!((MOB)newTarget).isMonster())||CMSecurity.isASysOp((MOB)newTarget))
logError(scripted,"MPPOSSESS","RunTime",tt[2]+" is not a mob.");
else
{
final MOB mobM=(MOB)newSource;
final MOB targetM=(MOB)newTarget;
final Session S=mobM.session();
S.setMob(targetM);
targetM.setSession(S);
targetM.setSoulMate(mobM);
mobM.setSession(null);
}
break;
}
case 20: // mpsetvar
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
String which=tt[1];
final Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if(!which.equals("*"))
{
if(E==null)
which=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,which);
else
if(E instanceof Room)
which=CMLib.map().getExtendedRoomID((Room)E);
else
which=E.Name();
}
if((which.length()>0)&&(arg2.length()>0))
{
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS))
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+which+"("+arg2+")="+arg3+"<");
setVar(which,arg2,arg3);
}
break;
}
case 36: // mpsavevar
{
if(tt==null)
{
tt=parseBits(script,si,"CcR");
if(tt==null)
return null;
}
String which=tt[1];
String arg2=tt[2];
final Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
if((which.length()>0)&&(arg2.length()>0))
{
final PairList<String,String> vars=getScriptVarSet(which,arg2);
for(int v=0;v<vars.size();v++)
{
which=vars.elementAtFirst(v);
arg2=vars.elementAtSecond(v).toUpperCase();
@SuppressWarnings("unchecked")
final Hashtable<String,String> H=(Hashtable<String,String>)resources._getResource("SCRIPTVAR-"+which);
String val="";
if(H!=null)
{
val=H.get(arg2);
if(val==null)
val="";
}
if(val.length()>0)
CMLib.database().DBReCreatePlayerData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2,val);
else
CMLib.database().DBDeletePlayerData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2);
}
}
break;
}
case 39: // mploadvar
{
if(tt==null)
{
tt=parseBits(script,si,"CcR");
if(tt==null)
return null;
}
String which=tt[1];
final String arg2=tt[2];
final Environmental E=getArgumentItem(which,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(arg2.length()>0)
{
List<PlayerData> V=null;
which=getVarHost(E,which,source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp);
if(arg2.equals("*"))
V=CMLib.database().DBReadPlayerData(which,"SCRIPTABLEVARS");
else
V=CMLib.database().DBReadPlayerData(which,"SCRIPTABLEVARS",which.toUpperCase()+"_SCRIPTABLEVARS_"+arg2);
if((V!=null)&&(V.size()>0))
for(int v=0;v<V.size();v++)
{
final DatabaseEngine.PlayerData VAR=V.get(v);
String varName=VAR.key();
if(varName.startsWith(which.toUpperCase()+"_SCRIPTABLEVARS_"))
varName=varName.substring((which+"_SCRIPTABLEVARS_").length());
if(CMSecurity.isDebugging(CMSecurity.DbgFlag.SCRIPTVARS))
Log.debugOut(CMStrings.padRight(scripted.Name(), 15)+": SETVAR: "+which+"("+varName+")="+VAR.xml()+"<");
setVar(which,varName,VAR.xml());
}
}
break;
}
case 40: // MPM2I2M
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final String arg1=tt[1];
final Environmental E=getArgumentItem(arg1,source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
if(E instanceof MOB)
{
final String arg2=tt[2];
final String arg3=tt[3];
final CagedAnimal caged=(CagedAnimal)CMClass.getItem("GenCaged");
if(caged!=null)
{
((Item)caged).basePhyStats().setAbility(1);
((Item)caged).recoverPhyStats();
}
if((caged!=null)&&caged.cageMe((MOB)E)&&(lastKnownLocation!=null))
{
if(arg2.length()>0)
((Item)caged).setName(arg2);
if(arg3.length()>0)
((Item)caged).setDisplayText(arg3);
lastKnownLocation.addItem(caged,ItemPossessor.Expire.Player_Drop);
((MOB)E).killMeDead(false);
}
}
else
if(E instanceof CagedAnimal)
{
final MOB M=((CagedAnimal)E).unCageMe();
if((M!=null)&&(lastKnownLocation!=null))
{
M.bringToLife(lastKnownLocation,true);
((Item)E).destroy();
}
}
else
logError(scripted,"MPM2I2M","RunTime",arg1+" is not a mob or a caged item.");
break;
}
case 28: // mpdamage
{
if(tt==null)
{
tt=parseBits(script,si,"Ccccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
final String arg4=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]).toUpperCase();
if((newTarget!=null)&&(arg2.length()>0))
{
if(newTarget instanceof MOB)
{
final MOB deadM=(MOB)newTarget;
MOB killerM=(MOB)newTarget;
boolean me=false;
boolean kill=false;
int damageType = CMMsg.TYP_CAST_SPELL;
for(final String s4 : arg4.split(" "))
{
if(arg4.length()==0)
continue;
if(arg4.equals("MEKILL"))
{
me=true;
kill=true;
}
else
if(arg4.equals("ME"))
me=true;
else
if(arg4.equals("KILL"))
kill=true;
else
{
for(int i4=0;i4<CharStats.DEFAULT_STAT_MSG_MAP.length;i4++)
{
final int code4=CharStats.DEFAULT_STAT_MSG_MAP[i4];
if((code4>0)&&(CMMsg.TYPE_DESCS[code4&CMMsg.MINOR_MASK].equals(s4)))
{
damageType=code4;
break;
}
}
}
}
if(me)
killerM=monster;
final int min=CMath.s_int(arg2.trim());
int max=CMath.s_int(arg3.trim());
if(max<min)
max=min;
if(min>0)
{
int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min);
if((dmg>=deadM.curState().getHitPoints())
&&(!kill))
dmg=deadM.curState().getHitPoints()-1;
if(dmg>0)
CMLib.combat().postDamage(killerM,deadM,null,dmg,CMMsg.MASK_ALWAYS|damageType,-1,null);
}
}
else
if(newTarget instanceof Item)
{
final Item E=(Item)newTarget;
final int min=CMath.s_int(arg2.trim());
int max=CMath.s_int(arg3.trim());
if(max<min)
max=min;
if(min>0)
{
int dmg=(max==min)?min:CMLib.dice().roll(1,max-min,min);
boolean destroy=false;
if(E.subjectToWearAndTear())
{
if((dmg>=E.usesRemaining())&&(!arg4.equalsIgnoreCase("kill")))
dmg=E.usesRemaining()-1;
if(dmg>0)
E.setUsesRemaining(E.usesRemaining()-dmg);
if(E.usesRemaining()<=0)
destroy=true;
}
else
if(arg4.equalsIgnoreCase("kill"))
destroy=true;
if(destroy)
{
if(lastKnownLocation!=null)
lastKnownLocation.showHappens(CMMsg.MSG_OK_VISUAL,L("@x1 is destroyed!",E.name()));
E.destroy();
}
}
}
}
break;
}
case 78: // mpheal
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentItem(tt[1],source,monster,scripted,target,primaryItem,secondaryItem,msg,tmp);
final String arg2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final String arg3=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
if((newTarget!=null)&&(arg2.length()>0))
{
if(newTarget instanceof MOB)
{
final MOB healedM=(MOB)newTarget;
final MOB healerM=(MOB)newTarget;
final int min=CMath.s_int(arg2.trim());
int max=CMath.s_int(arg3.trim());
if(max<min)
max=min;
if(min>0)
{
final int amt=(max==min)?min:CMLib.dice().roll(1,max-min,min);
if(amt>0)
CMLib.combat().postHealing(healerM,healedM,null,amt,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,null);
}
}
else
if(newTarget instanceof Item)
{
final Item E=(Item)newTarget;
final int min=CMath.s_int(arg2.trim());
int max=CMath.s_int(arg3.trim());
if(max<min)
max=min;
if(min>0)
{
final int amt=(max==min)?min:CMLib.dice().roll(1,max-min,min);
if(E.subjectToWearAndTear())
{
E.setUsesRemaining(E.usesRemaining()+amt);
if(E.usesRemaining()>100)
E.setUsesRemaining(100);
}
}
}
}
break;
}
case 90: // mplink
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final String dirWord=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final int dir=CMLib.directions().getGoodDirectionCode(dirWord);
if(dir < 0)
logError(scripted,"MPLINK","RunTime",dirWord+" is not a valid direction.");
else
{
final String roomID = varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
final Room startR=(homeKnownLocation!=null)?homeKnownLocation:CMLib.map().getStartRoom(scripted);
final Room R=this.getRoom(roomID, lastKnownLocation);
if((R==null)||(lastKnownLocation==null)||(R.getArea()!=lastKnownLocation.getArea()))
logError(scripted,"MPLINK","RunTime",roomID+" is not a target room.");
else
if((startR!=null)&&(startR.getArea()!=lastKnownLocation.getArea()))
logError(scripted,"MPLINK","RunTime","mplink from "+roomID+" is an illegal source room.");
else
{
String exitID=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
String nameArg=null;
final int x=exitID.indexOf(' ');
if(x>0)
{
nameArg=exitID.substring(x+1).trim();
exitID=exitID.substring(0,x);
}
final Exit E=CMClass.getExit(exitID);
if(E==null)
logError(scripted,"MPLINK","RunTime",exitID+" is not a exit class.");
else
if((lastKnownLocation.rawDoors()[dir]==null)
&&(lastKnownLocation.getRawExit(dir)==null))
{
lastKnownLocation.rawDoors()[dir]=R;
lastKnownLocation.setRawExit(dir, E);
E.basePhyStats().setSensesMask(E.basePhyStats().sensesMask()|PhyStats.SENSE_ITEMNOWISH);
E.setSavable(false);
E.recoverPhyStats();
if(nameArg!=null)
E.setName(nameArg);
}
}
}
break;
}
case 91: // mpunlink
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String dirWord=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final int dir=CMLib.directions().getGoodDirectionCode(dirWord);
if(dir < 0)
logError(scripted,"MPLINK","RunTime",dirWord+" is not a valid direction.");
else
if((lastKnownLocation==null)
||((lastKnownLocation.rawDoors()[dir]!=null)&&(lastKnownLocation.rawDoors()[dir].getArea()!=lastKnownLocation.getArea())))
logError(scripted,"MPLINK","RunTime",dirWord+" is a non-in-area direction.");
else
if((lastKnownLocation.getRawExit(dir)!=null)
&&(lastKnownLocation.getRawExit(dir).isSavable()
||(!CMath.bset(lastKnownLocation.getRawExit(dir).basePhyStats().sensesMask(), PhyStats.SENSE_ITEMNOWISH))))
logError(scripted,"MPLINK","RunTime",dirWord+" is not a legal unlinkable exit.");
else
{
lastKnownLocation.setRawExit(dir, null);
lastKnownLocation.rawDoors()[dir]=null;
}
break;
}
case 29: // mptrackto
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final Ability A=CMClass.getAbility("Skill_Track");
if(A!=null)
{
if((monster != scripted)
&&(monster!=null))
monster.resetToMaxState();
if(A.text().length()>0 && A.text().equalsIgnoreCase(arg1))
{
// already on the move
}
else
{
altStatusTickable=A;
A.invoke(monster,CMParms.parse(arg1),null,true,0);
altStatusTickable=null;
}
}
break;
}
case 53: // mpwalkto
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String arg1=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final Ability A=CMClass.getAbility("Skill_Track");
if(A!=null)
{
altStatusTickable=A;
if((monster != scripted)
&&(monster!=null))
monster.resetToMaxState();
A.invoke(monster,CMParms.parse(arg1+" LANDONLY"),null,true,0);
altStatusTickable=null;
}
break;
}
case 21: //MPENDQUEST
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final PhysicalAgent newTarget;
final String q=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim());
final Quest Q=getQuest(q);
if(Q!=null)
{
final CMMsg stopMsg=CMClass.getMsg(monster,null,null,CMMsg.NO_EFFECT,null,CMMsg.TYP_ENDQUEST,Q.name(),CMMsg.NO_EFFECT,null);
CMLib.map().sendGlobalMessage(monster, CMMsg.TYP_ENDQUEST, stopMsg);
Q.stopQuest();
CMLib.coffeeTables().bump(Q,CoffeeTableRow.STAT_QUESTSTOP);
}
else
if((tt[1].length()>0)
&&(defaultQuestName!=null)
&&(defaultQuestName.length()>0)
&&((newTarget=getArgumentMOB(tt[1].trim(),source,monster,target,primaryItem,secondaryItem,msg,tmp))!=null))
{
for(int i=newTarget.numScripts()-1;i>=0;i--)
{
final ScriptingEngine S=newTarget.fetchScript(i);
if((S!=null)
&&(S.defaultQuestName()!=null)
&&(S.defaultQuestName().equalsIgnoreCase(defaultQuestName)))
{
newTarget.delScript(S);
S.endQuest(newTarget, (newTarget instanceof MOB)?((MOB)newTarget):monster, defaultQuestName);
}
}
}
else
if(q.length()>0)
{
boolean foundOne=false;
for(int i=scripted.numScripts()-1;i>=0;i--)
{
final ScriptingEngine S=scripted.fetchScript(i);
if((S!=null)
&&(S.defaultQuestName()!=null)
&&(S.defaultQuestName().equalsIgnoreCase(q)))
{
foundOne=true;
S.endQuest(scripted, monster, S.defaultQuestName());
scripted.delScript(S);
}
}
if((!foundOne)
&&((defaultQuestName==null)||(!defaultQuestName.equalsIgnoreCase(q))))
logError(scripted,"MPENDQUEST","Unknown","Quest: "+s);
}
break;
}
case 69: // MPSTEPQUEST
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String qName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim());
final Quest Q=getQuest(qName);
if(Q!=null)
Q.stepQuest();
else
logError(scripted,"MPSTEPQUEST","Unknown","Quest: "+s);
break;
}
case 23: //MPSTARTQUEST
{
if(tt==null)
{
tt=parseBits(script,si,"Cr");
if(tt==null)
return null;
}
final String qName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim());
final Quest Q=getQuest(qName);
if(Q!=null)
Q.startQuest();
else
logError(scripted,"MPSTARTQUEST","Unknown","Quest: "+s);
break;
}
case 64: //MPLOADQUESTOBJ
{
if(tt==null)
{
tt=parseBits(script,si,"Cccr");
if(tt==null)
return null;
}
final String questName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1].trim());
final Quest Q=getQuest(questName);
if(Q==null)
{
logError(scripted,"MPLOADQUESTOBJ","Unknown","Quest: "+questName);
break;
}
final Object O=Q.getDesignatedObject(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]));
if(O==null)
{
logError(scripted,"MPLOADQUESTOBJ","Unknown","Unknown var "+tt[2]+" for Quest: "+questName);
break;
}
final String varArg=tt[3];
if((varArg.length()!=2)||(!varArg.startsWith("$")))
{
logError(scripted,"MPLOADQUESTOBJ","Syntax","Invalid argument var: "+varArg+" for "+scripted.Name());
break;
}
final char c=varArg.charAt(1);
if(Character.isDigit(c))
tmp[CMath.s_int(Character.toString(c))]=O;
else
switch(c)
{
case 'N':
case 'n':
if (O instanceof MOB)
source = (MOB) O;
break;
case 'I':
case 'i':
if (O instanceof PhysicalAgent)
scripted = (PhysicalAgent) O;
if (O instanceof MOB)
monster = (MOB) O;
break;
case 'B':
case 'b':
if (O instanceof Environmental)
lastLoaded = (Environmental) O;
break;
case 'T':
case 't':
if (O instanceof Environmental)
target = (Environmental) O;
break;
case 'O':
case 'o':
if (O instanceof Item)
primaryItem = (Item) O;
break;
case 'P':
case 'p':
if (O instanceof Item)
secondaryItem = (Item) O;
break;
case 'd':
case 'D':
if (O instanceof Room)
lastKnownLocation = (Room) O;
break;
default:
logError(scripted, "MPLOADQUESTOBJ", "Syntax", "Invalid argument var: " + varArg + " for " + scripted.Name());
break;
}
break;
}
case 22: //MPQUESTWIN
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
String whoName=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
MOB M=null;
if(lastKnownLocation!=null)
M=lastKnownLocation.fetchInhabitant(whoName);
if(M==null)
M=CMLib.players().getPlayerAllHosts(whoName);
if(M!=null)
whoName=M.Name();
if(whoName.length()>0)
{
final Quest Q=getQuest(tt[2]);
if(Q!=null)
{
if(M!=null)
{
CMLib.achievements().possiblyBumpAchievement(M, AchievementLibrary.Event.QUESTOR, 1, Q);
final CMMsg winMsg=CMClass.getMsg(M,null,null,CMMsg.NO_EFFECT,null,CMMsg.TYP_WINQUEST,Q.name(),CMMsg.NO_EFFECT,null);
CMLib.map().sendGlobalMessage(M, CMMsg.TYP_WINQUEST, winMsg);
}
Q.declareWinner(whoName);
CMLib.players().bumpPrideStat(M,AccountStats.PrideStat.QUESTS_COMPLETED, 1);
}
else
logError(scripted,"MPQUESTWIN","Unknown","Quest: "+s);
}
break;
}
case 24: // MPCALLFUNC
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
if(script.elementAt(si, 3) != null)
{
execute(scripted, source, target, monster, primaryItem, secondaryItem, (DVector)script.elementAt(si, 3),
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2].trim()),
tmp);
}
else
{
final String named=tt[1];
final String parms=tt[2].trim();
final DVector script2 = findFunc(named);
if(script2 != null)
{
script.setElementAt(si, 3, script2);
execute(scripted, source, target, monster, primaryItem, secondaryItem, script2,
varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,parms),
tmp);
}
else
logError(scripted,"MPCALLFUNC","Unknown","Function: "+named);
}
break;
}
case 27: // MPWHILE
{
if(tt==null)
{
final ArrayList<String> V=new ArrayList<String>();
V.add("MPWHILE");
String conditionStr=(s.substring(7).trim());
if(!conditionStr.startsWith("("))
{
logError(scripted,"MPWHILE","Syntax"," NO Starting (: "+s);
break;
}
conditionStr=conditionStr.substring(1).trim();
int x=-1;
int depth=0;
for(int i=0;i<conditionStr.length();i++)
{
if(conditionStr.charAt(i)=='(')
depth++;
else
if((conditionStr.charAt(i)==')')&&((--depth)<0))
{
x=i;
break;
}
}
if(x<0)
{
logError(scripted,"MPWHILE","Syntax"," no closing ')': "+s);
break;
}
final String DO=conditionStr.substring(x+1).trim();
conditionStr=conditionStr.substring(0,x);
try
{
final String[] EVAL=parseEval(conditionStr);
V.add("(");
V.addAll(Arrays.asList(EVAL));
V.add(")");
V.add(DO);
tt=CMParms.toStringArray(V);
script.setElementAt(si,2,tt);
}
catch(final Exception e)
{
logError(scripted,"MPWHILE","Syntax",e.getMessage());
break;
}
if(tt==null)
return null;
}
int evalEnd=2;
int depth=0;
while((evalEnd<tt.length)&&((!tt[evalEnd].equals(")"))||(depth>0)))
{
if(tt[evalEnd].equals("("))
depth++;
else
if(tt[evalEnd].equals(")"))
depth--;
evalEnd++;
}
if(evalEnd==tt.length)
{
logError(scripted,"MPWHILE","Syntax"," no closing ')': "+s);
break;
}
final String[] EVAL=new String[evalEnd-2];
for(int y=2;y<evalEnd;y++)
EVAL[y-2]=tt[y];
String DO=tt[evalEnd+1];
String[] DOT=null;
final int doLen=(tt.length-evalEnd)-1;
if(doLen>1)
{
DOT=new String[doLen];
for(int y=0;y<DOT.length;y++)
{
DOT[y]=tt[evalEnd+y+1];
if(y>0)
DO+=" "+tt[evalEnd+y+1];
}
}
final String[][] EVALO={EVAL};
final DVector vscript=new DVector(3);
vscript.addElement("FUNCTION_PROG MPWHILE_"+Math.random(),null,null);
vscript.addElement(DO,DOT,null);
final long time=System.currentTimeMillis();
while((eval(scripted,source,target,monster,primaryItem,secondaryItem,msg,tmp,EVALO,0))
&&((System.currentTimeMillis()-time)<4000)
&&(!scripted.amDestroyed()))
execute(scripted,source,target,monster,primaryItem,secondaryItem,vscript,msg,tmp);
if(vscript.elementAt(1,2)!=DOT)
{
final int oldDotLen=(DOT==null)?1:DOT.length;
final String[] newDOT=(String[])vscript.elementAt(1,2);
final String[] newTT=new String[tt.length-oldDotLen+newDOT.length];
int end=0;
for(end=0;end<tt.length-oldDotLen;end++)
newTT[end]=tt[end];
for(int y=0;y<newDOT.length;y++)
newTT[end+y]=newDOT[y];
tt=newTT;
script.setElementAt(si,2,tt);
}
if(EVALO[0]!=EVAL)
{
final Vector<String> lazyV=new Vector<String>();
lazyV.addElement("MPWHILE");
lazyV.addElement("(");
final String[] newEVAL=EVALO[0];
for (final String element : newEVAL)
lazyV.addElement(element);
for(int i=evalEnd;i<tt.length;i++)
lazyV.addElement(tt[i]);
tt=CMParms.toStringArray(lazyV);
script.setElementAt(si,2,tt);
}
if((System.currentTimeMillis()-time)>=4000)
{
logError(scripted,"MPWHILE","RunTime","4 second limit exceeded: "+s);
break;
}
break;
}
case 26: // MPALARM
{
if(tt==null)
{
tt=parseBits(script,si,"Ccp");
if(tt==null)
return null;
}
final String time=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[1]);
final String parms=tt[2].trim();
if(CMath.s_int(time.trim())<=0)
{
logError(scripted,"MPALARM","Syntax","Bad time "+time);
break;
}
if(parms.length()==0)
{
logError(scripted,"MPALARM","Syntax","No command!");
break;
}
final DVector vscript=new DVector(3);
vscript.addElement("FUNCTION_PROG ALARM_"+time+Math.random(),null,null);
vscript.addElement(parms,null,null);
prequeResponse(scripted,source,target,monster,primaryItem,secondaryItem,vscript,CMath.s_int(time.trim()),msg);
break;
}
case 37: // mpenable
{
if(tt==null)
{
tt=parseBits(script,si,"Ccccp");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
String p2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[3]);
final String m2=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[4]);
Ability A=null;
if(cast!=null)
{
if(newTarget instanceof MOB)
A=((MOB)newTarget).fetchAbility(cast);
if(A==null)
A=getAbility(cast);
if(A==null)
{
final ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false);
if(D==null)
logError(scripted,"MPENABLE","Syntax","Unknown skill/expertise: "+cast);
else
if((newTarget!=null)&&(newTarget instanceof MOB))
((MOB)newTarget).addExpertise(D.ID());
}
}
if((newTarget!=null)
&&(A!=null)
&&(newTarget instanceof MOB))
{
if(!((MOB)newTarget).isMonster())
Log.sysOut("Scripting",newTarget.Name()+" was MPENABLED with "+A.Name());
if(p2.trim().startsWith("++"))
p2=""+(CMath.s_int(p2.trim().substring(2))+A.proficiency());
else
if(p2.trim().startsWith("--"))
p2=""+(A.proficiency()-CMath.s_int(p2.trim().substring(2)));
A.setProficiency(CMath.s_int(p2.trim()));
A.setMiscText(m2);
if(((MOB)newTarget).fetchAbility(A.ID())==null)
{
((MOB)newTarget).addAbility(A);
A.autoInvocation((MOB)newTarget, false);
}
}
break;
}
case 38: // mpdisable
{
if(tt==null)
{
tt=parseBits(script,si,"Ccr");
if(tt==null)
return null;
}
final Environmental newTarget=getArgumentMOB(tt[1],source,monster,target,primaryItem,secondaryItem,msg,tmp);
final String cast=varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,tt[2]);
if((newTarget!=null)&&(newTarget instanceof MOB))
{
final Ability A=((MOB)newTarget).findAbility(cast);
if(A!=null)
((MOB)newTarget).delAbility(A);
if((!((MOB)newTarget).isMonster())&&(A!=null))
Log.sysOut("Scripting",newTarget.Name()+" was MPDISABLED with "+A.Name());
final ExpertiseLibrary.ExpertiseDefinition D=CMLib.expertises().findDefinition(cast,false);
if((newTarget instanceof MOB)&&(D!=null))
((MOB)newTarget).delExpertise(D.ID());
}
break;
}
case Integer.MIN_VALUE:
logError(scripted,cmd.toUpperCase(),"Syntax","Unexpected prog start -- missing '~'?");
break;
default:
if(cmd.length()>0)
{
final Vector<String> V=CMParms.parse(varify(source,target,scripted,monster,primaryItem,secondaryItem,msg,tmp,s));
if((V.size()>0)
&&(monster!=null))
monster.doCommand(V,MUDCmdProcessor.METAFLAG_MPFORCED);
}
break;
}
}
tickStatus=Tickable.STATUS_END;
return null;
}
protected static final Vector<DVector> empty=new ReadOnlyVector<DVector>();
@Override
public String getScriptResourceKey()
{
return scriptKey;
}
public void bumpUpCache(final String key)
{
if((key != null)
&& (key.length()>0)
&& (!key.equals("*")))
{
synchronized(counterCache)
{
if(!counterCache.containsKey(key))
counterCache.put(key, new AtomicInteger(0));
counterCache.get(key).addAndGet(1);
}
}
}
public void bumpUpCache()
{
synchronized(this)
{
final Object ref=cachedRef;
if((ref != this)
&&(this.scriptKey!=null)
&&(this.scriptKey.length()>0))
{
bumpUpCache(getScriptResourceKey());
bumpUpCache(scope);
bumpUpCache(defaultQuestName);
cachedRef=this;
}
}
}
public boolean bumpDownCache(final String key)
{
if((key != null)
&& (key.length()>0)
&& (!key.equals("*")))
{
if((key != null)
&&(key.length()>0)
&&(!key.equals("*")))
{
synchronized(counterCache)
{
if(counterCache.containsKey(key))
{
if(counterCache.get(key).addAndGet(-1) <= 0)
{
counterCache.remove(key);
return true;
}
}
}
}
}
return false;
}
protected void bumpDownCache()
{
synchronized(this)
{
final Object ref=cachedRef;
if(ref == this)
{
if(bumpDownCache(getScriptResourceKey()))
{
for(final Resources R : Resources.all())
R._removeResource(getScriptResourceKey());
}
if(bumpDownCache(scope))
{
for(final Resources R : Resources.all())
R._removeResource("VARSCOPE-"+scope.toUpperCase().trim());
}
if(bumpDownCache(defaultQuestName))
{
for(final Resources R : Resources.all())
R._removeResource("VARSCOPE-"+defaultQuestName.toUpperCase().trim());
}
}
}
}
@Override
protected void finalize() throws Throwable
{
bumpDownCache();
super.finalize();
}
protected List<DVector> getScripts()
{
if(CMSecurity.isDisabled(CMSecurity.DisFlag.SCRIPTABLE)||CMSecurity.isDisabled(CMSecurity.DisFlag.SCRIPTING))
return empty;
@SuppressWarnings("unchecked")
List<DVector> scripts=(List<DVector>)Resources.getResource(getScriptResourceKey());
if(scripts==null)
{
String scr=getScript();
scr=CMStrings.replaceAll(scr,"`","'");
scripts=parseScripts(scr);
Resources.submitResource(getScriptResourceKey(),scripts);
}
return scripts;
}
protected boolean match(final String str, final String patt)
{
if(patt.trim().equalsIgnoreCase("ALL"))
return true;
if(patt.length()==0)
return true;
if(str.length()==0)
return false;
if(str.equalsIgnoreCase(patt))
return true;
return false;
}
private Item makeCheapItem(final Environmental E)
{
Item product=null;
if(E instanceof Item)
product=(Item)E;
else
{
product=CMClass.getItem("StdItem");
product.setName(E.Name());
product.setDisplayText(E.displayText());
product.setDescription(E.description());
if(E instanceof Physical)
product.setBasePhyStats((PhyStats)((Physical)E).basePhyStats().copyOf());
product.recoverPhyStats();
}
return product;
}
@Override
public boolean okMessage(final Environmental host, final CMMsg msg)
{
if((!(host instanceof PhysicalAgent))||(msg.source()==null)||(recurseCounter.get()>2))
return true;
try
{
// atomic recurse counter
recurseCounter.addAndGet(1);
final PhysicalAgent affecting = (PhysicalAgent)host;
final List<DVector> scripts=getScripts();
DVector script=null;
boolean tryIt=false;
String trigger=null;
String[] t=null;
int triggerCode=0;
String str=null;
for(int v=0;v<scripts.size();v++)
{
tryIt=false;
script=scripts.get(v);
if(script.size()<1)
continue;
trigger=((String)script.elementAt(0,1)).toUpperCase().trim();
t=(String[])script.elementAt(0,2);
triggerCode=getTriggerCode(trigger,t);
switch(triggerCode)
{
case 51: // cmdfail_prog
if(canTrigger(51)
&&(msg.targetMessage()!=null))
{
if(t==null)
t=parseBits(script,0,"CCT");
if(t!=null)
{
final String command=t[1];
final int x=msg.targetMessage().indexOf(' ');
final String userCmd=(x<0)?msg.targetMessage():msg.targetMessage().substring(0,x).trim().toUpperCase();
if(command.toUpperCase().startsWith(userCmd))
{
str=(x<0)?"":msg.targetMessage().substring(x).trim().toUpperCase();
if(str == null)
break;
if((t[2].length()==0)||(t[2].equals("ALL")))
tryIt=true;
else
if((t[2].equals("P"))&&(t.length>3))
{
if(match(str.trim(),t[3]))
tryIt=true;
}
else
for(int i=2;i<t.length;i++)
{
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=(t[i].trim()+" "+str.trim()).trim();
tryIt=true;
break;
}
}
if(tryIt)
{
final MOB monster=getMakeMOB(affecting);
if(lastKnownLocation==null)
{
lastKnownLocation=msg.source().location();
if(homeKnownLocation==null)
homeKnownLocation=lastKnownLocation;
}
if((monster==null)||(monster.amDead())||(lastKnownLocation==null))
return true;
final Item defaultItem=(affecting instanceof Item)?(Item)affecting:null;
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null)
Tool=defaultItem;
String resp=null;
if(msg.target() instanceof MOB)
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs());
else
if(msg.target() instanceof Item)
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,str,newObjs());
else
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs());
if((resp!=null)&&(resp.equalsIgnoreCase("CANCEL")))
return false;
}
}
}
}
break;
case 42: // cnclmsg_prog
if(canTrigger(42))
{
if(t==null)
t=parseBits(script,0,"CCT");
if(t!=null)
{
final String command=t[1];
boolean chk=false;
final int x=command.indexOf('=');
if(x>0)
{
chk=true;
boolean minorOnly = false;
boolean majorOnly = false;
for(int i=0;i<x;i++)
{
switch(command.charAt(i))
{
case 'S':
if(majorOnly)
chk=chk&&msg.isSourceMajor(command.substring(x+1));
else
if(minorOnly)
chk=chk&&msg.isSourceMinor(command.substring(x+1));
else
chk=chk&&msg.isSource(command.substring(x+1));
break;
case 'T':
if(majorOnly)
chk=chk&&msg.isTargetMajor(command.substring(x+1));
else
if(minorOnly)
chk=chk&&msg.isTargetMinor(command.substring(x+1));
else
chk=chk&&msg.isTarget(command.substring(x+1));
break;
case 'O':
if(majorOnly)
chk=chk&&msg.isOthersMajor(command.substring(x+1));
else
if(minorOnly)
chk=chk&&msg.isOthersMinor(command.substring(x+1));
else
chk=chk&&msg.isOthers(command.substring(x+1));
break;
case '<':
minorOnly=true;
majorOnly=false;
break;
case '>':
majorOnly=true;
minorOnly=false;
break;
case '?':
majorOnly=false;
minorOnly=false;
break;
default:
chk=false;
break;
}
}
}
else
if(command.startsWith(">"))
{
final String cmd=command.substring(1);
chk=msg.isSourceMajor(cmd)||msg.isTargetMajor(cmd)||msg.isOthersMajor(cmd);
}
else
if(command.startsWith("<"))
{
final String cmd=command.substring(1);
chk=msg.isSourceMinor(cmd)||msg.isTargetMinor(cmd)||msg.isOthersMinor(cmd);
}
else
if(command.startsWith("?"))
{
final String cmd=command.substring(1);
chk=msg.isSource(cmd)||msg.isTarget(cmd)||msg.isOthers(cmd);
}
else
chk=msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command);
if(chk)
{
str="";
if((msg.source().session()!=null)&&(msg.source().session().getPreviousCMD()!=null))
str=" "+CMParms.combine(msg.source().session().getPreviousCMD(),0).toUpperCase()+" ";
if((t[2].length()==0)||(t[2].equals("ALL")))
tryIt=true;
else
if((t[2].equals("P"))&&(t.length>3))
{
if(match(str.trim(),t[3]))
tryIt=true;
}
else
for(int i=2;i<t.length;i++)
{
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=(t[i].trim()+" "+str.trim()).trim();
tryIt=true;
break;
}
}
}
}
}
break;
}
if(tryIt)
{
final MOB monster=getMakeMOB(affecting);
if(lastKnownLocation==null)
{
lastKnownLocation=msg.source().location();
if(homeKnownLocation==null)
homeKnownLocation=lastKnownLocation;
}
if((monster==null)||(monster.amDead())||(lastKnownLocation==null))
return true;
final Item defaultItem=(affecting instanceof Item)?(Item)affecting:null;
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null)
Tool=defaultItem;
String resp=null;
if(msg.target() instanceof MOB)
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs());
else
if(msg.target() instanceof Item)
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,str,newObjs());
else
resp=execute(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,str,newObjs());
if((resp!=null)&&(resp.equalsIgnoreCase("CANCEL")))
return false;
}
}
}
finally
{
recurseCounter.addAndGet(-1);
}
return true;
}
protected String standardTriggerCheck(final DVector script, String[] t, final Environmental E,
final PhysicalAgent scripted, final MOB source, final Environmental target, final MOB monster, final Item primaryItem, final Item secondaryItem, final Object[] tmp)
{
if(E==null)
return null;
final boolean[] dollarChecks;
if(t==null)
{
t=parseBits(script,0,"CT");
dollarChecks=new boolean[t.length];
for(int i=1;i<t.length;i++)
dollarChecks[i] = t[i].indexOf('$')>=0;
script.setElementAt(0, 3, dollarChecks);
}
else
dollarChecks=(boolean[])script.elementAt(0, 3);
final String NAME=E.Name().toUpperCase();
final String ID=E.ID().toUpperCase();
if((t[1].length()==0)
||(t[1].equals("ALL"))
||(t[1].equals("P")
&&(t.length==3)
&&((t[2].equalsIgnoreCase(NAME))
||(t[2].equalsIgnoreCase("ALL")))))
return t[1];
for(int i=1;i<t.length;i++)
{
final String word;
if (dollarChecks[i])
word=this.varify(source, target, scripted, monster, primaryItem, secondaryItem, NAME, tmp, t[i]);
else
word=t[i];
if(word.equals("P") && (i < t.length-1))
{
final String arg;
if (dollarChecks[i+1])
arg=this.varify(source, target, scripted, monster, primaryItem, secondaryItem, NAME, tmp, t[i+1]);
else
arg=t[i+1];
if( arg.equalsIgnoreCase(NAME)
|| arg.equalsIgnoreCase(ID)
|| arg.equalsIgnoreCase("ALL"))
return word;
i++;
}
else
if(((" "+NAME+" ").indexOf(" "+word+" ")>=0)
||(ID.equalsIgnoreCase(word))
||(word.equalsIgnoreCase("ALL")))
return word;
}
return null;
}
@Override
public void executeMsg(final Environmental host, final CMMsg msg)
{
if((!(host instanceof PhysicalAgent))||(msg.source()==null)||(recurseCounter.get() > 2))
return;
try
{
// atomic recurse counter
recurseCounter.addAndGet(1);
final PhysicalAgent affecting = (PhysicalAgent)host;
final MOB monster=getMakeMOB(affecting);
if(lastKnownLocation==null)
{
lastKnownLocation=msg.source().location();
if(homeKnownLocation==null)
homeKnownLocation=lastKnownLocation;
}
if((monster==null)||(monster.amDead())||(lastKnownLocation==null))
return;
final Item defaultItem=(affecting instanceof Item)?(Item)affecting:null;
MOB eventMob=monster;
if((defaultItem!=null)&&(defaultItem.owner() instanceof MOB))
eventMob=(MOB)defaultItem.owner();
final List<DVector> scripts=getScripts();
if(msg.amITarget(eventMob)
&&(!msg.amISource(monster))
&&(msg.targetMinor()==CMMsg.TYP_DAMAGE)
&&(msg.source()!=monster))
lastToHurtMe=msg.source();
DVector script=null;
String trigger=null;
String[] t=null;
for(int v=0;v<scripts.size();v++)
{
script=scripts.get(v);
if(script.size()<1)
continue;
trigger=((String)script.elementAt(0,1)).toUpperCase().trim();
t=(String[])script.elementAt(0,2);
final int triggerCode=getTriggerCode(trigger,t);
int targetMinorTrigger=-1;
switch(triggerCode)
{
case 1: // greet_prog
if((msg.targetMinor()==CMMsg.TYP_ENTER)
&&(msg.amITarget(lastKnownLocation))
&&(!msg.amISource(eventMob))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))
&&canTrigger(1)
&&((!(affecting instanceof MOB))||CMLib.flags().canSenseEnteringLeaving(msg.source(),(MOB)affecting)))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t);
return;
}
}
}
break;
case 45: // arrive_prog
if(((msg.targetMinor()==CMMsg.TYP_ENTER)||(msg.sourceMinor()==CMMsg.TYP_LIFE))
&&(msg.amISource(eventMob))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))
&&canTrigger(45))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
if((host instanceof Item)
&&(((Item)host).owner() instanceof MOB)
&&(msg.source()==((Item)host).owner()))
{
// this is to prevent excessive queing when a player is running full throttle with a scripted item
// that pays attention to where it is.
for(int i=que.size()-1;i>=0;i--)
{
try
{
if(que.get(i).scr == script)
que.remove(i);
}
catch(final Exception e)
{
}
}
}
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t);
return;
}
}
}
break;
case 2: // all_greet_prog
if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(2)
&&(msg.amITarget(lastKnownLocation))
&&(!msg.amISource(eventMob))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))
&&((!(affecting instanceof MOB)) ||CMLib.flags().canActAtAll(monster)))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t);
return;
}
}
}
break;
case 47: // speak_prog
if(((msg.sourceMinor()==CMMsg.TYP_SPEAK)||(msg.targetMinor()==CMMsg.TYP_SPEAK))&&canTrigger(47)
&&(msg.amISource(monster)||(!(affecting instanceof MOB)))
&&(!msg.othersMajor(CMMsg.MASK_CHANNEL))
&&((msg.sourceMessage()!=null)
||((msg.target()==monster)&&(msg.targetMessage()!=null)&&(msg.tool()==null)))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
if(t==null)
{
t=parseBits(script,0,"CT");
for(int i=0;i<t.length;i++)
{
if(t[i]!=null)
t[i]=t[i].replace('`', '\'');
}
}
String str=null;
if(msg.sourceMessage() != null)
str=CMStrings.getSayFromMessage(msg.sourceMessage().toUpperCase());
else
if(msg.targetMessage() != null)
str=CMStrings.getSayFromMessage(msg.targetMessage().toUpperCase());
else
if(msg.othersMessage() != null)
str=CMStrings.getSayFromMessage(msg.othersMessage().toUpperCase());
if(str != null)
{
str=(" "+str.replace('`', '\'')+" ").toUpperCase();
str=CMStrings.removeColors(str);
str=CMStrings.replaceAll(str,"\n\r"," ");
if((t[1].length()==0)||(t[1].equals("ALL")))
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t);
return;
}
else
if((t[1].equals("P"))&&(t.length>2))
{
if(match(str.trim(),t[2]))
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t);
return;
}
}
else
for(int i=1;i<t.length;i++)
{
final int x=str.indexOf(" "+t[i]+" ");
if(x>=0)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str.substring(x).trim(), t);
return;
}
}
}
}
break;
case 3: // speech_prog
if(((msg.sourceMinor()==CMMsg.TYP_SPEAK)||(msg.targetMinor()==CMMsg.TYP_SPEAK))&&canTrigger(3)
&&(!msg.amISource(monster))
&&(!msg.othersMajor(CMMsg.MASK_CHANNEL))
&&(((msg.othersMessage()!=null)&&((msg.tool()==null)||(!(msg.tool() instanceof Ability))||((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)!=Ability.ACODE_LANGUAGE)))
||((msg.target()==monster)&&(msg.targetMessage()!=null)&&(msg.tool()==null)))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
if(t==null)
{
t=parseBits(script,0,"CT");
for(int i=0;i<t.length;i++)
{
if(t[i]!=null)
t[i]=t[i].replace('`', '\'');
}
}
String str=null;
if(msg.othersMessage() != null)
str=CMStrings.getSayFromMessage(msg.othersMessage().toUpperCase());
else
if(msg.targetMessage() != null)
str=CMStrings.getSayFromMessage(msg.targetMessage().toUpperCase());
if(str != null)
{
str=(" "+str.replace('`', '\'')+" ").toUpperCase();
str=CMStrings.removeColors(str);
str=CMStrings.replaceAll(str,"\n\r"," ");
if((t[1].length()==0)||(t[1].equals("ALL")))
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t);
return;
}
else
if((t[1].equals("P"))&&(t.length>2))
{
if(match(str.trim(),t[2]))
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str, t);
return;
}
}
else
for(int i=1;i<t.length;i++)
{
final int x=str.indexOf(" "+t[i]+" ");
if(x>=0)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,str.substring(x).trim(), t);
return;
}
}
}
}
break;
case 4: // give_prog
if((msg.targetMinor()==CMMsg.TYP_GIVE)
&&canTrigger(4)
&&((msg.amITarget(monster))
||(msg.tool()==affecting)
||(affecting instanceof Room)
||(affecting instanceof Area))
&&(!msg.amISource(monster))
&&(msg.tool() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.tool(), affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,check, t);
return;
}
}
break;
case 48: // giving_prog
if((msg.targetMinor()==CMMsg.TYP_GIVE)
&&canTrigger(48)
&&((msg.amISource(monster))
||(msg.tool()==affecting)
||(affecting instanceof Room)
||(affecting instanceof Area))
&&(msg.tool() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),msg.target(),monster,(Item)msg.tool(),defaultItem,t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.tool(),defaultItem,script,1,check, t);
return;
}
}
break;
case 49: // cast_prog
if((msg.tool() instanceof Ability)
&&canTrigger(49)
&&((msg.amITarget(monster))
||(affecting instanceof Room)
||(affecting instanceof Area))
&&(!msg.amISource(monster))
&&(msg.sourceMinor()!=CMMsg.TYP_TEACH)
&&(msg.sourceMinor()!=CMMsg.TYP_ITEMSGENERATED)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.tool(), affecting,msg.source(),monster,monster,defaultItem,null,t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,check, t);
return;
}
}
break;
case 50: // casting_prog
if((msg.tool() instanceof Ability)
&&canTrigger(50)
&&((msg.amISource(monster))
||(affecting instanceof Room)
||(affecting instanceof Area))
&&(msg.sourceMinor()!=CMMsg.TYP_TEACH)
&&(msg.sourceMinor()!=CMMsg.TYP_ITEMSGENERATED)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),msg.target(),monster,null,defaultItem,t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,check, t);
return;
}
}
break;
case 40: // llook_prog
if((msg.targetMinor()==CMMsg.TYP_EXAMINE)&&canTrigger(40)
&&(!msg.amISource(monster))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,defaultItem,null,t);
if(check!=null)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,null,script,1,check, t);
return;
}
}
break;
case 41: // execmsg_prog
if(canTrigger(41))
{
if(t==null)
t=parseBits(script,0,"CCT");
if(t!=null)
{
final String command=t[1];
boolean chk=false;
final int x=command.indexOf('=');
if(x>0)
{
chk=true;
boolean minorOnly = false;
boolean majorOnly = false;
for(int i=0;i<x;i++)
{
switch(command.charAt(i))
{
case 'S':
if(majorOnly)
chk=chk&&msg.isSourceMajor(command.substring(x+1));
else
if(minorOnly)
chk=chk&&msg.isSourceMinor(command.substring(x+1));
else
chk=chk&&msg.isSource(command.substring(x+1));
break;
case 'T':
if(majorOnly)
chk=chk&&msg.isTargetMajor(command.substring(x+1));
else
if(minorOnly)
chk=chk&&msg.isTargetMinor(command.substring(x+1));
else
chk=chk&&msg.isTarget(command.substring(x+1));
break;
case 'O':
if(majorOnly)
chk=chk&&msg.isOthersMajor(command.substring(x+1));
else
if(minorOnly)
chk=chk&&msg.isOthersMinor(command.substring(x+1));
else
chk=chk&&msg.isOthers(command.substring(x+1));
break;
case '<':
minorOnly=true;
majorOnly=false;
break;
case '>':
majorOnly=true;
minorOnly=false;
break;
case '?':
majorOnly=false;
minorOnly=false;
break;
default:
chk=false;
break;
}
}
}
else
if(command.startsWith(">"))
{
final String cmd=command.substring(1);
chk=msg.isSourceMajor(cmd)||msg.isTargetMajor(cmd)||msg.isOthersMajor(cmd);
}
else
if(command.startsWith("<"))
{
final String cmd=command.substring(1);
chk=msg.isSourceMinor(cmd)||msg.isTargetMinor(cmd)||msg.isOthersMinor(cmd);
}
else
if(command.startsWith("?"))
{
final String cmd=command.substring(1);
chk=msg.isSource(cmd)||msg.isTarget(cmd)||msg.isOthers(cmd);
}
else
chk=msg.isSource(command)||msg.isTarget(command)||msg.isOthers(command);
if(chk)
{
String str="";
if((msg.source().session()!=null)&&(msg.source().session().getPreviousCMD()!=null))
str=" "+CMParms.combine(msg.source().session().getPreviousCMD(),0).toUpperCase()+" ";
boolean doIt=false;
if((t[2].length()==0)||(t[2].equals("ALL")))
doIt=true;
else
if((t[2].equals("P"))&&(t.length>3))
{
if(match(str.trim(),t[3]))
doIt=true;
}
else
for(int i=2;i<t.length;i++)
{
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=(t[i].trim()+" "+str.trim()).trim();
doIt=true;
break;
}
}
if(doIt)
{
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null)
Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
return;
}
}
}
}
break;
case 39: // look_prog
if((msg.targetMinor()==CMMsg.TYP_LOOK)&&canTrigger(39)
&&(!msg.amISource(monster))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,defaultItem,defaultItem,t);
if(check!=null)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,defaultItem,defaultItem,script,1,check, t);
return;
}
}
break;
case 20: // get_prog
if((msg.targetMinor()==CMMsg.TYP_GET)&&canTrigger(20)
&&(msg.amITarget(affecting)
||(affecting instanceof Room)
||(affecting instanceof Area)
||(affecting instanceof MOB))
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
Item checkInE=(Item)msg.target();
if((msg.tool() instanceof Item)
&&(((Item)msg.tool()).container()==msg.target()))
checkInE=(Item)msg.tool();
final String check=standardTriggerCheck(script,t,checkInE,affecting,msg.source(),msg.target(),monster,checkInE,defaultItem,t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
enqueResponse(affecting,msg.source(),msg.target(),monster,checkInE,defaultItem,script,1,check, t);
return;
}
}
break;
case 22: // drop_prog
if((msg.targetMinor()==CMMsg.TYP_DROP)&&canTrigger(22)
&&((msg.amITarget(affecting))
||(affecting instanceof Room)
||(affecting instanceof Area)
||(affecting instanceof MOB))
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
if(msg.target() instanceof Coins)
execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check, t);
return;
}
}
break;
case 24: // remove_prog
if((msg.targetMinor()==CMMsg.TYP_REMOVE)&&canTrigger(24)
&&((msg.amITarget(affecting))
||(affecting instanceof Room)
||(affecting instanceof Area)
||(affecting instanceof MOB))
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,t);
if(check!=null)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check, t);
return;
}
}
break;
case 34: // open_prog
if(targetMinorTrigger<0)
targetMinorTrigger=CMMsg.TYP_OPEN;
//$FALL-THROUGH$
case 35: // close_prog
if(targetMinorTrigger<0)
targetMinorTrigger=CMMsg.TYP_CLOSE;
//$FALL-THROUGH$
case 36: // lock_prog
if(targetMinorTrigger<0)
targetMinorTrigger=CMMsg.TYP_LOCK;
//$FALL-THROUGH$
case 37: // unlock_prog
{
if(targetMinorTrigger<0)
targetMinorTrigger=CMMsg.TYP_UNLOCK;
if((msg.targetMinor()==targetMinorTrigger)&&canTrigger(triggerCode)
&&((msg.amITarget(affecting))
||(affecting instanceof Room)
||(affecting instanceof Area)
||(affecting instanceof MOB))
&&(!msg.amISource(monster))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final Item I=(msg.target() instanceof Item)?(Item)msg.target():defaultItem;
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,I,defaultItem,t);
if(check!=null)
{
enqueResponse(affecting,msg.source(),msg.target(),monster,I,defaultItem,script,1,check, t);
return;
}
}
break;
}
case 25: // consume_prog
if(((msg.targetMinor()==CMMsg.TYP_EAT)||(msg.targetMinor()==CMMsg.TYP_DRINK))
&&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB))
&&(!msg.amISource(monster))&&canTrigger(25)
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,t);
if(check!=null)
{
if((msg.target() == affecting)
&&(affecting instanceof Food))
execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),defaultItem,script,1,check, t);
return;
}
}
break;
case 21: // put_prog
if((msg.targetMinor()==CMMsg.TYP_PUT)&&canTrigger(21)
&&((msg.amITarget(affecting))
||(affecting instanceof Room)
||(affecting instanceof Area)
||(affecting instanceof MOB))
&&(msg.tool() instanceof Item)
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room))
execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),script,1,check, t);
return;
}
}
break;
case 46: // putting_prog
if((msg.targetMinor()==CMMsg.TYP_PUT)&&canTrigger(46)
&&((msg.tool()==affecting)
||(affecting instanceof Room)
||(affecting instanceof Area)
||(affecting instanceof MOB))
&&(msg.tool() instanceof Item)
&&(!msg.amISource(monster))
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),t);
if(check!=null)
{
if(lastMsg==msg)
break;
lastMsg=msg;
if((msg.tool() instanceof Coins)&&(((Item)msg.target()).owner() instanceof Room))
execute(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)((Item)msg.target()).copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),msg.target(),monster,(Item)msg.target(),(Item)msg.tool(),script,1,check, t);
return;
}
}
break;
case 27: // buy_prog
if((msg.targetMinor()==CMMsg.TYP_BUY)&&canTrigger(27)
&&((!(affecting instanceof ShopKeeper))
||msg.amITarget(affecting))
&&(!msg.amISource(monster))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final Item chItem = (msg.tool() instanceof Item)?((Item)msg.tool()):null;
final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),monster,monster,chItem,chItem,t);
if(check!=null)
{
final Item product=makeCheapItem(msg.tool());
if((product instanceof Coins)
&&(product.owner() instanceof Room))
execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,check,newObjs());
else
enqueResponse(affecting,msg.source(),monster,monster,product,product,script,1,check, t);
return;
}
}
break;
case 28: // sell_prog
if((msg.targetMinor()==CMMsg.TYP_SELL)&&canTrigger(28)
&&((msg.amITarget(affecting))||(!(affecting instanceof ShopKeeper)))
&&(!msg.amISource(monster))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final Item chItem = (msg.tool() instanceof Item)?((Item)msg.tool()):null;
final String check=standardTriggerCheck(script,t,msg.tool(),affecting,msg.source(),monster,monster,chItem,chItem,t);
if(check!=null)
{
final Item product=makeCheapItem(msg.tool());
if((product instanceof Coins)
&&(product.owner() instanceof Room))
execute(affecting,msg.source(),monster,monster,product,(Item)product.copyOf(),script,null,newObjs());
else
enqueResponse(affecting,msg.source(),monster,monster,product,product,script,1,check, t);
return;
}
}
break;
case 23: // wear_prog
if(((msg.targetMinor()==CMMsg.TYP_WEAR)
||(msg.targetMinor()==CMMsg.TYP_HOLD)
||(msg.targetMinor()==CMMsg.TYP_WIELD))
&&((msg.amITarget(affecting))||(affecting instanceof Room)||(affecting instanceof Area)||(affecting instanceof MOB))
&&(!msg.amISource(monster))&&canTrigger(23)
&&(msg.target() instanceof Item)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
final String check=standardTriggerCheck(script,t,msg.target(),affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,t);
if(check!=null)
{
enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.target(),defaultItem,script,1,check, t);
return;
}
}
break;
case 19: // bribe_prog
if((msg.targetMinor()==CMMsg.TYP_GIVE)
&&(msg.amITarget(eventMob)||(!(affecting instanceof MOB)))
&&(!msg.amISource(monster))&&canTrigger(19)
&&(msg.tool() instanceof Coins)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
if(t[1].startsWith("ANY")||t[1].startsWith("ALL"))
t[1]=t[1].trim();
else
if(!((Coins)msg.tool()).getCurrency().equals(CMLib.beanCounter().getCurrency(monster)))
break;
double d=0.0;
if(CMath.isDouble(t[1]))
d=CMath.s_double(t[1]);
else
d=CMath.s_int(t[1]);
if((((Coins)msg.tool()).getTotalValue()>=d)
||(t[1].equals("ALL"))
||(t[1].equals("ANY")))
{
enqueResponse(affecting,msg.source(),monster,monster,(Item)msg.tool(),defaultItem,script,1,null, t);
return;
}
}
}
break;
case 8: // entry_prog
if((msg.targetMinor()==CMMsg.TYP_ENTER)&&canTrigger(8)
&&(msg.amISource(eventMob)
||(msg.target()==affecting)
||(msg.tool()==affecting)
||(affecting instanceof Item))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
final List<ScriptableResponse> V=new XVector<ScriptableResponse>(que);
ScriptableResponse SB=null;
String roomID=null;
if(msg.target()!=null)
roomID=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(msg.target()));
for(int q=0;q<V.size();q++)
{
SB=V.get(q);
if((SB.scr==script)&&(SB.s==msg.source()))
{
if(que.remove(SB))
execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs());
break;
}
}
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,roomID, t);
return;
}
}
}
break;
case 9: // exit_prog
if((msg.targetMinor()==CMMsg.TYP_LEAVE)&&canTrigger(9)
&&(msg.amITarget(lastKnownLocation))
&&(!msg.amISource(eventMob))
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster)))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
final List<ScriptableResponse> V=new XVector<ScriptableResponse>(que);
ScriptableResponse SB=null;
String roomID=null;
if(msg.target()!=null)
roomID=CMLib.map().getExtendedRoomID(CMLib.map().roomLocation(msg.target()));
for(int q=0;q<V.size();q++)
{
SB=V.get(q);
if((SB.scr==script)&&(SB.s==msg.source()))
{
if(que.remove(SB))
execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs());
break;
}
}
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,roomID, t);
return;
}
}
}
break;
case 10: // death_prog
if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(10)
&&(msg.amISource(eventMob)||(!(affecting instanceof MOB))))
{
if(t==null)
t=parseBits(script,0,"C");
final MOB ded=msg.source();
MOB src=lastToHurtMe;
if(msg.tool() instanceof MOB)
src=(MOB)msg.tool();
if((src==null)||(src.location()!=monster.location()))
src=ded;
execute(affecting,src,ded,ded,defaultItem,null,script,null,newObjs());
return;
}
break;
case 44: // kill_prog
if((msg.sourceMinor()==CMMsg.TYP_DEATH)&&canTrigger(44)
&&((msg.tool()==affecting)||(!(affecting instanceof MOB))))
{
if(t==null)
t=parseBits(script,0,"C");
final MOB ded=msg.source();
MOB src=lastToHurtMe;
if(msg.tool() instanceof MOB)
src=(MOB)msg.tool();
if((src==null)||(src.location()!=monster.location()))
src=ded;
execute(affecting,src,ded,ded,defaultItem,null,script,null,newObjs());
return;
}
break;
case 26: // damage_prog
if((msg.targetMinor()==CMMsg.TYP_DAMAGE)&&canTrigger(26)
&&(msg.amITarget(eventMob)||(msg.tool()==affecting)))
{
if(t==null)
t=parseBits(script,0,"C");
Item I=null;
if(msg.tool() instanceof Item)
I=(Item)msg.tool();
execute(affecting,msg.source(),msg.target(),eventMob,defaultItem,I,script,""+msg.value(),newObjs());
return;
}
break;
case 29: // login_prog
if(!registeredEvents.contains(Integer.valueOf(CMMsg.TYP_LOGIN)))
{
CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LOGIN);
registeredEvents.add(Integer.valueOf(CMMsg.TYP_LOGIN));
}
if((msg.sourceMinor()==CMMsg.TYP_LOGIN)&&canTrigger(29)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))
&&(!CMLib.flags().isCloaked(msg.source())))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t);
return;
}
}
}
break;
case 32: // level_prog
if(!registeredEvents.contains(Integer.valueOf(CMMsg.TYP_LEVEL)))
{
CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_LEVEL);
registeredEvents.add(Integer.valueOf(CMMsg.TYP_LEVEL));
}
if((msg.sourceMinor()==CMMsg.TYP_LEVEL)&&canTrigger(32)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))
&&(msg.value() > msg.source().basePhyStats().level())
&&(!CMLib.flags().isCloaked(msg.source())))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
execute(affecting,msg.source(),monster,monster,defaultItem,null,script,null,t);
return;
}
}
}
break;
case 30: // logoff_prog
if((msg.sourceMinor()==CMMsg.TYP_QUIT)&&canTrigger(30)
&&((!(affecting instanceof MOB)) || isFreeToBeTriggered(monster))
&&((!CMLib.flags().isCloaked(msg.source()))||(!CMSecurity.isASysOp(msg.source()))))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
enqueResponse(affecting,msg.source(),monster,monster,defaultItem,null,script,1,null, t);
return;
}
}
}
break;
case 12: // mask_prog
{
if(!canTrigger(12))
break;
}
//$FALL-THROUGH$
case 18: // act_prog
if((msg.amISource(monster))
||((triggerCode==18)&&(!canTrigger(18))))
break;
//$FALL-THROUGH$
case 43: // imask_prog
if((triggerCode!=43)||(msg.amISource(monster)&&canTrigger(43)))
{
if(t==null)
{
t=parseBits(script,0,"CT");
for(int i=1;i<t.length;i++)
t[i]=CMLib.english().stripPunctuation(CMStrings.removeColors(t[i]));
}
boolean doIt=false;
String str=msg.othersMessage();
if(str==null)
str=msg.targetMessage();
if(str==null)
str=msg.sourceMessage();
if(str==null)
break;
str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false);
str=CMLib.english().stripPunctuation(CMStrings.removeColors(str));
str=" "+CMStrings.replaceAll(str,"\n\r"," ").toUpperCase().trim()+" ";
if((t[1].length()==0)||(t[1].equals("ALL")))
doIt=true;
else
if((t[1].equals("P"))&&(t.length>2))
{
if(match(str.trim(),t[2]))
doIt=true;
}
else
for(int i=1;i<t.length;i++)
{
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=t[i];
doIt=true;
break;
}
}
if(doIt)
{
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null)
Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
return;
}
}
break;
case 38: // social_prog
if(!msg.amISource(monster)
&&canTrigger(38)
&&(msg.tool() instanceof Social))
{
if(t==null)
t=parseBits(script,0,"CR");
if((t!=null)
&&((Social)msg.tool()).Name().toUpperCase().startsWith(t[1]))
{
final Item Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,msg.tool().Name(), t);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,msg.tool().Name(), t);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,msg.tool().Name(), t);
return;
}
}
break;
case 33: // channel_prog
if(!registeredEvents.contains(Integer.valueOf(CMMsg.TYP_CHANNEL)))
{
CMLib.map().addGlobalHandler(affecting,CMMsg.TYP_CHANNEL);
registeredEvents.add(Integer.valueOf(CMMsg.TYP_CHANNEL));
}
if(!msg.amISource(monster)
&&(msg.othersMajor(CMMsg.MASK_CHANNEL))
&&canTrigger(33))
{
if(t==null)
t=parseBits(script,0,"CCT");
boolean doIt=false;
if(t!=null)
{
final String channel=t[1];
final int channelInt=msg.othersMinor()-CMMsg.TYP_CHANNEL;
String str=null;
final CMChannel officialChannel=CMLib.channels().getChannel(channelInt);
if(officialChannel==null)
Log.errOut("Script","Unknown channel for code '"+channelInt+"': "+msg.othersMessage());
else
if(channel.equalsIgnoreCase(officialChannel.name()))
{
str=msg.sourceMessage();
if(str==null)
str=msg.othersMessage();
if(str==null)
str=msg.targetMessage();
if(str==null)
break;
str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false).toUpperCase().trim();
int dex=str.indexOf("["+channel+"]");
if(dex>0)
str=str.substring(dex+2+channel.length()).trim();
else
{
dex=str.indexOf('\'');
final int edex=str.lastIndexOf('\'');
if(edex>dex)
str=str.substring(dex+1,edex);
}
str=" "+CMStrings.removeColors(str)+" ";
str=CMStrings.replaceAll(str,"\n\r"," ");
if((t[2].length()==0)||(t[2].equals("ALL")))
doIt=true;
else
if(t[2].equals("P")&&(t.length>2))
{
if(match(str.trim(),t[3]))
doIt=true;
}
else
for(int i=2;i<t.length;i++)
{
if(str.indexOf(" "+t[i]+" ")>=0)
{
str=t[i];
doIt=true;
break;
}
}
}
if(doIt)
{
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null)
Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
return;
}
}
}
break;
case 31: // regmask_prog
if(!msg.amISource(monster)&&canTrigger(31))
{
boolean doIt=false;
String str=msg.othersMessage();
if(str==null)
str=msg.targetMessage();
if(str==null)
str=msg.sourceMessage();
if(str==null)
break;
str=CMLib.coffeeFilter().fullOutFilter(null,monster,msg.source(),msg.target(),msg.tool(),str,false);
if(t==null)
t=parseBits(script,0,"Cp");
if(t!=null)
{
if(CMParms.getCleanBit(t[1],0).equalsIgnoreCase("p"))
doIt=str.trim().equals(t[1].substring(1).trim());
else
{
Pattern P=patterns.get(t[1]);
if(P==null)
{
P=Pattern.compile(t[1], Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
patterns.put(t[1],P);
}
final Matcher M=P.matcher(str);
doIt=M.find();
if(doIt)
str=str.substring(M.start()).trim();
}
}
if(doIt)
{
Item Tool=null;
if(msg.tool() instanceof Item)
Tool=(Item)msg.tool();
if(Tool==null)
Tool=defaultItem;
if(msg.target() instanceof MOB)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
else
if(msg.target() instanceof Item)
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,(Item)msg.target(),script,1,str, t);
else
enqueResponse(affecting,msg.source(),msg.target(),monster,Tool,defaultItem,script,1,str, t);
return;
}
}
break;
}
}
}
finally
{
recurseCounter.addAndGet(-1);
}
}
protected int getTriggerCode(final String trigger, final String[] ttrigger)
{
final Integer I;
if((ttrigger!=null)&&(ttrigger.length>0))
I=progH.get(ttrigger[0]);
else
{
final int x=trigger.indexOf(' ');
if(x<0)
I=progH.get(trigger.toUpperCase().trim());
else
I=progH.get(trigger.substring(0,x).toUpperCase().trim());
}
if(I==null)
return 0;
return I.intValue();
}
@Override
public MOB getMakeMOB(final Tickable ticking)
{
MOB mob=null;
if(ticking instanceof MOB)
{
mob=(MOB)ticking;
if(!mob.amDead())
lastKnownLocation=mob.location();
}
else
if(ticking instanceof Environmental)
{
final Room R=CMLib.map().roomLocation((Environmental)ticking);
if(R!=null)
lastKnownLocation=R;
if((backupMOB==null)
||(backupMOB.amDestroyed())
||(backupMOB.amDead()))
{
backupMOB=CMClass.getMOB("StdMOB");
if(backupMOB!=null)
{
backupMOB.setName(ticking.name());
backupMOB.setDisplayText(L("@x1 is here.",ticking.name()));
backupMOB.setDescription("");
backupMOB.setAgeMinutes(-1);
mob=backupMOB;
if(backupMOB.location()!=lastKnownLocation)
backupMOB.setLocation(lastKnownLocation);
}
}
else
{
backupMOB.setAgeMinutes(-1);
mob=backupMOB;
if(backupMOB.location()!=lastKnownLocation)
{
backupMOB.setLocation(lastKnownLocation);
backupMOB.setName(ticking.name());
backupMOB.setDisplayText(L("@x1 is here.",ticking.name()));
}
}
}
return mob;
}
protected boolean canTrigger(final int triggerCode)
{
final Long L=noTrigger.get(Integer.valueOf(triggerCode));
if(L==null)
return true;
if(System.currentTimeMillis()<L.longValue())
return false;
noTrigger.remove(Integer.valueOf(triggerCode));
return true;
}
@Override
public boolean tick(final Tickable ticking, final int tickID)
{
final Item defaultItem=(ticking instanceof Item)?(Item)ticking:null;
final MOB mob;
synchronized(this) // supposedly this will cause a sync between cpus of the object
{
mob=getMakeMOB(ticking);
}
if((mob==null)||(lastKnownLocation==null))
{
altStatusTickable=null;
return true;
}
final PhysicalAgent affecting=(ticking instanceof PhysicalAgent)?((PhysicalAgent)ticking):null;
final List<DVector> scripts=getScripts();
if(!runInPassiveAreas)
{
final Area A=CMLib.map().areaLocation(ticking);
if((A!=null)&&(A.getAreaState() != Area.State.ACTIVE))
{
return true;
}
}
if(defaultItem != null)
{
final ItemPossessor poss=defaultItem.owner();
if(poss instanceof MOB)
{
final Room R=((MOB)poss).location();
if((R==null)||(R.numInhabitants()==0))
{
altStatusTickable=null;
return true;
}
}
}
int triggerCode=-1;
String trigger="";
String[] t=null;
for(int thisScriptIndex=0;thisScriptIndex<scripts.size();thisScriptIndex++)
{
final DVector script=scripts.get(thisScriptIndex);
if(script.size()<2)
continue;
trigger=((String)script.elementAt(0,1)).toUpperCase().trim();
t=(String[])script.elementAt(0,2);
triggerCode=getTriggerCode(trigger,t);
tickStatus=Tickable.STATUS_SCRIPT+triggerCode;
switch(triggerCode)
{
case 5: // rand_Prog
if((!mob.amDead())&&canTrigger(5))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
}
}
break;
case 16: // delay_prog
if((!mob.amDead())&&canTrigger(16))
{
int targetTick=-1;
final Integer thisScriptIndexI=Integer.valueOf(thisScriptIndex);
final int[] delayProgCounter;
synchronized(thisScriptIndexI)
{
if(delayTargetTimes.containsKey(thisScriptIndexI))
targetTick=delayTargetTimes.get(thisScriptIndexI).intValue();
else
{
if(t==null)
t=parseBits(script,0,"CCR");
if(t!=null)
{
final int low=CMath.s_int(t[1]);
int high=CMath.s_int(t[2]);
if(high<low)
high=low;
targetTick=CMLib.dice().roll(1,high-low+1,low-1);
delayTargetTimes.put(thisScriptIndexI,Integer.valueOf(targetTick));
}
}
if(delayProgCounters.containsKey(thisScriptIndexI))
delayProgCounter=delayProgCounters.get(thisScriptIndexI);
else
{
delayProgCounter=new int[]{0};
delayProgCounters.put(thisScriptIndexI,delayProgCounter);
}
}
boolean exec=false;
synchronized(delayProgCounter)
{
if(delayProgCounter[0]>=targetTick)
{
exec=true;
delayProgCounter[0]=0;
}
else
delayProgCounter[0]++;
}
if(exec)
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
}
break;
case 7: // fight_Prog
if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(7))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,newObjs());
}
}
else
if((ticking instanceof Item)
&&canTrigger(7)
&&(((Item)ticking).owner() instanceof MOB)
&&(((MOB)((Item)ticking).owner()).isInCombat()))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
if(CMLib.dice().rollPercentage()<prcnt)
{
final MOB M=(MOB)((Item)ticking).owner();
if(!M.amDead())
execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,newObjs());
}
}
}
break;
case 11: // hitprcnt_prog
if((mob.isInCombat())&&(!mob.amDead())&&canTrigger(11))
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
final int floor=(int)Math.round(CMath.mul(CMath.div(prcnt,100.0),mob.maxState().getHitPoints()));
if(mob.curState().getHitPoints()<=floor)
execute(affecting,mob.getVictim(),mob,mob,defaultItem,null,script,null,newObjs());
}
}
else
if((ticking instanceof Item)
&&canTrigger(11)
&&(((Item)ticking).owner() instanceof MOB)
&&(((MOB)((Item)ticking).owner()).isInCombat()))
{
final MOB M=(MOB)((Item)ticking).owner();
if(!M.amDead())
{
if(t==null)
t=parseBits(script,0,"CR");
if(t!=null)
{
final int prcnt=CMath.s_int(t[1]);
final int floor=(int)Math.round(CMath.mul(CMath.div(prcnt,100.0),M.maxState().getHitPoints()));
if(M.curState().getHitPoints()<=floor)
execute(affecting,M,mob.getVictim(),mob,defaultItem,null,script,null,newObjs());
}
}
}
break;
case 6: // once_prog
if(!oncesDone.contains(script)&&canTrigger(6))
{
if(t==null)
t=parseBits(script,0,"C");
oncesDone.add(script);
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
}
break;
case 14: // time_prog
if((mob.location()!=null)
&&canTrigger(14)
&&(!mob.amDead()))
{
if(t==null)
t=parseBits(script,0,"CT");
int lastTimeProgDone=-1;
if(lastTimeProgsDone.containsKey(Integer.valueOf(thisScriptIndex)))
lastTimeProgDone=lastTimeProgsDone.get(Integer.valueOf(thisScriptIndex)).intValue();
final int time=mob.location().getArea().getTimeObj().getHourOfDay();
if((t!=null)&&(lastTimeProgDone!=time))
{
boolean done=false;
for(int i=1;i<t.length;i++)
{
if(time==CMath.s_int(t[i]))
{
done=true;
execute(affecting,mob,mob,mob,defaultItem,null,script,""+time,newObjs());
lastTimeProgsDone.remove(Integer.valueOf(thisScriptIndex));
lastTimeProgsDone.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(time));
break;
}
}
if(!done)
lastTimeProgsDone.remove(Integer.valueOf(thisScriptIndex));
}
}
break;
case 15: // day_prog
if((mob.location()!=null)&&canTrigger(15)
&&(!mob.amDead()))
{
if(t==null)
t=parseBits(script,0,"CT");
int lastDayProgDone=-1;
if(lastDayProgsDone.containsKey(Integer.valueOf(thisScriptIndex)))
lastDayProgDone=lastDayProgsDone.get(Integer.valueOf(thisScriptIndex)).intValue();
final int day=mob.location().getArea().getTimeObj().getDayOfMonth();
if((t!=null)&&(lastDayProgDone!=day))
{
boolean done=false;
for(int i=1;i<t.length;i++)
{
if(day==CMath.s_int(t[i]))
{
done=true;
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
lastDayProgsDone.remove(Integer.valueOf(thisScriptIndex));
lastDayProgsDone.put(Integer.valueOf(thisScriptIndex),Integer.valueOf(day));
break;
}
}
if(!done)
lastDayProgsDone.remove(Integer.valueOf(thisScriptIndex));
}
}
break;
case 13: // quest_time_prog
if(!oncesDone.contains(script)&&canTrigger(13))
{
if(t==null)
t=parseBits(script,0,"CCC");
if(t!=null)
{
final Quest Q=getQuest(t[1]);
if((Q!=null)
&&(Q.running())
&&(!Q.stopping())
&&(Q.duration()!=0))
{
final int time=CMath.s_int(t[2]);
if(time>=Q.minsRemaining())
{
oncesDone.add(script);
execute(affecting,mob,mob,mob,defaultItem,null,script,null,newObjs());
}
}
}
}
break;
default:
break;
}
}
tickStatus=Tickable.STATUS_SCRIPT+100;
dequeResponses();
altStatusTickable=null;
return true;
}
@Override
public void initializeClass()
{
}
@Override
public int compareTo(final CMObject o)
{
return CMClass.classID(this).compareToIgnoreCase(CMClass.classID(o));
}
public void enqueResponse(final PhysicalAgent host,
final MOB source,
final Environmental target,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final DVector script,
final int ticks,
final String msg,
final String[] triggerStr)
{
if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED))
return;
if(que.size()>25)
{
this.logError(monster, "UNK", "SYS", "Attempt to enque more than 25 events (last was "+CMParms.toListString(triggerStr)+" ).");
que.clear();
}
if(noDelay)
execute(host,source,target,monster,primaryItem,secondaryItem,script,msg,newObjs());
else
que.add(new ScriptableResponse(host,source,target,monster,primaryItem,secondaryItem,script,ticks,msg));
}
public void prequeResponse(final PhysicalAgent host,
final MOB source,
final Environmental target,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final DVector script,
final int ticks,
final String msg)
{
if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED))
return;
if(que.size()>25)
{
this.logError(monster, "UNK", "SYS", "Attempt to pre que more than 25 events.");
que.clear();
}
que.add(0,new ScriptableResponse(host,source,target,monster,primaryItem,secondaryItem,script,ticks,msg));
}
@Override
public void dequeResponses()
{
try
{
tickStatus=Tickable.STATUS_SCRIPT+100;
for(int q=que.size()-1;q>=0;q--)
{
ScriptableResponse SB=null;
try
{
SB=que.get(q);
}
catch(final ArrayIndexOutOfBoundsException x)
{
continue;
}
if(SB.checkTimeToExecute())
{
execute(SB.h,SB.s,SB.t,SB.m,SB.pi,SB.si,SB.scr,SB.message,newObjs());
que.remove(SB);
}
}
}
catch (final Exception e)
{
Log.errOut("DefaultScriptingEngine", e);
}
}
public String L(final String str, final String ... xs)
{
return CMLib.lang().fullSessionTranslation(str, xs);
}
protected static class JScriptEvent extends ScriptableObject
{
@Override
public String getClassName()
{
return "JScriptEvent";
}
static final long serialVersionUID = 43;
final PhysicalAgent h;
final MOB s;
final Environmental t;
final MOB m;
final Item pi;
final Item si;
final Object[] objs;
Vector<String> scr;
final String message;
final DefaultScriptingEngine c;
public Environmental host()
{
return h;
}
public MOB source()
{
return s;
}
public Environmental target()
{
return t;
}
public MOB monster()
{
return m;
}
public Item item()
{
return pi;
}
public Item item2()
{
return si;
}
public String message()
{
return message;
}
public void setVar(final String host, final String var, final String value)
{
c.setVar(host,var.toUpperCase(),value);
}
public String getVar(final String host, final String var)
{
return c.getVar(host, var);
}
public String toJavaString(final Object O)
{
return Context.toString(O);
}
public String getCMType(final Object O)
{
if(O == null)
return "null";
final CMObjectType typ = CMClass.getObjectType(O);
if(typ == null)
return "unknown";
return typ.name().toLowerCase();
}
@Override
public Object get(final String name, final Scriptable start)
{
if (super.has(name, start))
return super.get(name, start);
if (methH.containsKey(name) || funcH.containsKey(name)
|| (name.endsWith("$")&&(funcH.containsKey(name.substring(0,name.length()-1)))))
{
return new Function()
{
@Override
public Object call(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args)
{
if(methH.containsKey(name))
{
final StringBuilder strb=new StringBuilder(name);
if(args.length==1)
strb.append(" ").append(String.valueOf(args[0]));
else
for(int i=0;i<args.length;i++)
{
if(i==args.length-1)
strb.append(" ").append(String.valueOf(args[i]));
else
strb.append(" ").append("'"+String.valueOf(args[i])+"'");
}
final DVector DV=new DVector(2);
DV.addElement("JS_PROG",null);
DV.addElement(strb.toString(),null);
return c.execute(h,s,t,m,pi,si,DV,message,objs);
}
if(name.endsWith("$"))
{
final StringBuilder strb=new StringBuilder(name.substring(0,name.length()-1)).append("(");
if(args.length==1)
strb.append(" ").append(String.valueOf(args[0]));
else
for(int i=0;i<args.length;i++)
{
if(i==args.length-1)
strb.append(" ").append(String.valueOf(args[i]));
else
strb.append(" ").append("'"+String.valueOf(args[i])+"'");
}
strb.append(" ) ");
return c.functify(h,s,t,m,pi,si,message,objs,strb.toString());
}
final String[] sargs=new String[args.length+3];
sargs[0]=name;
sargs[1]="(";
for(int i=0;i<args.length;i++)
sargs[i+2]=String.valueOf(args[i]);
sargs[sargs.length-1]=")";
final String[][] EVAL={sargs};
return Boolean.valueOf(c.eval(h,s,t,m,pi,si,message,objs,EVAL,0));
}
@Override
public void delete(final String arg0)
{
}
@Override
public void delete(final int arg0)
{
}
@Override
public Object get(final String arg0, final Scriptable arg1)
{
return null;
}
@Override
public Object get(final int arg0, final Scriptable arg1)
{
return null;
}
@Override
public String getClassName()
{
return null;
}
@Override
public Object getDefaultValue(final Class<?> arg0)
{
return null;
}
@Override
public Object[] getIds()
{
return null;
}
@Override
public Scriptable getParentScope()
{
return null;
}
@Override
public Scriptable getPrototype()
{
return null;
}
@Override
public boolean has(final String arg0, final Scriptable arg1)
{
return false;
}
@Override
public boolean has(final int arg0, final Scriptable arg1)
{
return false;
}
@Override
public boolean hasInstance(final Scriptable arg0)
{
return false;
}
@Override
public void put(final String arg0, final Scriptable arg1, final Object arg2)
{
}
@Override
public void put(final int arg0, final Scriptable arg1, final Object arg2)
{
}
@Override
public void setParentScope(final Scriptable arg0)
{
}
@Override
public void setPrototype(final Scriptable arg0)
{
}
@Override
public Scriptable construct(final Context arg0, final Scriptable arg1, final Object[] arg2)
{
return null;
}
};
}
return super.get(name, start);
}
public void executeEvent(final DVector script, final int lineNum)
{
c.execute(h, s, t, m, pi, si, script, message, objs, lineNum);
}
public JScriptEvent(final DefaultScriptingEngine scrpt,
final PhysicalAgent host,
final MOB source,
final Environmental target,
final MOB monster,
final Item primaryItem,
final Item secondaryItem,
final String msg,
final Object[] tmp)
{
c=scrpt;
h=host;
s=source;
t=target;
m=monster;
pi=primaryItem;
si=secondaryItem;
message=msg;
objs=tmp;
}
}
}
|
support for room numbers in mptransfer
git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@19783 0d6f1817-ed0e-0410-87c9-987e46238f29
|
com/planet_ink/coffee_mud/Common/DefaultScriptingEngine.java
|
support for room numbers in mptransfer
|
|
Java
|
apache-2.0
|
12a4fd7b0f19bc859c040a1e4d2bcb641ce1a86a
| 0
|
cescoffier/vertx-microservices-workshop,cescoffier/vertx-microservices-workshop,cescoffier/vertx-microservices-workshop,cescoffier/vertx-microservices-workshop,cescoffier/vertx-microservices-workshop
|
package io.vertx.workshop.quote;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.workshop.common.MicroServiceVerticle;
/**
* a verticle generating "fake" quotes based on the configuration.
*/
public class GeneratorConfigVerticle extends MicroServiceVerticle {
/**
* The address on which the data are sent.
*/
public static final String ADDRESS = "market";
/**
* This method is called when the verticle is deployed.
*/
@Override
public void start() {
super.start();
// Read the configuration, and deploy a MarketDataVerticle for each company listed in the configuration.
JsonArray quotes = config().getJsonArray("companies");
for (Object q : quotes) {
JsonObject company = (JsonObject) q;
// Deploy another verticle without configuration.
vertx.deployVerticle(MarketDataVerticle.class.getName(), new DeploymentOptions().setConfig(company));
}
// Deploy the verticle with a configuration.
vertx.deployVerticle(RestQuoteAPIVerticle.class.getName(), new DeploymentOptions().setConfig(config()));
// Publish the services in the discovery infrastructure.
publishMessageSource("market-data", ADDRESS, rec -> {
if (!rec.succeeded()) {
rec.cause().printStackTrace();
}
System.out.println("Market-Data service published : " + rec.succeeded());
});
publishHttpEndpoint("quotes", "localhost", config().getInteger("http.port", 8080), ar -> {
if (ar.failed()) {
ar.cause().printStackTrace();
} else {
System.out.println("Quotes (Rest endpoint) service published : " + ar.succeeded());
}
});
}
}
|
quote-generator/src/main/java/io/vertx/workshop/quote/GeneratorConfigVerticle.java
|
package io.vertx.workshop.quote;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.workshop.common.MicroServiceVerticle;
/**
* a verticle generating "fake" quotes based on the configuration.
*/
public class GeneratorConfigVerticle extends MicroServiceVerticle {
/**
* The address on which the data are sent.
*/
public static final String ADDRESS = "market";
/**
* This method is called when the verticle is deployed.
*/
@Override
public void start() {
super.start();
// Read the configuration, and deploy a MarketDataVerticle for each company listed in the configuration.
JsonArray quotes = config().getJsonArray("companies");
for (Object q : quotes) {
JsonObject company = (JsonObject) q;
// Deploy the verticle with a configuration.
vertx.deployVerticle(MarketDataVerticle.class.getName(), new DeploymentOptions().setConfig(company));
}
// Deploy another verticle without configuration.
vertx.deployVerticle(RestQuoteAPIVerticle.class.getName(), new DeploymentOptions().setConfig(config()));
// Publish the services in the discovery infrastructure.
publishMessageSource("market-data", ADDRESS, rec -> {
if (!rec.succeeded()) {
rec.cause().printStackTrace();
}
System.out.println("Market-Data service published : " + rec.succeeded());
});
publishHttpEndpoint("quotes", "localhost", config().getInteger("http.port", 8080), ar -> {
if (ar.failed()) {
ar.cause().printStackTrace();
} else {
System.out.println("Quotes (Rest endpoint) service published : " + ar.succeeded());
}
});
}
}
|
Fixed swapped comments above methods
|
quote-generator/src/main/java/io/vertx/workshop/quote/GeneratorConfigVerticle.java
|
Fixed swapped comments above methods
|
|
Java
|
apache-2.0
|
2c17430deae07002ff2c1f593965ad07b3fe4c10
| 0
|
drewrobb/logstash,suppandi/logstash,triforkse/logstash-mesos,drewrobb/logstash,kensipe/logstash,kensipe/logstash,triforkse/logstash-mesos,mesos/logstash,suppandi/logstash,mesosphere/logstash,frankscholten/logstash,alex-glv/logstash,triforkse/logstash-mesos,triforkse/logstash-mesos,alex-glv/logstash,mesosphere/logstash,mesosphere/logstash,suppandi/logstash,kensipe/logstash,frankscholten/logstash,drewrobb/logstash,kensipe/logstash,frankscholten/logstash,mesosphere/logstash,frankscholten/logstash,suppandi/logstash,alex-glv/logstash,mesos/logstash,alex-glv/logstash,drewrobb/logstash
|
package org.apache.mesos.logstash.scheduler;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Awaitility.fieldIn;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
@Ignore
public class ConfigMonitorTest {
@Rule
public TemporaryFolder configDir = new TemporaryFolder();
AtomicInteger notificationCounter;
@Before
public void setup() {
// Start at -1 because we want to ignore the initial notification from ConfigMonitor
notificationCounter = new AtomicInteger(-1);
}
public void awaitRunning(ConfigMonitor monitor) {
await().until(fieldIn(monitor).ofType(boolean.class).andWithName("isRunning"), is(true));
}
public void writeConfig(String configFileName, String content) throws IOException {
FileUtils.write(getFilePath(configFileName), content);
FileUtils.touch(getFilePath(configFileName));
}
private File getFilePath(String configFileName) {
return new File(configDir.getRoot() + "/" + configFileName);
}
@Test
public void getsNotifiedOnFileCreation() throws IOException {
// Setup
ConfigMonitor monitor = new ConfigMonitor(configDir.getRoot().getAbsolutePath());
final Map<String, String> config = startMonitor(monitor);
// Execute
writeConfig("my-framework.conf", "foo");
System.out.println("Awaiting notification");
awaitNotification(monitor);
// Verify
assertEquals(1, config.size());
assertEquals("foo", config.get("my-framework"));
}
@Test
public void getsNotifiedOnFileDelete() throws IOException {
ConfigMonitor monitor = new ConfigMonitor(configDir.getRoot().getAbsolutePath());
writeConfig("my-framework.conf", "foo");
final Map<String, String> config = startMonitor(monitor);
FileUtils.forceDelete(getFilePath("my-framework.conf"));
awaitNotification(monitor);
assertEquals(0, config.size());
}
@Test
public void getsNotifiedOnFileUpdate() throws IOException {
ConfigMonitor monitor = new ConfigMonitor(configDir.getRoot().getAbsolutePath());
// Write the config before the monitor starts.
writeConfig("my-framework.conf", "foo");
final Map<String, String> config = startMonitor(monitor);
// Work around because file system watcher on mac is slow
// and doesn't notice writes if they happen too fast after eachother
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// Modify the config
writeConfig("my-framework.conf", "bar");
awaitNotification(monitor);
assertEquals(1, config.size());
}
private void awaitNotification(ConfigMonitor monitor) {
await().untilAtomic(notificationCounter, is(1));
}
private Map<String, String> startMonitor(ConfigMonitor monitor) {
final Map<String, String> config = new ConcurrentHashMap<>();
monitor.start(c -> {
config.clear();
config.putAll(c);
notificationCounter.incrementAndGet();
});
awaitRunning(monitor);
return config;
}
}
|
scheduler/src/test/java/org/apache/mesos/logstash/scheduler/ConfigMonitorTest.java
|
package org.apache.mesos.logstash.scheduler;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static com.jayway.awaitility.Awaitility.await;
import static com.jayway.awaitility.Awaitility.fieldIn;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
public class ConfigMonitorTest {
@Rule
public TemporaryFolder configDir = new TemporaryFolder();
AtomicInteger notificationCounter;
@Before
public void setup() {
// Start at -1 because we want to ignore the initial notification from ConfigMonitor
notificationCounter = new AtomicInteger(-1);
}
public void awaitRunning(ConfigMonitor monitor) {
await().until(fieldIn(monitor).ofType(boolean.class).andWithName("isRunning"), is(true));
}
public void writeConfig(String configFileName, String content) throws IOException {
FileUtils.write(getFilePath(configFileName), content);
FileUtils.touch(getFilePath(configFileName));
}
private File getFilePath(String configFileName) {
return new File(configDir.getRoot() + "/" + configFileName);
}
@Test
public void getsNotifiedOnFileCreation() throws IOException {
// Setup
ConfigMonitor monitor = new ConfigMonitor(configDir.getRoot().getAbsolutePath());
final Map<String, String> config = startMonitor(monitor);
// Execute
writeConfig("my-framework.conf", "foo");
System.out.println("Awaiting notification");
awaitNotification(monitor);
// Verify
assertEquals(1, config.size());
assertEquals("foo", config.get("my-framework"));
}
@Test
public void getsNotifiedOnFileDelete() throws IOException {
ConfigMonitor monitor = new ConfigMonitor(configDir.getRoot().getAbsolutePath());
writeConfig("my-framework.conf", "foo");
final Map<String, String> config = startMonitor(monitor);
FileUtils.forceDelete(getFilePath("my-framework.conf"));
awaitNotification(monitor);
assertEquals(0, config.size());
}
@Test
public void getsNotifiedOnFileUpdate() throws IOException {
ConfigMonitor monitor = new ConfigMonitor(configDir.getRoot().getAbsolutePath());
// Write the config before the monitor starts.
writeConfig("my-framework.conf", "foo");
final Map<String, String> config = startMonitor(monitor);
// Work around because file system watcher on mac is slow
// and doesn't notice writes if they happen too fast after eachother
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// Modify the config
writeConfig("my-framework.conf", "bar");
awaitNotification(monitor);
assertEquals(1, config.size());
}
private void awaitNotification(ConfigMonitor monitor) {
await().untilAtomic(notificationCounter, is(1));
}
private Map<String, String> startMonitor(ConfigMonitor monitor) {
final Map<String, String> config = new ConcurrentHashMap<>();
monitor.start(c -> {
config.clear();
config.putAll(c);
notificationCounter.incrementAndGet();
});
awaitRunning(monitor);
return config;
}
}
|
Temporart ignoring a test to setup CI
|
scheduler/src/test/java/org/apache/mesos/logstash/scheduler/ConfigMonitorTest.java
|
Temporart ignoring a test to setup CI
|
|
Java
|
apache-2.0
|
641278ab1bf2f809d3f7c5d36946ae95fefb0638
| 0
|
variacode/rundeck,variacode/rundeck,variacode/rundeck,rundeck/rundeck,rundeck/rundeck,variacode/rundeck,variacode/rundeck,rundeck/rundeck,rundeck/rundeck,rundeck/rundeck
|
/*
* Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com)
*
* 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.dtolabs.rundeck.jetty.jaas;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.LoginException;
import ch.qos.logback.classic.Level;
import grails.boot.config.GrailsAutoConfiguration;
import grails.util.Holders;
import org.eclipse.jetty.jaas.callback.ObjectCallback;
import org.eclipse.jetty.jaas.spi.AbstractLoginModule;
import org.eclipse.jetty.jaas.spi.UserInfo;
import org.eclipse.jetty.util.security.Credential;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* A LdapLoginModule for use with JAAS setups
*
* The jvm should be started with the following parameter: <br>
* <br>
* <code>
* -Djava.security.auth.login.config=etc/ldap-loginModule.conf
* </code> <br>
* <br>
* and an example of the ldap-loginModule.conf would be: <br>
* <br>
*
* <pre>
* ldaploginmodule {
* com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule required
* debug="true"
* contextFactory="com.sun.jndi.ldap.LdapCtxFactory"
* hostname="ldap.example.com"
* port="389"
* timeoutRead="5000"
* timeoutConnect="30000"
* bindDn="cn=Directory Manager"
* bindPassword="directory"
* authenticationMethod="simple"
* forceBindingLogin="false"
* forceBindingLoginUseRootContextForRoles="false"
* userBaseDn="ou=people,dc=alcatel"
* userRdnAttribute="uid"
* userIdAttribute="uid"
* userPasswordAttribute="userPassword"
* userObjectClass="inetOrgPerson"
* roleBaseDn="ou=groups,dc=example,dc=com"
* roleNameAttribute="cn"
* roleMemberAttribute="uniqueMember"
* roleUsernameMemberAttribute="memberUid"
* roleObjectClass="groupOfUniqueNames"
* rolePrefix="rundeck"
* cacheDurationMillis="500"
* reportStatistics="true"
* nestedGroups="false";
* };
* </pre>
*
* @author Jesse McConnell <a href="mailto:jesse@codehaus.org">jesse@codehaus.org</a>
* @author Frederic Nizery <a href="mailto:frederic.nizery@alcatel-lucent.fr">frederic.nizery@alcatel-lucent.fr</a>
* @author Trygve Laugstol <a href="mailto:trygvis@codehaus.org">trygvis@codehaus.org</a>
* @author Noah Campbell <a href="mailto:noahcampbell@gmail.com">noahcampbell@gmail.com</a>
*/
public class JettyCachingLdapLoginModule extends AbstractLoginModule {
private static final Logger LOG = LoggerFactory.getLogger(JettyCachingLdapLoginModule.class);
static {
String logLevelSysProp = System.getProperty("com.dtolabs.rundeck.jetty.jaas.LEVEL");
if(logLevelSysProp != null) {
Level level = Level.toLevel(logLevelSysProp);
((ch.qos.logback.classic.Logger) LOG).setLevel(level);
}
}
private static final Pattern rolePattern = Pattern.compile("^cn=([^,]+)", Pattern.CASE_INSENSITIVE);
private static final String CRYPT_TYPE = "CRYPT:";
private static final String MD5_TYPE = "MD5:";
protected final String _roleMemberFilter = "member=*";
/**
* Provider URL
*/
protected String _providerUrl;
/**
* Role prefix to remove from ldap group name.
*/
protected String _rolePrefix = "";
/**
* Duration of storing the user in memory.
*/
protected int _cacheDuration = 0;
/**
* hostname of the ldap server
*/
protected String _hostname;
/**
* port of the ldap server
*/
protected int _port = 389;
/**
* Context.SECURITY_AUTHENTICATION
*/
protected String _authenticationMethod;
/**
* Context.INITIAL_CONTEXT_FACTORY
*/
protected String _contextFactory;
/**
* root DN used to connect to
*/
protected String _bindDn;
/**
* password used to connect to the root ldap context
*/
protected String _bindPassword;
/**
* object class of a user
*/
protected String _userObjectClass = "inetOrgPerson";
/**
* attribute that the principal is located
*/
protected String _userRdnAttribute = "uid";
/**
* attribute that the principal is located
*/
protected String _userIdAttribute = "cn";
/**
* name of the attribute that a users password is stored under
* <br>
* NOTE: not always accessible, see force binding login
*/
protected String _userPasswordAttribute = "userPassword";
/**
* base DN where users are to be searched from
*/
protected String _userBaseDn;
/**
* base DN where role membership is to be searched from
*/
protected String _roleBaseDn;
/**
* object class of roles
*/
protected String _roleObjectClass = "groupOfUniqueNames";
/**
* name of the attribute that a user DN would be under a role class
*/
protected String _roleMemberAttribute = "uniqueMember";
/**
* name of the attribute that a username would be under a role class
*/
protected String _roleUsernameMemberAttribute=null;
/**
* the name of the attribute that a role would be stored under
*/
protected String _roleNameAttribute = "roleName";
protected boolean _debug;
protected boolean _ldapsVerifyHostname=true;
/**
* if the getUserInfo can pull a password off of the user then password
* comparison is an option for authn, to force binding login checks, set
* this to true
*/
protected boolean _forceBindingLogin = false;
/**
* if _forceFindingLogin is true, and _forceBindingLoginUseRootContextForRoles
* is true, then role memberships are obtained using _rootContext
*/
protected boolean _forceBindingLoginUseRootContextForRoles = false;
protected DirContext _rootContext;
protected boolean _reportStatistics;
/**
* List of supplemental roles provided in config file that get added to
* all users.
*/
protected List<String> _supplementalRoles;
protected boolean _nestedGroups;
/**
* timeout for LDAP read
*/
protected long _timeoutRead =0;
/**
* timeout for LDAP connection
*/
protected long _timeoutConnect =0;
protected static final ConcurrentHashMap<String, CachedUserInfo> USERINFOCACHE =
new ConcurrentHashMap<String, CachedUserInfo>();
/**
* The number of cache hits for UserInfo objects.
*/
protected static long userInfoCacheHits;
/**
* The number of login attempts for this particular module.
*/
protected static long loginAttempts;
private static ConcurrentHashMap<String, List<String>> roleMemberOfMap;
private static long roleMemberOfMapExpires = 0;
/**
* get the available information about the user
* <br>
* for this LoginModule, the credential can be null which will result in a
* binding ldap authentication scenario
* <br>
* roles are also an optional concept if required
*
* @param username
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public UserInfo getUserInfo(String username) throws Exception {
String pwdCredential = getUserCredentials(username);
if (pwdCredential == null) {
return null;
}
pwdCredential = convertCredentialLdapToJetty(pwdCredential);
pwdCredential = decodeBase64EncodedPwd(pwdCredential);
Credential credential = Credential.getCredential(pwdCredential);
List roles = getUserRoles(_rootContext, username);
return new UserInfo(username, credential, roles);
}
String decodeBase64EncodedPwd(String encoded) {
String chkString = null;
String prefix = "";
if(encoded.startsWith(CRYPT_TYPE)) {
chkString = encoded.substring(CRYPT_TYPE.length(),encoded.length());
prefix = CRYPT_TYPE;
} else if(encoded.startsWith(MD5_TYPE)) {
chkString = encoded.substring(MD5_TYPE.length(), encoded.length());
prefix = MD5_TYPE;
} else {
return encoded; //make no attempt to further decode because we don't know what value this might be
}
return prefix+(isBase64(chkString) ? org.apache.commons.codec.binary.Hex.encodeHexString(org.apache.commons.codec.binary.Base64.decodeBase64(chkString)) : chkString);
}
boolean isBase64(String chkBase64) {
try {
Base64.getDecoder().decode(chkBase64);
return chkBase64.replace(" ","").length() % 4 == 0;
} catch(IllegalArgumentException iaex) {}
return false;
}
protected String doRFC2254Encoding(String inputString) {
StringBuffer buf = new StringBuffer(inputString.length());
for (int i = 0; i < inputString.length(); i++) {
char c = inputString.charAt(i);
switch (c) {
case '\\':
buf.append("\\5c");
break;
case '*':
buf.append("\\2a");
break;
case '(':
buf.append("\\28");
break;
case ')':
buf.append("\\29");
break;
case '\0':
buf.append("\\00");
break;
default:
buf.append(c);
break;
}
}
return buf.toString();
}
/**
* attempts to get the users credentials from the users context
* <p/>
* NOTE: this is not an user authenticated operation
*
* @param username
* @return
* @throws LoginException
*/
@SuppressWarnings("unchecked")
private String getUserCredentials(String username) throws LoginException {
String ldapCredential = null;
SearchControls ctls = new SearchControls();
ctls.setCountLimit(1);
ctls.setDerefLinkFlag(true);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectClass={0})({1}={2}))";
try {
Object[] filterArguments = { _userObjectClass, _userIdAttribute, username };
NamingEnumeration results = _rootContext.search(_userBaseDn, filter, filterArguments,
ctls);
LOG.debug("Found user?: " + results.hasMoreElements());
if (!results.hasMoreElements()) {
throw new LoginException("User not found.");
}
SearchResult result = findUser(username);
Attributes attributes = result.getAttributes();
Attribute attribute = attributes.get(_userPasswordAttribute);
if (attribute != null) {
try {
byte[] value = (byte[]) attribute.get();
ldapCredential = new String(value);
} catch (NamingException e) {
LOG.debug("no password available under attribute: " + _userPasswordAttribute);
}
}
} catch (NamingException e) {
throw new LoginException("Root context binding failure.");
}
LOG.debug("user cred is: " + ldapCredential);
return ldapCredential;
}
/**
* attempts to get the users roles from the root context
*
* NOTE: this is not an user authenticated operation
*
* @param dirContext
* @param username
* @return
* @throws LoginException
*/
@SuppressWarnings("unchecked")
protected List getUserRoles(DirContext dirContext, String username) throws LoginException,
NamingException {
String userDn = _userRdnAttribute + "=" + username + "," + _userBaseDn;
return getUserRolesByDn(dirContext, userDn, username);
}
@SuppressWarnings("unchecked")
private List getUserRolesByDn(DirContext dirContext, String userDn, String username) throws LoginException,
NamingException {
List<String> roleList = new ArrayList<String>();
if (dirContext == null || _roleBaseDn == null || (_roleMemberAttribute == null
&& _roleUsernameMemberAttribute == null)
|| _roleObjectClass == null) {
LOG.warn("JettyCachingLdapLoginModule: No user roles found: roleBaseDn, roleObjectClass and roleMemberAttribute or roleUsernameMemberAttribute must be specified.");
addSupplementalRoles(roleList);
return roleList;
}
String[] attrIDs = { _roleNameAttribute };
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(attrIDs);
ctls.setDerefLinkFlag(true);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectClass={0})({1}={2}))";
final NamingEnumeration results;
if(null!=_roleUsernameMemberAttribute){
Object[] filterArguments = { _roleObjectClass, _roleUsernameMemberAttribute, username };
results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
}else{
Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn };
results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
}
while (results.hasMoreElements()) {
SearchResult result = (SearchResult) results.nextElement();
Attributes attributes = result.getAttributes();
if (attributes == null) {
continue;
}
Attribute roleAttribute = attributes.get(_roleNameAttribute);
if (roleAttribute == null) {
continue;
}
NamingEnumeration roles = roleAttribute.getAll();
while (roles.hasMore()) {
if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
String role = (String) roles.next();
roleList.add(role.replace(_rolePrefix, ""));
} else {
roleList.add((String) roles.next());
}
}
}
addSupplementalRoles(roleList);
if(_nestedGroups) {
roleList = getNestedRoles(dirContext, roleList);
}
if (roleList.size() < 1) {
LOG.warn("JettyCachingLdapLoginModule: User '" + username + "' has no role membership; role query configuration may be incorrect");
}else{
LOG.debug("JettyCachingLdapLoginModule: User '" + username + "' has roles: " + roleList);
}
return roleList;
}
protected void addSupplementalRoles(final List<String> roleList) {
if (null != _supplementalRoles) {
for (String supplementalRole : _supplementalRoles) {
if(null!=supplementalRole&& !"".equals(supplementalRole.trim())){
roleList.add(supplementalRole.trim());
}
}
}
}
private List<String> getNestedRoles(DirContext dirContext, List<String> roleList) {
HashMap<String, List<String>> roleMemberOfMap = new HashMap<String, List<String>>();
roleMemberOfMap.putAll(getRoleMemberOfMap(dirContext));
List<String> mergedList = mergeRoles(roleList, roleMemberOfMap);
return mergedList;
}
private List<String> mergeRoles(List<String> roles, HashMap<String, List<String>> roleMemberOfMap) {
List<String> newRoles = new ArrayList<String>();
List<String> mergedRoles = new ArrayList<String>();
mergedRoles.addAll(roles);
for(String role : roles) {
if(roleMemberOfMap.containsKey(role)) {
for(String newRole : roleMemberOfMap.get(role)) {
if (!roles.contains(newRole)) {
newRoles.add(newRole);
}
}
roleMemberOfMap.remove(role);
}
}
if(!newRoles.isEmpty()) {
mergedRoles.addAll(mergeRoles(newRoles, roleMemberOfMap));
}
return mergedRoles;
}
private ConcurrentHashMap<String, List<String>> getRoleMemberOfMap(DirContext dirContext) {
if (_cacheDuration == 0 || System.currentTimeMillis() > roleMemberOfMapExpires) { // only worry about caching if there is a cacheDuration set.
roleMemberOfMap = buildRoleMemberOfMap(dirContext);
roleMemberOfMapExpires = System.currentTimeMillis() + _cacheDuration;
}
return roleMemberOfMap;
}
private ConcurrentHashMap<String, List<String>> buildRoleMemberOfMap(DirContext dirContext) {
Object[] filterArguments = { _roleObjectClass };
SearchControls ctls = new SearchControls();
ctls.setDerefLinkFlag(true);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
ConcurrentHashMap<String, List<String>> roleMemberOfMap = new ConcurrentHashMap<String, List<String>>();
try {
NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, _roleMemberFilter, ctls);
while (results.hasMoreElements()) {
SearchResult result = results.nextElement();
Attributes attributes = result.getAttributes();
if (attributes == null) {
continue;
}
Attribute roleAttribute = attributes.get(_roleNameAttribute);
Attribute memberAttribute = attributes.get(_roleMemberAttribute);
if (roleAttribute == null || memberAttribute == null) {
continue;
}
NamingEnumeration role = roleAttribute.getAll();
NamingEnumeration members = memberAttribute.getAll();
if(!role.hasMore() || !members.hasMore()) {
continue;
}
String roleName = (String) role.next();
if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
roleName = roleName.replace(_rolePrefix, "");
}
while(members.hasMore()) {
String member = (String) members.next();
Matcher roleMatcher = rolePattern.matcher(member);
if(!roleMatcher.find()) {
continue;
}
String roleMember = roleMatcher.group(1);
List<String> memberOf;
if(roleMemberOfMap.containsKey(roleMember)) {
memberOf = roleMemberOfMap.get(roleMember);
} else {
memberOf = new ArrayList<String>();
}
memberOf.add(roleName);
roleMemberOfMap.put(roleMember, memberOf);
}
}
} catch (NamingException e) {
e.printStackTrace();
}
return roleMemberOfMap;
}
protected boolean isDebug(){
return _debug;
}
/**
* Default behavior to emit to System.err
* @param message message
*/
protected void debug(String message) {
if (isDebug()) {
LOG.debug(message);
}
}
/**
* Gets credentials by calling {@link #getCallBackAuth()}, then performs {@link #authenticate(String, Object)}
*
* @return true if authenticated
* @throws LoginException
*/
@Override
public boolean login() throws LoginException {
try{
Object[] userPass= getCallBackAuth();
if (null == userPass || userPass.length < 2) {
setAuthenticated(false);
} else {
String name = (String) userPass[0];
Object pass = userPass[1];
setAuthenticated(authenticate(name, pass));
}
return isAuthenticated();
} catch (UnsupportedCallbackException e) {
throw new LoginException("Error obtaining callback information.");
} catch (IOException e) {
if (_debug) {
e.printStackTrace();
}
throw new LoginException("IO Error performing login.");
}
}
/**
*
* @return Return the object[] containing username and password, by using the callback mechanism
*
* @throws IOException
* @throws UnsupportedCallbackException
* @throws LoginException
*/
protected Object[] getCallBackAuth() throws IOException, UnsupportedCallbackException, LoginException {
if (getCallbackHandler() == null) {
throw new LoginException("No callback handler");
}
Callback[] callbacks = configureCallbacks();
getCallbackHandler().handle(callbacks);
String webUserName = ((NameCallback) callbacks[0]).getName();
Object webCredential = ((ObjectCallback) callbacks[1]).getObject();
if (webCredential == null) {
webCredential = ((PasswordCallback)callbacks[2]).getPassword();
}
return new Object[]{webUserName,webCredential};
}
/**
* since ldap uses a context bind for valid authentication checking, we
* override login()
* <br>
* if credentials are not available from the users context or if we are
* forcing the binding check then we try a binding authentication check,
* otherwise if we have the users encoded password then we can try
* authentication via that mechanic
* @param webUserName user
* @param webCredential password
*
*
* @return true if authenticated
* @throws LoginException
*/
protected boolean authenticate(final String webUserName, final Object webCredential) throws LoginException {
try {
if (isEmptyOrNull(webUserName) || isEmptyOrNull(webCredential)) {
setAuthenticated(false);
return isAuthenticated();
}
loginAttempts++;
if(_reportStatistics)
{
DecimalFormat percentHit = new DecimalFormat("#.##");
LOG.info("Login attempts: " + loginAttempts + ", Hits: " + userInfoCacheHits +
", Ratio: " + percentHit.format((double)userInfoCacheHits / loginAttempts * 100f) + "%.");
}
if (_forceBindingLogin) {
return bindingLogin(webUserName, webCredential);
}
// This sets read and the credential
UserInfo userInfo = getUserInfo(webUserName);
if (userInfo == null) {
setAuthenticated(false);
return false;
}
JAASUserInfo jaasUserInfo = new JAASUserInfo(userInfo);
jaasUserInfo.fetchRoles(); //must run this otherwise will throw NPE later
setCurrentUser(jaasUserInfo);
if (webCredential instanceof String) {
return credentialLogin(Credential.getCredential((String) webCredential));
}
return credentialLogin(webCredential);
} catch (UnsupportedCallbackException e) {
throw new LoginException("Error obtaining callback information.");
} catch (IOException e) {
if (_debug) {
e.printStackTrace();
}
throw new LoginException("IO Error performing login.");
} catch (Exception e) {
if (_debug) {
e.printStackTrace();
}
throw new LoginException("Error obtaining user info.");
}
}
private boolean isEmptyOrNull(final Object value) {
return null==value || "".equals(value);
}
/**
* password supplied authentication check
*
* @param webCredential
* @return
* @throws LoginException
*/
protected boolean credentialLogin(Object webCredential) throws LoginException {
setAuthenticated(getCurrentUser().checkCredential(webCredential));
return isAuthenticated();
}
/**
* binding authentication check This methode of authentication works only if
* the user branch of the DIT (ldap tree) has an ACI (acces control
* instruction) that allow the access to any user or at least for the user
* that logs in.
*
* @param username
* @param password
* @return
* @throws LoginException
*/
@SuppressWarnings("unchecked")
protected boolean bindingLogin(String username, Object password) throws LoginException,
NamingException {
final String cacheToken = Credential.MD5.digest(username + ":" + password.toString());
if (_cacheDuration > 0) { // only worry about caching if there is a cacheDuration set.
CachedUserInfo cached = USERINFOCACHE.get(cacheToken);
if (cached != null) {
if (System.currentTimeMillis() < cached.expires) {
LOG.debug("Cache Hit for " + username + ".");
userInfoCacheHits++;
setCurrentUser(new JAASUserInfo(cached.userInfo));
setAuthenticated(true);
return true;
} else {
LOG.info("Cache Eviction for " + username + ".");
USERINFOCACHE.remove(cacheToken);
}
} else {
LOG.debug("Cache Miss for " + username + ".");
}
}
SearchResult searchResult = findUser(username);
String userDn = searchResult.getNameInNamespace();
LOG.info("Attempting authentication: " + userDn);
Hashtable environment = getEnvironment();
environment.put(Context.SECURITY_PRINCIPAL, userDn);
environment.put(Context.SECURITY_CREDENTIALS, password);
DirContext dirContext = new InitialDirContext(environment);
// use _rootContext to find roles, if configured to doso
if ( _forceBindingLoginUseRootContextForRoles ) {
dirContext = _rootContext;
LOG.debug("Using _rootContext for role lookup.");
}
List roles = getUserRolesByDn(dirContext, userDn, username);
UserInfo userInfo = new UserInfo(username, null, roles);
if (_cacheDuration > 0) {
USERINFOCACHE.put(cacheToken,
new CachedUserInfo(userInfo,
System.currentTimeMillis() + _cacheDuration));
LOG.debug("Adding " + username + " set to expire: " + System.currentTimeMillis() + _cacheDuration);
}
JAASUserInfo jaasUserInfo = new JAASUserInfo(userInfo);
try {
jaasUserInfo.fetchRoles();
} catch(Exception ex) {
if(_debug) {
LOG.debug("Failed to fetch roles",ex);
}
}
setCurrentUser(jaasUserInfo);
setAuthenticated(true);
return true;
}
@SuppressWarnings("unchecked")
private SearchResult findUser(String username) throws NamingException, LoginException {
SearchControls ctls = new SearchControls();
ctls.setCountLimit(1);
ctls.setDerefLinkFlag(true);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectClass={0})({1}={2}))";
LOG.debug("Searching for users with filter: \'" + filter + "\'" + " from base dn: "
+ _userBaseDn);
Object[] filterArguments = new Object[] { _userObjectClass, _userIdAttribute, username };
NamingEnumeration results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls);
LOG.debug("Found user?: " + results.hasMoreElements());
if (!results.hasMoreElements()) {
throw new LoginException("User not found.");
}
return (SearchResult) results.nextElement();
}
@SuppressWarnings("unchecked")
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
Map<String, ?> options) {
super.initialize(subject, callbackHandler, sharedState, options);
initializeOptions(options);
try {
_rootContext = new InitialDirContext(getEnvironment());
} catch (NamingException ex) {
LOG.error("Naming error",ex);
throw new IllegalStateException("Unable to establish root context: "+ex.getMessage());
}
}
public void initializeOptions(final Map options) {
_hostname = (String) options.get("hostname");
if(options.containsKey("port")) {
_port = Integer.parseInt((String) options.get("port"));
}
_providerUrl = (String) options.get("providerUrl");
_contextFactory = (String) options.get("contextFactory");
_bindDn = (String) options.get("bindDn");
String bindPassword = Holders.getConfig().get("rundeck.security.ldap.bindPassword").toString();
if(bindPassword != null && !"null".equals(bindPassword)) {
_bindPassword = bindPassword;
} else {
_bindPassword = (String) options.get("bindPassword");
}
_authenticationMethod = (String) options.get("authenticationMethod");
_userBaseDn = (String) options.get("userBaseDn");
_roleBaseDn = (String) options.get("roleBaseDn");
if (options.containsKey("forceBindingLogin")) {
_forceBindingLogin = Boolean.parseBoolean((String) options.get("forceBindingLogin"));
}
if (options.containsKey("nestedGroups")) {
_nestedGroups = Boolean.parseBoolean((String) options.get("nestedGroups"));
}
if (options.containsKey("forceBindingLoginUseRootContextForRoles")) {
_forceBindingLoginUseRootContextForRoles = Boolean.parseBoolean((String) options.get("forceBindingLoginUseRootContextForRoles"));
}
_userObjectClass = getOption(options, "userObjectClass", _userObjectClass);
_userRdnAttribute = getOption(options, "userRdnAttribute", _userRdnAttribute);
_userIdAttribute = getOption(options, "userIdAttribute", _userIdAttribute);
_userPasswordAttribute = getOption(options, "userPasswordAttribute", _userPasswordAttribute);
_roleObjectClass = getOption(options, "roleObjectClass", _roleObjectClass);
_roleMemberAttribute = getOption(options, "roleMemberAttribute", _roleMemberAttribute);
_roleUsernameMemberAttribute = getOption(options, "roleUsernameMemberAttribute", _roleUsernameMemberAttribute);
_roleNameAttribute = getOption(options, "roleNameAttribute", _roleNameAttribute);
_debug = Boolean.parseBoolean(String.valueOf(getOption(options, "debug", Boolean
.toString(_debug))));
_ldapsVerifyHostname = Boolean.parseBoolean(String.valueOf(getOption(options, "ldapsVerifyHostname", Boolean
.toString(_ldapsVerifyHostname))));
_rolePrefix = (String) options.get("rolePrefix");
_reportStatistics = Boolean.parseBoolean(String.valueOf(getOption(options, "reportStatistics", Boolean
.toString(_reportStatistics))));
Object supplementalRoles = options.get("supplementalRoles");
if (null != supplementalRoles) {
this._supplementalRoles = new ArrayList<String>();
this._supplementalRoles.addAll(Arrays.asList(supplementalRoles.toString().split(", *")));
}
String cacheDurationSetting = (String) options.get("cacheDurationMillis");
if (cacheDurationSetting != null) {
try {
_cacheDuration = Integer.parseInt(cacheDurationSetting);
} catch (NumberFormatException e) {
LOG.warn("Unable to parse cacheDurationMillis to a number: " + cacheDurationSetting,
". Using default: " + _cacheDuration, e);
}
}
if (options.containsKey("timeoutRead")) {
_timeoutRead = Long.parseLong((String) options.get("timeoutRead"));
}
if (options.containsKey("timeoutConnect")) {
_timeoutConnect = Long.parseLong((String) options.get("timeoutConnect"));
}
}
public boolean commit() throws LoginException {
try {
_rootContext.close();
} catch (NamingException e) {
throw new LoginException("error closing root context: " + e.getMessage());
}
return super.commit();
}
public boolean abort() throws LoginException {
try {
_rootContext.close();
} catch (NamingException e) {
throw new LoginException("error closing root context: " + e.getMessage());
}
return super.abort();
}
@SuppressWarnings("unchecked")
protected String getOption(Map options, String key, String defaultValue) {
Object value = options.get(key);
if (value == null) {
return defaultValue;
}
return (String) value;
}
/**
* get the context for connection
*
* @return
*/
@SuppressWarnings("unchecked")
public Hashtable getEnvironment() {
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, _contextFactory);
String url = null;
if(_providerUrl != null) {
url = _providerUrl;
} else {
if (_hostname != null) {
url = "ldap://" + _hostname + "/";
if (_port != 0) {
url += ":" + _port + "/";
}
LOG.warn("Using hostname and port. Use providerUrl instead: " + url);
}
}
env.put(Context.PROVIDER_URL, url);
if (_authenticationMethod != null) {
env.put(Context.SECURITY_AUTHENTICATION, _authenticationMethod);
}
if (_bindDn != null) {
env.put(Context.SECURITY_PRINCIPAL, _bindDn);
}
if (_bindPassword != null) {
env.put(Context.SECURITY_CREDENTIALS, _bindPassword);
}
env.put("com.sun.jndi.ldap.read.timeout", Long.toString(_timeoutRead));
env.put("com.sun.jndi.ldap.connect.timeout", Long.toString(_timeoutConnect));
// Set the SSLContextFactory to implementation that validates cert subject
if (url != null && url.startsWith("ldaps") && _ldapsVerifyHostname) {
try {
URI uri = new URI(url);
HostnameVerifyingSSLSocketFactory.setTargetHost(uri.getHost());
env.put("java.naming.ldap.factory.socket",
"com.dtolabs.rundeck.jetty.jaas.HostnameVerifyingSSLSocketFactory");
}
catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
return env;
}
private static String convertCredentialLdapToJetty(String encryptedPassword) {
if (encryptedPassword == null) {
return encryptedPassword;
}
if (encryptedPassword.toUpperCase().startsWith("{MD5}")) {
return "MD5:"
+ encryptedPassword.substring("{MD5}".length(), encryptedPassword.length());
}
if (encryptedPassword.toUpperCase().startsWith("{CRYPT}")) {
return "CRYPT:"
+ encryptedPassword.substring("{CRYPT}".length(), encryptedPassword.length());
}
return encryptedPassword;
}
private static final class CachedUserInfo {
public final long expires;
public final UserInfo userInfo;
public CachedUserInfo(UserInfo userInfo, long expires) {
this.userInfo = userInfo;
this.expires = expires;
}
}
}
|
rundeckapp/src/main/groovy/com/dtolabs/rundeck/jetty/jaas/JettyCachingLdapLoginModule.java
|
/*
* Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com)
*
* 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.dtolabs.rundeck.jetty.jaas;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.LoginException;
import grails.boot.config.GrailsAutoConfiguration;
import grails.util.Holders;
import org.eclipse.jetty.jaas.callback.ObjectCallback;
import org.eclipse.jetty.jaas.spi.AbstractLoginModule;
import org.eclipse.jetty.jaas.spi.UserInfo;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.security.Credential;
/**
*
* A LdapLoginModule for use with JAAS setups
*
* The jvm should be started with the following parameter: <br>
* <br>
* <code>
* -Djava.security.auth.login.config=etc/ldap-loginModule.conf
* </code> <br>
* <br>
* and an example of the ldap-loginModule.conf would be: <br>
* <br>
*
* <pre>
* ldaploginmodule {
* com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule required
* debug="true"
* contextFactory="com.sun.jndi.ldap.LdapCtxFactory"
* hostname="ldap.example.com"
* port="389"
* timeoutRead="5000"
* timeoutConnect="30000"
* bindDn="cn=Directory Manager"
* bindPassword="directory"
* authenticationMethod="simple"
* forceBindingLogin="false"
* forceBindingLoginUseRootContextForRoles="false"
* userBaseDn="ou=people,dc=alcatel"
* userRdnAttribute="uid"
* userIdAttribute="uid"
* userPasswordAttribute="userPassword"
* userObjectClass="inetOrgPerson"
* roleBaseDn="ou=groups,dc=example,dc=com"
* roleNameAttribute="cn"
* roleMemberAttribute="uniqueMember"
* roleUsernameMemberAttribute="memberUid"
* roleObjectClass="groupOfUniqueNames"
* rolePrefix="rundeck"
* cacheDurationMillis="500"
* reportStatistics="true"
* nestedGroups="false";
* };
* </pre>
*
* @author Jesse McConnell <a href="mailto:jesse@codehaus.org">jesse@codehaus.org</a>
* @author Frederic Nizery <a href="mailto:frederic.nizery@alcatel-lucent.fr">frederic.nizery@alcatel-lucent.fr</a>
* @author Trygve Laugstol <a href="mailto:trygvis@codehaus.org">trygvis@codehaus.org</a>
* @author Noah Campbell <a href="mailto:noahcampbell@gmail.com">noahcampbell@gmail.com</a>
*/
public class JettyCachingLdapLoginModule extends AbstractLoginModule {
private static final Logger LOG = Log.getLogger(JettyCachingLdapLoginModule.class);
private static final Pattern rolePattern = Pattern.compile("^cn=([^,]+)", Pattern.CASE_INSENSITIVE);
private static final String CRYPT_TYPE = "CRYPT:";
private static final String MD5_TYPE = "MD5:";
protected final String _roleMemberFilter = "member=*";
/**
* Provider URL
*/
protected String _providerUrl;
/**
* Role prefix to remove from ldap group name.
*/
protected String _rolePrefix = "";
/**
* Duration of storing the user in memory.
*/
protected int _cacheDuration = 0;
/**
* hostname of the ldap server
*/
protected String _hostname;
/**
* port of the ldap server
*/
protected int _port = 389;
/**
* Context.SECURITY_AUTHENTICATION
*/
protected String _authenticationMethod;
/**
* Context.INITIAL_CONTEXT_FACTORY
*/
protected String _contextFactory;
/**
* root DN used to connect to
*/
protected String _bindDn;
/**
* password used to connect to the root ldap context
*/
protected String _bindPassword;
/**
* object class of a user
*/
protected String _userObjectClass = "inetOrgPerson";
/**
* attribute that the principal is located
*/
protected String _userRdnAttribute = "uid";
/**
* attribute that the principal is located
*/
protected String _userIdAttribute = "cn";
/**
* name of the attribute that a users password is stored under
* <br>
* NOTE: not always accessible, see force binding login
*/
protected String _userPasswordAttribute = "userPassword";
/**
* base DN where users are to be searched from
*/
protected String _userBaseDn;
/**
* base DN where role membership is to be searched from
*/
protected String _roleBaseDn;
/**
* object class of roles
*/
protected String _roleObjectClass = "groupOfUniqueNames";
/**
* name of the attribute that a user DN would be under a role class
*/
protected String _roleMemberAttribute = "uniqueMember";
/**
* name of the attribute that a username would be under a role class
*/
protected String _roleUsernameMemberAttribute=null;
/**
* the name of the attribute that a role would be stored under
*/
protected String _roleNameAttribute = "roleName";
protected boolean _debug;
protected boolean _ldapsVerifyHostname=true;
/**
* if the getUserInfo can pull a password off of the user then password
* comparison is an option for authn, to force binding login checks, set
* this to true
*/
protected boolean _forceBindingLogin = false;
/**
* if _forceFindingLogin is true, and _forceBindingLoginUseRootContextForRoles
* is true, then role memberships are obtained using _rootContext
*/
protected boolean _forceBindingLoginUseRootContextForRoles = false;
protected DirContext _rootContext;
protected boolean _reportStatistics;
/**
* List of supplemental roles provided in config file that get added to
* all users.
*/
protected List<String> _supplementalRoles;
protected boolean _nestedGroups;
/**
* timeout for LDAP read
*/
protected long _timeoutRead =0;
/**
* timeout for LDAP connection
*/
protected long _timeoutConnect =0;
protected static final ConcurrentHashMap<String, CachedUserInfo> USERINFOCACHE =
new ConcurrentHashMap<String, CachedUserInfo>();
/**
* The number of cache hits for UserInfo objects.
*/
protected static long userInfoCacheHits;
/**
* The number of login attempts for this particular module.
*/
protected static long loginAttempts;
private static ConcurrentHashMap<String, List<String>> roleMemberOfMap;
private static long roleMemberOfMapExpires = 0;
/**
* get the available information about the user
* <br>
* for this LoginModule, the credential can be null which will result in a
* binding ldap authentication scenario
* <br>
* roles are also an optional concept if required
*
* @param username
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public UserInfo getUserInfo(String username) throws Exception {
String pwdCredential = getUserCredentials(username);
if (pwdCredential == null) {
return null;
}
pwdCredential = convertCredentialLdapToJetty(pwdCredential);
pwdCredential = decodeBase64EncodedPwd(pwdCredential);
Credential credential = Credential.getCredential(pwdCredential);
List roles = getUserRoles(_rootContext, username);
return new UserInfo(username, credential, roles);
}
String decodeBase64EncodedPwd(String encoded) {
String chkString = null;
String prefix = "";
if(encoded.startsWith(CRYPT_TYPE)) {
chkString = encoded.substring(CRYPT_TYPE.length(),encoded.length());
prefix = CRYPT_TYPE;
} else if(encoded.startsWith(MD5_TYPE)) {
chkString = encoded.substring(MD5_TYPE.length(), encoded.length());
prefix = MD5_TYPE;
} else {
return encoded; //make no attempt to further decode because we don't know what value this might be
}
return prefix+(isBase64(chkString) ? org.apache.commons.codec.binary.Hex.encodeHexString(org.apache.commons.codec.binary.Base64.decodeBase64(chkString)) : chkString);
}
boolean isBase64(String chkBase64) {
try {
Base64.getDecoder().decode(chkBase64);
return chkBase64.replace(" ","").length() % 4 == 0;
} catch(IllegalArgumentException iaex) {}
return false;
}
protected String doRFC2254Encoding(String inputString) {
StringBuffer buf = new StringBuffer(inputString.length());
for (int i = 0; i < inputString.length(); i++) {
char c = inputString.charAt(i);
switch (c) {
case '\\':
buf.append("\\5c");
break;
case '*':
buf.append("\\2a");
break;
case '(':
buf.append("\\28");
break;
case ')':
buf.append("\\29");
break;
case '\0':
buf.append("\\00");
break;
default:
buf.append(c);
break;
}
}
return buf.toString();
}
/**
* attempts to get the users credentials from the users context
* <p/>
* NOTE: this is not an user authenticated operation
*
* @param username
* @return
* @throws LoginException
*/
@SuppressWarnings("unchecked")
private String getUserCredentials(String username) throws LoginException {
String ldapCredential = null;
SearchControls ctls = new SearchControls();
ctls.setCountLimit(1);
ctls.setDerefLinkFlag(true);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectClass={0})({1}={2}))";
try {
Object[] filterArguments = { _userObjectClass, _userIdAttribute, username };
NamingEnumeration results = _rootContext.search(_userBaseDn, filter, filterArguments,
ctls);
LOG.debug("Found user?: " + results.hasMoreElements());
if (!results.hasMoreElements()) {
throw new LoginException("User not found.");
}
SearchResult result = findUser(username);
Attributes attributes = result.getAttributes();
Attribute attribute = attributes.get(_userPasswordAttribute);
if (attribute != null) {
try {
byte[] value = (byte[]) attribute.get();
ldapCredential = new String(value);
} catch (NamingException e) {
LOG.debug("no password available under attribute: " + _userPasswordAttribute);
}
}
} catch (NamingException e) {
throw new LoginException("Root context binding failure.");
}
LOG.debug("user cred is: " + ldapCredential);
return ldapCredential;
}
/**
* attempts to get the users roles from the root context
*
* NOTE: this is not an user authenticated operation
*
* @param dirContext
* @param username
* @return
* @throws LoginException
*/
@SuppressWarnings("unchecked")
protected List getUserRoles(DirContext dirContext, String username) throws LoginException,
NamingException {
String userDn = _userRdnAttribute + "=" + username + "," + _userBaseDn;
return getUserRolesByDn(dirContext, userDn, username);
}
@SuppressWarnings("unchecked")
private List getUserRolesByDn(DirContext dirContext, String userDn, String username) throws LoginException,
NamingException {
List<String> roleList = new ArrayList<String>();
if (dirContext == null || _roleBaseDn == null || (_roleMemberAttribute == null
&& _roleUsernameMemberAttribute == null)
|| _roleObjectClass == null) {
LOG.warn("JettyCachingLdapLoginModule: No user roles found: roleBaseDn, roleObjectClass and roleMemberAttribute or roleUsernameMemberAttribute must be specified.");
addSupplementalRoles(roleList);
return roleList;
}
String[] attrIDs = { _roleNameAttribute };
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(attrIDs);
ctls.setDerefLinkFlag(true);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectClass={0})({1}={2}))";
final NamingEnumeration results;
if(null!=_roleUsernameMemberAttribute){
Object[] filterArguments = { _roleObjectClass, _roleUsernameMemberAttribute, username };
results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
}else{
Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn };
results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
}
while (results.hasMoreElements()) {
SearchResult result = (SearchResult) results.nextElement();
Attributes attributes = result.getAttributes();
if (attributes == null) {
continue;
}
Attribute roleAttribute = attributes.get(_roleNameAttribute);
if (roleAttribute == null) {
continue;
}
NamingEnumeration roles = roleAttribute.getAll();
while (roles.hasMore()) {
if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
String role = (String) roles.next();
roleList.add(role.replace(_rolePrefix, ""));
} else {
roleList.add((String) roles.next());
}
}
}
addSupplementalRoles(roleList);
if(_nestedGroups) {
roleList = getNestedRoles(dirContext, roleList);
}
if (roleList.size() < 1) {
LOG.warn("JettyCachingLdapLoginModule: User '" + username + "' has no role membership; role query configuration may be incorrect");
}else{
LOG.debug("JettyCachingLdapLoginModule: User '" + username + "' has roles: " + roleList);
}
return roleList;
}
protected void addSupplementalRoles(final List<String> roleList) {
if (null != _supplementalRoles) {
for (String supplementalRole : _supplementalRoles) {
if(null!=supplementalRole&& !"".equals(supplementalRole.trim())){
roleList.add(supplementalRole.trim());
}
}
}
}
private List<String> getNestedRoles(DirContext dirContext, List<String> roleList) {
HashMap<String, List<String>> roleMemberOfMap = new HashMap<String, List<String>>();
roleMemberOfMap.putAll(getRoleMemberOfMap(dirContext));
List<String> mergedList = mergeRoles(roleList, roleMemberOfMap);
return mergedList;
}
private List<String> mergeRoles(List<String> roles, HashMap<String, List<String>> roleMemberOfMap) {
List<String> newRoles = new ArrayList<String>();
List<String> mergedRoles = new ArrayList<String>();
mergedRoles.addAll(roles);
for(String role : roles) {
if(roleMemberOfMap.containsKey(role)) {
for(String newRole : roleMemberOfMap.get(role)) {
if (!roles.contains(newRole)) {
newRoles.add(newRole);
}
}
roleMemberOfMap.remove(role);
}
}
if(!newRoles.isEmpty()) {
mergedRoles.addAll(mergeRoles(newRoles, roleMemberOfMap));
}
return mergedRoles;
}
private ConcurrentHashMap<String, List<String>> getRoleMemberOfMap(DirContext dirContext) {
if (_cacheDuration == 0 || System.currentTimeMillis() > roleMemberOfMapExpires) { // only worry about caching if there is a cacheDuration set.
roleMemberOfMap = buildRoleMemberOfMap(dirContext);
roleMemberOfMapExpires = System.currentTimeMillis() + _cacheDuration;
}
return roleMemberOfMap;
}
private ConcurrentHashMap<String, List<String>> buildRoleMemberOfMap(DirContext dirContext) {
Object[] filterArguments = { _roleObjectClass };
SearchControls ctls = new SearchControls();
ctls.setDerefLinkFlag(true);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
ConcurrentHashMap<String, List<String>> roleMemberOfMap = new ConcurrentHashMap<String, List<String>>();
try {
NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, _roleMemberFilter, ctls);
while (results.hasMoreElements()) {
SearchResult result = results.nextElement();
Attributes attributes = result.getAttributes();
if (attributes == null) {
continue;
}
Attribute roleAttribute = attributes.get(_roleNameAttribute);
Attribute memberAttribute = attributes.get(_roleMemberAttribute);
if (roleAttribute == null || memberAttribute == null) {
continue;
}
NamingEnumeration role = roleAttribute.getAll();
NamingEnumeration members = memberAttribute.getAll();
if(!role.hasMore() || !members.hasMore()) {
continue;
}
String roleName = (String) role.next();
if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
roleName = roleName.replace(_rolePrefix, "");
}
while(members.hasMore()) {
String member = (String) members.next();
Matcher roleMatcher = rolePattern.matcher(member);
if(!roleMatcher.find()) {
continue;
}
String roleMember = roleMatcher.group(1);
List<String> memberOf;
if(roleMemberOfMap.containsKey(roleMember)) {
memberOf = roleMemberOfMap.get(roleMember);
} else {
memberOf = new ArrayList<String>();
}
memberOf.add(roleName);
roleMemberOfMap.put(roleMember, memberOf);
}
}
} catch (NamingException e) {
e.printStackTrace();
}
return roleMemberOfMap;
}
protected boolean isDebug(){
return _debug;
}
/**
* Default behavior to emit to System.err
* @param message message
*/
protected void debug(String message) {
if (isDebug()) {
LOG.debug(message);
}
}
/**
* Gets credentials by calling {@link #getCallBackAuth()}, then performs {@link #authenticate(String, Object)}
*
* @return true if authenticated
* @throws LoginException
*/
@Override
public boolean login() throws LoginException {
try{
Object[] userPass= getCallBackAuth();
if (null == userPass || userPass.length < 2) {
setAuthenticated(false);
} else {
String name = (String) userPass[0];
Object pass = userPass[1];
setAuthenticated(authenticate(name, pass));
}
return isAuthenticated();
} catch (UnsupportedCallbackException e) {
throw new LoginException("Error obtaining callback information.");
} catch (IOException e) {
if (_debug) {
e.printStackTrace();
}
throw new LoginException("IO Error performing login.");
}
}
/**
*
* @return Return the object[] containing username and password, by using the callback mechanism
*
* @throws IOException
* @throws UnsupportedCallbackException
* @throws LoginException
*/
protected Object[] getCallBackAuth() throws IOException, UnsupportedCallbackException, LoginException {
if (getCallbackHandler() == null) {
throw new LoginException("No callback handler");
}
Callback[] callbacks = configureCallbacks();
getCallbackHandler().handle(callbacks);
String webUserName = ((NameCallback) callbacks[0]).getName();
Object webCredential = ((ObjectCallback) callbacks[1]).getObject();
if (webCredential == null) {
webCredential = ((PasswordCallback)callbacks[2]).getPassword();
}
return new Object[]{webUserName,webCredential};
}
/**
* since ldap uses a context bind for valid authentication checking, we
* override login()
* <br>
* if credentials are not available from the users context or if we are
* forcing the binding check then we try a binding authentication check,
* otherwise if we have the users encoded password then we can try
* authentication via that mechanic
* @param webUserName user
* @param webCredential password
*
*
* @return true if authenticated
* @throws LoginException
*/
protected boolean authenticate(final String webUserName, final Object webCredential) throws LoginException {
try {
if (isEmptyOrNull(webUserName) || isEmptyOrNull(webCredential)) {
setAuthenticated(false);
return isAuthenticated();
}
loginAttempts++;
if(_reportStatistics)
{
DecimalFormat percentHit = new DecimalFormat("#.##");
LOG.info("Login attempts: " + loginAttempts + ", Hits: " + userInfoCacheHits +
", Ratio: " + percentHit.format((double)userInfoCacheHits / loginAttempts * 100f) + "%.");
}
if (_forceBindingLogin) {
return bindingLogin(webUserName, webCredential);
}
// This sets read and the credential
UserInfo userInfo = getUserInfo(webUserName);
if (userInfo == null) {
setAuthenticated(false);
return false;
}
JAASUserInfo jaasUserInfo = new JAASUserInfo(userInfo);
jaasUserInfo.fetchRoles(); //must run this otherwise will throw NPE later
setCurrentUser(jaasUserInfo);
if (webCredential instanceof String) {
return credentialLogin(Credential.getCredential((String) webCredential));
}
return credentialLogin(webCredential);
} catch (UnsupportedCallbackException e) {
throw new LoginException("Error obtaining callback information.");
} catch (IOException e) {
if (_debug) {
e.printStackTrace();
}
throw new LoginException("IO Error performing login.");
} catch (Exception e) {
if (_debug) {
e.printStackTrace();
}
throw new LoginException("Error obtaining user info.");
}
}
private boolean isEmptyOrNull(final Object value) {
return null==value || "".equals(value);
}
/**
* password supplied authentication check
*
* @param webCredential
* @return
* @throws LoginException
*/
protected boolean credentialLogin(Object webCredential) throws LoginException {
setAuthenticated(getCurrentUser().checkCredential(webCredential));
return isAuthenticated();
}
/**
* binding authentication check This methode of authentication works only if
* the user branch of the DIT (ldap tree) has an ACI (acces control
* instruction) that allow the access to any user or at least for the user
* that logs in.
*
* @param username
* @param password
* @return
* @throws LoginException
*/
@SuppressWarnings("unchecked")
protected boolean bindingLogin(String username, Object password) throws LoginException,
NamingException {
final String cacheToken = Credential.MD5.digest(username + ":" + password.toString());
if (_cacheDuration > 0) { // only worry about caching if there is a cacheDuration set.
CachedUserInfo cached = USERINFOCACHE.get(cacheToken);
if (cached != null) {
if (System.currentTimeMillis() < cached.expires) {
LOG.debug("Cache Hit for " + username + ".");
userInfoCacheHits++;
setCurrentUser(new JAASUserInfo(cached.userInfo));
setAuthenticated(true);
return true;
} else {
LOG.info("Cache Eviction for " + username + ".");
USERINFOCACHE.remove(cacheToken);
}
} else {
LOG.debug("Cache Miss for " + username + ".");
}
}
SearchResult searchResult = findUser(username);
String userDn = searchResult.getNameInNamespace();
LOG.info("Attempting authentication: " + userDn);
Hashtable environment = getEnvironment();
environment.put(Context.SECURITY_PRINCIPAL, userDn);
environment.put(Context.SECURITY_CREDENTIALS, password);
DirContext dirContext = new InitialDirContext(environment);
// use _rootContext to find roles, if configured to doso
if ( _forceBindingLoginUseRootContextForRoles ) {
dirContext = _rootContext;
LOG.debug("Using _rootContext for role lookup.");
}
List roles = getUserRolesByDn(dirContext, userDn, username);
UserInfo userInfo = new UserInfo(username, null, roles);
if (_cacheDuration > 0) {
USERINFOCACHE.put(cacheToken,
new CachedUserInfo(userInfo,
System.currentTimeMillis() + _cacheDuration));
LOG.debug("Adding " + username + " set to expire: " + System.currentTimeMillis() + _cacheDuration);
}
setCurrentUser(new JAASUserInfo(userInfo));
setAuthenticated(true);
return true;
}
@SuppressWarnings("unchecked")
private SearchResult findUser(String username) throws NamingException, LoginException {
SearchControls ctls = new SearchControls();
ctls.setCountLimit(1);
ctls.setDerefLinkFlag(true);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(objectClass={0})({1}={2}))";
LOG.debug("Searching for users with filter: \'" + filter + "\'" + " from base dn: "
+ _userBaseDn);
Object[] filterArguments = new Object[] { _userObjectClass, _userIdAttribute, username };
NamingEnumeration results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls);
LOG.debug("Found user?: " + results.hasMoreElements());
if (!results.hasMoreElements()) {
throw new LoginException("User not found.");
}
return (SearchResult) results.nextElement();
}
@SuppressWarnings("unchecked")
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
Map<String, ?> options) {
super.initialize(subject, callbackHandler, sharedState, options);
initializeOptions(options);
try {
_rootContext = new InitialDirContext(getEnvironment());
} catch (NamingException ex) {
LOG.warn(ex);
throw new IllegalStateException("Unable to establish root context: "+ex.getMessage());
}
}
public void initializeOptions(final Map options) {
_hostname = (String) options.get("hostname");
if(options.containsKey("port")) {
_port = Integer.parseInt((String) options.get("port"));
}
_providerUrl = (String) options.get("providerUrl");
_contextFactory = (String) options.get("contextFactory");
_bindDn = (String) options.get("bindDn");
String bindPassword = Holders.getConfig().get("rundeck.security.ldap.bindPassword").toString();
if(bindPassword != null && !"null".equals(bindPassword)) {
_bindPassword = bindPassword;
} else {
_bindPassword = (String) options.get("bindPassword");
}
_authenticationMethod = (String) options.get("authenticationMethod");
_userBaseDn = (String) options.get("userBaseDn");
_roleBaseDn = (String) options.get("roleBaseDn");
if (options.containsKey("forceBindingLogin")) {
_forceBindingLogin = Boolean.parseBoolean((String) options.get("forceBindingLogin"));
}
if (options.containsKey("nestedGroups")) {
_nestedGroups = Boolean.parseBoolean((String) options.get("nestedGroups"));
}
if (options.containsKey("forceBindingLoginUseRootContextForRoles")) {
_forceBindingLoginUseRootContextForRoles = Boolean.parseBoolean((String) options.get("forceBindingLoginUseRootContextForRoles"));
}
_userObjectClass = getOption(options, "userObjectClass", _userObjectClass);
_userRdnAttribute = getOption(options, "userRdnAttribute", _userRdnAttribute);
_userIdAttribute = getOption(options, "userIdAttribute", _userIdAttribute);
_userPasswordAttribute = getOption(options, "userPasswordAttribute", _userPasswordAttribute);
_roleObjectClass = getOption(options, "roleObjectClass", _roleObjectClass);
_roleMemberAttribute = getOption(options, "roleMemberAttribute", _roleMemberAttribute);
_roleUsernameMemberAttribute = getOption(options, "roleUsernameMemberAttribute", _roleUsernameMemberAttribute);
_roleNameAttribute = getOption(options, "roleNameAttribute", _roleNameAttribute);
_debug = Boolean.parseBoolean(String.valueOf(getOption(options, "debug", Boolean
.toString(_debug))));
_ldapsVerifyHostname = Boolean.parseBoolean(String.valueOf(getOption(options, "ldapsVerifyHostname", Boolean
.toString(_ldapsVerifyHostname))));
_rolePrefix = (String) options.get("rolePrefix");
_reportStatistics = Boolean.parseBoolean(String.valueOf(getOption(options, "reportStatistics", Boolean
.toString(_reportStatistics))));
Object supplementalRoles = options.get("supplementalRoles");
if (null != supplementalRoles) {
this._supplementalRoles = new ArrayList<String>();
this._supplementalRoles.addAll(Arrays.asList(supplementalRoles.toString().split(", *")));
}
String cacheDurationSetting = (String) options.get("cacheDurationMillis");
if (cacheDurationSetting != null) {
try {
_cacheDuration = Integer.parseInt(cacheDurationSetting);
} catch (NumberFormatException e) {
LOG.warn("Unable to parse cacheDurationMillis to a number: " + cacheDurationSetting,
". Using default: " + _cacheDuration, e);
}
}
if (options.containsKey("timeoutRead")) {
_timeoutRead = Long.parseLong((String) options.get("timeoutRead"));
}
if (options.containsKey("timeoutConnect")) {
_timeoutConnect = Long.parseLong((String) options.get("timeoutConnect"));
}
}
public boolean commit() throws LoginException {
try {
_rootContext.close();
} catch (NamingException e) {
throw new LoginException("error closing root context: " + e.getMessage());
}
return super.commit();
}
public boolean abort() throws LoginException {
try {
_rootContext.close();
} catch (NamingException e) {
throw new LoginException("error closing root context: " + e.getMessage());
}
return super.abort();
}
@SuppressWarnings("unchecked")
protected String getOption(Map options, String key, String defaultValue) {
Object value = options.get(key);
if (value == null) {
return defaultValue;
}
return (String) value;
}
/**
* get the context for connection
*
* @return
*/
@SuppressWarnings("unchecked")
public Hashtable getEnvironment() {
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, _contextFactory);
String url = null;
if(_providerUrl != null) {
url = _providerUrl;
} else {
if (_hostname != null) {
url = "ldap://" + _hostname + "/";
if (_port != 0) {
url += ":" + _port + "/";
}
LOG.warn("Using hostname and port. Use providerUrl instead: " + url);
}
}
env.put(Context.PROVIDER_URL, url);
if (_authenticationMethod != null) {
env.put(Context.SECURITY_AUTHENTICATION, _authenticationMethod);
}
if (_bindDn != null) {
env.put(Context.SECURITY_PRINCIPAL, _bindDn);
}
if (_bindPassword != null) {
env.put(Context.SECURITY_CREDENTIALS, _bindPassword);
}
env.put("com.sun.jndi.ldap.read.timeout", Long.toString(_timeoutRead));
env.put("com.sun.jndi.ldap.connect.timeout", Long.toString(_timeoutConnect));
// Set the SSLContextFactory to implementation that validates cert subject
if (url != null && url.startsWith("ldaps") && _ldapsVerifyHostname) {
try {
URI uri = new URI(url);
HostnameVerifyingSSLSocketFactory.setTargetHost(uri.getHost());
env.put("java.naming.ldap.factory.socket",
"com.dtolabs.rundeck.jetty.jaas.HostnameVerifyingSSLSocketFactory");
}
catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
return env;
}
private static String convertCredentialLdapToJetty(String encryptedPassword) {
if (encryptedPassword == null) {
return encryptedPassword;
}
if (encryptedPassword.toUpperCase().startsWith("{MD5}")) {
return "MD5:"
+ encryptedPassword.substring("{MD5}".length(), encryptedPassword.length());
}
if (encryptedPassword.toUpperCase().startsWith("{CRYPT}")) {
return "CRYPT:"
+ encryptedPassword.substring("{CRYPT}".length(), encryptedPassword.length());
}
return encryptedPassword;
}
private static final class CachedUserInfo {
public final long expires;
public final UserInfo userInfo;
public CachedUserInfo(UserInfo userInfo, long expires) {
this.userInfo = userInfo;
this.expires = expires;
}
}
}
|
Fix #3699. Bind authentication now works. Logger issue is fixed.
|
rundeckapp/src/main/groovy/com/dtolabs/rundeck/jetty/jaas/JettyCachingLdapLoginModule.java
|
Fix #3699. Bind authentication now works. Logger issue is fixed.
|
|
Java
|
apache-2.0
|
2d5241825e17a53ee2b3df915d03bc97295d80bd
| 0
|
delkyd/hawtjms,fusesource/hawtjms,delkyd/hawtjms
|
/**
* 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.fusesource.amqpjms.jms.transactions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import javax.jms.Connection;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import org.apache.activemq.broker.jmx.QueueViewMBean;
import org.fusesource.amqpjms.jms.JmsConnection;
import org.fusesource.amqpjms.jms.JmsConnectionFactory;
import org.fusesource.amqpjms.util.AmqpTestSupport;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test for messages produced inside a local transaction.
*/
public class JmsTransactedProducerTest extends AmqpTestSupport {
@Test(timeout = 60000)
public void testCreateTxSessionAndProducer() throws Exception {
JmsConnectionFactory factory = new JmsConnectionFactory(getBrokerAmqpConnectionURI());
JmsConnection connection = (JmsConnection) factory.createConnection();
assertNotNull(connection);
connection.start();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
assertNotNull(session);
assertTrue(session.getTransacted());
Queue queue = session.createQueue(name.getMethodName());
MessageProducer producer = session.createProducer(queue);
assertNotNull(producer);
connection.close();
}
@Ignore
@Test(timeout = 60000)
public void testTXProducerCommitsAreQueued() throws Exception {
final int MSG_COUNT = 10;
Connection connection = createAmqpConnection();
connection.start();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Session nonTxSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(name.getMethodName());
MessageProducer producer = session.createProducer(queue);
for (int i = 0; i < MSG_COUNT; ++i) {
producer.send(session.createTextMessage());
}
MessageConsumer consumer = nonTxSession.createConsumer(queue);
Message msg = consumer.receive(5000);
assertNull(msg);
QueueViewMBean proxy = getProxyToQueue(name.getMethodName());
session.commit();
assertEquals(MSG_COUNT, proxy.getQueueSize());
connection.close();
}
@Ignore
@Test(timeout = 60000)
public void testTXProducerRollbacksNotQueued() throws Exception {
final int MSG_COUNT = 10;
Connection connection = createAmqpConnection();
connection.start();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Queue queue = session.createQueue(name.getMethodName());
MessageProducer producer = session.createProducer(queue);
for (int i = 0; i < MSG_COUNT; ++i) {
producer.send(session.createTextMessage());
}
QueueViewMBean proxy = getProxyToQueue(name.getMethodName());
session.rollback();
assertEquals(0, proxy.getQueueSize());
connection.close();
}
}
|
amqpjms-client/src/test/java/org/fusesource/amqpjms/jms/transactions/JmsTransactedProducerTest.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.fusesource.amqpjms.jms.transactions;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import javax.jms.Connection;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import org.apache.activemq.broker.jmx.QueueViewMBean;
import org.fusesource.amqpjms.jms.JmsConnection;
import org.fusesource.amqpjms.jms.JmsConnectionFactory;
import org.fusesource.amqpjms.util.AmqpTestSupport;
import org.junit.Ignore;
import org.junit.Test;
/**
* Test for messages produced inside a local transaction.
*/
public class JmsTransactedProducerTest extends AmqpTestSupport {
@Test(timeout = 60000)
public void testCreateTxSessionAndProducer() throws Exception {
JmsConnectionFactory factory = new JmsConnectionFactory(getBrokerAmqpConnectionURI());
JmsConnection connection = (JmsConnection) factory.createConnection();
assertNotNull(connection);
connection.start();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
assertNotNull(session);
assertTrue(session.getTransacted());
Queue queue = session.createQueue(name.getMethodName());
MessageProducer producer = session.createProducer(queue);
assertNotNull(producer);
connection.close();
}
@Test(timeout = 60000)
public void testTXProducerCommitsAreQueued() throws Exception {
final int MSG_COUNT = 10;
Connection connection = createAmqpConnection();
connection.start();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Queue queue = session.createQueue(name.getMethodName());
MessageProducer producer = session.createProducer(queue);
for (int i = 0; i < MSG_COUNT; ++i) {
producer.send(session.createTextMessage());
}
QueueViewMBean proxy = getProxyToQueue(name.getMethodName());
session.commit();
assertEquals(MSG_COUNT, proxy.getQueueSize());
connection.close();
}
@Ignore
@Test(timeout = 60000)
public void testTXProducerRollbacksNotQueued() throws Exception {
final int MSG_COUNT = 10;
Connection connection = createAmqpConnection();
connection.start();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Queue queue = session.createQueue(name.getMethodName());
MessageProducer producer = session.createProducer(queue);
for (int i = 0; i < MSG_COUNT; ++i) {
producer.send(session.createTextMessage());
}
QueueViewMBean proxy = getProxyToQueue(name.getMethodName());
session.rollback();
assertEquals(0, proxy.getQueueSize());
connection.close();
}
}
|
Update test case and add ignore as it now fails.
|
amqpjms-client/src/test/java/org/fusesource/amqpjms/jms/transactions/JmsTransactedProducerTest.java
|
Update test case and add ignore as it now fails.
|
|
Java
|
apache-2.0
|
71f47b1296ef00aa44a3ad9cd3ddfd951fd61ea4
| 0
|
machristie/airavata,apache/airavata,glahiru/airavata,dogless/airavata,hasinitg/airavata,machristie/airavata,glahiru/airavata,jjj117/airavata,dogless/airavata,dogless/airavata,dogless/airavata,gouravshenoy/airavata,dogless/airavata,anujbhan/airavata,hasinitg/airavata,machristie/airavata,gouravshenoy/airavata,hasinitg/airavata,anujbhan/airavata,gouravshenoy/airavata,glahiru/airavata,jjj117/airavata,anujbhan/airavata,anujbhan/airavata,gouravshenoy/airavata,machristie/airavata,machristie/airavata,hasinitg/airavata,jjj117/airavata,apache/airavata,apache/airavata,hasinitg/airavata,gouravshenoy/airavata,apache/airavata,jjj117/airavata,dogless/airavata,apache/airavata,jjj117/airavata,machristie/airavata,hasinitg/airavata,anujbhan/airavata,jjj117/airavata,apache/airavata,anujbhan/airavata,anujbhan/airavata,gouravshenoy/airavata,gouravshenoy/airavata,machristie/airavata,glahiru/airavata,glahiru/airavata,apache/airavata,apache/airavata
|
/*
*
* 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.airavata.xbaya.appwrapper;
import org.apache.airavata.commons.gfac.type.HostDescription;
import org.apache.airavata.registry.api.Registry;
import org.apache.airavata.registry.api.exception.RegistryException;
import org.apache.airavata.schemas.gfac.GlobusHostType;
import org.apache.airavata.xbaya.XBayaEngine;
import org.apache.airavata.xbaya.gui.GridPanel;
import org.apache.airavata.xbaya.gui.XBayaDialog;
import org.apache.airavata.xbaya.gui.XBayaLabel;
import org.apache.airavata.xbaya.gui.XBayaTextField;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.regex.Pattern;
public class HostDescriptionDialog extends JDialog {
private XBayaEngine engine;
private XBayaDialog dialog;
private XBayaTextField hostIdTextField;
private XBayaTextField hostAddressTextField;
private XBayaTextField globusGateKeeperTextField;
private XBayaTextField GridFTPTextField;
private HostDescription hostDescription;
private GlobusHostType globusHostType;
private boolean hostCreated = false;
private boolean isGlobusHostCreated = false;
private Registry registry;
/**
* @param engine XBaya workflow engine
*/
public HostDescriptionDialog(XBayaEngine engine) {
this.engine = engine;
setRegistry(engine.getConfiguration().getJcrComponentRegistry().getRegistry());
initGUI();
}
/**
* Displays the dialog.
*/
public void show() {
this.dialog.show();
}
public void hide() {
this.dialog.hide();
}
private void ok() {
String hostId = this.hostIdTextField.getText();
String hostAddress = this.hostAddressTextField.getText();
String globusGateKeeperEPR = this.globusGateKeeperTextField.getText();
String gridFTP = this.GridFTPTextField.getText();
if((globusGateKeeperEPR != null) || (gridFTP != null)){
isGlobusHostCreated = true;
}
// TODO the logic here
setHostId(hostId);
setHostLocation(hostAddress);
if(globusGateKeeperEPR != null) {
setGlobusGateKeeperEPR(globusGateKeeperEPR);
}
if(gridFTP != null) {
setGridFTPEPR(globusGateKeeperEPR);
}
saveHostDescription();
hide();
}
private void setGlobusGateKeeperEPR(String epr) {
hostDescription.getType().changeType(GlobusHostType.type);
((GlobusHostType)hostDescription.getType()).addGlobusGateKeeperEndPoint(epr);
}
private String[] getGlobusGateKeeperEPR(String epr) {
if (hostDescription.getType() instanceof GlobusHostType) {
return ((GlobusHostType)hostDescription.getType()).getGlobusGateKeeperEndPointArray();
} else {
return null;
}
}
private void setGridFTPEPR(String epr) {
hostDescription.getType().changeType(GlobusHostType.type);
((GlobusHostType)hostDescription.getType()).addGridFTPEndPoint(epr);
}
private String[] getGridFTPEPR() {
if (hostDescription.getType() instanceof GlobusHostType) {
return ((GlobusHostType)hostDescription.getType()).getGridFTPEndPointArray();
} else {
return null;
}
}
/**
* Initializes the GUI.
*/
private void initGUI() {
this.hostIdTextField = new XBayaTextField();
this.hostAddressTextField = new XBayaTextField();
this.globusGateKeeperTextField = new XBayaTextField();
this.GridFTPTextField = new XBayaTextField();
XBayaLabel hostIdLabel = new XBayaLabel("Host ID", this.hostIdTextField);
XBayaLabel hostAddressLabel = new XBayaLabel("Host Address", this.hostAddressTextField);
XBayaLabel globusGateKeeperLabel = new XBayaLabel("Gloubus Gate Keeper Endpoint", this.globusGateKeeperTextField);
XBayaLabel gridFTPLabel = new XBayaLabel("Grid FTP Endpoint", this.GridFTPTextField);
GridPanel infoPanel = new GridPanel();
infoPanel.add(hostIdLabel);
infoPanel.add(this.hostIdTextField);
infoPanel.add(hostAddressLabel);
infoPanel.add(this.hostAddressTextField);
infoPanel.add(globusGateKeeperLabel);
infoPanel.add(globusGateKeeperTextField);
infoPanel.add(gridFTPLabel);
infoPanel.add(this.GridFTPTextField);
infoPanel.layout(4, 2, GridPanel.WEIGHT_NONE, 1);
JButton okButton = new JButton("OK");
okButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
ok();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
hide();
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
this.dialog = new XBayaDialog(this.engine, "New Host Description", infoPanel, buttonPanel);
this.dialog.setDefaultButton(okButton);
}
public String getHostId() {
return getHostDescription().getType().getHostName();
}
public void setHostId(String hostId) {
getHostDescription().getType().setHostName(hostId);
updateDialogStatus();
}
public String getHostLocation() {
return getHostDescription().getType().getHostAddress();
}
public void setHostLocation(String hostLocation) {
getHostDescription().getType().setHostAddress(hostLocation);
updateDialogStatus();
}
private void validateDialog() throws Exception {
if (getHostId() == null || getHostId().trim().equals("")) {
throw new Exception("Id of the host cannot be empty!!!");
}
HostDescription hostDescription2 = null;
try {
hostDescription2 = getRegistry().getHostDescription(Pattern.quote(getHostId()));
} catch (RegistryException e) {
throw e;
}
if (hostDescription2 != null) {
throw new Exception("Host descriptor with the given id already exists!!!");
}
if (getHostLocation() == null || getHostLocation().trim().equals("")) {
throw new Exception("Host location/ip cannot be empty!!!");
}
}
private void updateDialogStatus() {
String message = null;
try {
validateDialog();
} catch (Exception e) {
message = e.getLocalizedMessage();
}
//okButton.setEnabled(message == null);
//setError(message);
}
/* public void close() {
getDialog().setVisible(false);
}*/
public boolean isHostCreated() {
return hostCreated;
}
public void setHostCreated(boolean hostCreated) {
this.hostCreated = hostCreated;
}
public HostDescription getHostDescription() {
if (hostDescription == null) {
if (isGlobusHostCreated) {
hostDescription = new HostDescription(GlobusHostType.type);
} else {
hostDescription = new HostDescription();
}
}
return hostDescription;
}
public void saveHostDescription() {
getRegistry().saveHostDescription(getHostDescription());
setHostCreated(true);
}
/* private void setError(String errorMessage) {
if (errorMessage == null || errorMessage.trim().equals("")) {
lblError.setText("");
} else {
lblError.setText(errorMessage.trim());
}
}*/
public Registry getRegistry() {
return registry;
}
public void setRegistry(Registry registry) {
this.registry = registry;
}
}
|
modules/xbaya-gui/src/main/java/org/apache/airavata/xbaya/appwrapper/HostDescriptionDialog.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.airavata.xbaya.appwrapper;
import org.apache.airavata.commons.gfac.type.HostDescription;
import org.apache.airavata.registry.api.Registry;
import org.apache.airavata.registry.api.exception.RegistryException;
import org.apache.airavata.schemas.gfac.GlobusHostType;
import org.apache.airavata.xbaya.XBayaEngine;
import org.apache.airavata.xbaya.gui.GridPanel;
import org.apache.airavata.xbaya.gui.XBayaDialog;
import org.apache.airavata.xbaya.gui.XBayaLabel;
import org.apache.airavata.xbaya.gui.XBayaTextField;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.regex.Pattern;
public class HostDescriptionDialog extends JDialog {
private XBayaEngine engine;
private XBayaDialog dialog;
private XBayaTextField hostIdTextField;
private XBayaTextField hostAddressTextField;
private XBayaTextField globusGateKeeperTextField;
private XBayaTextField GridFTPTextField;
private HostDescription hostDescription;
private GlobusHostType globusHostType;
private boolean hostCreated = false;
private boolean isGlobusHostCreated = false;
private Registry registry;
/**
* @param engine XBaya workflow engine
*/
public HostDescriptionDialog(XBayaEngine engine) {
this.engine = engine;
setRegistry(engine.getConfiguration().getJcrComponentRegistry().getRegistry());
initGUI();
}
/**
* Displays the dialog.
*/
public void show() {
this.dialog.show();
}
public void hide() {
this.dialog.hide();
}
private void ok() {
String hostId = this.hostIdTextField.getText();
String hostAddress = this.hostAddressTextField.getText();
String globusGateKeeperEPR = this.globusGateKeeperTextField.getText();
String gridFTP = this.GridFTPTextField.getText();
if((globusGateKeeperEPR != null) || (gridFTP != null)){
isGlobusHostCreated = true;
}
// TODO the logic here
setHostId(hostId);
setHostLocation(hostAddress);
if(globusGateKeeperEPR != null) {
setGlobusGateKeeperEPR(globusGateKeeperEPR);
}
if(gridFTP != null) {
setGridFTPEPR(globusGateKeeperEPR);
}
saveHostDescription();
hide();
}
private void setGlobusGateKeeperEPR(String epr) {
hostDescription.getType().changeType(GlobusHostType.type);
((GlobusHostType)hostDescription.getType()).addGlobusGateKeeperEndPoint(epr);
}
private String[] getGlobusGateKeeperEPR(String epr) {
if (hostDescription.getType() instanceof GlobusHostType) {
return ((GlobusHostType)hostDescription.getType()).getGlobusGateKeeperEndPointArray();
} else {
return null;
}
}
private void setGridFTPEPR(String epr) {
hostDescription.getType().changeType(GlobusHostType.type);
((GlobusHostType)hostDescription.getType()).addGridFTPEndPoint(epr);
}
private String[] getGridFTPEPR(String epr) {
if (hostDescription.getType() == GlobusHostType.type) {
return ((GlobusHostType)hostDescription).getGridFTPEndPointArray();
} else {
return null;
}
}
/**
* Initializes the GUI.
*/
private void initGUI() {
this.hostIdTextField = new XBayaTextField();
this.hostAddressTextField = new XBayaTextField();
this.globusGateKeeperTextField = new XBayaTextField();
this.GridFTPTextField = new XBayaTextField();
XBayaLabel hostIdLabel = new XBayaLabel("Host ID", this.hostIdTextField);
XBayaLabel hostAddressLabel = new XBayaLabel("Host Address", this.hostAddressTextField);
XBayaLabel globusGateKeeperLabel = new XBayaLabel("Gloubus Gate Keeper Endpoint", this.globusGateKeeperTextField);
XBayaLabel gridFTPLabel = new XBayaLabel("Grid FTP Endpoint", this.GridFTPTextField);
GridPanel infoPanel = new GridPanel();
infoPanel.add(hostIdLabel);
infoPanel.add(this.hostIdTextField);
infoPanel.add(hostAddressLabel);
infoPanel.add(this.hostAddressTextField);
infoPanel.add(globusGateKeeperLabel);
infoPanel.add(globusGateKeeperTextField);
infoPanel.add(gridFTPLabel);
infoPanel.add(this.GridFTPTextField);
infoPanel.layout(4, 2, GridPanel.WEIGHT_NONE, 1);
JButton okButton = new JButton("OK");
okButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
ok();
}
});
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
hide();
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
this.dialog = new XBayaDialog(this.engine, "New Host Description", infoPanel, buttonPanel);
this.dialog.setDefaultButton(okButton);
}
public String getHostId() {
return getHostDescription().getType().getHostName();
}
public void setHostId(String hostId) {
getHostDescription().getType().setHostName(hostId);
updateDialogStatus();
}
public String getHostLocation() {
return getHostDescription().getType().getHostAddress();
}
public void setHostLocation(String hostLocation) {
getHostDescription().getType().setHostAddress(hostLocation);
updateDialogStatus();
}
private void validateDialog() throws Exception {
if (getHostId() == null || getHostId().trim().equals("")) {
throw new Exception("Id of the host cannot be empty!!!");
}
HostDescription hostDescription2 = null;
try {
hostDescription2 = getRegistry().getHostDescription(Pattern.quote(getHostId()));
} catch (RegistryException e) {
throw e;
}
if (hostDescription2 != null) {
throw new Exception("Host descriptor with the given id already exists!!!");
}
if (getHostLocation() == null || getHostLocation().trim().equals("")) {
throw new Exception("Host location/ip cannot be empty!!!");
}
}
private void updateDialogStatus() {
String message = null;
try {
validateDialog();
} catch (Exception e) {
message = e.getLocalizedMessage();
}
//okButton.setEnabled(message == null);
//setError(message);
}
/* public void close() {
getDialog().setVisible(false);
}*/
public boolean isHostCreated() {
return hostCreated;
}
public void setHostCreated(boolean hostCreated) {
this.hostCreated = hostCreated;
}
public HostDescription getHostDescription() {
if (hostDescription == null) {
if (isGlobusHostCreated) {
hostDescription = new HostDescription(GlobusHostType.type);
} else {
hostDescription = new HostDescription();
}
}
return hostDescription;
}
public void saveHostDescription() {
getRegistry().saveHostDescription(getHostDescription());
setHostCreated(true);
}
/* private void setError(String errorMessage) {
if (errorMessage == null || errorMessage.trim().equals("")) {
lblError.setText("");
} else {
lblError.setText(errorMessage.trim());
}
}*/
public Registry getRegistry() {
return registry;
}
public void setRegistry(Registry registry) {
this.registry = registry;
}
}
|
fixing some methods.
git-svn-id: 64c7115bac0e45f25b6ef7317621bf38f6d5f89e@1205446 13f79535-47bb-0310-9956-ffa450edef68
|
modules/xbaya-gui/src/main/java/org/apache/airavata/xbaya/appwrapper/HostDescriptionDialog.java
|
fixing some methods.
|
|
Java
|
apache-2.0
|
729c9dd85ab3c02097eaa97a55fd514fc3b8d76e
| 0
|
industrial-data-space/trusted-connector,industrial-data-space/trusted-connector,industrial-data-space/trusted-connector,industrial-data-space/trusted-connector,industrial-data-space/trusted-connector,industrial-data-space/trusted-connector
|
/*-
* ========================LICENSE_START=================================
* LUCON Data Flow Policy Engine
* %%
* Copyright (C) 2017 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.ids.dataflowcontrol.lucon;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import alice.tuprolog.InvalidTheoryException;
import alice.tuprolog.MalformedGoalException;
import alice.tuprolog.NoMoreSolutionException;
import alice.tuprolog.Prolog;
import alice.tuprolog.SolveInfo;
import alice.tuprolog.Theory;
/**
* LUCON (Logic based Usage Control) policy decision engine.
*
* This engine uses tuProlog as a logic language implementation to answer policy
* decision requests.
*
* @author Julian Schuette (julian.schuette@aisec.fraunhofer.de)
*
*/
public class LuconEngine {
private static final Logger LOG = LoggerFactory.getLogger(LuconEngine.class);
Prolog p;
public LuconEngine(OutputStream out) {
p = new Prolog();
// Add some listeners for logging/debugging
p.addExceptionListener(ex -> LOG.error("Exception in Prolog reasoning: " + ex.getMsg()));
p.addQueryListener(q -> LOG.trace("Prolog query " + q.getSolveInfo().getQuery().toString()));
p.addSpyListener(l -> LOG.trace(l.getMsg() + " " + l.getSource()));
p.addWarningListener(w -> {if (!w.getMsg().contains("The predicate false/0 is unknown")) LOG.warn(w.getMsg());});
p.addOutputListener(l -> {
if (out!=null) {
try {
out.write(l.getMsg().getBytes());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
});
}
public void setSpy(boolean spy) {
p.setSpy(spy);
}
/**
* Loads a policy in form of a prolog theory.
*
* Existing policies will be overwritten.
*
* @param is
* @throws InvalidTheoryException
* @throws IOException
*/
public void loadPolicy(InputStream is) throws InvalidTheoryException, IOException {
Theory t = new Theory(is);
LOG.debug("Loading theory: " + t.toString());
p.setTheory(t);
}
public List<SolveInfo> query(String query, boolean findAll) throws NoMoreSolutionException, MalformedGoalException {
List<SolveInfo> result = new ArrayList<>();
SolveInfo solution = p.solve(query);
while (solution.isSuccess()) {
result.add(solution);
if (findAll & p.hasOpenAlternatives()) {
solution = p.solveNext();
} else {
break;
}
}
p.solveEnd();
return result;
}
public String getTheory() {
return p.getTheory().toString();
}
public String getTheoryAsJSON() {
return p.getTheory().toJSON();
}
}
|
ids-dataflow-control/src/main/java/de/fhg/ids/dataflowcontrol/lucon/LuconEngine.java
|
/*-
* ========================LICENSE_START=================================
* LUCON Data Flow Policy Engine
* %%
* Copyright (C) 2017 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.ids.dataflowcontrol.lucon;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import alice.tuprolog.InvalidTheoryException;
import alice.tuprolog.MalformedGoalException;
import alice.tuprolog.NoMoreSolutionException;
import alice.tuprolog.Prolog;
import alice.tuprolog.SolveInfo;
import alice.tuprolog.Theory;
/**
* LUCON (Logic based Usage Control) policy decision engine.
*
* This engine uses tuProlog as a logic language implementation to answer policy
* decision requests.
*
* @author Julian Schuette (julian.schuette@aisec.fraunhofer.de)
*
*/
public class LuconEngine {
private static final Logger LOG = LoggerFactory.getLogger(LuconEngine.class);
Prolog p;
public LuconEngine(OutputStream out) {
p = new Prolog();
// Add some listeners for logging/debugging
p.addExceptionListener(ex -> LOG.error("Exception in Prolog reasoning: " + ex.getMsg()));
p.addQueryListener(q -> LOG.trace("Prolog query " + q.getSolveInfo().getQuery().toString()));
p.addSpyListener(l -> LOG.trace(l.getMsg() + " " + l.getSource()));
p.addWarningListener(w -> LOG.warn(w.getMsg()));
p.addOutputListener(l -> {
if (out!=null) {
try {
out.write(l.getMsg().getBytes());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
});
}
public void setSpy(boolean spy) {
p.setSpy(spy);
}
/**
* Loads a policy in form of a prolog theory.
*
* Existing policies will be overwritten.
*
* @param is
* @throws InvalidTheoryException
* @throws IOException
*/
public void loadPolicy(InputStream is) throws InvalidTheoryException, IOException {
Theory t = new Theory(is);
LOG.debug("Loading theory: " + t.toString());
p.setTheory(t);
}
public List<SolveInfo> query(String query, boolean findAll) throws NoMoreSolutionException, MalformedGoalException {
List<SolveInfo> result = new ArrayList<>();
SolveInfo solution = p.solve(query);
while (solution.isSuccess()) {
result.add(solution);
if (findAll & p.hasOpenAlternatives()) {
solution = p.solveNext();
} else {
break;
}
}
p.solveEnd();
return result;
}
public String getTheory() {
return p.getTheory().toString();
}
public String getTheoryAsJSON() {
return p.getTheory().toJSON();
}
}
|
Log: Removed uncritical warning from Lucon outputs
|
ids-dataflow-control/src/main/java/de/fhg/ids/dataflowcontrol/lucon/LuconEngine.java
|
Log: Removed uncritical warning from Lucon outputs
|
|
Java
|
bsd-3-clause
|
9c1bcca9bd5a69de5b6ea5cf196a0519efa9fbce
| 0
|
dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk
|
/*
* Copyright (c) 2016, University of Oslo
*
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.client.sdk.android.api.network;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import org.hisp.dhis.client.sdk.android.dataelement.DataElementApiClientImpl;
import org.hisp.dhis.client.sdk.android.dataelement.DataElementApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.event.EventApiClientImpl;
import org.hisp.dhis.client.sdk.android.event.EventApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.optionset.OptionSetApiClientImpl;
import org.hisp.dhis.client.sdk.android.optionset.OptionSetApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.organisationunit.OrganisationUnitApiClientImpl;
import org.hisp.dhis.client.sdk.android.organisationunit.OrganisationUnitApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramIndicatorApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramIndicatorApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramRuleActionApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramRuleActionApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramRuleApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramRuleApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramRuleVariableApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramRuleVariableApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramStageApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramStageApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramStageDataElementApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramStageDataElementApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramStageSectionApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramStageSectionApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.systeminfo.SystemInfoApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.trackedentity.TrackedEntityAttributeApiClientImpl;
import org.hisp.dhis.client.sdk.android.trackedentity.TrackedEntityAttributeApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.user.UserAccountApiClientImpl;
import org.hisp.dhis.client.sdk.android.user.UserApiClientRetrofit;
import org.hisp.dhis.client.sdk.core.common.network.Configuration;
import org.hisp.dhis.client.sdk.core.common.network.NetworkModule;
import org.hisp.dhis.client.sdk.core.common.network.UserCredentials;
import org.hisp.dhis.client.sdk.core.common.preferences.PreferencesModule;
import org.hisp.dhis.client.sdk.core.common.preferences.UserPreferences;
import org.hisp.dhis.client.sdk.core.dataelement.DataElementApiClient;
import org.hisp.dhis.client.sdk.core.event.EventApiClient;
import org.hisp.dhis.client.sdk.core.optionset.OptionSetApiClient;
import org.hisp.dhis.client.sdk.core.organisationunit.OrganisationUnitApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramIndicatorApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramRuleActionApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramRuleApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramRuleVariableApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramStageApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramStageDataElementApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramStageSectionApiClient;
import org.hisp.dhis.client.sdk.core.systeminfo.SystemInfoApiClient;
import org.hisp.dhis.client.sdk.core.trackedentity.TrackedEntityAttributeApiClient;
import org.hisp.dhis.client.sdk.core.user.UserApiClient;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.concurrent.TimeUnit;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import static android.text.TextUtils.isEmpty;
import static okhttp3.Credentials.basic;
// Find a way to organize session
public class NetworkModuleImpl implements NetworkModule {
private static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s
private static final int DEFAULT_READ_TIMEOUT_MILLIS = 20 * 1000; // 20s
private static final int DEFAULT_WRITE_TIMEOUT_MILLIS = 20 * 1000; // 20s
private final OrganisationUnitApiClient organisationUnitApiClient;
private final SystemInfoApiClient systemInfoApiClient;
private final ProgramApiClient programApiClient;
private final ProgramStageApiClient programStageApiClient;
private final ProgramStageSectionApiClient programStageSectionApiClient;
private final ProgramRuleApiClient programRuleApiClient;
private final ProgramRuleActionApiClient programRuleActionApiClient;
private final ProgramRuleVariableApiClient programRuleVariableApiClient;
private final ProgramIndicatorApiClient programIndicatorApiClient;
private final UserApiClient userApiClient;
private final EventApiClient eventApiClient;
private final DataElementApiClient dataElementApiClient;
private final ProgramStageDataElementApiClient programStageDataElementApiClient;
private final OptionSetApiClient optionSetApiClient;
private final TrackedEntityAttributeApiClient trackedEntityAttributeApiClient;
public NetworkModuleImpl(PreferencesModule preferencesModule, OkHttpClient okClient) {
AuthInterceptor authInterceptor = new AuthInterceptor(
preferencesModule.getUserPreferences());
OkHttpClient okHttpClient = okClient.newBuilder()
.addInterceptor(authInterceptor)
.connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.readTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.build();
// Constructing jackson's object mapper
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.disable(
MapperFeature.AUTO_DETECT_CREATORS, MapperFeature.AUTO_DETECT_FIELDS,
MapperFeature.AUTO_DETECT_GETTERS, MapperFeature.AUTO_DETECT_IS_GETTERS,
MapperFeature.AUTO_DETECT_SETTERS);
// Extracting base url
Configuration configuration = preferencesModule
.getConfigurationPreferences().get();
HttpUrl url = HttpUrl.parse(configuration.getServerUrl())
.newBuilder()
.addPathSegment("api")
.build();
HttpUrl modifiedUrl = HttpUrl.parse(url.toString() + "/"); // TODO EW!!!
// Creating retrofit instance
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(modifiedUrl)
.client(okHttpClient)
.addConverterFactory(JacksonConverterFactory.create(mapper))
.build();
programApiClient = new ProgramApiClientImpl(retrofit.create(
ProgramApiClientRetrofit.class));
programStageApiClient = new ProgramStageApiClientImpl(retrofit.create(
ProgramStageApiClientRetrofit.class));
programStageSectionApiClient = new ProgramStageSectionApiClientImpl(
retrofit.create(ProgramStageSectionApiClientRetrofit.class));
programRuleApiClient = new ProgramRuleApiClientImpl(retrofit.create(
ProgramRuleApiClientRetrofit.class));
programRuleActionApiClient = new ProgramRuleActionApiClientImpl(
retrofit.create(ProgramRuleActionApiClientRetrofit.class));
programRuleVariableApiClient = new ProgramRuleVariableApiClientImpl(retrofit.create(
ProgramRuleVariableApiClientRetrofit.class));
programIndicatorApiClient = new ProgramIndicatorApiClientImpl(
retrofit.create(ProgramIndicatorApiClientRetrofit.class));
systemInfoApiClient = new org.hisp.dhis.client.sdk.android.systeminfo
.SystemInfoApiClientImpl(retrofit.create(
SystemInfoApiClientRetrofit.class));
userApiClient = new UserAccountApiClientImpl(retrofit.create(
UserApiClientRetrofit.class));
organisationUnitApiClient = new OrganisationUnitApiClientImpl(retrofit.create(
OrganisationUnitApiClientRetrofit.class));
eventApiClient = new EventApiClientImpl(retrofit.create(
EventApiClientRetrofit.class));
dataElementApiClient = new DataElementApiClientImpl(retrofit.create(
DataElementApiClientRetrofit.class));
programStageDataElementApiClient = new ProgramStageDataElementApiClientImpl(retrofit.create(
ProgramStageDataElementApiClientRetrofit.class));
optionSetApiClient = new OptionSetApiClientImpl(retrofit.create(
OptionSetApiClientRetrofit.class));
trackedEntityAttributeApiClient = new TrackedEntityAttributeApiClientImpl(retrofit.create(
TrackedEntityAttributeApiClientRetrofit.class));
}
@Override
public SystemInfoApiClient getSystemInfoApiClient() {
return systemInfoApiClient;
}
@Override
public ProgramApiClient getProgramApiClient() {
return programApiClient;
}
@Override
public ProgramStageApiClient getProgramStageApiClient() {
return programStageApiClient;
}
@Override
public ProgramStageSectionApiClient getProgramStageSectionApiClient() {
return programStageSectionApiClient;
}
@Override
public OrganisationUnitApiClient getOrganisationUnitApiClient() {
return organisationUnitApiClient;
}
@Override
public UserApiClient getUserApiClient() {
return userApiClient;
}
@Override
public EventApiClient getEventApiClient() {
return eventApiClient;
}
@Override
public DataElementApiClient getDataElementApiClient() {
return dataElementApiClient;
}
@Override
public ProgramStageDataElementApiClient getProgramStageDataElementApiClient() {
return programStageDataElementApiClient;
}
@Override
public OptionSetApiClient getOptionSetApiClient() {
return optionSetApiClient;
}
@Override
public TrackedEntityAttributeApiClient getTrackedEntityAttributeApiClient() {
return trackedEntityAttributeApiClient;
}
@Override
public ProgramRuleApiClient getProgramRuleApiClient() {
return programRuleApiClient;
}
@Override
public ProgramRuleActionApiClient getProgramRuleActionApiClient() {
return programRuleActionApiClient;
}
@Override
public ProgramRuleVariableApiClient getProgramRuleVariableApiClient() {
return programRuleVariableApiClient;
}
@Override
public ProgramIndicatorApiClient getProgramIndicatorApiClient() {
return programIndicatorApiClient;
}
private static class AuthInterceptor implements Interceptor {
private final UserPreferences mUserPreferences;
public AuthInterceptor(UserPreferences preferences) {
mUserPreferences = preferences;
}
@Override
public Response intercept(Chain chain) throws IOException {
UserCredentials userCredentials = mUserPreferences.get();
if (isEmpty(userCredentials.getUsername()) ||
isEmpty(userCredentials.getPassword())) {
return chain.proceed(chain.request());
}
String base64Credentials = basic(
userCredentials.getUsername(),
userCredentials.getPassword());
Request request = chain.request().newBuilder()
.addHeader("Authorization", base64Credentials)
.build();
Response response = chain.proceed(request);
if (mUserPreferences.isUserConfirmed()) {
if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
mUserPreferences.invalidateUser();
}
} else {
if (response.isSuccessful()) {
mUserPreferences.confirmUser();
} else {
mUserPreferences.clear();
}
}
return response;
}
}
}
|
core-android/src/main/java/org/hisp/dhis/client/sdk/android/api/network/NetworkModuleImpl.java
|
/*
* Copyright (c) 2016, University of Oslo
*
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.client.sdk.android.api.network;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import org.hisp.dhis.client.sdk.android.dataelement.DataElementApiClientImpl;
import org.hisp.dhis.client.sdk.android.dataelement.DataElementApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.event.EventApiClientImpl;
import org.hisp.dhis.client.sdk.android.event.EventApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.optionset.OptionSetApiClientImpl;
import org.hisp.dhis.client.sdk.android.optionset.OptionSetApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.organisationunit.OrganisationUnitApiClientImpl;
import org.hisp.dhis.client.sdk.android.organisationunit.OrganisationUnitApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramIndicatorApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramIndicatorApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramRuleActionApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramRuleActionApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramRuleApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramRuleApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramRuleVariableApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramRuleVariableApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramStageApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramStageApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramStageDataElementApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramStageDataElementApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.program.ProgramStageSectionApiClientImpl;
import org.hisp.dhis.client.sdk.android.program.ProgramStageSectionApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.systeminfo.SystemInfoApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.trackedentity.TrackedEntityAttributeApiClientImpl;
import org.hisp.dhis.client.sdk.android.trackedentity.TrackedEntityAttributeApiClientRetrofit;
import org.hisp.dhis.client.sdk.android.user.UserAccountApiClientImpl;
import org.hisp.dhis.client.sdk.android.user.UserApiClientRetrofit;
import org.hisp.dhis.client.sdk.core.common.network.Configuration;
import org.hisp.dhis.client.sdk.core.common.network.NetworkModule;
import org.hisp.dhis.client.sdk.core.common.network.UserCredentials;
import org.hisp.dhis.client.sdk.core.common.preferences.PreferencesModule;
import org.hisp.dhis.client.sdk.core.common.preferences.UserPreferences;
import org.hisp.dhis.client.sdk.core.dataelement.DataElementApiClient;
import org.hisp.dhis.client.sdk.core.event.EventApiClient;
import org.hisp.dhis.client.sdk.core.optionset.OptionSetApiClient;
import org.hisp.dhis.client.sdk.core.organisationunit.OrganisationUnitApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramIndicatorApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramRuleActionApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramRuleApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramRuleVariableApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramStageApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramStageDataElementApiClient;
import org.hisp.dhis.client.sdk.core.program.ProgramStageSectionApiClient;
import org.hisp.dhis.client.sdk.core.systeminfo.SystemInfoApiClient;
import org.hisp.dhis.client.sdk.core.trackedentity.TrackedEntityAttributeApiClient;
import org.hisp.dhis.client.sdk.core.user.UserApiClient;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.concurrent.TimeUnit;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import static android.text.TextUtils.isEmpty;
import static okhttp3.Credentials.basic;
// Find a way to organize session
public class NetworkModuleImpl implements NetworkModule {
private static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s
private static final int DEFAULT_READ_TIMEOUT_MILLIS = 20 * 1000; // 20s
private static final int DEFAULT_WRITE_TIMEOUT_MILLIS = 20 * 1000; // 20s
private final OrganisationUnitApiClient organisationUnitApiClient;
private final SystemInfoApiClient systemInfoApiClient;
private final ProgramApiClient programApiClient;
private final ProgramStageApiClient programStageApiClient;
private final ProgramStageSectionApiClient programStageSectionApiClient;
private final ProgramRuleApiClient programRuleApiClient;
private final ProgramRuleActionApiClient programRuleActionApiClient;
private final ProgramRuleVariableApiClient programRuleVariableApiClient;
private final ProgramIndicatorApiClient programIndicatorApiClient;
private final UserApiClient userApiClient;
private final EventApiClient eventApiClient;
private final DataElementApiClient dataElementApiClient;
private final ProgramStageDataElementApiClient programStageDataElementApiClient;
private final OptionSetApiClient optionSetApiClient;
private final TrackedEntityAttributeApiClient trackedEntityAttributeApiClient;
public NetworkModuleImpl(PreferencesModule preferencesModule, OkHttpClient okClient) {
AuthInterceptor authInterceptor = new AuthInterceptor(
preferencesModule.getUserPreferences());
OkHttpClient okHttpClient = okClient.newBuilder()
.addInterceptor(authInterceptor)
.connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.readTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
.build();
// Constructing jackson's object mapper
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.disable(
MapperFeature.AUTO_DETECT_CREATORS, MapperFeature.AUTO_DETECT_FIELDS,
MapperFeature.AUTO_DETECT_GETTERS, MapperFeature.AUTO_DETECT_IS_GETTERS,
MapperFeature.AUTO_DETECT_SETTERS);
// Extracting base url
Configuration configuration = preferencesModule
.getConfigurationPreferences().get();
HttpUrl url = HttpUrl.parse(configuration.getServerUrl())
.newBuilder()
.addPathSegment("api")
.build();
HttpUrl modifiedUrl = HttpUrl.parse(url.toString() + "/"); // TODO EW!!!
// Creating retrofit instance
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(modifiedUrl)
.client(okHttpClient)
.addConverterFactory(JacksonConverterFactory.create(mapper))
.build();
programApiClient = new ProgramApiClientImpl(retrofit.create(
ProgramApiClientRetrofit.class));
programStageApiClient = new ProgramStageApiClientImpl(retrofit.create(
ProgramStageApiClientRetrofit.class));
programStageSectionApiClient = new ProgramStageSectionApiClientImpl(
retrofit.create(ProgramStageSectionApiClientRetrofit.class));
programRuleApiClient = new ProgramRuleApiClientImpl(retrofit.create(
ProgramRuleApiClientRetrofit.class));
programRuleActionApiClient = new ProgramRuleActionApiClientImpl(
retrofit.create(ProgramRuleActionApiClientRetrofit.class));
programRuleVariableApiClient = new ProgramRuleVariableApiClientImpl(retrofit.create(
ProgramRuleVariableApiClientRetrofit.class));
programIndicatorApiClient = new ProgramIndicatorApiClientImpl(
retrofit.create(ProgramIndicatorApiClientRetrofit.class));
systemInfoApiClient = new org.hisp.dhis.client.sdk.android.systeminfo
.SystemInfoApiClientImpl(retrofit.create(
SystemInfoApiClientRetrofit.class));
userApiClient = new UserAccountApiClientImpl(retrofit.create(
UserApiClientRetrofit.class));
organisationUnitApiClient = new OrganisationUnitApiClientImpl(retrofit.create(
OrganisationUnitApiClientRetrofit.class));
eventApiClient = new EventApiClientImpl(retrofit.create(
EventApiClientRetrofit.class));
dataElementApiClient = new DataElementApiClientImpl(retrofit.create(
DataElementApiClientRetrofit.class));
programStageDataElementApiClient = new ProgramStageDataElementApiClientImpl(retrofit.create(
ProgramStageDataElementApiClientRetrofit.class));
optionSetApiClient = new OptionSetApiClientImpl(retrofit.create(
OptionSetApiClientRetrofit.class));
trackedEntityAttributeApiClient = new TrackedEntityAttributeApiClientImpl(retrofit.create(
TrackedEntityAttributeApiClientRetrofit.class));
}
@Override
public SystemInfoApiClient getSystemInfoApiClient() {
return systemInfoApiClient;
}
@Override
public ProgramApiClient getProgramApiClient() {
return programApiClient;
}
@Override
public ProgramStageApiClient getProgramStageApiClient() {
return programStageApiClient;
}
@Override
public ProgramStageSectionApiClient getProgramStageSectionApiClient() {
return programStageSectionApiClient;
}
@Override
public OrganisationUnitApiClient getOrganisationUnitApiClient() {
return organisationUnitApiClient;
}
@Override
public UserApiClient getUserApiClient() {
return userApiClient;
}
@Override
public EventApiClient getEventApiClient() {
return eventApiClient;
}
@Override
public DataElementApiClient getDataElementApiClient() {
return dataElementApiClient;
}
@Override
public ProgramStageDataElementApiClient getProgramStageDataElementApiClient() {
return programStageDataElementApiClient;
}
@Override
public OptionSetApiClient getOptionSetApiClient() {
return optionSetApiClient;
}
@Override
public TrackedEntityAttributeApiClient getTrackedEntityAttributeApiClient() {
return trackedEntityAttributeApiClient;
}
@Override
public ProgramRuleApiClient getProgramRuleApiClient() {
return programRuleApiClient;
}
@Override
public ProgramRuleActionApiClient getProgramRuleActionApiClient() {
return programRuleActionApiClient;
}
@Override
public ProgramRuleVariableApiClient getProgramRuleVariableApiClient() {
return programRuleVariableApiClient;
}
@Override
public ProgramIndicatorApiClient getProgramIndicatorApiClient() {
return programIndicatorApiClient;
}
private static class AuthInterceptor implements Interceptor {
private final UserPreferences mUserPreferences;
public AuthInterceptor(UserPreferences preferences) {
mUserPreferences = preferences;
}
@Override
public Response intercept(Chain chain) throws IOException {
UserCredentials userCredentials = mUserPreferences.get();
if (isEmpty(userCredentials.getUsername()) ||
isEmpty(userCredentials.getPassword())) {
return chain.proceed(chain.request());
}
String base64Credentials = basic(
userCredentials.getUsername(),
userCredentials.getPassword());
Request request = chain.request().newBuilder()
.addHeader("Authorization", base64Credentials)
.build();
Response response = chain.proceed(request);
if (!response.isSuccessful() &&
response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
if (mUserPreferences.isUserConfirmed()) {
// invalidate existing user
mUserPreferences.invalidateUser();
} else {
// remove username/password
mUserPreferences.clear();
}
} else {
if (!mUserPreferences.isUserConfirmed()) {
mUserPreferences.confirmUser();
}
}
return response;
}
}
}
|
Simplified authentication logic
|
core-android/src/main/java/org/hisp/dhis/client/sdk/android/api/network/NetworkModuleImpl.java
|
Simplified authentication logic
|
|
Java
|
mit
|
fd00e6f6cfbf529424dfdded196e83dd04122b9e
| 0
|
project-icarus/icarus-atc,project-icarus/project-icarus
|
package com.icarus.project;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.Ellipse;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.graphics.g2d.freetype.FreetypeFontLoader.FreeTypeFontLoaderParameter;
import com.badlogic.gdx.graphics.g2d.freetype.FreetypeFontLoader;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGeneratorLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.input.GestureDetector;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import java.util.ArrayList;
public class ProjectIcarus extends ApplicationAdapter implements GestureDetector.GestureListener {
private Vector2 oldInitialFirstPointer=null, oldInitialSecondPointer=null;
private float oldScale;
//Used for drawing waypoints
public ShapeRenderer shapes;
//The currently loaded Airport
private Airport airport;
//The airplanes in the current game
private ArrayList<Airplane> airplanes;
//The font used for labels
private BitmapFont labelFont;
//Used for drawing airplanes
private SpriteBatch batch;
private Utils utils;
public MainUi ui;
private OrthographicCamera camera;
private float maxZoomIn; // Maximum possible zoomed in distance
private float maxZoomOut; // Maximum possible zoomed out distance
private float fontSize;
// Pan boundaries
private float toBoundaryRight;
private float toBoundaryLeft;
private float toBoundaryTop;
private float toBoundaryBottom;
public boolean followingPlane;
private Airplane selectedAirplane;
public static final String TAG = "ProjectIcarus";
public static ProjectIcarus self;
public UiState uiState;
public FreeTypeFontLoaderParameter labelFontParams;
@Override
public void create () {
self = this;
fontSize = 20.0f * Gdx.graphics.getDensity();
//initialize the AssetManager
AssetManager manager = new AssetManager();
FileHandleResolver resolver = new InternalFileHandleResolver();
manager.setLoader(Airport.class, new AirportLoader(resolver));
manager.setLoader(FreeTypeFontGenerator.class, new FreeTypeFontGeneratorLoader(resolver));
manager.setLoader(BitmapFont.class, ".ttf", new FreetypeFontLoader(resolver));
//load the airport
manager.load("airports/airport.json", Airport.class);
//load the label font
labelFontParams = new FreeTypeFontLoaderParameter();
labelFontParams.fontFileName = "fonts/3270Medium.ttf";
labelFontParams.fontParameters.size = Math.round(fontSize);
manager.load("fonts/3270Medium.ttf", BitmapFont.class, labelFontParams);
//load the airplane sprite
manager.load("sprites/airplane.png", Texture.class);
manager.load("buttons/altitude_button.png", Texture.class);
manager.load("buttons/heading_button.png", Texture.class);
manager.load("buttons/takeoff_button.png", Texture.class);
manager.load("buttons/circle_button.png", Texture.class);
manager.load("buttons/landing_button.png", Texture.class);
manager.load("buttons/more_button.png", Texture.class);
manager.load("buttons/selection_wheel.png", Texture.class);
manager.finishLoading();
airport = manager.get("airports/airport.json");
labelFont = manager.get("fonts/3270Medium.ttf");
Airplane.texture = manager.get("sprites/airplane.png");
shapes = new ShapeRenderer();
batch = new SpriteBatch();
//add test airplanes
airplanes = new ArrayList<Airplane>();
airplanes.add(new Airplane("airplane1", new Vector2(100, 100), new Vector2(4, 0), 10000));
airplanes.add(new Airplane("airplane2", new Vector2(100, 500), new Vector2(4, 0), 10000));
airplanes.add(new Airplane("airplane3", new Vector2(500, 100), new Vector2(4, 0), 10000));
airplanes.add(new Airplane("airplane4", new Vector2(500, 500), new Vector2(4, 0), 10000));
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
utils = new Utils();
// The maximum zoom level is the smallest dimension compared to the viewer
maxZoomOut = Math.min(airport.width / Gdx.graphics.getWidth(),
airport.height / Gdx.graphics.getHeight());
maxZoomIn = maxZoomOut / 100;
// Start the app in maximum zoomed out state
camera.zoom = maxZoomOut;
camera.position.set(airport.width/2, airport.height/2, 0);
camera.update();
ui = new MainUi(manager, labelFont);
selectedAirplane = null;
uiState = UiState.SELECT_AIRPLANE;
Gdx.input.setInputProcessor(new InputMultiplexer(ui.stage, new GestureDetector(this)));
}
private void setToBoundary() {
// Calculates the distance from the edge of the camera to the specified boundary
toBoundaryRight = (airport.width - camera.position.x
- Gdx.graphics.getWidth()/2 * camera.zoom);
toBoundaryLeft = (-camera.position.x + Gdx.graphics.getWidth()/2 * camera.zoom);
toBoundaryTop = (airport.height - camera.position.y
- Gdx.graphics.getHeight()/2 * camera.zoom);
toBoundaryBottom = (-camera.position.y + Gdx.graphics.getHeight()/2 * camera.zoom);
}
@Override
public void render () {
super.render();
Gdx.gl.glClearColor(Colors.colors[0].r, Colors.colors[0].g, Colors.colors[2].b, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//draw waypoint triangles
shapes.begin(ShapeRenderer.ShapeType.Filled);
for(Waypoint waypoint: airport.waypoints) {
waypoint.draw(shapes, camera);
}
shapes.end();
//draw runways
shapes.begin(ShapeRenderer.ShapeType.Filled);
for(Runway runway: airport.runways) {
runway.draw(shapes, camera);
}
shapes.end();
//draw waypoint labels
batch.begin();
for(Waypoint waypoint: airport.waypoints) {
waypoint.drawLabel(labelFont, batch, camera);
}
batch.end();
//draw runway labels
batch.begin();
for(Runway runway: airport.runways) {
runway.drawLabel(labelFont, batch, camera);
}
batch.end();
//draw airplanes
batch.begin();
for(Airplane airplane: airplanes) {
airplane.step(); //Move airplanes
airplane.draw(labelFont, batch, camera);
}
batch.end();
ui.draw();
// follow selected airplane
if(selectedAirplane != null && followingPlane) {
setCameraPosition(new Vector3(selectedAirplane.position, 0));
}
}
public void setCameraPosition(Vector3 position) {
camera.position.set(position);
Vector2 camMin = new Vector2(camera.viewportWidth, camera.viewportHeight);
camMin.scl(camera.zoom / 2);
Vector2 camMax = new Vector2(airport.width, airport.height);
camMax.sub(camMin);
camera.position.x = Math.min(camMax.x, Math.max(camera.position.x, camMin.x));
camera.position.y = Math.min(camMax.y, Math.max(camera.position.y, camMin.y));
camera.update();
}
@Override
public void dispose() {
shapes.dispose();
batch.dispose();
labelFont.dispose();
}
@Override
public boolean touchDown(float x, float y, int pointer, int button) {
return false;
}
public void setSelectedAirplane(Airplane selectedAirplane){
// deselect old selectedAirplane if not null
if(this.selectedAirplane != null){
this.selectedAirplane.setSelected(false);
}
this.selectedAirplane = selectedAirplane;
// select new selectedAirplane if not null
if(selectedAirplane != null){
followingPlane = true;
selectedAirplane.setSelected(true);
}
else {
followingPlane = false;
}
}
public Airplane getSelectedAirplane(){
return this.selectedAirplane;
}
@Override
public boolean tap(float x, float y, int count, int button) {
Vector3 position = new Vector3(x, Gdx.graphics.getHeight() - y, 0);
switch (uiState) {
case SELECT_AIRPLANE:
setSelectedAirplane(null);
for(Airplane airplane: airplanes) {
if(airplane.sprite.getBoundingRectangle().contains(position.x, position.y)) {
setSelectedAirplane(airplane);
ui.setStatus("selected " + getSelectedAirplane().name);
return true;
}
}
break;
case SELECT_WAYPOINT:
for(Waypoint waypoint: airport.waypoints) {
Vector3 pos = camera.project(new Vector3(waypoint.position, 0));
Circle circle = new Circle(pos.x, pos.y, Waypoint.waypointSize * 2);
if(circle.contains(position.x, position.y)) {
selectedAirplane.setTargetWaypoint(waypoint);
ui.setStatus("Selected waypoint " + waypoint.name);
uiState = UiState.SELECT_AIRPLANE;
followingPlane = true;
return true;
}
}
break;
case SELECT_HEADING:
uiState = UiState.SELECT_AIRPLANE;
ui.showHeadingSelector(false);
break;
case SELECT_RUNWAY:
for(Runway runway: airport.runways) {
Vector3 pos1 = camera.project(new Vector3(runway.points[0], 0));
Circle circle1 = new Circle(pos1.x, pos1.y, 20 * Gdx.graphics.getDensity());
Vector3 pos2 = camera.project(new Vector3(runway.points[1], 0));
Circle circle2 = new Circle(pos2.x, pos2.y, 20 * Gdx.graphics.getDensity());
if (circle1.contains(position.x, position.y)) {
ui.setStatus("selected runway end 1 " + runway.names[0]);
uiState = UiState.SELECT_AIRPLANE;
followingPlane = true;
break;
}
else if (circle2.contains(position.x, position.y)) {
ui.setStatus("selected runway end 2 " + runway.names[1]);
uiState = UiState.SELECT_AIRPLANE;
followingPlane = true;
break;
}
}
break;
default:
break;
}
if(selectedAirplane == null){
ui.setStatus("deselected airplane");
}
return true;
}
public enum UiState {
SELECT_WAYPOINT, SELECT_AIRPLANE, SELECT_HEADING, SELECT_RUNWAY
}
@Override
public boolean longPress(float x, float y) {
return false;
}
@Override
public boolean fling(float velocityX, float velocityY, int button) {
return false;
}
@Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
followingPlane = false;
setCameraPosition(camera.position.add(
camera.unproject(new Vector3(0, 0, 0))
.add(camera.unproject(new Vector3(deltaX, deltaY, 0)).scl(-1f))
));
return true;
}
@Override
public boolean panStop(float x, float y, int pointer, int button) {
return false;
}
@Override
public boolean zoom(float initialDistance, float distance) {
return false;
}
@Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1,
Vector2 pointer2)
{
if (!(initialPointer1.equals(oldInitialFirstPointer)
&& initialPointer2.equals(oldInitialSecondPointer)))
{
oldInitialFirstPointer = initialPointer1.cpy();
oldInitialSecondPointer = initialPointer2.cpy();
oldScale = camera.zoom;
}
Vector3 center = new Vector3(
(pointer1.x + initialPointer2.x) / 2,
(pointer2.y + initialPointer1.y) / 2,
0
);
zoomCamera(center,
oldScale * initialPointer1.dst(initialPointer2) / pointer1.dst(pointer2));
return true;
}
@Override
public void pinchStop() {
}
private void zoomCamera(Vector3 origin, float scale) {
if(followingPlane) {
camera.zoom = scale;
camera.zoom = Math.min(maxZoomOut, Math.max(camera.zoom, maxZoomIn));
}
else {
Vector3 oldUnprojection = camera.unproject(origin.cpy()).cpy();
camera.zoom = scale; //Larger value of zoom = small images, border view
camera.zoom = Math.min(maxZoomOut, Math.max(camera.zoom, maxZoomIn));
camera.update();
Vector3 newUnprojection = camera.unproject(origin.cpy()).cpy();
camera.position.add(oldUnprojection.cpy().add(newUnprojection.cpy().scl(-1f)));
}
setToBoundary(); //Calculate distances to boundaries
//Shift the view when zooming to keep view within map
if (toBoundaryRight < 0 || toBoundaryTop < 0){
camera.position.add(
camera.unproject(new Vector3(0, 0, 0))
.add(camera.unproject(new Vector3(Math.max(0, -toBoundaryRight),
Math.min(0, toBoundaryTop),
0)).scl(-1f))
);
}
if (toBoundaryLeft > 0 || toBoundaryBottom > 0){
camera.position.add(
camera.unproject(new Vector3(0, 0, 0))
.add(camera.unproject(new Vector3(Math.min(0, -toBoundaryLeft),
Math.max(0, toBoundaryBottom),
0)).scl(-1f))
);
}
camera.update();
}
public static ProjectIcarus getInstance() {
return self;
}
}
|
core/src/com/icarus/project/ProjectIcarus.java
|
package com.icarus.project;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.Ellipse;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.graphics.g2d.freetype.FreetypeFontLoader.FreeTypeFontLoaderParameter;
import com.badlogic.gdx.graphics.g2d.freetype.FreetypeFontLoader;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGeneratorLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.input.GestureDetector;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import java.util.ArrayList;
public class ProjectIcarus extends ApplicationAdapter implements GestureDetector.GestureListener {
private Vector2 oldInitialFirstPointer=null, oldInitialSecondPointer=null;
private float oldScale;
//Used for drawing waypoints
public ShapeRenderer shapes;
//The currently loaded Airport
private Airport airport;
//The airplanes in the current game
private ArrayList<Airplane> airplanes;
//The font used for labels
private BitmapFont labelFont;
//Used for drawing airplanes
private SpriteBatch batch;
private Utils utils;
public MainUi ui;
private OrthographicCamera camera;
private float maxZoomIn; // Maximum possible zoomed in distance
private float maxZoomOut; // Maximum possible zoomed out distance
private float fontSize;
// Pan boundaries
private float toBoundaryRight;
private float toBoundaryLeft;
private float toBoundaryTop;
private float toBoundaryBottom;
public boolean followingPlane;
private Airplane selectedAirplane;
public static final String TAG = "ProjectIcarus";
public static ProjectIcarus self;
public UiState uiState;
public FreeTypeFontLoaderParameter labelFontParams;
@Override
public void create () {
self = this;
fontSize = 20.0f * Gdx.graphics.getDensity();
//initialize the AssetManager
AssetManager manager = new AssetManager();
FileHandleResolver resolver = new InternalFileHandleResolver();
manager.setLoader(Airport.class, new AirportLoader(resolver));
manager.setLoader(FreeTypeFontGenerator.class, new FreeTypeFontGeneratorLoader(resolver));
manager.setLoader(BitmapFont.class, ".ttf", new FreetypeFontLoader(resolver));
//load the airport
manager.load("airports/test.json", Airport.class);
//load the label font
labelFontParams = new FreeTypeFontLoaderParameter();
labelFontParams.fontFileName = "fonts/3270Medium.ttf";
labelFontParams.fontParameters.size = Math.round(fontSize);
manager.load("fonts/3270Medium.ttf", BitmapFont.class, labelFontParams);
//load the airplane sprite
manager.load("sprites/airplane.png", Texture.class);
manager.load("buttons/altitude_button.png", Texture.class);
manager.load("buttons/heading_button.png", Texture.class);
manager.load("buttons/takeoff_button.png", Texture.class);
manager.load("buttons/circle_button.png", Texture.class);
manager.load("buttons/landing_button.png", Texture.class);
manager.load("buttons/more_button.png", Texture.class);
manager.load("buttons/selection_wheel.png", Texture.class);
manager.finishLoading();
airport = manager.get("airports/test.json");
labelFont = manager.get("fonts/3270Medium.ttf");
Airplane.texture = manager.get("sprites/airplane.png");
shapes = new ShapeRenderer();
batch = new SpriteBatch();
//add test airplanes
airplanes = new ArrayList<Airplane>();
airplanes.add(new Airplane("airplane1", new Vector2(100, 100), new Vector2(4, 0), 10000));
airplanes.add(new Airplane("airplane2", new Vector2(100, 500), new Vector2(4, 0), 10000));
airplanes.add(new Airplane("airplane3", new Vector2(500, 100), new Vector2(4, 0), 10000));
airplanes.add(new Airplane("airplane4", new Vector2(500, 500), new Vector2(4, 0), 10000));
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
utils = new Utils();
// The maximum zoom level is the smallest dimension compared to the viewer
maxZoomOut = Math.min(airport.width / Gdx.graphics.getWidth(),
airport.height / Gdx.graphics.getHeight());
maxZoomIn = maxZoomOut / 100;
// Start the app in maximum zoomed out state
camera.zoom = maxZoomOut;
camera.position.set(airport.width/2, airport.height/2, 0);
camera.update();
ui = new MainUi(manager, labelFont);
selectedAirplane = null;
uiState = UiState.SELECT_AIRPLANE;
Gdx.input.setInputProcessor(new InputMultiplexer(ui.stage, new GestureDetector(this)));
}
private void setToBoundary() {
// Calculates the distance from the edge of the camera to the specified boundary
toBoundaryRight = (airport.width - camera.position.x
- Gdx.graphics.getWidth()/2 * camera.zoom);
toBoundaryLeft = (-camera.position.x + Gdx.graphics.getWidth()/2 * camera.zoom);
toBoundaryTop = (airport.height - camera.position.y
- Gdx.graphics.getHeight()/2 * camera.zoom);
toBoundaryBottom = (-camera.position.y + Gdx.graphics.getHeight()/2 * camera.zoom);
}
@Override
public void render () {
super.render();
Gdx.gl.glClearColor(Colors.colors[0].r, Colors.colors[0].g, Colors.colors[2].b, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//draw waypoint triangles
shapes.begin(ShapeRenderer.ShapeType.Filled);
for(Waypoint waypoint: airport.waypoints) {
waypoint.draw(shapes, camera);
}
shapes.end();
//draw runways
shapes.begin(ShapeRenderer.ShapeType.Filled);
for(Runway runway: airport.runways) {
runway.draw(shapes, camera);
}
shapes.end();
//draw waypoint labels
batch.begin();
for(Waypoint waypoint: airport.waypoints) {
waypoint.drawLabel(labelFont, batch, camera);
}
batch.end();
//draw runway labels
batch.begin();
for(Runway runway: airport.runways) {
runway.drawLabel(labelFont, batch, camera);
}
batch.end();
//draw airplanes
batch.begin();
for(Airplane airplane: airplanes) {
airplane.step(); //Move airplanes
airplane.draw(labelFont, batch, camera);
}
batch.end();
ui.draw();
// follow selected airplane
if(selectedAirplane != null && followingPlane) {
setCameraPosition(new Vector3(selectedAirplane.position, 0));
}
}
public void setCameraPosition(Vector3 position) {
camera.position.set(position);
Vector2 camMin = new Vector2(camera.viewportWidth, camera.viewportHeight);
camMin.scl(camera.zoom / 2);
Vector2 camMax = new Vector2(airport.width, airport.height);
camMax.sub(camMin);
camera.position.x = Math.min(camMax.x, Math.max(camera.position.x, camMin.x));
camera.position.y = Math.min(camMax.y, Math.max(camera.position.y, camMin.y));
camera.update();
}
@Override
public void dispose() {
shapes.dispose();
batch.dispose();
labelFont.dispose();
}
@Override
public boolean touchDown(float x, float y, int pointer, int button) {
return false;
}
public void setSelectedAirplane(Airplane selectedAirplane){
// deselect old selectedAirplane if not null
if(this.selectedAirplane != null){
this.selectedAirplane.setSelected(false);
}
this.selectedAirplane = selectedAirplane;
// select new selectedAirplane if not null
if(selectedAirplane != null){
followingPlane = true;
selectedAirplane.setSelected(true);
}
else {
followingPlane = false;
}
}
public Airplane getSelectedAirplane(){
return this.selectedAirplane;
}
@Override
public boolean tap(float x, float y, int count, int button) {
Vector3 position = new Vector3(x, Gdx.graphics.getHeight() - y, 0);
switch (uiState) {
case SELECT_AIRPLANE:
setSelectedAirplane(null);
for(Airplane airplane: airplanes) {
if(airplane.sprite.getBoundingRectangle().contains(position.x, position.y)) {
setSelectedAirplane(airplane);
ui.setStatus("selected " + getSelectedAirplane().name);
return true;
}
}
break;
case SELECT_WAYPOINT:
for(Waypoint waypoint: airport.waypoints) {
Vector3 pos = camera.project(new Vector3(waypoint.position, 0));
Circle circle = new Circle(pos.x, pos.y, Waypoint.waypointSize * 2);
if(circle.contains(position.x, position.y)) {
selectedAirplane.setTargetWaypoint(waypoint);
ui.setStatus("Selected waypoint " + waypoint.name);
uiState = UiState.SELECT_AIRPLANE;
followingPlane = true;
return true;
}
}
break;
case SELECT_HEADING:
uiState = UiState.SELECT_AIRPLANE;
ui.showHeadingSelector(false);
break;
case SELECT_RUNWAY:
for(Runway runway: airport.runways) {
Vector3 pos1 = camera.project(new Vector3(runway.points[0], 0));
Circle circle1 = new Circle(pos1.x, pos1.y, 20 * Gdx.graphics.getDensity());
Vector3 pos2 = camera.project(new Vector3(runway.points[1], 0));
Circle circle2 = new Circle(pos2.x, pos2.y, 20 * Gdx.graphics.getDensity());
if (circle1.contains(position.x, position.y)) {
ui.setStatus("selected runway end 1");
uiState = UiState.SELECT_AIRPLANE;
followingPlane = true;
break;
}
else if (circle2.contains(position.x, position.y)) {
ui.setStatus("selected runway end 2");
uiState = UiState.SELECT_AIRPLANE;
followingPlane = true;
break;
}
}
break;
default:
break;
}
if(selectedAirplane == null){
ui.setStatus("deselected airplane");
}
return true;
}
public enum UiState {
SELECT_WAYPOINT, SELECT_AIRPLANE, SELECT_HEADING, SELECT_RUNWAY
}
@Override
public boolean longPress(float x, float y) {
return false;
}
@Override
public boolean fling(float velocityX, float velocityY, int button) {
return false;
}
@Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
followingPlane = false;
setCameraPosition(camera.position.add(
camera.unproject(new Vector3(0, 0, 0))
.add(camera.unproject(new Vector3(deltaX, deltaY, 0)).scl(-1f))
));
return true;
}
@Override
public boolean panStop(float x, float y, int pointer, int button) {
return false;
}
@Override
public boolean zoom(float initialDistance, float distance) {
return false;
}
@Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1,
Vector2 pointer2)
{
if (!(initialPointer1.equals(oldInitialFirstPointer)
&& initialPointer2.equals(oldInitialSecondPointer)))
{
oldInitialFirstPointer = initialPointer1.cpy();
oldInitialSecondPointer = initialPointer2.cpy();
oldScale = camera.zoom;
}
Vector3 center = new Vector3(
(pointer1.x + initialPointer2.x) / 2,
(pointer2.y + initialPointer1.y) / 2,
0
);
zoomCamera(center,
oldScale * initialPointer1.dst(initialPointer2) / pointer1.dst(pointer2));
return true;
}
@Override
public void pinchStop() {
}
private void zoomCamera(Vector3 origin, float scale) {
if(followingPlane) {
camera.zoom = scale;
camera.zoom = Math.min(maxZoomOut, Math.max(camera.zoom, maxZoomIn));
}
else {
Vector3 oldUnprojection = camera.unproject(origin.cpy()).cpy();
camera.zoom = scale; //Larger value of zoom = small images, border view
camera.zoom = Math.min(maxZoomOut, Math.max(camera.zoom, maxZoomIn));
camera.update();
Vector3 newUnprojection = camera.unproject(origin.cpy()).cpy();
camera.position.add(oldUnprojection.cpy().add(newUnprojection.cpy().scl(-1f)));
}
setToBoundary(); //Calculate distances to boundaries
//Shift the view when zooming to keep view within map
if (toBoundaryRight < 0 || toBoundaryTop < 0){
camera.position.add(
camera.unproject(new Vector3(0, 0, 0))
.add(camera.unproject(new Vector3(Math.max(0, -toBoundaryRight),
Math.min(0, toBoundaryTop),
0)).scl(-1f))
);
}
if (toBoundaryLeft > 0 || toBoundaryBottom > 0){
camera.position.add(
camera.unproject(new Vector3(0, 0, 0))
.add(camera.unproject(new Vector3(Math.min(0, -toBoundaryLeft),
Math.max(0, toBoundaryBottom),
0)).scl(-1f))
);
}
camera.update();
}
public static ProjectIcarus getInstance() {
return self;
}
}
|
changed airport
|
core/src/com/icarus/project/ProjectIcarus.java
|
changed airport
|
|
Java
|
mit
|
6387d0d77a2b342e8de0cd303823868291561ecb
| 0
|
manifoldjs/ManifoldCordova,manifoldjs/ManifoldCordova,lijie371/ManifoldCordova,Boltmade/cordova-plugin-offline-page,lijie371/ManifoldCordova,lijie371/ManifoldCordova,manifoldjs/ManifoldCordova,Boltmade/cordova-plugin-offline-page
|
package com.microsoft.hostedwebapp;
import android.content.res.AssetManager;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
/**
* This class manipulates the Web App W3C manifest.
*/
public class HostedWebApp extends CordovaPlugin {
private static final String DEFAULT_MANIFEST_FILE = "manifest.json";
private static final String OFFLINE_PAGE = "offline.html";
private static final String OFFLINE_PAGE_TEMPLATE = "<html><body><div style=\"top:50%%;text-align:center;position:absolute\">%s</div></body></html>";
private boolean loadingManifest;
private JSONObject manifestObject;
private CordovaActivity activity;
private LinearLayout rootLayout;
private WebView offlineWebView;
private boolean offlineOverlayEnabled;
private boolean isConnectionError = false;
@Override
public void pluginInitialize() {
final HostedWebApp me = HostedWebApp.this;
this.activity = (CordovaActivity)this.cordova.getActivity();
// Load default manifest file.
this.loadingManifest = true;
if (this.assetExists(HostedWebApp.DEFAULT_MANIFEST_FILE)) {
try {
this.manifestObject = this.loadLocalManifest(HostedWebApp.DEFAULT_MANIFEST_FILE);
this.webView.postMessage("hostedWebApp_manifestLoaded", this.manifestObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
this.loadingManifest = false;
// Initialize offline overlay
this.activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (me.rootLayout == null) {
me.rootLayout = me.createOfflineRootLayout();
me.activity.addContentView(me.rootLayout, me.rootLayout.getLayoutParams());
}
if (me.offlineWebView == null) {
me.offlineWebView = me.createOfflineWebView();
me.rootLayout.addView(me.offlineWebView);
}
if (me.assetExists(HostedWebApp.OFFLINE_PAGE)) {
me.offlineWebView.loadUrl("file:///android_asset/www/" + HostedWebApp.OFFLINE_PAGE);
} else {
me.offlineWebView.loadData(
String.format(HostedWebApp.OFFLINE_PAGE_TEMPLATE, "It looks like you are offline. Please reconnect to use this application."),
"text/html",
null);
}
me.offlineOverlayEnabled = true;
}
});
}
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
final HostedWebApp me = HostedWebApp.this;
if (action.equals("getManifest")) {
if (this.manifestObject != null) {
callbackContext.success(manifestObject.toString());
} else {
callbackContext.error("Manifest not loaded, load a manifest using loadManifest.");
}
return true;
}
if (action.equals("loadManifest")) {
if (this.loadingManifest) {
callbackContext.error("Already loading a manifest");
} else if (args.length() == 0) {
callbackContext.error("Manifest file name required");
} else {
final String configFilename = args.getString(0);
this.loadingManifest = true;
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
if (me.assetExists(configFilename)) {
try {
me.manifestObject = me.loadLocalManifest(configFilename);
me.webView.postMessage("hostedWebApp_manifestLoaded", me.manifestObject);
callbackContext.success(me.manifestObject);
} catch (JSONException e) {
callbackContext.error(e.getMessage());
}
} else {
callbackContext.error("Manifest file not found in folder assets/www");
}
me.loadingManifest = false;
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
return true;
}
if (action.equals("enableOfflinePage")) {
this.offlineOverlayEnabled = true;
return true;
}
if (action.equals("disableOfflinePage")) {
this.offlineOverlayEnabled = false;
return true;
}
return false;
}
@Override
public Object onMessage(String id, Object data) {
if (id.equals("networkconnection") && data != null) {
this.handleNetworkConnectionChange(data.toString());
} else if (id.equals("onPageStarted")) {
this.isConnectionError = false;
} else if (id.equals("onReceivedError")) {
if (data instanceof JSONObject) {
JSONObject errorData = (JSONObject) data;
try {
int errorCode = errorData.getInt("errorCode");
if (404 == errorCode
|| WebViewClient.ERROR_HOST_LOOKUP == errorCode
|| WebViewClient.ERROR_CONNECT == errorCode
|| WebViewClient.ERROR_TIMEOUT == errorCode) {
this.isConnectionError = true;
this.showOfflineOverlay();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
else if (id.equals("onPageFinished")) {
if (!this.isConnectionError) {
this.hideOfflineOverlay();
}
}
return null;
}
public JSONObject getManifest() {
return this.manifestObject;
}
private boolean assetExists(String asset) {
final AssetManager assetManager = this.activity.getResources().getAssets();
try {
return Arrays.asList(assetManager.list("www")).contains(asset);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private WebView createOfflineWebView() {
WebView webView = new WebView(activity);
webView.getSettings().setJavaScriptEnabled(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
1.0F));
return webView;
}
private LinearLayout createOfflineRootLayout() {
LinearLayout root = new LinearLayout(activity.getBaseContext());
root.setOrientation(LinearLayout.VERTICAL);
root.setVisibility(View.INVISIBLE);
root.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
0.0F));
return root;
}
private void handleNetworkConnectionChange(String info) {
if (info.equals("none")) {
this.showOfflineOverlay();
} else {
if (this.isConnectionError) {
this.webView.reload();
} else {
this.hideOfflineOverlay();
}
}
}
private void showOfflineOverlay() {
final HostedWebApp me = HostedWebApp.this;
if (this.offlineOverlayEnabled) {
this.activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (me.rootLayout != null) {
me.rootLayout.setVisibility(View.VISIBLE);
}
}
});
}
}
private void hideOfflineOverlay() {
final HostedWebApp me = HostedWebApp.this;
this.activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (me.rootLayout != null) {
me.rootLayout.setVisibility(View.INVISIBLE);
}
}
});
}
private JSONObject loadLocalManifest(String manifestFile) throws JSONException {
try {
InputStream inputStream = this.activity.getResources().getAssets().open("www/" + manifestFile);
int size = inputStream.available();
byte[] bytes = new byte[size];
inputStream.read(bytes);
inputStream.close();
String jsonString = new String(bytes, "UTF-8");
return new JSONObject(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
|
src/android/HostedWebApp.java
|
package com.microsoft.hostedwebapp;
import android.content.res.AssetManager;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
/**
* This class manipulates the Web App W3C manifest.
*/
public class HostedWebApp extends CordovaPlugin {
private static final String DEFAULT_MANIFEST_FILE = "manifest.json";
private static final String OFFLINE_PAGE = "offline.html";
private static final String OFFLINE_PAGE_TEMPLATE = "<html><body><div style=\"top:50%%;text-align:center;position:absolute\">%s</div></body></html>";
private boolean loadingManifest;
private JSONObject manifestObject;
private CordovaActivity activity;
private LinearLayout rootLayout;
private WebView offlineWebView;
private boolean offlineOverlayEnabled;
private boolean isConnectionError = false;
@Override
public void pluginInitialize() {
final HostedWebApp me = HostedWebApp.this;
this.activity = (CordovaActivity)this.cordova.getActivity();
// Load default manifest file.
this.loadingManifest = true;
if (this.assetExists(HostedWebApp.DEFAULT_MANIFEST_FILE)) {
try {
this.manifestObject = this.loadLocalManifest(HostedWebApp.DEFAULT_MANIFEST_FILE);
this.webView.postMessage("hostedWebApp_manifestLoaded", this.manifestObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
this.loadingManifest = false;
// Initialize offline overlay
this.activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (me.rootLayout == null) {
me.rootLayout = me.createOfflineRootLayout();
me.activity.addContentView(me.rootLayout, me.rootLayout.getLayoutParams());
}
if (me.offlineWebView == null) {
me.offlineWebView = me.createOfflineWebView();
me.rootLayout.addView(me.offlineWebView);
}
if (me.assetExists(HostedWebApp.OFFLINE_PAGE)) {
me.offlineWebView.loadUrl("file:///android_asset/www/" + HostedWebApp.OFFLINE_PAGE);
} else {
me.offlineWebView.loadData(
String.format(HostedWebApp.OFFLINE_PAGE_TEMPLATE, "It looks like you are offline. Please reconnect to use this application."),
"text/html",
null);
}
me.offlineOverlayEnabled = true;
}
});
}
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
final HostedWebApp me = HostedWebApp.this;
if (action.equals("getManifest")) {
if (this.manifestObject != null) {
callbackContext.success(manifestObject.toString());
} else {
callbackContext.error("Manifest not loaded, load a manifest using loadManifest.");
}
return true;
}
if (action.equals("loadManifest")) {
if (this.loadingManifest) {
callbackContext.error("Already loading a manifest");
} else if (args.length() == 0) {
callbackContext.error("Manifest file name required");
} else {
final String configFilename = args.getString(0);
this.loadingManifest = true;
this.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
if (me.assetExists(configFilename)) {
try {
me.manifestObject = me.loadLocalManifest(configFilename);
me.webView.postMessage("hostedWebApp_manifestLoaded", me.manifestObject);
callbackContext.success(me.manifestObject);
} catch (JSONException e) {
callbackContext.error(e.getMessage());
}
} else {
callbackContext.error("Manifest file not found in folder assets/www");
}
me.loadingManifest = false;
}
});
PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);
}
return true;
}
if (action.equals("enableOfflinePage")) {
this.offlineOverlayEnabled = true;
return true;
}
if (action.equals("disableOfflinePage")) {
this.offlineOverlayEnabled = false;
return true;
}
return false;
}
@Override
public Object onMessage(String id, Object data) {
if (id.equals("networkconnection") && data != null) {
this.handleNetworkConnectionChange(data.toString());
} else if (id.equals("onPageStarted")) {
this.isConnectionError = false;
} else if (id.equals("onReceivedError")) {
if (data instanceof JSONObject) {
JSONObject errorData = (JSONObject) data;
try {
int errorCode = errorData.getInt("errorCode");
if (404 == errorCode
|| WebViewClient.ERROR_HOST_LOOKUP == errorCode
|| WebViewClient.ERROR_CONNECT == errorCode
|| WebViewClient.ERROR_TIMEOUT == errorCode) {
this.isConnectionError = true;
this.showOfflineOverlay();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
else if (id.equals("onPageFinished")) {
if (!this.isConnectionError) {
this.hideOfflineOverlay();
}
}
return null;
}
private boolean assetExists(String asset) {
final AssetManager assetManager = this.activity.getResources().getAssets();
try {
return Arrays.asList(assetManager.list("www")).contains(asset);
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private WebView createOfflineWebView() {
WebView webView = new WebView(activity);
webView.getSettings().setJavaScriptEnabled(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
1.0F));
return webView;
}
private LinearLayout createOfflineRootLayout() {
LinearLayout root = new LinearLayout(activity.getBaseContext());
root.setOrientation(LinearLayout.VERTICAL);
root.setVisibility(View.INVISIBLE);
root.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
0.0F));
return root;
}
private void handleNetworkConnectionChange(String info) {
if (info.equals("none")) {
this.showOfflineOverlay();
} else {
if (this.isConnectionError) {
this.webView.reload();
} else {
this.hideOfflineOverlay();
}
}
}
private void showOfflineOverlay() {
final HostedWebApp me = HostedWebApp.this;
if (this.offlineOverlayEnabled) {
this.activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (me.rootLayout != null) {
me.rootLayout.setVisibility(View.VISIBLE);
}
}
});
}
}
private void hideOfflineOverlay() {
final HostedWebApp me = HostedWebApp.this;
this.activity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (me.rootLayout != null) {
me.rootLayout.setVisibility(View.INVISIBLE);
}
}
});
}
private JSONObject loadLocalManifest(String manifestFile) throws JSONException {
try {
InputStream inputStream = this.activity.getResources().getAssets().open("www/" + manifestFile);
int size = inputStream.available();
byte[] bytes = new byte[size];
inputStream.read(bytes);
inputStream.close();
String jsonString = new String(bytes, "UTF-8");
return new JSONObject(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
|
[Android] Fixed issue with Manifest loaded event being throw before loading the WAT plugin
Conflicts:
src/android/HostedWebApp.java
|
src/android/HostedWebApp.java
|
[Android] Fixed issue with Manifest loaded event being throw before loading the WAT plugin
|
|
Java
|
mit
|
b2db27018c2103615a83be71ecd5b79bef2c9b75
| 0
|
smarr/SOMns,richard-roberts/SOMns,MetaConc/SOMns,richard-roberts/SOMns,richard-roberts/SOMns,smarr/SOMns,richard-roberts/SOMns,smarr/SOMns,smarr/SOMns,MetaConc/SOMns,smarr/SOMns,smarr/SOMns,richard-roberts/SOMns,richard-roberts/SOMns,smarr/SOMns,MetaConc/SOMns,richard-roberts/SOMns,VAISHALI-DHANOA/SOMns,VAISHALI-DHANOA/SOMns,VAISHALI-DHANOA/SOMns
|
package som.compiler;
public class Tags {
public static final String ROOT_TAG = "ROOT";
public static final String UNSPECIFIED_INVOKE = "UNSPECIFIED_INVOKE"; // this is some form of invoke in the source, unclear what it is during program execution
public static final String NEW_OBJECT = "NEW_OBJECT";
public static final String NEW_ARRAY = "NEW_ARRAY";
public static final String CONTROL_FLOW_CONDITION = "CONTROL_FLOW_CONDITION"; // a condition expression that results in a control-flow change
public static final String FIELD_READ = "FIELD_READ";
public static final String FIELD_WRITE = "FIELD_WRITE";
public static final String LOCAL_VAR_READ = "LOCAL_VAR_READ";
public static final String LOCAL_VAR_WRITE = "LOCAL_VAR_WRITE";
public static final String LOCAL_ARG_READ = "LOCAL_ARG_READ";
public static final String ARRAY_READ = "ARRAY_READ";
public static final String ARRAY_WRITE = "ARRAY_WRITE";
public static final String LOOP_BODY = "LOOP_BODY";
// Syntax annotations
public static final String SYNTAX_KEYWORD = "SYNTAX_KEYWORD";
public static final String SYNTAX_LITERAL = "SYNTAX_LITERAL";
public static final String SYNTAX_COMMENT = "SYNTAX_COMMENT";
public static final String SYNTAX_IDENTIFIER = "SYNTAX_IDENTIFIER";
public static final String SYNTAX_ARGUMENT = "SYNTAX_ARGUMENT";
public static final String SYNTAX_LOCAL_VARIABLE = "SYNTAX_LOCAL_VARIABLE";
}
|
src/som/compiler/Tags.java
|
package som.compiler;
public class Tags {
public static final String ROOT_TAG = "ROOT";
public static final String UNSPECIFIED_INVOKE = "UNSPECIFIED_INVOKE"; // this is some form of invoke in the source, unclear what it is during program execution
public static final String NEW_OBJECT = "NEW_OBJECT";
public static final String NEW_ARRAY = "NEW_ARRAY";
public static final String CONTROL_FLOW_CONDITION = "CONTROL_FLOW_CONDITION"; // a condition expression that results in a control-flow change
public static final String FIELD_READ = "FIELD_READ";
public static final String FIELD_WRITE = "FIELD_WRITE";
public static final String ARRAY_READ = "ARRAY_READ";
public static final String ARRAY_WRITE = "ARRAY_WRITE";
public static final String LOOP_BODY = "LOOP_BODY";
// Syntax annotations
public static final String SYNTAX_KEYWORD = "SYNTAX_KEYWORD";
public static final String SYNTAX_LITERAL = "SYNTAX_LITERAL";
public static final String SYNTAX_COMMENT = "SYNTAX_COMMENT";
public static final String SYNTAX_IDENTIFIER = "SYNTAX_IDENTIFIER";
}
|
Added more tags
Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
|
src/som/compiler/Tags.java
|
Added more tags
|
|
Java
|
mit
|
63e6f71db1869129add93a4f987bd415571805ed
| 0
|
nico1510/react-native-image-crop-picker,nico1510/react-native-image-crop-picker,ivpusic/react-native-image-crop-picker,ropc/react-native-image-crop-picker,zoofei/react-native-my-image-crop-picker,ropc/react-native-image-crop-picker,ropc/react-native-image-crop-picker,zoofei/react-native-my-image-crop-picker,ropc/react-native-image-crop-picker,nico1510/react-native-image-crop-picker,nico1510/react-native-image-crop-picker,ivpusic/react-native-image-crop-picker,ivpusic/react-native-image-crop-picker,zoofei/react-native-my-image-crop-picker,zoofei/react-native-my-image-crop-picker
|
package com.reactnative.ivpusic.imagepicker;
import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Base64;
import android.webkit.MimeTypeMap;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.PromiseImpl;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
class PickerModule extends ReactContextBaseJavaModule implements ActivityEventListener {
private static final int IMAGE_PICKER_REQUEST = 61110;
private static final int CAMERA_PICKER_REQUEST = 61111;
private static final String E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST";
private static final String E_PICKER_CANCELLED_KEY = "E_PICKER_CANCELLED";
private static final String E_PICKER_CANCELLED_MSG = "User cancelled image selection";
private static final String E_CALLBACK_ERROR = "E_CALLBACK_ERROR";
private static final String E_FAILED_TO_SHOW_PICKER = "E_FAILED_TO_SHOW_PICKER";
private static final String E_FAILED_TO_OPEN_CAMERA = "E_FAILED_TO_OPEN_CAMERA";
private static final String E_NO_IMAGE_DATA_FOUND = "E_NO_IMAGE_DATA_FOUND";
private static final String E_CAMERA_IS_NOT_AVAILABLE = "E_CAMERA_IS_NOT_AVAILABLE";
private static final String E_CANNOT_LAUNCH_CAMERA = "E_CANNOT_LAUNCH_CAMERA";
private static final String E_PERMISSIONS_MISSING = "E_PERMISSIONS_MISSING";
private static final String E_ERROR_WHILE_CLEANING_FILES = "E_ERROR_WHILE_CLEANING_FILES";
private String mediaType = "any";
private boolean multiple = false;
private boolean includeBase64 = false;
private boolean cropping = false;
private boolean cropperCircleOverlay = false;
private boolean showCropGuidelines = true;
private boolean hideBottomControls = false;
private boolean enableRotationGesture = false;
private ReadableMap options;
//Grey 800
private final String DEFAULT_TINT = "#424242";
private String cropperActiveWidgetColor = DEFAULT_TINT;
private String cropperStatusBarColor = DEFAULT_TINT;
private String cropperToolbarColor = DEFAULT_TINT;
//Light Blue 500
private final String DEFAULT_WIDGET_COLOR = "#03A9F4";
private int width = 200;
private int height = 200;
private Uri mCameraCaptureURI;
private String mCurrentPhotoPath;
private ResultCollector resultCollector;
private Compression compression = new Compression();
PickerModule(ReactApplicationContext reactContext) {
super(reactContext);
reactContext.addActivityEventListener(this);
}
private String getTmpDir(Activity activity) {
String tmpDir = activity.getCacheDir() + "/react-native-image-crop-picker";
Boolean created = new File(tmpDir).mkdir();
return tmpDir;
}
@Override
public String getName() {
return "ImageCropPicker";
}
private void setConfiguration(final ReadableMap options) {
mediaType = options.hasKey("mediaType") ? options.getString("mediaType") : mediaType;
multiple = options.hasKey("multiple") && options.getBoolean("multiple");
includeBase64 = options.hasKey("includeBase64") && options.getBoolean("includeBase64");
width = options.hasKey("width") ? options.getInt("width") : width;
height = options.hasKey("height") ? options.getInt("height") : height;
cropping = options.hasKey("cropping") ? options.getBoolean("cropping") : cropping;
cropperActiveWidgetColor = options.hasKey("cropperActiveWidgetColor") ? options.getString("cropperActiveWidgetColor") : cropperActiveWidgetColor;
cropperStatusBarColor = options.hasKey("cropperStatusBarColor") ? options.getString("cropperStatusBarColor") : cropperStatusBarColor;
cropperToolbarColor = options.hasKey("cropperToolbarColor") ? options.getString("cropperToolbarColor") : cropperToolbarColor;
cropperCircleOverlay = options.hasKey("cropperCircleOverlay") ? options.getBoolean("cropperCircleOverlay") : cropperCircleOverlay;
showCropGuidelines = options.hasKey("showCropGuidelines") ? options.getBoolean("showCropGuidelines") : showCropGuidelines;
hideBottomControls = options.hasKey("hideBottomControls") ? options.getBoolean("hideBottomControls") : hideBottomControls;
enableRotationGesture = options.hasKey("enableRotationGesture") ? options.getBoolean("enableRotationGesture") : enableRotationGesture;
this.options = options;
}
private void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
deleteRecursive(child);
}
}
fileOrDirectory.delete();
}
@ReactMethod
public void clean(final Promise promise) {
final Activity activity = getCurrentActivity();
final PickerModule module = this;
if (activity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
permissionsCheck(activity, promise, Arrays.asList(Manifest.permission.WRITE_EXTERNAL_STORAGE), new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
File file = new File(module.getTmpDir(activity));
if (!file.exists()) throw new Exception("File does not exist");
module.deleteRecursive(file);
promise.resolve(null);
} catch (Exception ex) {
ex.printStackTrace();
promise.reject(E_ERROR_WHILE_CLEANING_FILES, ex.getMessage());
}
return null;
}
});
}
@ReactMethod
public void cleanSingle(final String pathToDelete, final Promise promise) {
if (pathToDelete == null) {
promise.reject(E_ERROR_WHILE_CLEANING_FILES, "Cannot cleanup empty path");
return;
}
final Activity activity = getCurrentActivity();
final PickerModule module = this;
if (activity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
permissionsCheck(activity, promise, Arrays.asList(Manifest.permission.WRITE_EXTERNAL_STORAGE), new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
String path = pathToDelete;
final String filePrefix = "file://";
if (path.startsWith(filePrefix)) {
path = path.substring(filePrefix.length());
}
File file = new File(path);
if (!file.exists()) throw new Exception("File does not exist. Path: " + path);
module.deleteRecursive(file);
promise.resolve(null);
} catch (Exception ex) {
ex.printStackTrace();
promise.reject(E_ERROR_WHILE_CLEANING_FILES, ex.getMessage());
}
return null;
}
});
}
private void permissionsCheck(final Activity activity, final Promise promise, final List<String> requiredPermissions, final Callable<Void> callback) {
List<String> missingPermissions = new ArrayList<>();
for (String permission : requiredPermissions) {
int status = ActivityCompat.checkSelfPermission(activity, permission);
if (status != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
((PermissionAwareActivity) activity).requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), 1, new PermissionListener() {
@Override
public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 1) {
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
promise.reject(E_PERMISSIONS_MISSING, "Required permission missing");
return true;
}
}
try {
callback.call();
} catch (Exception e) {
promise.reject(E_CALLBACK_ERROR, "Unknown error", e);
}
}
return true;
}
});
return;
}
// all permissions granted
try {
callback.call();
} catch (Exception e) {
promise.reject(E_CALLBACK_ERROR, "Unknown error", e);
}
}
@ReactMethod
public void openCamera(final ReadableMap options, final Promise promise) {
final Activity activity = getCurrentActivity();
if (activity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
if (!isCameraAvailable(activity)) {
promise.reject(E_CAMERA_IS_NOT_AVAILABLE, "Camera not available");
return;
}
setConfiguration(options);
resultCollector = new ResultCollector(promise, multiple);
permissionsCheck(activity, promise, Arrays.asList(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE), new Callable<Void>() {
@Override
public Void call() throws Exception {
initiateCamera(activity);
return null;
}
});
}
private void initiateCamera(Activity activity) {
try {
int requestCode = CAMERA_PICKER_REQUEST;
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imageFile = createImageFile();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
mCameraCaptureURI = Uri.fromFile(imageFile);
} else {
mCameraCaptureURI = FileProvider.getUriForFile(activity,
activity.getApplicationContext().getPackageName() + ".provider",
imageFile);
}
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraCaptureURI);
if (cameraIntent.resolveActivity(activity.getPackageManager()) == null) {
resultCollector.notifyProblem(E_CANNOT_LAUNCH_CAMERA, "Cannot launch camera");
return;
}
activity.startActivityForResult(cameraIntent, requestCode);
} catch (Exception e) {
resultCollector.notifyProblem(E_FAILED_TO_OPEN_CAMERA, e);
}
}
private void initiatePicker(final Activity activity) {
try {
final Intent galleryIntent = new Intent(Intent.ACTION_PICK);
if (cropping || mediaType.equals("photo")) {
galleryIntent.setType("image/*");
} else if (mediaType.equals("video")) {
galleryIntent.setType("video/*");
} else {
galleryIntent.setType("*/*");
String[] mimetypes = {"image/*", "video/*"};
galleryIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
}
galleryIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, multiple);
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Pick an image");
activity.startActivityForResult(chooserIntent, IMAGE_PICKER_REQUEST);
} catch (Exception e) {
resultCollector.notifyProblem(E_FAILED_TO_SHOW_PICKER, e);
}
}
@ReactMethod
public void openPicker(final ReadableMap options, final Promise promise) {
final Activity activity = getCurrentActivity();
if (activity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
setConfiguration(options);
resultCollector = new ResultCollector(promise, multiple);
permissionsCheck(activity, promise, Collections.singletonList(Manifest.permission.WRITE_EXTERNAL_STORAGE), new Callable<Void>() {
@Override
public Void call() throws Exception {
initiatePicker(activity);
return null;
}
});
}
@ReactMethod
public void openCropper(final ReadableMap options, final Promise promise) {
final Activity activity = getCurrentActivity();
if (activity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
setConfiguration(options);
resultCollector = new ResultCollector(promise, false);
Uri uri = Uri.parse(options.getString("path"));
startCropping(activity, uri);
}
private String getBase64StringFromFile(String absoluteFilePath) {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(absoluteFilePath));
} 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);
}
private static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
private WritableMap getSelection(Activity activity, Uri uri, boolean isCamera) throws Exception {
String path = resolveRealPath(activity, uri, isCamera);
if (path == null || path.isEmpty()) {
throw new Exception("Cannot resolve asset path.");
}
return getImage(activity, path);
}
private void getAsyncSelection(final Activity activity, Uri uri, boolean isCamera) throws Exception {
String path = resolveRealPath(activity, uri, isCamera);
if (path == null || path.isEmpty()) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, "Cannot resolve asset path.");
return;
}
String mime = getMimeType(path);
if (mime != null && mime.startsWith("video/")) {
getVideo(activity, path, mime);
return;
}
resultCollector.notifySuccess(getImage(activity, path));
}
private Bitmap validateVideo(String path) throws Exception {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(path);
Bitmap bmp = retriever.getFrameAtTime();
if (bmp == null) {
throw new Exception("Cannot retrieve video data");
}
return bmp;
}
private void getVideo(final Activity activity, final String path, final String mime) throws Exception {
validateVideo(path);
final String compressedVideoPath = getTmpDir(activity) + "/" + UUID.randomUUID().toString() + ".mp4";
new Thread(new Runnable() {
@Override
public void run() {
compression.compressVideo(activity, options, path, compressedVideoPath, new PromiseImpl(new Callback() {
@Override
public void invoke(Object... args) {
String videoPath = (String) args[0];
try {
Bitmap bmp = validateVideo(videoPath);
WritableMap video = new WritableNativeMap();
video.putInt("width", bmp.getWidth());
video.putInt("height", bmp.getHeight());
video.putString("mime", mime);
video.putInt("size", (int) new File(videoPath).length());
video.putString("path", "file://" + videoPath);
resultCollector.notifySuccess(video);
} catch (Exception e) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, e);
}
}
}, new Callback() {
@Override
public void invoke(Object... args) {
WritableNativeMap ex = (WritableNativeMap) args[0];
resultCollector.notifyProblem(ex.getString("code"), ex.getString("message"));
}
}));
}
}).run();
}
private String resolveRealPath(Activity activity, Uri uri, boolean isCamera) {
String path;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
path = RealPathUtil.getRealPathFromURI(activity, uri);
} else {
if (isCamera) {
Uri imageUri = Uri.parse(mCurrentPhotoPath);
path = imageUri.getPath();
} else {
path = RealPathUtil.getRealPathFromURI(activity, uri);
}
}
return path;
}
private BitmapFactory.Options validateImage(String path) throws Exception {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
BitmapFactory.decodeFile(path, options);
if (options.outMimeType == null || options.outWidth == 0 || options.outHeight == 0) {
throw new Exception("Invalid image selected");
}
return options;
}
private WritableMap getImage(final Activity activity, String path) throws Exception {
WritableMap image = new WritableNativeMap();
if (path.startsWith("http://") || path.startsWith("https://")) {
throw new Exception("Cannot select remote files");
}
validateImage(path);
// if compression options are provided image will be compressed. If none options is provided,
// then original image will be returned
File compressedImage = compression.compressImage(activity, options, path);
String compressedImagePath = compressedImage.getPath();
BitmapFactory.Options options = validateImage(compressedImagePath);
image.putString("path", "file://" + compressedImagePath);
image.putInt("width", options.outWidth);
image.putInt("height", options.outHeight);
image.putString("mime", options.outMimeType);
image.putInt("size", (int) new File(compressedImagePath).length());
if (includeBase64) {
image.putString("data", getBase64StringFromFile(compressedImagePath));
}
return image;
}
private void configureCropperColors(UCrop.Options options) {
int activeWidgetColor = Color.parseColor(cropperActiveWidgetColor);
int toolbarColor = Color.parseColor(cropperToolbarColor);
int statusBarColor = Color.parseColor(cropperStatusBarColor);
options.setToolbarColor(toolbarColor);
options.setStatusBarColor(statusBarColor);
if (activeWidgetColor == Color.parseColor(DEFAULT_TINT)) {
/*
Default tint is grey => use a more flashy color that stands out more as the call to action
Here we use 'Light Blue 500' from https://material.google.com/style/color.html#color-color-palette
*/
options.setActiveWidgetColor(Color.parseColor(DEFAULT_WIDGET_COLOR));
} else {
//If they pass a custom tint color in, we use this for everything
options.setActiveWidgetColor(activeWidgetColor);
}
}
private void startCropping(Activity activity, Uri uri) {
UCrop.Options options = new UCrop.Options();
options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
options.setCompressionQuality(100);
options.setCircleDimmedLayer(cropperCircleOverlay);
options.setShowCropGrid(showCropGuidelines);
options.setHideBottomControls(hideBottomControls);
if (enableRotationGesture) {
// UCropActivity.ALL = enable both rotation & scaling
options.setAllowedGestures(
UCropActivity.ALL, // When 'scale'-tab active
UCropActivity.ALL, // When 'rotate'-tab active
UCropActivity.ALL // When 'aspect ratio'-tab active
);
}
configureCropperColors(options);
UCrop.of(uri, Uri.fromFile(new File(this.getTmpDir(activity), UUID.randomUUID().toString() + ".jpg")))
.withMaxResultSize(width, height)
.withAspectRatio(width, height)
.withOptions(options)
.start(activity);
}
private void imagePickerResult(Activity activity, final int requestCode, final int resultCode, final Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
resultCollector.notifyProblem(E_PICKER_CANCELLED_KEY, E_PICKER_CANCELLED_MSG);
} else if (resultCode == Activity.RESULT_OK) {
if (multiple) {
ClipData clipData = data.getClipData();
try {
// only one image selected
if (clipData == null) {
resultCollector.setWaitCount(1);
getAsyncSelection(activity, data.getData(), false);
} else {
resultCollector.setWaitCount(clipData.getItemCount());
for (int i = 0; i < clipData.getItemCount(); i++) {
getAsyncSelection(activity, clipData.getItemAt(i).getUri(), false);
}
}
} catch (Exception ex) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, ex.getMessage());
}
} else {
Uri uri = data.getData();
if (uri == null) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, "Cannot resolve image url");
return;
}
if (cropping) {
startCropping(activity, uri);
} else {
try {
getAsyncSelection(activity, uri, false);
} catch (Exception ex) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, ex.getMessage());
}
}
}
}
}
private void cameraPickerResult(Activity activity, final int requestCode, final int resultCode, final Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
resultCollector.notifyProblem(E_PICKER_CANCELLED_KEY, E_PICKER_CANCELLED_MSG);
} else if (resultCode == Activity.RESULT_OK) {
Uri uri = mCameraCaptureURI;
if (uri == null) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, "Cannot resolve image url");
return;
}
if (cropping) {
UCrop.Options options = new UCrop.Options();
options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
startCropping(activity, uri);
} else {
try {
resultCollector.setWaitCount(1);
resultCollector.notifySuccess(getSelection(activity, uri, true));
} catch (Exception ex) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, ex.getMessage());
}
}
}
}
private void croppingResult(Activity activity, final int requestCode, final int resultCode, final Intent data) {
if (data != null) {
final Uri resultUri = UCrop.getOutput(data);
if (resultUri != null) {
try {
resultCollector.setWaitCount(1);
resultCollector.notifySuccess(getSelection(activity, resultUri, false));
} catch (Exception ex) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, ex.getMessage());
}
} else {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, "Cannot find image data");
}
} else {
resultCollector.notifyProblem(E_PICKER_CANCELLED_KEY, E_PICKER_CANCELLED_MSG);
}
}
@Override
public void onActivityResult(Activity activity, final int requestCode, final int resultCode, final Intent data) {
if (requestCode == IMAGE_PICKER_REQUEST) {
imagePickerResult(activity, requestCode, resultCode, data);
} else if (requestCode == CAMERA_PICKER_REQUEST) {
cameraPickerResult(activity, requestCode, resultCode, data);
} else if (requestCode == UCrop.REQUEST_CROP) {
croppingResult(activity, requestCode, resultCode, data);
}
}
@Override
public void onNewIntent(Intent intent) {
}
private boolean isCameraAvailable(Activity activity) {
return activity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)
|| activity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
private File createImageFile() throws IOException {
String imageFileName = "image-" + UUID.randomUUID().toString();
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
if (!path.exists() && !path.isDirectory()) {
path.mkdirs();
}
File image = File.createTempFile(imageFileName, ".jpg", path);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
}
|
android/src/main/java/com/reactnative/ivpusic/imagepicker/PickerModule.java
|
package com.reactnative.ivpusic.imagepicker;
import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Base64;
import android.webkit.MimeTypeMap;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.PromiseImpl;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Callable;
class PickerModule extends ReactContextBaseJavaModule implements ActivityEventListener {
private static final int IMAGE_PICKER_REQUEST = 61110;
private static final int CAMERA_PICKER_REQUEST = 61111;
private static final String E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST";
private static final String E_PICKER_CANCELLED_KEY = "E_PICKER_CANCELLED";
private static final String E_PICKER_CANCELLED_MSG = "User cancelled image selection";
private static final String E_CALLBACK_ERROR = "E_CALLBACK_ERROR";
private static final String E_FAILED_TO_SHOW_PICKER = "E_FAILED_TO_SHOW_PICKER";
private static final String E_FAILED_TO_OPEN_CAMERA = "E_FAILED_TO_OPEN_CAMERA";
private static final String E_NO_IMAGE_DATA_FOUND = "E_NO_IMAGE_DATA_FOUND";
private static final String E_CAMERA_IS_NOT_AVAILABLE = "E_CAMERA_IS_NOT_AVAILABLE";
private static final String E_CANNOT_LAUNCH_CAMERA = "E_CANNOT_LAUNCH_CAMERA";
private static final String E_PERMISSIONS_MISSING = "E_PERMISSIONS_MISSING";
private static final String E_ERROR_WHILE_CLEANING_FILES = "E_ERROR_WHILE_CLEANING_FILES";
private String mediaType = "any";
private boolean multiple = false;
private boolean includeBase64 = false;
private boolean cropping = false;
private boolean cropperCircleOverlay = false;
private boolean showCropGuidelines = true;
private boolean hideBottomControls = false;
private boolean enableRotationGesture = false;
private ReadableMap options;
//Grey 800
private final String DEFAULT_TINT = "#424242";
private String cropperActiveWidgetColor = DEFAULT_TINT;
private String cropperStatusBarColor = DEFAULT_TINT;
private String cropperToolbarColor = DEFAULT_TINT;
//Light Blue 500
private final String DEFAULT_WIDGET_COLOR = "#03A9F4";
private int width = 200;
private int height = 200;
private Uri mCameraCaptureURI;
private String mCurrentPhotoPath;
private ResultCollector resultCollector;
private Compression compression = new Compression();
PickerModule(ReactApplicationContext reactContext) {
super(reactContext);
reactContext.addActivityEventListener(this);
}
private String getTmpDir(Activity activity) {
String tmpDir = activity.getCacheDir() + "/react-native-image-crop-picker";
Boolean created = new File(tmpDir).mkdir();
return tmpDir;
}
@Override
public String getName() {
return "ImageCropPicker";
}
private void setConfiguration(final ReadableMap options) {
mediaType = options.hasKey("mediaType") ? options.getString("mediaType") : mediaType;
multiple = options.hasKey("multiple") && options.getBoolean("multiple");
includeBase64 = options.hasKey("includeBase64") && options.getBoolean("includeBase64");
width = options.hasKey("width") ? options.getInt("width") : width;
height = options.hasKey("height") ? options.getInt("height") : height;
cropping = options.hasKey("cropping") ? options.getBoolean("cropping") : cropping;
cropperActiveWidgetColor = options.hasKey("cropperActiveWidgetColor") ? options.getString("cropperActiveWidgetColor") : cropperActiveWidgetColor;
cropperStatusBarColor = options.hasKey("cropperStatusBarColor") ? options.getString("cropperStatusBarColor") : cropperStatusBarColor;
cropperToolbarColor = options.hasKey("cropperToolbarColor") ? options.getString("cropperToolbarColor") : cropperToolbarColor;
cropperCircleOverlay = options.hasKey("cropperCircleOverlay") ? options.getBoolean("cropperCircleOverlay") : cropperCircleOverlay;
showCropGuidelines = options.hasKey("showCropGuidelines") ? options.getBoolean("showCropGuidelines") : showCropGuidelines;
hideBottomControls = options.hasKey("hideBottomControls") ? options.getBoolean("hideBottomControls") : hideBottomControls;
enableRotationGesture = options.hasKey("enableRotationGesture") ? options.getBoolean("enableRotationGesture") : enableRotationGesture;
this.options = options;
}
private void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
deleteRecursive(child);
}
}
fileOrDirectory.delete();
}
@ReactMethod
public void clean(final Promise promise) {
final Activity activity = getCurrentActivity();
final PickerModule module = this;
if (activity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
permissionsCheck(activity, promise, Arrays.asList(Manifest.permission.WRITE_EXTERNAL_STORAGE), new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
File file = new File(module.getTmpDir(activity));
if (!file.exists()) throw new Exception("File does not exist");
module.deleteRecursive(file);
promise.resolve(null);
} catch (Exception ex) {
ex.printStackTrace();
promise.reject(E_ERROR_WHILE_CLEANING_FILES, ex.getMessage());
}
return null;
}
});
}
@ReactMethod
public void cleanSingle(final String pathToDelete, final Promise promise) {
if (pathToDelete == null) {
promise.reject(E_ERROR_WHILE_CLEANING_FILES, "Cannot cleanup empty path");
return;
}
final Activity activity = getCurrentActivity();
final PickerModule module = this;
if (activity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
permissionsCheck(activity, promise, Arrays.asList(Manifest.permission.WRITE_EXTERNAL_STORAGE), new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
String path = pathToDelete;
final String filePrefix = "file://";
if (path.startsWith(filePrefix)) {
path = path.substring(filePrefix.length());
}
File file = new File(path);
if (!file.exists()) throw new Exception("File does not exist. Path: " + path);
module.deleteRecursive(file);
promise.resolve(null);
} catch (Exception ex) {
ex.printStackTrace();
promise.reject(E_ERROR_WHILE_CLEANING_FILES, ex.getMessage());
}
return null;
}
});
}
private void permissionsCheck(final Activity activity, final Promise promise, final List<String> requiredPermissions, final Callable<Void> callback) {
List<String> missingPermissions = new ArrayList<>();
for (String permission : requiredPermissions) {
int status = ActivityCompat.checkSelfPermission(activity, permission);
if (status != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
((PermissionAwareActivity) activity).requestPermissions(missingPermissions.toArray(new String[missingPermissions.size()]), 1, new PermissionListener() {
@Override
public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 1) {
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
promise.reject(E_PERMISSIONS_MISSING, "Required permission missing");
return true;
}
}
try {
callback.call();
} catch (Exception e) {
promise.reject(E_CALLBACK_ERROR, "Unknown error", e);
}
}
return true;
}
});
return;
}
// all permissions granted
try {
callback.call();
} catch (Exception e) {
promise.reject(E_CALLBACK_ERROR, "Unknown error", e);
}
}
@ReactMethod
public void openCamera(final ReadableMap options, final Promise promise) {
final Activity activity = getCurrentActivity();
if (activity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
if (!isCameraAvailable(activity)) {
promise.reject(E_CAMERA_IS_NOT_AVAILABLE, "Camera not available");
return;
}
setConfiguration(options);
resultCollector = new ResultCollector(promise, multiple);
permissionsCheck(activity, promise, Arrays.asList(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE), new Callable<Void>() {
@Override
public Void call() throws Exception {
initiateCamera(activity);
return null;
}
});
}
private void initiateCamera(Activity activity) {
try {
int requestCode = CAMERA_PICKER_REQUEST;
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imageFile = createImageFile();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
mCameraCaptureURI = Uri.fromFile(imageFile);
} else {
mCameraCaptureURI = FileProvider.getUriForFile(activity,
activity.getApplicationContext().getPackageName() + ".provider",
imageFile);
}
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraCaptureURI);
if (cameraIntent.resolveActivity(activity.getPackageManager()) == null) {
resultCollector.notifyProblem(E_CANNOT_LAUNCH_CAMERA, "Cannot launch camera");
return;
}
activity.startActivityForResult(cameraIntent, requestCode);
} catch (Exception e) {
resultCollector.notifyProblem(E_FAILED_TO_OPEN_CAMERA, e);
}
}
private void initiatePicker(final Activity activity) {
try {
final Intent galleryIntent = new Intent(Intent.ACTION_PICK);
if (cropping || mediaType.equals("photo")) {
galleryIntent.setType("image/*");
} else if (mediaType.equals("video")) {
galleryIntent.setType("video/*");
} else {
galleryIntent.setType("*/*");
String[] mimetypes = {"image/*", "video/*"};
galleryIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
}
galleryIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, multiple);
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Pick an image");
activity.startActivityForResult(chooserIntent, IMAGE_PICKER_REQUEST);
} catch (Exception e) {
resultCollector.notifyProblem(E_FAILED_TO_SHOW_PICKER, e);
}
}
@ReactMethod
public void openPicker(final ReadableMap options, final Promise promise) {
final Activity activity = getCurrentActivity();
if (activity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
setConfiguration(options);
resultCollector = new ResultCollector(promise, multiple);
permissionsCheck(activity, promise, Collections.singletonList(Manifest.permission.WRITE_EXTERNAL_STORAGE), new Callable<Void>() {
@Override
public Void call() throws Exception {
initiatePicker(activity);
return null;
}
});
}
@ReactMethod
public void openCropper(final ReadableMap options, final Promise promise) {
final Activity activity = getCurrentActivity();
if (activity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
setConfiguration(options);
resultCollector = new ResultCollector(promise, false);
Uri uri = Uri.parse(options.getString("path"));
startCropping(activity, uri);
}
private String getBase64StringFromFile(String absoluteFilePath) {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(absoluteFilePath));
} 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);
}
private static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
private WritableMap getSelection(Activity activity, Uri uri, boolean isCamera) throws Exception {
String path = resolveRealPath(activity, uri, isCamera);
if (path == null || path.isEmpty()) {
throw new Exception("Cannot resolve asset path.");
}
return getImage(activity, path);
}
private void getAsyncSelection(final Activity activity, Uri uri, boolean isCamera) throws Exception {
String path = resolveRealPath(activity, uri, isCamera);
if (path == null || path.isEmpty()) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, "Cannot resolve asset path.");
return;
}
String mime = getMimeType(path);
if (mime != null && mime.startsWith("video/")) {
getVideo(activity, path, mime);
return;
}
resultCollector.notifySuccess(getImage(activity, path));
}
private Bitmap validateVideo(String path) throws Exception {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(path);
Bitmap bmp = retriever.getFrameAtTime();
if (bmp == null) {
throw new Exception("Cannot retrieve video data");
}
return bmp;
}
private void getVideo(final Activity activity, final String path, final String mime) throws Exception {
validateVideo(path);
final String compressedVideoPath = getTmpDir(activity) + "/" + UUID.randomUUID().toString() + ".mp4";
new Thread(new Runnable() {
@Override
public void run() {
compression.compressVideo(activity, options, path, compressedVideoPath, new PromiseImpl(new Callback() {
@Override
public void invoke(Object... args) {
String videoPath = (String) args[0];
try {
Bitmap bmp = validateVideo(videoPath);
WritableMap video = new WritableNativeMap();
video.putInt("width", bmp.getWidth());
video.putInt("height", bmp.getHeight());
video.putString("mime", mime);
video.putInt("size", (int) new File(videoPath).length());
video.putString("path", "file://" + videoPath);
resultCollector.notifySuccess(video);
} catch (Exception e) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, e);
}
}
}, new Callback() {
@Override
public void invoke(Object... args) {
WritableNativeMap ex = (WritableNativeMap) args[0];
resultCollector.notifyProblem(ex.getString("code"), ex.getString("message"));
}
}));
}
}).run();
}
private String resolveRealPath(Activity activity, Uri uri, boolean isCamera) {
String path;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
path = RealPathUtil.getRealPathFromURI(activity, uri);
} else {
if (isCamera) {
Uri imageUri = Uri.parse(mCurrentPhotoPath);
path = imageUri.getPath();
} else {
path = RealPathUtil.getRealPathFromURI(activity, uri);
}
}
return path;
}
private BitmapFactory.Options validateImage(String path) throws Exception {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
BitmapFactory.decodeFile(path, options);
if (options.outMimeType == null || options.outWidth == 0 || options.outHeight == 0) {
throw new Exception("Invalid image selected");
}
return options;
}
private WritableMap getImage(final Activity activity, String path) throws Exception {
WritableMap image = new WritableNativeMap();
if (path.startsWith("http://") || path.startsWith("https://")) {
throw new Exception("Cannot select remote files");
}
validateImage(path);
// if compression options are provided image will be compressed. If none options is provided,
// then original image will be returned
File compressedImage = compression.compressImage(activity, options, path);
String compressedImagePath = compressedImage.getPath();
BitmapFactory.Options options = validateImage(compressedImagePath);
image.putString("path", "file://" + compressedImagePath);
image.putInt("width", options.outWidth);
image.putInt("height", options.outHeight);
image.putString("mime", options.outMimeType);
image.putInt("size", (int) new File(compressedImagePath).length());
if (includeBase64) {
image.putString("data", getBase64StringFromFile(compressedImagePath));
}
return image;
}
private void configureCropperColors(UCrop.Options options) {
int activeWidgetColor = Color.parseColor(cropperActiveWidgetColor);
int toolbarColor = Color.parseColor(cropperToolbarColor);
int statusBarColor = Color.parseColor(cropperStatusBarColor);
options.setToolbarColor(toolbarColor);
options.setStatusBarColor(statusBarColor);
if (activeWidgetColor == Color.parseColor(DEFAULT_TINT)) {
/*
Default tint is grey => use a more flashy color that stands out more as the call to action
Here we use 'Light Blue 500' from https://material.google.com/style/color.html#color-color-palette
*/
options.setActiveWidgetColor(Color.parseColor(DEFAULT_WIDGET_COLOR));
} else {
//If they pass a custom tint color in, we use this for everything
options.setActiveWidgetColor(activeWidgetColor);
}
}
private void startCropping(Activity activity, Uri uri) {
UCrop.Options options = new UCrop.Options();
options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
options.setCompressionQuality(100);
options.setCircleDimmedLayer(cropperCircleOverlay);
options.setShowCropGrid(showCropGuidelines);
options.setHideBottomControls(hideBottomControls);
if (enableRotationGesture) {
// UCropActivity.ALL = enable both rotation & scaling
options.setAllowedGestures(
UCropActivity.ALL, // When 'scale'-tab active
UCropActivity.ALL, // When 'rotate'-tab active
UCropActivity.ALL // When 'aspect ratio'-tab active
);
}
configureCropperColors(options);
UCrop.of(uri, Uri.fromFile(new File(this.getTmpDir(activity), UUID.randomUUID().toString() + ".jpg")))
.withMaxResultSize(width, height)
.withAspectRatio(width, height)
.withOptions(options)
.start(activity);
}
private void imagePickerResult(Activity activity, final int requestCode, final int resultCode, final Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
resultCollector.notifyProblem(E_PICKER_CANCELLED_KEY, E_PICKER_CANCELLED_MSG);
} else if (resultCode == Activity.RESULT_OK) {
if (multiple) {
ClipData clipData = data.getClipData();
try {
// only one image selected
if (clipData == null) {
resultCollector.setWaitCount(1);
getAsyncSelection(activity, data.getData(), false);
} else {
resultCollector.setWaitCount(clipData.getItemCount());
for (int i = 0; i < clipData.getItemCount(); i++) {
getAsyncSelection(activity, clipData.getItemAt(i).getUri(), false);
}
}
} catch (Exception ex) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, ex.getMessage());
}
} else {
Uri uri = data.getData();
if (uri == null) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, "Cannot resolve image url");
return;
}
if (cropping) {
startCropping(activity, uri);
} else {
try {
getAsyncSelection(activity, uri, false);
} catch (Exception ex) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, ex.getMessage());
}
}
}
}
}
private void cameraPickerResult(Activity activity, final int requestCode, final int resultCode, final Intent data) {
if (resultCode == Activity.RESULT_CANCELED) {
resultCollector.notifyProblem(E_PICKER_CANCELLED_KEY, E_PICKER_CANCELLED_MSG);
} else if (resultCode == Activity.RESULT_OK) {
Uri uri = mCameraCaptureURI;
if (uri == null) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, "Cannot resolve image url");
return;
}
if (cropping) {
UCrop.Options options = new UCrop.Options();
options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
startCropping(activity, uri);
} else {
try {
resultCollector.notifySuccess(getSelection(activity, uri, true));
} catch (Exception ex) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, ex.getMessage());
}
}
}
}
private void croppingResult(Activity activity, final int requestCode, final int resultCode, final Intent data) {
if (data != null) {
final Uri resultUri = UCrop.getOutput(data);
if (resultUri != null) {
try {
resultCollector.notifySuccess(getSelection(activity, resultUri, false));
} catch (Exception ex) {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, ex.getMessage());
}
} else {
resultCollector.notifyProblem(E_NO_IMAGE_DATA_FOUND, "Cannot find image data");
}
} else {
resultCollector.notifyProblem(E_PICKER_CANCELLED_KEY, E_PICKER_CANCELLED_MSG);
}
}
@Override
public void onActivityResult(Activity activity, final int requestCode, final int resultCode, final Intent data) {
if (requestCode == IMAGE_PICKER_REQUEST) {
imagePickerResult(activity, requestCode, resultCode, data);
} else if (requestCode == CAMERA_PICKER_REQUEST) {
cameraPickerResult(activity, requestCode, resultCode, data);
} else if (requestCode == UCrop.REQUEST_CROP) {
croppingResult(activity, requestCode, resultCode, data);
}
}
@Override
public void onNewIntent(Intent intent) {
}
private boolean isCameraAvailable(Activity activity) {
return activity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)
|| activity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
private File createImageFile() throws IOException {
String imageFileName = "image-" + UUID.randomUUID().toString();
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
if (!path.exists() && !path.isDirectory()) {
path.mkdirs();
}
File image = File.createTempFile(imageFileName, ".jpg", path);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
}
|
fixed a bug when using openCamera with [multiple: true]
related issue: https://github.com/ivpusic/react-native-image-crop-picker/issues/353
|
android/src/main/java/com/reactnative/ivpusic/imagepicker/PickerModule.java
|
fixed a bug when using openCamera with [multiple: true]
|
|
Java
|
mit
|
5ec3f5839b8905ddaa0961193db92a75dd176a0d
| 0
|
wepay/WePay-Java-SDK
|
package com.wepay.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.HttpsURLConnection;
import com.wepay.model.data.HeaderData;
import org.json.JSONObject;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wepay.exception.WePayException;
import com.wepay.model.data.deserialization.WepayExclusionStrategy;
public class WePayResource {
public static String apiEndpoint;
public static String uiEndpoint;
protected final static String STAGE_API_ENDPOINT = "https://stage.wepayapi.com/v2";
protected final static String STAGE_UI_ENDPOINT = "https://stage.wepay.com/v2";
protected final static String PRODUCTION_API_ENDPOINT = "https://wepayapi.com/v2";
protected final static String PRODUCTION_UI_ENDPOINT = "https://www.wepay.com/v2";
public static final Gson gson = new GsonBuilder()
.addDeserializationExclusionStrategy(new WepayExclusionStrategy())
.setPrettyPrinting()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
public static void initializeWePayResource(Boolean useStageEnv) {
if (useStageEnv) {
apiEndpoint = STAGE_API_ENDPOINT;
uiEndpoint = STAGE_UI_ENDPOINT;
} else {
apiEndpoint = PRODUCTION_API_ENDPOINT;
uiEndpoint = PRODUCTION_UI_ENDPOINT;
}
}
protected static javax.net.ssl.HttpsURLConnection httpsConnect(String call, HeaderData headerData) throws IOException {
URL url = new URL(apiEndpoint + call);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setConnectTimeout(30000); // 30 seconds
connection.setReadTimeout(100000); // 100 seconds
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Api-Version", "2018-10-03");
connection.setRequestProperty("User-Agent", "WePay Java SDK v11.0.0");
if (headerData != null) {
if (headerData.accessToken != null) {
connection.setRequestProperty("Authorization", "Bearer " + headerData.accessToken);
}
if (headerData.riskToken != null) {
connection.setRequestProperty("WePay-Risk-Token", headerData.riskToken);
}
if (headerData.clientIP != null) {
connection.setRequestProperty("Client-IP", headerData.clientIP);
}
}
return connection;
}
protected static javax.net.ssl.HttpsURLConnection httpsConnect(String call, String accessToken) throws IOException {
HeaderData headerData = new HeaderData();
if (accessToken != null) {
headerData.accessToken = accessToken;
}
return httpsConnect(call, headerData);
}
public static String request(String call, JSONObject params, HeaderData headerData) throws WePayException, IOException {
HttpsURLConnection connection = httpsConnect(call, headerData);
Writer wr=new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
wr.write(params.toString());
wr.flush();
wr.close();
boolean error = false;
int responseCode = connection.getResponseCode();
InputStream is;
if (responseCode >= 200 && responseCode < 300) {
is = connection.getInputStream();
}
else {
is = connection.getErrorStream();
error = true;
}
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
String responseString = response.toString();
if (error) {
WePayException ex = WePayResource.gson.fromJson(responseString, WePayException.class);
throw ex;
}
return responseString;
}
public static String request(String call, JSONObject params, String accessToken) throws WePayException, IOException {
HeaderData headerData = new HeaderData();
if (accessToken != null) {
headerData.accessToken = accessToken;
}
return request(call, params, headerData);
}
}
|
src/main/java/com/wepay/net/WePayResource.java
|
package com.wepay.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.HttpsURLConnection;
import com.wepay.model.data.HeaderData;
import org.json.JSONObject;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wepay.exception.WePayException;
import com.wepay.model.data.deserialization.WepayExclusionStrategy;
public class WePayResource {
public static String apiEndpoint;
public static String uiEndpoint;
protected final static String STAGE_API_ENDPOINT = "https://stage.wepayapi.com/v2";
protected final static String STAGE_UI_ENDPOINT = "https://stage.wepay.com/v2";
protected final static String PRODUCTION_API_ENDPOINT = "https://wepayapi.com/v2";
protected final static String PRODUCTION_UI_ENDPOINT = "https://www.wepay.com/v2";
public static final Gson gson = new GsonBuilder()
.addDeserializationExclusionStrategy(new WepayExclusionStrategy())
.setPrettyPrinting()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
public static void initializeWePayResource(Boolean useStageEnv) {
if (useStageEnv) {
apiEndpoint = STAGE_API_ENDPOINT;
uiEndpoint = STAGE_UI_ENDPOINT;
} else {
apiEndpoint = PRODUCTION_API_ENDPOINT;
uiEndpoint = PRODUCTION_UI_ENDPOINT;
}
}
protected static javax.net.ssl.HttpsURLConnection httpsConnect(String call, HeaderData headerData) throws IOException {
URL url = new URL(apiEndpoint + call);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setConnectTimeout(30000); // 30 seconds
connection.setReadTimeout(100000); // 100 seconds
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Api-Version", "2018-10-03");
connection.setRequestProperty("User-Agent", "WePay Java SDK v10.2.0");
if (headerData != null) {
if (headerData.accessToken != null) {
connection.setRequestProperty("Authorization", "Bearer " + headerData.accessToken);
}
if (headerData.riskToken != null) {
connection.setRequestProperty("WePay-Risk-Token", headerData.riskToken);
}
if (headerData.clientIP != null) {
connection.setRequestProperty("Client-IP", headerData.clientIP);
}
}
return connection;
}
protected static javax.net.ssl.HttpsURLConnection httpsConnect(String call, String accessToken) throws IOException {
HeaderData headerData = new HeaderData();
if (accessToken != null) {
headerData.accessToken = accessToken;
}
return httpsConnect(call, headerData);
}
public static String request(String call, JSONObject params, HeaderData headerData) throws WePayException, IOException {
HttpsURLConnection connection = httpsConnect(call, headerData);
Writer wr=new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
wr.write(params.toString());
wr.flush();
wr.close();
boolean error = false;
int responseCode = connection.getResponseCode();
InputStream is;
if (responseCode >= 200 && responseCode < 300) {
is = connection.getInputStream();
}
else {
is = connection.getErrorStream();
error = true;
}
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
String responseString = response.toString();
if (error) {
WePayException ex = WePayResource.gson.fromJson(responseString, WePayException.class);
throw ex;
}
return responseString;
}
public static String request(String call, JSONObject params, String accessToken) throws WePayException, IOException {
HeaderData headerData = new HeaderData();
if (accessToken != null) {
headerData.accessToken = accessToken;
}
return request(call, params, headerData);
}
}
|
Fix the SDK version
|
src/main/java/com/wepay/net/WePayResource.java
|
Fix the SDK version
|
|
Java
|
mit
|
3d758f508610a82a242bb95bc1eb3fdb9ee73303
| 0
|
raeleus/skin-composer
|
/*******************************************************************************
* MIT License
*
* Copyright (c) 2022 Raymond Buckley
*
* 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 com.ray3k.skincomposer;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Net.HttpMethods;
import com.badlogic.gdx.Net.HttpRequest;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch;
import com.badlogic.gdx.net.HttpRequestBuilder;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.CheckBox.CheckBoxStyle;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton.ImageTextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle;
import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar.ProgressBarStyle;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle;
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox.SelectBoxStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Slider.SliderStyle;
import com.badlogic.gdx.scenes.scene2d.ui.SplitPane.SplitPaneStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextTooltip.TextTooltipStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad.TouchpadStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Tree.TreeStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Window.WindowStyle;
import com.badlogic.gdx.utils.Null;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.esotericsoftware.spine.AnimationStateData;
import com.esotericsoftware.spine.SkeletonData;
import com.esotericsoftware.spine.SkeletonJson;
import com.esotericsoftware.spine.SkeletonRenderer;
import com.ray3k.skincomposer.data.AtlasData;
import com.ray3k.skincomposer.data.JsonData;
import com.ray3k.skincomposer.data.ProjectData;
import com.ray3k.skincomposer.dialog.DialogFactory;
import com.ray3k.skincomposer.dialog.DialogListener;
import com.ray3k.skincomposer.utils.Utils;
import com.ray3k.stripe.FreeTypeSkin;
import com.ray3k.stripe.PopColorPicker.PopColorPickerStyle;
import com.ray3k.stripe.ScrollFocusListener;
import com.ray3k.tenpatch.TenPatchDrawable;
import dev.lyze.gdxtinyvg.TinyVGAssetLoader;
import dev.lyze.gdxtinyvg.drawers.TinyVGShapeDrawer;
import dev.lyze.gdxtinyvg.scene2d.TinyVGDrawable;
import space.earlygrey.shapedrawer.GraphDrawer;
public class Main extends ApplicationAdapter {
public final static String VERSION = "51";
public static String newVersion;
public static final Class[] BASIC_CLASSES = {Button.class, CheckBox.class,
ImageButton.class, ImageTextButton.class, Label.class, List.class,
ProgressBar.class, ScrollPane.class, SelectBox.class, Slider.class,
SplitPane.class, TextButton.class, TextField.class, TextTooltip.class,
Touchpad.class, Tree.class, Window.class};
public static final Class[] STYLE_CLASSES = {ButtonStyle.class,
CheckBoxStyle.class, ImageButtonStyle.class, ImageTextButtonStyle.class,
LabelStyle.class, ListStyle.class, ProgressBarStyle.class,
ScrollPaneStyle.class, SelectBoxStyle.class, SliderStyle.class,
SplitPaneStyle.class, TextButtonStyle.class, TextFieldStyle.class,
TextTooltipStyle.class, TouchpadStyle.class, TreeStyle.class,
WindowStyle.class};
public static Stage stage;
public static Skin skin;
public static ScreenViewport viewport;
public static TinyVGShapeDrawer shapeDrawer;
public static GraphDrawer graphDrawer;
public static DialogFactory dialogFactory;
public static DesktopWorker desktopWorker;
public static TenPatchDrawable loadingAnimation;
public static TenPatchDrawable loadingAnimation2;
public static UndoableManager undoableManager;
public static ProjectData projectData;
public static JsonData jsonData;
public static AtlasData atlasData;
public static RootTable rootTable;
public static IbeamListener ibeamListener;
public static MainListener mainListener;
public static HandListener handListener;
public static ScrollFocusListener scrollFocusListener;
public static ResizeArrowListener verticalResizeArrowListener;
public static ResizeArrowListener horizontalResizeArrowListener;
public static TooltipManager tooltipManager;
public static FileHandle appFolder;
private String[] args;
public static Main main;
public static SkeletonRenderer skeletonRenderer;
public static SkeletonData floppySkeletonData;
public static AnimationStateData floppyAnimationStateData;
public static SkeletonData uiScaleSkeletonData;
public static AnimationStateData uiScaleAnimationStateData;
public static SkeletonData textraTypistLogoSkeletonData;
public static AnimationStateData textraTypistLogoAnimationStateData;
public static SkeletonData arrowSkeletonData;
public static AnimationStateData arrowAnimationStateData;
public static TinyVGAssetLoader tinyVGAssetLoader;
private static final int SPINE_MAX_VERTS = 32767;
private static TinyVGDrawable drawable;
public static PopColorPickerStyle popColorPickerStyle;
public Main (String[] args) {
this.args = args;
main = this;
}
@Override
public void create() {
appFolder = Gdx.files.external(".skincomposer/");
skin = new FreeTypeSkin(Gdx.files.internal("skin-composer-ui/skin-composer-ui.json"));
viewport = new ScreenViewport();
// viewport.setUnitsPerPixel(.5f);
var batch = new PolygonSpriteBatch(SPINE_MAX_VERTS);
stage = new Stage(viewport, batch);
Gdx.input.setInputProcessor(stage);
shapeDrawer = new TinyVGShapeDrawer(stage.getBatch(), skin.getRegion("white"));
graphDrawer = new GraphDrawer(shapeDrawer);
tinyVGAssetLoader = new TinyVGAssetLoader();
skeletonRenderer = new SkeletonRenderer();
var skeletonJson = new SkeletonJson(Main.skin.getAtlas());
floppySkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/floppy.json"));
floppyAnimationStateData = new AnimationStateData(floppySkeletonData);
uiScaleSkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/uiscale.json"));
uiScaleAnimationStateData = new AnimationStateData(uiScaleSkeletonData);
textraTypistLogoSkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/TextraTypist Logo.json"));
textraTypistLogoAnimationStateData = new AnimationStateData(textraTypistLogoSkeletonData);
arrowSkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/arrow-animation.json"));
arrowAnimationStateData = new AnimationStateData(arrowSkeletonData);
popColorPickerStyle = new PopColorPickerStyle();
popColorPickerStyle.background = skin.getDrawable("cp-bg-10");
popColorPickerStyle.stageBackground = skin.getDrawable("stage-background");
popColorPickerStyle.titleBarBackground = skin.getDrawable("cp-title-bar-10");
popColorPickerStyle.labelStyle = skin.get("tt", LabelStyle.class);
popColorPickerStyle.fileTextButtonStyle = skin.get("cp-file", TextButtonStyle.class);
popColorPickerStyle.scrollPaneStyle = skin.get("tt", ScrollPaneStyle.class);
popColorPickerStyle.colorSwatch = skin.getDrawable("tt-color-swatch");
popColorPickerStyle.colorSwatchNew = skin.getDrawable("tt-color-swatch-new");
popColorPickerStyle.colorSwatchPopBackground = skin.getDrawable("tt-panel-10");
popColorPickerStyle.colorSwatchPopPreview = skin.getDrawable("tt-color-swatch-10");
popColorPickerStyle.previewSwatchBackground = skin.getDrawable("tt-swatch");
popColorPickerStyle.previewSwatchOld = skin.getDrawable("tt-swatch-old");
popColorPickerStyle.previewSwatchNew = skin.getDrawable("tt-swatch-new");
popColorPickerStyle.previewSwatchSingleBackground = skin.getDrawable("tt-swatch-null");
popColorPickerStyle.previewSwatchSingle = skin.getDrawable("tt-swatch-new-null");
popColorPickerStyle.textFieldStyle = skin.get("cp", TextFieldStyle.class);
popColorPickerStyle.hexTextFieldStyle = skin.get("cp-hexfield", TextFieldStyle.class);
popColorPickerStyle.textButtonStyle = skin.get("cp", TextButtonStyle.class);
popColorPickerStyle.colorSliderBackground = skin.getDrawable("tt-slider-10");
popColorPickerStyle.colorKnobCircleBackground = skin.getDrawable("tt-color-ball");
popColorPickerStyle.colorKnobCircleForeground = skin.getDrawable("tt-color-ball-interior");
popColorPickerStyle.colorSliderKnobHorizontal = skin.getDrawable("tt-slider-knob");
popColorPickerStyle.colorSliderKnobVertical = skin.getDrawable("tt-slider-knob-vertical");
popColorPickerStyle.radioButtonStyle = skin.get("cp-radio", ImageButtonStyle.class);
popColorPickerStyle.increaseButtonStyle = skin.get("cp-increase", ImageButtonStyle.class);
popColorPickerStyle.decreaseButtonStyle = skin.get("cp-decrease", ImageButtonStyle.class);
popColorPickerStyle.checkerBackground = skin.getDrawable("tt-checker-10");
initDefaults();
populate();
resizeUiScale(projectData.getUiScale());
}
private void initDefaults() {
if (Utils.isMac()) System.setProperty("java.awt.headless", "true");
skin.getFont("font").getData().markupEnabled = true;
//copy defaults.json to temp folder if it doesn't exist
var fileHandle = appFolder.child("texturepacker/atlas-export-settings.json");
if (!fileHandle.exists()) {
Gdx.files.internal("atlas-export-settings.json").copyTo(fileHandle);
}
//copy atlas settings for preview to temp folder if it doesn't exist
fileHandle = appFolder.child("texturepacker/atlas-internal-settings.json");
if (!fileHandle.exists()) {
Gdx.files.internal("atlas-internal-settings.json").copyTo(fileHandle);
}
//copy white-pixel.png for pixel drawables
fileHandle = appFolder.child("texturepacker/white-pixel.png");
if (!fileHandle.exists()) {
Gdx.files.internal("white-pixel.png").copyTo(fileHandle);
}
//copy preview fonts to preview fonts folder if they do not exist
fileHandle = appFolder.child("preview fonts/IBMPlexSerif-Medium.ttf");
if (!fileHandle.exists()) {
Gdx.files.internal("preview fonts/IBMPlexSerif-Medium.ttf").copyTo(fileHandle);
}
fileHandle = appFolder.child("preview fonts/Pacifico-Regular.ttf");
if (!fileHandle.exists()) {
Gdx.files.internal("preview fonts/Pacifico-Regular.ttf").copyTo(fileHandle);
}
fileHandle = appFolder.child("preview fonts/PressStart2P-Regular.ttf");
if (!fileHandle.exists()) {
Gdx.files.internal("preview fonts/PressStart2P-Regular.ttf").copyTo(fileHandle);
}
fileHandle = appFolder.child("preview fonts/SourceSansPro-Regular.ttf");
if (!fileHandle.exists()) {
Gdx.files.internal("preview fonts/SourceSansPro-Regular.ttf").copyTo(fileHandle);
}
ibeamListener = new IbeamListener();
dialogFactory = new DialogFactory();
projectData = new ProjectData();
projectData.randomizeId();
projectData.setMaxUndos(30);
atlasData = projectData.getAtlasData();
jsonData = projectData.getJsonData();
newVersion = VERSION;
if (projectData.isCheckingForUpdates()) {
checkForUpdates(this);
}
undoableManager = new UndoableManager(this);
desktopWorker.attachLogListener();
desktopWorker.setCloseListener(() -> {
dialogFactory.showCloseDialog(new DialogListener() {
@Override
public void opened() {
desktopWorker.removeFilesDroppedListener(rootTable.getFilesDroppedListener());
}
@Override
public void closed() {
desktopWorker.addFilesDroppedListener(rootTable.getFilesDroppedListener());
}
});
return false;
});
loadingAnimation = skin.get("loading-animation", TenPatchDrawable.class);
loadingAnimation2 = skin.get("loading-animation2", TenPatchDrawable.class);
projectData.getAtlasData().clearTempData();
handListener = new HandListener();
scrollFocusListener = new ScrollFocusListener(stage);
verticalResizeArrowListener = new ResizeArrowListener(true);
horizontalResizeArrowListener = new ResizeArrowListener(false);
tooltipManager = new TooltipManager();
tooltipManager.animations = false;
tooltipManager.initialTime = .4f;
tooltipManager.resetTime = 0.0f;
tooltipManager.subsequentTime = 0.0f;
tooltipManager.maxWidth = 400f;
tooltipManager.hideAll();
tooltipManager.instant();
}
private void populate() {
stage.clear();
rootTable = new RootTable();
rootTable.setFillParent(true);
mainListener = new MainListener();
rootTable.addListener(mainListener);
rootTable.populate();
stage.addActor(rootTable);
rootTable.updateRecentFiles();
//pass arguments
if (!mainListener.argumentsPassed(args)) {
//show welcome screen if there are no valid arguments
mainListener.createWelcomeListener();
}
}
@Override
public void render() {
Gdx.gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
for (var tenPatch : skin.getAll(TenPatchDrawable.class)) {
tenPatch.value.update(Gdx.graphics.getDeltaTime());
}
stage.draw();
}
@Override
public void resize(int width, int height) {
if (width != 0 && height != 0) {
stage.getViewport().update(width, height, true);
rootTable.fire(new StageResizeEvent(width, height));
}
}
@Override
public void dispose() {
stage.dispose();
skin.dispose();
}
public void resizeUiScale(int scale) {
resizeUiScale(scale, scale > 1);
}
public void resizeUiScale(int scale, boolean large) {
if (large) {
desktopWorker.sizeWindowToFit(1440, 1440, 50, Gdx.graphics);
} else {
desktopWorker.sizeWindowToFit(800, 800, 50, Gdx.graphics);
}
desktopWorker.centerWindow(Gdx.graphics);
viewport.setUnitsPerPixel(1f / scale);
viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
}
public static Class basicToStyleClass(Class clazz) {
int i = 0;
for (Class basicClass : BASIC_CLASSES) {
if (clazz.equals(basicClass)) {
break;
} else {
i++;
}
}
return i < STYLE_CLASSES.length ? STYLE_CLASSES[i] : null;
}
public static Class styleToBasicClass(Class clazz) {
int i = 0;
for (Class styleClass : STYLE_CLASSES) {
if (clazz.equals(styleClass)) {
break;
} else {
i++;
}
}
return BASIC_CLASSES[i];
}
public static void checkForUpdates(Main main) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://raw.githubusercontent.com/raeleus/skin-composer/master/version").build();
Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() {
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
newVersion = httpResponse.getResultAsString();
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
main.rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.CHECK_FOR_UPDATES_COMPLETE));
}
});
}
@Override
public void failed(Throwable t) {
newVersion = VERSION;
}
@Override
public void cancelled() {
newVersion = VERSION;
}
});
}
});
thread.start();
}
public static TextTooltip fixTooltip(TextTooltip toolTip) {
toolTip.getContainer().width(new Value() {
public float get (@Null Actor context) {
return Math.min(toolTip.getManager().maxWidth, toolTip.getActor().getGlyphLayout().width);
}
});
return toolTip;
}
}
|
core/src/com/ray3k/skincomposer/Main.java
|
/*******************************************************************************
* MIT License
*
* Copyright (c) 2022 Raymond Buckley
*
* 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 com.ray3k.skincomposer;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net;
import com.badlogic.gdx.Net.HttpMethods;
import com.badlogic.gdx.Net.HttpRequest;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Cursor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch;
import com.badlogic.gdx.net.HttpRequestBuilder;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.CheckBox.CheckBoxStyle;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton.ImageTextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle;
import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar.ProgressBarStyle;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle;
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox.SelectBoxStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Slider.SliderStyle;
import com.badlogic.gdx.scenes.scene2d.ui.SplitPane.SplitPaneStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextTooltip.TextTooltipStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad.TouchpadStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Tree.TreeStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Window.WindowStyle;
import com.badlogic.gdx.utils.Null;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.esotericsoftware.spine.AnimationStateData;
import com.esotericsoftware.spine.SkeletonData;
import com.esotericsoftware.spine.SkeletonJson;
import com.esotericsoftware.spine.SkeletonRenderer;
import com.ray3k.skincomposer.data.AtlasData;
import com.ray3k.skincomposer.data.JsonData;
import com.ray3k.skincomposer.data.ProjectData;
import com.ray3k.skincomposer.dialog.DialogFactory;
import com.ray3k.skincomposer.dialog.DialogListener;
import com.ray3k.skincomposer.utils.Utils;
import com.ray3k.stripe.FreeTypeSkin;
import com.ray3k.stripe.PopColorPicker.PopColorPickerStyle;
import com.ray3k.stripe.ScrollFocusListener;
import com.ray3k.tenpatch.TenPatchDrawable;
import dev.lyze.gdxtinyvg.TinyVGAssetLoader;
import dev.lyze.gdxtinyvg.drawers.TinyVGShapeDrawer;
import dev.lyze.gdxtinyvg.scene2d.TinyVGDrawable;
import space.earlygrey.shapedrawer.GraphDrawer;
public class Main extends ApplicationAdapter {
public final static String VERSION = "51";
public static String newVersion;
public static final Class[] BASIC_CLASSES = {Button.class, CheckBox.class,
ImageButton.class, ImageTextButton.class, Label.class, List.class,
ProgressBar.class, ScrollPane.class, SelectBox.class, Slider.class,
SplitPane.class, TextButton.class, TextField.class, TextTooltip.class,
Touchpad.class, Tree.class, Window.class};
public static final Class[] STYLE_CLASSES = {ButtonStyle.class,
CheckBoxStyle.class, ImageButtonStyle.class, ImageTextButtonStyle.class,
LabelStyle.class, ListStyle.class, ProgressBarStyle.class,
ScrollPaneStyle.class, SelectBoxStyle.class, SliderStyle.class,
SplitPaneStyle.class, TextButtonStyle.class, TextFieldStyle.class,
TextTooltipStyle.class, TouchpadStyle.class, TreeStyle.class,
WindowStyle.class};
public static Stage stage;
public static Skin skin;
public static ScreenViewport viewport;
public static TinyVGShapeDrawer shapeDrawer;
public static GraphDrawer graphDrawer;
public static DialogFactory dialogFactory;
public static DesktopWorker desktopWorker;
public static TenPatchDrawable loadingAnimation;
public static TenPatchDrawable loadingAnimation2;
public static UndoableManager undoableManager;
public static ProjectData projectData;
public static JsonData jsonData;
public static AtlasData atlasData;
public static RootTable rootTable;
public static IbeamListener ibeamListener;
public static MainListener mainListener;
public static HandListener handListener;
public static ScrollFocusListener scrollFocusListener;
public static ResizeArrowListener verticalResizeArrowListener;
public static ResizeArrowListener horizontalResizeArrowListener;
public static TooltipManager tooltipManager;
public static FileHandle appFolder;
private String[] args;
public static Main main;
public static SkeletonRenderer skeletonRenderer;
public static SkeletonData floppySkeletonData;
public static AnimationStateData floppyAnimationStateData;
public static SkeletonData uiScaleSkeletonData;
public static AnimationStateData uiScaleAnimationStateData;
public static SkeletonData textraTypistLogoSkeletonData;
public static AnimationStateData textraTypistLogoAnimationStateData;
public static SkeletonData arrowSkeletonData;
public static AnimationStateData arrowAnimationStateData;
public static TinyVGAssetLoader tinyVGAssetLoader;
private static final int SPINE_MAX_VERTS = 32767;
private static TinyVGDrawable drawable;
public static PopColorPickerStyle popColorPickerStyle;
public Main (String[] args) {
this.args = args;
main = this;
}
@Override
public void create() {
appFolder = Gdx.files.external(".skincomposer/");
skin = new FreeTypeSkin(Gdx.files.internal("skin-composer-ui/skin-composer-ui.json"));
viewport = new ScreenViewport();
// viewport.setUnitsPerPixel(.5f);
var batch = new PolygonSpriteBatch(SPINE_MAX_VERTS);
stage = new Stage(viewport, batch);
Gdx.input.setInputProcessor(stage);
shapeDrawer = new TinyVGShapeDrawer(stage.getBatch(), skin.getRegion("white"));
graphDrawer = new GraphDrawer(shapeDrawer);
tinyVGAssetLoader = new TinyVGAssetLoader();
skeletonRenderer = new SkeletonRenderer();
var skeletonJson = new SkeletonJson(Main.skin.getAtlas());
floppySkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/floppy.json"));
floppyAnimationStateData = new AnimationStateData(floppySkeletonData);
uiScaleSkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/uiscale.json"));
uiScaleAnimationStateData = new AnimationStateData(uiScaleSkeletonData);
textraTypistLogoSkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/TextraTypist Logo.json"));
textraTypistLogoAnimationStateData = new AnimationStateData(textraTypistLogoSkeletonData);
arrowSkeletonData = skeletonJson.readSkeletonData(Gdx.files.internal("spine/arrow-animation.json"));
arrowAnimationStateData = new AnimationStateData(arrowSkeletonData);
popColorPickerStyle = new PopColorPickerStyle();
popColorPickerStyle.background = skin.getDrawable("cp-bg-10");
popColorPickerStyle.stageBackground = skin.getDrawable("stage-background");
popColorPickerStyle.titleBarBackground = skin.getDrawable("cp-title-bar-10");
popColorPickerStyle.labelStyle = skin.get("tt", LabelStyle.class);
popColorPickerStyle.fileTextButtonStyle = skin.get("cp-file", TextButtonStyle.class);
popColorPickerStyle.scrollPaneStyle = skin.get("tt", ScrollPaneStyle.class);
popColorPickerStyle.colorSwatch = skin.getDrawable("tt-color-swatch");
popColorPickerStyle.colorSwatchNew = skin.getDrawable("tt-color-swatch-new");
popColorPickerStyle.colorSwatchPopBackground = skin.getDrawable("tt-panel-10");
popColorPickerStyle.colorSwatchPopPreview = skin.getDrawable("tt-color-swatch-10");
popColorPickerStyle.previewSwatchBackground = skin.getDrawable("tt-swatch");
popColorPickerStyle.previewSwatchOld = skin.getDrawable("tt-swatch-old");
popColorPickerStyle.previewSwatchNew = skin.getDrawable("tt-swatch-new");
popColorPickerStyle.previewSwatchSingleBackground = skin.getDrawable("tt-swatch-null");
popColorPickerStyle.previewSwatchSingle = skin.getDrawable("tt-swatch-new-null");
popColorPickerStyle.textFieldStyle = skin.get("cp", TextFieldStyle.class);
popColorPickerStyle.hexTextFieldStyle = skin.get("cp-hexfield", TextFieldStyle.class);
popColorPickerStyle.textButtonStyle = skin.get("cp", TextButtonStyle.class);
popColorPickerStyle.colorSliderBackground = skin.getDrawable("tt-slider-10");
popColorPickerStyle.colorKnobCircleBackground = skin.getDrawable("tt-color-ball");
popColorPickerStyle.colorKnobCircleForeground = skin.getDrawable("tt-color-ball-interior");
popColorPickerStyle.colorSliderKnobHorizontal = skin.getDrawable("tt-slider-knob");
popColorPickerStyle.colorSliderKnobVertical = skin.getDrawable("tt-slider-knob-vertical");
popColorPickerStyle.radioButtonStyle = skin.get("cp-radio", ImageButtonStyle.class);
popColorPickerStyle.increaseButtonStyle = skin.get("cp-increase", ImageButtonStyle.class);
popColorPickerStyle.decreaseButtonStyle = skin.get("cp-decrease", ImageButtonStyle.class);
popColorPickerStyle.checkerBackground = skin.getDrawable("tt-checker-10");
initDefaults();
populate();
resizeUiScale(projectData.getUiScale());
}
private void initDefaults() {
if (Utils.isMac()) System.setProperty("java.awt.headless", "true");
skin.getFont("font").getData().markupEnabled = true;
//copy defaults.json to temp folder if it doesn't exist
var fileHandle = appFolder.child("texturepacker/atlas-export-settings.json");
if (!fileHandle.exists()) {
Gdx.files.internal("atlas-export-settings.json").copyTo(fileHandle);
}
//copy atlas settings for preview to temp folder if it doesn't exist
fileHandle = appFolder.child("texturepacker/atlas-internal-settings.json");
if (!fileHandle.exists()) {
Gdx.files.internal("atlas-internal-settings.json").copyTo(fileHandle);
}
//copy white-pixel.png for pixel drawables
fileHandle = appFolder.child("texturepacker/white-pixel.png");
if (!fileHandle.exists()) {
Gdx.files.internal("white-pixel.png").copyTo(fileHandle);
}
//copy preview fonts to preview fonts folder if they do not exist
fileHandle = appFolder.child("preview fonts/IBMPlexSerif-Medium.ttf");
if (!fileHandle.exists()) {
Gdx.files.internal("preview fonts/IBMPlexSerif-Medium.ttf").copyTo(fileHandle);
}
fileHandle = appFolder.child("preview fonts/Pacifico-Regular.ttf");
if (!fileHandle.exists()) {
Gdx.files.internal("preview fonts/Pacifico-Regular.ttf").copyTo(fileHandle);
}
fileHandle = appFolder.child("preview fonts/PressStart2P-Regular.ttf");
if (!fileHandle.exists()) {
Gdx.files.internal("preview fonts/PressStart2P-Regular.ttf").copyTo(fileHandle);
}
fileHandle = appFolder.child("preview fonts/SourceSansPro-Regular.ttf");
if (!fileHandle.exists()) {
Gdx.files.internal("preview fonts/SourceSansPro-Regular.ttf").copyTo(fileHandle);
}
ibeamListener = new IbeamListener();
dialogFactory = new DialogFactory();
projectData = new ProjectData();
projectData.randomizeId();
projectData.setMaxUndos(30);
atlasData = projectData.getAtlasData();
jsonData = projectData.getJsonData();
newVersion = VERSION;
if (projectData.isCheckingForUpdates()) {
checkForUpdates(this);
}
undoableManager = new UndoableManager(this);
desktopWorker.attachLogListener();
desktopWorker.setCloseListener(() -> {
dialogFactory.showCloseDialog(new DialogListener() {
@Override
public void opened() {
desktopWorker.removeFilesDroppedListener(rootTable.getFilesDroppedListener());
}
@Override
public void closed() {
desktopWorker.addFilesDroppedListener(rootTable.getFilesDroppedListener());
}
});
return false;
});
loadingAnimation = skin.get("loading-animation", TenPatchDrawable.class);
loadingAnimation2 = skin.get("loading-animation2", TenPatchDrawable.class);
projectData.getAtlasData().clearTempData();
handListener = new HandListener();
scrollFocusListener = new ScrollFocusListener(stage);
verticalResizeArrowListener = new ResizeArrowListener(true);
horizontalResizeArrowListener = new ResizeArrowListener(false);
tooltipManager = new TooltipManager();
tooltipManager.animations = false;
tooltipManager.initialTime = .4f;
tooltipManager.resetTime = 0.0f;
tooltipManager.subsequentTime = 0.0f;
tooltipManager.maxWidth = 400f;
tooltipManager.hideAll();
tooltipManager.instant();
}
private void populate() {
stage.clear();
rootTable = new RootTable();
rootTable.setFillParent(true);
mainListener = new MainListener();
rootTable.addListener(mainListener);
rootTable.populate();
stage.addActor(rootTable);
rootTable.updateRecentFiles();
//pass arguments
if (!mainListener.argumentsPassed(args)) {
//show welcome screen if there are no valid arguments
mainListener.createWelcomeListener();
}
}
@Override
public void render() {
Gdx.gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
for (var tenPatch : skin.getAll(TenPatchDrawable.class)) {
tenPatch.value.update(Gdx.graphics.getDeltaTime());
}
stage.draw();
}
@Override
public void resize(int width, int height) {
if (width != 0 && height != 0) {
stage.getViewport().update(width, height, true);
rootTable.fire(new StageResizeEvent(width, height));
}
}
@Override
public void dispose() {
stage.dispose();
skin.dispose();
}
public void resizeUiScale(int scale) {
resizeUiScale(scale, scale > 1);
}
public void resizeUiScale(int scale, boolean large) {
if (large) {
desktopWorker.sizeWindowToFit(1440, 1440, 50, Gdx.graphics);
} else {
desktopWorker.sizeWindowToFit(800, 800, 50, Gdx.graphics);
}
desktopWorker.centerWindow(Gdx.graphics);
viewport.setUnitsPerPixel(1f / scale);
viewport.update(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), true);
}
public static Class basicToStyleClass(Class clazz) {
int i = 0;
for (Class basicClass : BASIC_CLASSES) {
if (clazz.equals(basicClass)) {
break;
} else {
i++;
}
}
return i < STYLE_CLASSES.length ? STYLE_CLASSES[i] : null;
}
public static Class styleToBasicClass(Class clazz) {
int i = 0;
for (Class styleClass : STYLE_CLASSES) {
if (clazz.equals(styleClass)) {
break;
} else {
i++;
}
}
return BASIC_CLASSES[i];
}
public static void checkForUpdates(Main main) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://raw.githubusercontent.com/raeleus/skin-composer/master/version").build();
Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() {
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
newVersion = httpResponse.getResultAsString();
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
main.rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.CHECK_FOR_UPDATES_COMPLETE));
}
});
}
@Override
public void failed(Throwable t) {
newVersion = VERSION;
}
@Override
public void cancelled() {
newVersion = VERSION;
}
});
}
});
thread.start();
}
public static TextTooltip fixTooltip(TextTooltip toolTip) {
toolTip.getContainer().width(new Value() {
public float get (@Null Actor context) {
return Math.min(toolTip.getManager().maxWidth, toolTip.getActor().getGlyphLayout().width);
}
});
return toolTip;
}
}
|
Clean up imports.
|
core/src/com/ray3k/skincomposer/Main.java
|
Clean up imports.
|
|
Java
|
mit
|
f134abc81d60135e32a0d764c52715da0eaaff9e
| 0
|
bmaupin/coursework,bmaupin/coursework
|
/*
* File: Breakout.java
* -------------------
* Name:
* Section Leader:
*
* This file will eventually implement the game of Breakout.
*/
import java.util.Random;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
public class Breakout extends Application {
/** Width and height of application window in pixels */
public static final int APPLICATION_WIDTH = 400;
public static final int APPLICATION_HEIGHT = 600;
/** Dimensions of game board (usually the same) */
private static final int WIDTH = APPLICATION_WIDTH;
private static final int HEIGHT = APPLICATION_HEIGHT;
/** Dimensions of the paddle */
private static final int PADDLE_WIDTH = 60;
private static final int PADDLE_HEIGHT = 10;
/** Offset of the paddle up from the bottom */
private static final int PADDLE_Y_OFFSET = 30;
// Maximum value of x the paddle should have so it doesn't go off the screen
private static final int PADDLE_MAX_X = APPLICATION_WIDTH - PADDLE_WIDTH;
/** Number of bricks per row */
private static final int NBRICKS_PER_ROW = 10;
/** Number of rows of bricks */
private static final int NBRICK_ROWS = 10;
/** Separation between bricks */
private static final int BRICK_SEP = 4;
/** Width of a brick */
private static final int BRICK_WIDTH = (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;
/** Height of a brick */
private static final int BRICK_HEIGHT = 8;
/** Radius of the ball in pixels */
private static final int BALL_RADIUS = 10;
/** Offset of the top brick row from the top */
private static final int BRICK_Y_OFFSET = 70;
/** Number of turns */
private static final int NTURNS = 3;
private Color[] brickColors = { Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.CYAN };
private double ballVelocityX;
private double ballVelocityY = 3.0;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Canvas canvas = new Canvas(APPLICATION_WIDTH, APPLICATION_HEIGHT);
GraphicsContext gc = canvas.getGraphicsContext2D();
setUpGame(gc);
// TODO: move this into setUpGame
final Rectangle paddle = createPaddle();
root.getChildren().add(paddle);
final Circle ball = createBall();
root.getChildren().add(ball);
root.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
double paddleX = event.getSceneX();
// Don't let the paddle go off the right edge of the screen
if (paddleX > PADDLE_MAX_X) {
paddleX = PADDLE_MAX_X;
}
paddle.setX(paddleX);
}
});
root.getChildren().add(canvas);
Scene scene = new Scene(root);
// Hide the mouse cursor
scene.setCursor(Cursor.NONE);
primaryStage.setScene(scene);
// Generate a random velocity between 1.0 and 3.0
ballVelocityX = new Random().nextDouble() * 2 + 1;
final AnimationTimer ballAnimation = new AnimationTimer() {
@Override
public void handle(long now) {
ball.setCenterX(ball.getCenterX() + ballVelocityX);
ball.setCenterY(ball.getCenterY() + ballVelocityY);
}
};
ballAnimation.start();
checkCollision(ball, paddle);
primaryStage.show();
}
private void setUpGame(GraphicsContext gc) {
drawWall(gc);
drawBricks(gc);
}
private void drawWall(GraphicsContext gc) {
gc.setStroke(Color.BLACK);
gc.strokeRect(0, 0, WIDTH, HEIGHT);
}
private void drawBricks(GraphicsContext gc) {
for (int row = 0; row < NBRICKS_PER_ROW; row++) {
gc.setFill(brickColors[row / 2]);
for (int col = 0; col < NBRICK_ROWS; col++) {
int x = (APPLICATION_WIDTH - NBRICKS_PER_ROW * BRICK_WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / 2
+ (BRICK_WIDTH + BRICK_SEP) * col;
int y = BRICK_Y_OFFSET + (BRICK_HEIGHT + BRICK_SEP) * row;
drawBrick(gc, x, y);
}
}
}
private void drawBrick(GraphicsContext gc, int x, int y) {
gc.fillRect(x, y, BRICK_WIDTH, BRICK_HEIGHT);
}
private Rectangle createPaddle() {
int x = (APPLICATION_WIDTH - PADDLE_WIDTH) / 2;
int y = APPLICATION_HEIGHT - PADDLE_HEIGHT - PADDLE_Y_OFFSET;
final Rectangle paddle = new Rectangle(x, y, PADDLE_WIDTH, PADDLE_HEIGHT);
paddle.setFill(Color.BLACK);
return paddle;
}
private Circle createBall() {
// x and y are the center coordinates of the circle
int x = APPLICATION_WIDTH / 2;
int y = APPLICATION_HEIGHT / 2;
final Circle ball = new Circle(x, y, BALL_RADIUS, Color.BLACK);
return ball;
}
// TODO: pass bricks and the paddle, check all for collisions
void checkCollision(final Shape ball, final Shape shape2) {
ball.boundsInParentProperty().addListener(new ChangeListener<Bounds>() {
@Override
public void changed(ObservableValue<? extends Bounds> arg0, Bounds oldValue, Bounds newValue) {
if (shape2.getBoundsInParent().intersects(newValue)) {
ball.setFill(Color.RED);
shape2.setFill(Color.RED);
}
}
});
}
}
|
cs106a-stanford/Assignment3/Breakout.java
|
/*
* File: Breakout.java
* -------------------
* Name:
* Section Leader:
*
* This file will eventually implement the game of Breakout.
*/
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.scene.Cursor;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Breakout extends Application {
/** Width and height of application window in pixels */
public static final int APPLICATION_WIDTH = 400;
public static final int APPLICATION_HEIGHT = 600;
/** Dimensions of game board (usually the same) */
private static final int WIDTH = APPLICATION_WIDTH;
private static final int HEIGHT = APPLICATION_HEIGHT;
/** Dimensions of the paddle */
private static final int PADDLE_WIDTH = 60;
private static final int PADDLE_HEIGHT = 10;
/** Offset of the paddle up from the bottom */
private static final int PADDLE_Y_OFFSET = 30;
// Maximum value of x the paddle should have so it doesn't go off the screen
private static final int PADDLE_MAX_X = APPLICATION_WIDTH - PADDLE_WIDTH;
/** Number of bricks per row */
private static final int NBRICKS_PER_ROW = 10;
/** Number of rows of bricks */
private static final int NBRICK_ROWS = 10;
/** Separation between bricks */
private static final int BRICK_SEP = 4;
/** Width of a brick */
private static final int BRICK_WIDTH = (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;
/** Height of a brick */
private static final int BRICK_HEIGHT = 8;
/** Radius of the ball in pixels */
private static final int BALL_RADIUS = 10;
/** Offset of the top brick row from the top */
private static final int BRICK_Y_OFFSET = 70;
/** Number of turns */
private static final int NTURNS = 3;
private Color[] BrickColors = { Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.CYAN };
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
Group root = new Group();
Canvas canvas = new Canvas(APPLICATION_WIDTH, APPLICATION_HEIGHT);
GraphicsContext gc = canvas.getGraphicsContext2D();
setUpGame(gc);
// TODO: move this into setUpGame
final Rectangle paddle = createPaddle();
root.getChildren().add(paddle);
final Circle ball = createBall();
root.getChildren().add(ball);
root.setOnMouseMoved(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
double paddleX = event.getSceneX();
// Don't let the paddle go off the right edge of the screen
if (paddleX > PADDLE_MAX_X) {
paddleX = PADDLE_MAX_X;
}
paddle.setX(paddleX);
}
});
root.getChildren().add(canvas);
Scene scene = new Scene(root);
// Hide the mouse cursor
scene.setCursor(Cursor.NONE);
primaryStage.setScene(scene);
final Timeline timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
// final KeyValue kv = new KeyValue(ball.centerXProperty(),
// ball.getCenterX() + 300);
final KeyValue kv = new KeyValue(ball.centerYProperty(), ball.getCenterY() + 300);
final KeyFrame kf = new KeyFrame(Duration.millis(1000), kv);
timeline.getKeyFrames().add(kf);
timeline.play();
checkCollision(ball, paddle);
primaryStage.show();
}
private void setUpGame(GraphicsContext gc) {
drawWall(gc);
drawBricks(gc);
}
private void drawWall(GraphicsContext gc) {
gc.setStroke(Color.BLACK);
gc.strokeRect(0, 0, WIDTH, HEIGHT);
}
private void drawBricks(GraphicsContext gc) {
for (int row = 0; row < NBRICKS_PER_ROW; row++) {
gc.setFill(BrickColors[row / 2]);
for (int col = 0; col < NBRICK_ROWS; col++) {
int x = (APPLICATION_WIDTH - NBRICKS_PER_ROW * BRICK_WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / 2
+ (BRICK_WIDTH + BRICK_SEP) * col;
int y = BRICK_Y_OFFSET + (BRICK_HEIGHT + BRICK_SEP) * row;
drawBrick(gc, x, y);
}
}
}
private void drawBrick(GraphicsContext gc, int x, int y) {
gc.fillRect(x, y, BRICK_WIDTH, BRICK_HEIGHT);
}
private Rectangle createPaddle() {
int x = (APPLICATION_WIDTH - PADDLE_WIDTH) / 2;
int y = APPLICATION_HEIGHT - PADDLE_HEIGHT - PADDLE_Y_OFFSET;
final Rectangle paddle = new Rectangle(x, y, PADDLE_WIDTH, PADDLE_HEIGHT);
paddle.setFill(Color.BLACK);
return paddle;
}
private Circle createBall() {
// x and y are the center coordinates of the circle
int x = APPLICATION_WIDTH / 2;
int y = APPLICATION_HEIGHT / 2;
final Circle ball = new Circle(x, y, BALL_RADIUS, Color.BLACK);
return ball;
}
void checkCollision(final Shape ball, final Shape shape2) {
ball.boundsInParentProperty().addListener(new ChangeListener<Bounds>() {
@Override
public void changed(ObservableValue<? extends Bounds> arg0, Bounds oldValue, Bounds newValue) {
if (shape2.getBoundsInParent().intersects(newValue)) {
ball.setFill(Color.RED);
shape2.setFill(Color.RED);
}
}
});
}
/*
* private void checkCollision(Shape shape1, Shape shape2) { Shape intersect
* = Shape.intersect(shape1, shape2); if
* (intersect.getBoundsInLocal().getWidth() != -1) {
* shape1.setFill(Color.RED); shape2.setFill(Color.RED); } }
*/
/*
* private void checkShapeIntersection(Shape shape) { boolean
* collisionDetected = false; for (Shape static_bloc : nodes) { if
* (static_bloc != shape) { static_bloc.setFill(Color.GREEN);
*
* Shape intersect = Shape.intersect(shape, static_bloc); if
* (intersect.getBoundsInLocal().getWidth() != -1) { collisionDetected =
* true; } } }
*
* if (collisionDetected) { shape.setFill(Color.BLUE); } else {
* shape.setFill(Color.GREEN); } }
*/
}
|
Use simpler AnimationTimer for animation and set random X velocity
|
cs106a-stanford/Assignment3/Breakout.java
|
Use simpler AnimationTimer for animation and set random X velocity
|
|
Java
|
epl-1.0
|
196e83d2ede68f18f9aada928288e87a52eb2464
| 0
|
jtrfp/terminal-recall,jtrfp/terminal-recall,jtrfp/terminal-recall
|
/*******************************************************************************
* This file is part of TERMINAL RECALL
* Copyright (c) 2012-2014 Chuck Ritola
* Part of the jTRFP.org project
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* chuck - initial API and implementation
******************************************************************************/
package org.jtrfp.trcl.miss;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.Camera;
import org.jtrfp.trcl.DisplayModeHandler;
import org.jtrfp.trcl.OverworldSystem;
import org.jtrfp.trcl.RenderableSpacePartitioningGrid;
import org.jtrfp.trcl.SkySystem;
import org.jtrfp.trcl.WeakPropertyChangeListener;
import org.jtrfp.trcl.World;
import org.jtrfp.trcl.beh.CollidesWithTerrain;
import org.jtrfp.trcl.beh.MatchDirection;
import org.jtrfp.trcl.beh.MatchPosition;
import org.jtrfp.trcl.beh.SkyCubeCloudModeUpdateBehavior;
import org.jtrfp.trcl.beh.SpawnsRandomSmoke;
import org.jtrfp.trcl.core.Features;
import org.jtrfp.trcl.core.ResourceManager;
import org.jtrfp.trcl.core.TRFactory;
import org.jtrfp.trcl.core.TRFactory.TR;
import org.jtrfp.trcl.ext.tr.SoundSystemFactory.SoundSystemFeature;
import org.jtrfp.trcl.file.AbstractTriplet;
import org.jtrfp.trcl.file.LVLFile;
import org.jtrfp.trcl.file.Location3D;
import org.jtrfp.trcl.file.NAVFile.NAVSubObject;
import org.jtrfp.trcl.file.NAVFile.START;
import org.jtrfp.trcl.file.TDFFile;
import org.jtrfp.trcl.game.Game;
import org.jtrfp.trcl.game.TVF3Game;
import org.jtrfp.trcl.gpu.Renderer;
import org.jtrfp.trcl.gui.ReporterFactory.Reporter;
import org.jtrfp.trcl.miss.LoadingProgressReporter.UpdateHandler;
import org.jtrfp.trcl.miss.NAVObjective.Factory;
import org.jtrfp.trcl.miss.TunnelSystemFactory.TunnelSystem;
import org.jtrfp.trcl.obj.DEFObject;
import org.jtrfp.trcl.obj.ObjectDirection;
import org.jtrfp.trcl.obj.ObjectSystem;
import org.jtrfp.trcl.obj.Player;
import org.jtrfp.trcl.obj.Projectile;
import org.jtrfp.trcl.obj.ProjectileFactory;
import org.jtrfp.trcl.obj.Propelled;
import org.jtrfp.trcl.obj.SpawnsRandomExplosionsAndDebris;
import org.jtrfp.trcl.obj.WorldObject;
import org.jtrfp.trcl.obj.Player.PlayerSaveState;
import org.jtrfp.trcl.shell.GameShellFactory;
import org.jtrfp.trcl.shell.GameShellFactory.GameShell;
import org.jtrfp.trcl.snd.GPUResidentMOD;
import org.jtrfp.trcl.snd.MusicPlaybackEvent;
import org.jtrfp.trcl.snd.SoundSystem;
import org.jtrfp.trcl.tools.Util;
public class Mission {
// PROPERTIES
public static final String LEVEL_NAME = "levelName",
//NAVS = "navs",
NAV_SUB_OBJECTS = "navSubObjects",
GROUND_TARGETS_DESTROYED = "groundTargetsDestroyed",
AIR_TARGETS_DESTROYED = "airTargetsDestroyed",
FOLIAGE_DESTROYED = "foliageDestroyed",
SHOW_INTRO = "showIntro",
CURRENT_NAV_TARGET = "currentNavTarget",
LVL_FILE_NAME = "lvlFileName",
SATELLITE_VIEW = "satelliteView",
PLAYER_START_POSITION = "playerStartPosition",
PLAYER_START_HEADING = "playerStartHeading",
PLAYER_START_TOP = "playerStartTop",
DEF_OBJECT_LIST = "defObjectList",
CURRENT_BOSS = "currentBoss",
PLAYER_SAVE_STATE = "playerSaveState";
//// INTROSPECTOR
static {
try{
final Set<String> persistentProperties = new HashSet<String>();
persistentProperties.addAll(Arrays.asList(
LEVEL_NAME,
//NAVS,
NAV_SUB_OBJECTS,
GROUND_TARGETS_DESTROYED,
AIR_TARGETS_DESTROYED,
FOLIAGE_DESTROYED,
SHOW_INTRO,
CURRENT_NAV_TARGET,
LVL_FILE_NAME,
PLAYER_START_POSITION,
PLAYER_START_HEADING,
PLAYER_START_TOP,
DEF_OBJECT_LIST,
PLAYER_SAVE_STATE
));
BeanInfo info = Introspector.getBeanInfo(Mission.class);
PropertyDescriptor[] propertyDescriptors =
info.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; ++i) {
PropertyDescriptor pd = propertyDescriptors[i];
if (!persistentProperties.contains(pd.getName())) {
pd.setValue("transient", Boolean.TRUE);
}
}
}catch(Exception e){e.printStackTrace();}
}//end static{}
private final TR tr;
private final List<NAVObjective>
navs = new LinkedList<NAVObjective>();
private LVLFile lvl;
private double[] playerStartPosition;
private List<NAVSubObject> navSubObjects;
private double [] playerStartHeading,
playerStartTop;
private Game game;
private String levelName;
private OverworldSystem overworldSystem;
private final Result[] missionEnd = new Result[]{null};
private int groundTargetsDestroyed=0,
airTargetsDestroyed=0,
foliageDestroyed=0;
private boolean showIntro = true;
private volatile MusicPlaybackEvent
bgMusic;
private final Object missionLock = new Object();
private boolean satelliteView = false;
private WorldObject currentBoss = null;
//private MissionMode missionMode = new Mission.LoadingMode();
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private final DisplayModeHandler displayHandler;
private Object [] levelLoadingMode, overworldMode, gameplayMode, briefingMode, summaryMode, emptyMode= new Object[]{};
private NAVObjective currentNavTarget;
private final RenderableSpacePartitioningGrid partitioningGrid = new RenderableSpacePartitioningGrid();
private GameShell gameShell;
private final RunStateListener runStateListener = new RunStateListener();
private WeakPropertyChangeListener weakRunStateListener; // HARD REFERENCE; DO NOT REMOVE.
private String lvlFileName;
private List<DEFObject> defObjectList;
private Map<NAVObjective,NAVSubObject> navMap = new HashMap<>();
private PlayerSaveState playerSaveState;
enum LoadingStages {
navs, tunnels, overworld
}// end LoadingStages
//ROOT STATES
public interface MissionState extends Game.GameRunningMode{}
public interface ConstructingState extends MissionState{}
public interface ConstructedState extends MissionState{}
public interface ActiveMissionState extends ConstructedState{}
public interface LoadingState extends ActiveMissionState{}
public interface GameplayState extends ActiveMissionState{}
public interface Briefing extends GameplayState{}
public interface PlanetBrief extends Briefing{}
public interface EnemyBrief extends Briefing{}
public interface MissionSummary extends Briefing{}
public interface PlayerActivity extends GameplayState{}
public interface OverworldState extends PlayerActivity{}
public interface SatelliteState extends OverworldState{}
public interface ChamberState extends PlayerActivity{}
public interface TunnelState extends PlayerActivity{}
public Mission() {
this.tr = Features.get(Features.getSingleton(), TR.class);
this.displayHandler = new DisplayModeHandler(this.getPartitioningGrid());
tr.addPropertyChangeListener(
TRFactory.RUN_STATE,
weakRunStateListener = new WeakPropertyChangeListener(runStateListener, tr));
}// end Mission
private class RunStateListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
final Object newState = evt.getNewValue();
if(newState instanceof Game.GameDestructingMode)
abort();
}//end propertyChange(...)
}//end RunStateListener
public Result go() {
//Kludge to fulfill previous dependencies
tr.setRunState(new ConstructingState(){});
tr.setRunState(new ConstructedState(){});
Util.assertPropertiesNotNull(this,
"tr",
"game");
final TR tr = getTr();
tr.setRunState(new LoadingState(){});
final LVLFile lvlData = getLvl();
synchronized(missionLock){
synchronized(missionEnd){
if(missionEnd[0]!=null)
return missionEnd[0];
}
tr.getThreadManager().setPaused(true);
for(ProjectileFactory pf:tr.getResourceManager().getProjectileFactories())
for(Projectile proj:pf.getProjectiles())
proj.destroy();
System.out.println("Starting GampeplayLevel loading sequence...");
final LoadingProgressReporter rootProgress = LoadingProgressReporter.Impl
.createRoot(new UpdateHandler() {
@Override
public void update(double unitProgress) {
((TVF3Game)getGame()).getLevelLoadingScreen().setLoadingProgress(unitProgress);
}
});
final LoadingProgressReporter[] progressStages = rootProgress
.generateSubReporters(LoadingStages.values().length);
final Renderer renderer = tr.mainRenderer;
renderer.getCamera().probeForBehavior(SkyCubeCloudModeUpdateBehavior.class).setEnable(false);
renderer.getSkyCube().setSkyCubeGen(GameShellFactory.DEFAULT_GRADIENT);
final Camera camera = renderer.getCamera();
camera.setHeading(Vector3D.PLUS_I);
camera.setTop(Vector3D.PLUS_J);
((TVF3Game)game).levelLoadingMode();
displayHandler.setDisplayMode(getLevelLoadingMode());
((TVF3Game)game).getUpfrontDisplay().submitPersistentMessage(levelName);
try {
final ResourceManager rm = tr.getResourceManager();
final Player player = ((TVF3Game)getGameShell().getGame()).getPlayer();
final TDFFile tdf = rm.getTDFData(lvlData.getTunnelDefinitionFile());
player.setActive(false);
// Abort check
synchronized(missionEnd){
if(missionEnd[0]!=null)
return missionEnd[0];
}
setOverworldSystem(new OverworldSystem(tr,
progressStages[LoadingStages.overworld.ordinal()]));
briefingMode = new Object[]{
((TVF3Game)game).briefingScreen,
overworldSystem
};
gameplayMode = new Object[]{
((TVF3Game)game).upfrontDisplay,
rm.getDebrisSystem(),
rm.getPowerupSystem(),
rm.getProjectileFactories(),
rm.getExplosionFactory(),
rm.getSmokeSystem()
};
overworldMode = new Object[]{
gameplayMode,
overworldSystem
};
summaryMode = new Object[]{
((TVF3Game)game).getBriefingScreen(),
overworldSystem
};
overworldSystem.loadLevel(lvlData, tdf);
final List<DEFObject> defObjectList = getDefObjectList();
final ObjectSystem objectSystem = overworldSystem.getObjectSystem();
if(defObjectList != null)
objectSystem.setDefList(defObjectList);
else{
objectSystem.populateFromLVL(lvlData);
setDefObjectList(objectSystem.getDefList());
}
assert getDefObjectList() != null;
//overworldSystem.loadLevel(lvlData, tdf);
System.out.println("\t...Done.");
//TODO: TunnelSystem should be isolated from Mission
final TunnelSystem ts = Features.get(this, TunnelSystem.class);
ts.installTunnels(tdf,progressStages[LoadingStages.tunnels.ordinal()]);
// Install NAVs if not already set
if( getNavSubObjects() == null ){
setNavSubObjects(rm.getNAVData(lvlData.getNavigationFile())
.getNavObjects());
}
if( navs.isEmpty() ){
Factory f = new NAVObjective.Factory(tr, getLevelName());
//final LoadingProgressReporter[] navProgress = progressStages[LoadingStages.navs
// .ordinal()].generateSubReporters(navSubObjects.size());
final Reporter reporter = Features.get(getTr(), Reporter.class);
for (int i = 0; i < navSubObjects.size(); i++) {
final NAVSubObject obj = navSubObjects.get(i);
f.create(reporter, obj, navs, navMap);
//navProgress[i].complete();
}// end for(navSubObjects)
}//end if( empty )
// ////// INITIAL HEADING
PlayerSaveState playerSaveState = getStoredPlayerSaveState();
//final double [] playerStartPos = getStoredPlayerStartPosition();
//final double [] playerStartHdg = getStoredPlayerStartHeading();
//final double [] playerStartTop = getStoredPlayerStartTop();
if(playerSaveState == null){//No savestate data. Use the map
playerSaveState = new PlayerSaveState();
setPlayerSaveState(playerSaveState);
playerSaveState.readFrom(player);
START startNav = (START) getNavSubObjects().get(0);
final ObjectDirection od = new ObjectDirection(startNav.getRoll(),
startNav.getPitch(), startNav.getYaw());
Location3D l3d = startNav.getLocationOnMap();
final double HEIGHT_PADDING = 10000;
playerSaveState.setHeading(od.getHeading().negate().toArray());
//setPlayerStartHeading (od.getHeading().negate().toArray());
playerSaveState.setTop(od.getTop().toArray());
//setPlayerStartTop (od.getTop().toArray());
playerSaveState.setPosition(new Vector3D(
TRFactory.legacy2Modern(l3d.getZ()), //X (Z)
Math.max(HEIGHT_PADDING + getOverworldSystem().getAltitudeMap().heightAt(// Y
TRFactory.legacy2Modern(l3d.getZ()),
TRFactory.legacy2Modern(l3d.getX())),TRFactory.legacy2Modern(l3d.getY())),
TRFactory.legacy2Modern(l3d.getX()) //Z (X)
).toArray());
}//end if(nulls)
//APPLY STATE
playerSaveState.writeTo(player);
//////// PLAYER POSITIONS
//player.setPosition(getStoredPlayerStartPosition() );
//player.setHeading(new Vector3D(getStoredPlayerStartHeading()) );// Kludge to fix incorrect hdg
//player.setTop (new Vector3D(getStoredPlayerStartTop()) );
///////// STATE
final Propelled propelled = player.probeForBehavior(Propelled.class);
propelled.setPropulsion(propelled.getMinPropulsion());
player.probeForBehavior(CollidesWithTerrain.class) .setEnable(true);
if(player.hasBehavior(SpawnsRandomSmoke.class))
player.probeForBehavior(SpawnsRandomSmoke.class) .setEnable(false);
if(player.hasBehavior(SpawnsRandomExplosionsAndDebris.class))
player.probeForBehavior(SpawnsRandomExplosionsAndDebris.class).setEnable(false);
//player.probeForBehavior(SpinCrashDeathBehavior.class).setEnable(false);
final TVF3Game game = (TVF3Game)getGame();
game.getNavSystem().updateNAVState();
player.resetVelocityRotMomentum();
final String startX = System.getProperty("org.jtrfp.trcl.startX");
final String startY = System.getProperty("org.jtrfp.trcl.startY");
final String startZ = System.getProperty("org.jtrfp.trcl.startZ");
final double[] playerPos = player.getPosition();
if (startX != null && startY != null && startZ != null) {
System.out.println("Using user-specified start point");
final int sX = Integer.parseInt(startX);
final int sY = Integer.parseInt(startY);
final int sZ = Integer.parseInt(startZ);
playerPos[0] = sX;
playerPos[1] = sY;
playerPos[2] = sZ;
player.notifyPositionChange();
}// end if(user start point)
System.out.println("Start position set to " + player.getPosition()[0]+" "+player.getPosition()[1]+" "+player.getPosition()[2]);
System.out.println("Setting sun vector");
final AbstractTriplet sunVector = lvlData.getSunlightDirectionVector();
tr.getThreadManager().submitToGL(new Callable<Void>() {
@Override
public Void call() throws Exception {
tr.mainRenderer.setSunVector(
new Vector3D(sunVector.getX(), sunVector.getY(),
sunVector.getZ()).normalize());
return null;
}
}).get();
System.out.println("\t...Done.");
} catch (Exception e) {
e.printStackTrace();
}
if (System.getProperties().containsKey(
"org.jtrfp.trcl.flow.Mission.skipNavs")) {
try {
final int skips = Integer.parseInt(System
.getProperty("org.jtrfp.trcl.flow.Mission.skipNavs"));
System.out.println("Skipping " + skips + " navs.");
for (int i = 0; i < skips; i++) {
removeNAVObjective(currentNAVObjective());
}// end for(skips)
} catch (NumberFormatException e) {
System.err
.println("Invalid format for property \"org.jtrfp.trcl.flow.Mission.skipNavs\". Must be integer.");
}
}// end if(containsKey)
// Transition to gameplay mode.
// Abort check
synchronized (missionEnd) {
if (missionEnd[0] != null)
return missionEnd[0];
}//end sync(missionEnd)
final SoundSystem ss = Features.get(tr,SoundSystemFeature.class);
MusicPlaybackEvent evt;
Features.get(tr,SoundSystemFeature.class).enqueuePlaybackEvent(
evt =ss
.getMusicFactory()
.create(new GPUResidentMOD(tr, tr
.getResourceManager().getMOD(
lvlData.getBackgroundMusicFile())),
true));
synchronized(Mission.this){
if(bgMusic==null){
bgMusic=evt;
bgMusic.play();
}
}//end sync(Mission.this)
((TVF3Game)game).getUpfrontDisplay().removePersistentMessage();
Features.get(tr,SoundSystemFeature.class).setPaused(false);
tr.getThreadManager().setPaused(false);
if(isShowIntro()){
tr.setRunState(new EnemyBrief(){});
displayHandler.setDisplayMode(briefingMode);
//Make sure there is actually something to show, skip if not.
if(! lvl.getBriefingTextFile().toLowerCase().contentEquals("null.txt") )
((TVF3Game)game).getBriefingScreen().briefingSequence(lvl);//TODO: Convert to feature
setShowIntro(false);
}
tr.setRunState(new OverworldState(){});
final SkySystem skySystem = getOverworldSystem().getSkySystem();
tr.mainRenderer.getCamera().probeForBehavior(SkyCubeCloudModeUpdateBehavior.class).setEnable(true);
renderer.getSkyCube().setSkyCubeGen(skySystem.getBelowCloudsSkyCubeGen());
renderer.setAmbientLight(skySystem.getSuggestedAmbientLight());
renderer.setSunColor(skySystem.getSuggestedSunColor());
((TVF3Game)game).getNavSystem() .activate();
displayHandler.setDisplayMode(overworldMode);
((TVF3Game)game).getPlayer() .setActive(true);
((TVF3Game)getGameShell().getGame()).setPaused(false);
//tr.setRunState(new PlayerActivity(){});
//Wait for mission end
synchronized(missionEnd){
while(missionEnd[0]==null){try{missionEnd.wait();}
catch(InterruptedException e){break;}}}
//Completion summary
if(missionEnd[0]!=null)
if(!missionEnd[0].isAbort()){
displayHandler.setDisplayMode(summaryMode);
tr.setRunState(new MissionSummary(){});
final boolean showEndBriefing = !lvl.getBriefingTextFile().toLowerCase().contentEquals("null.txt");
if( showEndBriefing )
((TVF3Game)game).getBriefingScreen().missionCompleteSummary(lvl,missionEnd[0]);
//TODO: Level end video
}//end if(proper ending)
bgMusic.stop();
cleanup();
return missionEnd[0];
}//end sync
}// end go()
private LVLFile getLvl() {
if(lvl == null)
try{lvl = getTr().getResourceManager().getLVL(getLvlFileName());}
catch(Exception e){e.printStackTrace();}
return lvl;
}
private Object [] getLevelLoadingMode(){
if(levelLoadingMode == null){
final Game game = getGame();
if(game == null)
throw new IllegalStateException("game property intolerably null.");
levelLoadingMode = new Object[]{
((TVF3Game)game).getLevelLoadingScreen(),
((TVF3Game)game).getUpfrontDisplay()
};
}
return levelLoadingMode;
}//end getLevelLoadingMode
public NAVObjective currentNAVObjective() {
if (navs.isEmpty())
return null;
return navs.get(0);
}//end currentNAVObjective()
public void removeNAVObjective(NAVObjective o) {
navs.remove(o);
getNavSubObjects().remove(navMap.get(o));
updateNavState();
((TVF3Game)getGameShell().getGame()).getNavSystem().updateNAVState();
}// end removeNAVObjective(...)
private void updateNavState(){
try{this.setCurrentNavTarget(navs.get(0));}
catch(IndexOutOfBoundsException e){setCurrentNavTarget(null);}
}
public static class Result {
private final int airTargetsDestroyed, groundTargetsDestroyed,foliageDestroyed;
private boolean abort=false;
public Result(int airTargetsDestroyed, int groundTargetsDestroyed, int foliageDestroyed) {
this.airTargetsDestroyed =airTargetsDestroyed;
this.groundTargetsDestroyed =groundTargetsDestroyed;
this.foliageDestroyed =foliageDestroyed;
}//end constructor
/**
* @return the airTargetsDestroyed
*/
public int getAirTargetsDestroyed() {
return airTargetsDestroyed;
}
/**
* @return the groundTargetsDestroyed
*/
public int getGroundTargetsDestroyed() {
return groundTargetsDestroyed;
}
/**
* @return the foliageDestroyed
*/
public int getFoliageDestroyed() {
return foliageDestroyed;
}
/**
* @return the abort
*/
public boolean isAbort() {
return abort;
}
/**
* @param abort the abort to set
*/
public void setAbort(boolean abort) {
this.abort = abort;
}
}// end Result
/**
* NOTE: This returns the current Game's Player position and does not directly reflect setter changes.
* @return
* @since Jul 15, 2016
*/
public double[] getPlayerStartPosition() {
final Game game = getGame();
if(game == null)
return null;
final Player player = game.getPlayer();
if(player == null)
return null;
return player.getPosition();
}
public double[] getStoredPlayerStartPosition(){
return playerStartPosition;
}
public void playerDestroyed() {
new Thread() {
@Override
public void run() {
System.out.println("MISSION FAILED.");
notifyMissionEnd(null);
}// end run()
}.start();
}// end playerDestroyed()
public void notifyMissionEnd(Result r){
synchronized(missionEnd){
missionEnd[0]=r;
missionEnd.notifyAll();}
}//end notifyMissionEnd()
public List<NAVObjective> getRemainingNAVObjectives() {
return navs;
}
/**
* @return the navSubObjects
*/
public List<NAVSubObject> getNavSubObjects() {
return navSubObjects;
}
/**
* @param navSubObjects
* the navSubObjects to set
*/
public void setNavSubObjects(List<NAVSubObject> navSubObjects) {
if( navSubObjects != null)
this.navSubObjects = new ArrayList<NAVSubObject>(navSubObjects);
else
navSubObjects = null;
navs.clear();//Ensure navs get repopulated.
}
public OverworldSystem getOverworldSystem() {
return overworldSystem;
}
public Mission notifyAirTargetDestroyed(){
airTargetsDestroyed++;
return this;
}
public Mission notifyGroundTargetDestroyed(){
groundTargetsDestroyed++;
return this;
}
public Mission notifyFoliageDestroyed(){
foliageDestroyed++;
return this;
}
public void enterBossMode(final String bossMusicFile, WorldObject boss){
setCurrentBoss(boss);
tr.getThreadManager().submitToThreadPool(new Callable<Void>() {
@Override
public Void call() throws Exception {
MusicPlaybackEvent evt;
final SoundSystem ss = Features.get(tr,SoundSystemFeature.class);
Features.get(tr,SoundSystemFeature.class).enqueuePlaybackEvent(
evt =ss
.getMusicFactory()
.create(tr.getResourceManager().gpuResidentMODs.get(bossMusicFile),
true));
synchronized(Mission.this){
evt.play();
if(bgMusic!=null)
bgMusic.stop();
bgMusic=evt;
}
return null;
}// end call()
});
}//end enterBossMode()
public void exitBossMode(){
setCurrentBoss(null);
tr.getThreadManager().submitToThreadPool(new Callable<Void>() {
@Override
public Void call() throws Exception {
MusicPlaybackEvent evt;
final SoundSystem ss = Features.get(tr,SoundSystemFeature.class);
Features.get(tr,SoundSystemFeature.class).enqueuePlaybackEvent(
evt =ss
.getMusicFactory()
.create(tr.getResourceManager().gpuResidentMODs.get(getLvl().getBackgroundMusicFile()),
true));
synchronized(Mission.this){
evt.play();
bgMusic.stop();
bgMusic=evt;}
return null;
}// end call()
});
}//end exitBossMode()
public void abort() {
final Result result = new Result(
airTargetsDestroyed,
groundTargetsDestroyed,
foliageDestroyed/*,
1.-(double)tunnelsRemaining.size()/(double)totalNumTunnels*/);
result.setAbort(true);
notifyMissionEnd(result);
//Wait for mission to end
synchronized(missionLock){//Don't execute while mission is in progress.
cleanup();
}//end sync{}
}//end abort()
private void cleanup() {
displayHandler.setDisplayMode(emptyMode);
tr.getResourceManager().getPowerupSystem().removeAll();
// Remove projectile factories
for(ProjectileFactory pf:tr.getResourceManager().getProjectileFactories())
for(Projectile projectile:pf.getProjectiles())
projectile.destroy();
}//end cleanup()
/**
* @param listener
* @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
/**
* @param propertyName
* @param listener
* @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
*/
public void addPropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
pcs.addPropertyChangeListener(propertyName, listener);
}
/**
* @return
* @see java.beans.PropertyChangeSupport#getPropertyChangeListeners()
*/
public PropertyChangeListener[] getPropertyChangeListeners() {
return pcs.getPropertyChangeListeners();
}
/**
* @param propertyName
* @return
* @see java.beans.PropertyChangeSupport#getPropertyChangeListeners(java.lang.String)
*/
public PropertyChangeListener[] getPropertyChangeListeners(
String propertyName) {
return pcs.getPropertyChangeListeners(propertyName);
}
/**
* @param propertyName
* @return
* @see java.beans.PropertyChangeSupport#hasListeners(java.lang.String)
*/
public boolean hasListeners(String propertyName) {
return pcs.hasListeners(propertyName);
}
/**
* @param listener
* @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
/**
* @param propertyName
* @param listener
* @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
*/
public void removePropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
pcs.removePropertyChangeListener(propertyName, listener);
}
/**
* @return the bossFight
*/
public WorldObject getCurrentBoss() {
return currentBoss;
}
public void setCurrentBoss(WorldObject boss) {
final WorldObject oldBoss = this.currentBoss;//Probably null.
this.currentBoss = boss;
pcs.firePropertyChange(CURRENT_BOSS, oldBoss, boss);
}
public void setSatelliteView(boolean satelliteView) {
if(!(tr.getRunState() instanceof OverworldState)&&satelliteView)
throw new IllegalArgumentException("Cannot activate satellite view while runState is "+tr.getRunState().getClass().getSimpleName());
if(satelliteView && ((TVF3Game)getGameShell().getGame()).isPaused())
throw new IllegalArgumentException("Cannot activate satellite view while paused.");
final boolean oldValue = this.satelliteView;
if(satelliteView!=oldValue){
final Game game = ((TVF3Game)getGameShell().getGame());
final Camera cam = tr.mainRenderer.getCamera();
this.satelliteView=satelliteView;
pcs.firePropertyChange(SATELLITE_VIEW, oldValue, satelliteView);
tr.setRunState(satelliteView?new SatelliteState(){}:new OverworldState(){});
if(satelliteView){//Switched on
tr.getThreadManager().setPaused(true);
cam.setFogEnabled(false);
cam.probeForBehavior(MatchPosition.class).setEnable(false);
cam.probeForBehavior(MatchDirection.class).setEnable(false);
final Vector3D pPos = new Vector3D(((TVF3Game)game).getPlayer().getPosition());
final Vector3D pHeading = ((TVF3Game)getGameShell().getGame()).getPlayer().getHeading();
cam.setPosition(new Vector3D(pPos.getX(),TRFactory.visibilityDiameterInMapSquares*TRFactory.mapSquareSize*.65,pPos.getZ()));
cam.setHeading(Vector3D.MINUS_J);
cam.setTop(new Vector3D(pHeading.getX(),.0000000001,pHeading.getZ()).normalize());
((TVF3Game)getGameShell().getGame()).getSatDashboard().setVisible(true);
}else{//Switched off
tr.getThreadManager().setPaused(false);
World.relevanceExecutor.submit(new Runnable(){
@Override
public void run() {
((TVF3Game)getGameShell().getGame()).getNavSystem().activate();
}});
cam.setFogEnabled(true);
cam.probeForBehavior(MatchPosition.class).setEnable(true);
cam.probeForBehavior(MatchDirection.class).setEnable(true);
((TVF3Game)getGameShell().getGame()).getSatDashboard().setVisible(false);
}//end !satelliteView
}//end if(change)
}
/**
* @return the satelliteView
*/
public boolean isSatelliteView() {
return satelliteView;
}
public Game getGame() {
return game;
}
public void destruct() {
Features.destruct(this);
}
public String getLevelName() {
return levelName;
}
public int getGroundTargetsDestroyed() {
return groundTargetsDestroyed;
}
public void setGroundTargetsDestroyed(int groundTargetsDestroyed) {
this.groundTargetsDestroyed = groundTargetsDestroyed;
}
public int getAirTargetsDestroyed() {
return airTargetsDestroyed;
}
public void setAirTargetsDestroyed(int airTargetsDestroyed) {
this.airTargetsDestroyed = airTargetsDestroyed;
}
public int getFoliageDestroyed() {
return foliageDestroyed;
}
public void setFoliageDestroyed(int foliageDestroyed) {
this.foliageDestroyed = foliageDestroyed;
}
public NAVObjective getCurrentNavTarget() {
return currentNavTarget;
}
public Mission setCurrentNavTarget(NAVObjective newTarget) {
final NAVObjective oldTarget = this.currentNavTarget;
this.currentNavTarget = newTarget;
pcs.firePropertyChange(CURRENT_NAV_TARGET, oldTarget, newTarget);
return this;
}
public void setDisplayMode(Object [] newMode){//TODO: Refactor this to follow tr's run state instead
displayHandler.setDisplayMode(newMode);
}
public RenderableSpacePartitioningGrid getPartitioningGrid() {
return partitioningGrid;
}
public TR getTr() {
return tr;
}
public GameShell getGameShell() {
if(gameShell == null)
gameShell = Features.get(getTr(), GameShell.class);
return gameShell;
}
public void setGameShell(GameShell gameShell) {
this.gameShell = gameShell;
}
public void setGame(Game game) {
this.game = game;
}
public void setLevelName(String levelName) {
this.levelName = levelName;
}
public boolean isShowIntro() {
return showIntro;
}
public void setShowIntro(boolean showIntro) {
this.showIntro = showIntro;
}
public String getLvlFileName() {
return lvlFileName;
}
public void setLvlFileName(String lvlFileName) {
this.lvlFileName = lvlFileName;
}
public List<DEFObject> getDefObjectList() {
return defObjectList;
}
public void setDefObjectList(List<DEFObject> defObjectList) {
this.defObjectList = defObjectList;
}//end setDefObjectList(...)
void setOverworldSystem(OverworldSystem overworldSystem) {
this.overworldSystem = overworldSystem;
}
public Object [] getOverworldMode(){
return overworldMode;
}
public PlayerSaveState getPlayerSaveState(){
final Game game = getGame();
if(game == null)
return null;
final Player player = game.getPlayer();
if(player == null)
return null;
return player.getPlayerSaveState();
}
protected PlayerSaveState getStoredPlayerSaveState(){
return playerSaveState;
}
public void setPlayerSaveState(PlayerSaveState pss){
playerSaveState = pss;
}
}// end Mission
|
src/main/java/org/jtrfp/trcl/miss/Mission.java
|
/*******************************************************************************
* This file is part of TERMINAL RECALL
* Copyright (c) 2012-2014 Chuck Ritola
* Part of the jTRFP.org project
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* chuck - initial API and implementation
******************************************************************************/
package org.jtrfp.trcl.miss;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.Camera;
import org.jtrfp.trcl.DisplayModeHandler;
import org.jtrfp.trcl.OverworldSystem;
import org.jtrfp.trcl.RenderableSpacePartitioningGrid;
import org.jtrfp.trcl.SkySystem;
import org.jtrfp.trcl.WeakPropertyChangeListener;
import org.jtrfp.trcl.World;
import org.jtrfp.trcl.beh.CollidesWithTerrain;
import org.jtrfp.trcl.beh.MatchDirection;
import org.jtrfp.trcl.beh.MatchPosition;
import org.jtrfp.trcl.beh.SkyCubeCloudModeUpdateBehavior;
import org.jtrfp.trcl.beh.SpawnsRandomSmoke;
import org.jtrfp.trcl.core.Features;
import org.jtrfp.trcl.core.ResourceManager;
import org.jtrfp.trcl.core.TRFactory;
import org.jtrfp.trcl.core.TRFactory.TR;
import org.jtrfp.trcl.ext.tr.SoundSystemFactory.SoundSystemFeature;
import org.jtrfp.trcl.file.AbstractTriplet;
import org.jtrfp.trcl.file.LVLFile;
import org.jtrfp.trcl.file.Location3D;
import org.jtrfp.trcl.file.NAVFile.NAVSubObject;
import org.jtrfp.trcl.file.NAVFile.START;
import org.jtrfp.trcl.file.TDFFile;
import org.jtrfp.trcl.game.Game;
import org.jtrfp.trcl.game.TVF3Game;
import org.jtrfp.trcl.gpu.Renderer;
import org.jtrfp.trcl.gui.ReporterFactory.Reporter;
import org.jtrfp.trcl.miss.LoadingProgressReporter.UpdateHandler;
import org.jtrfp.trcl.miss.NAVObjective.Factory;
import org.jtrfp.trcl.miss.TunnelSystemFactory.TunnelSystem;
import org.jtrfp.trcl.obj.DEFObject;
import org.jtrfp.trcl.obj.ObjectDirection;
import org.jtrfp.trcl.obj.ObjectSystem;
import org.jtrfp.trcl.obj.Player;
import org.jtrfp.trcl.obj.Projectile;
import org.jtrfp.trcl.obj.ProjectileFactory;
import org.jtrfp.trcl.obj.Propelled;
import org.jtrfp.trcl.obj.SpawnsRandomExplosionsAndDebris;
import org.jtrfp.trcl.obj.WorldObject;
import org.jtrfp.trcl.obj.Player.PlayerSaveState;
import org.jtrfp.trcl.shell.GameShellFactory;
import org.jtrfp.trcl.shell.GameShellFactory.GameShell;
import org.jtrfp.trcl.snd.GPUResidentMOD;
import org.jtrfp.trcl.snd.MusicPlaybackEvent;
import org.jtrfp.trcl.snd.SoundSystem;
import org.jtrfp.trcl.tools.Util;
public class Mission {
// PROPERTIES
public static final String LEVEL_NAME = "levelName",
//NAVS = "navs",
NAV_SUB_OBJECTS = "navSubObjects",
GROUND_TARGETS_DESTROYED = "groundTargetsDestroyed",
AIR_TARGETS_DESTROYED = "airTargetsDestroyed",
FOLIAGE_DESTROYED = "foliageDestroyed",
SHOW_INTRO = "showIntro",
CURRENT_NAV_TARGET = "currentNavTarget",
LVL_FILE_NAME = "lvlFileName",
SATELLITE_VIEW = "satelliteView",
PLAYER_START_POSITION = "playerStartPosition",
PLAYER_START_HEADING = "playerStartHeading",
PLAYER_START_TOP = "playerStartTop",
DEF_OBJECT_LIST = "defObjectList",
CURRENT_BOSS = "currentBoss",
PLAYER_SAVE_STATE = "playerSaveState";
//// INTROSPECTOR
static {
try{
final Set<String> persistentProperties = new HashSet<String>();
persistentProperties.addAll(Arrays.asList(
LEVEL_NAME,
//NAVS,
NAV_SUB_OBJECTS,
GROUND_TARGETS_DESTROYED,
AIR_TARGETS_DESTROYED,
FOLIAGE_DESTROYED,
SHOW_INTRO,
CURRENT_NAV_TARGET,
LVL_FILE_NAME,
PLAYER_START_POSITION,
PLAYER_START_HEADING,
PLAYER_START_TOP,
DEF_OBJECT_LIST,
PLAYER_SAVE_STATE
));
BeanInfo info = Introspector.getBeanInfo(Mission.class);
PropertyDescriptor[] propertyDescriptors =
info.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; ++i) {
PropertyDescriptor pd = propertyDescriptors[i];
if (!persistentProperties.contains(pd.getName())) {
pd.setValue("transient", Boolean.TRUE);
}
}
}catch(Exception e){e.printStackTrace();}
}//end static{}
private final TR tr;
private final List<NAVObjective>
navs = new LinkedList<NAVObjective>();
private LVLFile lvl;
private double[] playerStartPosition;
private List<NAVSubObject> navSubObjects;
private double [] playerStartHeading,
playerStartTop;
private Game game;
private String levelName;
private OverworldSystem overworldSystem;
private final Result[] missionEnd = new Result[]{null};
private int groundTargetsDestroyed=0,
airTargetsDestroyed=0,
foliageDestroyed=0;
private boolean showIntro = true;
private volatile MusicPlaybackEvent
bgMusic;
private final Object missionLock = new Object();
private boolean satelliteView = false;
private WorldObject currentBoss = null;
//private MissionMode missionMode = new Mission.LoadingMode();
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private final DisplayModeHandler displayHandler;
private Object [] levelLoadingMode, overworldMode, gameplayMode, briefingMode, summaryMode, emptyMode= new Object[]{};
private NAVObjective currentNavTarget;
private final RenderableSpacePartitioningGrid partitioningGrid = new RenderableSpacePartitioningGrid();
private GameShell gameShell;
private final RunStateListener runStateListener = new RunStateListener();
private WeakPropertyChangeListener weakRunStateListener; // HARD REFERENCE; DO NOT REMOVE.
private String lvlFileName;
private List<DEFObject> defObjectList;
private Map<NAVObjective,NAVSubObject> navMap = new HashMap<>();
private PlayerSaveState playerSaveState;
enum LoadingStages {
navs, tunnels, overworld
}// end LoadingStages
//ROOT STATES
public interface MissionState extends Game.GameRunningMode{}
public interface ConstructingState extends MissionState{}
public interface ConstructedState extends MissionState{}
public interface ActiveMissionState extends ConstructedState{}
public interface LoadingState extends ActiveMissionState{}
public interface GameplayState extends ActiveMissionState{}
public interface Briefing extends GameplayState{}
public interface PlanetBrief extends Briefing{}
public interface EnemyBrief extends Briefing{}
public interface MissionSummary extends Briefing{}
public interface PlayerActivity extends GameplayState{}
public interface OverworldState extends PlayerActivity{}
public interface SatelliteState extends OverworldState{}
public interface ChamberState extends PlayerActivity{}
public interface TunnelState extends PlayerActivity{}
public Mission() {
this.tr = Features.get(Features.getSingleton(), TR.class);
this.displayHandler = new DisplayModeHandler(this.getPartitioningGrid());
tr.addPropertyChangeListener(
TRFactory.RUN_STATE,
weakRunStateListener = new WeakPropertyChangeListener(runStateListener, tr));
}// end Mission
private class RunStateListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
final Object newState = evt.getNewValue();
if(newState instanceof Game.GameDestructingMode)
abort();
}//end propertyChange(...)
}//end RunStateListener
public Result go() {
//Kludge to fulfill previous dependencies
tr.setRunState(new ConstructingState(){});
tr.setRunState(new ConstructedState(){});
Util.assertPropertiesNotNull(this,
"tr",
"game");
final TR tr = getTr();
tr.setRunState(new LoadingState(){});
final LVLFile lvlData = getLvl();
synchronized(missionLock){
synchronized(missionEnd){
if(missionEnd[0]!=null)
return missionEnd[0];
}
tr.getThreadManager().setPaused(true);
for(ProjectileFactory pf:tr.getResourceManager().getProjectileFactories())
for(Projectile proj:pf.getProjectiles())
proj.destroy();
System.out.println("Starting GampeplayLevel loading sequence...");
final LoadingProgressReporter rootProgress = LoadingProgressReporter.Impl
.createRoot(new UpdateHandler() {
@Override
public void update(double unitProgress) {
((TVF3Game)getGame()).getLevelLoadingScreen().setLoadingProgress(unitProgress);
}
});
final LoadingProgressReporter[] progressStages = rootProgress
.generateSubReporters(LoadingStages.values().length);
final Renderer renderer = tr.mainRenderer;
renderer.getCamera().probeForBehavior(SkyCubeCloudModeUpdateBehavior.class).setEnable(false);
renderer.getSkyCube().setSkyCubeGen(GameShellFactory.DEFAULT_GRADIENT);
final Camera camera = renderer.getCamera();
camera.setHeading(Vector3D.PLUS_I);
camera.setTop(Vector3D.PLUS_J);
((TVF3Game)game).levelLoadingMode();
displayHandler.setDisplayMode(getLevelLoadingMode());
((TVF3Game)game).getUpfrontDisplay().submitPersistentMessage(levelName);
try {
final ResourceManager rm = tr.getResourceManager();
final Player player = ((TVF3Game)getGameShell().getGame()).getPlayer();
final TDFFile tdf = rm.getTDFData(lvlData.getTunnelDefinitionFile());
player.setActive(false);
// Abort check
synchronized(missionEnd){
if(missionEnd[0]!=null)
return missionEnd[0];
}
setOverworldSystem(new OverworldSystem(tr,
progressStages[LoadingStages.overworld.ordinal()]));
briefingMode = new Object[]{
((TVF3Game)game).briefingScreen,
overworldSystem
};
gameplayMode = new Object[]{
((TVF3Game)game).upfrontDisplay,
rm.getDebrisSystem(),
rm.getPowerupSystem(),
rm.getProjectileFactories(),
rm.getExplosionFactory(),
rm.getSmokeSystem()
};
overworldMode = new Object[]{
gameplayMode,
overworldSystem
};
summaryMode = new Object[]{
((TVF3Game)game).getBriefingScreen(),
overworldSystem
};
overworldSystem.loadLevel(lvlData, tdf);
final List<DEFObject> defObjectList = getDefObjectList();
final ObjectSystem objectSystem = overworldSystem.getObjectSystem();
if(defObjectList != null)
objectSystem.setDefList(defObjectList);
else{
objectSystem.populateFromLVL(lvlData);
setDefObjectList(objectSystem.getDefList());
}
assert getDefObjectList() != null;
//overworldSystem.loadLevel(lvlData, tdf);
System.out.println("\t...Done.");
//TODO: TunnelSystem should be isolated from Mission
final TunnelSystem ts = Features.get(this, TunnelSystem.class);
ts.installTunnels(tdf,progressStages[LoadingStages.tunnels.ordinal()]);
// Install NAVs if not already set
if( getNavSubObjects() == null ){
setNavSubObjects(rm.getNAVData(lvlData.getNavigationFile())
.getNavObjects());
}
if( navs.isEmpty() ){
Factory f = new NAVObjective.Factory(tr, getLevelName());
//final LoadingProgressReporter[] navProgress = progressStages[LoadingStages.navs
// .ordinal()].generateSubReporters(navSubObjects.size());
final Reporter reporter = Features.get(getTr(), Reporter.class);
for (int i = 0; i < navSubObjects.size(); i++) {
final NAVSubObject obj = navSubObjects.get(i);
f.create(reporter, obj, navs, navMap);
//navProgress[i].complete();
}// end for(navSubObjects)
}//end if( empty )
// ////// INITIAL HEADING
PlayerSaveState playerSaveState = getStoredPlayerSaveState();
//final double [] playerStartPos = getStoredPlayerStartPosition();
//final double [] playerStartHdg = getStoredPlayerStartHeading();
//final double [] playerStartTop = getStoredPlayerStartTop();
if(playerSaveState == null){//No savestate data. Use the map
playerSaveState = new PlayerSaveState();
setPlayerSaveState(playerSaveState);
playerSaveState.readFrom(player);
START startNav = (START) getNavSubObjects().get(0);
final ObjectDirection od = new ObjectDirection(startNav.getRoll(),
startNav.getPitch(), startNav.getYaw());
Location3D l3d = startNav.getLocationOnMap();
final double HEIGHT_PADDING = 10000;
playerSaveState.setHeading(od.getHeading().negate().toArray());
//setPlayerStartHeading (od.getHeading().negate().toArray());
playerSaveState.setTop(od.getTop().toArray());
//setPlayerStartTop (od.getTop().toArray());
playerSaveState.setPosition(new Vector3D(
TRFactory.legacy2Modern(l3d.getZ()), //X (Z)
Math.max(HEIGHT_PADDING + getOverworldSystem().getAltitudeMap().heightAt(// Y
TRFactory.legacy2Modern(l3d.getZ()),
TRFactory.legacy2Modern(l3d.getX())),TRFactory.legacy2Modern(l3d.getY())),
TRFactory.legacy2Modern(l3d.getX()) //Z (X)
).toArray());
}//end if(nulls)
//APPLY STATE
playerSaveState.writeTo(player);
//////// PLAYER POSITIONS
//player.setPosition(getStoredPlayerStartPosition() );
//player.setHeading(new Vector3D(getStoredPlayerStartHeading()) );// Kludge to fix incorrect hdg
//player.setTop (new Vector3D(getStoredPlayerStartTop()) );
///////// STATE
final Propelled propelled = player.probeForBehavior(Propelled.class);
propelled.setPropulsion(propelled.getMinPropulsion());
player.probeForBehavior(CollidesWithTerrain.class) .setEnable(true);
if(player.hasBehavior(SpawnsRandomSmoke.class))
player.probeForBehavior(SpawnsRandomSmoke.class) .setEnable(false);
if(player.hasBehavior(SpawnsRandomExplosionsAndDebris.class))
player.probeForBehavior(SpawnsRandomExplosionsAndDebris.class).setEnable(false);
//player.probeForBehavior(SpinCrashDeathBehavior.class).setEnable(false);
final TVF3Game game = (TVF3Game)getGame();
game.getNavSystem().updateNAVState();
player.resetVelocityRotMomentum();
final String startX = System.getProperty("org.jtrfp.trcl.startX");
final String startY = System.getProperty("org.jtrfp.trcl.startY");
final String startZ = System.getProperty("org.jtrfp.trcl.startZ");
final double[] playerPos = player.getPosition();
if (startX != null && startY != null && startZ != null) {
System.out.println("Using user-specified start point");
final int sX = Integer.parseInt(startX);
final int sY = Integer.parseInt(startY);
final int sZ = Integer.parseInt(startZ);
playerPos[0] = sX;
playerPos[1] = sY;
playerPos[2] = sZ;
player.notifyPositionChange();
}// end if(user start point)
System.out.println("Start position set to " + player.getPosition()[0]+" "+player.getPosition()[1]+" "+player.getPosition()[2]);
System.out.println("Setting sun vector");
final AbstractTriplet sunVector = lvlData.getSunlightDirectionVector();
tr.getThreadManager().submitToGL(new Callable<Void>() {
@Override
public Void call() throws Exception {
tr.mainRenderer.setSunVector(
new Vector3D(sunVector.getX(), sunVector.getY(),
sunVector.getZ()).normalize());
return null;
}
}).get();
System.out.println("\t...Done.");
} catch (Exception e) {
e.printStackTrace();
}
if (System.getProperties().containsKey(
"org.jtrfp.trcl.flow.Mission.skipNavs")) {
try {
final int skips = Integer.parseInt(System
.getProperty("org.jtrfp.trcl.flow.Mission.skipNavs"));
System.out.println("Skipping " + skips + " navs.");
for (int i = 0; i < skips; i++) {
removeNAVObjective(currentNAVObjective());
}// end for(skips)
} catch (NumberFormatException e) {
System.err
.println("Invalid format for property \"org.jtrfp.trcl.flow.Mission.skipNavs\". Must be integer.");
}
}// end if(containsKey)
// Transition to gameplay mode.
// Abort check
synchronized (missionEnd) {
if (missionEnd[0] != null)
return missionEnd[0];
}//end sync(missionEnd)
final SoundSystem ss = Features.get(tr,SoundSystemFeature.class);
MusicPlaybackEvent evt;
Features.get(tr,SoundSystemFeature.class).enqueuePlaybackEvent(
evt =ss
.getMusicFactory()
.create(new GPUResidentMOD(tr, tr
.getResourceManager().getMOD(
lvlData.getBackgroundMusicFile())),
true));
synchronized(Mission.this){
if(bgMusic==null){
bgMusic=evt;
bgMusic.play();
}
}//end sync(Mission.this)
((TVF3Game)game).getUpfrontDisplay().removePersistentMessage();
Features.get(tr,SoundSystemFeature.class).setPaused(false);
tr.getThreadManager().setPaused(false);
if(isShowIntro()){
tr.setRunState(new EnemyBrief(){});
displayHandler.setDisplayMode(briefingMode);
((TVF3Game)game).getBriefingScreen().briefingSequence(lvl);//TODO: Convert to feature
setShowIntro(false);
}
tr.setRunState(new OverworldState(){});
final SkySystem skySystem = getOverworldSystem().getSkySystem();
tr.mainRenderer.getCamera().probeForBehavior(SkyCubeCloudModeUpdateBehavior.class).setEnable(true);
renderer.getSkyCube().setSkyCubeGen(skySystem.getBelowCloudsSkyCubeGen());
renderer.setAmbientLight(skySystem.getSuggestedAmbientLight());
renderer.setSunColor(skySystem.getSuggestedSunColor());
((TVF3Game)game).getNavSystem() .activate();
displayHandler.setDisplayMode(overworldMode);
((TVF3Game)game).getPlayer() .setActive(true);
((TVF3Game)getGameShell().getGame()).setPaused(false);
//tr.setRunState(new PlayerActivity(){});
//Wait for mission end
synchronized(missionEnd){
while(missionEnd[0]==null){try{missionEnd.wait();}
catch(InterruptedException e){break;}}}
//Completion summary
if(missionEnd[0]!=null)
if(!missionEnd[0].isAbort()){
displayHandler.setDisplayMode(summaryMode);
tr.setRunState(new MissionSummary(){});
((TVF3Game)game).getBriefingScreen().missionCompleteSummary(lvl,missionEnd[0]);
}//end if(proper ending)
bgMusic.stop();
cleanup();
return missionEnd[0];
}//end sync
}// end go()
private LVLFile getLvl() {
if(lvl == null)
try{lvl = getTr().getResourceManager().getLVL(getLvlFileName());}
catch(Exception e){e.printStackTrace();}
return lvl;
}
private Object [] getLevelLoadingMode(){
if(levelLoadingMode == null){
final Game game = getGame();
if(game == null)
throw new IllegalStateException("game property intolerably null.");
levelLoadingMode = new Object[]{
((TVF3Game)game).getLevelLoadingScreen(),
((TVF3Game)game).getUpfrontDisplay()
};
}
return levelLoadingMode;
}//end getLevelLoadingMode
public NAVObjective currentNAVObjective() {
if (navs.isEmpty())
return null;
return navs.get(0);
}//end currentNAVObjective()
public void removeNAVObjective(NAVObjective o) {
navs.remove(o);
getNavSubObjects().remove(navMap.get(o));
updateNavState();
((TVF3Game)getGameShell().getGame()).getNavSystem().updateNAVState();
}// end removeNAVObjective(...)
private void updateNavState(){
try{this.setCurrentNavTarget(navs.get(0));}
catch(IndexOutOfBoundsException e){setCurrentNavTarget(null);}
}
public static class Result {
private final int airTargetsDestroyed, groundTargetsDestroyed,foliageDestroyed;
private boolean abort=false;
public Result(int airTargetsDestroyed, int groundTargetsDestroyed, int foliageDestroyed) {
this.airTargetsDestroyed =airTargetsDestroyed;
this.groundTargetsDestroyed =groundTargetsDestroyed;
this.foliageDestroyed =foliageDestroyed;
}//end constructor
/**
* @return the airTargetsDestroyed
*/
public int getAirTargetsDestroyed() {
return airTargetsDestroyed;
}
/**
* @return the groundTargetsDestroyed
*/
public int getGroundTargetsDestroyed() {
return groundTargetsDestroyed;
}
/**
* @return the foliageDestroyed
*/
public int getFoliageDestroyed() {
return foliageDestroyed;
}
/**
* @return the abort
*/
public boolean isAbort() {
return abort;
}
/**
* @param abort the abort to set
*/
public void setAbort(boolean abort) {
this.abort = abort;
}
}// end Result
/**
* NOTE: This returns the current Game's Player position and does not directly reflect setter changes.
* @return
* @since Jul 15, 2016
*/
public double[] getPlayerStartPosition() {
final Game game = getGame();
if(game == null)
return null;
final Player player = game.getPlayer();
if(player == null)
return null;
return player.getPosition();
}
public double[] getStoredPlayerStartPosition(){
return playerStartPosition;
}
public void playerDestroyed() {
new Thread() {
@Override
public void run() {
System.out.println("MISSION FAILED.");
notifyMissionEnd(null);
}// end run()
}.start();
}// end playerDestroyed()
public void notifyMissionEnd(Result r){
synchronized(missionEnd){
missionEnd[0]=r;
missionEnd.notifyAll();}
}//end notifyMissionEnd()
public List<NAVObjective> getRemainingNAVObjectives() {
return navs;
}
/**
* @return the navSubObjects
*/
public List<NAVSubObject> getNavSubObjects() {
return navSubObjects;
}
/**
* @param navSubObjects
* the navSubObjects to set
*/
public void setNavSubObjects(List<NAVSubObject> navSubObjects) {
if( navSubObjects != null)
this.navSubObjects = new ArrayList<NAVSubObject>(navSubObjects);
else
navSubObjects = null;
navs.clear();//Ensure navs get repopulated.
}
public OverworldSystem getOverworldSystem() {
return overworldSystem;
}
public Mission notifyAirTargetDestroyed(){
airTargetsDestroyed++;
return this;
}
public Mission notifyGroundTargetDestroyed(){
groundTargetsDestroyed++;
return this;
}
public Mission notifyFoliageDestroyed(){
foliageDestroyed++;
return this;
}
public void enterBossMode(final String bossMusicFile, WorldObject boss){
setCurrentBoss(boss);
tr.getThreadManager().submitToThreadPool(new Callable<Void>() {
@Override
public Void call() throws Exception {
MusicPlaybackEvent evt;
final SoundSystem ss = Features.get(tr,SoundSystemFeature.class);
Features.get(tr,SoundSystemFeature.class).enqueuePlaybackEvent(
evt =ss
.getMusicFactory()
.create(tr.getResourceManager().gpuResidentMODs.get(bossMusicFile),
true));
synchronized(Mission.this){
evt.play();
if(bgMusic!=null)
bgMusic.stop();
bgMusic=evt;
}
return null;
}// end call()
});
}//end enterBossMode()
public void exitBossMode(){
setCurrentBoss(null);
tr.getThreadManager().submitToThreadPool(new Callable<Void>() {
@Override
public Void call() throws Exception {
MusicPlaybackEvent evt;
final SoundSystem ss = Features.get(tr,SoundSystemFeature.class);
Features.get(tr,SoundSystemFeature.class).enqueuePlaybackEvent(
evt =ss
.getMusicFactory()
.create(tr.getResourceManager().gpuResidentMODs.get(getLvl().getBackgroundMusicFile()),
true));
synchronized(Mission.this){
evt.play();
bgMusic.stop();
bgMusic=evt;}
return null;
}// end call()
});
}//end exitBossMode()
public void abort() {
final Result result = new Result(
airTargetsDestroyed,
groundTargetsDestroyed,
foliageDestroyed/*,
1.-(double)tunnelsRemaining.size()/(double)totalNumTunnels*/);
result.setAbort(true);
notifyMissionEnd(result);
//Wait for mission to end
synchronized(missionLock){//Don't execute while mission is in progress.
cleanup();
}//end sync{}
}//end abort()
private void cleanup() {
displayHandler.setDisplayMode(emptyMode);
tr.getResourceManager().getPowerupSystem().removeAll();
// Remove projectile factories
for(ProjectileFactory pf:tr.getResourceManager().getProjectileFactories())
for(Projectile projectile:pf.getProjectiles())
projectile.destroy();
}//end cleanup()
/**
* @param listener
* @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.beans.PropertyChangeListener)
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
/**
* @param propertyName
* @param listener
* @see java.beans.PropertyChangeSupport#addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
*/
public void addPropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
pcs.addPropertyChangeListener(propertyName, listener);
}
/**
* @return
* @see java.beans.PropertyChangeSupport#getPropertyChangeListeners()
*/
public PropertyChangeListener[] getPropertyChangeListeners() {
return pcs.getPropertyChangeListeners();
}
/**
* @param propertyName
* @return
* @see java.beans.PropertyChangeSupport#getPropertyChangeListeners(java.lang.String)
*/
public PropertyChangeListener[] getPropertyChangeListeners(
String propertyName) {
return pcs.getPropertyChangeListeners(propertyName);
}
/**
* @param propertyName
* @return
* @see java.beans.PropertyChangeSupport#hasListeners(java.lang.String)
*/
public boolean hasListeners(String propertyName) {
return pcs.hasListeners(propertyName);
}
/**
* @param listener
* @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.beans.PropertyChangeListener)
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
/**
* @param propertyName
* @param listener
* @see java.beans.PropertyChangeSupport#removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
*/
public void removePropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
pcs.removePropertyChangeListener(propertyName, listener);
}
/**
* @return the bossFight
*/
public WorldObject getCurrentBoss() {
return currentBoss;
}
public void setCurrentBoss(WorldObject boss) {
final WorldObject oldBoss = this.currentBoss;//Probably null.
this.currentBoss = boss;
pcs.firePropertyChange(CURRENT_BOSS, oldBoss, boss);
}
public void setSatelliteView(boolean satelliteView) {
if(!(tr.getRunState() instanceof OverworldState)&&satelliteView)
throw new IllegalArgumentException("Cannot activate satellite view while runState is "+tr.getRunState().getClass().getSimpleName());
if(satelliteView && ((TVF3Game)getGameShell().getGame()).isPaused())
throw new IllegalArgumentException("Cannot activate satellite view while paused.");
final boolean oldValue = this.satelliteView;
if(satelliteView!=oldValue){
final Game game = ((TVF3Game)getGameShell().getGame());
final Camera cam = tr.mainRenderer.getCamera();
this.satelliteView=satelliteView;
pcs.firePropertyChange(SATELLITE_VIEW, oldValue, satelliteView);
tr.setRunState(satelliteView?new SatelliteState(){}:new OverworldState(){});
if(satelliteView){//Switched on
tr.getThreadManager().setPaused(true);
cam.setFogEnabled(false);
cam.probeForBehavior(MatchPosition.class).setEnable(false);
cam.probeForBehavior(MatchDirection.class).setEnable(false);
final Vector3D pPos = new Vector3D(((TVF3Game)game).getPlayer().getPosition());
final Vector3D pHeading = ((TVF3Game)getGameShell().getGame()).getPlayer().getHeading();
cam.setPosition(new Vector3D(pPos.getX(),TRFactory.visibilityDiameterInMapSquares*TRFactory.mapSquareSize*.65,pPos.getZ()));
cam.setHeading(Vector3D.MINUS_J);
cam.setTop(new Vector3D(pHeading.getX(),.0000000001,pHeading.getZ()).normalize());
((TVF3Game)getGameShell().getGame()).getSatDashboard().setVisible(true);
}else{//Switched off
tr.getThreadManager().setPaused(false);
World.relevanceExecutor.submit(new Runnable(){
@Override
public void run() {
((TVF3Game)getGameShell().getGame()).getNavSystem().activate();
}});
cam.setFogEnabled(true);
cam.probeForBehavior(MatchPosition.class).setEnable(true);
cam.probeForBehavior(MatchDirection.class).setEnable(true);
((TVF3Game)getGameShell().getGame()).getSatDashboard().setVisible(false);
}//end !satelliteView
}//end if(change)
}
/**
* @return the satelliteView
*/
public boolean isSatelliteView() {
return satelliteView;
}
public Game getGame() {
return game;
}
public void destruct() {
Features.destruct(this);
}
public String getLevelName() {
return levelName;
}
public int getGroundTargetsDestroyed() {
return groundTargetsDestroyed;
}
public void setGroundTargetsDestroyed(int groundTargetsDestroyed) {
this.groundTargetsDestroyed = groundTargetsDestroyed;
}
public int getAirTargetsDestroyed() {
return airTargetsDestroyed;
}
public void setAirTargetsDestroyed(int airTargetsDestroyed) {
this.airTargetsDestroyed = airTargetsDestroyed;
}
public int getFoliageDestroyed() {
return foliageDestroyed;
}
public void setFoliageDestroyed(int foliageDestroyed) {
this.foliageDestroyed = foliageDestroyed;
}
public NAVObjective getCurrentNavTarget() {
return currentNavTarget;
}
public Mission setCurrentNavTarget(NAVObjective newTarget) {
final NAVObjective oldTarget = this.currentNavTarget;
this.currentNavTarget = newTarget;
pcs.firePropertyChange(CURRENT_NAV_TARGET, oldTarget, newTarget);
return this;
}
public void setDisplayMode(Object [] newMode){//TODO: Refactor this to follow tr's run state instead
displayHandler.setDisplayMode(newMode);
}
public RenderableSpacePartitioningGrid getPartitioningGrid() {
return partitioningGrid;
}
public TR getTr() {
return tr;
}
public GameShell getGameShell() {
if(gameShell == null)
gameShell = Features.get(getTr(), GameShell.class);
return gameShell;
}
public void setGameShell(GameShell gameShell) {
this.gameShell = gameShell;
}
public void setGame(Game game) {
this.game = game;
}
public void setLevelName(String levelName) {
this.levelName = levelName;
}
public boolean isShowIntro() {
return showIntro;
}
public void setShowIntro(boolean showIntro) {
this.showIntro = showIntro;
}
public String getLvlFileName() {
return lvlFileName;
}
public void setLvlFileName(String lvlFileName) {
this.lvlFileName = lvlFileName;
}
public List<DEFObject> getDefObjectList() {
return defObjectList;
}
public void setDefObjectList(List<DEFObject> defObjectList) {
this.defObjectList = defObjectList;
}//end setDefObjectList(...)
void setOverworldSystem(OverworldSystem overworldSystem) {
this.overworldSystem = overworldSystem;
}
public Object [] getOverworldMode(){
return overworldMode;
}
public PlayerSaveState getPlayerSaveState(){
final Game game = getGame();
if(game == null)
return null;
final Player player = game.getPlayer();
if(player == null)
return null;
return player.getPlayerSaveState();
}
protected PlayerSaveState getStoredPlayerSaveState(){
return playerSaveState;
}
public void setPlayerSaveState(PlayerSaveState pss){
playerSaveState = pss;
}
}// end Mission
|
✔Mission must skip brief on null.txt for multiplayer maps to work.
|
src/main/java/org/jtrfp/trcl/miss/Mission.java
|
✔Mission must skip brief on null.txt for multiplayer maps to work.
|
|
Java
|
agpl-3.0
|
a49ad6e715c34e80f1b7506d92c74a07e98f4b77
| 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
|
0cf77e74-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
0cf205fc-2e62-11e5-9284-b827eb9e62be
|
0cf77e74-2e62-11e5-9284-b827eb9e62be
|
hello.java
|
0cf77e74-2e62-11e5-9284-b827eb9e62be
|
|
Java
|
agpl-3.0
|
c382b11f1398000aa4dbee5cdff3447e49fcad95
| 0
|
ingted/voltdb,VoltDB/voltdb,creative-quant/voltdb,wolffcm/voltdb,migue/voltdb,ingted/voltdb,ingted/voltdb,VoltDB/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,zuowang/voltdb,simonzhangsm/voltdb,flybird119/voltdb,deerwalk/voltdb,creative-quant/voltdb,zuowang/voltdb,flybird119/voltdb,wolffcm/voltdb,ingted/voltdb,migue/voltdb,simonzhangsm/voltdb,kumarrus/voltdb,paulmartel/voltdb,VoltDB/voltdb,zuowang/voltdb,paulmartel/voltdb,creative-quant/voltdb,creative-quant/voltdb,migue/voltdb,flybird119/voltdb,zuowang/voltdb,wolffcm/voltdb,VoltDB/voltdb,kumarrus/voltdb,kumarrus/voltdb,VoltDB/voltdb,simonzhangsm/voltdb,wolffcm/voltdb,wolffcm/voltdb,kumarrus/voltdb,migue/voltdb,migue/voltdb,simonzhangsm/voltdb,deerwalk/voltdb,wolffcm/voltdb,zuowang/voltdb,creative-quant/voltdb,paulmartel/voltdb,migue/voltdb,deerwalk/voltdb,paulmartel/voltdb,VoltDB/voltdb,flybird119/voltdb,flybird119/voltdb,ingted/voltdb,ingted/voltdb,kumarrus/voltdb,deerwalk/voltdb,migue/voltdb,paulmartel/voltdb,kumarrus/voltdb,paulmartel/voltdb,ingted/voltdb,VoltDB/voltdb,flybird119/voltdb,flybird119/voltdb,kumarrus/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,migue/voltdb,ingted/voltdb,zuowang/voltdb,zuowang/voltdb,simonzhangsm/voltdb,wolffcm/voltdb,deerwalk/voltdb,paulmartel/voltdb,creative-quant/voltdb,creative-quant/voltdb,flybird119/voltdb,simonzhangsm/voltdb,kumarrus/voltdb,zuowang/voltdb,creative-quant/voltdb,deerwalk/voltdb,paulmartel/voltdb,wolffcm/voltdb
|
/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This program 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.
*
* This program 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import org.supercsv.io.CsvListReader;
import org.supercsv.io.ICsvListReader;
import org.supercsv.prefs.CsvPreference;
import org.supercsv_voltpatches.tokenizer.Tokenizer;
import org.voltcore.logging.VoltLogger;
import org.voltdb.CLIConfig;
import org.voltdb.client.Client;
import org.voltdb.client.ClientConfig;
import org.voltdb.client.ClientFactory;
/**
* CSVLoader is a simple utility to load data from a CSV formatted file to a table.
*
* This utility processes partitioned data efficiently and creates as many partition processors.
* For partitioned data each processor calls
* @LoadSinglepartitionTable
*
* For multi-partitioned data it uses a single processor which call
* @LoadMultipartitionTable
*
* The maxerror indicates maximum number of errors it can tolerate.
* Its a threshold but since processors are processing in parallel we may process rows beyond
* maxerror and additional errors may occur. Only first maxerror indicated errors will be reported.
*
*/
public class CSVLoader {
/**
* Path of invalid row file that will be created.
*/
static String pathInvalidrowfile = "";
/**
* report file name
*/
static String pathReportfile = "csvloaderReport.log";
/**
* log file name
*/
static String pathLogfile = "csvloaderLog.log";
private static final VoltLogger m_log = new VoltLogger("CSVLOADER");
private static CSVConfig config = null;
private static long latency = 0;
private static long start = 0;
private static boolean standin = false;
private static BufferedWriter out_invaliderowfile;
private static BufferedWriter out_logfile;
private static BufferedWriter out_reportfile;
private static String insertProcedure = "";
private static CsvPreference csvPreference = null;
/**
* default CSV separator
*/
public static final char DEFAULT_SEPARATOR = ',';
/**
* default quote char
*/
public static final char DEFAULT_QUOTE_CHARACTER = '\"';
/**
* default escape char
*/
public static final char DEFAULT_ESCAPE_CHARACTER = '\\';
/**
* Are we using strict quotes
*/
public static final boolean DEFAULT_STRICT_QUOTES = false;
/**
* Number of lines to skip in CSV
*/
public static final int DEFAULT_SKIP_LINES = 0;
/**
* Allow whitespace?
*/
public static final boolean DEFAULT_NO_WHITESPACE = false;
/**
* Size limit for each column.
*/
public static final long DEFAULT_COLUMN_LIMIT_SIZE = 16777216;
/**
* Used for testing only.
*/
public static boolean testMode = false;
/**
* Configuration options.
*/
public static class CSVConfig extends CLIConfig {
@Option(shortOpt = "f", desc = "location of CSV input file")
String file = "";
@Option(shortOpt = "p", desc = "procedure name to insert the data into the database")
String procedure = "";
@Option(desc = "maximum rows to be read from the CSV file")
int limitrows = Integer.MAX_VALUE;
@Option(shortOpt = "r", desc = "directory path for report files")
String reportdir = System.getProperty("user.dir");
@Option(shortOpt = "m", desc = "maximum errors allowed")
int maxerrors = 100;
@Option(desc = "different ways to handle blank items: {error|null|empty} (default: error)")
String blank = "error";
@Option(desc = "delimiter to use for separating entries")
char separator = DEFAULT_SEPARATOR;
@Option(desc = "character to use for quoted elements (default: \")")
char quotechar = DEFAULT_QUOTE_CHARACTER;
@Option(desc = "character to use for escaping a separator or quote (default: \\)")
char escape = DEFAULT_ESCAPE_CHARACTER;
@Option(desc = "require all input values to be enclosed in quotation marks", hasArg = false)
boolean strictquotes = DEFAULT_STRICT_QUOTES;
@Option(desc = "number of lines to skip before inserting rows into the database")
long skip = DEFAULT_SKIP_LINES;
@Option(desc = "do not allow whitespace between values and separators", hasArg = false)
boolean nowhitespace = DEFAULT_NO_WHITESPACE;
@Option(desc = "max size of a quoted column in bytes(default: 16777216 = 16MB)")
long columnsizelimit = DEFAULT_COLUMN_LIMIT_SIZE;
@Option(shortOpt = "s", desc = "list of servers to connect to (default: localhost)")
String servers = "localhost";
@Option(desc = "username when connecting to the servers")
String user = "";
@Option(desc = "password to use when connecting to servers")
String password = "";
@Option(desc = "port to use when connecting to database (default: 21212)")
int port = Client.VOLTDB_SERVER_PORT;
/**
* Batch size for processing batched operations.
*/
@Option(desc = "Batch Size for processing.")
public int batch = 200;
/**
* Table name to insert CSV data into.
*/
@AdditionalArgs(desc = "insert the data into database by TABLENAME.insert procedure by default")
public String table = "";
// This is set to true when -p option us used.
boolean useSuppliedProcedure = false;
/**
* Validate command line options.
*/
@Override
public void validate() {
if (maxerrors < 0) {
exitWithMessageAndUsage("abortfailurecount must be >=0");
}
if (procedure.equals("") && table.equals("")) {
exitWithMessageAndUsage("procedure name or a table name required");
}
if (!procedure.equals("") && !table.equals("")) {
exitWithMessageAndUsage("Only a procedure name or a table name required, pass only one please");
}
if (skip < 0) {
exitWithMessageAndUsage("skipline must be >= 0");
}
if (port < 0) {
exitWithMessageAndUsage("port number must be >= 0");
}
if (batch < 0) {
exitWithMessageAndUsage("batch size number must be >= 0");
}
if ((blank.equalsIgnoreCase("error")
|| blank.equalsIgnoreCase("null")
|| blank.equalsIgnoreCase("empty")) == false) {
exitWithMessageAndUsage("blank configuration specified must be one of {error|null|empty}");
}
if ((procedure != null) && (procedure.trim().length() > 0)) {
useSuppliedProcedure = true;
}
}
/**
* Usage
*/
@Override
public void printUsage() {
System.out
.println("Usage: csvloader [args] tablename");
System.out
.println(" csvloader [args] -p procedurename");
super.printUsage();
}
}
/**
* csvloader main. (main is directly used by tests as well be sure to reset statics that you need to start over)
*
* @param args
* @throws IOException
* @throws InterruptedException
*
*/
public static void main(String[] args) throws IOException,
InterruptedException {
start = System.currentTimeMillis();
long insertTimeStart = start;
long insertTimeEnd;
final CSVConfig cfg = new CSVConfig();
cfg.parse(CSVLoader.class.getName(), args);
config = cfg;
configuration();
final Tokenizer tokenizer;
ICsvListReader listReader = null;
try {
if (CSVLoader.standin) {
tokenizer = new Tokenizer(new BufferedReader(new InputStreamReader(System.in)), csvPreference,
config.strictquotes, config.escape, config.columnsizelimit,
config.skip);
listReader = new CsvListReader(tokenizer, csvPreference);
} else {
tokenizer = new Tokenizer(new FileReader(config.file), csvPreference,
config.strictquotes, config.escape, config.columnsizelimit,
config.skip);
listReader = new CsvListReader(tokenizer, csvPreference);
}
} catch (FileNotFoundException e) {
m_log.error("CSV file '" + config.file + "' could not be found.");
System.exit(-1);
}
// Split server list
final String[] serverlist = config.servers.split(",");
// Create connection
final ClientConfig c_config = new ClientConfig(config.user, config.password);
c_config.setProcedureCallTimeout(0); // Set procedure all to infinite
Client csvClient = null;
try {
csvClient = CSVLoader.getClient(c_config, serverlist, config.port);
} catch (Exception e) {
m_log.error("Error connecting to the servers: "
+ config.servers);
System.exit(-1);
}
assert (csvClient != null);
try {
if (!CSVPartitionProcessor.initializeProcessorInformation(config, csvClient)) {
System.exit(-1);
}
//Create launch processor threads. If Multipartitioned only 1 processor is launched.
List<Thread> spawned = new ArrayList<Thread>(CSVPartitionProcessor.m_numProcessors);
CSVLineWithMetaData endOfData = new CSVLineWithMetaData(null, null, -1);
Map<Long, BlockingQueue<CSVLineWithMetaData>> lineq =
new HashMap<Long, BlockingQueue<CSVLineWithMetaData>>(CSVPartitionProcessor.m_numProcessors);
List<CSVPartitionProcessor> processors = new ArrayList<CSVPartitionProcessor>(CSVPartitionProcessor.m_numProcessors);
int numBatchesInQueuePerPartition = (1000 / CSVPartitionProcessor.m_numProcessors);
if (numBatchesInQueuePerPartition < 5) {
numBatchesInQueuePerPartition = 5;
}
m_log.debug("Max Number of batches per partition processor: " + numBatchesInQueuePerPartition);
for (long i = 0; i < CSVPartitionProcessor.m_numProcessors; i++) {
//Keep only numBatchesInQueuePerPartition batches worth data in queue.
LinkedBlockingQueue<CSVLineWithMetaData> partitionQueue
= new LinkedBlockingQueue<CSVLineWithMetaData>(config.batch * numBatchesInQueuePerPartition);
lineq.put(i, partitionQueue);
CSVPartitionProcessor processor = new CSVPartitionProcessor(csvClient, i,
CSVPartitionProcessor.m_partitionedColumnIndex, partitionQueue, endOfData);
processors.add(processor);
Thread th = new Thread(processor);
th.setName(processor.m_processorName);
spawned.add(th);
}
CSVFileReader.m_config = config;
CSVFileReader.m_listReader = listReader;
CSVFileReader.m_processorQueues = lineq;
CSVFileReader.m_endOfData = endOfData;
CSVFileReader.m_csvClient = csvClient;
CSVFileReader csvReader = new CSVFileReader();
Thread th = new Thread(csvReader);
th.setName("CSVFileReader");
th.setDaemon(true);
//Start the processor threads.
for (Thread th2 : spawned) {
th2.start();
}
//Wait for reader to finish it count downs the procesors.
th.start();
th.join();
long readerTime = (csvReader.m_parsingTime) / 1000000;
insertTimeEnd = System.currentTimeMillis();
csvClient.drain();
csvClient.close();
long insertCount = 0;
//Sum up all the partition processed count i.e the number of rows we sent to server.
for (CSVPartitionProcessor pp : processors) {
insertCount += pp.m_partitionProcessedCount.get();
}
long ackCount = CSVPartitionProcessor.m_partitionAcknowledgedCount.get();
m_log.debug("Parsing CSV file took " + readerTime + " milliseconds.");
m_log.debug("Inserting Data took " + ((insertTimeEnd - insertTimeStart) - readerTime) + " milliseconds.");
m_log.info("Read " + insertCount + " rows from file and successfully inserted "
+ ackCount + " rows (final)");
produceFiles(ackCount, insertCount);
boolean noerrors = CSVFileReader.m_errorInfo.isEmpty();
close_cleanup();
//In test junit mode we let it continue for reuse
if (!CSVLoader.testMode) {
System.exit(noerrors ? 0 : -1);
}
} catch (Exception ex) {
m_log.error("Exception Happened while loading CSV data: " + ex);
System.exit(1);
}
}
private static void configuration() {
csvPreference = new CsvPreference.Builder(config.quotechar, config.separator, "\n").build();
if (config.file.equals("")) {
standin = true;
}
if (!config.table.equals("")) {
insertProcedure = config.table.toUpperCase() + ".insert";
} else {
insertProcedure = config.procedure;
}
if (!config.reportdir.endsWith("/")) {
config.reportdir += "/";
}
try {
File dir = new File(config.reportdir);
if (!dir.exists()) {
dir.mkdirs();
}
} catch (Exception x) {
m_log.error(x.getMessage(), x);
System.exit(-1);
}
String myinsert = insertProcedure;
myinsert = myinsert.replaceAll("\\.", "_");
pathInvalidrowfile = config.reportdir + "csvloader_" + myinsert + "_"
+ "invalidrows.csv";
pathLogfile = config.reportdir + "csvloader_" + myinsert + "_"
+ "log.log";
pathReportfile = config.reportdir + "csvloader_" + myinsert + "_"
+ "report.log";
try {
out_invaliderowfile = new BufferedWriter(new FileWriter(
pathInvalidrowfile));
out_logfile = new BufferedWriter(new FileWriter(pathLogfile));
out_reportfile = new BufferedWriter(new FileWriter(pathReportfile));
} catch (IOException e) {
m_log.error(e.getMessage());
System.exit(-1);
}
}
/**
* Get connection to servers in cluster.
*
* @param config
* @param servers
* @param port
* @return
* @throws Exception
*/
public static Client getClient(ClientConfig config, String[] servers,
int port) throws Exception {
final Client client = ClientFactory.createClient(config);
for (String server : servers) {
client.createConnection(server.trim(), port);
}
return client;
}
private static void produceFiles(long ackCount, long insertCount) {
Map<Long, String[]> errorInfo = CSVFileReader.m_errorInfo;
latency = System.currentTimeMillis() - start;
m_log.info("Elapsed time: " + latency / 1000F
+ " seconds");
int bulkflush = 300; // by default right now
try {
long linect = 0;
for (Long irow : errorInfo.keySet()) {
String info[] = errorInfo.get(irow);
if (info.length != 2) {
System.out.println("internal error, information is not enough");
}
linect++;
out_invaliderowfile.write(info[0] + "\n");
String message = "Invalid input on line " + irow + ".\n Contents:" + info[0];
m_log.error(message);
out_logfile.write(message + "\n " + info[1] + "\n");
if (linect % bulkflush == 0) {
out_invaliderowfile.flush();
out_logfile.flush();
}
}
// Get elapsed time in seconds
float elapsedTimeSec = latency / 1000F;
out_reportfile.write("CSVLoader elaspsed: " + elapsedTimeSec
+ " seconds\n");
long trueSkip;
//get the actuall number of lines skipped
if (config.skip < CSVFileReader.m_totalLineCount.get()) {
trueSkip = config.skip;
} else {
trueSkip = CSVFileReader.m_totalLineCount.get();
}
out_reportfile.write("Number of input lines skipped: "
+ trueSkip + "\n");
out_reportfile.write("Number of lines read from input: "
+ (CSVFileReader.m_totalLineCount.get() - trueSkip) + "\n");
if (config.limitrows == -1) {
out_reportfile.write("Input stopped after "
+ CSVFileReader.m_totalRowCount.get() + " rows read" + "\n");
}
out_reportfile.write("Number of rows discovered: "
+ CSVFileReader.m_totalLineCount.get() + "\n");
out_reportfile.write("Number of rows successfully inserted: "
+ ackCount + "\n");
// if prompted msg changed, change it also for test case
out_reportfile.write("Number of rows that could not be inserted: "
+ errorInfo.size() + "\n");
out_reportfile.write("CSVLoader rate: " + insertCount
/ elapsedTimeSec + " row/s\n");
m_log.info("Invalid row file: " + pathInvalidrowfile);
m_log.info("Log file: " + pathLogfile);
m_log.info("Report file: " + pathReportfile);
out_invaliderowfile.flush();
out_logfile.flush();
out_reportfile.flush();
} catch (FileNotFoundException e) {
m_log.error("CSV report directory '" + config.reportdir
+ "' does not exist.");
} catch (Exception x) {
m_log.error(x.getMessage());
}
}
private static void close_cleanup() throws IOException,
InterruptedException {
//Reset all this for tests which uses main to load csv data.
CSVFileReader.m_errorInfo.clear();
CSVFileReader.m_errored = false;
CSVPartitionProcessor.m_numProcessors = 1;
CSVPartitionProcessor.m_columnCnt = 0;
CSVFileReader.m_totalLineCount = new AtomicLong(0);
CSVFileReader.m_totalRowCount = new AtomicLong(0);
CSVPartitionProcessor.m_partitionAcknowledgedCount = new AtomicLong(0);
out_invaliderowfile.close();
out_logfile.close();
out_reportfile.close();
}
}
|
src/frontend/org/voltdb/utils/CSVLoader.java
|
/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This program 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.
*
* This program 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import org.supercsv.io.CsvListReader;
import org.supercsv.io.ICsvListReader;
import org.supercsv.prefs.CsvPreference;
import org.supercsv_voltpatches.tokenizer.Tokenizer;
import org.voltcore.logging.VoltLogger;
import org.voltdb.CLIConfig;
import org.voltdb.client.Client;
import org.voltdb.client.ClientConfig;
import org.voltdb.client.ClientFactory;
/**
* CSVLoader is a simple utility to load data from a CSV formatted file to a table.
*
* This utility processes partitioned data efficiently and creates as many partition processors.
* For partitioned data each processor calls
* @LoadSinglepartitionTable
*
* For multi-partitioned data it uses a single processor which call
* @LoadMultipartitionTable
*
* The maxerror indicates maximum number of errors it can tolerate.
* Its a threshold but since processors are processing in parallel we may process rows beyond
* maxerror and additional errors may occur. Only first maxerror indicated errors will be reported.
*
*/
public class CSVLoader {
/**
* Path of invalid row file that will be created.
*/
static String pathInvalidrowfile = "";
/**
* report file name
*/
static String pathReportfile = "csvloaderReport.log";
/**
* log file name
*/
static String pathLogfile = "csvloaderLog.log";
private static final VoltLogger m_log = new VoltLogger("CSVLOADER");
private static CSVConfig config = null;
private static long latency = 0;
private static long start = 0;
private static boolean standin = false;
private static BufferedWriter out_invaliderowfile;
private static BufferedWriter out_logfile;
private static BufferedWriter out_reportfile;
private static String insertProcedure = "";
private static CsvPreference csvPreference = null;
/**
* default CSV separator
*/
public static final char DEFAULT_SEPARATOR = ',';
/**
* default quote char
*/
public static final char DEFAULT_QUOTE_CHARACTER = '\"';
/**
* default escape char
*/
public static final char DEFAULT_ESCAPE_CHARACTER = '\\';
/**
* Are we using strict quotes
*/
public static final boolean DEFAULT_STRICT_QUOTES = false;
/**
* Number of lines to skip in CSV
*/
public static final int DEFAULT_SKIP_LINES = 0;
/**
* Allow whitespace?
*/
public static final boolean DEFAULT_NO_WHITESPACE = false;
/**
* Size limit for each column.
*/
public static final long DEFAULT_COLUMN_LIMIT_SIZE = 16777216;
/**
* Used for testing only.
*/
public static boolean testMode = false;
/**
* Configuration options.
*/
public static class CSVConfig extends CLIConfig {
@Option(shortOpt = "f", desc = "location of CSV input file")
String file = "";
@Option(shortOpt = "p", desc = "procedure name to insert the data into the database")
String procedure = "";
@Option(desc = "maximum rows to be read from the CSV file")
int limitrows = Integer.MAX_VALUE;
@Option(shortOpt = "r", desc = "directory path for report files")
String reportdir = System.getProperty("user.dir");
@Option(shortOpt = "m", desc = "maximum errors allowed")
int maxerrors = 100;
@Option(desc = "different ways to handle blank items: {error|null|empty} (default: error)")
String blank = "error";
@Option(desc = "delimiter to use for separating entries")
char separator = DEFAULT_SEPARATOR;
@Option(desc = "character to use for quoted elements (default: \")")
char quotechar = DEFAULT_QUOTE_CHARACTER;
@Option(desc = "character to use for escaping a separator or quote (default: \\)")
char escape = DEFAULT_ESCAPE_CHARACTER;
@Option(desc = "require all input values to be enclosed in quotation marks", hasArg = false)
boolean strictquotes = DEFAULT_STRICT_QUOTES;
@Option(desc = "number of lines to skip before inserting rows into the database")
long skip = DEFAULT_SKIP_LINES;
@Option(desc = "do not allow whitespace between values and separators", hasArg = false)
boolean nowhitespace = DEFAULT_NO_WHITESPACE;
@Option(desc = "max size of a quoted column in bytes(default: 16777216 = 16MB)")
long columnsizelimit = DEFAULT_COLUMN_LIMIT_SIZE;
@Option(shortOpt = "s", desc = "list of servers to connect to (default: localhost)")
String servers = "localhost";
@Option(desc = "username when connecting to the servers")
String user = "";
@Option(desc = "password to use when connecting to servers")
String password = "";
@Option(desc = "port to use when connecting to database (default: 21212)")
int port = Client.VOLTDB_SERVER_PORT;
/**
* Batch size for processing batched operations.
*/
@Option(desc = "Batch Size for processing.")
public int batch = 200;
/**
* Table name to insert CSV data into.
*/
@AdditionalArgs(desc = "insert the data into database by TABLENAME.insert procedure by default")
public String table = "";
// This is set to true when -p option us used.
boolean useSuppliedProcedure = false;
/**
* Validate command line options.
*/
@Override
public void validate() {
if (maxerrors < 0) {
exitWithMessageAndUsage("abortfailurecount must be >=0");
}
if (procedure.equals("") && table.equals("")) {
exitWithMessageAndUsage("procedure name or a table name required");
}
if (!procedure.equals("") && !table.equals("")) {
exitWithMessageAndUsage("Only a procedure name or a table name required, pass only one please");
}
if (skip < 0) {
exitWithMessageAndUsage("skipline must be >= 0");
}
if (port < 0) {
exitWithMessageAndUsage("port number must be >= 0");
}
if (batch < 0) {
exitWithMessageAndUsage("batch size number must be >= 0");
}
if ((blank.equalsIgnoreCase("error")
|| blank.equalsIgnoreCase("null")
|| blank.equalsIgnoreCase("empty")) == false) {
exitWithMessageAndUsage("blank configuration specified must be one of {error|null|empty}");
}
if ((procedure != null) && (procedure.trim().length() > 0)) {
useSuppliedProcedure = true;
}
}
/**
* Usage
*/
@Override
public void printUsage() {
System.out
.println("Usage: csvloader [args] tablename");
System.out
.println(" csvloader [args] -p procedurename");
super.printUsage();
}
}
/**
* csvloader main. (main is directly used by tests as well be sure to reset statics that you need to start over)
*
* @param args
* @throws IOException
* @throws InterruptedException
*
*/
public static void main(String[] args) throws IOException,
InterruptedException {
start = System.currentTimeMillis();
long insertTimeStart = start;
long insertTimeEnd;
final CSVConfig cfg = new CSVConfig();
cfg.parse(CSVLoader.class.getName(), args);
config = cfg;
configuration();
final Tokenizer tokenizer;
ICsvListReader listReader = null;
try {
if (CSVLoader.standin) {
tokenizer = new Tokenizer(new BufferedReader(new InputStreamReader(System.in)), csvPreference,
config.strictquotes, config.escape, config.columnsizelimit,
config.skip);
listReader = new CsvListReader(tokenizer, csvPreference);
} else {
tokenizer = new Tokenizer(new FileReader(config.file), csvPreference,
config.strictquotes, config.escape, config.columnsizelimit,
config.skip);
listReader = new CsvListReader(tokenizer, csvPreference);
}
} catch (FileNotFoundException e) {
m_log.error("CSV file '" + config.file + "' could not be found.");
System.exit(-1);
}
// Split server list
final String[] serverlist = config.servers.split(",");
// Create connection
final ClientConfig c_config = new ClientConfig(config.user, config.password);
c_config.setProcedureCallTimeout(0); // Set procedure all to infinite
Client csvClient = null;
try {
csvClient = CSVLoader.getClient(c_config, serverlist, config.port);
} catch (Exception e) {
m_log.error("Error connecting to the servers: "
+ config.servers);
System.exit(-1);
}
assert (csvClient != null);
try {
if (!CSVPartitionProcessor.initializeProcessorInformation(config, csvClient)) {
System.exit(-1);
}
//Create launch processor threads. If Multipartitioned only 1 processor is launched.
List<Thread> spawned = new ArrayList<Thread>(CSVPartitionProcessor.m_numProcessors);
CSVLineWithMetaData endOfData = new CSVLineWithMetaData(null, null, -1);
Map<Long, BlockingQueue<CSVLineWithMetaData>> lineq =
new HashMap<Long, BlockingQueue<CSVLineWithMetaData>>(CSVPartitionProcessor.m_numProcessors);
List<CSVPartitionProcessor> processors = new ArrayList<CSVPartitionProcessor>(CSVPartitionProcessor.m_numProcessors);
int numBatchesInQueuePerPartition = (1000 / CSVPartitionProcessor.m_numProcessors);
if (numBatchesInQueuePerPartition < 5) {
numBatchesInQueuePerPartition = 5;
}
m_log.debug("Max Number of batches per partition processor: " + numBatchesInQueuePerPartition);
for (long i = 0; i < CSVPartitionProcessor.m_numProcessors; i++) {
//Keep only numBatchesInQueuePerPartition batches worth data in queue.
LinkedBlockingQueue<CSVLineWithMetaData> partitionQueue
= new LinkedBlockingQueue<CSVLineWithMetaData>(config.batch * numBatchesInQueuePerPartition);
lineq.put(i, partitionQueue);
CSVPartitionProcessor processor = new CSVPartitionProcessor(csvClient, i,
CSVPartitionProcessor.m_partitionedColumnIndex, partitionQueue, endOfData);
processors.add(processor);
Thread th = new Thread(processor);
th.setName(processor.m_processorName);
spawned.add(th);
}
CSVFileReader.m_config = config;
CSVFileReader.m_listReader = listReader;
CSVFileReader.m_processorQueues = lineq;
CSVFileReader.m_endOfData = endOfData;
CSVFileReader.m_csvClient = csvClient;
CSVFileReader csvReader = new CSVFileReader();
Thread th = new Thread(csvReader);
th.setName("CSVFileReader");
th.setDaemon(true);
//Start the processor threads.
for (Thread th2 : spawned) {
th2.start();
}
//Wait for reader to finish it count downs the procesors.
th.start();
th.join();
long readerTime = (csvReader.m_parsingTime) / 1000000;
insertTimeEnd = System.currentTimeMillis();
csvClient.drain();
csvClient.close();
long insertCount = 0;
//Sum up all the partition processed count i.e the number of rows we sent to server.
for (CSVPartitionProcessor pp : processors) {
insertCount += pp.m_partitionProcessedCount.get();
}
long ackCount = CSVPartitionProcessor.m_partitionAcknowledgedCount.get();
m_log.debug("Parsing CSV file took " + readerTime + " milliseconds.");
m_log.debug("Inserting Data took " + ((insertTimeEnd - insertTimeStart) - readerTime) + " milliseconds.");
m_log.info("Read " + insertCount + " rows from file and successfully inserted "
+ ackCount + " rows (final)");
produceFiles(ackCount, insertCount);
boolean noerrors = CSVFileReader.m_errorInfo.isEmpty();
close_cleanup();
//In test junit mode we let it continue for reuse
if (!CSVLoader.testMode) {
System.exit(noerrors ? 0 : 1);
}
} catch (Exception ex) {
m_log.error("Exception Happened while loading CSV data: " + ex);
System.exit(1);
}
}
private static void configuration() {
csvPreference = new CsvPreference.Builder(config.quotechar, config.separator, "\n").build();
if (config.file.equals("")) {
standin = true;
}
if (!config.table.equals("")) {
insertProcedure = config.table.toUpperCase() + ".insert";
} else {
insertProcedure = config.procedure;
}
if (!config.reportdir.endsWith("/")) {
config.reportdir += "/";
}
try {
File dir = new File(config.reportdir);
if (!dir.exists()) {
dir.mkdirs();
}
} catch (Exception x) {
m_log.error(x.getMessage(), x);
System.exit(-1);
}
String myinsert = insertProcedure;
myinsert = myinsert.replaceAll("\\.", "_");
pathInvalidrowfile = config.reportdir + "csvloader_" + myinsert + "_"
+ "invalidrows.csv";
pathLogfile = config.reportdir + "csvloader_" + myinsert + "_"
+ "log.log";
pathReportfile = config.reportdir + "csvloader_" + myinsert + "_"
+ "report.log";
try {
out_invaliderowfile = new BufferedWriter(new FileWriter(
pathInvalidrowfile));
out_logfile = new BufferedWriter(new FileWriter(pathLogfile));
out_reportfile = new BufferedWriter(new FileWriter(pathReportfile));
} catch (IOException e) {
m_log.error(e.getMessage());
System.exit(-1);
}
}
/**
* Get connection to servers in cluster.
*
* @param config
* @param servers
* @param port
* @return
* @throws Exception
*/
public static Client getClient(ClientConfig config, String[] servers,
int port) throws Exception {
final Client client = ClientFactory.createClient(config);
for (String server : servers) {
client.createConnection(server.trim(), port);
}
return client;
}
private static void produceFiles(long ackCount, long insertCount) {
Map<Long, String[]> errorInfo = CSVFileReader.m_errorInfo;
latency = System.currentTimeMillis() - start;
m_log.info("Elapsed time: " + latency / 1000F
+ " seconds");
int bulkflush = 300; // by default right now
try {
long linect = 0;
for (Long irow : errorInfo.keySet()) {
String info[] = errorInfo.get(irow);
if (info.length != 2) {
System.out.println("internal error, information is not enough");
}
linect++;
out_invaliderowfile.write(info[0] + "\n");
String message = "Invalid input on line " + irow + ".\n Contents:" + info[0];
m_log.error(message);
out_logfile.write(message + "\n " + info[1] + "\n");
if (linect % bulkflush == 0) {
out_invaliderowfile.flush();
out_logfile.flush();
}
}
// Get elapsed time in seconds
float elapsedTimeSec = latency / 1000F;
out_reportfile.write("CSVLoader elaspsed: " + elapsedTimeSec
+ " seconds\n");
long trueSkip;
//get the actuall number of lines skipped
if (config.skip < CSVFileReader.m_totalLineCount.get()) {
trueSkip = config.skip;
} else {
trueSkip = CSVFileReader.m_totalLineCount.get();
}
out_reportfile.write("Number of input lines skipped: "
+ trueSkip + "\n");
out_reportfile.write("Number of lines read from input: "
+ (CSVFileReader.m_totalLineCount.get() - trueSkip) + "\n");
if (config.limitrows == -1) {
out_reportfile.write("Input stopped after "
+ CSVFileReader.m_totalRowCount.get() + " rows read" + "\n");
}
out_reportfile.write("Number of rows discovered: "
+ CSVFileReader.m_totalLineCount.get() + "\n");
out_reportfile.write("Number of rows successfully inserted: "
+ ackCount + "\n");
// if prompted msg changed, change it also for test case
out_reportfile.write("Number of rows that could not be inserted: "
+ errorInfo.size() + "\n");
out_reportfile.write("CSVLoader rate: " + insertCount
/ elapsedTimeSec + " row/s\n");
m_log.info("Invalid row file: " + pathInvalidrowfile);
m_log.info("Log file: " + pathLogfile);
m_log.info("Report file: " + pathReportfile);
out_invaliderowfile.flush();
out_logfile.flush();
out_reportfile.flush();
} catch (FileNotFoundException e) {
m_log.error("CSV report directory '" + config.reportdir
+ "' does not exist.");
} catch (Exception x) {
m_log.error(x.getMessage());
}
}
private static void close_cleanup() throws IOException,
InterruptedException {
//Reset all this for tests which uses main to load csv data.
CSVFileReader.m_errorInfo.clear();
CSVFileReader.m_errored = false;
CSVPartitionProcessor.m_numProcessors = 1;
CSVPartitionProcessor.m_columnCnt = 0;
CSVFileReader.m_totalLineCount = new AtomicLong(0);
CSVFileReader.m_totalRowCount = new AtomicLong(0);
CSVPartitionProcessor.m_partitionAcknowledgedCount = new AtomicLong(0);
out_invaliderowfile.close();
out_logfile.close();
out_reportfile.close();
}
}
|
ENG-5283 keep 2 statuses for now.
|
src/frontend/org/voltdb/utils/CSVLoader.java
|
ENG-5283 keep 2 statuses for now.
|
|
Java
|
lgpl-2.1
|
0fb4996da1af9837c7a64eb7f7e59cd25ed90271
| 0
|
ggiudetti/opencms-core,gallardo/opencms-core,alkacon/opencms-core,alkacon/opencms-core,gallardo/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,gallardo/opencms-core,alkacon/opencms-core
|
/*
* File : $Source$
* Date : $Date$
* Version: $Revision$
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (C) 2002 - 2009 Alkacon Software (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.search.solr;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.configuration.CmsParameterConfiguration;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.types.CmsResourceTypeXmlContainerPage;
import org.opencms.file.types.CmsResourceTypeXmlContent;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.main.CmsException;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.report.I_CmsReport;
import org.opencms.search.CmsSearchException;
import org.opencms.search.CmsSearchIndex;
import org.opencms.search.CmsSearchIndexSource;
import org.opencms.search.CmsSearchManager;
import org.opencms.search.CmsSearchParameters;
import org.opencms.search.CmsSearchResource;
import org.opencms.search.CmsSearchResultList;
import org.opencms.search.I_CmsIndexWriter;
import org.opencms.search.I_CmsSearchDocument;
import org.opencms.search.documents.I_CmsDocumentFactory;
import org.opencms.search.fields.CmsSearchField;
import org.opencms.search.galleries.CmsGallerySearchParameters;
import org.opencms.search.galleries.CmsGallerySearchResult;
import org.opencms.search.galleries.CmsGallerySearchResultList;
import org.opencms.security.CmsRole;
import org.opencms.security.CmsRoleViolationException;
import org.opencms.util.CmsRequestUtil;
import org.opencms.util.CmsStringUtil;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.servlet.ServletResponse;
import org.apache.commons.logging.Log;
import org.apache.lucene.index.Term;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.HighlightParams;
import org.apache.solr.common.util.ContentStreamBase;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.ReplicationHandler;
import org.apache.solr.handler.component.ResponseBuilder;
import org.apache.solr.handler.component.SearchComponent;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.response.BinaryQueryResponseWriter;
import org.apache.solr.response.QueryResponseWriter;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.search.DocListAndSet;
import org.apache.solr.search.DocSlice;
import org.apache.solr.search.QParser;
import org.apache.solr.util.FastWriter;
/**
* Implements the search within an Solr index.<p>
*
* @since 8.5.0
*/
public class CmsSolrIndex extends CmsSearchIndex {
/** The name of the default Solr Offline index. */
public static final String DEFAULT_INDEX_NAME_OFFLINE = "Solr Offline";
/** The name of the default Solr Online index. */
public static final String DEFAULT_INDEX_NAME_ONLINE = "Solr Online";
/** Constant for additional parameter to set the post processor class name. */
public static final String POST_PROCESSOR = "search.solr.postProcessor";
/** The solr exclude property. */
public static final String PROPERTY_SEARCH_EXCLUDE_VALUE_SOLR = "solr";
/** Indicates the maximum number of documents from the complete result set to return. */
public static final int ROWS_MAX = 50;
/** A constant for debug formatting output. */
protected static final int DEBUG_PADDING_RIGHT = 50;
/** The name for the parameters key of the response header. */
private static final String HEADER_PARAMS_NAME = "params";
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsSolrIndex.class);
/** Pseudo resource used for not permission checked indexes. */
private static final CmsResource PSEUDO_RES = new CmsResource(
null,
null,
null,
0,
false,
0,
null,
null,
0L,
null,
0L,
null,
0L,
0L,
0,
0,
0L,
0);
/** The name of the key that is used for the result documents inside the Solr query response. */
private static final String QUERY_RESPONSE_NAME = "response";
/** The name of the key that is used for the query time. */
private static final String QUERY_TIME_NAME = "QTime";
/** A constant for UTF-8 charset. */
private static final Charset UTF8 = Charset.forName("UTF-8");
/** The embedded Solr client for this index. */
SolrClient m_solr;
/** The post document manipulator. */
private I_CmsSolrPostSearchProcessor m_postProcessor;
/** The core name for the index. */
private String m_coreName;
/**
* Default constructor.<p>
*/
public CmsSolrIndex() {
super();
}
/**
* Public constructor to create a Solr index.<p>
*
* @param name the name for this index.<p>
*
* @throws CmsIllegalArgumentException if something goes wrong
*/
public CmsSolrIndex(String name)
throws CmsIllegalArgumentException {
super(name);
}
/**
* Returns the resource type for the given root path.<p>
*
* @param cms the current CMS context
* @param rootPath the root path of the resource to get the type for
*
* @return the resource type for the given root path
*/
public static final String getType(CmsObject cms, String rootPath) {
String type = null;
CmsSolrIndex index = CmsSearchManager.getIndexSolr(cms, null);
if (index != null) {
I_CmsSearchDocument doc = index.getDocument(CmsSearchField.FIELD_PATH, rootPath);
if (doc != null) {
type = doc.getFieldValueAsString(CmsSearchField.FIELD_TYPE);
}
}
return type;
}
/**
* @see org.opencms.search.CmsSearchIndex#addConfigurationParameter(java.lang.String, java.lang.String)
*/
@Override
public void addConfigurationParameter(String key, String value) {
if (POST_PROCESSOR.equals(key)) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) {
try {
setPostProcessor((I_CmsSolrPostSearchProcessor)Class.forName(value).newInstance());
} catch (Exception e) {
CmsException ex = new CmsException(
Messages.get().container(Messages.LOG_SOLR_ERR_POST_PROCESSOR_NOT_EXIST_1, value),
e);
LOG.error(ex.getMessage(), ex);
}
}
}
super.addConfigurationParameter(key, value);
}
/**
* @see org.opencms.search.CmsSearchIndex#createEmptyDocument(org.opencms.file.CmsResource)
*/
@Override
public I_CmsSearchDocument createEmptyDocument(CmsResource resource) {
CmsSolrDocument doc = new CmsSolrDocument(new SolrInputDocument());
doc.setId(resource.getStructureId());
return doc;
}
/**
* @see org.opencms.search.CmsSearchIndex#createIndexWriter(boolean, org.opencms.report.I_CmsReport)
*/
@Override
public I_CmsIndexWriter createIndexWriter(boolean create, I_CmsReport report) {
return new CmsSolrIndexWriter(m_solr, this);
}
/**
* Performs a search with according to the gallery search parameters.<p>
*
* @param cms the cms context
* @param params the search parameters
*
* @return the search result
*/
public CmsGallerySearchResultList gallerySearch(CmsObject cms, CmsGallerySearchParameters params) {
CmsGallerySearchResultList resultList = new CmsGallerySearchResultList();
try {
CmsSolrResultList list = search(
cms,
params.getQuery(cms),
false,
null,
true,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
if (null == list) {
return null;
}
resultList.setHitCount(Long.valueOf(list.getNumFound()).intValue());
for (CmsSearchResource resource : list) {
I_CmsSearchDocument document = resource.getDocument();
Locale locale = CmsLocaleManager.getLocale(params.getLocale());
CmsGallerySearchResult result = new CmsGallerySearchResult(
document,
cms,
(int)document.getScore(),
locale);
resultList.add(result);
}
} catch (CmsSearchException e) {
LOG.error(e.getMessage(), e);
}
return resultList;
}
/**
* @see org.opencms.search.CmsSearchIndex#getConfiguration()
*/
@Override
public CmsParameterConfiguration getConfiguration() {
CmsParameterConfiguration result = super.getConfiguration();
if (getPostProcessor() != null) {
result.put(POST_PROCESSOR, getPostProcessor().getClass().getName());
}
return result;
}
/**
* Returns the name of the core of the index.
* NOTE: Index and core name differ since OpenCms 10.5 due to new naming rules for cores in SOLR.
*
* @return the name of the core of the index.
*/
public String getCoreName() {
return m_coreName;
}
/**
* @see org.opencms.search.CmsSearchIndex#getDocument(java.lang.String, java.lang.String)
*/
@Override
public synchronized I_CmsSearchDocument getDocument(String fieldname, String term) {
try {
SolrQuery query = new SolrQuery();
if (CmsSearchField.FIELD_PATH.equals(fieldname)) {
query.setQuery(fieldname + ":\"" + term + "\"");
} else {
query.setQuery(fieldname + ":" + term);
}
QueryResponse res = m_solr.query(query);
if (res != null) {
SolrDocumentList sdl = m_solr.query(query).getResults();
if ((sdl.getNumFound() > 0L) && (sdl.get(0) != null)) {
return new CmsSolrDocument(sdl.get(0));
}
}
} catch (Exception e) {
// ignore and assume that the document could not be found
LOG.error(e.getMessage(), e);
}
return null;
}
/**
* @see org.opencms.search.CmsSearchIndex#getDocumentFactory(org.opencms.file.CmsResource)
*/
@Override
public I_CmsDocumentFactory getDocumentFactory(CmsResource res) {
if (isIndexing(res)) {
if (OpenCms.getResourceManager().getResourceType(res) instanceof CmsResourceTypeXmlContainerPage) {
return OpenCms.getSearchManager().getDocumentFactory(
CmsSolrDocumentContainerPage.TYPE_CONTAINERPAGE_SOLR,
"text/html");
}
if (CmsResourceTypeXmlContent.isXmlContent(res)) {
return OpenCms.getSearchManager().getDocumentFactory(
CmsSolrDocumentXmlContent.TYPE_XMLCONTENT_SOLR,
"text/html");
} else {
return super.getDocumentFactory(res);
}
}
return null;
}
/**
* Returns the language locale for the given resource in this index.<p>
*
* @param cms the current OpenCms user context
* @param resource the resource to check
* @param availableLocales a list of locales supported by the resource
*
* @return the language locale for the given resource in this index
*/
@Override
public Locale getLocaleForResource(CmsObject cms, CmsResource resource, List<Locale> availableLocales) {
Locale result = null;
List<Locale> defaultLocales = OpenCms.getLocaleManager().getDefaultLocales(cms, resource);
if ((availableLocales != null) && (availableLocales.size() > 0)) {
result = OpenCms.getLocaleManager().getBestMatchingLocale(
defaultLocales.get(0),
defaultLocales,
availableLocales);
}
if (result == null) {
result = ((availableLocales != null) && availableLocales.isEmpty())
? availableLocales.get(0)
: defaultLocales.get(0);
}
return result;
}
/**
* Returns the search post processor.<p>
*
* @return the post processor to use
*/
public I_CmsSolrPostSearchProcessor getPostProcessor() {
return m_postProcessor;
}
/**
* @see org.opencms.search.CmsSearchIndex#initialize()
*/
@Override
public void initialize() throws CmsSearchException {
super.initialize();
getFieldConfiguration().init();
try {
OpenCms.getSearchManager().registerSolrIndex(this);
} catch (CmsConfigurationException ex) {
LOG.error(ex.getMessage(), ex);
setEnabled(false);
}
}
/** Returns a flag, indicating if the Solr server is not yet set.
* @return a flag, indicating if the Solr server is not yet set.
*/
public boolean isNoSolrServerSet() {
return null == m_solr;
}
/**
* Not yet implemented for Solr.<p>
*
* <code>
* #################<br>
* ### DON'T USE ###<br>
* #################<br>
* </code>
*
* @Deprecated Use {@link #search(CmsObject, SolrQuery)} or {@link #search(CmsObject, String)} instead
*/
@Override
@Deprecated
public synchronized CmsSearchResultList search(CmsObject cms, CmsSearchParameters params) {
throw new UnsupportedOperationException();
}
/**
* Default search method.<p>
*
* @param cms the current CMS object
* @param query the query
*
* @return the results
*
* @throws CmsSearchException if something goes wrong
*
* @see #search(CmsObject, String)
*/
public CmsSolrResultList search(CmsObject cms, CmsSolrQuery query) throws CmsSearchException {
return search(cms, query, false);
}
/**
* Performs a search.<p>
*
* Returns a list of 'OpenCms resource documents'
* ({@link CmsSearchResource}) encapsulated within the class {@link CmsSolrResultList}.
* This list can be accessed exactly like an {@link List} which entries are
* {@link CmsSearchResource} that extend {@link CmsResource} and holds the Solr
* implementation of {@link I_CmsSearchDocument} as member. <b>This enables you to deal
* with the resulting list as you do with well known {@link List} and work on it's entries
* like you do on {@link CmsResource}.</b>
*
* <h4>What will be done with the Solr search result?</h4>
* <ul>
* <li>Although it can happen, that there are less results returned than rows were requested
* (imagine an index containing less documents than requested rows) we try to guarantee
* the requested amount of search results and to provide a working pagination with
* security check.</li>
*
* <li>To be sure we get enough documents left even the permission check reduces the amount
* of found documents, the rows are multiplied by <code>'5'</code> and the current page
* additionally the offset is added. The count of documents we don't have enough
* permissions for grows with increasing page number, that's why we also multiply
* the rows by the current page count.</li>
*
* <li>Also make sure we perform the permission check for all found documents, so start with
* the first found doc.</li>
* </ul>
*
* <b>NOTE:</b> If latter pages than the current one are containing protected documents the
* total hit count will be incorrect, because the permission check ends if we have
* enough results found for the page to display. With other words latter pages than
* the current can contain documents that will first be checked if those pages are
* requested to be displayed, what causes a incorrect hit count.<p>
*
* @param cms the current OpenCms context
* @param ignoreMaxRows <code>true</code> to return all all requested rows, <code>false</code> to use max rows
* @param query the OpenCms Solr query
*
* @return the list of found documents
*
* @throws CmsSearchException if something goes wrong
*
* @see org.opencms.search.solr.CmsSolrResultList
* @see org.opencms.search.CmsSearchResource
* @see org.opencms.search.I_CmsSearchDocument
* @see org.opencms.search.solr.CmsSolrQuery
*/
public CmsSolrResultList search(CmsObject cms, final CmsSolrQuery query, boolean ignoreMaxRows)
throws CmsSearchException {
return search(cms, query, ignoreMaxRows, null, false, null);
}
/**
* Like {@link #search(CmsObject, CmsSolrQuery, boolean)}, but additionally a resource filter can be specified.
* By default, the filter depends on the index.
*
* @param cms the current OpenCms context
* @param ignoreMaxRows <code>true</code> to return all all requested rows, <code>false</code> to use max rows
* @param query the OpenCms Solr query
* @param filter the resource filter to use for post-processing.
*
* @return the list of documents found.
*
* @throws CmsSearchException if something goes wrong
*/
public CmsSolrResultList search(
CmsObject cms,
final CmsSolrQuery query,
boolean ignoreMaxRows,
final CmsResourceFilter filter)
throws CmsSearchException {
return search(cms, query, ignoreMaxRows, null, false, filter);
}
/**
* Performs the actual search.<p>
*
* @param cms the current OpenCms context
* @param ignoreMaxRows <code>true</code> to return all all requested rows, <code>false</code> to use max rows
* @param query the OpenCms Solr query
* @param response the servlet response to write the query result to, may also be <code>null</code>
* @param ignoreSearchExclude if set to false, only contents with search_exclude unset or "false" will be found - typical for the the non-gallery case
* @param filter the resource filter to use
*
* @return the found documents
*
* @throws CmsSearchException if something goes wrong
*
* @see #search(CmsObject, CmsSolrQuery, boolean)
*/
@SuppressWarnings("unchecked")
public CmsSolrResultList search(
CmsObject cms,
final CmsSolrQuery query,
boolean ignoreMaxRows,
ServletResponse response,
boolean ignoreSearchExclude,
CmsResourceFilter filter)
throws CmsSearchException {
// check if the user is allowed to access this index
checkOfflineAccess(cms);
if (!ignoreSearchExclude) {
query.addFilterQuery(CmsSearchField.FIELD_SEARCH_EXCLUDE + ":\"false\"");
}
int previousPriority = Thread.currentThread().getPriority();
long startTime = System.currentTimeMillis();
// remember the initial query
SolrQuery initQuery = query.clone();
query.setHighlight(false);
LocalSolrQueryRequest solrQueryRequest = null;
try {
// initialize the search context
CmsObject searchCms = OpenCms.initCmsObject(cms);
// change thread priority in order to reduce search impact on overall system performance
if (getPriority() > 0) {
Thread.currentThread().setPriority(getPriority());
}
// the lists storing the found documents that will be returned
List<CmsSearchResource> resourceDocumentList = new ArrayList<CmsSearchResource>();
SolrDocumentList solrDocumentList = new SolrDocumentList();
// Initialize rows, offset, end and the current page.
int rows = query.getRows() != null ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();
if (!ignoreMaxRows && (rows > ROWS_MAX)) {
rows = ROWS_MAX;
}
int start = query.getStart() != null ? query.getStart().intValue() : 0;
int end = start + rows;
int page = 0;
if (rows > 0) {
page = Math.round(start / rows) + 1;
}
// set the start to '0' and expand the rows before performing the query
query.setStart(new Integer(0));
query.setRows(new Integer((5 * rows * page) + start));
// perform the Solr query and remember the original Solr response
QueryResponse queryResponse = m_solr.query(query);
long solrTime = System.currentTimeMillis() - startTime;
// initialize the counts
long hitCount = queryResponse.getResults().getNumFound();
start = -1;
end = -1;
if ((rows > 0) && (page > 0) && (hitCount > 0)) {
// calculate the final size of the search result
start = rows * (page - 1);
end = start + rows;
// ensure that both i and n are inside the range of foundDocuments.size()
start = new Long((start > hitCount) ? hitCount : start).intValue();
end = new Long((end > hitCount) ? hitCount : end).intValue();
} else {
// return all found documents in the search result
start = 0;
end = new Long(hitCount).intValue();
}
long visibleHitCount = hitCount;
float maxScore = 0;
// If we're using a postprocessor, (re-)initialize it before using it
if (m_postProcessor != null) {
m_postProcessor.init();
}
// process found documents
List<CmsSearchResource> allDocs = new ArrayList<CmsSearchResource>();
int cnt = 0;
for (int i = 0; (i < queryResponse.getResults().size()) && (cnt < end); i++) {
try {
SolrDocument doc = queryResponse.getResults().get(i);
CmsSolrDocument searchDoc = new CmsSolrDocument(doc);
if (needsPermissionCheck(searchDoc)) {
// only if the document is an OpenCms internal resource perform the permission check
CmsResource resource = filter == null
? getResource(searchCms, searchDoc)
: getResource(searchCms, searchDoc, filter);
if (resource != null) {
// permission check performed successfully: the user has read permissions!
if (cnt >= start) {
if (m_postProcessor != null) {
doc = m_postProcessor.process(
searchCms,
resource,
(SolrInputDocument)searchDoc.getDocument());
}
resourceDocumentList.add(new CmsSearchResource(resource, searchDoc));
if (null != doc) {
solrDocumentList.add(doc);
}
maxScore = maxScore < searchDoc.getScore() ? searchDoc.getScore() : maxScore;
}
allDocs.add(new CmsSearchResource(resource, searchDoc));
cnt++;
} else {
visibleHitCount--;
}
} else {
// if permission check is not required for this index,
// add a pseudo resource together with document to the results
resourceDocumentList.add(new CmsSearchResource(PSEUDO_RES, searchDoc));
solrDocumentList.add(doc);
maxScore = maxScore < searchDoc.getScore() ? searchDoc.getScore() : maxScore;
cnt++;
}
} catch (Exception e) {
// should not happen, but if it does we want to go on with the next result nevertheless
LOG.warn(Messages.get().getBundle().key(Messages.LOG_SOLR_ERR_RESULT_ITERATION_FAILED_0), e);
}
}
// the last documents were all secret so let's take the last found docs
if (resourceDocumentList.isEmpty() && (allDocs.size() > 0)) {
page = Math.round(allDocs.size() / rows) + 1;
int showCount = allDocs.size() % rows;
showCount = showCount == 0 ? rows : showCount;
start = allDocs.size() - new Long(showCount).intValue();
end = allDocs.size();
if (allDocs.size() > start) {
resourceDocumentList = allDocs.subList(start, end);
for (CmsSearchResource r : resourceDocumentList) {
maxScore = maxScore < r.getDocument().getScore() ? r.getDocument().getScore() : maxScore;
solrDocumentList.add(((CmsSolrDocument)r.getDocument()).getSolrDocument());
}
}
}
long processTime = System.currentTimeMillis() - startTime - solrTime;
// create and return the result
solrDocumentList.setStart(start);
solrDocumentList.setMaxScore(new Float(maxScore));
solrDocumentList.setNumFound(visibleHitCount);
queryResponse.getResponse().setVal(
queryResponse.getResponse().indexOf(QUERY_RESPONSE_NAME, 0),
solrDocumentList);
queryResponse.getResponseHeader().setVal(
queryResponse.getResponseHeader().indexOf(QUERY_TIME_NAME, 0),
new Integer(new Long(System.currentTimeMillis() - startTime).intValue()));
long highlightEndTime = System.currentTimeMillis();
SolrCore core = m_solr instanceof EmbeddedSolrServer
? ((EmbeddedSolrServer)m_solr).getCoreContainer().getCore(getCoreName())
: null;
CmsSolrResultList result = null;
try {
SearchComponent highlightComponenet = null;
if (core != null) {
highlightComponenet = core.getSearchComponent("highlight");
solrQueryRequest = new LocalSolrQueryRequest(core, queryResponse.getResponseHeader());
}
SolrQueryResponse solrQueryResponse = null;
if (solrQueryRequest != null) {
// create and initialize the solr response
solrQueryResponse = new SolrQueryResponse();
solrQueryResponse.setAllValues(queryResponse.getResponse());
int paramsIndex = queryResponse.getResponseHeader().indexOf(HEADER_PARAMS_NAME, 0);
NamedList<Object> header = null;
Object o = queryResponse.getResponseHeader().getVal(paramsIndex);
if (o instanceof NamedList) {
header = (NamedList<Object>)o;
header.setVal(header.indexOf(CommonParams.ROWS, 0), new Integer(rows));
header.setVal(header.indexOf(CommonParams.START, 0), new Long(start));
}
// set the OpenCms Solr query as parameters to the request
solrQueryRequest.setParams(initQuery);
// perform the highlighting
if ((header != null) && (initQuery.getHighlight()) && (highlightComponenet != null)) {
header.add(HighlightParams.HIGHLIGHT, "on");
if ((initQuery.getHighlightFields() != null) && (initQuery.getHighlightFields().length > 0)) {
header.add(
HighlightParams.FIELDS,
CmsStringUtil.arrayAsString(initQuery.getHighlightFields(), ","));
}
String formatter = initQuery.getParams(HighlightParams.FORMATTER) != null
? initQuery.getParams(HighlightParams.FORMATTER)[0]
: null;
if (formatter != null) {
header.add(HighlightParams.FORMATTER, formatter);
}
if (initQuery.getHighlightFragsize() != 100) {
header.add(HighlightParams.FRAGSIZE, new Integer(initQuery.getHighlightFragsize()));
}
if (initQuery.getHighlightRequireFieldMatch()) {
header.add(
HighlightParams.FIELD_MATCH,
new Boolean(initQuery.getHighlightRequireFieldMatch()));
}
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(initQuery.getHighlightSimplePost())) {
header.add(HighlightParams.SIMPLE_POST, initQuery.getHighlightSimplePost());
}
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(initQuery.getHighlightSimplePre())) {
header.add(HighlightParams.SIMPLE_PRE, initQuery.getHighlightSimplePre());
}
if (initQuery.getHighlightSnippets() != 1) {
header.add(HighlightParams.SNIPPETS, new Integer(initQuery.getHighlightSnippets()));
}
ResponseBuilder rb = new ResponseBuilder(
solrQueryRequest,
solrQueryResponse,
Collections.singletonList(highlightComponenet));
try {
rb.doHighlights = true;
DocListAndSet res = new DocListAndSet();
SchemaField idField = OpenCms.getSearchManager().getSolrServerConfiguration().getSolrSchema().getUniqueKeyField();
int[] luceneIds = new int[rows];
int docs = 0;
for (SolrDocument doc : solrDocumentList) {
String idString = (String)doc.getFirstValue(CmsSearchField.FIELD_ID);
int id = solrQueryRequest.getSearcher().getFirstMatch(
new Term(idField.getName(), idField.getType().toInternal(idString)));
luceneIds[docs++] = id;
}
res.docList = new DocSlice(0, docs, luceneIds, null, docs, 0);
rb.setResults(res);
rb.setQuery(QParser.getParser(initQuery.getQuery(), null, solrQueryRequest).getQuery());
rb.setQueryString(initQuery.getQuery());
highlightComponenet.prepare(rb);
highlightComponenet.process(rb);
highlightComponenet.finishStage(rb);
} catch (Exception e) {
LOG.error(e.getMessage() + " in query: " + initQuery, new Exception(e));
}
// Make highlighting also available via the CmsSolrResultList
queryResponse.setResponse(solrQueryResponse.getValues());
highlightEndTime = System.currentTimeMillis();
}
}
result = new CmsSolrResultList(
initQuery,
queryResponse,
solrDocumentList,
resourceDocumentList,
start,
new Integer(rows),
end,
page,
visibleHitCount,
new Float(maxScore),
startTime,
highlightEndTime);
if (LOG.isDebugEnabled()) {
Object[] logParams = new Object[] {
new Long(System.currentTimeMillis() - startTime),
new Long(result.getNumFound()),
new Long(solrTime),
new Long(processTime),
new Long(result.getHighlightEndTime() != 0 ? result.getHighlightEndTime() - startTime : 0)};
LOG.debug(
query.toString()
+ "\n"
+ Messages.get().getBundle().key(Messages.LOG_SOLR_SEARCH_EXECUTED_5, logParams));
}
if (response != null) {
writeResp(response, solrQueryRequest, solrQueryResponse);
}
} finally {
if (solrQueryRequest != null) {
solrQueryRequest.close();
}
if (core != null) {
core.close();
}
}
return result;
} catch (Exception e) {
throw new CmsSearchException(
Messages.get().container(
Messages.LOG_SOLR_ERR_SEARCH_EXECUTION_FAILD_1,
CmsEncoder.decode(query.toString()),
e),
e);
} finally {
if (solrQueryRequest != null) {
solrQueryRequest.close();
}
// re-set thread to previous priority
Thread.currentThread().setPriority(previousPriority);
}
}
/**
* Default search method.<p>
*
* @param cms the current CMS object
* @param query the query
*
* @return the results
*
* @throws CmsSearchException if something goes wrong
*
* @see #search(CmsObject, String)
*/
public CmsSolrResultList search(CmsObject cms, SolrQuery query) throws CmsSearchException {
return search(cms, CmsEncoder.decode(query.toString()));
}
/**
* Performs a search.<p>
*
* @param cms the cms object
* @param solrQuery the Solr query
*
* @return a list of documents
*
* @throws CmsSearchException if something goes wrong
*
* @see #search(CmsObject, CmsSolrQuery, boolean)
*/
public CmsSolrResultList search(CmsObject cms, String solrQuery) throws CmsSearchException {
return search(cms, new CmsSolrQuery(null, CmsRequestUtil.createParameterMap(solrQuery)), false);
}
/**
* Writes the response into the writer.<p>
*
* NOTE: Currently not available for HTTP server.<p>
*
* @param response the servlet response
* @param cms the CMS object to use for search
* @param query the Solr query
* @param ignoreMaxRows if to return unlimited results
*
* @throws Exception if there is no embedded server
*/
public void select(ServletResponse response, CmsObject cms, CmsSolrQuery query, boolean ignoreMaxRows)
throws Exception {
boolean isOnline = cms.getRequestContext().getCurrentProject().isOnlineProject();
CmsResourceFilter filter = isOnline ? null : CmsResourceFilter.IGNORE_EXPIRATION;
search(cms, query, ignoreMaxRows, response, false, filter);
}
/**
* Sets the logical key/name of this search index.<p>
*
* @param name the logical key/name of this search index
*
* @throws CmsIllegalArgumentException if the given name is null, empty or already taken by another search index
*/
@Override
public void setName(String name) throws CmsIllegalArgumentException {
super.setName(name);
updateCoreName();
}
/**
* Sets the search post processor.<p>
*
* @param postProcessor the search post processor to set
*/
public void setPostProcessor(I_CmsSolrPostSearchProcessor postProcessor) {
m_postProcessor = postProcessor;
}
/**
* Sets the Solr server used by this index.<p>
*
* @param client the server to set
*/
public void setSolrServer(SolrClient client) {
m_solr = client;
}
/**
* Executes a spell checking Solr query and returns the Solr query response.<p>
*
* @param res the servlet response
* @param cms the CMS object
* @param q the query
*
* @throws CmsSearchException if something goes wrong
*/
public void spellCheck(ServletResponse res, CmsObject cms, CmsSolrQuery q) throws CmsSearchException {
SolrCore core = null;
LocalSolrQueryRequest solrQueryRequest = null;
try {
q.setRequestHandler("/spell");
QueryResponse queryResponse = m_solr.query(q);
List<CmsSearchResource> resourceDocumentList = new ArrayList<CmsSearchResource>();
SolrDocumentList solrDocumentList = new SolrDocumentList();
if (m_postProcessor != null) {
for (int i = 0; (i < queryResponse.getResults().size()); i++) {
try {
SolrDocument doc = queryResponse.getResults().get(i);
CmsSolrDocument searchDoc = new CmsSolrDocument(doc);
if (needsPermissionCheck(searchDoc)) {
// only if the document is an OpenCms internal resource perform the permission check
CmsResource resource = getResource(cms, searchDoc);
if (resource != null) {
// permission check performed successfully: the user has read permissions!
if (m_postProcessor != null) {
doc = m_postProcessor.process(
cms,
resource,
(SolrInputDocument)searchDoc.getDocument());
}
resourceDocumentList.add(new CmsSearchResource(resource, searchDoc));
solrDocumentList.add(doc);
}
}
} catch (Exception e) {
// should not happen, but if it does we want to go on with the next result nevertheless
LOG.warn(Messages.get().getBundle().key(Messages.LOG_SOLR_ERR_RESULT_ITERATION_FAILED_0), e);
}
}
queryResponse.getResponse().setVal(
queryResponse.getResponse().indexOf(QUERY_RESPONSE_NAME, 0),
solrDocumentList);
}
// create and return the result
core = m_solr instanceof EmbeddedSolrServer
? ((EmbeddedSolrServer)m_solr).getCoreContainer().getCore(getCoreName())
: null;
SolrQueryResponse solrQueryResponse = new SolrQueryResponse();
solrQueryResponse.setAllValues(queryResponse.getResponse());
// create and initialize the solr request
solrQueryRequest = new LocalSolrQueryRequest(core, solrQueryResponse.getResponseHeader());
// set the OpenCms Solr query as parameters to the request
solrQueryRequest.setParams(q);
writeResp(res, solrQueryRequest, solrQueryResponse);
} catch (Exception e) {
throw new CmsSearchException(
Messages.get().container(Messages.LOG_SOLR_ERR_SEARCH_EXECUTION_FAILD_1, q),
e);
} finally {
if (solrQueryRequest != null) {
solrQueryRequest.close();
}
if (core != null) {
core.close();
}
}
}
/**
* @see org.opencms.search.CmsSearchIndex#createIndexBackup()
*/
@Override
protected String createIndexBackup() {
if (!isBackupReindexing()) {
// if no backup is generated we don't need to do anything
return null;
}
if (m_solr instanceof EmbeddedSolrServer) {
EmbeddedSolrServer ser = (EmbeddedSolrServer)m_solr;
CoreContainer con = ser.getCoreContainer();
SolrCore core = con.getCore(getCoreName());
if (core != null) {
try {
SolrRequestHandler h = core.getRequestHandler("/replication");
if (h instanceof ReplicationHandler) {
h.handleRequest(
new LocalSolrQueryRequest(core, CmsRequestUtil.createParameterMap("?command=backup")),
new SolrQueryResponse());
}
} finally {
core.close();
}
}
}
return null;
}
/**
* @see org.opencms.search.CmsSearchIndex#excludeFromIndex(CmsObject, CmsResource)
*/
@Override
protected boolean excludeFromIndex(CmsObject cms, CmsResource resource) {
if (resource.isFolder() || resource.isTemporaryFile()) {
// don't index folders or temporary files for galleries, but pretty much everything else
return true;
}
return false;
}
/**
* @see org.opencms.search.CmsSearchIndex#indexSearcherClose()
*/
@SuppressWarnings("sync-override")
@Override
protected void indexSearcherClose() {
// nothing to do here
}
/**
* @see org.opencms.search.CmsSearchIndex#indexSearcherOpen(java.lang.String)
*/
@SuppressWarnings("sync-override")
@Override
protected void indexSearcherOpen(final String path) {
// nothing to do here
}
/**
* @see org.opencms.search.CmsSearchIndex#indexSearcherUpdate()
*/
@SuppressWarnings("sync-override")
@Override
protected void indexSearcherUpdate() {
// nothing to do here
}
/**
* Checks if the given resource should be indexed by this index or not.<p>
*
* @param res the resource candidate
*
* @return <code>true</code> if the given resource should be indexed or <code>false</code> if not
*/
protected boolean isIndexing(CmsResource res) {
if ((res != null) && (getSources() != null)) {
I_CmsDocumentFactory result = OpenCms.getSearchManager().getDocumentFactory(res);
for (CmsSearchIndexSource source : getSources()) {
if (source.isIndexing(res.getRootPath(), CmsSolrDocumentContainerPage.TYPE_CONTAINERPAGE_SOLR)
|| source.isIndexing(res.getRootPath(), CmsSolrDocumentXmlContent.TYPE_XMLCONTENT_SOLR)
|| source.isIndexing(res.getRootPath(), result.getName())) {
return true;
}
}
}
return false;
}
/**
* Checks if the current user is allowed to access non-online indexes.<p>
*
* To access non-online indexes the current user must be a workplace user at least.<p>
*
* @param cms the CMS object initialized with the current request context / user
*
* @throws CmsSearchException thrown if the access is not permitted
*/
private void checkOfflineAccess(CmsObject cms) throws CmsSearchException {
// If an offline index is being selected, check permissions
if (!CmsProject.ONLINE_PROJECT_NAME.equals(getProject())) {
// only if the user has the role Workplace user, he is allowed to access the Offline index
try {
OpenCms.getRoleManager().checkRole(cms, CmsRole.ELEMENT_AUTHOR);
} catch (CmsRoleViolationException e) {
throw new CmsSearchException(
Messages.get().container(
Messages.LOG_SOLR_ERR_SEARCH_PERMISSION_VIOLATION_2,
getName(),
cms.getRequestContext().getCurrentUser()),
e);
}
}
}
/**
* Generates a valid core name from the provided name (the index name).
* @param name the index name.
* @return the core name
*/
private String generateCoreName(final String name) {
if (name != null) {
//TODO: Add more name manipulations to guarantee a valid core name
return name.replace(" ", "-");
}
return null;
}
/**
* Updates the core name to be in sync with the index name.
*/
private void updateCoreName() {
m_coreName = generateCoreName(getName());
}
/**
* Writes the Solr response.<p>
*
* @param response the servlet response
* @param queryRequest the Solr request
* @param queryResponse the Solr response to write
*
* @throws IOException if sth. goes wrong
* @throws UnsupportedEncodingException if sth. goes wrong
*/
private void writeResp(ServletResponse response, SolrQueryRequest queryRequest, SolrQueryResponse queryResponse)
throws IOException, UnsupportedEncodingException {
if (m_solr instanceof EmbeddedSolrServer) {
SolrCore core = ((EmbeddedSolrServer)m_solr).getCoreContainer().getCore(getCoreName());
Writer out = null;
try {
QueryResponseWriter responseWriter = core.getQueryResponseWriter(queryRequest);
final String ct = responseWriter.getContentType(queryRequest, queryResponse);
if (null != ct) {
response.setContentType(ct);
}
if (responseWriter instanceof BinaryQueryResponseWriter) {
BinaryQueryResponseWriter binWriter = (BinaryQueryResponseWriter)responseWriter;
binWriter.write(response.getOutputStream(), queryRequest, queryResponse);
} else {
String charset = ContentStreamBase.getCharsetFromContentType(ct);
out = ((charset == null) || charset.equalsIgnoreCase(UTF8.toString()))
? new OutputStreamWriter(response.getOutputStream(), UTF8)
: new OutputStreamWriter(response.getOutputStream(), charset);
out = new FastWriter(out);
responseWriter.write(out, queryRequest, queryResponse);
out.flush();
}
} finally {
core.close();
if (out != null) {
out.close();
}
}
} else {
throw new UnsupportedOperationException();
}
}
}
|
src/org/opencms/search/solr/CmsSolrIndex.java
|
/*
* File : $Source$
* Date : $Date$
* Version: $Revision$
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (C) 2002 - 2009 Alkacon Software (http://www.alkacon.com)
*
* 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.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.search.solr;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.configuration.CmsParameterConfiguration;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.file.types.CmsResourceTypeXmlContainerPage;
import org.opencms.file.types.CmsResourceTypeXmlContent;
import org.opencms.i18n.CmsEncoder;
import org.opencms.i18n.CmsLocaleManager;
import org.opencms.main.CmsException;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.report.I_CmsReport;
import org.opencms.search.CmsSearchException;
import org.opencms.search.CmsSearchIndex;
import org.opencms.search.CmsSearchIndexSource;
import org.opencms.search.CmsSearchManager;
import org.opencms.search.CmsSearchParameters;
import org.opencms.search.CmsSearchResource;
import org.opencms.search.CmsSearchResultList;
import org.opencms.search.I_CmsIndexWriter;
import org.opencms.search.I_CmsSearchDocument;
import org.opencms.search.documents.I_CmsDocumentFactory;
import org.opencms.search.fields.CmsSearchField;
import org.opencms.search.galleries.CmsGallerySearchParameters;
import org.opencms.search.galleries.CmsGallerySearchResult;
import org.opencms.search.galleries.CmsGallerySearchResultList;
import org.opencms.security.CmsRole;
import org.opencms.security.CmsRoleViolationException;
import org.opencms.util.CmsRequestUtil;
import org.opencms.util.CmsStringUtil;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.servlet.ServletResponse;
import org.apache.commons.logging.Log;
import org.apache.lucene.index.Term;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.HighlightParams;
import org.apache.solr.common.util.ContentStreamBase;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.ReplicationHandler;
import org.apache.solr.handler.component.ResponseBuilder;
import org.apache.solr.handler.component.SearchComponent;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.response.BinaryQueryResponseWriter;
import org.apache.solr.response.QueryResponseWriter;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.search.DocListAndSet;
import org.apache.solr.search.DocSlice;
import org.apache.solr.search.QParser;
import org.apache.solr.util.FastWriter;
/**
* Implements the search within an Solr index.<p>
*
* @since 8.5.0
*/
public class CmsSolrIndex extends CmsSearchIndex {
/** The name of the default Solr Offline index. */
public static final String DEFAULT_INDEX_NAME_OFFLINE = "Solr Offline";
/** The name of the default Solr Online index. */
public static final String DEFAULT_INDEX_NAME_ONLINE = "Solr Online";
/** Constant for additional parameter to set the post processor class name. */
public static final String POST_PROCESSOR = "search.solr.postProcessor";
/** The solr exclude property. */
public static final String PROPERTY_SEARCH_EXCLUDE_VALUE_SOLR = "solr";
/** Indicates the maximum number of documents from the complete result set to return. */
public static final int ROWS_MAX = 50;
/** A constant for debug formatting output. */
protected static final int DEBUG_PADDING_RIGHT = 50;
/** The name for the parameters key of the response header. */
private static final String HEADER_PARAMS_NAME = "params";
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsSolrIndex.class);
/** Pseudo resource used for not permission checked indexes. */
private static final CmsResource PSEUDO_RES = new CmsResource(
null,
null,
null,
0,
false,
0,
null,
null,
0L,
null,
0L,
null,
0L,
0L,
0,
0,
0L,
0);
/** The name of the key that is used for the result documents inside the Solr query response. */
private static final String QUERY_RESPONSE_NAME = "response";
/** The name of the key that is used for the query time. */
private static final String QUERY_TIME_NAME = "QTime";
/** A constant for UTF-8 charset. */
private static final Charset UTF8 = Charset.forName("UTF-8");
/** The embedded Solr client for this index. */
SolrClient m_solr;
/** The post document manipulator. */
private I_CmsSolrPostSearchProcessor m_postProcessor;
/** The core name for the index. */
private String m_coreName;
/**
* Default constructor.<p>
*/
public CmsSolrIndex() {
super();
}
/**
* Public constructor to create a Solr index.<p>
*
* @param name the name for this index.<p>
*
* @throws CmsIllegalArgumentException if something goes wrong
*/
public CmsSolrIndex(String name)
throws CmsIllegalArgumentException {
super(name);
}
/**
* Returns the resource type for the given root path.<p>
*
* @param cms the current CMS context
* @param rootPath the root path of the resource to get the type for
*
* @return the resource type for the given root path
*/
public static final String getType(CmsObject cms, String rootPath) {
String type = null;
CmsSolrIndex index = CmsSearchManager.getIndexSolr(cms, null);
if (index != null) {
I_CmsSearchDocument doc = index.getDocument(CmsSearchField.FIELD_PATH, rootPath);
if (doc != null) {
type = doc.getFieldValueAsString(CmsSearchField.FIELD_TYPE);
}
}
return type;
}
/**
* @see org.opencms.search.CmsSearchIndex#addConfigurationParameter(java.lang.String, java.lang.String)
*/
@Override
public void addConfigurationParameter(String key, String value) {
if (POST_PROCESSOR.equals(key)) {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(value)) {
try {
setPostProcessor((I_CmsSolrPostSearchProcessor)Class.forName(value).newInstance());
} catch (Exception e) {
CmsException ex = new CmsException(
Messages.get().container(Messages.LOG_SOLR_ERR_POST_PROCESSOR_NOT_EXIST_1, value),
e);
LOG.error(ex.getMessage(), ex);
}
}
}
super.addConfigurationParameter(key, value);
}
/**
* @see org.opencms.search.CmsSearchIndex#createEmptyDocument(org.opencms.file.CmsResource)
*/
@Override
public I_CmsSearchDocument createEmptyDocument(CmsResource resource) {
CmsSolrDocument doc = new CmsSolrDocument(new SolrInputDocument());
doc.setId(resource.getStructureId());
return doc;
}
/**
* @see org.opencms.search.CmsSearchIndex#createIndexWriter(boolean, org.opencms.report.I_CmsReport)
*/
@Override
public I_CmsIndexWriter createIndexWriter(boolean create, I_CmsReport report) {
return new CmsSolrIndexWriter(m_solr, this);
}
/**
* Performs a search with according to the gallery search parameters.<p>
*
* @param cms the cms context
* @param params the search parameters
*
* @return the search result
*/
public CmsGallerySearchResultList gallerySearch(CmsObject cms, CmsGallerySearchParameters params) {
CmsGallerySearchResultList resultList = new CmsGallerySearchResultList();
try {
CmsSolrResultList list = search(
cms,
params.getQuery(cms),
false,
null,
true,
CmsResourceFilter.ONLY_VISIBLE_NO_DELETED);
if (null == list) {
return null;
}
resultList.setHitCount(Long.valueOf(list.getNumFound()).intValue());
for (CmsSearchResource resource : list) {
I_CmsSearchDocument document = resource.getDocument();
Locale locale = CmsLocaleManager.getLocale(params.getLocale());
CmsGallerySearchResult result = new CmsGallerySearchResult(
document,
cms,
(int)document.getScore(),
locale);
resultList.add(result);
}
} catch (CmsSearchException e) {
e.printStackTrace();
}
return resultList;
}
/**
* @see org.opencms.search.CmsSearchIndex#getConfiguration()
*/
@Override
public CmsParameterConfiguration getConfiguration() {
CmsParameterConfiguration result = super.getConfiguration();
if (getPostProcessor() != null) {
result.put(POST_PROCESSOR, getPostProcessor().getClass().getName());
}
return result;
}
/**
* Returns the name of the core of the index.
* NOTE: Index and core name differ since OpenCms 10.5 due to new naming rules for cores in SOLR.
*
* @return the name of the core of the index.
*/
public String getCoreName() {
return m_coreName;
}
/**
* @see org.opencms.search.CmsSearchIndex#getDocument(java.lang.String, java.lang.String)
*/
@Override
public synchronized I_CmsSearchDocument getDocument(String fieldname, String term) {
try {
SolrQuery query = new SolrQuery();
if (CmsSearchField.FIELD_PATH.equals(fieldname)) {
query.setQuery(fieldname + ":\"" + term + "\"");
} else {
query.setQuery(fieldname + ":" + term);
}
QueryResponse res = m_solr.query(query);
if (res != null) {
SolrDocumentList sdl = m_solr.query(query).getResults();
if ((sdl.getNumFound() > 0L) && (sdl.get(0) != null)) {
return new CmsSolrDocument(sdl.get(0));
}
}
} catch (Exception e) {
// ignore and assume that the document could not be found
LOG.error(e.getMessage(), e);
}
return null;
}
/**
* @see org.opencms.search.CmsSearchIndex#getDocumentFactory(org.opencms.file.CmsResource)
*/
@Override
public I_CmsDocumentFactory getDocumentFactory(CmsResource res) {
if (isIndexing(res)) {
if (OpenCms.getResourceManager().getResourceType(res) instanceof CmsResourceTypeXmlContainerPage) {
return OpenCms.getSearchManager().getDocumentFactory(
CmsSolrDocumentContainerPage.TYPE_CONTAINERPAGE_SOLR,
"text/html");
}
if (CmsResourceTypeXmlContent.isXmlContent(res)) {
return OpenCms.getSearchManager().getDocumentFactory(
CmsSolrDocumentXmlContent.TYPE_XMLCONTENT_SOLR,
"text/html");
} else {
return super.getDocumentFactory(res);
}
}
return null;
}
/**
* Returns the language locale for the given resource in this index.<p>
*
* @param cms the current OpenCms user context
* @param resource the resource to check
* @param availableLocales a list of locales supported by the resource
*
* @return the language locale for the given resource in this index
*/
@Override
public Locale getLocaleForResource(CmsObject cms, CmsResource resource, List<Locale> availableLocales) {
Locale result = null;
List<Locale> defaultLocales = OpenCms.getLocaleManager().getDefaultLocales(cms, resource);
if ((availableLocales != null) && (availableLocales.size() > 0)) {
result = OpenCms.getLocaleManager().getBestMatchingLocale(
defaultLocales.get(0),
defaultLocales,
availableLocales);
}
if (result == null) {
result = ((availableLocales != null) && availableLocales.isEmpty())
? availableLocales.get(0)
: defaultLocales.get(0);
}
return result;
}
/**
* Returns the search post processor.<p>
*
* @return the post processor to use
*/
public I_CmsSolrPostSearchProcessor getPostProcessor() {
return m_postProcessor;
}
/**
* @see org.opencms.search.CmsSearchIndex#initialize()
*/
@Override
public void initialize() throws CmsSearchException {
super.initialize();
getFieldConfiguration().init();
try {
OpenCms.getSearchManager().registerSolrIndex(this);
} catch (CmsConfigurationException ex) {
LOG.error(ex.getMessage(), ex);
setEnabled(false);
}
}
/** Returns a flag, indicating if the Solr server is not yet set.
* @return a flag, indicating if the Solr server is not yet set.
*/
public boolean isNoSolrServerSet() {
return null == m_solr;
}
/**
* Not yet implemented for Solr.<p>
*
* <code>
* #################<br>
* ### DON'T USE ###<br>
* #################<br>
* </code>
*
* @Deprecated Use {@link #search(CmsObject, SolrQuery)} or {@link #search(CmsObject, String)} instead
*/
@Override
@Deprecated
public synchronized CmsSearchResultList search(CmsObject cms, CmsSearchParameters params) {
throw new UnsupportedOperationException();
}
/**
* Default search method.<p>
*
* @param cms the current CMS object
* @param query the query
*
* @return the results
*
* @throws CmsSearchException if something goes wrong
*
* @see #search(CmsObject, String)
*/
public CmsSolrResultList search(CmsObject cms, CmsSolrQuery query) throws CmsSearchException {
return search(cms, query, false);
}
/**
* Performs a search.<p>
*
* Returns a list of 'OpenCms resource documents'
* ({@link CmsSearchResource}) encapsulated within the class {@link CmsSolrResultList}.
* This list can be accessed exactly like an {@link List} which entries are
* {@link CmsSearchResource} that extend {@link CmsResource} and holds the Solr
* implementation of {@link I_CmsSearchDocument} as member. <b>This enables you to deal
* with the resulting list as you do with well known {@link List} and work on it's entries
* like you do on {@link CmsResource}.</b>
*
* <h4>What will be done with the Solr search result?</h4>
* <ul>
* <li>Although it can happen, that there are less results returned than rows were requested
* (imagine an index containing less documents than requested rows) we try to guarantee
* the requested amount of search results and to provide a working pagination with
* security check.</li>
*
* <li>To be sure we get enough documents left even the permission check reduces the amount
* of found documents, the rows are multiplied by <code>'5'</code> and the current page
* additionally the offset is added. The count of documents we don't have enough
* permissions for grows with increasing page number, that's why we also multiply
* the rows by the current page count.</li>
*
* <li>Also make sure we perform the permission check for all found documents, so start with
* the first found doc.</li>
* </ul>
*
* <b>NOTE:</b> If latter pages than the current one are containing protected documents the
* total hit count will be incorrect, because the permission check ends if we have
* enough results found for the page to display. With other words latter pages than
* the current can contain documents that will first be checked if those pages are
* requested to be displayed, what causes a incorrect hit count.<p>
*
* @param cms the current OpenCms context
* @param ignoreMaxRows <code>true</code> to return all all requested rows, <code>false</code> to use max rows
* @param query the OpenCms Solr query
*
* @return the list of found documents
*
* @throws CmsSearchException if something goes wrong
*
* @see org.opencms.search.solr.CmsSolrResultList
* @see org.opencms.search.CmsSearchResource
* @see org.opencms.search.I_CmsSearchDocument
* @see org.opencms.search.solr.CmsSolrQuery
*/
public CmsSolrResultList search(CmsObject cms, final CmsSolrQuery query, boolean ignoreMaxRows)
throws CmsSearchException {
return search(cms, query, ignoreMaxRows, null, false, null);
}
/**
* Like {@link #search(CmsObject, CmsSolrQuery, boolean)}, but additionally a resource filter can be specified.
* By default, the filter depends on the index.
*
* @param cms the current OpenCms context
* @param ignoreMaxRows <code>true</code> to return all all requested rows, <code>false</code> to use max rows
* @param query the OpenCms Solr query
* @param filter the resource filter to use for post-processing.
*
* @return the list of documents found.
*
* @throws CmsSearchException if something goes wrong
*/
public CmsSolrResultList search(
CmsObject cms,
final CmsSolrQuery query,
boolean ignoreMaxRows,
final CmsResourceFilter filter)
throws CmsSearchException {
return search(cms, query, ignoreMaxRows, null, false, filter);
}
/**
* Performs the actual search.<p>
*
* @param cms the current OpenCms context
* @param ignoreMaxRows <code>true</code> to return all all requested rows, <code>false</code> to use max rows
* @param query the OpenCms Solr query
* @param response the servlet response to write the query result to, may also be <code>null</code>
* @param ignoreSearchExclude if set to false, only contents with search_exclude unset or "false" will be found - typical for the the non-gallery case
* @param filter the resource filter to use
*
* @return the found documents
*
* @throws CmsSearchException if something goes wrong
*
* @see #search(CmsObject, CmsSolrQuery, boolean)
*/
@SuppressWarnings("unchecked")
public CmsSolrResultList search(
CmsObject cms,
final CmsSolrQuery query,
boolean ignoreMaxRows,
ServletResponse response,
boolean ignoreSearchExclude,
CmsResourceFilter filter)
throws CmsSearchException {
// check if the user is allowed to access this index
checkOfflineAccess(cms);
if (!ignoreSearchExclude) {
query.addFilterQuery(CmsSearchField.FIELD_SEARCH_EXCLUDE + ":\"false\"");
}
int previousPriority = Thread.currentThread().getPriority();
long startTime = System.currentTimeMillis();
// remember the initial query
SolrQuery initQuery = query.clone();
query.setHighlight(false);
LocalSolrQueryRequest solrQueryRequest = null;
try {
// initialize the search context
CmsObject searchCms = OpenCms.initCmsObject(cms);
// change thread priority in order to reduce search impact on overall system performance
if (getPriority() > 0) {
Thread.currentThread().setPriority(getPriority());
}
// the lists storing the found documents that will be returned
List<CmsSearchResource> resourceDocumentList = new ArrayList<CmsSearchResource>();
SolrDocumentList solrDocumentList = new SolrDocumentList();
// Initialize rows, offset, end and the current page.
int rows = query.getRows() != null ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();
if (!ignoreMaxRows && (rows > ROWS_MAX)) {
rows = ROWS_MAX;
}
int start = query.getStart() != null ? query.getStart().intValue() : 0;
int end = start + rows;
int page = 0;
if (rows > 0) {
page = Math.round(start / rows) + 1;
}
// set the start to '0' and expand the rows before performing the query
query.setStart(new Integer(0));
query.setRows(new Integer((5 * rows * page) + start));
// perform the Solr query and remember the original Solr response
QueryResponse queryResponse = m_solr.query(query);
long solrTime = System.currentTimeMillis() - startTime;
// initialize the counts
long hitCount = queryResponse.getResults().getNumFound();
start = -1;
end = -1;
if ((rows > 0) && (page > 0) && (hitCount > 0)) {
// calculate the final size of the search result
start = rows * (page - 1);
end = start + rows;
// ensure that both i and n are inside the range of foundDocuments.size()
start = new Long((start > hitCount) ? hitCount : start).intValue();
end = new Long((end > hitCount) ? hitCount : end).intValue();
} else {
// return all found documents in the search result
start = 0;
end = new Long(hitCount).intValue();
}
long visibleHitCount = hitCount;
float maxScore = 0;
// If we're using a postprocessor, (re-)initialize it before using it
if (m_postProcessor != null) {
m_postProcessor.init();
}
// process found documents
List<CmsSearchResource> allDocs = new ArrayList<CmsSearchResource>();
int cnt = 0;
for (int i = 0; (i < queryResponse.getResults().size()) && (cnt < end); i++) {
try {
SolrDocument doc = queryResponse.getResults().get(i);
CmsSolrDocument searchDoc = new CmsSolrDocument(doc);
if (needsPermissionCheck(searchDoc)) {
// only if the document is an OpenCms internal resource perform the permission check
CmsResource resource = filter == null
? getResource(searchCms, searchDoc)
: getResource(searchCms, searchDoc, filter);
if (resource != null) {
// permission check performed successfully: the user has read permissions!
if (cnt >= start) {
if (m_postProcessor != null) {
doc = m_postProcessor.process(
searchCms,
resource,
(SolrInputDocument)searchDoc.getDocument());
}
resourceDocumentList.add(new CmsSearchResource(resource, searchDoc));
if (null != doc) {
solrDocumentList.add(doc);
}
maxScore = maxScore < searchDoc.getScore() ? searchDoc.getScore() : maxScore;
}
allDocs.add(new CmsSearchResource(resource, searchDoc));
cnt++;
} else {
visibleHitCount--;
}
} else {
// if permission check is not required for this index,
// add a pseudo resource together with document to the results
resourceDocumentList.add(new CmsSearchResource(PSEUDO_RES, searchDoc));
solrDocumentList.add(doc);
maxScore = maxScore < searchDoc.getScore() ? searchDoc.getScore() : maxScore;
cnt++;
}
} catch (Exception e) {
// should not happen, but if it does we want to go on with the next result nevertheless
LOG.warn(Messages.get().getBundle().key(Messages.LOG_SOLR_ERR_RESULT_ITERATION_FAILED_0), e);
}
}
// the last documents were all secret so let's take the last found docs
if (resourceDocumentList.isEmpty() && (allDocs.size() > 0)) {
page = Math.round(allDocs.size() / rows) + 1;
int showCount = allDocs.size() % rows;
showCount = showCount == 0 ? rows : showCount;
start = allDocs.size() - new Long(showCount).intValue();
end = allDocs.size();
if (allDocs.size() > start) {
resourceDocumentList = allDocs.subList(start, end);
for (CmsSearchResource r : resourceDocumentList) {
maxScore = maxScore < r.getDocument().getScore() ? r.getDocument().getScore() : maxScore;
solrDocumentList.add(((CmsSolrDocument)r.getDocument()).getSolrDocument());
}
}
}
long processTime = System.currentTimeMillis() - startTime - solrTime;
// create and return the result
solrDocumentList.setStart(start);
solrDocumentList.setMaxScore(new Float(maxScore));
solrDocumentList.setNumFound(visibleHitCount);
queryResponse.getResponse().setVal(
queryResponse.getResponse().indexOf(QUERY_RESPONSE_NAME, 0),
solrDocumentList);
queryResponse.getResponseHeader().setVal(
queryResponse.getResponseHeader().indexOf(QUERY_TIME_NAME, 0),
new Integer(new Long(System.currentTimeMillis() - startTime).intValue()));
long highlightEndTime = System.currentTimeMillis();
SolrCore core = m_solr instanceof EmbeddedSolrServer
? ((EmbeddedSolrServer)m_solr).getCoreContainer().getCore(getCoreName())
: null;
CmsSolrResultList result = null;
try {
SearchComponent highlightComponenet = null;
if (core != null) {
highlightComponenet = core.getSearchComponent("highlight");
solrQueryRequest = new LocalSolrQueryRequest(core, queryResponse.getResponseHeader());
}
SolrQueryResponse solrQueryResponse = null;
if (solrQueryRequest != null) {
// create and initialize the solr response
solrQueryResponse = new SolrQueryResponse();
solrQueryResponse.setAllValues(queryResponse.getResponse());
int paramsIndex = queryResponse.getResponseHeader().indexOf(HEADER_PARAMS_NAME, 0);
NamedList<Object> header = null;
Object o = queryResponse.getResponseHeader().getVal(paramsIndex);
if (o instanceof NamedList) {
header = (NamedList<Object>)o;
header.setVal(header.indexOf(CommonParams.ROWS, 0), new Integer(rows));
header.setVal(header.indexOf(CommonParams.START, 0), new Long(start));
}
// set the OpenCms Solr query as parameters to the request
solrQueryRequest.setParams(initQuery);
// perform the highlighting
if ((header != null) && (initQuery.getHighlight()) && (highlightComponenet != null)) {
header.add(HighlightParams.HIGHLIGHT, "on");
if ((initQuery.getHighlightFields() != null) && (initQuery.getHighlightFields().length > 0)) {
header.add(
HighlightParams.FIELDS,
CmsStringUtil.arrayAsString(initQuery.getHighlightFields(), ","));
}
String formatter = initQuery.getParams(HighlightParams.FORMATTER) != null
? initQuery.getParams(HighlightParams.FORMATTER)[0]
: null;
if (formatter != null) {
header.add(HighlightParams.FORMATTER, formatter);
}
if (initQuery.getHighlightFragsize() != 100) {
header.add(HighlightParams.FRAGSIZE, new Integer(initQuery.getHighlightFragsize()));
}
if (initQuery.getHighlightRequireFieldMatch()) {
header.add(
HighlightParams.FIELD_MATCH,
new Boolean(initQuery.getHighlightRequireFieldMatch()));
}
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(initQuery.getHighlightSimplePost())) {
header.add(HighlightParams.SIMPLE_POST, initQuery.getHighlightSimplePost());
}
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(initQuery.getHighlightSimplePre())) {
header.add(HighlightParams.SIMPLE_PRE, initQuery.getHighlightSimplePre());
}
if (initQuery.getHighlightSnippets() != 1) {
header.add(HighlightParams.SNIPPETS, new Integer(initQuery.getHighlightSnippets()));
}
ResponseBuilder rb = new ResponseBuilder(
solrQueryRequest,
solrQueryResponse,
Collections.singletonList(highlightComponenet));
try {
rb.doHighlights = true;
DocListAndSet res = new DocListAndSet();
SchemaField idField = OpenCms.getSearchManager().getSolrServerConfiguration().getSolrSchema().getUniqueKeyField();
int[] luceneIds = new int[rows];
int docs = 0;
for (SolrDocument doc : solrDocumentList) {
String idString = (String)doc.getFirstValue(CmsSearchField.FIELD_ID);
int id = solrQueryRequest.getSearcher().getFirstMatch(
new Term(idField.getName(), idField.getType().toInternal(idString)));
luceneIds[docs++] = id;
}
res.docList = new DocSlice(0, docs, luceneIds, null, docs, 0);
rb.setResults(res);
rb.setQuery(QParser.getParser(initQuery.getQuery(), null, solrQueryRequest).getQuery());
rb.setQueryString(initQuery.getQuery());
highlightComponenet.prepare(rb);
highlightComponenet.process(rb);
highlightComponenet.finishStage(rb);
} catch (Exception e) {
LOG.error(e.getMessage() + " in query: " + initQuery, new Exception(e));
}
// Make highlighting also available via the CmsSolrResultList
queryResponse.setResponse(solrQueryResponse.getValues());
highlightEndTime = System.currentTimeMillis();
}
}
result = new CmsSolrResultList(
initQuery,
queryResponse,
solrDocumentList,
resourceDocumentList,
start,
new Integer(rows),
end,
page,
visibleHitCount,
new Float(maxScore),
startTime,
highlightEndTime);
if (LOG.isDebugEnabled()) {
Object[] logParams = new Object[] {
new Long(System.currentTimeMillis() - startTime),
new Long(result.getNumFound()),
new Long(solrTime),
new Long(processTime),
new Long(result.getHighlightEndTime() != 0 ? result.getHighlightEndTime() - startTime : 0)};
LOG.debug(
query.toString()
+ "\n"
+ Messages.get().getBundle().key(Messages.LOG_SOLR_SEARCH_EXECUTED_5, logParams));
}
if (response != null) {
writeResp(response, solrQueryRequest, solrQueryResponse);
}
} finally {
if (solrQueryRequest != null) {
solrQueryRequest.close();
}
if (core != null) {
core.close();
}
}
return result;
} catch (Exception e) {
throw new CmsSearchException(
Messages.get().container(
Messages.LOG_SOLR_ERR_SEARCH_EXECUTION_FAILD_1,
CmsEncoder.decode(query.toString()),
e),
e);
} finally {
if (solrQueryRequest != null) {
solrQueryRequest.close();
}
// re-set thread to previous priority
Thread.currentThread().setPriority(previousPriority);
}
}
/**
* Default search method.<p>
*
* @param cms the current CMS object
* @param query the query
*
* @return the results
*
* @throws CmsSearchException if something goes wrong
*
* @see #search(CmsObject, String)
*/
public CmsSolrResultList search(CmsObject cms, SolrQuery query) throws CmsSearchException {
return search(cms, CmsEncoder.decode(query.toString()));
}
/**
* Performs a search.<p>
*
* @param cms the cms object
* @param solrQuery the Solr query
*
* @return a list of documents
*
* @throws CmsSearchException if something goes wrong
*
* @see #search(CmsObject, CmsSolrQuery, boolean)
*/
public CmsSolrResultList search(CmsObject cms, String solrQuery) throws CmsSearchException {
return search(cms, new CmsSolrQuery(null, CmsRequestUtil.createParameterMap(solrQuery)), false);
}
/**
* Writes the response into the writer.<p>
*
* NOTE: Currently not available for HTTP server.<p>
*
* @param response the servlet response
* @param cms the CMS object to use for search
* @param query the Solr query
* @param ignoreMaxRows if to return unlimited results
*
* @throws Exception if there is no embedded server
*/
public void select(ServletResponse response, CmsObject cms, CmsSolrQuery query, boolean ignoreMaxRows)
throws Exception {
boolean isOnline = cms.getRequestContext().getCurrentProject().isOnlineProject();
CmsResourceFilter filter = isOnline ? null : CmsResourceFilter.IGNORE_EXPIRATION;
search(cms, query, ignoreMaxRows, response, false, filter);
}
/**
* Sets the logical key/name of this search index.<p>
*
* @param name the logical key/name of this search index
*
* @throws CmsIllegalArgumentException if the given name is null, empty or already taken by another search index
*/
@Override
public void setName(String name) throws CmsIllegalArgumentException {
super.setName(name);
updateCoreName();
}
/**
* Sets the search post processor.<p>
*
* @param postProcessor the search post processor to set
*/
public void setPostProcessor(I_CmsSolrPostSearchProcessor postProcessor) {
m_postProcessor = postProcessor;
}
/**
* Sets the Solr server used by this index.<p>
*
* @param client the server to set
*/
public void setSolrServer(SolrClient client) {
m_solr = client;
}
/**
* Executes a spell checking Solr query and returns the Solr query response.<p>
*
* @param res the servlet response
* @param cms the CMS object
* @param q the query
*
* @throws CmsSearchException if something goes wrong
*/
public void spellCheck(ServletResponse res, CmsObject cms, CmsSolrQuery q) throws CmsSearchException {
SolrCore core = null;
LocalSolrQueryRequest solrQueryRequest = null;
try {
q.setRequestHandler("/spell");
QueryResponse queryResponse = m_solr.query(q);
List<CmsSearchResource> resourceDocumentList = new ArrayList<CmsSearchResource>();
SolrDocumentList solrDocumentList = new SolrDocumentList();
if (m_postProcessor != null) {
for (int i = 0; (i < queryResponse.getResults().size()); i++) {
try {
SolrDocument doc = queryResponse.getResults().get(i);
CmsSolrDocument searchDoc = new CmsSolrDocument(doc);
if (needsPermissionCheck(searchDoc)) {
// only if the document is an OpenCms internal resource perform the permission check
CmsResource resource = getResource(cms, searchDoc);
if (resource != null) {
// permission check performed successfully: the user has read permissions!
if (m_postProcessor != null) {
doc = m_postProcessor.process(
cms,
resource,
(SolrInputDocument)searchDoc.getDocument());
}
resourceDocumentList.add(new CmsSearchResource(resource, searchDoc));
solrDocumentList.add(doc);
}
}
} catch (Exception e) {
// should not happen, but if it does we want to go on with the next result nevertheless
LOG.warn(Messages.get().getBundle().key(Messages.LOG_SOLR_ERR_RESULT_ITERATION_FAILED_0), e);
}
}
queryResponse.getResponse().setVal(
queryResponse.getResponse().indexOf(QUERY_RESPONSE_NAME, 0),
solrDocumentList);
}
// create and return the result
core = m_solr instanceof EmbeddedSolrServer
? ((EmbeddedSolrServer)m_solr).getCoreContainer().getCore(getCoreName())
: null;
SolrQueryResponse solrQueryResponse = new SolrQueryResponse();
solrQueryResponse.setAllValues(queryResponse.getResponse());
// create and initialize the solr request
solrQueryRequest = new LocalSolrQueryRequest(core, solrQueryResponse.getResponseHeader());
// set the OpenCms Solr query as parameters to the request
solrQueryRequest.setParams(q);
writeResp(res, solrQueryRequest, solrQueryResponse);
} catch (Exception e) {
throw new CmsSearchException(
Messages.get().container(Messages.LOG_SOLR_ERR_SEARCH_EXECUTION_FAILD_1, q),
e);
} finally {
if (solrQueryRequest != null) {
solrQueryRequest.close();
}
if (core != null) {
core.close();
}
}
}
/**
* @see org.opencms.search.CmsSearchIndex#createIndexBackup()
*/
@Override
protected String createIndexBackup() {
if (!isBackupReindexing()) {
// if no backup is generated we don't need to do anything
return null;
}
if (m_solr instanceof EmbeddedSolrServer) {
EmbeddedSolrServer ser = (EmbeddedSolrServer)m_solr;
CoreContainer con = ser.getCoreContainer();
SolrCore core = con.getCore(getCoreName());
if (core != null) {
try {
SolrRequestHandler h = core.getRequestHandler("/replication");
if (h instanceof ReplicationHandler) {
h.handleRequest(
new LocalSolrQueryRequest(core, CmsRequestUtil.createParameterMap("?command=backup")),
new SolrQueryResponse());
}
} finally {
core.close();
}
}
}
return null;
}
/**
* @see org.opencms.search.CmsSearchIndex#excludeFromIndex(CmsObject, CmsResource)
*/
@Override
protected boolean excludeFromIndex(CmsObject cms, CmsResource resource) {
if (resource.isFolder() || resource.isTemporaryFile()) {
// don't index folders or temporary files for galleries, but pretty much everything else
return true;
}
return false;
}
/**
* @see org.opencms.search.CmsSearchIndex#indexSearcherClose()
*/
@SuppressWarnings("sync-override")
@Override
protected void indexSearcherClose() {
// nothing to do here
}
/**
* @see org.opencms.search.CmsSearchIndex#indexSearcherOpen(java.lang.String)
*/
@SuppressWarnings("sync-override")
@Override
protected void indexSearcherOpen(final String path) {
// nothing to do here
}
/**
* @see org.opencms.search.CmsSearchIndex#indexSearcherUpdate()
*/
@SuppressWarnings("sync-override")
@Override
protected void indexSearcherUpdate() {
// nothing to do here
}
/**
* Checks if the given resource should be indexed by this index or not.<p>
*
* @param res the resource candidate
*
* @return <code>true</code> if the given resource should be indexed or <code>false</code> if not
*/
protected boolean isIndexing(CmsResource res) {
if ((res != null) && (getSources() != null)) {
I_CmsDocumentFactory result = OpenCms.getSearchManager().getDocumentFactory(res);
for (CmsSearchIndexSource source : getSources()) {
if (source.isIndexing(res.getRootPath(), CmsSolrDocumentContainerPage.TYPE_CONTAINERPAGE_SOLR)
|| source.isIndexing(res.getRootPath(), CmsSolrDocumentXmlContent.TYPE_XMLCONTENT_SOLR)
|| source.isIndexing(res.getRootPath(), result.getName())) {
return true;
}
}
}
return false;
}
/**
* Checks if the current user is allowed to access non-online indexes.<p>
*
* To access non-online indexes the current user must be a workplace user at least.<p>
*
* @param cms the CMS object initialized with the current request context / user
*
* @throws CmsSearchException thrown if the access is not permitted
*/
private void checkOfflineAccess(CmsObject cms) throws CmsSearchException {
// If an offline index is being selected, check permissions
if (!CmsProject.ONLINE_PROJECT_NAME.equals(getProject())) {
// only if the user has the role Workplace user, he is allowed to access the Offline index
try {
OpenCms.getRoleManager().checkRole(cms, CmsRole.ELEMENT_AUTHOR);
} catch (CmsRoleViolationException e) {
throw new CmsSearchException(
Messages.get().container(
Messages.LOG_SOLR_ERR_SEARCH_PERMISSION_VIOLATION_2,
getName(),
cms.getRequestContext().getCurrentUser()),
e);
}
}
}
/**
* Generates a valid core name from the provided name (the index name).
* @param name the index name.
* @return the core name
*/
private String generateCoreName(final String name) {
if (name != null) {
//TODO: Add more name manipulations to guarantee a valid core name
return name.replace(" ", "-");
}
return null;
}
/**
* Updates the core name to be in sync with the index name.
*/
private void updateCoreName() {
m_coreName = generateCoreName(getName());
}
/**
* Writes the Solr response.<p>
*
* @param response the servlet response
* @param queryRequest the Solr request
* @param queryResponse the Solr response to write
*
* @throws IOException if sth. goes wrong
* @throws UnsupportedEncodingException if sth. goes wrong
*/
private void writeResp(ServletResponse response, SolrQueryRequest queryRequest, SolrQueryResponse queryResponse)
throws IOException, UnsupportedEncodingException {
if (m_solr instanceof EmbeddedSolrServer) {
SolrCore core = ((EmbeddedSolrServer)m_solr).getCoreContainer().getCore(getCoreName());
Writer out = null;
try {
QueryResponseWriter responseWriter = core.getQueryResponseWriter(queryRequest);
final String ct = responseWriter.getContentType(queryRequest, queryResponse);
if (null != ct) {
response.setContentType(ct);
}
if (responseWriter instanceof BinaryQueryResponseWriter) {
BinaryQueryResponseWriter binWriter = (BinaryQueryResponseWriter)responseWriter;
binWriter.write(response.getOutputStream(), queryRequest, queryResponse);
} else {
String charset = ContentStreamBase.getCharsetFromContentType(ct);
out = ((charset == null) || charset.equalsIgnoreCase(UTF8.toString()))
? new OutputStreamWriter(response.getOutputStream(), UTF8)
: new OutputStreamWriter(response.getOutputStream(), charset);
out = new FastWriter(out);
responseWriter.write(out, queryRequest, queryResponse);
out.flush();
}
} finally {
core.close();
if (out != null) {
out.close();
}
}
} else {
throw new UnsupportedOperationException();
}
}
}
|
Fixed issue #490 - improved logging in CmsSearchIndex.
|
src/org/opencms/search/solr/CmsSolrIndex.java
|
Fixed issue #490 - improved logging in CmsSearchIndex.
|
|
Java
|
lgpl-2.1
|
bd83ece459a99ff2b1c8d03e5a08fd7c9de7b367
| 0
|
svn2github/vosao,svn2github/vosao,svn2github/vosao,svn2github/vosao
|
/**
* Vosao CMS. Simple CMS for Google App Engine.
*
* Copyright (C) 2009-2010 Vosao development team.
*
* 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.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* email: vosao.dev@gmail.com
*/
package org.vosao.utils;
import java.util.Date;
import org.apache.commons.lang.StringEscapeUtils;
import com.josephoconnell.html.HTMLInputFilter;
/**
* @author Alexander Oleynik
*/
public class ParamUtil {
static public Integer getInteger(final String s,
final Integer defaultValue) {
try {
return Integer.valueOf(s);
}
catch (NumberFormatException e) {
return defaultValue;
}
}
static public Long getLong(final String s,
final Long defaultValue) {
try {
return Long.valueOf(s);
}
catch (NumberFormatException e) {
return defaultValue;
}
}
static public Boolean getBoolean(final String s,
final Boolean defaultValue) {
try {
return Boolean.valueOf(s);
}
catch (Exception e) {
return defaultValue;
}
}
/**
* Convert string to date from format dd.mm.yyyy
* @param s
* @param defaultValue
* @return
*/
static public Date getDate(final String s,
final Date defaultValue) {
try {
return DateUtil.toDate(s);
}
catch (Exception e) {
return defaultValue;
}
}
private static HTMLInputFilter xssFilter = new HTMLInputFilter();
static public String filterXSS(String value) {
//return StringEscapeUtils.escapeHtml(xssFilter.filter(value));
return StringEscapeUtils.escapeHtml(value);
}
}
|
api/src/main/java/org/vosao/utils/ParamUtil.java
|
/**
* Vosao CMS. Simple CMS for Google App Engine.
*
* Copyright (C) 2009-2010 Vosao development team.
*
* 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.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* email: vosao.dev@gmail.com
*/
package org.vosao.utils;
import java.util.Date;
import org.apache.commons.lang.StringEscapeUtils;
import com.josephoconnell.html.HTMLInputFilter;
/**
* @author Alexander Oleynik
*/
public class ParamUtil {
static public Integer getInteger(final String s,
final Integer defaultValue) {
try {
return Integer.valueOf(s);
}
catch (NumberFormatException e) {
return defaultValue;
}
}
static public Long getLong(final String s,
final Long defaultValue) {
try {
return Long.valueOf(s);
}
catch (NumberFormatException e) {
return defaultValue;
}
}
static public Boolean getBoolean(final String s,
final Boolean defaultValue) {
try {
return Boolean.valueOf(s);
}
catch (Exception e) {
return defaultValue;
}
}
/**
* Convert string to date from format dd.mm.yyyy
* @param s
* @param defaultValue
* @return
*/
static public Date getDate(final String s,
final Date defaultValue) {
try {
return DateUtil.toDate(s);
}
catch (Exception e) {
return defaultValue;
}
}
private static HTMLInputFilter xssFilter = new HTMLInputFilter();
static public String filterXSS(String value) {
return StringEscapeUtils.escapeHtml(xssFilter.filter(value));
}
}
|
Fixed issue 515.
git-svn-id: 5df5ab0fddff67249b3cdc000160820e23d702e1@1140 d7b8a73a-866d-11de-bed6-6d316fbe0868
|
api/src/main/java/org/vosao/utils/ParamUtil.java
|
Fixed issue 515.
|
|
Java
|
lgpl-2.1
|
98994ed88e49920a5c7f27327db072479c8427e2
| 0
|
netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration
|
/* $Id$
* $Revision$
* $Date$
* $Author$
*
*
*/
package dk.netarkivet.harvester.tools;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanException;
import javax.management.ReflectionException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.httpclient.URIException;
import org.archive.crawler.datamodel.CandidateURI;
import org.archive.crawler.datamodel.CrawlURI;
import org.archive.crawler.extractor.Extractor;
import org.archive.crawler.extractor.Link;
import org.archive.crawler.settings.SimpleType;
import org.archive.crawler.settings.StringList;
import org.archive.crawler.settings.Type;
import org.archive.net.UURI;
import org.archive.net.UURIFactory;
import twitter4j.Query;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.URLEntity;
/** T
* A processors which queues urls to tweets and, optionally, embedded links.
* Although written as a link extractor for heritrix, the processor actually
* browses twitter through its API using parameters passed in via the order
* template. Seeds are irrelevant, and all the work is done on the first call
* to innerProcess().
*/
public class TwitterHarvesterExtractor extends Extractor {
public static final String PROCESSOR_NAME = "Twitter Harvester Extractor";
public static final String PROCESSOR_FULL_NAME = TwitterHarvesterExtractor.class
.getName();
public static final String PROCESSOR_DESCRIPTION = "Harvests Twitter and embedded url's via Twitter API";
static Logger logger = Logger.getLogger(PROCESSOR_FULL_NAME);
/**
* Here we define bean properties which specify the search parameters for Twitter
*
*/
public static final String ATTR_KEYWORDS= "keywords";
public static final String ATTR_PAGES = "pages";
private StringList keywords;
private int pages;
private int resultsPerPage = 5;
private boolean queueLinks = true;
private boolean firstUri = true;
private Twitter twitter;
private int tweetCount = 0;
private int linkCount = 0;
public TwitterHarvesterExtractor(String name) {
super(name, PROCESSOR_NAME);
System.out.println(
"Constructing instance of " + TwitterHarvesterExtractor.class);
Type e = addElementToDefinition(new StringList(ATTR_KEYWORDS, "Keywords to search for"));
e = addElementToDefinition(new SimpleType(ATTR_PAGES, "Number of pages of twitter results to use.", new Integer(0) ));
twitter = (new TwitterFactory()).getInstance();
}
@Override
protected void initialTasks() {
super.initialTasks();
logger.info("Initial tasks for " + PROCESSOR_FULL_NAME);
System.out.println("Initial tasks for " + PROCESSOR_FULL_NAME);
StringList keywords = (StringList) getAttributeUnchecked(ATTR_KEYWORDS);
this.keywords = keywords;
for (Object keyword: keywords) {
logger.info("Twitter processor keyword: " + keyword);
System.out.println("Twitter processor keyword: " + keyword);
}
int pages = ((Integer) getAttributeUnchecked(ATTR_PAGES)).intValue();
this.pages = pages;
logger.info("Twitter processor will queue " + pages + " page(s) of results.");
System.out.println("Twitter processor will queue " + pages
+ " page(s) of results.");
}
/**
* Version of getAttributes that catches and logs exceptions
* and returns null if failure to fetch the attribute.
* @param name Attribute name.
* @return Attribute or null.
*/
public Object getAttributeUnchecked(String name) {
Object result = null;
try {
result = super.getAttribute(name);
} catch (AttributeNotFoundException e) {
logger.warning(e.getLocalizedMessage());
} catch (MBeanException e) {
logger.warning(e.getLocalizedMessage());
} catch (ReflectionException e) {
logger.warning(e.getLocalizedMessage());
}
return result;
}
@Override
protected void extract(CrawlURI crawlURI) {
if (firstUri) {
for (Object keyword: keywords) {
for (int page = 1; page <= pages; page++) {
Query query = new Query();
query.setRpp(resultsPerPage);
query.setQuery((String) keyword);
query.setPage(page);
try {
List<Tweet> tweets = twitter.search(query).getTweets();
for (Tweet tweet: tweets) {
long id = tweet.getId();
String fromUser = tweet.getFromUser();
String tweetUrl = "http://www.twitter.com/" + fromUser + "/status/" + id;
try {
URI uri = new URI(tweetUrl);
crawlURI.createAndAddLink(uri.toString(), Link.NAVLINK_MISC, Link.NAVLINK_HOP);
CandidateURI curi = new CandidateURI(UURIFactory.getInstance(tweetUrl));
getController().getScope().addSeed(curi);
System.out.println(TwitterHarvesterExtractor.class.getName() + " adding " + tweetUrl);
tweetCount++;
} catch (URIException e) {
logger.log(Level.SEVERE, e.getMessage());
e.printStackTrace();
} catch (URISyntaxException e) {
logger.log(Level.SEVERE, e.getMessage());
e.printStackTrace();
}
if (queueLinks) {
for (URLEntity urlEntity : tweet.getURLEntities()) {
try {
crawlURI.createAndAddLink(urlEntity.getExpandedURL().toString(), Link.PREREQ_MISC, Link.PREREQ_HOP);
crawlURI.createAndAddLink(urlEntity.getURL().toURI().toString(), Link.NAVLINK_MISC, Link.NAVLINK_HOP);
System.out.println(TwitterHarvesterExtractor.class.getName() + " adding " + urlEntity.getExpandedURL().toString());
System.out.println(TwitterHarvesterExtractor.class.getName() + " adding " + urlEntity.getURL().toString());
getController().getScope().addSeed(new CandidateURI(UURIFactory.getInstance(urlEntity.getURL().toString())));
} catch (URIException e) {
logger.log(Level.SEVERE, e.getMessage());
} catch (URISyntaxException e) {
logger.log(Level.SEVERE, e.getMessage());
}
linkCount++;
}
}
}
} catch (TwitterException e) {
logger.log(Level.SEVERE, e.getMessage());
}
}
}
firstUri = false;
crawlURI.linkExtractorFinished();
}
}
@Override
public String report() {
StringBuffer ret = new StringBuffer();
ret.append("Processor:" + TwitterHarvesterExtractor.class.getName() + "\n");
ret.append("Processed " + keywords.size() + " keywords.\n");
ret.append("Processed " + pages + " pages with " + resultsPerPage + " results per page.\n");
ret.append("Queued " + tweetCount + " tweets.\n");
ret.append("Queued " + linkCount + " external links.\n");
return ret.toString();
}
}
|
src/dk/netarkivet/harvester/tools/TwitterHarvesterExtractor.java
|
/* $Id$
* $Revision$
* $Date$
* $Author$
*
*
*/
package dk.netarkivet.harvester.tools;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanException;
import javax.management.ReflectionException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.httpclient.URIException;
import org.archive.crawler.datamodel.CandidateURI;
import org.archive.crawler.datamodel.CrawlURI;
import org.archive.crawler.extractor.Extractor;
import org.archive.crawler.extractor.Link;
import org.archive.crawler.settings.SimpleType;
import org.archive.crawler.settings.StringList;
import org.archive.crawler.settings.Type;
import org.archive.net.UURI;
import org.archive.net.UURIFactory;
import twitter4j.Query;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.URLEntity;
/** T
* A processors which queues urls to tweets and, optionally, embedded links.
* Although written as a link extractor for heritrix, the processor actually
* browses twitter through its API using parameters passed in via the order
* template. Seeds are irrelevant, and all the work is done on the first call
* to innerProcess().
*/
public class TwitterHarvesterExtractor extends Extractor {
public static final String PROCESSOR_NAME = "Twitter Harvester Extractor";
public static final String PROCESSOR_FULL_NAME = TwitterHarvesterExtractor.class
.getName();
public static final String PROCESSOR_DESCRIPTION = "Harvests Twitter and embedded url's via Twitter API";
static Logger logger = Logger.getLogger(PROCESSOR_FULL_NAME);
/**
* Here we define bean properties which specify the search parameters for Twitter
*
*/
public static final String ATTR_KEYWORDS= "keywords";
public static final String ATTR_PAGES = "pages";
private StringList keywords;
private int pages;
private int resultsPerPage = 5;
private boolean queueLinks = true;
private boolean firstUri = true;
private Twitter twitter;
private int tweetCount = 0;
private int linkCount = 0;
public TwitterHarvesterExtractor(String name) {
super(name, PROCESSOR_NAME);
System.out.println(
"Constructing instance of " + TwitterHarvesterExtractor.class);
Type e = addElementToDefinition(new StringList(ATTR_KEYWORDS, "Keywords to search for"));
e = addElementToDefinition(new SimpleType(ATTR_PAGES, "Number of pages of twitter results to use.", new Integer(0) ));
twitter = (new TwitterFactory()).getInstance();
}
@Override
protected void initialTasks() {
super.initialTasks();
logger.info("Initial tasks for " + PROCESSOR_FULL_NAME);
System.out.println("Initial tasks for " + PROCESSOR_FULL_NAME);
StringList keywords = (StringList) getAttributeUnchecked(ATTR_KEYWORDS);
this.keywords = keywords;
for (Object keyword: keywords) {
logger.info("Twitter processor keyword: " + keyword);
System.out.println("Twitter processor keyword: " + keyword);
}
int pages = ((Integer) getAttributeUnchecked(ATTR_PAGES)).intValue();
this.pages = pages;
logger.info("Twitter processor will queue " + pages + " page(s) of results.");
System.out.println("Twitter processor will queue " + pages
+ " page(s) of results.");
}
/**
* Version of getAttributes that catches and logs exceptions
* and returns null if failure to fetch the attribute.
* @param name Attribute name.
* @return Attribute or null.
*/
public Object getAttributeUnchecked(String name) {
Object result = null;
try {
result = super.getAttribute(name);
} catch (AttributeNotFoundException e) {
logger.warning(e.getLocalizedMessage());
} catch (MBeanException e) {
logger.warning(e.getLocalizedMessage());
} catch (ReflectionException e) {
logger.warning(e.getLocalizedMessage());
}
return result;
}
@Override
protected void extract(CrawlURI crawlURI) {
if (firstUri) {
for (Object keyword: keywords) {
for (int page = 1; page <= pages; page++) {
Query query = new Query();
query.setRpp(resultsPerPage);
query.setQuery((String) keyword);
query.setPage(page);
try {
List<Tweet> tweets = twitter.search(query).getTweets();
for (Tweet tweet: tweets) {
long id = tweet.getId();
String fromUser = tweet.getFromUser();
String tweetUrl = "http://twitter.com/" + fromUser + "/status/" + id;
try {
URI uri = new URI(tweetUrl);
crawlURI.createAndAddLink(uri.toString(), Link.NAVLINK_MISC, Link.NAVLINK_HOP);
CandidateURI curi = new CandidateURI(UURIFactory.getInstance(tweetUrl));
getController().getScope().addSeed(curi);
System.out.println(TwitterHarvesterExtractor.class.getName() + " adding " + tweetUrl);
tweetCount++;
} catch (URIException e) {
logger.log(Level.SEVERE, e.getMessage());
e.printStackTrace();
} catch (URISyntaxException e) {
logger.log(Level.SEVERE, e.getMessage());
e.printStackTrace();
}
if (queueLinks) {
for (URLEntity urlEntity : tweet.getURLEntities()) {
try {
crawlURI.createAndAddLink(urlEntity.getExpandedURL().toString(), Link.PREREQ_MISC, Link.PREREQ_HOP);
crawlURI.createAndAddLink(urlEntity.getURL().toURI().toString(), Link.NAVLINK_MISC, Link.NAVLINK_HOP);
System.out.println(TwitterHarvesterExtractor.class.getName() + " adding " + urlEntity.getExpandedURL().toString());
System.out.println(TwitterHarvesterExtractor.class.getName() + " adding " + urlEntity.getURL().toString());
} catch (URIException e) {
logger.log(Level.SEVERE, e.getMessage());
} catch (URISyntaxException e) {
logger.log(Level.SEVERE, e.getMessage());
}
linkCount++;
}
}
}
} catch (TwitterException e) {
logger.log(Level.SEVERE, e.getMessage());
}
}
}
firstUri = false;
crawlURI.linkExtractorFinished();
}
}
@Override
public String report() {
StringBuffer ret = new StringBuffer();
ret.append("Processor:" + TwitterHarvesterExtractor.class.getName() + "\n");
ret.append("Processed " + keywords.size() + " keywords.\n");
ret.append("Processed " + pages + " pages with " + resultsPerPage + " results per page.\n");
ret.append("Queued " + tweetCount + " tweets.\n");
ret.append("Queued " + linkCount + " external links.\n");
return ret.toString();
}
}
|
Initial work on twitter harvester
|
src/dk/netarkivet/harvester/tools/TwitterHarvesterExtractor.java
|
Initial work on twitter harvester
|
|
Java
|
unlicense
|
f0e4273cc1e70b1c15a88ff44b5ba68bc1d2b028
| 0
|
skeeto/october-chess-engine
|
package com.nullprogram.chess.gui;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Font;
import java.awt.Color;
import java.awt.RenderingHints;
import javax.swing.JPanel;
/**
* Progress bar and status bar combined as one.
*/
public class StatusBar extends JPanel {
/** Version for object serialization. */
private static final long serialVersionUID = 1L;
/** Maximum value of progress bar. */
private int maximum = 1;
/** Current value of progress bar. */
private int value = 0;
/** Status string to be displayed. */
private String status;
/** Panel's background color. */
static final Color BACKGROUND = new Color(0xAA, 0xAA, 0xAA);
/** Color of the progress bar. */
static final Color BAR_COLOR = new Color(0x40, 0x00, 0xFF);
/** Color of the status text. */
static final Color STATUS_COLOR = new Color(0x00, 0x00, 0x00);
/** Height of the progress bar. */
static final int BAR_HEIGHT = 3;
/** Vertical padding around the progress bar. */
static final int BAR_PADDING_Y = 3;
/** Horizontal padding around the progress bar. */
static final int BAR_PADDING_X = 10;
/**
* Create a new status bar.
*/
public StatusBar() {
super();
setBackground(BACKGROUND);
setPreferredSize(null);
setMinimumSize(null);
}
/** {@inheritDoc} */
public final Dimension getPreferredSize() {
Graphics g = getGraphics();
if (g != null) {
FontMetrics fm = g.getFontMetrics();
int bar = BAR_PADDING_Y * 2 + BAR_HEIGHT;
return new Dimension(0, fm.getAscent() + bar);
}
return null;
}
/** {@inheritDoc} */
public final Dimension getMinimumSize() {
return getPreferredSize();
}
/**
* Return the maximum value of the progress bar.
*
* @return maximum value
*/
public final int getMaximum() {
return maximum;
}
/**
* Set the maximum value of the progress bar.
*
* @param val new maximum value
*/
public final void setMaximum(final int val) {
maximum = Math.max(val, 1);
}
/**
* Get the current value of the progress bar.
*
* @return current progress bar value
*/
public final int getValue() {
return value;
}
/**
* Set the value of the progress bar.
*
* @param val the new value
*/
public final void setValue(final int val) {
value = Math.min(maximum, val);
repaint();
}
/**
* Set the status string of the status bar.
*
* @param message the new status string
*/
public final void setStatus(final String message) {
status = message;
repaint();
}
/** {@inheritDoc} */
public final void paintComponent(final Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
FontMetrics fm = g.getFontMetrics();
int fh = fm.getAscent();
/* Draw the progress bar. */
g.setColor(BAR_COLOR);
int barWidth = getWidth() - BAR_PADDING_X * 2;
int progress = (barWidth * value) / maximum;
g.fillRect(BAR_PADDING_X, fh + BAR_PADDING_Y,
progress, BAR_HEIGHT);
/* Draw the string. */
g.setColor(STATUS_COLOR);
int width = fm.stringWidth(status);
int height = fm.getHeight();
Font f = fm.getFont();
g.setFont(f.deriveFont(Font.BOLD));
g.drawString(status, getWidth() / 2 - width / 2, height);
}
}
|
src/com/nullprogram/chess/gui/StatusBar.java
|
package com.nullprogram.chess.gui;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Font;
import java.awt.Color;
import java.awt.RenderingHints;
import javax.swing.JPanel;
/**
* Progress bar and status bar combined as one.
*/
public class StatusBar extends JPanel {
/** Version for object serialization. */
private static final long serialVersionUID = 1L;
/** Maximum value of progress bar. */
private int maximum = 1;
/** Current value of progress bar. */
private int value = 0;
/** Status string to be displayed. */
private String status;
/** Panel's background color. */
static final Color BACKGROUND = new Color(0xAA, 0xAA, 0xAA);
/** Color of the progress bar. */
static final Color BAR_COLOR = new Color(0x40, 0x00, 0xFF);
/** Color of the status text. */
static final Color STATUS_COLOR = new Color(0x00, 0x00, 0x00);
/** Height of the progress bar. */
static final int BAR_HEIGHT = 3;
/** Vertical padding around the progress bar. */
static final int BAR_PADDING_Y = 3;
/** Horizontal padding around the progress bar. */
static final int BAR_PADDING_X = 10;
/**
* Create a new status bar.
*/
public StatusBar() {
super();
setBackground(BACKGROUND);
setPreferredSize(null);
setMinimumSize(null);
}
/** {@inheritDoc} */
public final Dimension getPreferredSize() {
Graphics g = getGraphics();
if (g != null) {
FontMetrics fm = g.getFontMetrics();
int bar = BAR_PADDING_Y * 2 + BAR_HEIGHT;
return new Dimension(0, fm.getAscent() + bar);
}
return null;
}
/** {@inheritDoc} */
public final Dimension getMinimumSize() {
return getPreferredSize();
}
/**
* Return the maximum value of the progress bar.
*
* @return maximum value
*/
public final int getMaximum() {
return maximum;
}
/**
* Set the maximum value of the progress bar.
*
* @param val new maximum value
*/
public final void setMaximum(final int val) {
maximum = Math.max(val, 1);
}
/**
* Get the current value of the progress bar.
*
* @return current progress bar value
*/
public final int getValue() {
return value;
}
/**
* Set the value of the progress bar.
*
* @param val the new value
*/
public final void setValue(final int val) {
value = Math.min(maximum, val);
repaint();
}
/**
* Set the status string of the status bar.
*
* @param message the new status string
*/
public final void setStatus(final String message) {
status = message;
System.out.println(message);
repaint();
}
/** {@inheritDoc} */
public final void paintComponent(final Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
FontMetrics fm = g.getFontMetrics();
int fh = fm.getAscent();
/* Draw the progress bar. */
g.setColor(BAR_COLOR);
int barWidth = getWidth() - BAR_PADDING_X * 2;
int progress = (barWidth * value) / maximum;
g.fillRect(BAR_PADDING_X, fh + BAR_PADDING_Y,
progress, BAR_HEIGHT);
/* Draw the string. */
g.setColor(STATUS_COLOR);
int width = fm.stringWidth(status);
int height = fm.getHeight();
Font f = fm.getFont();
g.setFont(f.deriveFont(Font.BOLD));
g.drawString(status, getWidth() / 2 - width / 2, height);
}
}
|
Remove System.out in StatusBar.
|
src/com/nullprogram/chess/gui/StatusBar.java
|
Remove System.out in StatusBar.
|
|
Java
|
apache-2.0
|
928e36aaeede659667332088615a1c8c04906b5e
| 0
|
kiereleaseuser/uberfire,mbiarnes/uberfire,psiroky/uberfire,ederign/uberfire,Salaboy/uberfire,mbiarnes/uberfire,karreiro/uberfire,porcelli-forks/uberfire,psiroky/uberfire,porcelli-forks/uberfire,karreiro/uberfire,karreiro/uberfire,paulovmr/uberfire,porcelli-forks/uberfire,paulovmr/uberfire,uberfire/uberfire,mbiarnes/uberfire,kiereleaseuser/uberfire,uberfire/uberfire,ederign/uberfire,porcelli-forks/uberfire,kiereleaseuser/uberfire,Salaboy/uberfire,uberfire/uberfire,Salaboy/uberfire,uberfire/uberfire,paulovmr/uberfire,ederign/uberfire,mbiarnes/uberfire,karreiro/uberfire,Salaboy/uberfire,kiereleaseuser/uberfire,ederign/uberfire,paulovmr/uberfire,psiroky/uberfire,paulovmr/uberfire,psiroky/uberfire
|
/**
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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.kie.uberfire.security.server;
import java.security.Principal;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.ServiceLoader;
import java.util.Set;
import javax.enterprise.context.ApplicationScoped;
import javax.security.auth.Subject;
import javax.security.jacc.PolicyContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jboss.errai.bus.server.annotations.Service;
import org.jboss.errai.security.shared.api.Group;
import org.jboss.errai.security.shared.api.GroupImpl;
import org.jboss.errai.security.shared.api.Role;
import org.jboss.errai.security.shared.api.identity.User;
import org.jboss.errai.security.shared.api.identity.UserImpl;
import org.jboss.errai.security.shared.exception.FailedAuthenticationException;
import org.jboss.errai.security.shared.service.AuthenticationService;
import org.kie.uberfire.security.server.adapter.GroupsAdapter;
@Service
@ApplicationScoped
public class ServletSecurityAuthenticationService implements AuthenticationService {
private static final String USER_SESSION_ATTR_NAME = "kie.uf.security.user";
private static final String DEFAULT_ROLE_PRINCIPLE_NAME = "Roles";
private final ServiceLoader<GroupsAdapter> groupsAdapterServiceLoader = ServiceLoader.load( GroupsAdapter.class );
private String[] rolePrincipleNames = new String[]{ DEFAULT_ROLE_PRINCIPLE_NAME };
public ServletSecurityAuthenticationService() {
final String value = System.getProperty( "org.kie.uberfire.security.principal.names", "" );
if ( value != null && !value.trim().isEmpty() ) {
rolePrincipleNames = value.split( "," );
}
}
@Override
public User login( String username,
String password ) {
final HttpServletRequest request = getRequestForThread();
try {
request.login( username, password );
return getUser();
} catch ( final ServletException e ) {
throw new FailedAuthenticationException();
}
}
@Override
public boolean isLoggedIn() {
HttpServletRequest request = getRequestForThread();
return request.getUserPrincipal() != null;
}
@Override
public void logout() {
HttpServletRequest request = getRequestForThread();
request.getSession().invalidate();
}
@Override
public User getUser() {
HttpServletRequest request = getRequestForThread();
if ( request.getUserPrincipal() == null ) {
return null;
}
User user = null;
final HttpSession session = request.getSession( false );
if ( session != null ) {
user = (User) session.getAttribute( USER_SESSION_ATTR_NAME );
if ( user == null ) {
final Set<Role> userRoles = new HashSet<Role>();
for ( final Role checkRole : RolesRegistry.get().getRegisteredRoles() ) {
if ( request.isUserInRole( checkRole.getName() ) ) {
userRoles.add( checkRole );
}
}
final String name = request.getUserPrincipal().getName();
final Set<Group> userGroups = new HashSet<Group>( loadGroups() );
for ( final GroupsAdapter adapter : groupsAdapterServiceLoader ) {
final List<Group> groupRoles = adapter.getGroups( name );
if ( groupRoles != null ) {
userGroups.addAll( groupRoles );
}
}
user = new UserImpl( name, userRoles, userGroups );
session.setAttribute( USER_SESSION_ATTR_NAME, user );
}
}
return user;
}
private Set<Group> loadGroups() {
Subject subject;
try {
subject = (Subject) PolicyContext.getContext( "javax.security.auth.Subject.container" );
} catch ( final Exception e ) {
subject = null;
}
if ( subject == null ) {
return Collections.emptySet();
}
final Set<Group> result = new HashSet<Group>();
final Set<java.security.Principal> principals = subject.getPrincipals();
if ( principals != null && !principals.isEmpty() ) {
for ( java.security.Principal p : principals ) {
if ( p instanceof java.security.acl.Group ) {
for ( final String rolePrincipleName : rolePrincipleNames ) {
if ( rolePrincipleName.equalsIgnoreCase( p.getName() ) ) {
final Enumeration<? extends Principal> groups = ( (java.security.acl.Group) p ).members();
while ( groups.hasMoreElements() ) {
final java.security.Principal groupPrincipal = groups.nextElement();
result.add( new GroupImpl( groupPrincipal.getName() ) );
}
}
}
}
}
}
return result;
}
protected static HttpServletRequest getRequestForThread() {
HttpServletRequest request = SecurityIntegrationFilter.getRequest();
if ( request == null ) {
throw new IllegalStateException( "This service only works from threads that are handling HTTP servlet requests" );
}
return request;
}
}
|
uberfire-extensions/kie-uberfire-security/kie-uberfire-servlet-security/src/main/java/org/kie/uberfire/security/server/ServletSecurityAuthenticationService.java
|
/**
* JBoss, Home of Professional Open Source
* Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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.kie.uberfire.security.server;
import java.security.Principal;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.ServiceLoader;
import java.util.Set;
import javax.enterprise.context.ApplicationScoped;
import javax.security.auth.Subject;
import javax.security.jacc.PolicyContext;
import javax.security.jacc.PolicyContextException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.jboss.errai.bus.server.annotations.Service;
import org.jboss.errai.security.shared.api.Group;
import org.jboss.errai.security.shared.api.GroupImpl;
import org.jboss.errai.security.shared.api.Role;
import org.jboss.errai.security.shared.api.identity.User;
import org.jboss.errai.security.shared.api.identity.UserImpl;
import org.jboss.errai.security.shared.exception.FailedAuthenticationException;
import org.jboss.errai.security.shared.service.AuthenticationService;
import org.kie.uberfire.security.server.adapter.GroupsAdapter;
@Service
@ApplicationScoped
public class ServletSecurityAuthenticationService implements AuthenticationService {
private ServiceLoader<GroupsAdapter> groupsAdapterServiceLoader = ServiceLoader.load( GroupsAdapter.class );
private static final String USER_SESSION_ATTR_NAME = "kie.uf.security.user";
@Override
public User login( String username,
String password ) {
final HttpServletRequest request = getRequestForThread();
try {
request.login( username, password );
return getUser();
} catch ( final ServletException e ) {
throw new FailedAuthenticationException();
}
}
@Override
public boolean isLoggedIn() {
HttpServletRequest request = getRequestForThread();
return request.getUserPrincipal() != null;
}
@Override
public void logout() {
HttpServletRequest request = getRequestForThread();
request.getSession().invalidate();
}
@Override
public User getUser() {
HttpServletRequest request = getRequestForThread();
if ( request.getUserPrincipal() == null ) {
return null;
}
User user = null;
final HttpSession session = request.getSession( false );
if (session != null) {
user = (User) session.getAttribute( USER_SESSION_ATTR_NAME );
if ( user == null ) {
final Set<Role> userRoles = new HashSet<Role>();
for ( final Role checkRole : RolesRegistry.get().getRegisteredRoles() ) {
if ( request.isUserInRole( checkRole.getName() ) ) {
userRoles.add( checkRole );
}
}
final String name = request.getUserPrincipal().getName();
final Set<Group> userGroups = new HashSet<Group>( loadGroups( name ) );
for ( final GroupsAdapter adapter : groupsAdapterServiceLoader ) {
final List<Group> groupRoles = adapter.getGroups( name );
if ( groupRoles != null ) {
userGroups.addAll( groupRoles );
}
}
user = new UserImpl( name, userRoles, userGroups );
session.setAttribute( USER_SESSION_ATTR_NAME, user );
}
}
return user;
}
private Set<Group> loadGroups( final String rolePrincipleName ) {
Subject subject;
try {
subject = (Subject) PolicyContext.getContext( "javax.security.auth.Subject.container" );
} catch ( final Exception e ) {
subject = null;
}
if ( subject == null ) {
return Collections.emptySet();
}
final Set<Group> result = new HashSet<Group>();
final Set<java.security.Principal> principals = subject.getPrincipals();
if ( principals != null && !principals.isEmpty() ) {
for ( java.security.Principal p : principals ) {
if ( p instanceof java.security.acl.Group && rolePrincipleName.equalsIgnoreCase( p.getName() ) ) {
final Enumeration<? extends Principal> groups = ( (java.security.acl.Group) p ).members();
while ( groups.hasMoreElements() ) {
final java.security.Principal groupPrincipal = groups.nextElement();
result.add( new GroupImpl( groupPrincipal.getName() ) );
}
break;
}
}
}
return result;
}
protected static HttpServletRequest getRequestForThread() {
HttpServletRequest request = SecurityIntegrationFilter.getRequest();
if ( request == null ) {
throw new IllegalStateException( "This service only works from threads that are handling HTTP servlet requests" );
}
return request;
}
}
|
fix the user's group loading (previously completely broken)
|
uberfire-extensions/kie-uberfire-security/kie-uberfire-servlet-security/src/main/java/org/kie/uberfire/security/server/ServletSecurityAuthenticationService.java
|
fix the user's group loading (previously completely broken)
|
|
Java
|
apache-2.0
|
b63f8bca8bd8e6cfcbb1a4965436256b883432c8
| 0
|
apache/skywalking,ascrutae/sky-walking,apache/skywalking,apache/skywalking,apache/skywalking,apache/skywalking,ascrutae/sky-walking,apache/skywalking,apache/skywalking,ascrutae/sky-walking,ascrutae/sky-walking,OpenSkywalking/skywalking,OpenSkywalking/skywalking
|
/*
* 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.skywalking.apm.toolkit.activation.opentracing.span;
import io.opentracing.tag.Tags;
import java.lang.reflect.Method;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
public class SpanSetTagInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
}
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Object ret) throws Throwable {
AbstractSpan activeSpan = ContextManager.activeSpan();
String tagKey = String.valueOf(allArguments[0]);
String tagValue = String.valueOf(allArguments[1]);
if (Tags.COMPONENT.getKey().equals(tagKey)) {
activeSpan.setComponent(tagValue);
} else if (Tags.PEER_SERVICE.getKey().equals(tagKey)) {
activeSpan.setOperationName(tagValue);
} else if (Tags.ERROR.getKey().equals(tagKey) && "true".equals(tagValue)) {
activeSpan.errorOccurred();
} else {
activeSpan.tag(tagKey, tagValue);
}
return ret;
}
@Override
public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Throwable t) {
}
}
|
apm-sniffer/apm-toolkit-activation/apm-toolkit-opentracing-activation/src/main/java/org/apache/skywalking/apm/toolkit/activation/opentracing/span/SpanSetTagInterceptor.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.skywalking.apm.toolkit.activation.opentracing.span;
import io.opentracing.tag.Tags;
import java.lang.reflect.Method;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
public class SpanSetTagInterceptor implements InstanceMethodsAroundInterceptor {
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, MethodInterceptResult result) throws Throwable {
}
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Object ret) throws Throwable {
AbstractSpan activeSpan = ContextManager.activeSpan();
String tagKey = String.valueOf(allArguments[0]);
String tagValue = String.valueOf(allArguments[1]);
if (Tags.COMPONENT.getKey().equals(tagKey)) {
activeSpan.setComponent(tagValue);
} else if (Tags.PEER_SERVICE.getKey().equals(tagKey)) {
activeSpan.setOperationName(tagValue);
} else {
activeSpan.tag(tagKey, tagValue);
}
return ret;
}
@Override
public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments,
Class<?>[] argumentsTypes, Throwable t) {
}
}
|
fix opentracing with tag error is failed (#3795)
|
apm-sniffer/apm-toolkit-activation/apm-toolkit-opentracing-activation/src/main/java/org/apache/skywalking/apm/toolkit/activation/opentracing/span/SpanSetTagInterceptor.java
|
fix opentracing with tag error is failed (#3795)
|
|
Java
|
apache-2.0
|
e763abe146c3868192cf597cfa637e6fd7a4675f
| 0
|
nuwand/carbon-identity,chanukaranaba/carbon-identity,IsuraD/carbon-identity,dulanjal/carbon-identity,laki88/carbon-identity,Shakila/carbon-identity,nuwand/carbon-identity,malithie/carbon-identity,bastiaanb/carbon-identity,madurangasiriwardena/carbon-identity,kasungayan/carbon-identity,uvindra/carbon-identity,0xkasun/carbon-identity,ChamaraPhilipsuom/carbon-identity,kasungayan/carbon-identity,Pushpalanka/carbon-identity,GayanM/carbon-identity,bastiaanb/carbon-identity,wso2/carbon-identity,madurangasiriwardena/carbon-identity,harsha1979/carbon-identity,isharak/carbon-identity,hasinthaindrajee/carbon-identity,dracusds123/carbon-identity,hasinthaindrajee/carbon-identity,jacklotusho/carbon-identity,thusithathilina/carbon-identity,dulanjal/carbon-identity,madurangasiriwardena/carbon-identity,ravihansa3000/carbon-identity,malithie/carbon-identity,kasungayan/carbon-identity,thilina27/carbon-identity,virajsenevirathne/carbon-identity,hpmtissera/carbon-identity,damithsenanayake/carbon-identity,nuwandi-is/carbon-identity,nuwandi-is/carbon-identity,Niranjan-K/carbon-identity,IndunilRathnayake/carbon-identity,darshanasbg/carbon-identity,GayanM/carbon-identity,keerthu/carbon-identity,kesavany/carbon-identity,kesavany/carbon-identity,JKAUSHALYA/carbon-identity,dracusds123/carbon-identity,virajsenevirathne/carbon-identity,johannnallathamby/carbon-identity,hpmtissera/carbon-identity,kesavany/carbon-identity,wso2/carbon-identity,pulasthi7/carbon-identity,laki88/carbon-identity,0xkasun/carbon-identity,thilina27/carbon-identity,chanukaranaba/carbon-identity,0xkasun/carbon-identity,thariyarox/carbon-identity,harsha1979/carbon-identity,johannnallathamby/carbon-identity,godwinamila/carbon-identity,GayanM/carbon-identity,Niranjan-K/carbon-identity,hasinthaindrajee/carbon-identity,isharak/carbon-identity,JKAUSHALYA/carbon-identity,Shakila/carbon-identity,liurl3/carbon-identity,pulasthi7/carbon-identity,godwinamila/carbon-identity,DMHP/carbon-identity,hpmtissera/carbon-identity,ChamaraPhilipsuom/carbon-identity,Pushpalanka/carbon-identity,thilina27/carbon-identity,DMHP/carbon-identity,IsuraD/carbon-identity,thariyarox/carbon-identity,chanukaranaba/carbon-identity,darshanasbg/carbon-identity,mefarazath/carbon-identity,nuwand/carbon-identity,ChamaraPhilipsuom/carbon-identity,jacklotusho/carbon-identity,darshanasbg/carbon-identity,thanujalk/carbon-identity,keerthu/carbon-identity,Shakila/carbon-identity,keerthu/carbon-identity,malithie/carbon-identity,damithsenanayake/carbon-identity,IndunilRathnayake/carbon-identity,liurl3/carbon-identity,ashalya/carbon-identity,thanujalk/carbon-identity,prabathabey/carbon-identity,thariyarox/carbon-identity,IsuraD/carbon-identity,uvindra/carbon-identity,harsha1979/carbon-identity,dulanjal/carbon-identity,dracusds123/carbon-identity,ashalya/carbon-identity,laki88/carbon-identity,pulasthi7/carbon-identity,jacklotusho/carbon-identity,godwinamila/carbon-identity,nuwandi-is/carbon-identity,wso2/carbon-identity,mefarazath/carbon-identity,bastiaanb/carbon-identity,johannnallathamby/carbon-identity,ravihansa3000/carbon-identity,mefarazath/carbon-identity,isharak/carbon-identity,thusithathilina/carbon-identity,DMHP/carbon-identity,Niranjan-K/carbon-identity,ravihansa3000/carbon-identity,thanujalk/carbon-identity,Pushpalanka/carbon-identity,damithsenanayake/carbon-identity,prabathabey/carbon-identity,liurl3/carbon-identity,virajsenevirathne/carbon-identity,JKAUSHALYA/carbon-identity,ashalya/carbon-identity,prabathabey/carbon-identity,thusithathilina/carbon-identity,uvindra/carbon-identity,IndunilRathnayake/carbon-identity
|
/*
* Copyright (c) 2015, 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.identity.application.authenticator.oidc.googleext;
import org.apache.amber.oauth2.client.OAuthClient;
import org.apache.amber.oauth2.client.URLConnectionClient;
import org.apache.amber.oauth2.client.request.OAuthClientRequest;
import org.apache.amber.oauth2.client.response.OAuthAuthzResponse;
import org.apache.amber.oauth2.client.response.OAuthClientResponse;
import org.apache.amber.oauth2.common.exception.OAuthProblemException;
import org.apache.amber.oauth2.common.exception.OAuthSystemException;
import org.apache.amber.oauth2.common.message.types.GrantType;
import org.apache.amber.oauth2.common.utils.JSONUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jettison.json.JSONException;
import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext;
import org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException;
import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser;
import org.wso2.carbon.identity.application.authenticator.oidc.OIDCAuthenticatorConstants;
import org.wso2.carbon.identity.application.authenticator.oidc.OpenIDConnectAuthenticator;
import org.wso2.carbon.identity.application.common.model.ClaimMapping;
import org.wso2.carbon.identity.application.common.model.Property;
import org.wso2.carbon.ui.CarbonUIUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GoogleOAuth2Authenticator extends OpenIDConnectAuthenticator {
private static final long serialVersionUID = -4154255583070524018L;
private static Log log = LogFactory.getLog(GoogleOAuth2Authenticator.class);
/**
* Get Authorization Server Endpoint
*
* @param authenticatorProperties
* @return
*/
@Override
protected String getAuthorizationServerEndpoint(
Map<String, String> authenticatorProperties) {
return GoogleOAuth2AuthenticationConstant.GOOGLE_OAUTH_ENDPOINT;
}
/**
* Get Token Endpoint
*
* @param authenticatorProperties
* @return
*/
@Override
protected String getTokenEndpoint(
Map<String, String> authenticatorProperties) {
return GoogleOAuth2AuthenticationConstant.GOOGLE_TOKEN_ENDPOINT;
}
/**
* This is override because of query string values hard coded and input
* values validations are not required.
*
* @param request
* @param response
* @param context
* @throws AuthenticationFailedException
*/
@Override
protected void initiateAuthenticationRequest(HttpServletRequest request,
HttpServletResponse response, AuthenticationContext context)
throws AuthenticationFailedException {
try {
Map<String, String> authenticatorProperties = context
.getAuthenticatorProperties();
if (authenticatorProperties != null) {
String clientId = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_ID);
String authorizationEP;
if (getAuthorizationServerEndpoint(authenticatorProperties) != null) {
authorizationEP = getAuthorizationServerEndpoint(authenticatorProperties);
} else {
authorizationEP = authenticatorProperties.get(OIDCAuthenticatorConstants.OAUTH2_AUTHZ_URL);
}
String callBackUrl = authenticatorProperties.get(GoogleOAuth2AuthenticationConstant.CALLBACK_URL);
if (log.isDebugEnabled()) {
log.debug("Google-callback-url : " + callBackUrl);
}
if (callBackUrl == null) {
callBackUrl = CarbonUIUtil.getAdminConsoleURL(request);
callBackUrl = callBackUrl.replace("commonauth/carbon/", "commonauth");
}
String state = context.getContextIdentifier() + "," + OIDCAuthenticatorConstants.LOGIN_TYPE;
state = getState(state, authenticatorProperties);
OAuthClientRequest authzRequest;
// This is the query string need to send in order to get email and
// profile
String queryString = GoogleOAuth2AuthenticationConstant.QUERY_STRING;
authzRequest = OAuthClientRequest
.authorizationLocation(authorizationEP)
.setClientId(clientId)
.setRedirectURI(callBackUrl)
.setResponseType(
OIDCAuthenticatorConstants.OAUTH2_GRANT_TYPE_CODE)
.setState(state).buildQueryMessage();
String loginPage = authzRequest.getLocationUri();
String domain = request.getParameter("domain");
if (domain != null) {
loginPage = loginPage + "&fidp=" + domain;
}
if (queryString != null) {
if (!queryString.startsWith("&")) {
loginPage = loginPage + "&" + queryString;
} else {
loginPage = loginPage + queryString;
}
}
response.sendRedirect(loginPage);
} else {
if (log.isDebugEnabled()) {
log.debug("Error while retrieving properties. Authenticator Properties cannot be null");
}
throw new AuthenticationFailedException(
"Error while retrieving properties. Authenticator Properties cannot be null");
}
} catch (IOException e) {
throw new AuthenticationFailedException("Exception while sending to the login page", e);
} catch (OAuthSystemException e) {
throw new AuthenticationFailedException("Exception while building authorization code request", e);
}
}
/**
* Get Scope
*
* @param scope
* @param authenticatorProperties
* @return
*/
@Override
protected String getScope(String scope,
Map<String, String> authenticatorProperties) {
return OIDCAuthenticatorConstants.OAUTH_OIDC_SCOPE;
}
/**
* Get Authenticated User
*
* @param token
* @return
*/
@Override
protected String getAuthenticateUser(OAuthClientResponse token) {
return token.getParam(OIDCAuthenticatorConstants.Claim.EMAIL);
}
/**
* Get Subject Attributes
*
* @param token
* @return
*/
@Override
protected Map<ClaimMapping, String> getSubjectAttributes(
OAuthClientResponse token) {
Map<ClaimMapping, String> claims = new HashMap<ClaimMapping, String>();
try {
String json = sendRequest(GoogleOAuth2AuthenticationConstant.GOOGLE_USERINFO_ENDPOINT,
token.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN));
Map<String, Object> jsonObject = JSONUtils.parseJSON(json);
if (jsonObject != null) {
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
claims.put(ClaimMapping.build(entry.getKey(),
entry.getKey(), null, false), entry.getValue()
.toString());
if (log.isDebugEnabled()) {
log.debug("Adding claim from end-point data mapping : " + entry.getKey() + " - " +
entry.getValue());
}
}
}
} catch (Exception e) {
log.error("Error occurred while accessing google user info endpoint", e);
}
return claims;
}
/**
* Get Configuration Properties
*
* @return
*/
@Override
public List<Property> getConfigurationProperties() {
List<Property> configProperties = new ArrayList<Property>();
Property clientId = new Property();
clientId.setName(OIDCAuthenticatorConstants.CLIENT_ID);
clientId.setDisplayName("Client Id");
clientId.setRequired(true);
clientId.setDescription("Enter Google IDP client identifier value");
configProperties.add(clientId);
Property clientSecret = new Property();
clientSecret.setName(OIDCAuthenticatorConstants.CLIENT_SECRET);
clientSecret.setDisplayName("Client Secret");
clientSecret.setRequired(true);
clientSecret.setConfidential(true);
clientSecret.setDescription("Enter Google IDP client secret value");
configProperties.add(clientSecret);
Property callbackUrl = new Property();
callbackUrl.setDisplayName("Callback Url");
callbackUrl.setName(GoogleOAuth2AuthenticationConstant.CALLBACK_URL);
callbackUrl.setRequired(true);
callbackUrl.setDescription("Enter value corresponding to callback url.");
configProperties.add(callbackUrl);
return configProperties;
}
/**
* this method are overridden for extra claim request to google end-point
*
* @param request
* @param response
* @param context
* @throws AuthenticationFailedException
*/
@Override
protected void processAuthenticationResponse(HttpServletRequest request,
HttpServletResponse response, AuthenticationContext context)
throws AuthenticationFailedException {
try {
Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
String clientId = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_ID);
String clientSecret = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_SECRET);
String tokenEndPoint;
if (getTokenEndpoint(authenticatorProperties) != null) {
tokenEndPoint = getTokenEndpoint(authenticatorProperties);
} else {
tokenEndPoint = authenticatorProperties.get(OIDCAuthenticatorConstants.OAUTH2_TOKEN_URL);
}
String callBackUrl = authenticatorProperties.get(GoogleOAuth2AuthenticationConstant.CALLBACK_URL);
log.debug("callBackUrl : " + callBackUrl);
if (callBackUrl == null) {
callBackUrl = CarbonUIUtil.getAdminConsoleURL(request);
callBackUrl = callBackUrl.replace("commonauth/carbon/", "commonauth");
}
@SuppressWarnings({"unchecked"})
Map<String, String> paramValueMap = (Map<String, String>) context.getProperty("oidc:param.map");
if (paramValueMap != null
&& paramValueMap.containsKey("redirect_uri")) {
callBackUrl = paramValueMap.get("redirect_uri");
}
OAuthAuthzResponse authzResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = authzResponse.getCode();
OAuthClientRequest accessRequest = null;
accessRequest = getAccessRequest(tokenEndPoint, clientId, clientSecret, callBackUrl, code);
// create OAuth client that uses custom http client under the hood
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthClientResponse oAuthResponse = null;
oAuthResponse = getOAuthResponse(accessRequest,oAuthClient, oAuthResponse);
// TODO : return access token and id token to framework
String accessToken = "";
String idToken = "";
if (oAuthResponse != null) {
accessToken = oAuthResponse.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN);
idToken = oAuthResponse.getParam(OIDCAuthenticatorConstants.ID_TOKEN);
}
if (accessToken != null && (idToken != null || !requiredIDToken(authenticatorProperties))) {
context.setProperty(OIDCAuthenticatorConstants.ACCESS_TOKEN, accessToken);
if (idToken != null) {
context.setProperty(OIDCAuthenticatorConstants.ID_TOKEN, idToken);
String base64Body = idToken.split("\\.")[1];
byte[] decoded = Base64.decodeBase64(base64Body.getBytes());
String json = new String(decoded, Charset.forName("utf-8"));
if (log.isDebugEnabled()) {
log.debug("Id token json string : " + json);
}
Map<String, Object> jsonObject = JSONUtils.parseJSON(json);
if (jsonObject != null) {
Map<ClaimMapping, String> claims = getSubjectAttributes(oAuthResponse);
String authenticatedUser = (String) jsonObject.get(OIDCAuthenticatorConstants.Claim.EMAIL);
AuthenticatedUser authenticatedUserObj = AuthenticatedUser
.createFederateAuthenticatedUserFromSubjectIdentifier(authenticatedUser);
authenticatedUserObj.setUserAttributes(claims);
context.setSubject(authenticatedUserObj);
} else {
if (log.isDebugEnabled()) {
log.debug("Decoded json object is null");
}
throw new AuthenticationFailedException("Decoded json object is null");
}
} else {
if (log.isDebugEnabled()) {
log.debug("Authentication Failed");
}
throw new AuthenticationFailedException("Authentication Failed");
}
} else {
throw new AuthenticationFailedException("Authentication Failed");
}
} catch (OAuthProblemException e) {
throw new AuthenticationFailedException("Error occurred while acquiring access token", e);
} catch (JSONException e) {
throw new AuthenticationFailedException("Error occurred while parsing json object", e);
}
}
private OAuthClientResponse getOAuthResponse(OAuthClientRequest accessRequest,OAuthClient oAuthClient, OAuthClientResponse oAuthResponse) throws AuthenticationFailedException {
OAuthClientResponse oAuthClientResponse = oAuthResponse;
try {
oAuthClientResponse = oAuthClient.accessToken(accessRequest);
} catch (OAuthSystemException e) {
if (log.isDebugEnabled()) {
log.debug("Exception while requesting access token", e);
}
throw new AuthenticationFailedException("Exception while requesting access token", e);
} catch (OAuthProblemException e) {
if (log.isDebugEnabled()) {
log.debug("Exception while requesting access token", e);
}
}
return oAuthClientResponse;
}
private OAuthClientRequest getAccessRequest(String tokenEndPoint, String clientId, String clientSecret
, String callBackUrl, String code)
throws AuthenticationFailedException {
OAuthClientRequest accessRequest = null;
try {
accessRequest = OAuthClientRequest.tokenLocation(tokenEndPoint)
.setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId).setClientSecret(clientSecret)
.setRedirectURI(callBackUrl).setCode(code).buildBodyMessage();
} catch (OAuthSystemException e) {
throw new AuthenticationFailedException("Exception while building request for request access token", e);
}
return accessRequest;
}
/**
* Get Friendly Name
*
* @return
*/
@Override
public String getFriendlyName() {
return GoogleOAuth2AuthenticationConstant.GOOGLE_CONNECTOR_FRIENDLY_NAME;
}
/**
* GetName
*
* @return
*/
@Override
public String getName() {
return GoogleOAuth2AuthenticationConstant.GOOGLE_CONNECTOR_NAME;
}
/**
* extra request sending to google user info end-point
*
* @param url
* @param accessToken
* @return
* @throws IOException
*/
private String sendRequest(String url, String accessToken)
throws IOException {
if (log.isDebugEnabled()) {
log.debug("claim url: " + url + " & accessToken : " + accessToken);
}
URL obj = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) obj.openConnection();
urlConnection.setRequestMethod("GET");
// add request header
urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder b = new StringBuilder();
String inputLine = in.readLine();
while (inputLine != null) {
b.append(inputLine).append("\n");
inputLine = in.readLine();
}
in.close();
if (log.isDebugEnabled()) {
log.debug("response: " + b.toString());
}
return b.toString();
}
}
|
components/application-authenticators/org.wso2.carbon.identity.application.authenticator.oidc.googleext/src/main/java/org/wso2/carbon/identity/application/authenticator/oidc/googleext/GoogleOAuth2Authenticator.java
|
/*
* Copyright (c) 2015, 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.identity.application.authenticator.oidc.googleext;
import org.apache.amber.oauth2.client.OAuthClient;
import org.apache.amber.oauth2.client.URLConnectionClient;
import org.apache.amber.oauth2.client.request.OAuthClientRequest;
import org.apache.amber.oauth2.client.response.OAuthAuthzResponse;
import org.apache.amber.oauth2.client.response.OAuthClientResponse;
import org.apache.amber.oauth2.common.exception.OAuthProblemException;
import org.apache.amber.oauth2.common.exception.OAuthSystemException;
import org.apache.amber.oauth2.common.message.types.GrantType;
import org.apache.amber.oauth2.common.utils.JSONUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jettison.json.JSONException;
import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext;
import org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException;
import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser;
import org.wso2.carbon.identity.application.authenticator.oidc.OIDCAuthenticatorConstants;
import org.wso2.carbon.identity.application.authenticator.oidc.OpenIDConnectAuthenticator;
import org.wso2.carbon.identity.application.common.model.ClaimMapping;
import org.wso2.carbon.identity.application.common.model.Property;
import org.wso2.carbon.ui.CarbonUIUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GoogleOAuth2Authenticator extends OpenIDConnectAuthenticator {
private static final long serialVersionUID = -4154255583070524018L;
private static Log log = LogFactory.getLog(GoogleOAuth2Authenticator.class);
/**
* Get Authorization Server Endpoint
*
* @param authenticatorProperties
* @return
*/
@Override
protected String getAuthorizationServerEndpoint(
Map<String, String> authenticatorProperties) {
return GoogleOAuth2AuthenticationConstant.GOOGLE_OAUTH_ENDPOINT;
}
/**
* Get Token Endpoint
*
* @param authenticatorProperties
* @return
*/
@Override
protected String getTokenEndpoint(
Map<String, String> authenticatorProperties) {
return GoogleOAuth2AuthenticationConstant.GOOGLE_TOKEN_ENDPOINT;
}
/**
* This is override because of query string values hard coded and input
* values validations are not required.
*
* @param request
* @param response
* @param context
* @throws AuthenticationFailedException
*/
@Override
protected void initiateAuthenticationRequest(HttpServletRequest request,
HttpServletResponse response, AuthenticationContext context)
throws AuthenticationFailedException {
try {
Map<String, String> authenticatorProperties = context
.getAuthenticatorProperties();
if (authenticatorProperties != null) {
String clientId = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_ID);
String authorizationEP;
if (getAuthorizationServerEndpoint(authenticatorProperties) != null) {
authorizationEP = getAuthorizationServerEndpoint(authenticatorProperties);
} else {
authorizationEP = authenticatorProperties.get(OIDCAuthenticatorConstants.OAUTH2_AUTHZ_URL);
}
String callBackUrl = authenticatorProperties.get(GoogleOAuth2AuthenticationConstant.CALLBACK_URL);
if (log.isDebugEnabled()) {
log.debug("Google-callback-url : " + callBackUrl);
}
if (callBackUrl == null) {
callBackUrl = CarbonUIUtil.getAdminConsoleURL(request);
callBackUrl = callBackUrl.replace("commonauth/carbon/", "commonauth");
}
String state = context.getContextIdentifier() + "," + OIDCAuthenticatorConstants.LOGIN_TYPE;
state = getState(state, authenticatorProperties);
OAuthClientRequest authzRequest;
// This is the query string need to send in order to get email and
// profile
String queryString = GoogleOAuth2AuthenticationConstant.QUERY_STRING;
authzRequest = OAuthClientRequest
.authorizationLocation(authorizationEP)
.setClientId(clientId)
.setRedirectURI(callBackUrl)
.setResponseType(
OIDCAuthenticatorConstants.OAUTH2_GRANT_TYPE_CODE)
.setState(state).buildQueryMessage();
String loginPage = authzRequest.getLocationUri();
String domain = request.getParameter("domain");
if (domain != null) {
loginPage = loginPage + "&fidp=" + domain;
}
if (queryString != null) {
if (!queryString.startsWith("&")) {
loginPage = loginPage + "&" + queryString;
} else {
loginPage = loginPage + queryString;
}
}
response.sendRedirect(loginPage);
} else {
if (log.isDebugEnabled()) {
log.debug("Error while retrieving properties. Authenticator Properties cannot be null");
}
throw new AuthenticationFailedException(
"Error while retrieving properties. Authenticator Properties cannot be null");
}
} catch (IOException e) {
throw new AuthenticationFailedException("Exception while sending to the login page", e);
} catch (OAuthSystemException e) {
throw new AuthenticationFailedException("Exception while building authorization code request", e);
}
}
/**
* Get Scope
*
* @param scope
* @param authenticatorProperties
* @return
*/
@Override
protected String getScope(String scope,
Map<String, String> authenticatorProperties) {
return OIDCAuthenticatorConstants.OAUTH_OIDC_SCOPE;
}
/**
* Get Authenticated User
*
* @param token
* @return
*/
@Override
protected String getAuthenticateUser(OAuthClientResponse token) {
return token.getParam(OIDCAuthenticatorConstants.Claim.EMAIL);
}
/**
* Get Subject Attributes
*
* @param token
* @return
*/
@Override
protected Map<ClaimMapping, String> getSubjectAttributes(
OAuthClientResponse token) {
Map<ClaimMapping, String> claims = new HashMap<ClaimMapping, String>();
try {
String json = sendRequest(GoogleOAuth2AuthenticationConstant.GOOGLE_USERINFO_ENDPOINT,
token.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN));
Map<String, Object> jsonObject = JSONUtils.parseJSON(json);
if (jsonObject != null) {
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
claims.put(ClaimMapping.build(entry.getKey(),
entry.getKey(), null, false), entry.getValue()
.toString());
if (log.isDebugEnabled()) {
log.debug("Adding claim from end-point data mapping : " + entry.getKey() + " - " +
entry.getValue());
}
}
}
} catch (Exception e) {
log.error("Error occurred while accessing google user info endpoint", e);
}
return claims;
}
/**
* Get Configuration Properties
*
* @return
*/
@Override
public List<Property> getConfigurationProperties() {
List<Property> configProperties = new ArrayList<Property>();
Property clientId = new Property();
clientId.setName(OIDCAuthenticatorConstants.CLIENT_ID);
clientId.setDisplayName("Client Id");
clientId.setRequired(true);
clientId.setDescription("Enter Google IDP client identifier value");
configProperties.add(clientId);
Property clientSecret = new Property();
clientSecret.setName(OIDCAuthenticatorConstants.CLIENT_SECRET);
clientSecret.setDisplayName("Client Secret");
clientSecret.setRequired(true);
clientSecret.setConfidential(true);
clientSecret.setDescription("Enter Google IDP client secret value");
configProperties.add(clientSecret);
Property callbackUrl = new Property();
callbackUrl.setDisplayName("Callback Url");
callbackUrl.setName(GoogleOAuth2AuthenticationConstant.CALLBACK_URL);
callbackUrl.setRequired(true);
callbackUrl.setDescription("Enter value corresponding to callback url.");
configProperties.add(callbackUrl);
return configProperties;
}
/**
* this method are overridden for extra claim request to google end-point
*
* @param request
* @param response
* @param context
* @throws AuthenticationFailedException
*/
@Override
protected void processAuthenticationResponse(HttpServletRequest request,
HttpServletResponse response, AuthenticationContext context)
throws AuthenticationFailedException {
try {
Map<String, String> authenticatorProperties = context.getAuthenticatorProperties();
String clientId = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_ID);
String clientSecret = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_SECRET);
String tokenEndPoint;
if (getTokenEndpoint(authenticatorProperties) != null) {
tokenEndPoint = getTokenEndpoint(authenticatorProperties);
} else {
tokenEndPoint = authenticatorProperties.get(OIDCAuthenticatorConstants.OAUTH2_TOKEN_URL);
}
String callBackUrl = authenticatorProperties.get(GoogleOAuth2AuthenticationConstant.CALLBACK_URL);
log.debug("callBackUrl : " + callBackUrl);
if (callBackUrl == null) {
callBackUrl = CarbonUIUtil.getAdminConsoleURL(request);
callBackUrl = callBackUrl.replace("commonauth/carbon/", "commonauth");
}
@SuppressWarnings({"unchecked"})
Map<String, String> paramValueMap = (Map<String, String>) context.getProperty("oidc:param.map");
if (paramValueMap != null
&& paramValueMap.containsKey("redirect_uri")) {
callBackUrl = paramValueMap.get("redirect_uri");
}
OAuthAuthzResponse authzResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = authzResponse.getCode();
OAuthClientRequest accessRequest = null;
accessRequest = getAccessRequest(tokenEndPoint, clientId, clientSecret, callBackUrl, code);
// create OAuth client that uses custom http client under the hood
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthClientResponse oAuthResponse = null;
oAuthResponse = getOAuthResponse(oAuthClient, oAuthResponse);
// TODO : return access token and id token to framework
String accessToken = "";
String idToken = "";
if (oAuthResponse != null) {
accessToken = oAuthResponse.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN);
idToken = oAuthResponse.getParam(OIDCAuthenticatorConstants.ID_TOKEN);
}
if (accessToken != null && (idToken != null || !requiredIDToken(authenticatorProperties))) {
context.setProperty(OIDCAuthenticatorConstants.ACCESS_TOKEN, accessToken);
if (idToken != null) {
context.setProperty(OIDCAuthenticatorConstants.ID_TOKEN, idToken);
String base64Body = idToken.split("\\.")[1];
byte[] decoded = Base64.decodeBase64(base64Body.getBytes());
String json = new String(decoded, Charset.forName("utf-8"));
if (log.isDebugEnabled()) {
log.debug("Id token json string : " + json);
}
Map<String, Object> jsonObject = JSONUtils.parseJSON(json);
if (jsonObject != null) {
Map<ClaimMapping, String> claims = getSubjectAttributes(oAuthResponse);
String authenticatedUser = (String) jsonObject.get(OIDCAuthenticatorConstants.Claim.EMAIL);
AuthenticatedUser authenticatedUserObj = AuthenticatedUser
.createFederateAuthenticatedUserFromSubjectIdentifier(authenticatedUser);
authenticatedUserObj.setUserAttributes(claims);
context.setSubject(authenticatedUserObj);
} else {
if (log.isDebugEnabled()) {
log.debug("Decoded json object is null");
}
throw new AuthenticationFailedException("Decoded json object is null");
}
} else {
if (log.isDebugEnabled()) {
log.debug("Authentication Failed");
}
throw new AuthenticationFailedException("Authentication Failed");
}
} else {
throw new AuthenticationFailedException("Authentication Failed");
}
} catch (OAuthProblemException e) {
throw new AuthenticationFailedException("Error occurred while acquiring access token", e);
} catch (JSONException e) {
throw new AuthenticationFailedException("Error occurred while parsing json object", e);
}
}
private OAuthClientResponse getOAuthResponse(OAuthClient oAuthClient, OAuthClientResponse oAuthResponse) throws AuthenticationFailedException {
OAuthClientResponse oAuthClientResponse = oAuthResponse;
OAuthClientRequest accessRequest = null;
try {
oAuthClientResponse = oAuthClient.accessToken(accessRequest);
} catch (OAuthSystemException e) {
if (log.isDebugEnabled()) {
log.debug("Exception while requesting access token", e);
}
throw new AuthenticationFailedException("Exception while requesting access token", e);
} catch (OAuthProblemException e) {
if (log.isDebugEnabled()) {
log.debug("Exception while requesting access token", e);
}
}
return oAuthClientResponse;
}
private OAuthClientRequest getAccessRequest(String tokenEndPoint, String clientId, String clientSecret
, String callBackUrl, String code)
throws AuthenticationFailedException {
OAuthClientRequest oAuthClientRequest = null;
try {
oAuthClientRequest = OAuthClientRequest.tokenLocation(tokenEndPoint)
.setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId).setClientSecret(clientSecret)
.setRedirectURI(callBackUrl).setCode(code).buildBodyMessage();
} catch (OAuthSystemException e) {
throw new AuthenticationFailedException("Exception while building request for request access token", e);
}
return oAuthClientRequest;
}
/**
* Get Friendly Name
*
* @return
*/
@Override
public String getFriendlyName() {
return GoogleOAuth2AuthenticationConstant.GOOGLE_CONNECTOR_FRIENDLY_NAME;
}
/**
* GetName
*
* @return
*/
@Override
public String getName() {
return GoogleOAuth2AuthenticationConstant.GOOGLE_CONNECTOR_NAME;
}
/**
* extra request sending to google user info end-point
*
* @param url
* @param accessToken
* @return
* @throws IOException
*/
private String sendRequest(String url, String accessToken)
throws IOException {
if (log.isDebugEnabled()) {
log.debug("claim url: " + url + " & accessToken : " + accessToken);
}
URL obj = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) obj.openConnection();
urlConnection.setRequestMethod("GET");
// add request header
urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder b = new StringBuilder();
String inputLine = in.readLine();
while (inputLine != null) {
b.append(inputLine).append("\n");
inputLine = in.readLine();
}
in.close();
if (log.isDebugEnabled()) {
log.debug("response: " + b.toString());
}
return b.toString();
}
}
|
IDENTITY-3358
|
components/application-authenticators/org.wso2.carbon.identity.application.authenticator.oidc.googleext/src/main/java/org/wso2/carbon/identity/application/authenticator/oidc/googleext/GoogleOAuth2Authenticator.java
|
IDENTITY-3358
|
|
Java
|
apache-2.0
|
1c0634399369ca92468569708f8f082e3c606069
| 0
|
vlogvinov/java_pft
|
package ru.stqa.pft.addressbook.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.GroupData;
import java.util.HashSet;
import java.util.List;
public class GroupCreationTests extends TestBase {
@Test
public void testGroupCreation() {
app.getNavigationHelper().goToGroupsPage();
List<GroupData> before = app.getGroupHelper().getGroupList();
app.getGroupHelper().initGroupCreation();
GroupData group = new GroupData();
group.setName("my group");
group.setHeader("my header");
group.setFooter("my footer");
app.getGroupHelper().fillGroupForm(group);
app.getGroupHelper().submitGroupCreation();
app.getGroupHelper().returnToGroupsPage();
List<GroupData> after = app.getGroupHelper().getGroupList();
Assert.assertEquals(after.size(), before.size() + 1);
group.setId(after.stream().max((o1, o2) -> Integer.compare(o1.getId(), o2.getId())).get().getId());
before.add(group);
Assert.assertEquals(new HashSet<Object>(before), new HashSet<Object>(after));
app.getSessionHelper().logout();
}
}
|
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/GroupCreationTests.java
|
package ru.stqa.pft.addressbook.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.GroupData;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
public class GroupCreationTests extends TestBase {
@Test
public void testGroupCreation() {
app.getNavigationHelper().goToGroupsPage();
List<GroupData> before = app.getGroupHelper().getGroupList();
app.getGroupHelper().initGroupCreation();
GroupData group = new GroupData();
group.setName("my group");
group.setHeader("my header");
group.setFooter("my footer");
app.getGroupHelper().fillGroupForm(group);
app.getGroupHelper().submitGroupCreation();
app.getGroupHelper().returnToGroupsPage();
List<GroupData> after = app.getGroupHelper().getGroupList();
Assert.assertEquals(after.size(), before.size() + 1);
int max = 0;
for(GroupData g: after){
if(g.getId() > max){
max = g.getId();
}
}
Comparator<? super GroupData> byId = new Comparator<GroupData>() {
@Override
public int compare(GroupData o1, GroupData o2) {
return Integer.compare(o1.getId(), o2.getId());
}
};
int max2 = after.stream().max(byId).get().getId();
group.setId(max);
before.add(group);
Assert.assertEquals(new HashSet<Object>(before), new HashSet<Object>(after));
app.getSessionHelper().logout();
}
}
|
change calculation method to lambda
|
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/GroupCreationTests.java
|
change calculation method to lambda
|
|
Java
|
apache-2.0
|
e15f75854fb7ec8dfb1d30e997bbaf0a0516c566
| 0
|
google/nomulus,google/nomulus,google/nomulus,google/nomulus,google/nomulus,google/nomulus
|
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// 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 google.registry.model.host;
import static com.google.common.collect.Sets.difference;
import static com.google.common.collect.Sets.union;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.model.ofy.Ofy.RECOMMENDED_MEMCACHE_EXPIRATION;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.IgnoreSave;
import com.googlecode.objectify.annotation.Index;
import com.googlecode.objectify.condition.IfNull;
import google.registry.model.EppResource;
import google.registry.model.EppResource.ForeignKeyedEppResource;
import google.registry.model.annotations.ExternalMessagingName;
import google.registry.model.annotations.ReportedOn;
import google.registry.model.domain.DomainResource;
import google.registry.model.eppcommon.StatusValue;
import google.registry.model.transfer.TransferData;
import google.registry.model.transfer.TransferStatus;
import java.net.InetAddress;
import java.util.Set;
import org.joda.time.DateTime;
/**
* A persistable Host resource including mutable and non-mutable fields.
*
* <p>A host's {@link TransferData} is stored on the superordinate domain. Non-subordinate hosts
* don't carry a full set of TransferData; all they have is lastTransferTime.
*
* @see <a href="https://tools.ietf.org/html/rfc5732">RFC 5732</a>
*/
@Cache(expirationSeconds = RECOMMENDED_MEMCACHE_EXPIRATION)
@ReportedOn
@Entity
@ExternalMessagingName("host")
public class HostResource extends EppResource implements ForeignKeyedEppResource {
/**
* Fully qualified hostname, which is a unique identifier for this host.
*
* <p>This is only unique in the sense that for any given lifetime specified as the time range
* from (creationTime, deletionTime) there can only be one host in the datastore with this name.
* However, there can be many hosts with the same name and non-overlapping lifetimes.
*/
@Index
String fullyQualifiedHostName;
/** IP Addresses for this host. Can be null if this is an external host. */
@Index
Set<InetAddress> inetAddresses;
/** The superordinate domain of this host, or null if this is an external host. */
@Index
@IgnoreSave(IfNull.class)
@DoNotHydrate
Key<DomainResource> superordinateDomain;
/**
* The time that this resource was last transferred.
*
* <p>Can be null if the resource has never been transferred.
*/
DateTime lastTransferTime;
/**
* The most recent time that the superordinate domain was changed, or null if this host is
* external.
*/
DateTime lastSuperordinateChange;
public String getFullyQualifiedHostName() {
return fullyQualifiedHostName;
}
public Key<DomainResource> getSuperordinateDomain() {
return superordinateDomain;
}
public ImmutableSet<InetAddress> getInetAddresses() {
return nullToEmptyImmutableCopy(inetAddresses);
}
public DateTime getLastTransferTime() {
return lastTransferTime;
}
public DateTime getLastSuperordinateChange() {
return lastSuperordinateChange;
}
@Override
public String getForeignKey() {
return fullyQualifiedHostName;
}
@Override
public HostResource cloneProjectedAtTime(DateTime now) {
Builder builder = this.asBuilder();
if (superordinateDomain == null) {
// If this was a subordinate host to a domain that was being transferred, there might be a
// pending transfer still extant, so remove it.
builder.removeStatusValue(StatusValue.PENDING_TRANSFER);
} else {
// For hosts with superordinate domains, the client id, last transfer time, and transfer
// status value need to be read off the domain projected to the correct time.
DomainResource domainAtTime = ofy().load().key(superordinateDomain).now()
.cloneProjectedAtTime(now);
builder.setCurrentSponsorClientId(domainAtTime.getCurrentSponsorClientId());
// If the superordinate domain's last transfer time is what is relevant, because the host's
// superordinate domain was last changed less recently than the domain's last transfer, then
// use the last transfer time on the domain.
if (Optional.fromNullable(lastSuperordinateChange).or(START_OF_TIME)
.isBefore(Optional.fromNullable(domainAtTime.getLastTransferTime()).or(START_OF_TIME))) {
builder.setLastTransferTime(domainAtTime.getLastTransferTime());
}
// Copy the transfer status from the superordinate domain onto the host, because the host's
// doesn't matter and the superordinate domain always has the canonical data.
TransferStatus domainTransferStatus = domainAtTime.getTransferData().getTransferStatus();
if (TransferStatus.PENDING.equals(domainTransferStatus)) {
builder.addStatusValue(StatusValue.PENDING_TRANSFER);
} else {
builder.removeStatusValue(StatusValue.PENDING_TRANSFER);
}
}
return builder.build();
}
@Override
public Builder asBuilder() {
return new Builder(clone(this));
}
/** A builder for constructing {@link HostResource}, since it is immutable. */
public static class Builder extends EppResource.Builder<HostResource, Builder> {
public Builder() {}
private Builder(HostResource instance) {
super(instance);
}
public Builder setFullyQualifiedHostName(String fullyQualifiedHostName) {
getInstance().fullyQualifiedHostName = fullyQualifiedHostName;
return this;
}
public Builder setInetAddresses(ImmutableSet<InetAddress> inetAddresses) {
getInstance().inetAddresses = inetAddresses;
return this;
}
public Builder setLastSuperordinateChange(DateTime lastSuperordinateChange) {
getInstance().lastSuperordinateChange = lastSuperordinateChange;
return this;
}
public Builder addInetAddresses(ImmutableSet<InetAddress> inetAddresses) {
return setInetAddresses(ImmutableSet.copyOf(
union(getInstance().getInetAddresses(), inetAddresses)));
}
public Builder removeInetAddresses(ImmutableSet<InetAddress> inetAddresses) {
return setInetAddresses(ImmutableSet.copyOf(
difference(getInstance().getInetAddresses(), inetAddresses)));
}
public Builder setSuperordinateDomain(Key<DomainResource> superordinateDomain) {
getInstance().superordinateDomain = superordinateDomain;
return this;
}
public Builder setLastTransferTime(DateTime lastTransferTime) {
getInstance().lastTransferTime = lastTransferTime;
return this;
}
}
}
|
java/google/registry/model/host/HostResource.java
|
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// 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 google.registry.model.host;
import static com.google.common.collect.Sets.difference;
import static com.google.common.collect.Sets.union;
import static google.registry.model.ofy.ObjectifyService.ofy;
import static google.registry.model.ofy.Ofy.RECOMMENDED_MEMCACHE_EXPIRATION;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.IgnoreSave;
import com.googlecode.objectify.annotation.Index;
import com.googlecode.objectify.condition.IfNull;
import google.registry.model.EppResource;
import google.registry.model.EppResource.ForeignKeyedEppResource;
import google.registry.model.annotations.ExternalMessagingName;
import google.registry.model.annotations.ReportedOn;
import google.registry.model.domain.DomainResource;
import google.registry.model.eppcommon.StatusValue;
import google.registry.model.transfer.TransferData;
import google.registry.model.transfer.TransferStatus;
import java.net.InetAddress;
import java.util.Set;
import org.joda.time.DateTime;
/**
* A persistable Host resource including mutable and non-mutable fields.
*
* <p>A host's {@link TransferData} is stored on the superordinate domain. Non-subordinate hosts
* don't carry a full set of TransferData; all they have is lastTransferTime.
*
* @see <a href="https://tools.ietf.org/html/rfc5732">RFC 5732</a>
*/
@Cache(expirationSeconds = RECOMMENDED_MEMCACHE_EXPIRATION)
@ReportedOn
@Entity
@ExternalMessagingName("host")
public class HostResource extends EppResource implements ForeignKeyedEppResource {
/**
* Fully qualified hostname, which is a unique identifier for this host.
*
* <p>This is only unique in the sense that for any given lifetime specified as the time range
* from (creationTime, deletionTime) there can only be one host in the datastore with this name.
* However, there can be many hosts with the same name and non-overlapping lifetimes.
*/
@Index
String fullyQualifiedHostName;
/** IP Addresses for this host. Can be null if this is an external host. */
@Index
Set<InetAddress> inetAddresses;
/** The superordinate domain of this host, or null if this is an external host. */
@Index
@IgnoreSave(IfNull.class)
@DoNotHydrate
Key<DomainResource> superordinateDomain;
/**
* The time that this resource was last transferred.
*
* <p>Can be null if the resource has never been transferred.
*/
DateTime lastTransferTime;
/**
* The most recent time that the superordinate domain was changed, or null if this host is
* external.
*/
DateTime lastSuperordinateChange;
public String getFullyQualifiedHostName() {
return fullyQualifiedHostName;
}
public Key<DomainResource> getSuperordinateDomain() {
return superordinateDomain;
}
public ImmutableSet<InetAddress> getInetAddresses() {
return nullToEmptyImmutableCopy(inetAddresses);
}
public DateTime getLastTransferTime() {
return lastTransferTime;
}
public DateTime getLastSuperordinateChange() {
return lastSuperordinateChange;
}
@Override
public String getForeignKey() {
return fullyQualifiedHostName;
}
@Override
public HostResource cloneProjectedAtTime(DateTime now) {
Builder builder = this.asBuilder();
if (superordinateDomain == null) {
// If this was a subordinate host to a domain that was being transferred, there might be a
// pending transfer still extant, so remove it.
builder.removeStatusValue(StatusValue.PENDING_TRANSFER);
} else {
// For hosts with superordinate domains, the client id, last transfer time, and transfer
// status value need to be read off the domain projected to the correct time.
DomainResource domainAtTime = ofy().load().key(superordinateDomain).now()
.cloneProjectedAtTime(now);
builder.setCurrentSponsorClientId(domainAtTime.getCurrentSponsorClientId());
// If the superordinate domain's last transfer time is what is relevant, because the host's
// superordinate domain was last changed less recently than the domain's last transfer, then
// use the last transfer time on the domain.
if (Optional.fromNullable(lastSuperordinateChange).or(START_OF_TIME)
.isBefore(Optional.fromNullable(domainAtTime.getLastTransferTime()).or(START_OF_TIME))) {
builder.setLastTransferTime(domainAtTime.getLastTransferTime());
}
// Copy the transfer status from the superordinate domain onto the host, because the host's
// doesn't matter and the superordinate domain always has the canonical data.
TransferStatus domainTransferStatus = domainAtTime.getTransferData().getTransferStatus();
if (TransferStatus.PENDING.equals(domainTransferStatus)) {
builder.addStatusValue(StatusValue.PENDING_TRANSFER);
} else {
builder.removeStatusValue(StatusValue.PENDING_TRANSFER);
}
}
return builder.build();
}
@Override
public Builder asBuilder() {
return new Builder(clone(this));
}
/** A builder for constructing {@link HostResource}, since it is immutable. */
public static class Builder extends EppResource.Builder<HostResource, Builder> {
public Builder() {}
private Builder(HostResource instance) {
super(instance);
}
public Builder setFullyQualifiedHostName(String fullyQualifiedHostName) {
getInstance().fullyQualifiedHostName = fullyQualifiedHostName;
return this;
}
public Builder setInetAddresses(ImmutableSet<InetAddress> inetAddresses) {
getInstance().inetAddresses = inetAddresses;
return this;
}
public Builder setLastSuperordinateChange(DateTime lastSuperordinateChange) {
getInstance().lastSuperordinateChange = lastSuperordinateChange;
return this;
}
public Builder addInetAddresses(ImmutableSet<InetAddress> inetAddresses) {
return setInetAddresses(ImmutableSet.copyOf(
union(getInstance().getInetAddresses(), inetAddresses)));
}
public Builder removeInetAddresses(ImmutableSet<InetAddress> inetAddresses) {
return setInetAddresses(ImmutableSet.copyOf(
difference(getInstance().getInetAddresses(), inetAddresses)));
}
public Builder setSuperordinateDomain(Key<DomainResource> superordinateDomain) {
getInstance().superordinateDomain = superordinateDomain;
return this;
}
public Builder setLastTransferTime(DateTime lastTransferTime) {
getInstance().lastTransferTime = lastTransferTime;
return this;
}
@Override
public HostResource build() {
return super.build();
}
}
}
|
Remove empty method
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=146146386
|
java/google/registry/model/host/HostResource.java
|
Remove empty method
|
|
Java
|
apache-2.0
|
2ad396be429dbd71d5e6439fc1fc8774506e817c
| 0
|
AndroidX/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support,androidx/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,androidx/androidx
|
/*
* Copyright (C) 2013 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 android.support.v7.widget;
import android.content.Context;
import android.database.Observable;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.InputDeviceCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ScrollingView;
import android.support.v4.view.VelocityTrackerCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.view.accessibility.AccessibilityEventCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.view.accessibility.AccessibilityRecordCompat;
import android.support.v4.widget.EdgeEffectCompat;
import android.support.v4.widget.ScrollerCompat;
import static android.support.v7.widget.AdapterHelper.UpdateOp;
import static android.support.v7.widget.AdapterHelper.Callback;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.util.TypedValue;
import android.view.FocusFinder;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.animation.Interpolator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A flexible view for providing a limited window into a large data set.
*
* <h3>Glossary of terms:</h3>
*
* <ul>
* <li><em>Adapter:</em> A subclass of {@link Adapter} responsible for providing views
* that represent items in a data set.</li>
* <li><em>Position:</em> The position of a data item within an <em>Adapter</em>.</li>
* <li><em>Index:</em> The index of an attached child view as used in a call to
* {@link ViewGroup#getChildAt}. Contrast with <em>Position.</em></li>
* <li><em>Binding:</em> The process of preparing a child view to display data corresponding
* to a <em>position</em> within the adapter.</li>
* <li><em>Recycle (view):</em> A view previously used to display data for a specific adapter
* position may be placed in a cache for later reuse to display the same type of data again
* later. This can drastically improve performance by skipping initial layout inflation
* or construction.</li>
* <li><em>Scrap (view):</em> A child view that has entered into a temporarily detached
* state during layout. Scrap views may be reused without becoming fully detached
* from the parent RecyclerView, either unmodified if no rebinding is required or modified
* by the adapter if the view was considered <em>dirty</em>.</li>
* <li><em>Dirty (view):</em> A child view that must be rebound by the adapter before
* being displayed.</li>
* </ul>
*
* <h4>Positions in RecyclerView:</h4>
* <p>
* RecyclerView introduces an additional level of abstraction between the {@link Adapter} and
* {@link LayoutManager} to be able to detect data set changes in batches during a layout
* calculation. This saves LayoutManager from tracking adapter changes to calculate animations.
* It also helps with performance because all view bindings happen at the same time and unnecessary
* bindings are avoided.
* <p>
* For this reason, there are two types of <code>position</code> related methods in RecyclerView:
* <ul>
* <li>layout position: Position of an item in the latest layout calculation. This is the
* position from the LayoutManager's perspective.</li>
* <li>adapter position: Position of an item in the adapter. This is the position from
* the Adapter's perspective.</li>
* </ul>
* <p>
* These two positions are the same except the time between dispatching <code>adapter.notify*
* </code> events and calculating the updated layout.
* <p>
* Methods that return or receive <code>*LayoutPosition*</code> use position as of the latest
* layout calculation (e.g. {@link ViewHolder#getLayoutPosition()},
* {@link #findViewHolderForLayoutPosition(int)}). These positions include all changes until the
* last layout calculation. You can rely on these positions to be consistent with what user is
* currently seeing on the screen. For example, if you have a list of items on the screen and user
* asks for the 5<sup>th</sup> element, you should use these methods as they'll match what user
* is seeing.
* <p>
* The other set of position related methods are in the form of
* <code>*AdapterPosition*</code>. (e.g. {@link ViewHolder#getAdapterPosition()},
* {@link #findViewHolderForAdapterPosition(int)}) You should use these methods when you need to
* work with up-to-date adapter positions even if they may not have been reflected to layout yet.
* For example, if you want to access the item in the adapter on a ViewHolder click, you should use
* {@link ViewHolder#getAdapterPosition()}. Beware that these methods may not be able to calculate
* adapter positions if {@link Adapter#notifyDataSetChanged()} has been called and new layout has
* not yet been calculated. For this reasons, you should carefully handle {@link #NO_POSITION} or
* <code>null</code> results from these methods.
* <p>
* When writing a {@link LayoutManager} you almost always want to use layout positions whereas when
* writing an {@link Adapter}, you probably want to use adapter positions.
*/
public class RecyclerView extends ViewGroup implements ScrollingView {
private static final String TAG = "RecyclerView";
private static final boolean DEBUG = false;
/**
* On Kitkat, there is a bug which prevents DisplayList from being invalidated if a View is two
* levels deep(wrt to ViewHolder.itemView). DisplayList can be invalidated by setting
* View's visibility to INVISIBLE when View is detached. On Kitkat, Recycler recursively
* traverses itemView and invalidates display list for each ViewGroup that matches this
* criteria.
*/
private static final boolean FORCE_INVALIDATE_DISPLAY_LIST = Build.VERSION.SDK_INT == 19 ||
Build.VERSION.SDK_INT == 20;
private static final boolean DISPATCH_TEMP_DETACH = false;
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
public static final int NO_POSITION = -1;
public static final long NO_ID = -1;
public static final int INVALID_TYPE = -1;
/**
* Constant for use with {@link #setScrollingTouchSlop(int)}. Indicates
* that the RecyclerView should use the standard touch slop for smooth,
* continuous scrolling.
*/
public static final int TOUCH_SLOP_DEFAULT = 0;
/**
* Constant for use with {@link #setScrollingTouchSlop(int)}. Indicates
* that the RecyclerView should use the standard touch slop for scrolling
* widgets that snap to a page or other coarse-grained barrier.
*/
public static final int TOUCH_SLOP_PAGING = 1;
private static final int MAX_SCROLL_DURATION = 2000;
private final RecyclerViewDataObserver mObserver = new RecyclerViewDataObserver();
final Recycler mRecycler = new Recycler();
private SavedState mPendingSavedState;
AdapterHelper mAdapterHelper;
ChildHelper mChildHelper;
// we use this like a set
final List<View> mDisappearingViewsInLayoutPass = new ArrayList<View>();
/**
* Prior to L, there is no way to query this variable which is why we override the setter and
* track it here.
*/
private boolean mClipToPadding;
/**
* Note: this Runnable is only ever posted if:
* 1) We've been through first layout
* 2) We know we have a fixed size (mHasFixedSize)
* 3) We're attached
*/
private final Runnable mUpdateChildViewsRunnable = new Runnable() {
public void run() {
if (!mFirstLayoutComplete) {
// a layout request will happen, we should not do layout here.
return;
}
if (mDataSetHasChangedAfterLayout) {
dispatchLayout();
} else if (mAdapterHelper.hasPendingUpdates()) {
eatRequestLayout();
mAdapterHelper.preProcess();
if (!mLayoutRequestEaten) {
// We run this after pre-processing is complete so that ViewHolders have their
// final adapter positions. No need to run it if a layout is already requested.
rebindUpdatedViewHolders();
}
resumeRequestLayout(true);
}
}
};
private final Rect mTempRect = new Rect();
private Adapter mAdapter;
private LayoutManager mLayout;
private RecyclerListener mRecyclerListener;
private final ArrayList<ItemDecoration> mItemDecorations = new ArrayList<ItemDecoration>();
private final ArrayList<OnItemTouchListener> mOnItemTouchListeners =
new ArrayList<OnItemTouchListener>();
private OnItemTouchListener mActiveOnItemTouchListener;
private boolean mIsAttached;
private boolean mHasFixedSize;
private boolean mFirstLayoutComplete;
private boolean mEatRequestLayout;
private boolean mLayoutRequestEaten;
private boolean mAdapterUpdateDuringMeasure;
private final boolean mPostUpdatesOnAnimation;
private final AccessibilityManager mAccessibilityManager;
/**
* Set to true when an adapter data set changed notification is received.
* In that case, we cannot run any animations since we don't know what happened.
*/
private boolean mDataSetHasChangedAfterLayout = false;
/**
* This variable is set to true during a dispatchLayout and/or scroll.
* Some methods should not be called during these periods (e.g. adapter data change).
* Doing so will create hard to find bugs so we better check it and throw an exception.
*
* @see #assertInLayoutOrScroll(String)
* @see #assertNotInLayoutOrScroll(String)
*/
private boolean mRunningLayoutOrScroll = false;
private EdgeEffectCompat mLeftGlow, mTopGlow, mRightGlow, mBottomGlow;
ItemAnimator mItemAnimator = new DefaultItemAnimator();
private static final int INVALID_POINTER = -1;
/**
* The RecyclerView is not currently scrolling.
* @see #getScrollState()
*/
public static final int SCROLL_STATE_IDLE = 0;
/**
* The RecyclerView is currently being dragged by outside input such as user touch input.
* @see #getScrollState()
*/
public static final int SCROLL_STATE_DRAGGING = 1;
/**
* The RecyclerView is currently animating to a final position while not under
* outside control.
* @see #getScrollState()
*/
public static final int SCROLL_STATE_SETTLING = 2;
// Touch/scrolling handling
private int mScrollState = SCROLL_STATE_IDLE;
private int mScrollPointerId = INVALID_POINTER;
private VelocityTracker mVelocityTracker;
private int mInitialTouchX;
private int mInitialTouchY;
private int mLastTouchX;
private int mLastTouchY;
private int mTouchSlop;
private final int mMinFlingVelocity;
private final int mMaxFlingVelocity;
// This value is used when handling generic motion events.
private float mScrollFactor = Float.MIN_VALUE;
private final ViewFlinger mViewFlinger = new ViewFlinger();
final State mState = new State();
private OnScrollListener mScrollListener;
// For use in item animations
boolean mItemsAddedOrRemoved = false;
boolean mItemsChanged = false;
private ItemAnimator.ItemAnimatorListener mItemAnimatorListener =
new ItemAnimatorRestoreListener();
private boolean mPostedAnimatorRunner = false;
private RecyclerViewAccessibilityDelegate mAccessibilityDelegate;
// simple array to keep min and max child position during a layout calculation
// preserved not to create a new one in each layout pass
private final int[] mMinMaxLayoutPositions = new int[2];
private Runnable mItemAnimatorRunner = new Runnable() {
@Override
public void run() {
if (mItemAnimator != null) {
mItemAnimator.runPendingAnimations();
}
mPostedAnimatorRunner = false;
}
};
private static final Interpolator sQuinticInterpolator = new Interpolator() {
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
public RecyclerView(Context context) {
this(context, null);
}
public RecyclerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final int version = Build.VERSION.SDK_INT;
mPostUpdatesOnAnimation = version >= 16;
final ViewConfiguration vc = ViewConfiguration.get(context);
mTouchSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
setWillNotDraw(ViewCompat.getOverScrollMode(this) == ViewCompat.OVER_SCROLL_NEVER);
mItemAnimator.setListener(mItemAnimatorListener);
initAdapterManager();
initChildrenHelper();
// If not explicitly specified this view is important for accessibility.
if (ViewCompat.getImportantForAccessibility(this)
== ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
ViewCompat.setImportantForAccessibility(this,
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
mAccessibilityManager = (AccessibilityManager) getContext()
.getSystemService(Context.ACCESSIBILITY_SERVICE);
setAccessibilityDelegateCompat(new RecyclerViewAccessibilityDelegate(this));
}
/**
* Returns the accessibility delegate compatibility implementation used by the RecyclerView.
* @return An instance of AccessibilityDelegateCompat used by RecyclerView
*/
public RecyclerViewAccessibilityDelegate getCompatAccessibilityDelegate() {
return mAccessibilityDelegate;
}
/**
* Sets the accessibility delegate compatibility implementation used by RecyclerView.
* @param accessibilityDelegate The accessibility delegate to be used by RecyclerView.
*/
public void setAccessibilityDelegateCompat(
RecyclerViewAccessibilityDelegate accessibilityDelegate) {
mAccessibilityDelegate = accessibilityDelegate;
ViewCompat.setAccessibilityDelegate(this, mAccessibilityDelegate);
}
private void initChildrenHelper() {
mChildHelper = new ChildHelper(new ChildHelper.Callback() {
@Override
public int getChildCount() {
return RecyclerView.this.getChildCount();
}
@Override
public void addView(View child, int index) {
RecyclerView.this.addView(child, index);
dispatchChildAttached(child);
}
@Override
public int indexOfChild(View view) {
return RecyclerView.this.indexOfChild(view);
}
@Override
public void removeViewAt(int index) {
final View child = RecyclerView.this.getChildAt(index);
if (child != null) {
dispatchChildDetached(child);
}
RecyclerView.this.removeViewAt(index);
}
@Override
public View getChildAt(int offset) {
return RecyclerView.this.getChildAt(offset);
}
@Override
public void removeAllViews() {
final int count = getChildCount();
for (int i = 0; i < count; i ++) {
dispatchChildDetached(getChildAt(i));
}
RecyclerView.this.removeAllViews();
}
@Override
public ViewHolder getChildViewHolder(View view) {
return getChildViewHolderInt(view);
}
@Override
public void attachViewToParent(View child, int index,
ViewGroup.LayoutParams layoutParams) {
final ViewHolder vh = getChildViewHolderInt(child);
if (vh != null) {
if (!vh.isTmpDetached() && !vh.shouldIgnore()) {
throw new IllegalArgumentException("Called attach on a child which is not"
+ " detached: " + vh);
}
if (DEBUG) {
Log.d(TAG, "reAttach " + vh);
}
vh.clearTmpDetachFlag();
}
RecyclerView.this.attachViewToParent(child, index, layoutParams);
}
@Override
public void detachViewFromParent(int offset) {
final View view = getChildAt(offset);
if (view != null) {
final ViewHolder vh = getChildViewHolderInt(view);
if (vh != null) {
if (vh.isTmpDetached() && !vh.shouldIgnore()) {
throw new IllegalArgumentException("called detach on an already"
+ " detached child " + vh);
}
if (DEBUG) {
Log.d(TAG, "tmpDetach " + vh);
}
vh.addFlags(ViewHolder.FLAG_TMP_DETACHED);
}
}
RecyclerView.this.detachViewFromParent(offset);
}
});
}
void initAdapterManager() {
mAdapterHelper = new AdapterHelper(new Callback() {
@Override
public ViewHolder findViewHolder(int position) {
final ViewHolder vh = findViewHolderForPosition(position, true);
if (vh == null) {
return null;
}
// ensure it is not hidden because for adapter helper, the only thing matter is that
// LM thinks view is a child.
if (mChildHelper.isHidden(vh.itemView)) {
if (DEBUG) {
Log.d(TAG, "assuming view holder cannot be find because it is hidden");
}
return null;
}
return vh;
}
@Override
public void offsetPositionsForRemovingInvisible(int start, int count) {
offsetPositionRecordsForRemove(start, count, true);
mItemsAddedOrRemoved = true;
mState.mDeletedInvisibleItemCountSincePreviousLayout += count;
}
@Override
public void offsetPositionsForRemovingLaidOutOrNewView(int positionStart, int itemCount) {
offsetPositionRecordsForRemove(positionStart, itemCount, false);
mItemsAddedOrRemoved = true;
}
@Override
public void markViewHoldersUpdated(int positionStart, int itemCount) {
viewRangeUpdate(positionStart, itemCount);
mItemsChanged = true;
}
@Override
public void onDispatchFirstPass(UpdateOp op) {
dispatchUpdate(op);
}
void dispatchUpdate(UpdateOp op) {
switch (op.cmd) {
case UpdateOp.ADD:
mLayout.onItemsAdded(RecyclerView.this, op.positionStart, op.itemCount);
break;
case UpdateOp.REMOVE:
mLayout.onItemsRemoved(RecyclerView.this, op.positionStart, op.itemCount);
break;
case UpdateOp.UPDATE:
mLayout.onItemsUpdated(RecyclerView.this, op.positionStart, op.itemCount);
break;
case UpdateOp.MOVE:
mLayout.onItemsMoved(RecyclerView.this, op.positionStart, op.itemCount, 1);
break;
}
}
@Override
public void onDispatchSecondPass(UpdateOp op) {
dispatchUpdate(op);
}
@Override
public void offsetPositionsForAdd(int positionStart, int itemCount) {
offsetPositionRecordsForInsert(positionStart, itemCount);
mItemsAddedOrRemoved = true;
}
@Override
public void offsetPositionsForMove(int from, int to) {
offsetPositionRecordsForMove(from, to);
// should we create mItemsMoved ?
mItemsAddedOrRemoved = true;
}
});
}
/**
* RecyclerView can perform several optimizations if it can know in advance that changes in
* adapter content cannot change the size of the RecyclerView itself.
* If your use of RecyclerView falls into this category, set this to true.
*
* @param hasFixedSize true if adapter changes cannot affect the size of the RecyclerView.
*/
public void setHasFixedSize(boolean hasFixedSize) {
mHasFixedSize = hasFixedSize;
}
/**
* @return true if the app has specified that changes in adapter content cannot change
* the size of the RecyclerView itself.
*/
public boolean hasFixedSize() {
return mHasFixedSize;
}
@Override
public void setClipToPadding(boolean clipToPadding) {
if (clipToPadding != mClipToPadding) {
invalidateGlows();
}
mClipToPadding = clipToPadding;
super.setClipToPadding(clipToPadding);
if (mFirstLayoutComplete) {
requestLayout();
}
}
/**
* Configure the scrolling touch slop for a specific use case.
*
* Set up the RecyclerView's scrolling motion threshold based on common usages.
* Valid arguments are {@link #TOUCH_SLOP_DEFAULT} and {@link #TOUCH_SLOP_PAGING}.
*
* @param slopConstant One of the <code>TOUCH_SLOP_</code> constants representing
* the intended usage of this RecyclerView
*/
public void setScrollingTouchSlop(int slopConstant) {
final ViewConfiguration vc = ViewConfiguration.get(getContext());
switch (slopConstant) {
default:
Log.w(TAG, "setScrollingTouchSlop(): bad argument constant "
+ slopConstant + "; using default value");
// fall-through
case TOUCH_SLOP_DEFAULT:
mTouchSlop = vc.getScaledTouchSlop();
break;
case TOUCH_SLOP_PAGING:
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(vc);
break;
}
}
/**
* Swaps the current adapter with the provided one. It is similar to
* {@link #setAdapter(Adapter)} but assumes existing adapter and the new adapter uses the same
* {@link ViewHolder} and does not clear the RecycledViewPool.
* <p>
* Note that it still calls onAdapterChanged callbacks.
*
* @param adapter The new adapter to set, or null to set no adapter.
* @param removeAndRecycleExistingViews If set to true, RecyclerView will recycle all existing
* Views. If adapters have stable ids and/or you want to
* animate the disappearing views, you may prefer to set
* this to false.
* @see #setAdapter(Adapter)
*/
public void swapAdapter(Adapter adapter, boolean removeAndRecycleExistingViews) {
setAdapterInternal(adapter, true, removeAndRecycleExistingViews);
setDataSetChangedAfterLayout();
requestLayout();
}
/**
* Set a new adapter to provide child views on demand.
* <p>
* When adapter is changed, all existing views are recycled back to the pool. If the pool has
* only one adapter, it will be cleared.
*
* @param adapter The new adapter to set, or null to set no adapter.
* @see #swapAdapter(Adapter, boolean)
*/
public void setAdapter(Adapter adapter) {
setAdapterInternal(adapter, false, true);
requestLayout();
}
/**
* Replaces the current adapter with the new one and triggers listeners.
* @param adapter The new adapter
* @param compatibleWithPrevious If true, the new adapter is using the same View Holders and
* item types with the current adapter (helps us avoid cache
* invalidation).
* @param removeAndRecycleViews If true, we'll remove and recycle all existing views. If
* compatibleWithPrevious is false, this parameter is ignored.
*/
private void setAdapterInternal(Adapter adapter, boolean compatibleWithPrevious,
boolean removeAndRecycleViews) {
if (mAdapter != null) {
mAdapter.unregisterAdapterDataObserver(mObserver);
mAdapter.onDetachedFromRecyclerView(this);
}
if (!compatibleWithPrevious || removeAndRecycleViews) {
// end all running animations
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
}
// Since animations are ended, mLayout.children should be equal to
// recyclerView.children. This may not be true if item animator's end does not work as
// expected. (e.g. not release children instantly). It is safer to use mLayout's child
// count.
if (mLayout != null) {
mLayout.removeAndRecycleAllViews(mRecycler);
mLayout.removeAndRecycleScrapInt(mRecycler);
}
// we should clear it here before adapters are swapped to ensure correct callbacks.
mRecycler.clear();
}
mAdapterHelper.reset();
final Adapter oldAdapter = mAdapter;
mAdapter = adapter;
if (adapter != null) {
adapter.registerAdapterDataObserver(mObserver);
adapter.onAttachedToRecyclerView(this);
}
if (mLayout != null) {
mLayout.onAdapterChanged(oldAdapter, mAdapter);
}
mRecycler.onAdapterChanged(oldAdapter, mAdapter, compatibleWithPrevious);
mState.mStructureChanged = true;
markKnownViewsInvalid();
}
/**
* Retrieves the previously set adapter or null if no adapter is set.
*
* @return The previously set adapter
* @see #setAdapter(Adapter)
*/
public Adapter getAdapter() {
return mAdapter;
}
/**
* Register a listener that will be notified whenever a child view is recycled.
*
* <p>This listener will be called when a LayoutManager or the RecyclerView decides
* that a child view is no longer needed. If an application associates expensive
* or heavyweight data with item views, this may be a good place to release
* or free those resources.</p>
*
* @param listener Listener to register, or null to clear
*/
public void setRecyclerListener(RecyclerListener listener) {
mRecyclerListener = listener;
}
/**
* Set the {@link LayoutManager} that this RecyclerView will use.
*
* <p>In contrast to other adapter-backed views such as {@link android.widget.ListView}
* or {@link android.widget.GridView}, RecyclerView allows client code to provide custom
* layout arrangements for child views. These arrangements are controlled by the
* {@link LayoutManager}. A LayoutManager must be provided for RecyclerView to function.</p>
*
* <p>Several default strategies are provided for common uses such as lists and grids.</p>
*
* @param layout LayoutManager to use
*/
public void setLayoutManager(LayoutManager layout) {
if (layout == mLayout) {
return;
}
// TODO We should do this switch a dispachLayout pass and animate children. There is a good
// chance that LayoutManagers will re-use views.
if (mLayout != null) {
if (mIsAttached) {
mLayout.onDetachedFromWindow(this, mRecycler);
}
mLayout.setRecyclerView(null);
}
mRecycler.clear();
mChildHelper.removeAllViewsUnfiltered();
mLayout = layout;
if (layout != null) {
if (layout.mRecyclerView != null) {
throw new IllegalArgumentException("LayoutManager " + layout +
" is already attached to a RecyclerView: " + layout.mRecyclerView);
}
mLayout.setRecyclerView(this);
if (mIsAttached) {
mLayout.onAttachedToWindow(this);
}
}
requestLayout();
}
@Override
protected Parcelable onSaveInstanceState() {
SavedState state = new SavedState(super.onSaveInstanceState());
if (mPendingSavedState != null) {
state.copyFrom(mPendingSavedState);
} else if (mLayout != null) {
state.mLayoutState = mLayout.onSaveInstanceState();
} else {
state.mLayoutState = null;
}
return state;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
mPendingSavedState = (SavedState) state;
super.onRestoreInstanceState(mPendingSavedState.getSuperState());
if (mLayout != null && mPendingSavedState.mLayoutState != null) {
mLayout.onRestoreInstanceState(mPendingSavedState.mLayoutState);
}
}
/**
* Adds a view to the animatingViews list.
* mAnimatingViews holds the child views that are currently being kept around
* purely for the purpose of being animated out of view. They are drawn as a regular
* part of the child list of the RecyclerView, but they are invisible to the LayoutManager
* as they are managed separately from the regular child views.
* @param viewHolder The ViewHolder to be removed
*/
private void addAnimatingView(ViewHolder viewHolder) {
final View view = viewHolder.itemView;
final boolean alreadyParented = view.getParent() == this;
mRecycler.unscrapView(getChildViewHolder(view));
if (viewHolder.isTmpDetached()) {
// re-attach
mChildHelper.attachViewToParent(view, -1, view.getLayoutParams(), true);
} else if(!alreadyParented) {
mChildHelper.addView(view, true);
} else {
mChildHelper.hide(view);
}
}
/**
* Removes a view from the animatingViews list.
* @param view The view to be removed
* @see #addAnimatingView(RecyclerView.ViewHolder)
* @return true if an animating view is removed
*/
private boolean removeAnimatingView(View view) {
eatRequestLayout();
final boolean removed = mChildHelper.removeViewIfHidden(view);
if (removed) {
final ViewHolder viewHolder = getChildViewHolderInt(view);
mRecycler.unscrapView(viewHolder);
mRecycler.recycleViewHolderInternal(viewHolder);
if (DEBUG) {
Log.d(TAG, "after removing animated view: " + view + ", " + this);
}
}
resumeRequestLayout(false);
return removed;
}
/**
* Return the {@link LayoutManager} currently responsible for
* layout policy for this RecyclerView.
*
* @return The currently bound LayoutManager
*/
public LayoutManager getLayoutManager() {
return mLayout;
}
/**
* Retrieve this RecyclerView's {@link RecycledViewPool}. This method will never return null;
* if no pool is set for this view a new one will be created. See
* {@link #setRecycledViewPool(RecycledViewPool) setRecycledViewPool} for more information.
*
* @return The pool used to store recycled item views for reuse.
* @see #setRecycledViewPool(RecycledViewPool)
*/
public RecycledViewPool getRecycledViewPool() {
return mRecycler.getRecycledViewPool();
}
/**
* Recycled view pools allow multiple RecyclerViews to share a common pool of scrap views.
* This can be useful if you have multiple RecyclerViews with adapters that use the same
* view types, for example if you have several data sets with the same kinds of item views
* displayed by a {@link android.support.v4.view.ViewPager ViewPager}.
*
* @param pool Pool to set. If this parameter is null a new pool will be created and used.
*/
public void setRecycledViewPool(RecycledViewPool pool) {
mRecycler.setRecycledViewPool(pool);
}
/**
* Sets a new {@link ViewCacheExtension} to be used by the Recycler.
*
* @param extension ViewCacheExtension to be used or null if you want to clear the existing one.
*
* @see {@link ViewCacheExtension#getViewForPositionAndType(Recycler, int, int)}
*/
public void setViewCacheExtension(ViewCacheExtension extension) {
mRecycler.setViewCacheExtension(extension);
}
/**
* Set the number of offscreen views to retain before adding them to the potentially shared
* {@link #getRecycledViewPool() recycled view pool}.
*
* <p>The offscreen view cache stays aware of changes in the attached adapter, allowing
* a LayoutManager to reuse those views unmodified without needing to return to the adapter
* to rebind them.</p>
*
* @param size Number of views to cache offscreen before returning them to the general
* recycled view pool
*/
public void setItemViewCacheSize(int size) {
mRecycler.setViewCacheSize(size);
}
/**
* Return the current scrolling state of the RecyclerView.
*
* @return {@link #SCROLL_STATE_IDLE}, {@link #SCROLL_STATE_DRAGGING} or
* {@link #SCROLL_STATE_SETTLING}
*/
public int getScrollState() {
return mScrollState;
}
private void setScrollState(int state) {
if (state == mScrollState) {
return;
}
if (DEBUG) {
Log.d(TAG, "setting scroll state to " + state + " from " + mScrollState, new Exception());
}
mScrollState = state;
if (state != SCROLL_STATE_SETTLING) {
stopScrollersInternal();
}
if (mScrollListener != null) {
mScrollListener.onScrollStateChanged(this, state);
}
if (mLayout != null) {
mLayout.onScrollStateChanged(state);
}
}
/**
* Add an {@link ItemDecoration} to this RecyclerView. Item decorations can
* affect both measurement and drawing of individual item views.
*
* <p>Item decorations are ordered. Decorations placed earlier in the list will
* be run/queried/drawn first for their effects on item views. Padding added to views
* will be nested; a padding added by an earlier decoration will mean further
* item decorations in the list will be asked to draw/pad within the previous decoration's
* given area.</p>
*
* @param decor Decoration to add
* @param index Position in the decoration chain to insert this decoration at. If this value
* is negative the decoration will be added at the end.
*/
public void addItemDecoration(ItemDecoration decor, int index) {
if (mLayout != null) {
mLayout.assertNotInLayoutOrScroll("Cannot add item decoration during a scroll or"
+ " layout");
}
if (mItemDecorations.isEmpty()) {
setWillNotDraw(false);
}
if (index < 0) {
mItemDecorations.add(decor);
} else {
mItemDecorations.add(index, decor);
}
markItemDecorInsetsDirty();
requestLayout();
}
/**
* Add an {@link ItemDecoration} to this RecyclerView. Item decorations can
* affect both measurement and drawing of individual item views.
*
* <p>Item decorations are ordered. Decorations placed earlier in the list will
* be run/queried/drawn first for their effects on item views. Padding added to views
* will be nested; a padding added by an earlier decoration will mean further
* item decorations in the list will be asked to draw/pad within the previous decoration's
* given area.</p>
*
* @param decor Decoration to add
*/
public void addItemDecoration(ItemDecoration decor) {
addItemDecoration(decor, -1);
}
/**
* Remove an {@link ItemDecoration} from this RecyclerView.
*
* <p>The given decoration will no longer impact the measurement and drawing of
* item views.</p>
*
* @param decor Decoration to remove
* @see #addItemDecoration(ItemDecoration)
*/
public void removeItemDecoration(ItemDecoration decor) {
if (mLayout != null) {
mLayout.assertNotInLayoutOrScroll("Cannot remove item decoration during a scroll or"
+ " layout");
}
mItemDecorations.remove(decor);
if (mItemDecorations.isEmpty()) {
setWillNotDraw(ViewCompat.getOverScrollMode(this) == ViewCompat.OVER_SCROLL_NEVER);
}
markItemDecorInsetsDirty();
requestLayout();
}
/**
* Set a listener that will be notified of any changes in scroll state or position.
*
* @param listener Listener to set or null to clear
*/
public void setOnScrollListener(OnScrollListener listener) {
mScrollListener = listener;
}
/**
* Convenience method to scroll to a certain position.
*
* RecyclerView does not implement scrolling logic, rather forwards the call to
* {@link android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)}
* @param position Scroll to this adapter position
* @see android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)
*/
public void scrollToPosition(int position) {
stopScroll();
if (mLayout == null) {
Log.e(TAG, "Cannot scroll to position a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
return;
}
mLayout.scrollToPosition(position);
awakenScrollBars();
}
/**
* Starts a smooth scroll to an adapter position.
* <p>
* To support smooth scrolling, you must override
* {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} and create a
* {@link SmoothScroller}.
* <p>
* {@link LayoutManager} is responsible for creating the actual scroll action. If you want to
* provide a custom smooth scroll logic, override
* {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} in your
* LayoutManager.
*
* @param position The adapter position to scroll to
* @see LayoutManager#smoothScrollToPosition(RecyclerView, State, int)
*/
public void smoothScrollToPosition(int position) {
if (mLayout == null) {
Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
return;
}
mLayout.smoothScrollToPosition(this, mState, position);
}
@Override
public void scrollTo(int x, int y) {
throw new UnsupportedOperationException(
"RecyclerView does not support scrolling to an absolute position.");
}
@Override
public void scrollBy(int x, int y) {
if (mLayout == null) {
Log.e(TAG, "Cannot scroll without a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
return;
}
final boolean canScrollHorizontal = mLayout.canScrollHorizontally();
final boolean canScrollVertical = mLayout.canScrollVertically();
if (canScrollHorizontal || canScrollVertical) {
scrollByInternal(canScrollHorizontal ? x : 0, canScrollVertical ? y : 0);
}
}
/**
* Helper method reflect data changes to the state.
* <p>
* Adapter changes during a scroll may trigger a crash because scroll assumes no data change
* but data actually changed.
* <p>
* This method consumes all deferred changes to avoid that case.
*/
private void consumePendingUpdateOperations() {
mUpdateChildViewsRunnable.run();
}
/**
* Does not perform bounds checking. Used by internal methods that have already validated input.
*
* @return Whether any scroll was consumed in either direction.
*/
boolean scrollByInternal(int x, int y) {
int overscrollX = 0, overscrollY = 0;
int hresult = 0, vresult = 0;
consumePendingUpdateOperations();
if (mAdapter != null) {
eatRequestLayout();
mRunningLayoutOrScroll = true;
if (x != 0) {
hresult = mLayout.scrollHorizontallyBy(x, mRecycler, mState);
overscrollX = x - hresult;
}
if (y != 0) {
vresult = mLayout.scrollVerticallyBy(y, mRecycler, mState);
overscrollY = y - vresult;
}
if (supportsChangeAnimations()) {
// Fix up shadow views used by changing animations
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; i++) {
View view = mChildHelper.getChildAt(i);
ViewHolder holder = getChildViewHolder(view);
if (holder != null && holder.mShadowingHolder != null) {
ViewHolder shadowingHolder = holder.mShadowingHolder;
View shadowingView = shadowingHolder != null ? shadowingHolder.itemView : null;
if (shadowingView != null) {
int left = view.getLeft();
int top = view.getTop();
if (left != shadowingView.getLeft() || top != shadowingView.getTop()) {
shadowingView.layout(left, top,
left + shadowingView.getWidth(),
top + shadowingView.getHeight());
}
}
}
}
}
mRunningLayoutOrScroll = false;
resumeRequestLayout(false);
}
if (!mItemDecorations.isEmpty()) {
invalidate();
}
if (ViewCompat.getOverScrollMode(this) != ViewCompat.OVER_SCROLL_NEVER) {
considerReleasingGlowsOnScroll(x, y);
pullGlows(overscrollX, overscrollY);
}
if (hresult != 0 || vresult != 0) {
notifyOnScrolled(hresult, vresult);
}
if (!awakenScrollBars()) {
invalidate();
}
return hresult != 0 || vresult != 0;
}
/**
* <p>Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal
* range. This value is used to compute the length of the thumb within the scrollbar's track.
* </p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeHorizontalScrollRange()} and {@link #computeHorizontalScrollExtent()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeHorizontalScrollOffset(RecyclerView.State)} in your
* LayoutManager. </p>
*
* @return The horizontal offset of the scrollbar's thumb
* @see android.support.v7.widget.RecyclerView.LayoutManager#computeHorizontalScrollOffset
* (RecyclerView.Adapter)
*/
@Override
public int computeHorizontalScrollOffset() {
return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollOffset(mState)
: 0;
}
/**
* <p>Compute the horizontal extent of the horizontal scrollbar's thumb within the
* horizontal range. This value is used to compute the length of the thumb within the
* scrollbar's track.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeHorizontalScrollRange()} and {@link #computeHorizontalScrollOffset()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeHorizontalScrollExtent(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The horizontal extent of the scrollbar's thumb
* @see RecyclerView.LayoutManager#computeHorizontalScrollExtent(RecyclerView.State)
*/
@Override
public int computeHorizontalScrollExtent() {
return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollExtent(mState) : 0;
}
/**
* <p>Compute the horizontal range that the horizontal scrollbar represents.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeHorizontalScrollExtent()} and {@link #computeHorizontalScrollOffset()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeHorizontalScrollRange(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The total horizontal range represented by the vertical scrollbar
* @see RecyclerView.LayoutManager#computeHorizontalScrollRange(RecyclerView.State)
*/
@Override
public int computeHorizontalScrollRange() {
return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollRange(mState) : 0;
}
/**
* <p>Compute the vertical offset of the vertical scrollbar's thumb within the vertical range.
* This value is used to compute the length of the thumb within the scrollbar's track. </p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeVerticalScrollRange()} and {@link #computeVerticalScrollExtent()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeVerticalScrollOffset(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The vertical offset of the scrollbar's thumb
* @see android.support.v7.widget.RecyclerView.LayoutManager#computeVerticalScrollOffset
* (RecyclerView.Adapter)
*/
@Override
public int computeVerticalScrollOffset() {
return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollOffset(mState) : 0;
}
/**
* <p>Compute the vertical extent of the vertical scrollbar's thumb within the vertical range.
* This value is used to compute the length of the thumb within the scrollbar's track.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeVerticalScrollRange()} and {@link #computeVerticalScrollOffset()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeVerticalScrollExtent(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The vertical extent of the scrollbar's thumb
* @see RecyclerView.LayoutManager#computeVerticalScrollExtent(RecyclerView.State)
*/
@Override
public int computeVerticalScrollExtent() {
return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollExtent(mState) : 0;
}
/**
* <p>Compute the vertical range that the vertical scrollbar represents.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeVerticalScrollExtent()} and {@link #computeVerticalScrollOffset()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeVerticalScrollRange(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The total vertical range represented by the vertical scrollbar
* @see RecyclerView.LayoutManager#computeVerticalScrollRange(RecyclerView.State)
*/
@Override
public int computeVerticalScrollRange() {
return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollRange(mState) : 0;
}
void eatRequestLayout() {
if (!mEatRequestLayout) {
mEatRequestLayout = true;
mLayoutRequestEaten = false;
}
}
void resumeRequestLayout(boolean performLayoutChildren) {
if (mEatRequestLayout) {
if (performLayoutChildren && mLayoutRequestEaten &&
mLayout != null && mAdapter != null) {
dispatchLayout();
}
mEatRequestLayout = false;
mLayoutRequestEaten = false;
}
}
/**
* Animate a scroll by the given amount of pixels along either axis.
*
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
*/
public void smoothScrollBy(int dx, int dy) {
if (mLayout == null) {
Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
return;
}
if (!mLayout.canScrollHorizontally()) {
dx = 0;
}
if (!mLayout.canScrollVertically()) {
dy = 0;
}
if (dx != 0 || dy != 0) {
mViewFlinger.smoothScrollBy(dx, dy);
}
}
/**
* Begin a standard fling with an initial velocity along each axis in pixels per second.
* If the velocity given is below the system-defined minimum this method will return false
* and no fling will occur.
*
* @param velocityX Initial horizontal velocity in pixels per second
* @param velocityY Initial vertical velocity in pixels per second
* @return true if the fling was started, false if the velocity was too low to fling or
* LayoutManager does not support scrolling in the axis fling is issued.
*
* @see LayoutManager#canScrollVertically()
* @see LayoutManager#canScrollHorizontally()
*/
public boolean fling(int velocityX, int velocityY) {
if (mLayout == null) {
Log.e(TAG, "Cannot fling without a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
return false;
}
final boolean canScrollHorizontal = mLayout.canScrollHorizontally();
final boolean canScrollVertical = mLayout.canScrollVertically();
if (!canScrollHorizontal || Math.abs(velocityX) < mMinFlingVelocity) {
velocityX = 0;
}
if (!canScrollVertical || Math.abs(velocityY) < mMinFlingVelocity) {
velocityY = 0;
}
velocityX = Math.max(-mMaxFlingVelocity, Math.min(velocityX, mMaxFlingVelocity));
velocityY = Math.max(-mMaxFlingVelocity, Math.min(velocityY, mMaxFlingVelocity));
if (velocityX != 0 || velocityY != 0) {
mViewFlinger.fling(velocityX, velocityY);
return true;
}
return false;
}
/**
* Stop any current scroll in progress, such as one started by
* {@link #smoothScrollBy(int, int)}, {@link #fling(int, int)} or a touch-initiated fling.
*/
public void stopScroll() {
setScrollState(SCROLL_STATE_IDLE);
stopScrollersInternal();
}
/**
* Similar to {@link #stopScroll()} but does not set the state.
*/
private void stopScrollersInternal() {
mViewFlinger.stop();
if (mLayout != null) {
mLayout.stopSmoothScroller();
}
}
/**
* Apply a pull to relevant overscroll glow effects
*/
private void pullGlows(int overscrollX, int overscrollY) {
if (overscrollX < 0) {
ensureLeftGlow();
mLeftGlow.onPull(-overscrollX / (float) getWidth());
} else if (overscrollX > 0) {
ensureRightGlow();
mRightGlow.onPull(overscrollX / (float) getWidth());
}
if (overscrollY < 0) {
ensureTopGlow();
mTopGlow.onPull(-overscrollY / (float) getHeight());
} else if (overscrollY > 0) {
ensureBottomGlow();
mBottomGlow.onPull(overscrollY / (float) getHeight());
}
if (overscrollX != 0 || overscrollY != 0) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
private void releaseGlows() {
boolean needsInvalidate = false;
if (mLeftGlow != null) needsInvalidate = mLeftGlow.onRelease();
if (mTopGlow != null) needsInvalidate |= mTopGlow.onRelease();
if (mRightGlow != null) needsInvalidate |= mRightGlow.onRelease();
if (mBottomGlow != null) needsInvalidate |= mBottomGlow.onRelease();
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
private void considerReleasingGlowsOnScroll(int dx, int dy) {
boolean needsInvalidate = false;
if (mLeftGlow != null && !mLeftGlow.isFinished() && dx > 0) {
needsInvalidate = mLeftGlow.onRelease();
}
if (mRightGlow != null && !mRightGlow.isFinished() && dx < 0) {
needsInvalidate |= mRightGlow.onRelease();
}
if (mTopGlow != null && !mTopGlow.isFinished() && dy > 0) {
needsInvalidate |= mTopGlow.onRelease();
}
if (mBottomGlow != null && !mBottomGlow.isFinished() && dy < 0) {
needsInvalidate |= mBottomGlow.onRelease();
}
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
void absorbGlows(int velocityX, int velocityY) {
if (velocityX < 0) {
ensureLeftGlow();
mLeftGlow.onAbsorb(-velocityX);
} else if (velocityX > 0) {
ensureRightGlow();
mRightGlow.onAbsorb(velocityX);
}
if (velocityY < 0) {
ensureTopGlow();
mTopGlow.onAbsorb(-velocityY);
} else if (velocityY > 0) {
ensureBottomGlow();
mBottomGlow.onAbsorb(velocityY);
}
if (velocityX != 0 || velocityY != 0) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
void ensureLeftGlow() {
if (mLeftGlow != null) {
return;
}
mLeftGlow = new EdgeEffectCompat(getContext());
if (mClipToPadding) {
mLeftGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
getMeasuredWidth() - getPaddingLeft() - getPaddingRight());
} else {
mLeftGlow.setSize(getMeasuredHeight(), getMeasuredWidth());
}
}
void ensureRightGlow() {
if (mRightGlow != null) {
return;
}
mRightGlow = new EdgeEffectCompat(getContext());
if (mClipToPadding) {
mRightGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
getMeasuredWidth() - getPaddingLeft() - getPaddingRight());
} else {
mRightGlow.setSize(getMeasuredHeight(), getMeasuredWidth());
}
}
void ensureTopGlow() {
if (mTopGlow != null) {
return;
}
mTopGlow = new EdgeEffectCompat(getContext());
if (mClipToPadding) {
mTopGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
getMeasuredHeight() - getPaddingTop() - getPaddingBottom());
} else {
mTopGlow.setSize(getMeasuredWidth(), getMeasuredHeight());
}
}
void ensureBottomGlow() {
if (mBottomGlow != null) {
return;
}
mBottomGlow = new EdgeEffectCompat(getContext());
if (mClipToPadding) {
mBottomGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
getMeasuredHeight() - getPaddingTop() - getPaddingBottom());
} else {
mBottomGlow.setSize(getMeasuredWidth(), getMeasuredHeight());
}
}
void invalidateGlows() {
mLeftGlow = mRightGlow = mTopGlow = mBottomGlow = null;
}
// Focus handling
@Override
public View focusSearch(View focused, int direction) {
View result = mLayout.onInterceptFocusSearch(focused, direction);
if (result != null) {
return result;
}
final FocusFinder ff = FocusFinder.getInstance();
result = ff.findNextFocus(this, focused, direction);
if (result == null && mAdapter != null && mLayout != null) {
eatRequestLayout();
result = mLayout.onFocusSearchFailed(focused, direction, mRecycler, mState);
resumeRequestLayout(false);
}
return result != null ? result : super.focusSearch(focused, direction);
}
@Override
public void requestChildFocus(View child, View focused) {
if (!mLayout.onRequestChildFocus(this, mState, child, focused) && focused != null) {
mTempRect.set(0, 0, focused.getWidth(), focused.getHeight());
// get item decor offsets w/o refreshing. If they are invalid, there will be another
// layout pass to fix them, then it is LayoutManager's responsibility to keep focused
// View in viewport.
final ViewGroup.LayoutParams focusedLayoutParams = focused.getLayoutParams();
if (focusedLayoutParams instanceof LayoutParams) {
// if focused child has item decors, use them. Otherwise, ignore.
final LayoutParams lp = (LayoutParams) focusedLayoutParams;
if (!lp.mInsetsDirty) {
final Rect insets = lp.mDecorInsets;
mTempRect.left -= insets.left;
mTempRect.right += insets.right;
mTempRect.top -= insets.top;
mTempRect.bottom += insets.bottom;
}
}
offsetDescendantRectToMyCoords(focused, mTempRect);
offsetRectIntoDescendantCoords(child, mTempRect);
requestChildRectangleOnScreen(child, mTempRect, !mFirstLayoutComplete);
}
super.requestChildFocus(child, focused);
}
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
return mLayout.requestChildRectangleOnScreen(this, child, rect, immediate);
}
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
if (!mLayout.onAddFocusables(this, views, direction, focusableMode)) {
super.addFocusables(views, direction, focusableMode);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mIsAttached = true;
mFirstLayoutComplete = false;
if (mLayout != null) {
mLayout.onAttachedToWindow(this);
}
mPostedAnimatorRunner = false;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
}
mFirstLayoutComplete = false;
stopScroll();
mIsAttached = false;
if (mLayout != null) {
mLayout.onDetachedFromWindow(this, mRecycler);
}
removeCallbacks(mItemAnimatorRunner);
}
/**
* Checks if RecyclerView is in the middle of a layout or scroll and throws an
* {@link IllegalStateException} if it <b>is not</b>.
*
* @param message The message for the exception. Can be null.
* @see #assertNotInLayoutOrScroll(String)
*/
void assertInLayoutOrScroll(String message) {
if (!mRunningLayoutOrScroll) {
if (message == null) {
throw new IllegalStateException("Cannot call this method unless RecyclerView is "
+ "computing a layout or scrolling");
}
throw new IllegalStateException(message);
}
}
/**
* Checks if RecyclerView is in the middle of a layout or scroll and throws an
* {@link IllegalStateException} if it <b>is</b>.
*
* @param message The message for the exception. Can be null.
* @see #assertInLayoutOrScroll(String)
*/
void assertNotInLayoutOrScroll(String message) {
if (mRunningLayoutOrScroll) {
if (message == null) {
throw new IllegalStateException("Cannot call this method while RecyclerView is "
+ "computing a layout or scrolling");
}
throw new IllegalStateException(message);
}
}
/**
* Add an {@link OnItemTouchListener} to intercept touch events before they are dispatched
* to child views or this view's standard scrolling behavior.
*
* <p>Client code may use listeners to implement item manipulation behavior. Once a listener
* returns true from
* {@link OnItemTouchListener#onInterceptTouchEvent(RecyclerView, MotionEvent)} its
* {@link OnItemTouchListener#onTouchEvent(RecyclerView, MotionEvent)} method will be called
* for each incoming MotionEvent until the end of the gesture.</p>
*
* @param listener Listener to add
*/
public void addOnItemTouchListener(OnItemTouchListener listener) {
mOnItemTouchListeners.add(listener);
}
/**
* Remove an {@link OnItemTouchListener}. It will no longer be able to intercept touch events.
*
* @param listener Listener to remove
*/
public void removeOnItemTouchListener(OnItemTouchListener listener) {
mOnItemTouchListeners.remove(listener);
if (mActiveOnItemTouchListener == listener) {
mActiveOnItemTouchListener = null;
}
}
private boolean dispatchOnItemTouchIntercept(MotionEvent e) {
final int action = e.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_DOWN) {
mActiveOnItemTouchListener = null;
}
final int listenerCount = mOnItemTouchListeners.size();
for (int i = 0; i < listenerCount; i++) {
final OnItemTouchListener listener = mOnItemTouchListeners.get(i);
if (listener.onInterceptTouchEvent(this, e) && action != MotionEvent.ACTION_CANCEL) {
mActiveOnItemTouchListener = listener;
return true;
}
}
return false;
}
private boolean dispatchOnItemTouch(MotionEvent e) {
final int action = e.getAction();
if (mActiveOnItemTouchListener != null) {
if (action == MotionEvent.ACTION_DOWN) {
// Stale state from a previous gesture, we're starting a new one. Clear it.
mActiveOnItemTouchListener = null;
} else {
mActiveOnItemTouchListener.onTouchEvent(this, e);
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
// Clean up for the next gesture.
mActiveOnItemTouchListener = null;
}
return true;
}
}
// Listeners will have already received the ACTION_DOWN via dispatchOnItemTouchIntercept
// as called from onInterceptTouchEvent; skip it.
if (action != MotionEvent.ACTION_DOWN) {
final int listenerCount = mOnItemTouchListeners.size();
for (int i = 0; i < listenerCount; i++) {
final OnItemTouchListener listener = mOnItemTouchListeners.get(i);
if (listener.onInterceptTouchEvent(this, e)) {
mActiveOnItemTouchListener = listener;
return true;
}
}
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if (dispatchOnItemTouchIntercept(e)) {
cancelTouch();
return true;
}
final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
final boolean canScrollVertically = mLayout.canScrollVertically();
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(e);
final int action = MotionEventCompat.getActionMasked(e);
final int actionIndex = MotionEventCompat.getActionIndex(e);
switch (action) {
case MotionEvent.ACTION_DOWN:
mScrollPointerId = MotionEventCompat.getPointerId(e, 0);
mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);
if (mScrollState == SCROLL_STATE_SETTLING) {
getParent().requestDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN:
mScrollPointerId = MotionEventCompat.getPointerId(e, actionIndex);
mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, actionIndex) + 0.5f);
mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, actionIndex) + 0.5f);
break;
case MotionEvent.ACTION_MOVE: {
final int index = MotionEventCompat.findPointerIndex(e, mScrollPointerId);
if (index < 0) {
Log.e(TAG, "Error processing scroll; pointer index for id " +
mScrollPointerId + " not found. Did any MotionEvents get skipped?");
return false;
}
final int x = (int) (MotionEventCompat.getX(e, index) + 0.5f);
final int y = (int) (MotionEventCompat.getY(e, index) + 0.5f);
if (mScrollState != SCROLL_STATE_DRAGGING) {
final int dx = x - mInitialTouchX;
final int dy = y - mInitialTouchY;
boolean startScroll = false;
if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) {
mLastTouchX = mInitialTouchX + mTouchSlop * (dx < 0 ? -1 : 1);
startScroll = true;
}
if (canScrollVertically && Math.abs(dy) > mTouchSlop) {
mLastTouchY = mInitialTouchY + mTouchSlop * (dy < 0 ? -1 : 1);
startScroll = true;
}
if (startScroll) {
setScrollState(SCROLL_STATE_DRAGGING);
}
}
} break;
case MotionEventCompat.ACTION_POINTER_UP: {
onPointerUp(e);
} break;
case MotionEvent.ACTION_UP: {
mVelocityTracker.clear();
} break;
case MotionEvent.ACTION_CANCEL: {
cancelTouch();
}
}
return mScrollState == SCROLL_STATE_DRAGGING;
}
@Override
public boolean onTouchEvent(MotionEvent e) {
if (dispatchOnItemTouch(e)) {
cancelTouch();
return true;
}
final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
final boolean canScrollVertically = mLayout.canScrollVertically();
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(e);
final int action = MotionEventCompat.getActionMasked(e);
final int actionIndex = MotionEventCompat.getActionIndex(e);
switch (action) {
case MotionEvent.ACTION_DOWN: {
mScrollPointerId = MotionEventCompat.getPointerId(e, 0);
mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);
} break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
mScrollPointerId = MotionEventCompat.getPointerId(e, actionIndex);
mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, actionIndex) + 0.5f);
mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, actionIndex) + 0.5f);
} break;
case MotionEvent.ACTION_MOVE: {
final int index = MotionEventCompat.findPointerIndex(e, mScrollPointerId);
if (index < 0) {
Log.e(TAG, "Error processing scroll; pointer index for id " +
mScrollPointerId + " not found. Did any MotionEvents get skipped?");
return false;
}
final int x = (int) (MotionEventCompat.getX(e, index) + 0.5f);
final int y = (int) (MotionEventCompat.getY(e, index) + 0.5f);
if (mScrollState != SCROLL_STATE_DRAGGING) {
final int dx = x - mInitialTouchX;
final int dy = y - mInitialTouchY;
boolean startScroll = false;
if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) {
mLastTouchX = mInitialTouchX + mTouchSlop * (dx < 0 ? -1 : 1);
startScroll = true;
}
if (canScrollVertically && Math.abs(dy) > mTouchSlop) {
mLastTouchY = mInitialTouchY + mTouchSlop * (dy < 0 ? -1 : 1);
startScroll = true;
}
if (startScroll) {
setScrollState(SCROLL_STATE_DRAGGING);
}
}
if (mScrollState == SCROLL_STATE_DRAGGING) {
final int dx = x - mLastTouchX;
final int dy = y - mLastTouchY;
if (scrollByInternal(
canScrollHorizontally ? -dx : 0, canScrollVertically ? -dy : 0)) {
getParent().requestDisallowInterceptTouchEvent(true);
}
}
mLastTouchX = x;
mLastTouchY = y;
} break;
case MotionEventCompat.ACTION_POINTER_UP: {
onPointerUp(e);
} break;
case MotionEvent.ACTION_UP: {
mVelocityTracker.computeCurrentVelocity(1000, mMaxFlingVelocity);
final float xvel = canScrollHorizontally ?
-VelocityTrackerCompat.getXVelocity(mVelocityTracker, mScrollPointerId) : 0;
final float yvel = canScrollVertically ?
-VelocityTrackerCompat.getYVelocity(mVelocityTracker, mScrollPointerId) : 0;
if (!((xvel != 0 || yvel != 0) && fling((int) xvel, (int) yvel))) {
setScrollState(SCROLL_STATE_IDLE);
}
mVelocityTracker.clear();
releaseGlows();
} break;
case MotionEvent.ACTION_CANCEL: {
cancelTouch();
} break;
}
return true;
}
private void cancelTouch() {
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
releaseGlows();
setScrollState(SCROLL_STATE_IDLE);
}
private void onPointerUp(MotionEvent e) {
final int actionIndex = MotionEventCompat.getActionIndex(e);
if (MotionEventCompat.getPointerId(e, actionIndex) == mScrollPointerId) {
// Pick a new pointer to pick up the slack.
final int newIndex = actionIndex == 0 ? 1 : 0;
mScrollPointerId = MotionEventCompat.getPointerId(e, newIndex);
mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, newIndex) + 0.5f);
mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, newIndex) + 0.5f);
}
}
// @Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (mLayout == null) {
return false;
}
if ((MotionEventCompat.getSource(event) & InputDeviceCompat.SOURCE_CLASS_POINTER) != 0) {
if (event.getAction() == MotionEventCompat.ACTION_SCROLL) {
final float vScroll, hScroll;
if (mLayout.canScrollVertically()) {
vScroll = MotionEventCompat
.getAxisValue(event, MotionEventCompat.AXIS_VSCROLL);
} else {
vScroll = 0f;
}
if (mLayout.canScrollHorizontally()) {
hScroll = MotionEventCompat
.getAxisValue(event, MotionEventCompat.AXIS_HSCROLL);
} else {
hScroll = 0f;
}
if (vScroll != 0 || hScroll != 0) {
final float scrollFactor = getScrollFactor();
scrollBy((int) (hScroll * scrollFactor), (int) (vScroll * scrollFactor));
}
}
}
return false;
}
/**
* Ported from View.getVerticalScrollFactor.
*/
private float getScrollFactor() {
if (mScrollFactor == Float.MIN_VALUE) {
TypedValue outValue = new TypedValue();
if (getContext().getTheme().resolveAttribute(
android.R.attr.listPreferredItemHeight, outValue, true)) {
mScrollFactor = outValue.getDimension(
getContext().getResources().getDisplayMetrics());
} else {
return 0; //listPreferredItemHeight is not defined, no generic scrolling
}
}
return mScrollFactor;
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
if (mAdapterUpdateDuringMeasure) {
eatRequestLayout();
processAdapterUpdatesAndSetAnimationFlags();
if (mState.mRunPredictiveAnimations) {
// TODO: try to provide a better approach.
// When RV decides to run predictive animations, we need to measure in pre-layout
// state so that pre-layout pass results in correct layout.
// On the other hand, this will prevent the layout manager from resizing properly.
mState.mInPreLayout = true;
} else {
// consume remaining updates to provide a consistent state with the layout pass.
mAdapterHelper.consumeUpdatesInOnePass();
mState.mInPreLayout = false;
}
mAdapterUpdateDuringMeasure = false;
resumeRequestLayout(false);
}
if (mAdapter != null) {
mState.mItemCount = mAdapter.getItemCount();
} else {
mState.mItemCount = 0;
}
if (mLayout == null) {
defaultOnMeasure(widthSpec, heightSpec);
} else {
mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);
}
mState.mInPreLayout = false; // clear
}
/**
* Used when onMeasure is called before layout manager is set
*/
private void defaultOnMeasure(int widthSpec, int heightSpec) {
final int widthMode = MeasureSpec.getMode(widthSpec);
final int heightMode = MeasureSpec.getMode(heightSpec);
final int widthSize = MeasureSpec.getSize(widthSpec);
final int heightSize = MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
switch (widthMode) {
case MeasureSpec.EXACTLY:
case MeasureSpec.AT_MOST:
width = widthSize;
break;
case MeasureSpec.UNSPECIFIED:
default:
width = ViewCompat.getMinimumWidth(this);
break;
}
switch (heightMode) {
case MeasureSpec.EXACTLY:
case MeasureSpec.AT_MOST:
height = heightSize;
break;
case MeasureSpec.UNSPECIFIED:
default:
height = ViewCompat.getMinimumHeight(this);
break;
}
setMeasuredDimension(width, height);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w != oldw || h != oldh) {
invalidateGlows();
}
}
/**
* Sets the {@link ItemAnimator} that will handle animations involving changes
* to the items in this RecyclerView. By default, RecyclerView instantiates and
* uses an instance of {@link DefaultItemAnimator}. Whether item animations are
* enabled for the RecyclerView depends on the ItemAnimator and whether
* the LayoutManager {@link LayoutManager#supportsPredictiveItemAnimations()
* supports item animations}.
*
* @param animator The ItemAnimator being set. If null, no animations will occur
* when changes occur to the items in this RecyclerView.
*/
public void setItemAnimator(ItemAnimator animator) {
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
mItemAnimator.setListener(null);
}
mItemAnimator = animator;
if (mItemAnimator != null) {
mItemAnimator.setListener(mItemAnimatorListener);
}
}
/**
* Gets the current ItemAnimator for this RecyclerView. A null return value
* indicates that there is no animator and that item changes will happen without
* any animations. By default, RecyclerView instantiates and
* uses an instance of {@link DefaultItemAnimator}.
*
* @return ItemAnimator The current ItemAnimator. If null, no animations will occur
* when changes occur to the items in this RecyclerView.
*/
public ItemAnimator getItemAnimator() {
return mItemAnimator;
}
private boolean supportsChangeAnimations() {
return mItemAnimator != null && mItemAnimator.getSupportsChangeAnimations();
}
/**
* Post a runnable to the next frame to run pending item animations. Only the first such
* request will be posted, governed by the mPostedAnimatorRunner flag.
*/
private void postAnimationRunner() {
if (!mPostedAnimatorRunner && mIsAttached) {
ViewCompat.postOnAnimation(this, mItemAnimatorRunner);
mPostedAnimatorRunner = true;
}
}
private boolean predictiveItemAnimationsEnabled() {
return (mItemAnimator != null && mLayout.supportsPredictiveItemAnimations());
}
/**
* Consumes adapter updates and calculates which type of animations we want to run.
* Called in onMeasure and dispatchLayout.
* <p>
* This method may process only the pre-layout state of updates or all of them.
*/
private void processAdapterUpdatesAndSetAnimationFlags() {
if (mDataSetHasChangedAfterLayout) {
// Processing these items have no value since data set changed unexpectedly.
// Instead, we just reset it.
mAdapterHelper.reset();
markKnownViewsInvalid();
mLayout.onItemsChanged(this);
}
// simple animations are a subset of advanced animations (which will cause a
// pre-layout step)
// If layout supports predictive animations, pre-process to decide if we want to run them
if (mItemAnimator != null && mLayout.supportsPredictiveItemAnimations()) {
mAdapterHelper.preProcess();
} else {
mAdapterHelper.consumeUpdatesInOnePass();
}
boolean animationTypeSupported = (mItemsAddedOrRemoved && !mItemsChanged) ||
(mItemsAddedOrRemoved || (mItemsChanged && supportsChangeAnimations()));
mState.mRunSimpleAnimations = mFirstLayoutComplete && mItemAnimator != null &&
(mDataSetHasChangedAfterLayout || animationTypeSupported ||
mLayout.mRequestedSimpleAnimations) &&
(!mDataSetHasChangedAfterLayout || mAdapter.hasStableIds());
mState.mRunPredictiveAnimations = mState.mRunSimpleAnimations &&
animationTypeSupported && !mDataSetHasChangedAfterLayout &&
predictiveItemAnimationsEnabled();
}
/**
* Wrapper around layoutChildren() that handles animating changes caused by layout.
* Animations work on the assumption that there are five different kinds of items
* in play:
* PERSISTENT: items are visible before and after layout
* REMOVED: items were visible before layout and were removed by the app
* ADDED: items did not exist before layout and were added by the app
* DISAPPEARING: items exist in the data set before/after, but changed from
* visible to non-visible in the process of layout (they were moved off
* screen as a side-effect of other changes)
* APPEARING: items exist in the data set before/after, but changed from
* non-visible to visible in the process of layout (they were moved on
* screen as a side-effect of other changes)
* The overall approach figures out what items exist before/after layout and
* infers one of the five above states for each of the items. Then the animations
* are set up accordingly:
* PERSISTENT views are moved ({@link ItemAnimator#animateMove(ViewHolder, int, int, int, int)})
* REMOVED views are removed ({@link ItemAnimator#animateRemove(ViewHolder)})
* ADDED views are added ({@link ItemAnimator#animateAdd(ViewHolder)})
* DISAPPEARING views are moved off screen
* APPEARING views are moved on screen
*/
void dispatchLayout() {
if (mAdapter == null) {
Log.e(TAG, "No adapter attached; skipping layout");
return;
}
if (mLayout == null) {
Log.e(TAG, "No layout manager attached; skipping layout");
return;
}
mDisappearingViewsInLayoutPass.clear();
eatRequestLayout();
mRunningLayoutOrScroll = true;
processAdapterUpdatesAndSetAnimationFlags();
mState.mOldChangedHolders = mState.mRunSimpleAnimations && mItemsChanged
&& supportsChangeAnimations() ? new ArrayMap<Long, ViewHolder>() : null;
mItemsAddedOrRemoved = mItemsChanged = false;
ArrayMap<View, Rect> appearingViewInitialBounds = null;
mState.mInPreLayout = mState.mRunPredictiveAnimations;
mState.mItemCount = mAdapter.getItemCount();
findMinMaxChildLayoutPositions(mMinMaxLayoutPositions);
if (mState.mRunSimpleAnimations) {
// Step 0: Find out where all non-removed items are, pre-layout
mState.mPreLayoutHolderMap.clear();
mState.mPostLayoutHolderMap.clear();
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.shouldIgnore() || (holder.isInvalid() && !mAdapter.hasStableIds())) {
continue;
}
final View view = holder.itemView;
mState.mPreLayoutHolderMap.put(holder, new ItemHolderInfo(holder,
view.getLeft(), view.getTop(), view.getRight(), view.getBottom()));
}
}
if (mState.mRunPredictiveAnimations) {
// Step 1: run prelayout: This will use the old positions of items. The layout manager
// is expected to layout everything, even removed items (though not to add removed
// items back to the container). This gives the pre-layout position of APPEARING views
// which come into existence as part of the real layout.
// Save old positions so that LayoutManager can run its mapping logic.
saveOldPositions();
// processAdapterUpdatesAndSetAnimationFlags already run pre-layout animations.
if (mState.mOldChangedHolders != null) {
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.isChanged() && !holder.isRemoved() && !holder.shouldIgnore()) {
long key = getChangedHolderKey(holder);
mState.mOldChangedHolders.put(key, holder);
mState.mPreLayoutHolderMap.remove(holder);
}
}
}
final boolean didStructureChange = mState.mStructureChanged;
mState.mStructureChanged = false;
// temporarily disable flag because we are asking for previous layout
mLayout.onLayoutChildren(mRecycler, mState);
mState.mStructureChanged = didStructureChange;
appearingViewInitialBounds = new ArrayMap<View, Rect>();
for (int i = 0; i < mChildHelper.getChildCount(); ++i) {
boolean found = false;
View child = mChildHelper.getChildAt(i);
if (getChildViewHolderInt(child).shouldIgnore()) {
continue;
}
for (int j = 0; j < mState.mPreLayoutHolderMap.size(); ++j) {
ViewHolder holder = mState.mPreLayoutHolderMap.keyAt(j);
if (holder.itemView == child) {
found = true;
break;
}
}
if (!found) {
appearingViewInitialBounds.put(child, new Rect(child.getLeft(), child.getTop(),
child.getRight(), child.getBottom()));
}
}
// we don't process disappearing list because they may re-appear in post layout pass.
clearOldPositions();
mAdapterHelper.consumePostponedUpdates();
} else {
clearOldPositions();
// in case pre layout did run but we decided not to run predictive animations.
mAdapterHelper.consumeUpdatesInOnePass();
if (mState.mOldChangedHolders != null) {
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.isChanged() && !holder.isRemoved() && !holder.shouldIgnore()) {
long key = getChangedHolderKey(holder);
mState.mOldChangedHolders.put(key, holder);
mState.mPreLayoutHolderMap.remove(holder);
}
}
}
}
mState.mItemCount = mAdapter.getItemCount();
mState.mDeletedInvisibleItemCountSincePreviousLayout = 0;
// Step 2: Run layout
mState.mInPreLayout = false;
mLayout.onLayoutChildren(mRecycler, mState);
mState.mStructureChanged = false;
mPendingSavedState = null;
// onLayoutChildren may have caused client code to disable item animations; re-check
mState.mRunSimpleAnimations = mState.mRunSimpleAnimations && mItemAnimator != null;
if (mState.mRunSimpleAnimations) {
// Step 3: Find out where things are now, post-layout
ArrayMap<Long, ViewHolder> newChangedHolders = mState.mOldChangedHolders != null ?
new ArrayMap<Long, ViewHolder>() : null;
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; ++i) {
ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.shouldIgnore()) {
continue;
}
final View view = holder.itemView;
long key = getChangedHolderKey(holder);
if (newChangedHolders != null && mState.mOldChangedHolders.get(key) != null) {
newChangedHolders.put(key, holder);
} else {
mState.mPostLayoutHolderMap.put(holder, new ItemHolderInfo(holder,
view.getLeft(), view.getTop(), view.getRight(), view.getBottom()));
}
}
processDisappearingList(appearingViewInitialBounds);
// Step 4: Animate DISAPPEARING and REMOVED items
int preLayoutCount = mState.mPreLayoutHolderMap.size();
for (int i = preLayoutCount - 1; i >= 0; i--) {
ViewHolder itemHolder = mState.mPreLayoutHolderMap.keyAt(i);
if (!mState.mPostLayoutHolderMap.containsKey(itemHolder)) {
ItemHolderInfo disappearingItem = mState.mPreLayoutHolderMap.valueAt(i);
mState.mPreLayoutHolderMap.removeAt(i);
View disappearingItemView = disappearingItem.holder.itemView;
mRecycler.unscrapView(disappearingItem.holder);
animateDisappearance(disappearingItem);
}
}
// Step 5: Animate APPEARING and ADDED items
int postLayoutCount = mState.mPostLayoutHolderMap.size();
if (postLayoutCount > 0) {
for (int i = postLayoutCount - 1; i >= 0; i--) {
ViewHolder itemHolder = mState.mPostLayoutHolderMap.keyAt(i);
ItemHolderInfo info = mState.mPostLayoutHolderMap.valueAt(i);
if ((mState.mPreLayoutHolderMap.isEmpty() ||
!mState.mPreLayoutHolderMap.containsKey(itemHolder))) {
mState.mPostLayoutHolderMap.removeAt(i);
Rect initialBounds = (appearingViewInitialBounds != null) ?
appearingViewInitialBounds.get(itemHolder.itemView) : null;
animateAppearance(itemHolder, initialBounds,
info.left, info.top);
}
}
}
// Step 6: Animate PERSISTENT items
count = mState.mPostLayoutHolderMap.size();
for (int i = 0; i < count; ++i) {
ViewHolder postHolder = mState.mPostLayoutHolderMap.keyAt(i);
ItemHolderInfo postInfo = mState.mPostLayoutHolderMap.valueAt(i);
ItemHolderInfo preInfo = mState.mPreLayoutHolderMap.get(postHolder);
if (preInfo != null && postInfo != null) {
if (preInfo.left != postInfo.left || preInfo.top != postInfo.top) {
postHolder.setIsRecyclable(false);
if (DEBUG) {
Log.d(TAG, "PERSISTENT: " + postHolder +
" with view " + postHolder.itemView);
}
if (mItemAnimator.animateMove(postHolder,
preInfo.left, preInfo.top, postInfo.left, postInfo.top)) {
postAnimationRunner();
}
}
}
}
// Step 7: Animate CHANGING items
count = mState.mOldChangedHolders != null ? mState.mOldChangedHolders.size() : 0;
// traverse reverse in case view gets recycled while we are traversing the list.
for (int i = count - 1; i >= 0; i--) {
long key = mState.mOldChangedHolders.keyAt(i);
ViewHolder oldHolder = mState.mOldChangedHolders.get(key);
View oldView = oldHolder.itemView;
if (oldHolder.shouldIgnore()) {
continue;
}
// We probably don't need this check anymore since these views are removed from
// the list if they are recycled.
if (mRecycler.mChangedScrap != null &&
mRecycler.mChangedScrap.contains(oldHolder)) {
animateChange(oldHolder, newChangedHolders.get(key));
} else if (DEBUG) {
Log.e(TAG, "cannot find old changed holder in changed scrap :/" + oldHolder);
}
}
}
resumeRequestLayout(false);
mLayout.removeAndRecycleScrapInt(mRecycler);
mState.mPreviousLayoutItemCount = mState.mItemCount;
mDataSetHasChangedAfterLayout = false;
mState.mRunSimpleAnimations = false;
mState.mRunPredictiveAnimations = false;
mRunningLayoutOrScroll = false;
mLayout.mRequestedSimpleAnimations = false;
if (mRecycler.mChangedScrap != null) {
mRecycler.mChangedScrap.clear();
}
mState.mOldChangedHolders = null;
if (didChildRangeChange(mMinMaxLayoutPositions[0], mMinMaxLayoutPositions[1])) {
notifyOnScrolled(0, 0);
}
}
private void findMinMaxChildLayoutPositions(int[] into) {
final int count = mChildHelper.getChildCount();
if (count == 0) {
into[0] = 0;
into[1] = 0;
return;
}
int minPositionPreLayout = Integer.MAX_VALUE;
int maxPositionPreLayout = Integer.MIN_VALUE;
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.shouldIgnore()) {
continue;
}
final int pos = holder.getLayoutPosition();
if (pos < minPositionPreLayout) {
minPositionPreLayout = pos;
}
if (pos > maxPositionPreLayout) {
maxPositionPreLayout = pos;
}
}
into[0] = minPositionPreLayout;
into[1] = maxPositionPreLayout;
}
private boolean didChildRangeChange(int minPositionPreLayout, int maxPositionPreLayout) {
int count = mChildHelper.getChildCount();
if (count == 0) {
return minPositionPreLayout != 0 || maxPositionPreLayout != 0;
}
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.shouldIgnore()) {
continue;
}
final int pos = holder.getLayoutPosition();
if (pos < minPositionPreLayout || pos > maxPositionPreLayout) {
return true;
}
}
return false;
}
@Override
protected void removeDetachedView(View child, boolean animate) {
ViewHolder vh = getChildViewHolderInt(child);
if (vh != null) {
if (vh.isTmpDetached()) {
vh.clearTmpDetachFlag();
} else if (!vh.shouldIgnore()) {
throw new IllegalArgumentException("Called removeDetachedView with a view which"
+ " is not flagged as tmp detached." + vh);
}
}
dispatchChildDetached(child);
super.removeDetachedView(child, animate);
}
/**
* Returns a unique key to be used while handling change animations.
* It might be child's position or stable id depending on the adapter type.
*/
long getChangedHolderKey(ViewHolder holder) {
return mAdapter.hasStableIds() ? holder.getItemId() : holder.mPosition;
}
/**
* A LayoutManager may want to layout a view just to animate disappearance.
* This method handles those views and triggers remove animation on them.
*/
private void processDisappearingList(ArrayMap<View, Rect> appearingViews) {
final int count = mDisappearingViewsInLayoutPass.size();
for (int i = 0; i < count; i ++) {
View view = mDisappearingViewsInLayoutPass.get(i);
ViewHolder vh = getChildViewHolderInt(view);
final ItemHolderInfo info = mState.mPreLayoutHolderMap.remove(vh);
if (!mState.isPreLayout()) {
mState.mPostLayoutHolderMap.remove(vh);
}
if (appearingViews.remove(view) != null) {
mLayout.removeAndRecycleView(view, mRecycler);
continue;
}
if (info != null) {
animateDisappearance(info);
} else {
// let it disappear from the position it becomes visible
animateDisappearance(new ItemHolderInfo(vh, view.getLeft(), view.getTop(),
view.getRight(), view.getBottom()));
}
}
mDisappearingViewsInLayoutPass.clear();
}
private void animateAppearance(ViewHolder itemHolder, Rect beforeBounds, int afterLeft,
int afterTop) {
View newItemView = itemHolder.itemView;
if (beforeBounds != null &&
(beforeBounds.left != afterLeft || beforeBounds.top != afterTop)) {
// slide items in if before/after locations differ
itemHolder.setIsRecyclable(false);
if (DEBUG) {
Log.d(TAG, "APPEARING: " + itemHolder + " with view " + newItemView);
}
if (mItemAnimator.animateMove(itemHolder,
beforeBounds.left, beforeBounds.top,
afterLeft, afterTop)) {
postAnimationRunner();
}
} else {
if (DEBUG) {
Log.d(TAG, "ADDED: " + itemHolder + " with view " + newItemView);
}
itemHolder.setIsRecyclable(false);
if (mItemAnimator.animateAdd(itemHolder)) {
postAnimationRunner();
}
}
}
private void animateDisappearance(ItemHolderInfo disappearingItem) {
View disappearingItemView = disappearingItem.holder.itemView;
addAnimatingView(disappearingItem.holder);
int oldLeft = disappearingItem.left;
int oldTop = disappearingItem.top;
int newLeft = disappearingItemView.getLeft();
int newTop = disappearingItemView.getTop();
if (oldLeft != newLeft || oldTop != newTop) {
disappearingItem.holder.setIsRecyclable(false);
disappearingItemView.layout(newLeft, newTop,
newLeft + disappearingItemView.getWidth(),
newTop + disappearingItemView.getHeight());
if (DEBUG) {
Log.d(TAG, "DISAPPEARING: " + disappearingItem.holder +
" with view " + disappearingItemView);
}
if (mItemAnimator.animateMove(disappearingItem.holder, oldLeft, oldTop,
newLeft, newTop)) {
postAnimationRunner();
}
} else {
if (DEBUG) {
Log.d(TAG, "REMOVED: " + disappearingItem.holder +
" with view " + disappearingItemView);
}
disappearingItem.holder.setIsRecyclable(false);
if (mItemAnimator.animateRemove(disappearingItem.holder)) {
postAnimationRunner();
}
}
}
private void animateChange(ViewHolder oldHolder, ViewHolder newHolder) {
oldHolder.setIsRecyclable(false);
addAnimatingView(oldHolder);
oldHolder.mShadowedHolder = newHolder;
mRecycler.unscrapView(oldHolder);
if (DEBUG) {
Log.d(TAG, "CHANGED: " + oldHolder + " with view " + oldHolder.itemView);
}
final int fromLeft = oldHolder.itemView.getLeft();
final int fromTop = oldHolder.itemView.getTop();
final int toLeft, toTop;
if (newHolder == null || newHolder.shouldIgnore()) {
toLeft = fromLeft;
toTop = fromTop;
} else {
toLeft = newHolder.itemView.getLeft();
toTop = newHolder.itemView.getTop();
newHolder.setIsRecyclable(false);
newHolder.mShadowingHolder = oldHolder;
}
if(mItemAnimator.animateChange(oldHolder, newHolder,
fromLeft, fromTop, toLeft, toTop)) {
postAnimationRunner();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
eatRequestLayout();
dispatchLayout();
resumeRequestLayout(false);
mFirstLayoutComplete = true;
}
@Override
public void requestLayout() {
if (!mEatRequestLayout) {
super.requestLayout();
} else {
mLayoutRequestEaten = true;
}
}
void markItemDecorInsetsDirty() {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final View child = mChildHelper.getUnfilteredChildAt(i);
((LayoutParams) child.getLayoutParams()).mInsetsDirty = true;
}
mRecycler.markItemDecorInsetsDirty();
}
@Override
public void draw(Canvas c) {
super.draw(c);
final int count = mItemDecorations.size();
for (int i = 0; i < count; i++) {
mItemDecorations.get(i).onDrawOver(c, this, mState);
}
// TODO If padding is not 0 and chilChildrenToPadding is false, to draw glows properly, we
// need find children closest to edges. Not sure if it is worth the effort.
boolean needsInvalidate = false;
if (mLeftGlow != null && !mLeftGlow.isFinished()) {
final int restore = c.save();
final int padding = mClipToPadding ? getPaddingBottom() : 0;
c.rotate(270);
c.translate(-getHeight() + padding, 0);
needsInvalidate = mLeftGlow != null && mLeftGlow.draw(c);
c.restoreToCount(restore);
}
if (mTopGlow != null && !mTopGlow.isFinished()) {
final int restore = c.save();
if (mClipToPadding) {
c.translate(getPaddingLeft(), getPaddingTop());
}
needsInvalidate |= mTopGlow != null && mTopGlow.draw(c);
c.restoreToCount(restore);
}
if (mRightGlow != null && !mRightGlow.isFinished()) {
final int restore = c.save();
final int width = getWidth();
final int padding = mClipToPadding ? getPaddingTop() : 0;
c.rotate(90);
c.translate(-padding, -width);
needsInvalidate |= mRightGlow != null && mRightGlow.draw(c);
c.restoreToCount(restore);
}
if (mBottomGlow != null && !mBottomGlow.isFinished()) {
final int restore = c.save();
c.rotate(180);
if (mClipToPadding) {
c.translate(-getWidth() + getPaddingRight(), -getHeight() + getPaddingBottom());
} else {
c.translate(-getWidth(), -getHeight());
}
needsInvalidate |= mBottomGlow != null && mBottomGlow.draw(c);
c.restoreToCount(restore);
}
// If some views are animating, ItemDecorators are likely to move/change with them.
// Invalidate RecyclerView to re-draw decorators. This is still efficient because children's
// display lists are not invalidated.
if (!needsInvalidate && mItemAnimator != null && mItemDecorations.size() > 0 &&
mItemAnimator.isRunning()) {
needsInvalidate = true;
}
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
public void onDraw(Canvas c) {
super.onDraw(c);
final int count = mItemDecorations.size();
for (int i = 0; i < count; i++) {
mItemDecorations.get(i).onDraw(c, this, mState);
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && mLayout.checkLayoutParams((LayoutParams) p);
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
if (mLayout == null) {
throw new IllegalStateException("RecyclerView has no LayoutManager");
}
return mLayout.generateDefaultLayoutParams();
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
if (mLayout == null) {
throw new IllegalStateException("RecyclerView has no LayoutManager");
}
return mLayout.generateLayoutParams(getContext(), attrs);
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
if (mLayout == null) {
throw new IllegalStateException("RecyclerView has no LayoutManager");
}
return mLayout.generateLayoutParams(p);
}
void saveOldPositions() {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (DEBUG && holder.mPosition == -1 && !holder.isRemoved()) {
throw new IllegalStateException("view holder cannot have position -1 unless it"
+ " is removed");
}
if (!holder.shouldIgnore()) {
holder.saveOldPosition();
}
}
}
void clearOldPositions() {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (!holder.shouldIgnore()) {
holder.clearOldPosition();
}
}
mRecycler.clearOldPositions();
}
void offsetPositionRecordsForMove(int from, int to) {
final int childCount = mChildHelper.getUnfilteredChildCount();
final int start, end, inBetweenOffset;
if (from < to) {
start = from;
end = to;
inBetweenOffset = -1;
} else {
start = to;
end = from;
inBetweenOffset = 1;
}
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder == null || holder.mPosition < start || holder.mPosition > end) {
continue;
}
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForMove attached child " + i + " holder " +
holder);
}
if (holder.mPosition == from) {
holder.offsetPosition(to - from, false);
} else {
holder.offsetPosition(inBetweenOffset, false);
}
mState.mStructureChanged = true;
}
mRecycler.offsetPositionRecordsForMove(from, to);
requestLayout();
}
void offsetPositionRecordsForInsert(int positionStart, int itemCount) {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.shouldIgnore() && holder.mPosition >= positionStart) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForInsert attached child " + i + " holder " +
holder + " now at position " + (holder.mPosition + itemCount));
}
holder.offsetPosition(itemCount, false);
mState.mStructureChanged = true;
}
}
mRecycler.offsetPositionRecordsForInsert(positionStart, itemCount);
requestLayout();
}
void offsetPositionRecordsForRemove(int positionStart, int itemCount,
boolean applyToPreLayout) {
final int positionEnd = positionStart + itemCount;
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.shouldIgnore()) {
if (holder.mPosition >= positionEnd) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i +
" holder " + holder + " now at position " +
(holder.mPosition - itemCount));
}
holder.offsetPosition(-itemCount, applyToPreLayout);
mState.mStructureChanged = true;
} else if (holder.mPosition >= positionStart) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i +
" holder " + holder + " now REMOVED");
}
holder.flagRemovedAndOffsetPosition(positionStart - 1, -itemCount,
applyToPreLayout);
mState.mStructureChanged = true;
}
}
}
mRecycler.offsetPositionRecordsForRemove(positionStart, itemCount, applyToPreLayout);
requestLayout();
}
/**
* Rebind existing views for the given range, or create as needed.
*
* @param positionStart Adapter position to start at
* @param itemCount Number of views that must explicitly be rebound
*/
void viewRangeUpdate(int positionStart, int itemCount) {
final int childCount = mChildHelper.getUnfilteredChildCount();
final int positionEnd = positionStart + itemCount;
for (int i = 0; i < childCount; i++) {
final View child = mChildHelper.getUnfilteredChildAt(i);
final ViewHolder holder = getChildViewHolderInt(child);
if (holder == null || holder.shouldIgnore()) {
continue;
}
if (holder.mPosition >= positionStart && holder.mPosition < positionEnd) {
// We re-bind these view holders after pre-processing is complete so that
// ViewHolders have their final positions assigned.
holder.addFlags(ViewHolder.FLAG_UPDATE);
if (supportsChangeAnimations()) {
holder.addFlags(ViewHolder.FLAG_CHANGED);
}
// lp cannot be null since we get ViewHolder from it.
((LayoutParams) child.getLayoutParams()).mInsetsDirty = true;
}
}
mRecycler.viewRangeUpdate(positionStart, itemCount);
}
void rebindUpdatedViewHolders() {
final int childCount = mChildHelper.getChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
// validate type is correct
if (holder == null || holder.shouldIgnore()) {
continue;
}
if (holder.isRemoved() || holder.isInvalid()) {
requestLayout();
} else if (holder.needsUpdate()) {
final int type = mAdapter.getItemViewType(holder.mPosition);
if (holder.getItemViewType() == type) {
// Binding an attached view will request a layout if needed.
if (!holder.isChanged() || !supportsChangeAnimations()) {
mAdapter.bindViewHolder(holder, holder.mPosition);
} else {
// Don't rebind changed holders if change animations are enabled.
// We want the old contents for the animation and will get a new
// holder for the new contents.
requestLayout();
}
} else {
// binding to a new view will need re-layout anyways. We can as well trigger
// it here so that it happens during layout
requestLayout();
break;
}
}
}
}
private void setDataSetChangedAfterLayout() {
if (mDataSetHasChangedAfterLayout) {
return;
}
mDataSetHasChangedAfterLayout = true;
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.shouldIgnore()) {
holder.addFlags(ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN);
}
}
mRecycler.setAdapterPositionsAsUnknown();
}
/**
* Mark all known views as invalid. Used in response to a, "the whole world might have changed"
* data change event.
*/
void markKnownViewsInvalid() {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.shouldIgnore()) {
holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID);
}
}
markItemDecorInsetsDirty();
mRecycler.markKnownViewsInvalid();
}
/**
* Invalidates all ItemDecorations. If RecyclerView has item decorations, calling this method
* will trigger a {@link #requestLayout()} call.
*/
public void invalidateItemDecorations() {
if (mItemDecorations.size() == 0) {
return;
}
if (mLayout != null) {
mLayout.assertNotInLayoutOrScroll("Cannot invalidate item decorations during a scroll"
+ " or layout");
}
markItemDecorInsetsDirty();
requestLayout();
}
/**
* Retrieve the {@link ViewHolder} for the given child view.
*
* @param child Child of this RecyclerView to query for its ViewHolder
* @return The child view's ViewHolder
*/
public ViewHolder getChildViewHolder(View child) {
final ViewParent parent = child.getParent();
if (parent != null && parent != this) {
throw new IllegalArgumentException("View " + child + " is not a direct child of " +
this);
}
return getChildViewHolderInt(child);
}
static ViewHolder getChildViewHolderInt(View child) {
if (child == null) {
return null;
}
return ((LayoutParams) child.getLayoutParams()).mViewHolder;
}
/**
* @deprecated use {@link #getChildAdapterPosition(View)} or
* {@link #getChildLayoutPosition(View)}.
*/
@Deprecated
public int getChildPosition(View child) {
return getChildAdapterPosition(child);
}
/**
* Return the adapter position that the given child view corresponds to.
*
* @param child Child View to query
* @return Adapter position corresponding to the given view or {@link #NO_POSITION}
*/
public int getChildAdapterPosition(View child) {
final ViewHolder holder = getChildViewHolderInt(child);
return holder != null ? holder.getAdapterPosition() : NO_POSITION;
}
/**
* Return the adapter position of the given child view as of the latest completed layout pass.
* <p>
* This position may not be equal to Item's adapter position if there are pending changes
* in the adapter which have not been reflected to the layout yet.
*
* @param child Child View to query
* @return Adapter position of the given View as of last layout pass or {@link #NO_POSITION} if
* the View is representing a removed item.
*/
public int getChildLayoutPosition(View child) {
final ViewHolder holder = getChildViewHolderInt(child);
return holder != null ? holder.getLayoutPosition() : NO_POSITION;
}
/**
* Return the stable item id that the given child view corresponds to.
*
* @param child Child View to query
* @return Item id corresponding to the given view or {@link #NO_ID}
*/
public long getChildItemId(View child) {
if (mAdapter == null || !mAdapter.hasStableIds()) {
return NO_ID;
}
final ViewHolder holder = getChildViewHolderInt(child);
return holder != null ? holder.getItemId() : NO_ID;
}
/**
* @deprecated use {@link #findViewHolderForLayoutPosition(int)} or
* {@link #findViewHolderForAdapterPosition(int)}
*/
@Deprecated
public ViewHolder findViewHolderForPosition(int position) {
return findViewHolderForPosition(position, false);
}
/**
* Return the ViewHolder for the item in the given position of the data set as of the latest
* layout pass.
* <p>
* This method checks only the children of RecyclerView. If the item at the given
* <code>position</code> is not laid out, it <em>will not</em> create a new one.
* <p>
* Note that when Adapter contents change, ViewHolder positions are not updated until the
* next layout calculation. If there are pending adapter updates, the return value of this
* method may not match your adapter contents. You can use
* #{@link ViewHolder#getAdapterPosition()} to get the current adapter position of a ViewHolder.
*
* @param position The position of the item in the data set of the adapter
* @return The ViewHolder at <code>position</code> or null if there is no such item
*/
public ViewHolder findViewHolderForLayoutPosition(int position) {
return findViewHolderForPosition(position, false);
}
/**
* Return the ViewHolder for the item in the given position of the data set. Unlike
* {@link #findViewHolderForLayoutPosition(int)} this method takes into account any pending
* adapter changes that may not be reflected to the layout yet. On the other hand, if
* {@link Adapter#notifyDataSetChanged()} has been called but the new layout has not been
* calculated yet, this method will return <code>null</code> since the new positions of views
* are unknown until the layout is calculated.
* <p>
* This method checks only the children of RecyclerView. If the item at the given
* <code>position</code> is not laid out, it <em>will not</em> create a new one.
*
* @param position The position of the item in the data set of the adapter
* @return The ViewHolder at <code>position</code> or null if there is no such item
*/
public ViewHolder findViewHolderForAdapterPosition(int position) {
if (mDataSetHasChangedAfterLayout) {
return null;
}
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.isRemoved() && getAdapterPositionFor(holder) == position) {
return holder;
}
}
return null;
}
ViewHolder findViewHolderForPosition(int position, boolean checkNewPosition) {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.isRemoved()) {
if (checkNewPosition) {
if (holder.mPosition == position) {
return holder;
}
} else if (holder.getLayoutPosition() == position) {
return holder;
}
}
}
// This method should not query cached views. It creates a problem during adapter updates
// when we are dealing with already laid out views. Also, for the public method, it is more
// reasonable to return null if position is not laid out.
return null;
}
/**
* Return the ViewHolder for the item with the given id. The RecyclerView must
* use an Adapter with {@link Adapter#setHasStableIds(boolean) stableIds} to
* return a non-null value.
* <p>
* This method checks only the children of RecyclerView. If the item with the given
* <code>id</code> is not laid out, it <em>will not</em> create a new one.
*
* @param id The id for the requested item
* @return The ViewHolder with the given <code>id</code> or null if there is no such item
*/
public ViewHolder findViewHolderForItemId(long id) {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && holder.getItemId() == id) {
return holder;
}
}
// this method should not query cached views. They are not children so they
// should not be returned in this public method
return null;
}
/**
* Find the topmost view under the given point.
*
* @param x Horizontal position in pixels to search
* @param y Vertical position in pixels to search
* @return The child view under (x, y) or null if no matching child is found
*/
public View findChildViewUnder(float x, float y) {
final int count = mChildHelper.getChildCount();
for (int i = count - 1; i >= 0; i--) {
final View child = mChildHelper.getChildAt(i);
final float translationX = ViewCompat.getTranslationX(child);
final float translationY = ViewCompat.getTranslationY(child);
if (x >= child.getLeft() + translationX &&
x <= child.getRight() + translationX &&
y >= child.getTop() + translationY &&
y <= child.getBottom() + translationY) {
return child;
}
}
return null;
}
/**
* Offset the bounds of all child views by <code>dy</code> pixels.
* Useful for implementing simple scrolling in {@link LayoutManager LayoutManagers}.
*
* @param dy Vertical pixel offset to apply to the bounds of all child views
*/
public void offsetChildrenVertical(int dy) {
final int childCount = mChildHelper.getChildCount();
for (int i = 0; i < childCount; i++) {
mChildHelper.getChildAt(i).offsetTopAndBottom(dy);
}
}
/**
* Called when an item view is attached to this RecyclerView.
*
* <p>Subclasses of RecyclerView may want to perform extra bookkeeping or modifications
* of child views as they become attached. This will be called before a
* {@link LayoutManager} measures or lays out the view and is a good time to perform these
* changes.</p>
*
* @param child Child view that is now attached to this RecyclerView and its associated window
*/
public void onChildAttachedToWindow(View child) {
}
/**
* Called when an item view is detached from this RecyclerView.
*
* <p>Subclasses of RecyclerView may want to perform extra bookkeeping or modifications
* of child views as they become detached. This will be called as a
* {@link LayoutManager} fully detaches the child view from the parent and its window.</p>
*
* @param child Child view that is now detached from this RecyclerView and its associated window
*/
public void onChildDetachedFromWindow(View child) {
}
/**
* Offset the bounds of all child views by <code>dx</code> pixels.
* Useful for implementing simple scrolling in {@link LayoutManager LayoutManagers}.
*
* @param dx Horizontal pixel offset to apply to the bounds of all child views
*/
public void offsetChildrenHorizontal(int dx) {
final int childCount = mChildHelper.getChildCount();
for (int i = 0; i < childCount; i++) {
mChildHelper.getChildAt(i).offsetLeftAndRight(dx);
}
}
Rect getItemDecorInsetsForChild(View child) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.mInsetsDirty) {
return lp.mDecorInsets;
}
final Rect insets = lp.mDecorInsets;
insets.set(0, 0, 0, 0);
final int decorCount = mItemDecorations.size();
for (int i = 0; i < decorCount; i++) {
mTempRect.set(0, 0, 0, 0);
mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState);
insets.left += mTempRect.left;
insets.top += mTempRect.top;
insets.right += mTempRect.right;
insets.bottom += mTempRect.bottom;
}
lp.mInsetsDirty = false;
return insets;
}
private class ViewFlinger implements Runnable {
private int mLastFlingX;
private int mLastFlingY;
private ScrollerCompat mScroller;
private Interpolator mInterpolator = sQuinticInterpolator;
// When set to true, postOnAnimation callbacks are delayed until the run method completes
private boolean mEatRunOnAnimationRequest = false;
// Tracks if postAnimationCallback should be re-attached when it is done
private boolean mReSchedulePostAnimationCallback = false;
public ViewFlinger() {
mScroller = ScrollerCompat.create(getContext(), sQuinticInterpolator);
}
@Override
public void run() {
disableRunOnAnimationRequests();
consumePendingUpdateOperations();
// keep a local reference so that if it is changed during onAnimation method, it won't
// cause unexpected behaviors
final ScrollerCompat scroller = mScroller;
final SmoothScroller smoothScroller = mLayout.mSmoothScroller;
if (scroller.computeScrollOffset()) {
final int x = scroller.getCurrX();
final int y = scroller.getCurrY();
final int dx = x - mLastFlingX;
final int dy = y - mLastFlingY;
int hresult = 0;
int vresult = 0;
mLastFlingX = x;
mLastFlingY = y;
int overscrollX = 0, overscrollY = 0;
if (mAdapter != null) {
eatRequestLayout();
mRunningLayoutOrScroll = true;
if (dx != 0) {
hresult = mLayout.scrollHorizontallyBy(dx, mRecycler, mState);
overscrollX = dx - hresult;
}
if (dy != 0) {
vresult = mLayout.scrollVerticallyBy(dy, mRecycler, mState);
overscrollY = dy - vresult;
}
if (supportsChangeAnimations()) {
// Fix up shadow views used by changing animations
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; i++) {
View view = mChildHelper.getChildAt(i);
ViewHolder holder = getChildViewHolder(view);
if (holder != null && holder.mShadowingHolder != null) {
View shadowingView = holder.mShadowingHolder.itemView;
int left = view.getLeft();
int top = view.getTop();
if (left != shadowingView.getLeft() ||
top != shadowingView.getTop()) {
shadowingView.layout(left, top,
left + shadowingView.getWidth(),
top + shadowingView.getHeight());
}
}
}
}
if (smoothScroller != null && !smoothScroller.isPendingInitialRun() &&
smoothScroller.isRunning()) {
final int adapterSize = mState.getItemCount();
if (adapterSize == 0) {
smoothScroller.stop();
} else if (smoothScroller.getTargetPosition() >= adapterSize) {
smoothScroller.setTargetPosition(adapterSize - 1);
smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY);
} else {
smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY);
}
}
mRunningLayoutOrScroll = false;
resumeRequestLayout(false);
}
if (!mItemDecorations.isEmpty()) {
invalidate();
}
if (ViewCompat.getOverScrollMode(RecyclerView.this) !=
ViewCompat.OVER_SCROLL_NEVER) {
considerReleasingGlowsOnScroll(dx, dy);
}
if (overscrollX != 0 || overscrollY != 0) {
final int vel = (int) scroller.getCurrVelocity();
int velX = 0;
if (overscrollX != x) {
velX = overscrollX < 0 ? -vel : overscrollX > 0 ? vel : 0;
}
int velY = 0;
if (overscrollY != y) {
velY = overscrollY < 0 ? -vel : overscrollY > 0 ? vel : 0;
}
if (ViewCompat.getOverScrollMode(RecyclerView.this) !=
ViewCompat.OVER_SCROLL_NEVER) {
absorbGlows(velX, velY);
}
if ((velX != 0 || overscrollX == x || scroller.getFinalX() == 0) &&
(velY != 0 || overscrollY == y || scroller.getFinalY() == 0)) {
scroller.abortAnimation();
}
}
if (hresult != 0 || vresult != 0) {
notifyOnScrolled(hresult, vresult);
}
if (!awakenScrollBars()) {
invalidate();
}
final boolean fullyConsumedVertical = dy != 0 && mLayout.canScrollVertically()
&& vresult == dy;
final boolean fullyConsumedHorizontal = dx != 0 && mLayout.canScrollHorizontally()
&& hresult == dx;
final boolean fullyConsumedAny = (dx == 0 && dy == 0) || fullyConsumedHorizontal
|| fullyConsumedVertical;
if (scroller.isFinished() || !fullyConsumedAny) {
setScrollState(SCROLL_STATE_IDLE); // setting state to idle will stop this.
} else {
postOnAnimation();
}
}
// call this after the onAnimation is complete not to have inconsistent callbacks etc.
if (smoothScroller != null && smoothScroller.isPendingInitialRun()) {
smoothScroller.onAnimation(0, 0);
}
enableRunOnAnimationRequests();
}
private void disableRunOnAnimationRequests() {
mReSchedulePostAnimationCallback = false;
mEatRunOnAnimationRequest = true;
}
private void enableRunOnAnimationRequests() {
mEatRunOnAnimationRequest = false;
if (mReSchedulePostAnimationCallback) {
postOnAnimation();
}
}
void postOnAnimation() {
if (mEatRunOnAnimationRequest) {
mReSchedulePostAnimationCallback = true;
} else {
removeCallbacks(this);
ViewCompat.postOnAnimation(RecyclerView.this, this);
}
}
public void fling(int velocityX, int velocityY) {
setScrollState(SCROLL_STATE_SETTLING);
mLastFlingX = mLastFlingY = 0;
mScroller.fling(0, 0, velocityX, velocityY,
Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);
postOnAnimation();
}
public void smoothScrollBy(int dx, int dy) {
smoothScrollBy(dx, dy, 0, 0);
}
public void smoothScrollBy(int dx, int dy, int vx, int vy) {
smoothScrollBy(dx, dy, computeScrollDuration(dx, dy, vx, vy));
}
private float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f; // center the values about 0.
f *= 0.3f * Math.PI / 2.0f;
return (float) Math.sin(f);
}
private int computeScrollDuration(int dx, int dy, int vx, int vy) {
final int absDx = Math.abs(dx);
final int absDy = Math.abs(dy);
final boolean horizontal = absDx > absDy;
final int velocity = (int) Math.sqrt(vx * vx + vy * vy);
final int delta = (int) Math.sqrt(dx * dx + dy * dy);
final int containerSize = horizontal ? getWidth() : getHeight();
final int halfContainerSize = containerSize / 2;
final float distanceRatio = Math.min(1.f, 1.f * delta / containerSize);
final float distance = halfContainerSize + halfContainerSize *
distanceInfluenceForSnapDuration(distanceRatio);
final int duration;
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
float absDelta = (float) (horizontal ? absDx : absDy);
duration = (int) (((absDelta / containerSize) + 1) * 300);
}
return Math.min(duration, MAX_SCROLL_DURATION);
}
public void smoothScrollBy(int dx, int dy, int duration) {
smoothScrollBy(dx, dy, duration, sQuinticInterpolator);
}
public void smoothScrollBy(int dx, int dy, int duration, Interpolator interpolator) {
if (mInterpolator != interpolator) {
mInterpolator = interpolator;
mScroller = ScrollerCompat.create(getContext(), interpolator);
}
setScrollState(SCROLL_STATE_SETTLING);
mLastFlingX = mLastFlingY = 0;
mScroller.startScroll(0, 0, dx, dy, duration);
postOnAnimation();
}
public void stop() {
removeCallbacks(this);
mScroller.abortAnimation();
}
}
private void notifyOnScrolled(int hresult, int vresult) {
// dummy values, View's implementation does not use these.
onScrollChanged(0, 0, 0, 0);
if (mScrollListener != null) {
mScrollListener.onScrolled(this, hresult, vresult);
}
}
private class RecyclerViewDataObserver extends AdapterDataObserver {
@Override
public void onChanged() {
assertNotInLayoutOrScroll(null);
if (mAdapter.hasStableIds()) {
// TODO Determine what actually changed.
// This is more important to implement now since this callback will disable all
// animations because we cannot rely on positions.
mState.mStructureChanged = true;
setDataSetChangedAfterLayout();
} else {
mState.mStructureChanged = true;
setDataSetChangedAfterLayout();
}
if (!mAdapterHelper.hasPendingUpdates()) {
requestLayout();
}
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
assertNotInLayoutOrScroll(null);
if (mAdapterHelper.onItemRangeChanged(positionStart, itemCount)) {
triggerUpdateProcessor();
}
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
assertNotInLayoutOrScroll(null);
if (mAdapterHelper.onItemRangeInserted(positionStart, itemCount)) {
triggerUpdateProcessor();
}
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
assertNotInLayoutOrScroll(null);
if (mAdapterHelper.onItemRangeRemoved(positionStart, itemCount)) {
triggerUpdateProcessor();
}
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
assertNotInLayoutOrScroll(null);
if (mAdapterHelper.onItemRangeMoved(fromPosition, toPosition, itemCount)) {
triggerUpdateProcessor();
}
}
void triggerUpdateProcessor() {
if (mPostUpdatesOnAnimation && mHasFixedSize && mIsAttached) {
ViewCompat.postOnAnimation(RecyclerView.this, mUpdateChildViewsRunnable);
} else {
mAdapterUpdateDuringMeasure = true;
requestLayout();
}
}
}
/**
* RecycledViewPool lets you share Views between multiple RecyclerViews.
* <p>
* If you want to recycle views across RecyclerViews, create an instance of RecycledViewPool
* and use {@link RecyclerView#setRecycledViewPool(RecycledViewPool)}.
* <p>
* RecyclerView automatically creates a pool for itself if you don't provide one.
*
*/
public static class RecycledViewPool {
private SparseArray<ArrayList<ViewHolder>> mScrap =
new SparseArray<ArrayList<ViewHolder>>();
private SparseIntArray mMaxScrap = new SparseIntArray();
private int mAttachCount = 0;
private static final int DEFAULT_MAX_SCRAP = 5;
public void clear() {
mScrap.clear();
}
public void setMaxRecycledViews(int viewType, int max) {
mMaxScrap.put(viewType, max);
final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType);
if (scrapHeap != null) {
while (scrapHeap.size() > max) {
scrapHeap.remove(scrapHeap.size() - 1);
}
}
}
public ViewHolder getRecycledView(int viewType) {
final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType);
if (scrapHeap != null && !scrapHeap.isEmpty()) {
final int index = scrapHeap.size() - 1;
final ViewHolder scrap = scrapHeap.get(index);
scrapHeap.remove(index);
return scrap;
}
return null;
}
int size() {
int count = 0;
for (int i = 0; i < mScrap.size(); i ++) {
ArrayList<ViewHolder> viewHolders = mScrap.valueAt(i);
if (viewHolders != null) {
count += viewHolders.size();
}
}
return count;
}
public void putRecycledView(ViewHolder scrap) {
final int viewType = scrap.getItemViewType();
final ArrayList scrapHeap = getScrapHeapForType(viewType);
if (mMaxScrap.get(viewType) <= scrapHeap.size()) {
return;
}
scrap.resetInternal();
scrapHeap.add(scrap);
}
void attach(Adapter adapter) {
mAttachCount++;
}
void detach() {
mAttachCount--;
}
/**
* Detaches the old adapter and attaches the new one.
* <p>
* RecycledViewPool will clear its cache if it has only one adapter attached and the new
* adapter uses a different ViewHolder than the oldAdapter.
*
* @param oldAdapter The previous adapter instance. Will be detached.
* @param newAdapter The new adapter instance. Will be attached.
* @param compatibleWithPrevious True if both oldAdapter and newAdapter are using the same
* ViewHolder and view types.
*/
void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter,
boolean compatibleWithPrevious) {
if (oldAdapter != null) {
detach();
}
if (!compatibleWithPrevious && mAttachCount == 0) {
clear();
}
if (newAdapter != null) {
attach(newAdapter);
}
}
private ArrayList<ViewHolder> getScrapHeapForType(int viewType) {
ArrayList<ViewHolder> scrap = mScrap.get(viewType);
if (scrap == null) {
scrap = new ArrayList<ViewHolder>();
mScrap.put(viewType, scrap);
if (mMaxScrap.indexOfKey(viewType) < 0) {
mMaxScrap.put(viewType, DEFAULT_MAX_SCRAP);
}
}
return scrap;
}
}
/**
* A Recycler is responsible for managing scrapped or detached item views for reuse.
*
* <p>A "scrapped" view is a view that is still attached to its parent RecyclerView but
* that has been marked for removal or reuse.</p>
*
* <p>Typical use of a Recycler by a {@link LayoutManager} will be to obtain views for
* an adapter's data set representing the data at a given position or item ID.
* If the view to be reused is considered "dirty" the adapter will be asked to rebind it.
* If not, the view can be quickly reused by the LayoutManager with no further work.
* Clean views that have not {@link android.view.View#isLayoutRequested() requested layout}
* may be repositioned by a LayoutManager without remeasurement.</p>
*/
public final class Recycler {
final ArrayList<ViewHolder> mAttachedScrap = new ArrayList<ViewHolder>();
private ArrayList<ViewHolder> mChangedScrap = null;
final ArrayList<ViewHolder> mCachedViews = new ArrayList<ViewHolder>();
private final List<ViewHolder>
mUnmodifiableAttachedScrap = Collections.unmodifiableList(mAttachedScrap);
private int mViewCacheMax = DEFAULT_CACHE_SIZE;
private RecycledViewPool mRecyclerPool;
private ViewCacheExtension mViewCacheExtension;
private static final int DEFAULT_CACHE_SIZE = 2;
/**
* Clear scrap views out of this recycler. Detached views contained within a
* recycled view pool will remain.
*/
public void clear() {
mAttachedScrap.clear();
recycleAndClearCachedViews();
}
/**
* Set the maximum number of detached, valid views we should retain for later use.
*
* @param viewCount Number of views to keep before sending views to the shared pool
*/
public void setViewCacheSize(int viewCount) {
mViewCacheMax = viewCount;
// first, try the views that can be recycled
for (int i = mCachedViews.size() - 1; i >= 0 && mCachedViews.size() > viewCount; i--) {
recycleCachedViewAt(i);
}
}
/**
* Returns an unmodifiable list of ViewHolders that are currently in the scrap list.
*
* @return List of ViewHolders in the scrap list.
*/
public List<ViewHolder> getScrapList() {
return mUnmodifiableAttachedScrap;
}
/**
* Helper method for getViewForPosition.
* <p>
* Checks whether a given view holder can be used for the provided position.
*
* @param holder ViewHolder
* @return true if ViewHolder matches the provided position, false otherwise
*/
boolean validateViewHolderForOffsetPosition(ViewHolder holder) {
// if it is a removed holder, nothing to verify since we cannot ask adapter anymore
// if it is not removed, verify the type and id.
if (holder.isRemoved()) {
return true;
}
if (holder.mPosition < 0 || holder.mPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid view holder "
+ "adapter position" + holder);
}
if (!mState.isPreLayout()) {
// don't check type if it is pre-layout.
final int type = mAdapter.getItemViewType(holder.mPosition);
if (type != holder.getItemViewType()) {
return false;
}
}
if (mAdapter.hasStableIds()) {
return holder.getItemId() == mAdapter.getItemId(holder.mPosition);
}
return true;
}
/**
* Binds the given View to the position. The View can be a View previously retrieved via
* {@link #getViewForPosition(int)} or created by
* {@link Adapter#onCreateViewHolder(ViewGroup, int)}.
* <p>
* Generally, a LayoutManager should acquire its views via {@link #getViewForPosition(int)}
* and let the RecyclerView handle caching. This is a helper method for LayoutManager who
* wants to handle its own recycling logic.
* <p>
* Note that, {@link #getViewForPosition(int)} already binds the View to the position so
* you don't need to call this method unless you want to bind this View to another position.
*
* @param view The view to update.
* @param position The position of the item to bind to this View.
*/
public void bindViewToPosition(View view, int position) {
ViewHolder holder = getChildViewHolderInt(view);
if (holder == null) {
throw new IllegalArgumentException("The view does not have a ViewHolder. You cannot"
+ " pass arbitrary views to this method, they should be created by the "
+ "Adapter");
}
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
+ "position " + position + "(offset:" + offsetPosition + ")."
+ "state:" + mState.getItemCount());
}
holder.mOwnerRecyclerView = RecyclerView.this;
mAdapter.bindViewHolder(holder, offsetPosition);
attachAccessibilityDelegate(view);
if (mState.isPreLayout()) {
holder.mPreLayoutPosition = position;
}
final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
final LayoutParams rvLayoutParams;
if (lp == null) {
rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();
holder.itemView.setLayoutParams(rvLayoutParams);
} else if (!checkLayoutParams(lp)) {
rvLayoutParams = (LayoutParams) generateLayoutParams(lp);
holder.itemView.setLayoutParams(rvLayoutParams);
} else {
rvLayoutParams = (LayoutParams) lp;
}
rvLayoutParams.mInsetsDirty = true;
rvLayoutParams.mViewHolder = holder;
rvLayoutParams.mPendingInvalidate = holder.itemView.getParent() == null;
}
/**
* RecyclerView provides artificial position range (item count) in pre-layout state and
* automatically maps these positions to {@link Adapter} positions when
* {@link #getViewForPosition(int)} or {@link #bindViewToPosition(View, int)} is called.
* <p>
* Usually, LayoutManager does not need to worry about this. However, in some cases, your
* LayoutManager may need to call some custom component with item positions in which
* case you need the actual adapter position instead of the pre layout position. You
* can use this method to convert a pre-layout position to adapter (post layout) position.
* <p>
* Note that if the provided position belongs to a deleted ViewHolder, this method will
* return -1.
* <p>
* Calling this method in post-layout state returns the same value back.
*
* @param position The pre-layout position to convert. Must be greater or equal to 0 and
* less than {@link State#getItemCount()}.
*/
public int convertPreLayoutPositionToPostLayout(int position) {
if (position < 0 || position >= mState.getItemCount()) {
throw new IndexOutOfBoundsException("invalid position " + position + ". State "
+ "item count is " + mState.getItemCount());
}
if (!mState.isPreLayout()) {
return position;
}
return mAdapterHelper.findPositionOffset(position);
}
/**
* Obtain a view initialized for the given position.
*
* This method should be used by {@link LayoutManager} implementations to obtain
* views to represent data from an {@link Adapter}.
* <p>
* The Recycler may reuse a scrap or detached view from a shared pool if one is
* available for the correct view type. If the adapter has not indicated that the
* data at the given position has changed, the Recycler will attempt to hand back
* a scrap view that was previously initialized for that data without rebinding.
*
* @param position Position to obtain a view for
* @return A view representing the data at <code>position</code> from <code>adapter</code>
*/
public View getViewForPosition(int position) {
return getViewForPosition(position, false);
}
View getViewForPosition(int position, boolean dryRun) {
if (position < 0 || position >= mState.getItemCount()) {
throw new IndexOutOfBoundsException("Invalid item position " + position
+ "(" + position + "). Item count:" + mState.getItemCount());
}
boolean fromScrap = false;
ViewHolder holder = null;
// 0) If there is a changed scrap, try to find from there
if (mState.isPreLayout()) {
holder = getChangedScrapViewForPosition(position);
fromScrap = holder != null;
}
// 1) Find from scrap by position
if (holder == null) {
holder = getScrapViewForPosition(position, INVALID_TYPE, dryRun);
if (holder != null) {
if (!validateViewHolderForOffsetPosition(holder)) {
// recycle this scrap
if (!dryRun) {
// we would like to recycle this but need to make sure it is not used by
// animation logic etc.
holder.addFlags(ViewHolder.FLAG_INVALID);
if (holder.isScrap()) {
removeDetachedView(holder.itemView, false);
holder.unScrap();
} else if (holder.wasReturnedFromScrap()) {
holder.clearReturnedFromScrapFlag();
}
recycleViewHolderInternal(holder);
}
holder = null;
} else {
fromScrap = true;
}
}
}
if (holder == null) {
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
+ "position " + position + "(offset:" + offsetPosition + ")."
+ "state:" + mState.getItemCount());
}
final int type = mAdapter.getItemViewType(offsetPosition);
// 2) Find from scrap via stable ids, if exists
if (mAdapter.hasStableIds()) {
holder = getScrapViewForId(mAdapter.getItemId(offsetPosition), type, dryRun);
if (holder != null) {
// update position
holder.mPosition = offsetPosition;
fromScrap = true;
}
}
if (holder == null && mViewCacheExtension != null) {
// We are NOT sending the offsetPosition because LayoutManager does not
// know it.
final View view = mViewCacheExtension
.getViewForPositionAndType(this, position, type);
if (view != null) {
holder = getChildViewHolder(view);
if (holder == null) {
throw new IllegalArgumentException("getViewForPositionAndType returned"
+ " a view which does not have a ViewHolder");
} else if (holder.shouldIgnore()) {
throw new IllegalArgumentException("getViewForPositionAndType returned"
+ " a view that is ignored. You must call stopIgnoring before"
+ " returning this view.");
}
}
}
if (holder == null) { // fallback to recycler
// try recycler.
// Head to the shared pool.
if (DEBUG) {
Log.d(TAG, "getViewForPosition(" + position + ") fetching from shared "
+ "pool");
}
holder = getRecycledViewPool().getRecycledView(type);
if (holder != null) {
holder.resetInternal();
if (FORCE_INVALIDATE_DISPLAY_LIST) {
invalidateDisplayListInt(holder);
}
}
}
if (holder == null) {
holder = mAdapter.createViewHolder(RecyclerView.this, type);
if (DEBUG) {
Log.d(TAG, "getViewForPosition created new ViewHolder");
}
}
}
boolean bound = false;
if (mState.isPreLayout() && holder.isBound()) {
// do not update unless we absolutely have to.
holder.mPreLayoutPosition = position;
} else if (!holder.isBound() || holder.needsUpdate() || holder.isInvalid()) {
if (DEBUG && holder.isRemoved()) {
throw new IllegalStateException("Removed holder should be bound and it should"
+ " come here only in pre-layout. Holder: " + holder);
}
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
holder.mOwnerRecyclerView = RecyclerView.this;
mAdapter.bindViewHolder(holder, offsetPosition);
attachAccessibilityDelegate(holder.itemView);
bound = true;
if (mState.isPreLayout()) {
holder.mPreLayoutPosition = position;
}
}
final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
final LayoutParams rvLayoutParams;
if (lp == null) {
rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();
holder.itemView.setLayoutParams(rvLayoutParams);
} else if (!checkLayoutParams(lp)) {
rvLayoutParams = (LayoutParams) generateLayoutParams(lp);
holder.itemView.setLayoutParams(rvLayoutParams);
} else {
rvLayoutParams = (LayoutParams) lp;
}
rvLayoutParams.mViewHolder = holder;
rvLayoutParams.mPendingInvalidate = fromScrap && bound;
return holder.itemView;
}
private void attachAccessibilityDelegate(View itemView) {
if (mAccessibilityManager != null && mAccessibilityManager.isEnabled()) {
if (ViewCompat.getImportantForAccessibility(itemView) ==
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
ViewCompat.setImportantForAccessibility(itemView,
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
if (!ViewCompat.hasAccessibilityDelegate(itemView)) {
ViewCompat.setAccessibilityDelegate(itemView,
mAccessibilityDelegate.getItemDelegate());
}
}
}
private void invalidateDisplayListInt(ViewHolder holder) {
if (holder.itemView instanceof ViewGroup) {
invalidateDisplayListInt((ViewGroup) holder.itemView, false);
}
}
private void invalidateDisplayListInt(ViewGroup viewGroup, boolean invalidateThis) {
for (int i = viewGroup.getChildCount() - 1; i >= 0; i--) {
final View view = viewGroup.getChildAt(i);
if (view instanceof ViewGroup) {
invalidateDisplayListInt((ViewGroup) view, true);
}
}
if (!invalidateThis) {
return;
}
// we need to force it to become invisible
if (viewGroup.getVisibility() == View.INVISIBLE) {
viewGroup.setVisibility(View.VISIBLE);
viewGroup.setVisibility(View.INVISIBLE);
} else {
final int visibility = viewGroup.getVisibility();
viewGroup.setVisibility(View.INVISIBLE);
viewGroup.setVisibility(visibility);
}
}
/**
* Recycle a detached view. The specified view will be added to a pool of views
* for later rebinding and reuse.
*
* <p>A view must be fully detached (removed from parent) before it may be recycled. If the
* View is scrapped, it will be removed from scrap list.</p>
*
* @param view Removed view for recycling
* @see LayoutManager#removeAndRecycleView(View, Recycler)
*/
public void recycleView(View view) {
// This public recycle method tries to make view recycle-able since layout manager
// intended to recycle this view (e.g. even if it is in scrap or change cache)
ViewHolder holder = getChildViewHolderInt(view);
if (holder.isTmpDetached()) {
removeDetachedView(view, false);
}
if (holder.isScrap()) {
holder.unScrap();
} else if (holder.wasReturnedFromScrap()){
holder.clearReturnedFromScrapFlag();
}
recycleViewHolderInternal(holder);
}
/**
* Internally, use this method instead of {@link #recycleView(android.view.View)} to
* catch potential bugs.
* @param view
*/
void recycleViewInternal(View view) {
recycleViewHolderInternal(getChildViewHolderInt(view));
}
void recycleAndClearCachedViews() {
final int count = mCachedViews.size();
for (int i = count - 1; i >= 0; i--) {
recycleCachedViewAt(i);
}
mCachedViews.clear();
}
/**
* Recycles a cached view and removes the view from the list. Views are added to cache
* if and only if they are recyclable, so this method does not check it again.
* <p>
* A small exception to this rule is when the view does not have an animator reference
* but transient state is true (due to animations created outside ItemAnimator). In that
* case, adapter may choose to recycle it. From RecyclerView's perspective, the view is
* still recyclable since Adapter wants to do so.
*
* @param cachedViewIndex The index of the view in cached views list
*/
void recycleCachedViewAt(int cachedViewIndex) {
if (DEBUG) {
Log.d(TAG, "Recycling cached view at index " + cachedViewIndex);
}
ViewHolder viewHolder = mCachedViews.get(cachedViewIndex);
if (DEBUG) {
Log.d(TAG, "CachedViewHolder to be recycled: " + viewHolder);
}
addViewHolderToRecycledViewPool(viewHolder);
mCachedViews.remove(cachedViewIndex);
}
/**
* internal implementation checks if view is scrapped or attached and throws an exception
* if so.
* Public version un-scraps before calling recycle.
*/
void recycleViewHolderInternal(ViewHolder holder) {
if (holder.isScrap() || holder.itemView.getParent() != null) {
throw new IllegalArgumentException(
"Scrapped or attached views may not be recycled. isScrap:"
+ holder.isScrap() + " isAttached:"
+ (holder.itemView.getParent() != null));
}
if (holder.isTmpDetached()) {
throw new IllegalArgumentException("Tmp detached view should be removed "
+ "from RecyclerView before it can be recycled: " + holder);
}
if (holder.shouldIgnore()) {
throw new IllegalArgumentException("Trying to recycle an ignored view holder. You"
+ " should first call stopIgnoringView(view) before calling recycle.");
}
//noinspection unchecked
final boolean transientStatePreventsRecycling = holder
.doesTransientStatePreventRecycling();
final boolean forceRecycle = mAdapter != null
&& transientStatePreventsRecycling
&& mAdapter.onFailedToRecycleView(holder);
boolean cached = false;
boolean recycled = false;
if (forceRecycle || holder.isRecyclable()) {
if (!holder.isInvalid() && (mState.mInPreLayout || !holder.isRemoved()) &&
!holder.isChanged()) {
// Retire oldest cached view
final int cachedViewSize = mCachedViews.size();
if (cachedViewSize == mViewCacheMax && cachedViewSize > 0) {
recycleCachedViewAt(0);
}
if (cachedViewSize < mViewCacheMax) {
mCachedViews.add(holder);
cached = true;
}
}
if (!cached) {
addViewHolderToRecycledViewPool(holder);
recycled = true;
}
} else if (DEBUG) {
Log.d(TAG, "trying to recycle a non-recycleable holder. Hopefully, it will "
+ "re-visit here. We are still removing it from animation lists");
}
// even if the holder is not removed, we still call this method so that it is removed
// from view holder lists.
mState.onViewRecycled(holder);
if (!cached && !recycled && transientStatePreventsRecycling) {
holder.mOwnerRecyclerView = null;
}
}
void addViewHolderToRecycledViewPool(ViewHolder holder) {
ViewCompat.setAccessibilityDelegate(holder.itemView, null);
dispatchViewRecycled(holder);
holder.mOwnerRecyclerView = null;
getRecycledViewPool().putRecycledView(holder);
}
/**
* Used as a fast path for unscrapping and recycling a view during a bulk operation.
* The caller must call {@link #clearScrap()} when it's done to update the recycler's
* internal bookkeeping.
*/
void quickRecycleScrapView(View view) {
final ViewHolder holder = getChildViewHolderInt(view);
holder.mScrapContainer = null;
holder.clearReturnedFromScrapFlag();
recycleViewHolderInternal(holder);
}
/**
* Mark an attached view as scrap.
*
* <p>"Scrap" views are still attached to their parent RecyclerView but are eligible
* for rebinding and reuse. Requests for a view for a given position may return a
* reused or rebound scrap view instance.</p>
*
* @param view View to scrap
*/
void scrapView(View view) {
final ViewHolder holder = getChildViewHolderInt(view);
holder.setScrapContainer(this);
if (!holder.isChanged() || !supportsChangeAnimations()) {
if (holder.isInvalid() && !holder.isRemoved() && !mAdapter.hasStableIds()) {
throw new IllegalArgumentException("Called scrap view with an invalid view."
+ " Invalid views cannot be reused from scrap, they should rebound from"
+ " recycler pool.");
}
mAttachedScrap.add(holder);
} else {
if (mChangedScrap == null) {
mChangedScrap = new ArrayList<ViewHolder>();
}
mChangedScrap.add(holder);
}
}
/**
* Remove a previously scrapped view from the pool of eligible scrap.
*
* <p>This view will no longer be eligible for reuse until re-scrapped or
* until it is explicitly removed and recycled.</p>
*/
void unscrapView(ViewHolder holder) {
if (!holder.isChanged() || !supportsChangeAnimations() || mChangedScrap == null) {
mAttachedScrap.remove(holder);
} else {
mChangedScrap.remove(holder);
}
holder.mScrapContainer = null;
holder.clearReturnedFromScrapFlag();
}
int getScrapCount() {
return mAttachedScrap.size();
}
View getScrapViewAt(int index) {
return mAttachedScrap.get(index).itemView;
}
void clearScrap() {
mAttachedScrap.clear();
}
ViewHolder getChangedScrapViewForPosition(int position) {
// If pre-layout, check the changed scrap for an exact match.
final int changedScrapSize;
if (mChangedScrap == null || (changedScrapSize = mChangedScrap.size()) == 0) {
return null;
}
// find by position
for (int i = 0; i < changedScrapSize; i++) {
final ViewHolder holder = mChangedScrap.get(i);
if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position) {
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
return holder;
}
}
// find by id
if (mAdapter.hasStableIds()) {
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
if (offsetPosition > 0 && offsetPosition < mAdapter.getItemCount()) {
final long id = mAdapter.getItemId(offsetPosition);
for (int i = 0; i < changedScrapSize; i++) {
final ViewHolder holder = mChangedScrap.get(i);
if (!holder.wasReturnedFromScrap() && holder.getItemId() == id) {
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
return holder;
}
}
}
}
return null;
}
/**
* Returns a scrap view for the position. If type is not INVALID_TYPE, it also checks if
* ViewHolder's type matches the provided type.
*
* @param position Item position
* @param type View type
* @param dryRun Does a dry run, finds the ViewHolder but does not remove
* @return a ViewHolder that can be re-used for this position.
*/
ViewHolder getScrapViewForPosition(int position, int type, boolean dryRun) {
final int scrapCount = mAttachedScrap.size();
// Try first for an exact, non-invalid match from scrap.
for (int i = 0; i < scrapCount; i++) {
final ViewHolder holder = mAttachedScrap.get(i);
if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position
&& !holder.isInvalid() && (mState.mInPreLayout || !holder.isRemoved())) {
if (type != INVALID_TYPE && holder.getItemViewType() != type) {
Log.e(TAG, "Scrap view for position " + position + " isn't dirty but has" +
" wrong view type! (found " + holder.getItemViewType() +
" but expected " + type + ")");
break;
}
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
return holder;
}
}
if (!dryRun) {
View view = mChildHelper.findHiddenNonRemovedView(position, type);
if (view != null) {
// ending the animation should cause it to get recycled before we reuse it
mItemAnimator.endAnimation(getChildViewHolder(view));
}
}
// Search in our first-level recycled view cache.
final int cacheSize = mCachedViews.size();
for (int i = 0; i < cacheSize; i++) {
final ViewHolder holder = mCachedViews.get(i);
// invalid view holders may be in cache if adapter has stable ids as they can be
// retrieved via getScrapViewForId
if (!holder.isInvalid() && holder.getLayoutPosition() == position) {
if (!dryRun) {
mCachedViews.remove(i);
}
if (DEBUG) {
Log.d(TAG, "getScrapViewForPosition(" + position + ", " + type +
") found match in cache: " + holder);
}
return holder;
}
}
return null;
}
ViewHolder getScrapViewForId(long id, int type, boolean dryRun) {
// Look in our attached views first
final int count = mAttachedScrap.size();
for (int i = count - 1; i >= 0; i--) {
final ViewHolder holder = mAttachedScrap.get(i);
if (holder.getItemId() == id && !holder.wasReturnedFromScrap()) {
if (type == holder.getItemViewType()) {
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
if (holder.isRemoved()) {
// this might be valid in two cases:
// > item is removed but we are in pre-layout pass
// >> do nothing. return as is. make sure we don't rebind
// > item is removed then added to another position and we are in
// post layout.
// >> remove removed and invalid flags, add update flag to rebind
// because item was invisible to us and we don't know what happened in
// between.
if (!mState.isPreLayout()) {
holder.setFlags(ViewHolder.FLAG_UPDATE, ViewHolder.FLAG_UPDATE |
ViewHolder.FLAG_INVALID | ViewHolder.FLAG_REMOVED);
}
}
return holder;
} else if (!dryRun) {
// Recycle this scrap. Type mismatch.
mAttachedScrap.remove(i);
removeDetachedView(holder.itemView, false);
quickRecycleScrapView(holder.itemView);
}
}
}
// Search the first-level cache
final int cacheSize = mCachedViews.size();
for (int i = cacheSize - 1; i >= 0; i--) {
final ViewHolder holder = mCachedViews.get(i);
if (holder.getItemId() == id) {
if (type == holder.getItemViewType()) {
if (!dryRun) {
mCachedViews.remove(i);
}
return holder;
} else if (!dryRun) {
recycleCachedViewAt(i);
}
}
}
return null;
}
void dispatchViewRecycled(ViewHolder holder) {
if (mRecyclerListener != null) {
mRecyclerListener.onViewRecycled(holder);
}
if (mAdapter != null) {
mAdapter.onViewRecycled(holder);
}
if (mState != null) {
mState.onViewRecycled(holder);
}
if (DEBUG) Log.d(TAG, "dispatchViewRecycled: " + holder);
}
void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter,
boolean compatibleWithPrevious) {
clear();
getRecycledViewPool().onAdapterChanged(oldAdapter, newAdapter, compatibleWithPrevious);
}
void offsetPositionRecordsForMove(int from, int to) {
final int start, end, inBetweenOffset;
if (from < to) {
start = from;
end = to;
inBetweenOffset = -1;
} else {
start = to;
end = from;
inBetweenOffset = 1;
}
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder == null || holder.mPosition < start || holder.mPosition > end) {
continue;
}
if (holder.mPosition == from) {
holder.offsetPosition(to - from, false);
} else {
holder.offsetPosition(inBetweenOffset, false);
}
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForMove cached child " + i + " holder " +
holder);
}
}
}
void offsetPositionRecordsForInsert(int insertedAt, int count) {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null && holder.getLayoutPosition() >= insertedAt) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForInsert cached " + i + " holder " +
holder + " now at position " + (holder.mPosition + count));
}
holder.offsetPosition(count, true);
}
}
}
/**
* @param removedFrom Remove start index
* @param count Remove count
* @param applyToPreLayout If true, changes will affect ViewHolder's pre-layout position, if
* false, they'll be applied before the second layout pass
*/
void offsetPositionRecordsForRemove(int removedFrom, int count, boolean applyToPreLayout) {
final int removedEnd = removedFrom + count;
final int cachedCount = mCachedViews.size();
for (int i = cachedCount - 1; i >= 0; i--) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null) {
if (holder.getLayoutPosition() >= removedEnd) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove cached " + i +
" holder " + holder + " now at position " +
(holder.mPosition - count));
}
holder.offsetPosition(-count, applyToPreLayout);
} else if (holder.getLayoutPosition() >= removedFrom) {
// Item for this view was removed. Dump it from the cache.
holder.addFlags(ViewHolder.FLAG_REMOVED);
recycleCachedViewAt(i);
}
}
}
}
void setViewCacheExtension(ViewCacheExtension extension) {
mViewCacheExtension = extension;
}
void setRecycledViewPool(RecycledViewPool pool) {
if (mRecyclerPool != null) {
mRecyclerPool.detach();
}
mRecyclerPool = pool;
if (pool != null) {
mRecyclerPool.attach(getAdapter());
}
}
RecycledViewPool getRecycledViewPool() {
if (mRecyclerPool == null) {
mRecyclerPool = new RecycledViewPool();
}
return mRecyclerPool;
}
void viewRangeUpdate(int positionStart, int itemCount) {
final int positionEnd = positionStart + itemCount;
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder == null) {
continue;
}
final int pos = holder.getLayoutPosition();
if (pos >= positionStart && pos < positionEnd) {
holder.addFlags(ViewHolder.FLAG_UPDATE);
// cached views should not be flagged as changed because this will cause them
// to animate when they are returned from cache.
}
}
}
void setAdapterPositionsAsUnknown() {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null) {
holder.addFlags(ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN);
}
}
}
void markKnownViewsInvalid() {
if (mAdapter != null && mAdapter.hasStableIds()) {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null) {
holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID);
}
}
} else {
// we cannot re-use cached views in this case. Recycle them all
recycleAndClearCachedViews();
}
}
void clearOldPositions() {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
holder.clearOldPosition();
}
final int scrapCount = mAttachedScrap.size();
for (int i = 0; i < scrapCount; i++) {
mAttachedScrap.get(i).clearOldPosition();
}
if (mChangedScrap != null) {
final int changedScrapCount = mChangedScrap.size();
for (int i = 0; i < changedScrapCount; i++) {
mChangedScrap.get(i).clearOldPosition();
}
}
}
void markItemDecorInsetsDirty() {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
LayoutParams layoutParams = (LayoutParams) holder.itemView.getLayoutParams();
if (layoutParams != null) {
layoutParams.mInsetsDirty = true;
}
}
}
}
/**
* ViewCacheExtension is a helper class to provide an additional layer of view caching that can
* ben controlled by the developer.
* <p>
* When {@link Recycler#getViewForPosition(int)} is called, Recycler checks attached scrap and
* first level cache to find a matching View. If it cannot find a suitable View, Recycler will
* call the {@link #getViewForPositionAndType(Recycler, int, int)} before checking
* {@link RecycledViewPool}.
* <p>
* Note that, Recycler never sends Views to this method to be cached. It is developers
* responsibility to decide whether they want to keep their Views in this custom cache or let
* the default recycling policy handle it.
*/
public abstract static class ViewCacheExtension {
/**
* Returns a View that can be binded to the given Adapter position.
* <p>
* This method should <b>not</b> create a new View. Instead, it is expected to return
* an already created View that can be re-used for the given type and position.
* If the View is marked as ignored, it should first call
* {@link LayoutManager#stopIgnoringView(View)} before returning the View.
* <p>
* RecyclerView will re-bind the returned View to the position if necessary.
*
* @param recycler The Recycler that can be used to bind the View
* @param position The adapter position
* @param type The type of the View, defined by adapter
* @return A View that is bound to the given position or NULL if there is no View to re-use
* @see LayoutManager#ignoreView(View)
*/
abstract public View getViewForPositionAndType(Recycler recycler, int position, int type);
}
/**
* Base class for an Adapter
*
* <p>Adapters provide a binding from an app-specific data set to views that are displayed
* within a {@link RecyclerView}.</p>
*/
public static abstract class Adapter<VH extends ViewHolder> {
private final AdapterDataObservable mObservable = new AdapterDataObservable();
private boolean mHasStableIds = false;
/**
* Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent
* an item.
* <p>
* This new ViewHolder should be constructed with a new View that can represent the items
* of the given type. You can either create a new View manually or inflate it from an XML
* layout file.
* <p>
* The new ViewHolder will be used to display items of the adapter using
* {@link #onBindViewHolder(ViewHolder, int)}. Since it will be re-used to display different
* items in the data set, it is a good idea to cache references to sub views of the View to
* avoid unnecessary {@link View#findViewById(int)} calls.
*
* @param parent The ViewGroup into which the new View will be added after it is bound to
* an adapter position.
* @param viewType The view type of the new View.
*
* @return A new ViewHolder that holds a View of the given view type.
* @see #getItemViewType(int)
* @see #onBindViewHolder(ViewHolder, int)
*/
public abstract VH onCreateViewHolder(ViewGroup parent, int viewType);
/**
* Called by RecyclerView to display the data at the specified position. This method
* should update the contents of the {@link ViewHolder#itemView} to reflect the item at
* the given position.
* <p>
* Note that unlike {@link android.widget.ListView}, RecyclerView will not call this
* method again if the position of the item changes in the data set unless the item itself
* is invalidated or the new position cannot be determined. For this reason, you should only
* use the <code>position</code> parameter while acquiring the related data item inside this
* method and should not keep a copy of it. If you need the position of an item later on
* (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will have
* the updated adapter position.
*
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter's data set.
*/
public abstract void onBindViewHolder(VH holder, int position);
/**
* This method calls {@link #onCreateViewHolder(ViewGroup, int)} to create a new
* {@link ViewHolder} and initializes some private fields to be used by RecyclerView.
*
* @see #onCreateViewHolder(ViewGroup, int)
*/
public final VH createViewHolder(ViewGroup parent, int viewType) {
final VH holder = onCreateViewHolder(parent, viewType);
holder.mItemViewType = viewType;
return holder;
}
/**
* This method internally calls {@link #onBindViewHolder(ViewHolder, int)} to update the
* {@link ViewHolder} contents with the item at the given position and also sets up some
* private fields to be used by RecyclerView.
*
* @see #onBindViewHolder(ViewHolder, int)
*/
public final void bindViewHolder(VH holder, int position) {
holder.mPosition = position;
if (hasStableIds()) {
holder.mItemId = getItemId(position);
}
holder.setFlags(ViewHolder.FLAG_BOUND,
ViewHolder.FLAG_BOUND | ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID
| ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN);
onBindViewHolder(holder, position);
}
/**
* Return the view type of the item at <code>position</code> for the purposes
* of view recycling.
*
* <p>The default implementation of this method returns 0, making the assumption of
* a single view type for the adapter. Unlike ListView adapters, types need not
* be contiguous. Consider using id resources to uniquely identify item view types.
*
* @param position position to query
* @return integer value identifying the type of the view needed to represent the item at
* <code>position</code>. Type codes need not be contiguous.
*/
public int getItemViewType(int position) {
return 0;
}
/**
* Indicates whether each item in the data set can be represented with a unique identifier
* of type {@link java.lang.Long}.
*
* @param hasStableIds Whether items in data set have unique identifiers or not.
* @see #hasStableIds()
* @see #getItemId(int)
*/
public void setHasStableIds(boolean hasStableIds) {
if (hasObservers()) {
throw new IllegalStateException("Cannot change whether this adapter has " +
"stable IDs while the adapter has registered observers.");
}
mHasStableIds = hasStableIds;
}
/**
* Return the stable ID for the item at <code>position</code>. If {@link #hasStableIds()}
* would return false this method should return {@link #NO_ID}. The default implementation
* of this method returns {@link #NO_ID}.
*
* @param position Adapter position to query
* @return the stable ID of the item at position
*/
public long getItemId(int position) {
return NO_ID;
}
/**
* Returns the total number of items in the data set hold by the adapter.
*
* @return The total number of items in this adapter.
*/
public abstract int getItemCount();
/**
* Returns true if this adapter publishes a unique <code>long</code> value that can
* act as a key for the item at a given position in the data set. If that item is relocated
* in the data set, the ID returned for that item should be the same.
*
* @return true if this adapter's items have stable IDs
*/
public final boolean hasStableIds() {
return mHasStableIds;
}
/**
* Called when a view created by this adapter has been recycled.
*
* <p>A view is recycled when a {@link LayoutManager} decides that it no longer
* needs to be attached to its parent {@link RecyclerView}. This can be because it has
* fallen out of visibility or a set of cached views represented by views still
* attached to the parent RecyclerView. If an item view has large or expensive data
* bound to it such as large bitmaps, this may be a good place to release those
* resources.</p>
* <p>
* RecyclerView calls this method right before clearing ViewHolder's internal data and
* sending it to RecycledViewPool. This way, if ViewHolder was holding valid information
* before being recycled, you can call {@link ViewHolder#getAdapterPosition()} to get
* its adapter position.
*
* @param holder The ViewHolder for the view being recycled
*/
public void onViewRecycled(VH holder) {
}
/**
* Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycled
* due to its transient state. Upon receiving this callback, Adapter can clear the
* animation(s) that effect the View's transient state and return <code>true</code> so that
* the View can be recycled. Keep in mind that the View in question is already removed from
* the RecyclerView.
* <p>
* In some cases, it is acceptable to recycle a View although it has transient state. Most
* of the time, this is a case where the transient state will be cleared in
* {@link #onBindViewHolder(ViewHolder, int)} call when View is rebound to a new position.
* For this reason, RecyclerView leaves the decision to the Adapter and uses the return
* value of this method to decide whether the View should be recycled or not.
* <p>
* Note that when all animations are created by {@link RecyclerView.ItemAnimator}, you
* should never receive this callback because RecyclerView keeps those Views as children
* until their animations are complete. This callback is useful when children of the item
* views create animations which may not be easy to implement using an {@link ItemAnimator}.
* <p>
* You should <em>never</em> fix this issue by calling
* <code>holder.itemView.setHasTransientState(false);</code> unless you've previously called
* <code>holder.itemView.setHasTransientState(true);</code>. Each
* <code>View.setHasTransientState(true)</code> call must be matched by a
* <code>View.setHasTransientState(false)</code> call, otherwise, the state of the View
* may become inconsistent. You should always prefer to end or cancel animations that are
* triggering the transient state instead of handling it manually.
*
* @param holder The ViewHolder containing the View that could not be recycled due to its
* transient state.
* @return True if the View should be recycled, false otherwise. Note that if this method
* returns <code>true</code>, RecyclerView <em>will ignore</em> the transient state of
* the View and recycle it regardless. If this method returns <code>false</code>,
* RecyclerView will check the View's transient state again before giving a final decision.
* Default implementation returns false.
*/
public boolean onFailedToRecycleView(VH holder) {
return false;
}
/**
* Called when a view created by this adapter has been attached to a window.
*
* <p>This can be used as a reasonable signal that the view is about to be seen
* by the user. If the adapter previously freed any resources in
* {@link #onViewDetachedFromWindow(RecyclerView.ViewHolder) onViewDetachedFromWindow}
* those resources should be restored here.</p>
*
* @param holder Holder of the view being attached
*/
public void onViewAttachedToWindow(VH holder) {
}
/**
* Called when a view created by this adapter has been detached from its window.
*
* <p>Becoming detached from the window is not necessarily a permanent condition;
* the consumer of an Adapter's views may choose to cache views offscreen while they
* are not visible, attaching an detaching them as appropriate.</p>
*
* @param holder Holder of the view being detached
*/
public void onViewDetachedFromWindow(VH holder) {
}
/**
* Returns true if one or more observers are attached to this adapter.
*
* @return true if this adapter has observers
*/
public final boolean hasObservers() {
return mObservable.hasObservers();
}
/**
* Register a new observer to listen for data changes.
*
* <p>The adapter may publish a variety of events describing specific changes.
* Not all adapters may support all change types and some may fall back to a generic
* {@link android.support.v7.widget.RecyclerView.AdapterDataObserver#onChanged()
* "something changed"} event if more specific data is not available.</p>
*
* <p>Components registering observers with an adapter are responsible for
* {@link #unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver)
* unregistering} those observers when finished.</p>
*
* @param observer Observer to register
*
* @see #unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver)
*/
public void registerAdapterDataObserver(AdapterDataObserver observer) {
mObservable.registerObserver(observer);
}
/**
* Unregister an observer currently listening for data changes.
*
* <p>The unregistered observer will no longer receive events about changes
* to the adapter.</p>
*
* @param observer Observer to unregister
*
* @see #registerAdapterDataObserver(RecyclerView.AdapterDataObserver)
*/
public void unregisterAdapterDataObserver(AdapterDataObserver observer) {
mObservable.unregisterObserver(observer);
}
/**
* Called by RecyclerView when it starts observing this Adapter.
* <p>
* Keep in mind that same adapter may be observed by multiple RecyclerViews.
*
* @param recyclerView The RecyclerView instance which started observing this adapter.
* @see #onDetachedFromRecyclerView(RecyclerView)
*/
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
}
/**
* Called by RecyclerView when it stops observing this Adapter.
*
* @param recyclerView The RecyclerView instance which stopped observing this adapter.
* @see #onAttachedToRecyclerView(RecyclerView)
*/
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
}
/**
* Notify any registered observers that the data set has changed.
*
* <p>There are two different classes of data change events, item changes and structural
* changes. Item changes are when a single item has its data updated but no positional
* changes have occurred. Structural changes are when items are inserted, removed or moved
* within the data set.</p>
*
* <p>This event does not specify what about the data set has changed, forcing
* any observers to assume that all existing items and structure may no longer be valid.
* LayoutManagers will be forced to fully rebind and relayout all visible views.</p>
*
* <p><code>RecyclerView</code> will attempt to synthesize visible structural change events
* for adapters that report that they have {@link #hasStableIds() stable IDs} when
* this method is used. This can help for the purposes of animation and visual
* object persistence but individual item views will still need to be rebound
* and relaid out.</p>
*
* <p>If you are writing an adapter it will always be more efficient to use the more
* specific change events if you can. Rely on <code>notifyDataSetChanged()</code>
* as a last resort.</p>
*
* @see #notifyItemChanged(int)
* @see #notifyItemInserted(int)
* @see #notifyItemRemoved(int)
* @see #notifyItemRangeChanged(int, int)
* @see #notifyItemRangeInserted(int, int)
* @see #notifyItemRangeRemoved(int, int)
*/
public final void notifyDataSetChanged() {
mObservable.notifyChanged();
}
/**
* Notify any registered observers that the item at <code>position</code> has changed.
*
* <p>This is an item change event, not a structural change event. It indicates that any
* reflection of the data at <code>position</code> is out of date and should be updated.
* The item at <code>position</code> retains the same identity.</p>
*
* @param position Position of the item that has changed
*
* @see #notifyItemRangeChanged(int, int)
*/
public final void notifyItemChanged(int position) {
mObservable.notifyItemRangeChanged(position, 1);
}
/**
* Notify any registered observers that the <code>itemCount</code> items starting at
* position <code>positionStart</code> have changed.
*
* <p>This is an item change event, not a structural change event. It indicates that
* any reflection of the data in the given position range is out of date and should
* be updated. The items in the given range retain the same identity.</p>
*
* @param positionStart Position of the first item that has changed
* @param itemCount Number of items that have changed
*
* @see #notifyItemChanged(int)
*/
public final void notifyItemRangeChanged(int positionStart, int itemCount) {
mObservable.notifyItemRangeChanged(positionStart, itemCount);
}
/**
* Notify any registered observers that the item reflected at <code>position</code>
* has been newly inserted. The item previously at <code>position</code> is now at
* position <code>position + 1</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param position Position of the newly inserted item in the data set
*
* @see #notifyItemRangeInserted(int, int)
*/
public final void notifyItemInserted(int position) {
mObservable.notifyItemRangeInserted(position, 1);
}
/**
* Notify any registered observers that the item reflected at <code>fromPosition</code>
* has been moved to <code>toPosition</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param fromPosition Previous position of the item.
* @param toPosition New position of the item.
*/
public final void notifyItemMoved(int fromPosition, int toPosition) {
mObservable.notifyItemMoved(fromPosition, toPosition);
}
/**
* Notify any registered observers that the currently reflected <code>itemCount</code>
* items starting at <code>positionStart</code> have been newly inserted. The items
* previously located at <code>positionStart</code> and beyond can now be found starting
* at position <code>positionStart + itemCount</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param positionStart Position of the first item that was inserted
* @param itemCount Number of items inserted
*
* @see #notifyItemInserted(int)
*/
public final void notifyItemRangeInserted(int positionStart, int itemCount) {
mObservable.notifyItemRangeInserted(positionStart, itemCount);
}
/**
* Notify any registered observers that the item previously located at <code>position</code>
* has been removed from the data set. The items previously located at and after
* <code>position</code> may now be found at <code>oldPosition - 1</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param position Position of the item that has now been removed
*
* @see #notifyItemRangeRemoved(int, int)
*/
public final void notifyItemRemoved(int position) {
mObservable.notifyItemRangeRemoved(position, 1);
}
/**
* Notify any registered observers that the <code>itemCount</code> items previously
* located at <code>positionStart</code> have been removed from the data set. The items
* previously located at and after <code>positionStart + itemCount</code> may now be found
* at <code>oldPosition - itemCount</code>.
*
* <p>This is a structural change event. Representations of other existing items in the data
* set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param positionStart Previous position of the first item that was removed
* @param itemCount Number of items removed from the data set
*/
public final void notifyItemRangeRemoved(int positionStart, int itemCount) {
mObservable.notifyItemRangeRemoved(positionStart, itemCount);
}
}
private void dispatchChildDetached(View child) {
if (mAdapter != null) {
mAdapter.onViewDetachedFromWindow(getChildViewHolderInt(child));
}
onChildDetachedFromWindow(child);
}
private void dispatchChildAttached(View child) {
if (mAdapter != null) {
mAdapter.onViewAttachedToWindow(getChildViewHolderInt(child));
}
onChildAttachedToWindow(child);
}
/**
* A <code>LayoutManager</code> is responsible for measuring and positioning item views
* within a <code>RecyclerView</code> as well as determining the policy for when to recycle
* item views that are no longer visible to the user. By changing the <code>LayoutManager</code>
* a <code>RecyclerView</code> can be used to implement a standard vertically scrolling list,
* a uniform grid, staggered grids, horizontally scrolling collections and more. Several stock
* layout managers are provided for general use.
*/
public static abstract class LayoutManager {
ChildHelper mChildHelper;
RecyclerView mRecyclerView;
@Nullable
SmoothScroller mSmoothScroller;
private boolean mRequestedSimpleAnimations = false;
void setRecyclerView(RecyclerView recyclerView) {
if (recyclerView == null) {
mRecyclerView = null;
mChildHelper = null;
} else {
mRecyclerView = recyclerView;
mChildHelper = recyclerView.mChildHelper;
}
}
/**
* Calls {@code RecyclerView#requestLayout} on the underlying RecyclerView
*/
public void requestLayout() {
if(mRecyclerView != null) {
mRecyclerView.requestLayout();
}
}
/**
* Checks if RecyclerView is in the middle of a layout or scroll and throws an
* {@link IllegalStateException} if it <b>is not</b>.
*
* @param message The message for the exception. Can be null.
* @see #assertNotInLayoutOrScroll(String)
*/
public void assertInLayoutOrScroll(String message) {
if (mRecyclerView != null) {
mRecyclerView.assertInLayoutOrScroll(message);
}
}
/**
* Checks if RecyclerView is in the middle of a layout or scroll and throws an
* {@link IllegalStateException} if it <b>is</b>.
*
* @param message The message for the exception. Can be null.
* @see #assertInLayoutOrScroll(String)
*/
public void assertNotInLayoutOrScroll(String message) {
if (mRecyclerView != null) {
mRecyclerView.assertNotInLayoutOrScroll(message);
}
}
/**
* Returns whether this LayoutManager supports automatic item animations.
* A LayoutManager wishing to support item animations should obey certain
* rules as outlined in {@link #onLayoutChildren(Recycler, State)}.
* The default return value is <code>false</code>, so subclasses of LayoutManager
* will not get predictive item animations by default.
*
* <p>Whether item animations are enabled in a RecyclerView is determined both
* by the return value from this method and the
* {@link RecyclerView#setItemAnimator(ItemAnimator) ItemAnimator} set on the
* RecyclerView itself. If the RecyclerView has a non-null ItemAnimator but this
* method returns false, then simple item animations will be enabled, in which
* views that are moving onto or off of the screen are simply faded in/out. If
* the RecyclerView has a non-null ItemAnimator and this method returns true,
* then there will be two calls to {@link #onLayoutChildren(Recycler, State)} to
* setup up the information needed to more intelligently predict where appearing
* and disappearing views should be animated from/to.</p>
*
* @return true if predictive item animations should be enabled, false otherwise
*/
public boolean supportsPredictiveItemAnimations() {
return false;
}
/**
* Called when this LayoutManager is both attached to a RecyclerView and that RecyclerView
* is attached to a window.
*
* <p>Subclass implementations should always call through to the superclass implementation.
* </p>
*
* @param view The RecyclerView this LayoutManager is bound to
*/
public void onAttachedToWindow(RecyclerView view) {
}
/**
* @deprecated
* override {@link #onDetachedFromWindow(RecyclerView, Recycler)}
*/
@Deprecated
public void onDetachedFromWindow(RecyclerView view) {
}
/**
* Called when this LayoutManager is detached from its parent RecyclerView or when
* its parent RecyclerView is detached from its window.
*
* <p>Subclass implementations should always call through to the superclass implementation.
* </p>
*
* @param view The RecyclerView this LayoutManager is bound to
* @param recycler The recycler to use if you prefer to recycle your children instead of
* keeping them around.
*/
public void onDetachedFromWindow(RecyclerView view, Recycler recycler) {
onDetachedFromWindow(view);
}
/**
* Check if the RecyclerView is configured to clip child views to its padding.
*
* @return true if this RecyclerView clips children to its padding, false otherwise
*/
public boolean getClipToPadding() {
return mRecyclerView != null && mRecyclerView.mClipToPadding;
}
/**
* Lay out all relevant child views from the given adapter.
*
* The LayoutManager is in charge of the behavior of item animations. By default,
* RecyclerView has a non-null {@link #getItemAnimator() ItemAnimator}, and simple
* item animations are enabled. This means that add/remove operations on the
* adapter will result in animations to add new or appearing items, removed or
* disappearing items, and moved items. If a LayoutManager returns false from
* {@link #supportsPredictiveItemAnimations()}, which is the default, and runs a
* normal layout operation during {@link #onLayoutChildren(Recycler, State)}, the
* RecyclerView will have enough information to run those animations in a simple
* way. For example, the default ItemAnimator, {@link DefaultItemAnimator}, will
* simple fade views in and out, whether they are actuall added/removed or whether
* they are moved on or off the screen due to other add/remove operations.
*
* <p>A LayoutManager wanting a better item animation experience, where items can be
* animated onto and off of the screen according to where the items exist when they
* are not on screen, then the LayoutManager should return true from
* {@link #supportsPredictiveItemAnimations()} and add additional logic to
* {@link #onLayoutChildren(Recycler, State)}. Supporting predictive animations
* means that {@link #onLayoutChildren(Recycler, State)} will be called twice;
* once as a "pre" layout step to determine where items would have been prior to
* a real layout, and again to do the "real" layout. In the pre-layout phase,
* items will remember their pre-layout positions to allow them to be laid out
* appropriately. Also, {@link LayoutParams#isItemRemoved() removed} items will
* be returned from the scrap to help determine correct placement of other items.
* These removed items should not be added to the child list, but should be used
* to help calculate correct positioning of other views, including views that
* were not previously onscreen (referred to as APPEARING views), but whose
* pre-layout offscreen position can be determined given the extra
* information about the pre-layout removed views.</p>
*
* <p>The second layout pass is the real layout in which only non-removed views
* will be used. The only additional requirement during this pass is, if
* {@link #supportsPredictiveItemAnimations()} returns true, to note which
* views exist in the child list prior to layout and which are not there after
* layout (referred to as DISAPPEARING views), and to position/layout those views
* appropriately, without regard to the actual bounds of the RecyclerView. This allows
* the animation system to know the location to which to animate these disappearing
* views.</p>
*
* <p>The default LayoutManager implementations for RecyclerView handle all of these
* requirements for animations already. Clients of RecyclerView can either use one
* of these layout managers directly or look at their implementations of
* onLayoutChildren() to see how they account for the APPEARING and
* DISAPPEARING views.</p>
*
* @param recycler Recycler to use for fetching potentially cached views for a
* position
* @param state Transient state of RecyclerView
*/
public void onLayoutChildren(Recycler recycler, State state) {
Log.e(TAG, "You must override onLayoutChildren(Recycler recycler, State state) ");
}
/**
* Create a default <code>LayoutParams</code> object for a child of the RecyclerView.
*
* <p>LayoutManagers will often want to use a custom <code>LayoutParams</code> type
* to store extra information specific to the layout. Client code should subclass
* {@link RecyclerView.LayoutParams} for this purpose.</p>
*
* <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type
* you must also override
* {@link #checkLayoutParams(LayoutParams)},
* {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and
* {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p>
*
* @return A new LayoutParams for a child view
*/
public abstract LayoutParams generateDefaultLayoutParams();
/**
* Determines the validity of the supplied LayoutParams object.
*
* <p>This should check to make sure that the object is of the correct type
* and all values are within acceptable ranges. The default implementation
* returns <code>true</code> for non-null params.</p>
*
* @param lp LayoutParams object to check
* @return true if this LayoutParams object is valid, false otherwise
*/
public boolean checkLayoutParams(LayoutParams lp) {
return lp != null;
}
/**
* Create a LayoutParams object suitable for this LayoutManager, copying relevant
* values from the supplied LayoutParams object if possible.
*
* <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type
* you must also override
* {@link #checkLayoutParams(LayoutParams)},
* {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and
* {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p>
*
* @param lp Source LayoutParams object to copy values from
* @return a new LayoutParams object
*/
public LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
if (lp instanceof LayoutParams) {
return new LayoutParams((LayoutParams) lp);
} else if (lp instanceof MarginLayoutParams) {
return new LayoutParams((MarginLayoutParams) lp);
} else {
return new LayoutParams(lp);
}
}
/**
* Create a LayoutParams object suitable for this LayoutManager from
* an inflated layout resource.
*
* <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type
* you must also override
* {@link #checkLayoutParams(LayoutParams)},
* {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and
* {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p>
*
* @param c Context for obtaining styled attributes
* @param attrs AttributeSet describing the supplied arguments
* @return a new LayoutParams object
*/
public LayoutParams generateLayoutParams(Context c, AttributeSet attrs) {
return new LayoutParams(c, attrs);
}
/**
* Scroll horizontally by dx pixels in screen coordinates and return the distance traveled.
* The default implementation does nothing and returns 0.
*
* @param dx distance to scroll by in pixels. X increases as scroll position
* approaches the right.
* @param recycler Recycler to use for fetching potentially cached views for a
* position
* @param state Transient state of RecyclerView
* @return The actual distance scrolled. The return value will be negative if dx was
* negative and scrolling proceeeded in that direction.
* <code>Math.abs(result)</code> may be less than dx if a boundary was reached.
*/
public int scrollHorizontallyBy(int dx, Recycler recycler, State state) {
return 0;
}
/**
* Scroll vertically by dy pixels in screen coordinates and return the distance traveled.
* The default implementation does nothing and returns 0.
*
* @param dy distance to scroll in pixels. Y increases as scroll position
* approaches the bottom.
* @param recycler Recycler to use for fetching potentially cached views for a
* position
* @param state Transient state of RecyclerView
* @return The actual distance scrolled. The return value will be negative if dy was
* negative and scrolling proceeeded in that direction.
* <code>Math.abs(result)</code> may be less than dy if a boundary was reached.
*/
public int scrollVerticallyBy(int dy, Recycler recycler, State state) {
return 0;
}
/**
* Query if horizontal scrolling is currently supported. The default implementation
* returns false.
*
* @return True if this LayoutManager can scroll the current contents horizontally
*/
public boolean canScrollHorizontally() {
return false;
}
/**
* Query if vertical scrolling is currently supported. The default implementation
* returns false.
*
* @return True if this LayoutManager can scroll the current contents vertically
*/
public boolean canScrollVertically() {
return false;
}
/**
* Scroll to the specified adapter position.
*
* Actual position of the item on the screen depends on the LayoutManager implementation.
* @param position Scroll to this adapter position.
*/
public void scrollToPosition(int position) {
if (DEBUG) {
Log.e(TAG, "You MUST implement scrollToPosition. It will soon become abstract");
}
}
/**
* <p>Smooth scroll to the specified adapter position.</p>
* <p>To support smooth scrolling, override this method, create your {@link SmoothScroller}
* instance and call {@link #startSmoothScroll(SmoothScroller)}.
* </p>
* @param recyclerView The RecyclerView to which this layout manager is attached
* @param state Current State of RecyclerView
* @param position Scroll to this adapter position.
*/
public void smoothScrollToPosition(RecyclerView recyclerView, State state,
int position) {
Log.e(TAG, "You must override smoothScrollToPosition to support smooth scrolling");
}
/**
* <p>Starts a smooth scroll using the provided SmoothScroller.</p>
* <p>Calling this method will cancel any previous smooth scroll request.</p>
* @param smoothScroller Unstance which defines how smooth scroll should be animated
*/
public void startSmoothScroll(SmoothScroller smoothScroller) {
if (mSmoothScroller != null && smoothScroller != mSmoothScroller
&& mSmoothScroller.isRunning()) {
mSmoothScroller.stop();
}
mSmoothScroller = smoothScroller;
mSmoothScroller.start(mRecyclerView, this);
}
/**
* @return true if RecycylerView is currently in the state of smooth scrolling.
*/
public boolean isSmoothScrolling() {
return mSmoothScroller != null && mSmoothScroller.isRunning();
}
/**
* Returns the resolved layout direction for this RecyclerView.
*
* @return {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_RTL} if the layout
* direction is RTL or returns
* {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_LTR} if the layout direction
* is not RTL.
*/
public int getLayoutDirection() {
return ViewCompat.getLayoutDirection(mRecyclerView);
}
/**
* Ends all animations on the view created by the {@link ItemAnimator}.
*
* @param view The View for which the animations should be ended.
* @see RecyclerView.ItemAnimator#endAnimations()
*/
public void endAnimation(View view) {
if (mRecyclerView.mItemAnimator != null) {
mRecyclerView.mItemAnimator.endAnimation(getChildViewHolderInt(view));
}
}
/**
* To be called only during {@link #onLayoutChildren(Recycler, State)} to add a view
* to the layout that is known to be going away, either because it has been
* {@link Adapter#notifyItemRemoved(int) removed} or because it is actually not in the
* visible portion of the container but is being laid out in order to inform RecyclerView
* in how to animate the item out of view.
* <p>
* Views added via this method are going to be invisible to LayoutManager after the
* dispatchLayout pass is complete. They cannot be retrieved via {@link #getChildAt(int)}
* or won't be included in {@link #getChildCount()} method.
*
* @param child View to add and then remove with animation.
*/
public void addDisappearingView(View child) {
addDisappearingView(child, -1);
}
/**
* To be called only during {@link #onLayoutChildren(Recycler, State)} to add a view
* to the layout that is known to be going away, either because it has been
* {@link Adapter#notifyItemRemoved(int) removed} or because it is actually not in the
* visible portion of the container but is being laid out in order to inform RecyclerView
* in how to animate the item out of view.
* <p>
* Views added via this method are going to be invisible to LayoutManager after the
* dispatchLayout pass is complete. They cannot be retrieved via {@link #getChildAt(int)}
* or won't be included in {@link #getChildCount()} method.
*
* @param child View to add and then remove with animation.
* @param index Index of the view.
*/
public void addDisappearingView(View child, int index) {
addViewInt(child, index, true);
}
/**
* Add a view to the currently attached RecyclerView if needed. LayoutManagers should
* use this method to add views obtained from a {@link Recycler} using
* {@link Recycler#getViewForPosition(int)}.
*
* @param child View to add
*/
public void addView(View child) {
addView(child, -1);
}
/**
* Add a view to the currently attached RecyclerView if needed. LayoutManagers should
* use this method to add views obtained from a {@link Recycler} using
* {@link Recycler#getViewForPosition(int)}.
*
* @param child View to add
* @param index Index to add child at
*/
public void addView(View child, int index) {
addViewInt(child, index, false);
}
private void addViewInt(View child, int index, boolean disappearing) {
final ViewHolder holder = getChildViewHolderInt(child);
if (disappearing || holder.isRemoved()) {
// these views will be hidden at the end of the layout pass.
mRecyclerView.addToDisappearingList(child);
} else {
// This may look like unnecessary but may happen if layout manager supports
// predictive layouts and adapter removed then re-added the same item.
// In this case, added version will be visible in the post layout (because add is
// deferred) but RV will still bind it to the same View.
// So if a View re-appears in post layout pass, remove it from disappearing list.
mRecyclerView.removeFromDisappearingList(child);
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (holder.wasReturnedFromScrap() || holder.isScrap()) {
if (holder.isScrap()) {
holder.unScrap();
} else {
holder.clearReturnedFromScrapFlag();
}
mChildHelper.attachViewToParent(child, index, child.getLayoutParams(), false);
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchFinishTemporaryDetach(child);
}
} else if (child.getParent() == mRecyclerView) { // it was not a scrap but a valid child
// ensure in correct position
int currentIndex = mChildHelper.indexOfChild(child);
if (index == -1) {
index = mChildHelper.getChildCount();
}
if (currentIndex == -1) {
throw new IllegalStateException("Added View has RecyclerView as parent but"
+ " view is not a real child. Unfiltered index:"
+ mRecyclerView.indexOfChild(child));
}
if (currentIndex != index) {
mRecyclerView.mLayout.moveView(currentIndex, index);
}
} else {
mChildHelper.addView(child, index, false);
lp.mInsetsDirty = true;
if (mSmoothScroller != null && mSmoothScroller.isRunning()) {
mSmoothScroller.onChildAttachedToWindow(child);
}
}
if (lp.mPendingInvalidate) {
if (DEBUG) {
Log.d(TAG, "consuming pending invalidate on child " + lp.mViewHolder);
}
holder.itemView.invalidate();
lp.mPendingInvalidate = false;
}
}
/**
* Remove a view from the currently attached RecyclerView if needed. LayoutManagers should
* use this method to completely remove a child view that is no longer needed.
* LayoutManagers should strongly consider recycling removed views using
* {@link Recycler#recycleView(android.view.View)}.
*
* @param child View to remove
*/
public void removeView(View child) {
mChildHelper.removeView(child);
}
/**
* Remove a view from the currently attached RecyclerView if needed. LayoutManagers should
* use this method to completely remove a child view that is no longer needed.
* LayoutManagers should strongly consider recycling removed views using
* {@link Recycler#recycleView(android.view.View)}.
*
* @param index Index of the child view to remove
*/
public void removeViewAt(int index) {
final View child = getChildAt(index);
if (child != null) {
mChildHelper.removeViewAt(index);
}
}
/**
* Remove all views from the currently attached RecyclerView. This will not recycle
* any of the affected views; the LayoutManager is responsible for doing so if desired.
*/
public void removeAllViews() {
// Only remove non-animating views
final int childCount = getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
mChildHelper.removeViewAt(i);
}
}
/**
* Returns the adapter position of the item represented by the given View. This does not
* contain any adapter changes that might have happened after the last layout.
*
* @param view The view to query
* @return The adapter position of the item which is rendered by this View.
*/
public int getPosition(View view) {
return ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
}
/**
* Returns the View type defined by the adapter.
*
* @param view The view to query
* @return The type of the view assigned by the adapter.
*/
public int getItemViewType(View view) {
return getChildViewHolderInt(view).getItemViewType();
}
/**
* Finds the view which represents the given adapter position.
* <p>
* This method traverses each child since it has no information about child order.
* Override this method to improve performance if your LayoutManager keeps data about
* child views.
* <p>
* If a view is ignored via {@link #ignoreView(View)}, it is also ignored by this method.
*
* @param position Position of the item in adapter
* @return The child view that represents the given position or null if the position is not
* laid out
*/
public View findViewByPosition(int position) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
ViewHolder vh = getChildViewHolderInt(child);
if (vh == null) {
continue;
}
if (vh.getLayoutPosition() == position && !vh.shouldIgnore() &&
(mRecyclerView.mState.isPreLayout() || !vh.isRemoved())) {
return child;
}
}
return null;
}
/**
* Temporarily detach a child view.
*
* <p>LayoutManagers may want to perform a lightweight detach operation to rearrange
* views currently attached to the RecyclerView. Generally LayoutManager implementations
* will want to use {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)}
* so that the detached view may be rebound and reused.</p>
*
* <p>If a LayoutManager uses this method to detach a view, it <em>must</em>
* {@link #attachView(android.view.View, int, RecyclerView.LayoutParams) reattach}
* or {@link #removeDetachedView(android.view.View) fully remove} the detached view
* before the LayoutManager entry point method called by RecyclerView returns.</p>
*
* @param child Child to detach
*/
public void detachView(View child) {
final int ind = mChildHelper.indexOfChild(child);
if (ind >= 0) {
detachViewInternal(ind, child);
}
}
/**
* Temporarily detach a child view.
*
* <p>LayoutManagers may want to perform a lightweight detach operation to rearrange
* views currently attached to the RecyclerView. Generally LayoutManager implementations
* will want to use {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)}
* so that the detached view may be rebound and reused.</p>
*
* <p>If a LayoutManager uses this method to detach a view, it <em>must</em>
* {@link #attachView(android.view.View, int, RecyclerView.LayoutParams) reattach}
* or {@link #removeDetachedView(android.view.View) fully remove} the detached view
* before the LayoutManager entry point method called by RecyclerView returns.</p>
*
* @param index Index of the child to detach
*/
public void detachViewAt(int index) {
detachViewInternal(index, getChildAt(index));
}
private void detachViewInternal(int index, View view) {
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchStartTemporaryDetach(view);
}
mChildHelper.detachViewFromParent(index);
}
/**
* Reattach a previously {@link #detachView(android.view.View) detached} view.
* This method should not be used to reattach views that were previously
* {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}.
*
* @param child Child to reattach
* @param index Intended child index for child
* @param lp LayoutParams for child
*/
public void attachView(View child, int index, LayoutParams lp) {
ViewHolder vh = getChildViewHolderInt(child);
if (vh.isRemoved()) {
mRecyclerView.addToDisappearingList(child);
} else {
mRecyclerView.removeFromDisappearingList(child);
}
mChildHelper.attachViewToParent(child, index, lp, vh.isRemoved());
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchFinishTemporaryDetach(child);
}
}
/**
* Reattach a previously {@link #detachView(android.view.View) detached} view.
* This method should not be used to reattach views that were previously
* {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}.
*
* @param child Child to reattach
* @param index Intended child index for child
*/
public void attachView(View child, int index) {
attachView(child, index, (LayoutParams) child.getLayoutParams());
}
/**
* Reattach a previously {@link #detachView(android.view.View) detached} view.
* This method should not be used to reattach views that were previously
* {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}.
*
* @param child Child to reattach
*/
public void attachView(View child) {
attachView(child, -1);
}
/**
* Finish removing a view that was previously temporarily
* {@link #detachView(android.view.View) detached}.
*
* @param child Detached child to remove
*/
public void removeDetachedView(View child) {
mRecyclerView.removeDetachedView(child, false);
}
/**
* Moves a View from one position to another.
*
* @param fromIndex The View's initial index
* @param toIndex The View's target index
*/
public void moveView(int fromIndex, int toIndex) {
View view = getChildAt(fromIndex);
if (view == null) {
throw new IllegalArgumentException("Cannot move a child from non-existing index:"
+ fromIndex);
}
detachViewAt(fromIndex);
attachView(view, toIndex);
}
/**
* Detach a child view and add it to a {@link Recycler Recycler's} scrap heap.
*
* <p>Scrapping a view allows it to be rebound and reused to show updated or
* different data.</p>
*
* @param child Child to detach and scrap
* @param recycler Recycler to deposit the new scrap view into
*/
public void detachAndScrapView(View child, Recycler recycler) {
int index = mChildHelper.indexOfChild(child);
scrapOrRecycleView(recycler, index, child);
}
/**
* Detach a child view and add it to a {@link Recycler Recycler's} scrap heap.
*
* <p>Scrapping a view allows it to be rebound and reused to show updated or
* different data.</p>
*
* @param index Index of child to detach and scrap
* @param recycler Recycler to deposit the new scrap view into
*/
public void detachAndScrapViewAt(int index, Recycler recycler) {
final View child = getChildAt(index);
scrapOrRecycleView(recycler, index, child);
}
/**
* Remove a child view and recycle it using the given Recycler.
*
* @param child Child to remove and recycle
* @param recycler Recycler to use to recycle child
*/
public void removeAndRecycleView(View child, Recycler recycler) {
removeView(child);
recycler.recycleView(child);
}
/**
* Remove a child view and recycle it using the given Recycler.
*
* @param index Index of child to remove and recycle
* @param recycler Recycler to use to recycle child
*/
public void removeAndRecycleViewAt(int index, Recycler recycler) {
final View view = getChildAt(index);
removeViewAt(index);
recycler.recycleView(view);
}
/**
* Return the current number of child views attached to the parent RecyclerView.
* This does not include child views that were temporarily detached and/or scrapped.
*
* @return Number of attached children
*/
public int getChildCount() {
return mChildHelper != null ? mChildHelper.getChildCount() : 0;
}
/**
* Return the child view at the given index
* @param index Index of child to return
* @return Child view at index
*/
public View getChildAt(int index) {
return mChildHelper != null ? mChildHelper.getChildAt(index) : null;
}
/**
* Return the width of the parent RecyclerView
*
* @return Width in pixels
*/
public int getWidth() {
return mRecyclerView != null ? mRecyclerView.getWidth() : 0;
}
/**
* Return the height of the parent RecyclerView
*
* @return Height in pixels
*/
public int getHeight() {
return mRecyclerView != null ? mRecyclerView.getHeight() : 0;
}
/**
* Return the left padding of the parent RecyclerView
*
* @return Padding in pixels
*/
public int getPaddingLeft() {
return mRecyclerView != null ? mRecyclerView.getPaddingLeft() : 0;
}
/**
* Return the top padding of the parent RecyclerView
*
* @return Padding in pixels
*/
public int getPaddingTop() {
return mRecyclerView != null ? mRecyclerView.getPaddingTop() : 0;
}
/**
* Return the right padding of the parent RecyclerView
*
* @return Padding in pixels
*/
public int getPaddingRight() {
return mRecyclerView != null ? mRecyclerView.getPaddingRight() : 0;
}
/**
* Return the bottom padding of the parent RecyclerView
*
* @return Padding in pixels
*/
public int getPaddingBottom() {
return mRecyclerView != null ? mRecyclerView.getPaddingBottom() : 0;
}
/**
* Return the start padding of the parent RecyclerView
*
* @return Padding in pixels
*/
public int getPaddingStart() {
return mRecyclerView != null ? ViewCompat.getPaddingStart(mRecyclerView) : 0;
}
/**
* Return the end padding of the parent RecyclerView
*
* @return Padding in pixels
*/
public int getPaddingEnd() {
return mRecyclerView != null ? ViewCompat.getPaddingEnd(mRecyclerView) : 0;
}
/**
* Returns true if the RecyclerView this LayoutManager is bound to has focus.
*
* @return True if the RecyclerView has focus, false otherwise.
* @see View#isFocused()
*/
public boolean isFocused() {
return mRecyclerView != null && mRecyclerView.isFocused();
}
/**
* Returns true if the RecyclerView this LayoutManager is bound to has or contains focus.
*
* @return true if the RecyclerView has or contains focus
* @see View#hasFocus()
*/
public boolean hasFocus() {
return mRecyclerView != null && mRecyclerView.hasFocus();
}
/**
* Returns the item View which has or contains focus.
*
* @return A direct child of RecyclerView which has focus or contains the focused child.
*/
public View getFocusedChild() {
if (mRecyclerView == null) {
return null;
}
final View focused = mRecyclerView.getFocusedChild();
if (focused == null || mChildHelper.isHidden(focused)) {
return null;
}
return focused;
}
/**
* Returns the number of items in the adapter bound to the parent RecyclerView.
* <p>
* Note that this number is not necessarily equal to {@link State#getItemCount()}. In
* methods where State is available, you should use {@link State#getItemCount()} instead.
* For more details, check the documentation for {@link State#getItemCount()}.
*
* @return The number of items in the bound adapter
* @see State#getItemCount()
*/
public int getItemCount() {
final Adapter a = mRecyclerView != null ? mRecyclerView.getAdapter() : null;
return a != null ? a.getItemCount() : 0;
}
/**
* Offset all child views attached to the parent RecyclerView by dx pixels along
* the horizontal axis.
*
* @param dx Pixels to offset by
*/
public void offsetChildrenHorizontal(int dx) {
if (mRecyclerView != null) {
mRecyclerView.offsetChildrenHorizontal(dx);
}
}
/**
* Offset all child views attached to the parent RecyclerView by dy pixels along
* the vertical axis.
*
* @param dy Pixels to offset by
*/
public void offsetChildrenVertical(int dy) {
if (mRecyclerView != null) {
mRecyclerView.offsetChildrenVertical(dy);
}
}
/**
* Flags a view so that it will not be scrapped or recycled.
* <p>
* Scope of ignoring a child is strictly restricted to position tracking, scrapping and
* recyling. Methods like {@link #removeAndRecycleAllViews(Recycler)} will ignore the child
* whereas {@link #removeAllViews()} or {@link #offsetChildrenHorizontal(int)} will not
* ignore the child.
* <p>
* Before this child can be recycled again, you have to call
* {@link #stopIgnoringView(View)}.
* <p>
* You can call this method only if your LayoutManger is in onLayout or onScroll callback.
*
* @param view View to ignore.
* @see #stopIgnoringView(View)
*/
public void ignoreView(View view) {
if (view.getParent() != mRecyclerView || mRecyclerView.indexOfChild(view) == -1) {
// checking this because calling this method on a recycled or detached view may
// cause loss of state.
throw new IllegalArgumentException("View should be fully attached to be ignored");
}
final ViewHolder vh = getChildViewHolderInt(view);
vh.addFlags(ViewHolder.FLAG_IGNORE);
mRecyclerView.mState.onViewIgnored(vh);
}
/**
* View can be scrapped and recycled again.
* <p>
* Note that calling this method removes all information in the view holder.
* <p>
* You can call this method only if your LayoutManger is in onLayout or onScroll callback.
*
* @param view View to ignore.
*/
public void stopIgnoringView(View view) {
final ViewHolder vh = getChildViewHolderInt(view);
vh.stopIgnoring();
vh.resetInternal();
vh.addFlags(ViewHolder.FLAG_INVALID);
}
/**
* Temporarily detach and scrap all currently attached child views. Views will be scrapped
* into the given Recycler. The Recycler may prefer to reuse scrap views before
* other views that were previously recycled.
*
* @param recycler Recycler to scrap views into
*/
public void detachAndScrapAttachedViews(Recycler recycler) {
final int childCount = getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
final View v = getChildAt(i);
scrapOrRecycleView(recycler, i, v);
}
}
private void scrapOrRecycleView(Recycler recycler, int index, View view) {
final ViewHolder viewHolder = getChildViewHolderInt(view);
if (viewHolder.shouldIgnore()) {
if (DEBUG) {
Log.d(TAG, "ignoring view " + viewHolder);
}
return;
}
if (viewHolder.isInvalid() && !viewHolder.isRemoved() && !viewHolder.isChanged() &&
!mRecyclerView.mAdapter.hasStableIds()) {
removeViewAt(index);
recycler.recycleViewHolderInternal(viewHolder);
} else {
detachViewAt(index);
recycler.scrapView(view);
}
}
/**
* Recycles the scrapped views.
* <p>
* When a view is detached and removed, it does not trigger a ViewGroup invalidate. This is
* the expected behavior if scrapped views are used for animations. Otherwise, we need to
* call remove and invalidate RecyclerView to ensure UI update.
*
* @param recycler Recycler
*/
void removeAndRecycleScrapInt(Recycler recycler) {
final int scrapCount = recycler.getScrapCount();
for (int i = 0; i < scrapCount; i++) {
final View scrap = recycler.getScrapViewAt(i);
final ViewHolder vh = getChildViewHolderInt(scrap);
if (vh.shouldIgnore()) {
continue;
}
if (vh.isTmpDetached()) {
mRecyclerView.removeDetachedView(scrap, false);
}
recycler.quickRecycleScrapView(scrap);
}
recycler.clearScrap();
if (scrapCount > 0) {
mRecyclerView.invalidate();
}
}
/**
* Measure a child view using standard measurement policy, taking the padding
* of the parent RecyclerView and any added item decorations into account.
*
* <p>If the RecyclerView can be scrolled in either dimension the caller may
* pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p>
*
* @param child Child view to measure
* @param widthUsed Width in pixels currently consumed by other views, if relevant
* @param heightUsed Height in pixels currently consumed by other views, if relevant
*/
public void measureChild(View child, int widthUsed, int heightUsed) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
widthUsed += insets.left + insets.right;
heightUsed += insets.top + insets.bottom;
final int widthSpec = getChildMeasureSpec(getWidth(),
getPaddingLeft() + getPaddingRight() + widthUsed, lp.width,
canScrollHorizontally());
final int heightSpec = getChildMeasureSpec(getHeight(),
getPaddingTop() + getPaddingBottom() + heightUsed, lp.height,
canScrollVertically());
child.measure(widthSpec, heightSpec);
}
/**
* Measure a child view using standard measurement policy, taking the padding
* of the parent RecyclerView, any added item decorations and the child margins
* into account.
*
* <p>If the RecyclerView can be scrolled in either dimension the caller may
* pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p>
*
* @param child Child view to measure
* @param widthUsed Width in pixels currently consumed by other views, if relevant
* @param heightUsed Height in pixels currently consumed by other views, if relevant
*/
public void measureChildWithMargins(View child, int widthUsed, int heightUsed) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
widthUsed += insets.left + insets.right;
heightUsed += insets.top + insets.bottom;
final int widthSpec = getChildMeasureSpec(getWidth(),
getPaddingLeft() + getPaddingRight() +
lp.leftMargin + lp.rightMargin + widthUsed, lp.width,
canScrollHorizontally());
final int heightSpec = getChildMeasureSpec(getHeight(),
getPaddingTop() + getPaddingBottom() +
lp.topMargin + lp.bottomMargin + heightUsed, lp.height,
canScrollVertically());
child.measure(widthSpec, heightSpec);
}
/**
* Calculate a MeasureSpec value for measuring a child view in one dimension.
*
* @param parentSize Size of the parent view where the child will be placed
* @param padding Total space currently consumed by other elements of parent
* @param childDimension Desired size of the child view, or MATCH_PARENT/WRAP_CONTENT.
* Generally obtained from the child view's LayoutParams
* @param canScroll true if the parent RecyclerView can scroll in this dimension
*
* @return a MeasureSpec value for the child view
*/
public static int getChildMeasureSpec(int parentSize, int padding, int childDimension,
boolean canScroll) {
int size = Math.max(0, parentSize - padding);
int resultSize = 0;
int resultMode = 0;
if (canScroll) {
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else {
// MATCH_PARENT can't be applied since we can scroll in this dimension, wrap
// instead using UNSPECIFIED.
resultSize = 0;
resultMode = MeasureSpec.UNSPECIFIED;
}
} else {
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.FILL_PARENT) {
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
/**
* Returns the measured width of the given child, plus the additional size of
* any insets applied by {@link ItemDecoration ItemDecorations}.
*
* @param child Child view to query
* @return child's measured width plus <code>ItemDecoration</code> insets
*
* @see View#getMeasuredWidth()
*/
public int getDecoratedMeasuredWidth(View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getMeasuredWidth() + insets.left + insets.right;
}
/**
* Returns the measured height of the given child, plus the additional size of
* any insets applied by {@link ItemDecoration ItemDecorations}.
*
* @param child Child view to query
* @return child's measured height plus <code>ItemDecoration</code> insets
*
* @see View#getMeasuredHeight()
*/
public int getDecoratedMeasuredHeight(View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getMeasuredHeight() + insets.top + insets.bottom;
}
/**
* Lay out the given child view within the RecyclerView using coordinates that
* include any current {@link ItemDecoration ItemDecorations}.
*
* <p>LayoutManagers should prefer working in sizes and coordinates that include
* item decoration insets whenever possible. This allows the LayoutManager to effectively
* ignore decoration insets within measurement and layout code. See the following
* methods:</p>
* <ul>
* <li>{@link #measureChild(View, int, int)}</li>
* <li>{@link #measureChildWithMargins(View, int, int)}</li>
* <li>{@link #getDecoratedLeft(View)}</li>
* <li>{@link #getDecoratedTop(View)}</li>
* <li>{@link #getDecoratedRight(View)}</li>
* <li>{@link #getDecoratedBottom(View)}</li>
* <li>{@link #getDecoratedMeasuredWidth(View)}</li>
* <li>{@link #getDecoratedMeasuredHeight(View)}</li>
* </ul>
*
* @param child Child to lay out
* @param left Left edge, with item decoration insets included
* @param top Top edge, with item decoration insets included
* @param right Right edge, with item decoration insets included
* @param bottom Bottom edge, with item decoration insets included
*
* @see View#layout(int, int, int, int)
*/
public void layoutDecorated(View child, int left, int top, int right, int bottom) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
child.layout(left + insets.left, top + insets.top, right - insets.right,
bottom - insets.bottom);
}
/**
* Returns the left edge of the given child view within its parent, offset by any applied
* {@link ItemDecoration ItemDecorations}.
*
* @param child Child to query
* @return Child left edge with offsets applied
* @see #getLeftDecorationWidth(View)
*/
public int getDecoratedLeft(View child) {
return child.getLeft() - getLeftDecorationWidth(child);
}
/**
* Returns the top edge of the given child view within its parent, offset by any applied
* {@link ItemDecoration ItemDecorations}.
*
* @param child Child to query
* @return Child top edge with offsets applied
* @see #getTopDecorationHeight(View)
*/
public int getDecoratedTop(View child) {
return child.getTop() - getTopDecorationHeight(child);
}
/**
* Returns the right edge of the given child view within its parent, offset by any applied
* {@link ItemDecoration ItemDecorations}.
*
* @param child Child to query
* @return Child right edge with offsets applied
* @see #getRightDecorationWidth(View)
*/
public int getDecoratedRight(View child) {
return child.getRight() + getRightDecorationWidth(child);
}
/**
* Returns the bottom edge of the given child view within its parent, offset by any applied
* {@link ItemDecoration ItemDecorations}.
*
* @param child Child to query
* @return Child bottom edge with offsets applied
* @see #getBottomDecorationHeight(View)
*/
public int getDecoratedBottom(View child) {
return child.getBottom() + getBottomDecorationHeight(child);
}
/**
* Calculates the item decor insets applied to the given child and updates the provided
* Rect instance with the inset values.
* <ul>
* <li>The Rect's left is set to the total width of left decorations.</li>
* <li>The Rect's top is set to the total height of top decorations.</li>
* <li>The Rect's right is set to the total width of right decorations.</li>
* <li>The Rect's bottom is set to total height of bottom decorations.</li>
* </ul>
* <p>
* Note that item decorations are automatically calculated when one of the LayoutManager's
* measure child methods is called. If you need to measure the child with custom specs via
* {@link View#measure(int, int)}, you can use this method to get decorations.
*
* @param child The child view whose decorations should be calculated
* @param outRect The Rect to hold result values
*/
public void calculateItemDecorationsForChild(View child, Rect outRect) {
if (mRecyclerView == null) {
outRect.set(0, 0, 0, 0);
return;
}
Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
outRect.set(insets);
}
/**
* Returns the total height of item decorations applied to child's top.
* <p>
* Note that this value is not updated until the View is measured or
* {@link #calculateItemDecorationsForChild(View, Rect)} is called.
*
* @param child Child to query
* @return The total height of item decorations applied to the child's top.
* @see #getDecoratedTop(View)
* @see #calculateItemDecorationsForChild(View, Rect)
*/
public int getTopDecorationHeight(View child) {
return ((LayoutParams) child.getLayoutParams()).mDecorInsets.top;
}
/**
* Returns the total height of item decorations applied to child's bottom.
* <p>
* Note that this value is not updated until the View is measured or
* {@link #calculateItemDecorationsForChild(View, Rect)} is called.
*
* @param child Child to query
* @return The total height of item decorations applied to the child's bottom.
* @see #getDecoratedBottom(View)
* @see #calculateItemDecorationsForChild(View, Rect)
*/
public int getBottomDecorationHeight(View child) {
return ((LayoutParams) child.getLayoutParams()).mDecorInsets.bottom;
}
/**
* Returns the total width of item decorations applied to child's left.
* <p>
* Note that this value is not updated until the View is measured or
* {@link #calculateItemDecorationsForChild(View, Rect)} is called.
*
* @param child Child to query
* @return The total width of item decorations applied to the child's left.
* @see #getDecoratedLeft(View)
* @see #calculateItemDecorationsForChild(View, Rect)
*/
public int getLeftDecorationWidth(View child) {
return ((LayoutParams) child.getLayoutParams()).mDecorInsets.left;
}
/**
* Returns the total width of item decorations applied to child's right.
* <p>
* Note that this value is not updated until the View is measured or
* {@link #calculateItemDecorationsForChild(View, Rect)} is called.
*
* @param child Child to query
* @return The total width of item decorations applied to the child's right.
* @see #getDecoratedRight(View)
* @see #calculateItemDecorationsForChild(View, Rect)
*/
public int getRightDecorationWidth(View child) {
return ((LayoutParams) child.getLayoutParams()).mDecorInsets.right;
}
/**
* Called when searching for a focusable view in the given direction has failed
* for the current content of the RecyclerView.
*
* <p>This is the LayoutManager's opportunity to populate views in the given direction
* to fulfill the request if it can. The LayoutManager should attach and return
* the view to be focused. The default implementation returns null.</p>
*
* @param focused The currently focused view
* @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
* {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
* {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
* or 0 for not applicable
* @param recycler The recycler to use for obtaining views for currently offscreen items
* @param state Transient state of RecyclerView
* @return The chosen view to be focused
*/
public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
State state) {
return null;
}
/**
* This method gives a LayoutManager an opportunity to intercept the initial focus search
* before the default behavior of {@link FocusFinder} is used. If this method returns
* null FocusFinder will attempt to find a focusable child view. If it fails
* then {@link #onFocusSearchFailed(View, int, RecyclerView.Recycler, RecyclerView.State)}
* will be called to give the LayoutManager an opportunity to add new views for items
* that did not have attached views representing them. The LayoutManager should not add
* or remove views from this method.
*
* @param focused The currently focused view
* @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
* {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
* {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
* @return A descendant view to focus or null to fall back to default behavior.
* The default implementation returns null.
*/
public View onInterceptFocusSearch(View focused, int direction) {
return null;
}
/**
* Called when a child of the RecyclerView wants a particular rectangle to be positioned
* onto the screen. See {@link ViewParent#requestChildRectangleOnScreen(android.view.View,
* android.graphics.Rect, boolean)} for more details.
*
* <p>The base implementation will attempt to perform a standard programmatic scroll
* to bring the given rect into view, within the padded area of the RecyclerView.</p>
*
* @param child The direct child making the request.
* @param rect The rectangle in the child's coordinates the child
* wishes to be on the screen.
* @param immediate True to forbid animated or delayed scrolling,
* false otherwise
* @return Whether the group scrolled to handle the operation
*/
public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect,
boolean immediate) {
final int parentLeft = getPaddingLeft();
final int parentTop = getPaddingTop();
final int parentRight = getWidth() - getPaddingRight();
final int parentBottom = getHeight() - getPaddingBottom();
final int childLeft = child.getLeft() + rect.left;
final int childTop = child.getTop() + rect.top;
final int childRight = childLeft + rect.width();
final int childBottom = childTop + rect.height();
final int offScreenLeft = Math.min(0, childLeft - parentLeft);
final int offScreenTop = Math.min(0, childTop - parentTop);
final int offScreenRight = Math.max(0, childRight - parentRight);
final int offScreenBottom = Math.max(0, childBottom - parentBottom);
// Favor the "start" layout direction over the end when bringing one side or the other
// of a large rect into view.
final int dx;
if (ViewCompat.getLayoutDirection(parent) == ViewCompat.LAYOUT_DIRECTION_RTL) {
dx = offScreenRight != 0 ? offScreenRight : offScreenLeft;
} else {
dx = offScreenLeft != 0 ? offScreenLeft : offScreenRight;
}
// Favor bringing the top into view over the bottom
final int dy = offScreenTop != 0 ? offScreenTop : offScreenBottom;
if (dx != 0 || dy != 0) {
if (immediate) {
parent.scrollBy(dx, dy);
} else {
parent.smoothScrollBy(dx, dy);
}
return true;
}
return false;
}
/**
* @deprecated Use {@link #onRequestChildFocus(RecyclerView, State, View, View)}
*/
@Deprecated
public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
// eat the request if we are in the middle of a scroll or layout
return isSmoothScrolling() || parent.mRunningLayoutOrScroll;
}
/**
* Called when a descendant view of the RecyclerView requests focus.
*
* <p>A LayoutManager wishing to keep focused views aligned in a specific
* portion of the view may implement that behavior in an override of this method.</p>
*
* <p>If the LayoutManager executes different behavior that should override the default
* behavior of scrolling the focused child on screen instead of running alongside it,
* this method should return true.</p>
*
* @param parent The RecyclerView hosting this LayoutManager
* @param state Current state of RecyclerView
* @param child Direct child of the RecyclerView containing the newly focused view
* @param focused The newly focused view. This may be the same view as child or it may be
* null
* @return true if the default scroll behavior should be suppressed
*/
public boolean onRequestChildFocus(RecyclerView parent, State state, View child,
View focused) {
return onRequestChildFocus(parent, child, focused);
}
/**
* Called if the RecyclerView this LayoutManager is bound to has a different adapter set.
* The LayoutManager may use this opportunity to clear caches and configure state such
* that it can relayout appropriately with the new data and potentially new view types.
*
* <p>The default implementation removes all currently attached views.</p>
*
* @param oldAdapter The previous adapter instance. Will be null if there was previously no
* adapter.
* @param newAdapter The new adapter instance. Might be null if
* {@link #setAdapter(RecyclerView.Adapter)} is called with {@code null}.
*/
public void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter) {
}
/**
* Called to populate focusable views within the RecyclerView.
*
* <p>The LayoutManager implementation should return <code>true</code> if the default
* behavior of {@link ViewGroup#addFocusables(java.util.ArrayList, int)} should be
* suppressed.</p>
*
* <p>The default implementation returns <code>false</code> to trigger RecyclerView
* to fall back to the default ViewGroup behavior.</p>
*
* @param recyclerView The RecyclerView hosting this LayoutManager
* @param views List of output views. This method should add valid focusable views
* to this list.
* @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
* {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
* {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
* @param focusableMode The type of focusables to be added.
*
* @return true to suppress the default behavior, false to add default focusables after
* this method returns.
*
* @see #FOCUSABLES_ALL
* @see #FOCUSABLES_TOUCH_MODE
*/
public boolean onAddFocusables(RecyclerView recyclerView, ArrayList<View> views,
int direction, int focusableMode) {
return false;
}
/**
* Called when {@link Adapter#notifyDataSetChanged()} is triggered instead of giving
* detailed information on what has actually changed.
*
* @param recyclerView
*/
public void onItemsChanged(RecyclerView recyclerView) {
}
/**
* Called when items have been added to the adapter. The LayoutManager may choose to
* requestLayout if the inserted items would require refreshing the currently visible set
* of child views. (e.g. currently empty space would be filled by appended items, etc.)
*
* @param recyclerView
* @param positionStart
* @param itemCount
*/
public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
}
/**
* Called when items have been removed from the adapter.
*
* @param recyclerView
* @param positionStart
* @param itemCount
*/
public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) {
}
/**
* Called when items have been changed in the adapter.
*
* @param recyclerView
* @param positionStart
* @param itemCount
*/
public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount) {
}
/**
* Called when an item is moved withing the adapter.
* <p>
* Note that, an item may also change position in response to another ADD/REMOVE/MOVE
* operation. This callback is only called if and only if {@link Adapter#notifyItemMoved}
* is called.
*
* @param recyclerView
* @param from
* @param to
* @param itemCount
*/
public void onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount) {
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeHorizontalScrollExtent()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current state of RecyclerView
* @return The horizontal extent of the scrollbar's thumb
* @see RecyclerView#computeHorizontalScrollExtent()
*/
public int computeHorizontalScrollExtent(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeHorizontalScrollOffset()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current State of RecyclerView where you can find total item count
* @return The horizontal offset of the scrollbar's thumb
* @see RecyclerView#computeHorizontalScrollOffset()
*/
public int computeHorizontalScrollOffset(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeHorizontalScrollRange()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current State of RecyclerView where you can find total item count
* @return The total horizontal range represented by the vertical scrollbar
* @see RecyclerView#computeHorizontalScrollRange()
*/
public int computeHorizontalScrollRange(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeVerticalScrollExtent()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current state of RecyclerView
* @return The vertical extent of the scrollbar's thumb
* @see RecyclerView#computeVerticalScrollExtent()
*/
public int computeVerticalScrollExtent(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeVerticalScrollOffset()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current State of RecyclerView where you can find total item count
* @return The vertical offset of the scrollbar's thumb
* @see RecyclerView#computeVerticalScrollOffset()
*/
public int computeVerticalScrollOffset(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeVerticalScrollRange()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current State of RecyclerView where you can find total item count
* @return The total vertical range represented by the vertical scrollbar
* @see RecyclerView#computeVerticalScrollRange()
*/
public int computeVerticalScrollRange(State state) {
return 0;
}
/**
* Measure the attached RecyclerView. Implementations must call
* {@link #setMeasuredDimension(int, int)} before returning.
*
* <p>The default implementation will handle EXACTLY measurements and respect
* the minimum width and height properties of the host RecyclerView if measured
* as UNSPECIFIED. AT_MOST measurements will be treated as EXACTLY and the RecyclerView
* will consume all available space.</p>
*
* @param recycler Recycler
* @param state Transient state of RecyclerView
* @param widthSpec Width {@link android.view.View.MeasureSpec}
* @param heightSpec Height {@link android.view.View.MeasureSpec}
*/
public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) {
mRecyclerView.defaultOnMeasure(widthSpec, heightSpec);
}
/**
* {@link View#setMeasuredDimension(int, int) Set the measured dimensions} of the
* host RecyclerView.
*
* @param widthSize Measured width
* @param heightSize Measured height
*/
public void setMeasuredDimension(int widthSize, int heightSize) {
mRecyclerView.setMeasuredDimension(widthSize, heightSize);
}
/**
* @return The host RecyclerView's {@link View#getMinimumWidth()}
*/
public int getMinimumWidth() {
return ViewCompat.getMinimumWidth(mRecyclerView);
}
/**
* @return The host RecyclerView's {@link View#getMinimumHeight()}
*/
public int getMinimumHeight() {
return ViewCompat.getMinimumHeight(mRecyclerView);
}
/**
* <p>Called when the LayoutManager should save its state. This is a good time to save your
* scroll position, configuration and anything else that may be required to restore the same
* layout state if the LayoutManager is recreated.</p>
* <p>RecyclerView does NOT verify if the LayoutManager has changed between state save and
* restore. This will let you share information between your LayoutManagers but it is also
* your responsibility to make sure they use the same parcelable class.</p>
*
* @return Necessary information for LayoutManager to be able to restore its state
*/
public Parcelable onSaveInstanceState() {
return null;
}
public void onRestoreInstanceState(Parcelable state) {
}
void stopSmoothScroller() {
if (mSmoothScroller != null) {
mSmoothScroller.stop();
}
}
private void onSmoothScrollerStopped(SmoothScroller smoothScroller) {
if (mSmoothScroller == smoothScroller) {
mSmoothScroller = null;
}
}
/**
* RecyclerView calls this method to notify LayoutManager that scroll state has changed.
*
* @param state The new scroll state for RecyclerView
*/
public void onScrollStateChanged(int state) {
}
/**
* Removes all views and recycles them using the given recycler.
* <p>
* If you want to clean cached views as well, you should call {@link Recycler#clear()} too.
* <p>
* If a View is marked as "ignored", it is not removed nor recycled.
*
* @param recycler Recycler to use to recycle children
* @see #removeAndRecycleView(View, Recycler)
* @see #removeAndRecycleViewAt(int, Recycler)
* @see #ignoreView(View)
*/
public void removeAndRecycleAllViews(Recycler recycler) {
for (int i = getChildCount() - 1; i >= 0; i--) {
final View view = getChildAt(i);
if (!getChildViewHolderInt(view).shouldIgnore()) {
removeAndRecycleViewAt(i, recycler);
}
}
}
// called by accessibility delegate
void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfoCompat info) {
onInitializeAccessibilityNodeInfo(mRecyclerView.mRecycler, mRecyclerView.mState,
info);
}
/**
* Called by the AccessibilityDelegate when the information about the current layout should
* be populated.
* <p>
* Default implementation adds a {@link
* android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.CollectionInfoCompat}.
* <p>
* You should override
* {@link #getRowCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)},
* {@link #getColumnCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)},
* {@link #isLayoutHierarchical(RecyclerView.Recycler, RecyclerView.State)} and
* {@link #getSelectionModeForAccessibility(RecyclerView.Recycler, RecyclerView.State)} for
* more accurate accessibility information.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param info The info that should be filled by the LayoutManager
* @see View#onInitializeAccessibilityNodeInfo(
*android.view.accessibility.AccessibilityNodeInfo)
* @see #getRowCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)
* @see #getColumnCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)
* @see #isLayoutHierarchical(RecyclerView.Recycler, RecyclerView.State)
* @see #getSelectionModeForAccessibility(RecyclerView.Recycler, RecyclerView.State)
*/
public void onInitializeAccessibilityNodeInfo(Recycler recycler, State state,
AccessibilityNodeInfoCompat info) {
info.setClassName(RecyclerView.class.getName());
if (ViewCompat.canScrollVertically(mRecyclerView, -1) ||
ViewCompat.canScrollHorizontally(mRecyclerView, -1)) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD);
info.setScrollable(true);
}
if (ViewCompat.canScrollVertically(mRecyclerView, 1) ||
ViewCompat.canScrollHorizontally(mRecyclerView, 1)) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD);
info.setScrollable(true);
}
final AccessibilityNodeInfoCompat.CollectionInfoCompat collectionInfo
= AccessibilityNodeInfoCompat.CollectionInfoCompat
.obtain(getRowCountForAccessibility(recycler, state),
getColumnCountForAccessibility(recycler, state),
isLayoutHierarchical(recycler, state),
getSelectionModeForAccessibility(recycler, state));
info.setCollectionInfo(collectionInfo);
}
// called by accessibility delegate
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
onInitializeAccessibilityEvent(mRecyclerView.mRecycler, mRecyclerView.mState, event);
}
/**
* Called by the accessibility delegate to initialize an accessibility event.
* <p>
* Default implementation adds item count and scroll information to the event.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param event The event instance to initialize
* @see View#onInitializeAccessibilityEvent(android.view.accessibility.AccessibilityEvent)
*/
public void onInitializeAccessibilityEvent(Recycler recycler, State state,
AccessibilityEvent event) {
final AccessibilityRecordCompat record = AccessibilityEventCompat
.asRecord(event);
if (mRecyclerView == null || record == null) {
return;
}
record.setScrollable(ViewCompat.canScrollVertically(mRecyclerView, 1)
|| ViewCompat.canScrollVertically(mRecyclerView, -1)
|| ViewCompat.canScrollHorizontally(mRecyclerView, -1)
|| ViewCompat.canScrollHorizontally(mRecyclerView, 1));
if (mRecyclerView.mAdapter != null) {
record.setItemCount(mRecyclerView.mAdapter.getItemCount());
}
}
// called by accessibility delegate
void onInitializeAccessibilityNodeInfoForItem(View host, AccessibilityNodeInfoCompat info) {
final ViewHolder vh = getChildViewHolderInt(host);
// avoid trying to create accessibility node info for removed children
if (vh != null && !vh.isRemoved()) {
onInitializeAccessibilityNodeInfoForItem(mRecyclerView.mRecycler,
mRecyclerView.mState, host, info);
}
}
/**
* Called by the AccessibilityDelegate when the accessibility information for a specific
* item should be populated.
* <p>
* Default implementation adds basic positioning information about the item.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param host The child for which accessibility node info should be populated
* @param info The info to fill out about the item
* @see android.widget.AbsListView#onInitializeAccessibilityNodeInfoForItem(View, int,
* android.view.accessibility.AccessibilityNodeInfo)
*/
public void onInitializeAccessibilityNodeInfoForItem(Recycler recycler, State state,
View host, AccessibilityNodeInfoCompat info) {
int rowIndexGuess = canScrollVertically() ? getPosition(host) : 0;
int columnIndexGuess = canScrollHorizontally() ? getPosition(host) : 0;
final AccessibilityNodeInfoCompat.CollectionItemInfoCompat itemInfo
= AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain(rowIndexGuess, 1,
columnIndexGuess, 1, false, false);
info.setCollectionItemInfo(itemInfo);
}
/**
* A LayoutManager can call this method to force RecyclerView to run simple animations in
* the next layout pass, even if there is not any trigger to do so. (e.g. adapter data
* change).
* <p>
* Note that, calling this method will not guarantee that RecyclerView will run animations
* at all. For example, if there is not any {@link ItemAnimator} set, RecyclerView will
* not run any animations but will still clear this flag after the layout is complete.
*
*/
public void requestSimpleAnimationsInNextLayout() {
mRequestedSimpleAnimations = true;
}
/**
* Returns the selection mode for accessibility. Should be
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE},
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_SINGLE} or
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_MULTIPLE}.
* <p>
* Default implementation returns
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE}.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @return Selection mode for accessibility. Default implementation returns
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE}.
*/
public int getSelectionModeForAccessibility(Recycler recycler, State state) {
return AccessibilityNodeInfoCompat.CollectionInfoCompat.SELECTION_MODE_NONE;
}
/**
* Returns the number of rows for accessibility.
* <p>
* Default implementation returns the number of items in the adapter if LayoutManager
* supports vertical scrolling or 1 if LayoutManager does not support vertical
* scrolling.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @return The number of rows in LayoutManager for accessibility.
*/
public int getRowCountForAccessibility(Recycler recycler, State state) {
if (mRecyclerView == null || mRecyclerView.mAdapter == null) {
return 1;
}
return canScrollVertically() ? mRecyclerView.mAdapter.getItemCount() : 1;
}
/**
* Returns the number of columns for accessibility.
* <p>
* Default implementation returns the number of items in the adapter if LayoutManager
* supports horizontal scrolling or 1 if LayoutManager does not support horizontal
* scrolling.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @return The number of rows in LayoutManager for accessibility.
*/
public int getColumnCountForAccessibility(Recycler recycler, State state) {
if (mRecyclerView == null || mRecyclerView.mAdapter == null) {
return 1;
}
return canScrollHorizontally() ? mRecyclerView.mAdapter.getItemCount() : 1;
}
/**
* Returns whether layout is hierarchical or not to be used for accessibility.
* <p>
* Default implementation returns false.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @return True if layout is hierarchical.
*/
public boolean isLayoutHierarchical(Recycler recycler, State state) {
return false;
}
// called by accessibility delegate
boolean performAccessibilityAction(int action, Bundle args) {
return performAccessibilityAction(mRecyclerView.mRecycler, mRecyclerView.mState,
action, args);
}
/**
* Called by AccessibilityDelegate when an action is requested from the RecyclerView.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param action The action to perform
* @param args Optional action arguments
* @see View#performAccessibilityAction(int, android.os.Bundle)
*/
public boolean performAccessibilityAction(Recycler recycler, State state, int action,
Bundle args) {
if (mRecyclerView == null) {
return false;
}
int vScroll = 0, hScroll = 0;
switch (action) {
case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD:
if (ViewCompat.canScrollVertically(mRecyclerView, -1)) {
vScroll = -(getHeight() - getPaddingTop() - getPaddingBottom());
}
if (ViewCompat.canScrollHorizontally(mRecyclerView, -1)) {
hScroll = -(getWidth() - getPaddingLeft() - getPaddingRight());
}
break;
case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD:
if (ViewCompat.canScrollVertically(mRecyclerView, 1)) {
vScroll = getHeight() - getPaddingTop() - getPaddingBottom();
}
if (ViewCompat.canScrollHorizontally(mRecyclerView, 1)) {
hScroll = getWidth() - getPaddingLeft() - getPaddingRight();
}
break;
}
if (vScroll == 0 && hScroll == 0) {
return false;
}
mRecyclerView.scrollBy(hScroll, vScroll);
return true;
}
// called by accessibility delegate
boolean performAccessibilityActionForItem(View view, int action, Bundle args) {
return performAccessibilityActionForItem(mRecyclerView.mRecycler, mRecyclerView.mState,
view, action, args);
}
/**
* Called by AccessibilityDelegate when an accessibility action is requested on one of the
* children of LayoutManager.
* <p>
* Default implementation does not do anything.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param view The child view on which the action is performed
* @param action The action to perform
* @param args Optional action arguments
* @return true if action is handled
* @see View#performAccessibilityAction(int, android.os.Bundle)
*/
public boolean performAccessibilityActionForItem(Recycler recycler, State state, View view,
int action, Bundle args) {
return false;
}
}
private void removeFromDisappearingList(View child) {
mDisappearingViewsInLayoutPass.remove(child);
}
private void addToDisappearingList(View child) {
if (!mDisappearingViewsInLayoutPass.contains(child)) {
mDisappearingViewsInLayoutPass.add(child);
}
}
/**
* An ItemDecoration allows the application to add a special drawing and layout offset
* to specific item views from the adapter's data set. This can be useful for drawing dividers
* between items, highlights, visual grouping boundaries and more.
*
* <p>All ItemDecorations are drawn in the order they were added, before the item
* views (in {@link ItemDecoration#onDraw(Canvas, RecyclerView, RecyclerView.State) onDraw()}
* and after the items (in {@link ItemDecoration#onDrawOver(Canvas, RecyclerView,
* RecyclerView.State)}.</p>
*/
public static abstract class ItemDecoration {
/**
* Draw any appropriate decorations into the Canvas supplied to the RecyclerView.
* Any content drawn by this method will be drawn before the item views are drawn,
* and will thus appear underneath the views.
*
* @param c Canvas to draw into
* @param parent RecyclerView this ItemDecoration is drawing into
* @param state The current state of RecyclerView
*/
public void onDraw(Canvas c, RecyclerView parent, State state) {
onDraw(c, parent);
}
/**
* @deprecated
* Override {@link #onDraw(Canvas, RecyclerView, RecyclerView.State)}
*/
@Deprecated
public void onDraw(Canvas c, RecyclerView parent) {
}
/**
* Draw any appropriate decorations into the Canvas supplied to the RecyclerView.
* Any content drawn by this method will be drawn after the item views are drawn
* and will thus appear over the views.
*
* @param c Canvas to draw into
* @param parent RecyclerView this ItemDecoration is drawing into
* @param state The current state of RecyclerView.
*/
public void onDrawOver(Canvas c, RecyclerView parent, State state) {
onDrawOver(c, parent);
}
/**
* @deprecated
* Override {@link #onDrawOver(Canvas, RecyclerView, RecyclerView.State)}
*/
@Deprecated
public void onDrawOver(Canvas c, RecyclerView parent) {
}
/**
* @deprecated
* Use {@link #getItemOffsets(Rect, View, RecyclerView, State)}
*/
@Deprecated
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
outRect.set(0, 0, 0, 0);
}
/**
* Retrieve any offsets for the given item. Each field of <code>outRect</code> specifies
* the number of pixels that the item view should be inset by, similar to padding or margin.
* The default implementation sets the bounds of outRect to 0 and returns.
*
* <p>
* If this ItemDecoration does not affect the positioning of item views, it should set
* all four fields of <code>outRect</code> (left, top, right, bottom) to zero
* before returning.
*
* <p>
* If you need to access Adapter for additional data, you can call
* {@link RecyclerView#getChildAdapterPosition(View)} to get the adapter position of the
* View.
*
* @param outRect Rect to receive the output.
* @param view The child view to decorate
* @param parent RecyclerView this ItemDecoration is decorating
* @param state The current state of RecyclerView.
*/
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
parent);
}
}
/**
* An OnItemTouchListener allows the application to intercept touch events in progress at the
* view hierarchy level of the RecyclerView before those touch events are considered for
* RecyclerView's own scrolling behavior.
*
* <p>This can be useful for applications that wish to implement various forms of gestural
* manipulation of item views within the RecyclerView. OnItemTouchListeners may intercept
* a touch interaction already in progress even if the RecyclerView is already handling that
* gesture stream itself for the purposes of scrolling.</p>
*/
public interface OnItemTouchListener {
/**
* Silently observe and/or take over touch events sent to the RecyclerView
* before they are handled by either the RecyclerView itself or its child views.
*
* <p>The onInterceptTouchEvent methods of each attached OnItemTouchListener will be run
* in the order in which each listener was added, before any other touch processing
* by the RecyclerView itself or child views occurs.</p>
*
* @param e MotionEvent describing the touch event. All coordinates are in
* the RecyclerView's coordinate system.
* @return true if this OnItemTouchListener wishes to begin intercepting touch events, false
* to continue with the current behavior and continue observing future events in
* the gesture.
*/
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e);
/**
* Process a touch event as part of a gesture that was claimed by returning true from
* a previous call to {@link #onInterceptTouchEvent}.
*
* @param e MotionEvent describing the touch event. All coordinates are in
* the RecyclerView's coordinate system.
*/
public void onTouchEvent(RecyclerView rv, MotionEvent e);
}
/**
* An OnScrollListener can be set on a RecyclerView to receive messages
* when a scrolling event has occurred on that RecyclerView.
*
* @see RecyclerView#setOnScrollListener(OnScrollListener)
*/
abstract static public class OnScrollListener {
/**
* Callback method to be invoked when RecyclerView's scroll state changes.
*
* @param recyclerView The RecyclerView whose scroll state has changed.
* @param newState The updated scroll state. One of {@link #SCROLL_STATE_IDLE},
* {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}.
*/
public void onScrollStateChanged(RecyclerView recyclerView, int newState){}
/**
* Callback method to be invoked when the RecyclerView has been scrolled. This will be
* called after the scroll has completed.
* <p>
* This callback will also be called if visible item range changes after a layout
* calculation. In that case, dx and dy will be 0.
*
* @param recyclerView The RecyclerView which scrolled.
* @param dx The amount of horizontal scroll.
* @param dy The amount of vertical scroll.
*/
public void onScrolled(RecyclerView recyclerView, int dx, int dy){}
}
/**
* A RecyclerListener can be set on a RecyclerView to receive messages whenever
* a view is recycled.
*
* @see RecyclerView#setRecyclerListener(RecyclerListener)
*/
public interface RecyclerListener {
/**
* This method is called whenever the view in the ViewHolder is recycled.
*
* RecyclerView calls this method right before clearing ViewHolder's internal data and
* sending it to RecycledViewPool. This way, if ViewHolder was holding valid information
* before being recycled, you can call {@link ViewHolder#getAdapterPosition()} to get
* its adapter position.
*
* @param holder The ViewHolder containing the view that was recycled
*/
public void onViewRecycled(ViewHolder holder);
}
/**
* A ViewHolder describes an item view and metadata about its place within the RecyclerView.
*
* <p>{@link Adapter} implementations should subclass ViewHolder and add fields for caching
* potentially expensive {@link View#findViewById(int)} results.</p>
*
* <p>While {@link LayoutParams} belong to the {@link LayoutManager},
* {@link ViewHolder ViewHolders} belong to the adapter. Adapters should feel free to use
* their own custom ViewHolder implementations to store data that makes binding view contents
* easier. Implementations should assume that individual item views will hold strong references
* to <code>ViewHolder</code> objects and that <code>RecyclerView</code> instances may hold
* strong references to extra off-screen item views for caching purposes</p>
*/
public static abstract class ViewHolder {
public final View itemView;
int mPosition = NO_POSITION;
int mOldPosition = NO_POSITION;
long mItemId = NO_ID;
int mItemViewType = INVALID_TYPE;
int mPreLayoutPosition = NO_POSITION;
// The item that this holder is shadowing during an item change event/animation
ViewHolder mShadowedHolder = null;
// The item that is shadowing this holder during an item change event/animation
ViewHolder mShadowingHolder = null;
/**
* This ViewHolder has been bound to a position; mPosition, mItemId and mItemViewType
* are all valid.
*/
static final int FLAG_BOUND = 1 << 0;
/**
* The data this ViewHolder's view reflects is stale and needs to be rebound
* by the adapter. mPosition and mItemId are consistent.
*/
static final int FLAG_UPDATE = 1 << 1;
/**
* This ViewHolder's data is invalid. The identity implied by mPosition and mItemId
* are not to be trusted and may no longer match the item view type.
* This ViewHolder must be fully rebound to different data.
*/
static final int FLAG_INVALID = 1 << 2;
/**
* This ViewHolder points at data that represents an item previously removed from the
* data set. Its view may still be used for things like outgoing animations.
*/
static final int FLAG_REMOVED = 1 << 3;
/**
* This ViewHolder should not be recycled. This flag is set via setIsRecyclable()
* and is intended to keep views around during animations.
*/
static final int FLAG_NOT_RECYCLABLE = 1 << 4;
/**
* This ViewHolder is returned from scrap which means we are expecting an addView call
* for this itemView. When returned from scrap, ViewHolder stays in the scrap list until
* the end of the layout pass and then recycled by RecyclerView if it is not added back to
* the RecyclerView.
*/
static final int FLAG_RETURNED_FROM_SCRAP = 1 << 5;
/**
* This ViewHolder's contents have changed. This flag is used as an indication that
* change animations may be used, if supported by the ItemAnimator.
*/
static final int FLAG_CHANGED = 1 << 6;
/**
* This ViewHolder is fully managed by the LayoutManager. We do not scrap, recycle or remove
* it unless LayoutManager is replaced.
* It is still fully visible to the LayoutManager.
*/
static final int FLAG_IGNORE = 1 << 7;
/**
* When the View is detached form the parent, we set this flag so that we can take correct
* action when we need to remove it or add it back.
*/
static final int FLAG_TMP_DETACHED = 1 << 8;
/**
* Set when we can no longer determine the adapter position of this ViewHolder until it is
* rebound to a new position. It is different than FLAG_INVALID because FLAG_INVALID is
* set even when the type does not match. Also, FLAG_ADAPTER_POSITION_UNKNOWN is set as soon
* as adapter notification arrives vs FLAG_INVALID is set lazily before layout is
* re-calculated.
*/
static final int FLAG_ADAPTER_POSITION_UNKNOWN = 1 << 9;
private int mFlags;
private int mIsRecyclableCount = 0;
// If non-null, view is currently considered scrap and may be reused for other data by the
// scrap container.
private Recycler mScrapContainer = null;
/**
* Is set when VH is bound from the adapter and cleaned right before it is sent to
* {@link RecycledViewPool}.
*/
RecyclerView mOwnerRecyclerView;
public ViewHolder(View itemView) {
if (itemView == null) {
throw new IllegalArgumentException("itemView may not be null");
}
this.itemView = itemView;
}
void flagRemovedAndOffsetPosition(int mNewPosition, int offset, boolean applyToPreLayout) {
addFlags(ViewHolder.FLAG_REMOVED);
offsetPosition(offset, applyToPreLayout);
mPosition = mNewPosition;
}
void offsetPosition(int offset, boolean applyToPreLayout) {
if (mOldPosition == NO_POSITION) {
mOldPosition = mPosition;
}
if (mPreLayoutPosition == NO_POSITION) {
mPreLayoutPosition = mPosition;
}
if (applyToPreLayout) {
mPreLayoutPosition += offset;
}
mPosition += offset;
if (itemView.getLayoutParams() != null) {
((LayoutParams) itemView.getLayoutParams()).mInsetsDirty = true;
}
}
void clearOldPosition() {
mOldPosition = NO_POSITION;
mPreLayoutPosition = NO_POSITION;
}
void saveOldPosition() {
if (mOldPosition == NO_POSITION) {
mOldPosition = mPosition;
}
}
boolean shouldIgnore() {
return (mFlags & FLAG_IGNORE) != 0;
}
/**
* @deprecated This method is deprecated because its meaning is ambiguous due to the async
* handling of adapter updates. Please use {@link #getLayoutPosition()} or
* {@link #getAdapterPosition()} depending on your use case.
*
* @see #getLayoutPosition()
* @see #getAdapterPosition()
*/
@Deprecated
public final int getPosition() {
return mPreLayoutPosition == NO_POSITION ? mPosition : mPreLayoutPosition;
}
/**
* Returns the position of the ViewHolder in terms of the latest layout pass.
* <p>
* This position is mostly used by RecyclerView components to be consistent while
* RecyclerView lazily processes adapter updates.
* <p>
* For performance and animation reasons, RecyclerView batches all adapter updates until the
* next layout pass. This may cause mismatches between the Adapter position of the item and
* the position it had in the latest layout calculations.
* <p>
* LayoutManagers should always call this method while doing calculations based on item
* positions. All methods in {@link RecyclerView.LayoutManager}, {@link RecyclerView.State},
* {@link RecyclerView.Recycler} that receive a position expect it to be the layout position
* of the item.
* <p>
* If LayoutManager needs to call an external method that requires the adapter position of
* the item, it can use {@link #getAdapterPosition()} or
* {@link RecyclerView.Recycler#convertPreLayoutPositionToPostLayout(int)}.
*
* @return Returns the adapter position of the ViewHolder in the latest layout pass.
* @see #getAdapterPosition()
*/
public final int getLayoutPosition() {
return mPreLayoutPosition == NO_POSITION ? mPosition : mPreLayoutPosition;
}
/**
* Returns the Adapter position of the item represented by this ViewHolder.
* <p>
* Note that this might be different than the {@link #getLayoutPosition()} if there are
* pending adapter updates but a new layout pass has not happened yet.
* <p>
* RecyclerView does not handle any adapter updates until the next layout traversal. This
* may create temporary inconsistencies between what user sees on the screen and what
* adapter contents have. This inconsistency is not important since it will be less than
* 16ms but it might be a problem if you want to use ViewHolder position to access the
* adapter. Sometimes, you may need to get the exact adapter position to do
* some actions in response to user events. In that case, you should use this method which
* will calculate the Adapter position of the ViewHolder.
* <p>
* Note that if you've called {@link RecyclerView.Adapter#notifyDataSetChanged()}, until the
* next layout pass, the return value of this method will be {@link #NO_POSITION}.
*
* @return The adapter position of the item if it still exists in the adapter.
* {@link RecyclerView#NO_POSITION} if item has been removed from the adapter,
* {@link RecyclerView.Adapter#notifyDataSetChanged()} has been called after the last
* layout pass or the ViewHolder has already been recycled.
*/
public final int getAdapterPosition() {
if (mOwnerRecyclerView == null) {
return NO_POSITION;
}
return mOwnerRecyclerView.getAdapterPositionFor(this);
}
/**
* When LayoutManager supports animations, RecyclerView tracks 3 positions for ViewHolders
* to perform animations.
* <p>
* If a ViewHolder was laid out in the previous onLayout call, old position will keep its
* adapter index in the previous layout.
*
* @return The previous adapter index of the Item represented by this ViewHolder or
* {@link #NO_POSITION} if old position does not exists or cleared (pre-layout is
* complete).
*/
public final int getOldPosition() {
return mOldPosition;
}
/**
* Returns The itemId represented by this ViewHolder.
*
* @return The the item's id if adapter has stable ids, {@link RecyclerView#NO_ID}
* otherwise
*/
public final long getItemId() {
return mItemId;
}
/**
* @return The view type of this ViewHolder.
*/
public final int getItemViewType() {
return mItemViewType;
}
boolean isScrap() {
return mScrapContainer != null;
}
void unScrap() {
mScrapContainer.unscrapView(this);
}
boolean wasReturnedFromScrap() {
return (mFlags & FLAG_RETURNED_FROM_SCRAP) != 0;
}
void clearReturnedFromScrapFlag() {
mFlags = mFlags & ~FLAG_RETURNED_FROM_SCRAP;
}
void clearTmpDetachFlag() {
mFlags = mFlags & ~FLAG_TMP_DETACHED;
}
void stopIgnoring() {
mFlags = mFlags & ~FLAG_IGNORE;
}
void setScrapContainer(Recycler recycler) {
mScrapContainer = recycler;
}
boolean isInvalid() {
return (mFlags & FLAG_INVALID) != 0;
}
boolean needsUpdate() {
return (mFlags & FLAG_UPDATE) != 0;
}
boolean isChanged() {
return (mFlags & FLAG_CHANGED) != 0;
}
boolean isBound() {
return (mFlags & FLAG_BOUND) != 0;
}
boolean isRemoved() {
return (mFlags & FLAG_REMOVED) != 0;
}
boolean hasAnyOfTheFlags(int flags) {
return (mFlags & flags) != 0;
}
boolean isTmpDetached() {
return (mFlags & FLAG_TMP_DETACHED) != 0;
}
boolean isAdapterPositionUnknown() {
return (mFlags & FLAG_ADAPTER_POSITION_UNKNOWN) != 0 || isInvalid();
}
void setFlags(int flags, int mask) {
mFlags = (mFlags & ~mask) | (flags & mask);
}
void addFlags(int flags) {
mFlags |= flags;
}
void resetInternal() {
mFlags = 0;
mPosition = NO_POSITION;
mOldPosition = NO_POSITION;
mItemId = NO_ID;
mPreLayoutPosition = NO_POSITION;
mIsRecyclableCount = 0;
mShadowedHolder = null;
mShadowingHolder = null;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ViewHolder{" +
Integer.toHexString(hashCode()) + " position=" + mPosition + " id=" + mItemId +
", oldPos=" + mOldPosition + ", pLpos:" + mPreLayoutPosition);
if (isScrap()) sb.append(" scrap");
if (isInvalid()) sb.append(" invalid");
if (!isBound()) sb.append(" unbound");
if (needsUpdate()) sb.append(" update");
if (isRemoved()) sb.append(" removed");
if (shouldIgnore()) sb.append(" ignored");
if (isChanged()) sb.append(" changed");
if (isTmpDetached()) sb.append(" tmpDetached");
if (!isRecyclable()) sb.append(" not recyclable(" + mIsRecyclableCount + ")");
if (isAdapterPositionUnknown()) sb.append("undefined adapter position");
if (itemView.getParent() == null) sb.append(" no parent");
sb.append("}");
return sb.toString();
}
/**
* Informs the recycler whether this item can be recycled. Views which are not
* recyclable will not be reused for other items until setIsRecyclable() is
* later set to true. Calls to setIsRecyclable() should always be paired (one
* call to setIsRecyclabe(false) should always be matched with a later call to
* setIsRecyclable(true)). Pairs of calls may be nested, as the state is internally
* reference-counted.
*
* @param recyclable Whether this item is available to be recycled. Default value
* is true.
*/
public final void setIsRecyclable(boolean recyclable) {
mIsRecyclableCount = recyclable ? mIsRecyclableCount - 1 : mIsRecyclableCount + 1;
if (mIsRecyclableCount < 0) {
mIsRecyclableCount = 0;
if (DEBUG) {
throw new RuntimeException("isRecyclable decremented below 0: " +
"unmatched pair of setIsRecyable() calls for " + this);
}
Log.e(VIEW_LOG_TAG, "isRecyclable decremented below 0: " +
"unmatched pair of setIsRecyable() calls for " + this);
} else if (!recyclable && mIsRecyclableCount == 1) {
mFlags |= FLAG_NOT_RECYCLABLE;
} else if (recyclable && mIsRecyclableCount == 0) {
mFlags &= ~FLAG_NOT_RECYCLABLE;
}
if (DEBUG) {
Log.d(TAG, "setIsRecyclable val:" + recyclable + ":" + this);
}
}
/**
* @see {@link #setIsRecyclable(boolean)}
*
* @return true if this item is available to be recycled, false otherwise.
*/
public final boolean isRecyclable() {
return (mFlags & FLAG_NOT_RECYCLABLE) == 0 &&
!ViewCompat.hasTransientState(itemView);
}
/**
* Returns whether we have animations referring to this view holder or not.
* This is similar to isRecyclable flag but does not check transient state.
*/
private boolean shouldBeKeptAsChild() {
return (mFlags & FLAG_NOT_RECYCLABLE) != 0;
}
/**
* @return True if ViewHolder is not refenrenced by RecyclerView animations but has
* transient state which will prevent it from being recycled.
*/
private boolean doesTransientStatePreventRecycling() {
return (mFlags & FLAG_NOT_RECYCLABLE) == 0 && ViewCompat.hasTransientState(itemView);
}
}
private int getAdapterPositionFor(ViewHolder viewHolder) {
if (viewHolder.hasAnyOfTheFlags( ViewHolder.FLAG_INVALID |
ViewHolder.FLAG_REMOVED | ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN)
|| !viewHolder.isBound()) {
return RecyclerView.NO_POSITION;
}
return mAdapterHelper.applyPendingUpdatesToPosition(viewHolder.mPosition);
}
/**
* {@link android.view.ViewGroup.MarginLayoutParams LayoutParams} subclass for children of
* {@link RecyclerView}. Custom {@link LayoutManager layout managers} are encouraged
* to create their own subclass of this <code>LayoutParams</code> class
* to store any additional required per-child view metadata about the layout.
*/
public static class LayoutParams extends android.view.ViewGroup.MarginLayoutParams {
ViewHolder mViewHolder;
final Rect mDecorInsets = new Rect();
boolean mInsetsDirty = true;
// Flag is set to true if the view is bound while it is detached from RV.
// In this case, we need to manually call invalidate after view is added to guarantee that
// invalidation is populated through the View hierarchy
boolean mPendingInvalidate = false;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(LayoutParams source) {
super((ViewGroup.LayoutParams) source);
}
/**
* Returns true if the view this LayoutParams is attached to needs to have its content
* updated from the corresponding adapter.
*
* @return true if the view should have its content updated
*/
public boolean viewNeedsUpdate() {
return mViewHolder.needsUpdate();
}
/**
* Returns true if the view this LayoutParams is attached to is now representing
* potentially invalid data. A LayoutManager should scrap/recycle it.
*
* @return true if the view is invalid
*/
public boolean isViewInvalid() {
return mViewHolder.isInvalid();
}
/**
* Returns true if the adapter data item corresponding to the view this LayoutParams
* is attached to has been removed from the data set. A LayoutManager may choose to
* treat it differently in order to animate its outgoing or disappearing state.
*
* @return true if the item the view corresponds to was removed from the data set
*/
public boolean isItemRemoved() {
return mViewHolder.isRemoved();
}
/**
* Returns true if the adapter data item corresponding to the view this LayoutParams
* is attached to has been changed in the data set. A LayoutManager may choose to
* treat it differently in order to animate its changing state.
*
* @return true if the item the view corresponds to was changed in the data set
*/
public boolean isItemChanged() {
return mViewHolder.isChanged();
}
/**
* @deprecated use {@link #getViewLayoutPosition()} or {@link #getViewAdapterPosition()}
*/
public int getViewPosition() {
return mViewHolder.getPosition();
}
/**
* Returns the adapter position that the view this LayoutParams is attached to corresponds
* to as of latest layout calculation.
*
* @return the adapter position this view as of latest layout pass
*/
public int getViewLayoutPosition() {
return mViewHolder.getLayoutPosition();
}
/**
* Returns the up-to-date adapter position that the view this LayoutParams is attached to
* corresponds to.
*
* @return the up-to-date adapter position this view. It may return
* {@link RecyclerView#NO_POSITION} if item represented by this View has been removed or
* its up-to-date position cannot be calculated.
*/
public int getViewAdapterPosition() {
return mViewHolder.getAdapterPosition();
}
}
/**
* Observer base class for watching changes to an {@link Adapter}.
* See {@link Adapter#registerAdapterDataObserver(AdapterDataObserver)}.
*/
public static abstract class AdapterDataObserver {
public void onChanged() {
// Do nothing
}
public void onItemRangeChanged(int positionStart, int itemCount) {
// do nothing
}
public void onItemRangeInserted(int positionStart, int itemCount) {
// do nothing
}
public void onItemRangeRemoved(int positionStart, int itemCount) {
// do nothing
}
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
// do nothing
}
}
/**
* <p>Base class for smooth scrolling. Handles basic tracking of the target view position and
* provides methods to trigger a programmatic scroll.</p>
*
* @see LinearSmoothScroller
*/
public static abstract class SmoothScroller {
private int mTargetPosition = RecyclerView.NO_POSITION;
private RecyclerView mRecyclerView;
private LayoutManager mLayoutManager;
private boolean mPendingInitialRun;
private boolean mRunning;
private View mTargetView;
private final Action mRecyclingAction;
public SmoothScroller() {
mRecyclingAction = new Action(0, 0);
}
/**
* Starts a smooth scroll for the given target position.
* <p>In each animation step, {@link RecyclerView} will check
* for the target view and call either
* {@link #onTargetFound(android.view.View, RecyclerView.State, SmoothScroller.Action)} or
* {@link #onSeekTargetStep(int, int, RecyclerView.State, SmoothScroller.Action)} until
* SmoothScroller is stopped.</p>
*
* <p>Note that if RecyclerView finds the target view, it will automatically stop the
* SmoothScroller. This <b>does not</b> mean that scroll will stop, it only means it will
* stop calling SmoothScroller in each animation step.</p>
*/
void start(RecyclerView recyclerView, LayoutManager layoutManager) {
mRecyclerView = recyclerView;
mLayoutManager = layoutManager;
if (mTargetPosition == RecyclerView.NO_POSITION) {
throw new IllegalArgumentException("Invalid target position");
}
mRecyclerView.mState.mTargetPosition = mTargetPosition;
mRunning = true;
mPendingInitialRun = true;
mTargetView = findViewByPosition(getTargetPosition());
onStart();
mRecyclerView.mViewFlinger.postOnAnimation();
}
public void setTargetPosition(int targetPosition) {
mTargetPosition = targetPosition;
}
/**
* @return The LayoutManager to which this SmoothScroller is attached
*/
public LayoutManager getLayoutManager() {
return mLayoutManager;
}
/**
* Stops running the SmoothScroller in each animation callback. Note that this does not
* cancel any existing {@link Action} updated by
* {@link #onTargetFound(android.view.View, RecyclerView.State, SmoothScroller.Action)} or
* {@link #onSeekTargetStep(int, int, RecyclerView.State, SmoothScroller.Action)}.
*/
final protected void stop() {
if (!mRunning) {
return;
}
onStop();
mRecyclerView.mState.mTargetPosition = RecyclerView.NO_POSITION;
mTargetView = null;
mTargetPosition = RecyclerView.NO_POSITION;
mPendingInitialRun = false;
mRunning = false;
// trigger a cleanup
mLayoutManager.onSmoothScrollerStopped(this);
// clear references to avoid any potential leak by a custom smooth scroller
mLayoutManager = null;
mRecyclerView = null;
}
/**
* Returns true if SmoothScroller has been started but has not received the first
* animation
* callback yet.
*
* @return True if this SmoothScroller is waiting to start
*/
public boolean isPendingInitialRun() {
return mPendingInitialRun;
}
/**
* @return True if SmoothScroller is currently active
*/
public boolean isRunning() {
return mRunning;
}
/**
* Returns the adapter position of the target item
*
* @return Adapter position of the target item or
* {@link RecyclerView#NO_POSITION} if no target view is set.
*/
public int getTargetPosition() {
return mTargetPosition;
}
private void onAnimation(int dx, int dy) {
if (!mRunning || mTargetPosition == RecyclerView.NO_POSITION) {
stop();
}
mPendingInitialRun = false;
if (mTargetView != null) {
// verify target position
if (getChildPosition(mTargetView) == mTargetPosition) {
onTargetFound(mTargetView, mRecyclerView.mState, mRecyclingAction);
mRecyclingAction.runIfNecessary(mRecyclerView);
stop();
} else {
Log.e(TAG, "Passed over target position while smooth scrolling.");
mTargetView = null;
}
}
if (mRunning) {
onSeekTargetStep(dx, dy, mRecyclerView.mState, mRecyclingAction);
mRecyclingAction.runIfNecessary(mRecyclerView);
}
}
/**
* @see RecyclerView#getChildLayoutPosition(android.view.View)
*/
public int getChildPosition(View view) {
return mRecyclerView.getChildLayoutPosition(view);
}
/**
* @see RecyclerView.LayoutManager#getChildCount()
*/
public int getChildCount() {
return mRecyclerView.mLayout.getChildCount();
}
/**
* @see RecyclerView.LayoutManager#findViewByPosition(int)
*/
public View findViewByPosition(int position) {
return mRecyclerView.mLayout.findViewByPosition(position);
}
/**
* @see RecyclerView#scrollToPosition(int)
*/
public void instantScrollToPosition(int position) {
mRecyclerView.scrollToPosition(position);
}
protected void onChildAttachedToWindow(View child) {
if (getChildPosition(child) == getTargetPosition()) {
mTargetView = child;
if (DEBUG) {
Log.d(TAG, "smooth scroll target view has been attached");
}
}
}
/**
* Normalizes the vector.
* @param scrollVector The vector that points to the target scroll position
*/
protected void normalize(PointF scrollVector) {
final double magnitute = Math.sqrt(scrollVector.x * scrollVector.x + scrollVector.y *
scrollVector.y);
scrollVector.x /= magnitute;
scrollVector.y /= magnitute;
}
/**
* Called when smooth scroll is started. This might be a good time to do setup.
*/
abstract protected void onStart();
/**
* Called when smooth scroller is stopped. This is a good place to cleanup your state etc.
* @see #stop()
*/
abstract protected void onStop();
/**
* <p>RecyclerView will call this method each time it scrolls until it can find the target
* position in the layout.</p>
* <p>SmoothScroller should check dx, dy and if scroll should be changed, update the
* provided {@link Action} to define the next scroll.</p>
*
* @param dx Last scroll amount horizontally
* @param dy Last scroll amount verticaully
* @param state Transient state of RecyclerView
* @param action If you want to trigger a new smooth scroll and cancel the previous one,
* update this object.
*/
abstract protected void onSeekTargetStep(int dx, int dy, State state, Action action);
/**
* Called when the target position is laid out. This is the last callback SmoothScroller
* will receive and it should update the provided {@link Action} to define the scroll
* details towards the target view.
* @param targetView The view element which render the target position.
* @param state Transient state of RecyclerView
* @param action Action instance that you should update to define final scroll action
* towards the targetView
*/
abstract protected void onTargetFound(View targetView, State state, Action action);
/**
* Holds information about a smooth scroll request by a {@link SmoothScroller}.
*/
public static class Action {
public static final int UNDEFINED_DURATION = Integer.MIN_VALUE;
private int mDx;
private int mDy;
private int mDuration;
private Interpolator mInterpolator;
private boolean changed = false;
// we track this variable to inform custom implementer if they are updating the action
// in every animation callback
private int consecutiveUpdates = 0;
/**
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
*/
public Action(int dx, int dy) {
this(dx, dy, UNDEFINED_DURATION, null);
}
/**
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
* @param duration Duration of the animation in milliseconds
*/
public Action(int dx, int dy, int duration) {
this(dx, dy, duration, null);
}
/**
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
* @param duration Duration of the animation in milliseconds
* @param interpolator Interpolator to be used when calculating scroll position in each
* animation step
*/
public Action(int dx, int dy, int duration, Interpolator interpolator) {
mDx = dx;
mDy = dy;
mDuration = duration;
mInterpolator = interpolator;
}
private void runIfNecessary(RecyclerView recyclerView) {
if (changed) {
validate();
if (mInterpolator == null) {
if (mDuration == UNDEFINED_DURATION) {
recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy);
} else {
recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration);
}
} else {
recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration, mInterpolator);
}
consecutiveUpdates ++;
if (consecutiveUpdates > 10) {
// A new action is being set in every animation step. This looks like a bad
// implementation. Inform developer.
Log.e(TAG, "Smooth Scroll action is being updated too frequently. Make sure"
+ " you are not changing it unless necessary");
}
changed = false;
} else {
consecutiveUpdates = 0;
}
}
private void validate() {
if (mInterpolator != null && mDuration < 1) {
throw new IllegalStateException("If you provide an interpolator, you must"
+ " set a positive duration");
} else if (mDuration < 1) {
throw new IllegalStateException("Scroll duration must be a positive number");
}
}
public int getDx() {
return mDx;
}
public void setDx(int dx) {
changed = true;
mDx = dx;
}
public int getDy() {
return mDy;
}
public void setDy(int dy) {
changed = true;
mDy = dy;
}
public int getDuration() {
return mDuration;
}
public void setDuration(int duration) {
changed = true;
mDuration = duration;
}
public Interpolator getInterpolator() {
return mInterpolator;
}
/**
* Sets the interpolator to calculate scroll steps
* @param interpolator The interpolator to use. If you specify an interpolator, you must
* also set the duration.
* @see #setDuration(int)
*/
public void setInterpolator(Interpolator interpolator) {
changed = true;
mInterpolator = interpolator;
}
/**
* Updates the action with given parameters.
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
* @param duration Duration of the animation in milliseconds
* @param interpolator Interpolator to be used when calculating scroll position in each
* animation step
*/
public void update(int dx, int dy, int duration, Interpolator interpolator) {
mDx = dx;
mDy = dy;
mDuration = duration;
mInterpolator = interpolator;
changed = true;
}
}
}
static class AdapterDataObservable extends Observable<AdapterDataObserver> {
public boolean hasObservers() {
return !mObservers.isEmpty();
}
public void notifyChanged() {
// since onChanged() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
}
public void notifyItemRangeChanged(int positionStart, int itemCount) {
// since onItemRangeChanged() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeChanged(positionStart, itemCount);
}
}
public void notifyItemRangeInserted(int positionStart, int itemCount) {
// since onItemRangeInserted() is implemented by the app, it could do anything,
// including removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeInserted(positionStart, itemCount);
}
}
public void notifyItemRangeRemoved(int positionStart, int itemCount) {
// since onItemRangeRemoved() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeRemoved(positionStart, itemCount);
}
}
public void notifyItemMoved(int fromPosition, int toPosition) {
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeMoved(fromPosition, toPosition, 1);
}
}
}
static class SavedState extends android.view.View.BaseSavedState {
Parcelable mLayoutState;
/**
* called by CREATOR
*/
SavedState(Parcel in) {
super(in);
mLayoutState = in.readParcelable(LayoutManager.class.getClassLoader());
}
/**
* Called by onSaveInstanceState
*/
SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeParcelable(mLayoutState, 0);
}
private void copyFrom(SavedState other) {
mLayoutState = other.mLayoutState;
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
/**
* <p>Contains useful information about the current RecyclerView state like target scroll
* position or view focus. State object can also keep arbitrary data, identified by resource
* ids.</p>
* <p>Often times, RecyclerView components will need to pass information between each other.
* To provide a well defined data bus between components, RecyclerView passes the same State
* object to component callbacks and these components can use it to exchange data.</p>
* <p>If you implement custom components, you can use State's put/get/remove methods to pass
* data between your components without needing to manage their lifecycles.</p>
*/
public static class State {
private int mTargetPosition = RecyclerView.NO_POSITION;
ArrayMap<ViewHolder, ItemHolderInfo> mPreLayoutHolderMap =
new ArrayMap<ViewHolder, ItemHolderInfo>();
ArrayMap<ViewHolder, ItemHolderInfo> mPostLayoutHolderMap =
new ArrayMap<ViewHolder, ItemHolderInfo>();
// nullable
ArrayMap<Long, ViewHolder> mOldChangedHolders = new ArrayMap<Long, ViewHolder>();
private SparseArray<Object> mData;
/**
* Number of items adapter has.
*/
int mItemCount = 0;
/**
* Number of items adapter had in the previous layout.
*/
private int mPreviousLayoutItemCount = 0;
/**
* Number of items that were NOT laid out but has been deleted from the adapter after the
* previous layout.
*/
private int mDeletedInvisibleItemCountSincePreviousLayout = 0;
private boolean mStructureChanged = false;
private boolean mInPreLayout = false;
private boolean mRunSimpleAnimations = false;
private boolean mRunPredictiveAnimations = false;
State reset() {
mTargetPosition = RecyclerView.NO_POSITION;
if (mData != null) {
mData.clear();
}
mItemCount = 0;
mStructureChanged = false;
return this;
}
public boolean isPreLayout() {
return mInPreLayout;
}
/**
* Returns whether RecyclerView will run predictive animations in this layout pass
* or not.
*
* @return true if RecyclerView is calculating predictive animations to be run at the end
* of the layout pass.
*/
public boolean willRunPredictiveAnimations() {
return mRunPredictiveAnimations;
}
/**
* Returns whether RecyclerView will run simple animations in this layout pass
* or not.
*
* @return true if RecyclerView is calculating simple animations to be run at the end of
* the layout pass.
*/
public boolean willRunSimpleAnimations() {
return mRunSimpleAnimations;
}
/**
* Removes the mapping from the specified id, if there was any.
* @param resourceId Id of the resource you want to remove. It is suggested to use R.id.* to
* preserve cross functionality and avoid conflicts.
*/
public void remove(int resourceId) {
if (mData == null) {
return;
}
mData.remove(resourceId);
}
/**
* Gets the Object mapped from the specified id, or <code>null</code>
* if no such data exists.
*
* @param resourceId Id of the resource you want to remove. It is suggested to use R.id.*
* to
* preserve cross functionality and avoid conflicts.
*/
public <T> T get(int resourceId) {
if (mData == null) {
return null;
}
return (T) mData.get(resourceId);
}
/**
* Adds a mapping from the specified id to the specified value, replacing the previous
* mapping from the specified key if there was one.
*
* @param resourceId Id of the resource you want to add. It is suggested to use R.id.* to
* preserve cross functionality and avoid conflicts.
* @param data The data you want to associate with the resourceId.
*/
public void put(int resourceId, Object data) {
if (mData == null) {
mData = new SparseArray<Object>();
}
mData.put(resourceId, data);
}
/**
* If scroll is triggered to make a certain item visible, this value will return the
* adapter index of that item.
* @return Adapter index of the target item or
* {@link RecyclerView#NO_POSITION} if there is no target
* position.
*/
public int getTargetScrollPosition() {
return mTargetPosition;
}
/**
* Returns if current scroll has a target position.
* @return true if scroll is being triggered to make a certain position visible
* @see #getTargetScrollPosition()
*/
public boolean hasTargetScrollPosition() {
return mTargetPosition != RecyclerView.NO_POSITION;
}
/**
* @return true if the structure of the data set has changed since the last call to
* onLayoutChildren, false otherwise
*/
public boolean didStructureChange() {
return mStructureChanged;
}
/**
* Returns the total number of items that can be laid out. Note that this number is not
* necessarily equal to the number of items in the adapter, so you should always use this
* number for your position calculations and never access the adapter directly.
* <p>
* RecyclerView listens for Adapter's notify events and calculates the effects of adapter
* data changes on existing Views. These calculations are used to decide which animations
* should be run.
* <p>
* To support predictive animations, RecyclerView may rewrite or reorder Adapter changes to
* present the correct state to LayoutManager in pre-layout pass.
* <p>
* For example, a newly added item is not included in pre-layout item count because
* pre-layout reflects the contents of the adapter before the item is added. Behind the
* scenes, RecyclerView offsets {@link Recycler#getViewForPosition(int)} calls such that
* LayoutManager does not know about the new item's existence in pre-layout. The item will
* be available in second layout pass and will be included in the item count. Similar
* adjustments are made for moved and removed items as well.
* <p>
* You can get the adapter's item count via {@link LayoutManager#getItemCount()} method.
*
* @return The number of items currently available
* @see LayoutManager#getItemCount()
*/
public int getItemCount() {
return mInPreLayout ?
(mPreviousLayoutItemCount - mDeletedInvisibleItemCountSincePreviousLayout) :
mItemCount;
}
void onViewRecycled(ViewHolder holder) {
mPreLayoutHolderMap.remove(holder);
mPostLayoutHolderMap.remove(holder);
if (mOldChangedHolders != null) {
removeFrom(mOldChangedHolders, holder);
}
// holder cannot be in new list.
}
public void onViewIgnored(ViewHolder holder) {
onViewRecycled(holder);
}
private void removeFrom(ArrayMap<Long, ViewHolder> holderMap, ViewHolder holder) {
for (int i = holderMap.size() - 1; i >= 0; i --) {
if (holder == holderMap.valueAt(i)) {
holderMap.removeAt(i);
return;
}
}
}
@Override
public String toString() {
return "State{" +
"mTargetPosition=" + mTargetPosition +
", mPreLayoutHolderMap=" + mPreLayoutHolderMap +
", mPostLayoutHolderMap=" + mPostLayoutHolderMap +
", mData=" + mData +
", mItemCount=" + mItemCount +
", mPreviousLayoutItemCount=" + mPreviousLayoutItemCount +
", mDeletedInvisibleItemCountSincePreviousLayout="
+ mDeletedInvisibleItemCountSincePreviousLayout +
", mStructureChanged=" + mStructureChanged +
", mInPreLayout=" + mInPreLayout +
", mRunSimpleAnimations=" + mRunSimpleAnimations +
", mRunPredictiveAnimations=" + mRunPredictiveAnimations +
'}';
}
}
/**
* Internal listener that manages items after animations finish. This is how items are
* retained (not recycled) during animations, but allowed to be recycled afterwards.
* It depends on the contract with the ItemAnimator to call the appropriate dispatch*Finished()
* method on the animator's listener when it is done animating any item.
*/
private class ItemAnimatorRestoreListener implements ItemAnimator.ItemAnimatorListener {
@Override
public void onRemoveFinished(ViewHolder item) {
item.setIsRecyclable(true);
if (!removeAnimatingView(item.itemView) && item.isTmpDetached()) {
removeDetachedView(item.itemView, false);
}
}
@Override
public void onAddFinished(ViewHolder item) {
item.setIsRecyclable(true);
if (!item.shouldBeKeptAsChild()) {
removeAnimatingView(item.itemView);
}
}
@Override
public void onMoveFinished(ViewHolder item) {
item.setIsRecyclable(true);
if (!item.shouldBeKeptAsChild()) {
removeAnimatingView(item.itemView);
}
}
@Override
public void onChangeFinished(ViewHolder item) {
item.setIsRecyclable(true);
/**
* We check both shadowed and shadowing because a ViewHolder may get both roles at the
* same time.
*
* Assume this flow:
* item X is represented by VH_1. Then itemX changes, so we create VH_2 .
* RV sets the following and calls item animator:
* VH_1.shadowed = VH_2;
* VH_1.mChanged = true;
* VH_2.shadowing =VH_1;
*
* Then, before the first change finishes, item changes again so we create VH_3.
* RV sets the following and calls item animator:
* VH_2.shadowed = VH_3
* VH_2.mChanged = true
* VH_3.shadowing = VH_2
*
* Because VH_2 already has an animation, it will be cancelled. At this point VH_2 has
* both shadowing and shadowed fields set. Shadowing information is obsolete now
* because the first animation where VH_2 is newViewHolder is not valid anymore.
* We ended up in this case because VH_2 played both roles. On the other hand,
* we DO NOT want to clear its changed flag.
*
* If second change was simply reverting first change, we would find VH_1 in
* {@link Recycler#getScrapViewForPosition(int, int, boolean)} and recycle it before
* re-using
*/
if (item.mShadowedHolder != null && item.mShadowingHolder == null) { // old vh
item.mShadowedHolder = null;
item.setFlags(~ViewHolder.FLAG_CHANGED, item.mFlags);
}
// always null this because an OldViewHolder can never become NewViewHolder w/o being
// recycled.
item.mShadowingHolder = null;
if (!item.shouldBeKeptAsChild()) {
removeAnimatingView(item.itemView);
}
}
};
/**
* This class defines the animations that take place on items as changes are made
* to the adapter.
*
* Subclasses of ItemAnimator can be used to implement custom animations for actions on
* ViewHolder items. The RecyclerView will manage retaining these items while they
* are being animated, but implementors must call the appropriate "Starting"
* ({@link #dispatchRemoveStarting(ViewHolder)}, {@link #dispatchMoveStarting(ViewHolder)},
* {@link #dispatchChangeStarting(ViewHolder, boolean)}, or
* {@link #dispatchAddStarting(ViewHolder)})
* and "Finished" ({@link #dispatchRemoveFinished(ViewHolder)},
* {@link #dispatchMoveFinished(ViewHolder)},
* {@link #dispatchChangeFinished(ViewHolder, boolean)},
* or {@link #dispatchAddFinished(ViewHolder)}) methods when each item animation is
* being started and ended.
*
* <p>By default, RecyclerView uses {@link DefaultItemAnimator}</p>
*
* @see #setItemAnimator(ItemAnimator)
*/
public static abstract class ItemAnimator {
private ItemAnimatorListener mListener = null;
private ArrayList<ItemAnimatorFinishedListener> mFinishedListeners =
new ArrayList<ItemAnimatorFinishedListener>();
private long mAddDuration = 120;
private long mRemoveDuration = 120;
private long mMoveDuration = 250;
private long mChangeDuration = 250;
private boolean mSupportsChangeAnimations = true;
/**
* Gets the current duration for which all move animations will run.
*
* @return The current move duration
*/
public long getMoveDuration() {
return mMoveDuration;
}
/**
* Sets the duration for which all move animations will run.
*
* @param moveDuration The move duration
*/
public void setMoveDuration(long moveDuration) {
mMoveDuration = moveDuration;
}
/**
* Gets the current duration for which all add animations will run.
*
* @return The current add duration
*/
public long getAddDuration() {
return mAddDuration;
}
/**
* Sets the duration for which all add animations will run.
*
* @param addDuration The add duration
*/
public void setAddDuration(long addDuration) {
mAddDuration = addDuration;
}
/**
* Gets the current duration for which all remove animations will run.
*
* @return The current remove duration
*/
public long getRemoveDuration() {
return mRemoveDuration;
}
/**
* Sets the duration for which all remove animations will run.
*
* @param removeDuration The remove duration
*/
public void setRemoveDuration(long removeDuration) {
mRemoveDuration = removeDuration;
}
/**
* Gets the current duration for which all change animations will run.
*
* @return The current change duration
*/
public long getChangeDuration() {
return mChangeDuration;
}
/**
* Sets the duration for which all change animations will run.
*
* @param changeDuration The change duration
*/
public void setChangeDuration(long changeDuration) {
mChangeDuration = changeDuration;
}
/**
* Returns whether this ItemAnimator supports animations of change events.
*
* @return true if change animations are supported, false otherwise
*/
public boolean getSupportsChangeAnimations() {
return mSupportsChangeAnimations;
}
/**
* Sets whether this ItemAnimator supports animations of item change events.
* If you set this property to false, actions on the data set which change the
* contents of items will not be animated. What those animations are is left
* up to the discretion of the ItemAnimator subclass, in its
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} implementation.
* The value of this property is true by default.
*
* @see Adapter#notifyItemChanged(int)
* @see Adapter#notifyItemRangeChanged(int, int)
*
* @param supportsChangeAnimations true if change animations are supported by
* this ItemAnimator, false otherwise. If the property is false, the ItemAnimator
* will not receive a call to
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} when changes occur.
*/
public void setSupportsChangeAnimations(boolean supportsChangeAnimations) {
mSupportsChangeAnimations = supportsChangeAnimations;
}
/**
* Internal only:
* Sets the listener that must be called when the animator is finished
* animating the item (or immediately if no animation happens). This is set
* internally and is not intended to be set by external code.
*
* @param listener The listener that must be called.
*/
void setListener(ItemAnimatorListener listener) {
mListener = listener;
}
/**
* Called when there are pending animations waiting to be started. This state
* is governed by the return values from {@link #animateAdd(ViewHolder) animateAdd()},
* {@link #animateMove(ViewHolder, int, int, int, int) animateMove()}, and
* {@link #animateRemove(ViewHolder) animateRemove()}, which inform the
* RecyclerView that the ItemAnimator wants to be called later to start the
* associated animations. runPendingAnimations() will be scheduled to be run
* on the next frame.
*/
abstract public void runPendingAnimations();
/**
* Called when an item is removed from the RecyclerView. Implementors can choose
* whether and how to animate that change, but must always call
* {@link #dispatchRemoveFinished(ViewHolder)} when done, either
* immediately (if no animation will occur) or after the animation actually finishes.
* The return value indicates whether an animation has been set up and whether the
* ItemAnimator's {@link #runPendingAnimations()} method should be called at the
* next opportunity. This mechanism allows ItemAnimator to set up individual animations
* as separate calls to {@link #animateAdd(ViewHolder) animateAdd()},
* {@link #animateMove(ViewHolder, int, int, int, int) animateMove()},
* {@link #animateRemove(ViewHolder) animateRemove()}, and
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} come in one by one,
* then start the animations together in the later call to {@link #runPendingAnimations()}.
*
* <p>This method may also be called for disappearing items which continue to exist in the
* RecyclerView, but for which the system does not have enough information to animate
* them out of view. In that case, the default animation for removing items is run
* on those items as well.</p>
*
* @param holder The item that is being removed.
* @return true if a later call to {@link #runPendingAnimations()} is requested,
* false otherwise.
*/
abstract public boolean animateRemove(ViewHolder holder);
/**
* Called when an item is added to the RecyclerView. Implementors can choose
* whether and how to animate that change, but must always call
* {@link #dispatchAddFinished(ViewHolder)} when done, either
* immediately (if no animation will occur) or after the animation actually finishes.
* The return value indicates whether an animation has been set up and whether the
* ItemAnimator's {@link #runPendingAnimations()} method should be called at the
* next opportunity. This mechanism allows ItemAnimator to set up individual animations
* as separate calls to {@link #animateAdd(ViewHolder) animateAdd()},
* {@link #animateMove(ViewHolder, int, int, int, int) animateMove()},
* {@link #animateRemove(ViewHolder) animateRemove()}, and
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} come in one by one,
* then start the animations together in the later call to {@link #runPendingAnimations()}.
*
* <p>This method may also be called for appearing items which were already in the
* RecyclerView, but for which the system does not have enough information to animate
* them into view. In that case, the default animation for adding items is run
* on those items as well.</p>
*
* @param holder The item that is being added.
* @return true if a later call to {@link #runPendingAnimations()} is requested,
* false otherwise.
*/
abstract public boolean animateAdd(ViewHolder holder);
/**
* Called when an item is moved in the RecyclerView. Implementors can choose
* whether and how to animate that change, but must always call
* {@link #dispatchMoveFinished(ViewHolder)} when done, either
* immediately (if no animation will occur) or after the animation actually finishes.
* The return value indicates whether an animation has been set up and whether the
* ItemAnimator's {@link #runPendingAnimations()} method should be called at the
* next opportunity. This mechanism allows ItemAnimator to set up individual animations
* as separate calls to {@link #animateAdd(ViewHolder) animateAdd()},
* {@link #animateMove(ViewHolder, int, int, int, int) animateMove()},
* {@link #animateRemove(ViewHolder) animateRemove()}, and
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} come in one by one,
* then start the animations together in the later call to {@link #runPendingAnimations()}.
*
* @param holder The item that is being moved.
* @return true if a later call to {@link #runPendingAnimations()} is requested,
* false otherwise.
*/
abstract public boolean animateMove(ViewHolder holder, int fromX, int fromY,
int toX, int toY);
/**
* Called when an item is changed in the RecyclerView, as indicated by a call to
* {@link Adapter#notifyItemChanged(int)} or
* {@link Adapter#notifyItemRangeChanged(int, int)}.
* <p>
* Implementers can choose whether and how to animate changes, but must always call
* {@link #dispatchChangeFinished(ViewHolder, boolean)} for each non-null ViewHolder,
* either immediately (if no animation will occur) or after the animation actually finishes.
* The return value indicates whether an animation has been set up and whether the
* ItemAnimator's {@link #runPendingAnimations()} method should be called at the
* next opportunity. This mechanism allows ItemAnimator to set up individual animations
* as separate calls to {@link #animateAdd(ViewHolder) animateAdd()},
* {@link #animateMove(ViewHolder, int, int, int, int) animateMove()},
* {@link #animateRemove(ViewHolder) animateRemove()}, and
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} come in one by one,
* then start the animations together in the later call to {@link #runPendingAnimations()}.
*
* @param oldHolder The original item that changed.
* @param newHolder The new item that was created with the changed content. Might be null
* @param fromLeft Left of the old view holder
* @param fromTop Top of the old view holder
* @param toLeft Left of the new view holder
* @param toTop Top of the new view holder
* @return true if a later call to {@link #runPendingAnimations()} is requested,
* false otherwise.
*/
abstract public boolean animateChange(ViewHolder oldHolder,
ViewHolder newHolder, int fromLeft, int fromTop, int toLeft, int toTop);
/**
* Method to be called by subclasses when a remove animation is done.
*
* @param item The item which has been removed
*/
public final void dispatchRemoveFinished(ViewHolder item) {
onRemoveFinished(item);
if (mListener != null) {
mListener.onRemoveFinished(item);
}
}
/**
* Method to be called by subclasses when a move animation is done.
*
* @param item The item which has been moved
*/
public final void dispatchMoveFinished(ViewHolder item) {
onMoveFinished(item);
if (mListener != null) {
mListener.onMoveFinished(item);
}
}
/**
* Method to be called by subclasses when an add animation is done.
*
* @param item The item which has been added
*/
public final void dispatchAddFinished(ViewHolder item) {
onAddFinished(item);
if (mListener != null) {
mListener.onAddFinished(item);
}
}
/**
* Method to be called by subclasses when a change animation is done.
*
* @see #animateChange(ViewHolder, ViewHolder, int, int, int, int)
* @param item The item which has been changed (this method must be called for
* each non-null ViewHolder passed into
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)}).
* @param oldItem true if this is the old item that was changed, false if
* it is the new item that replaced the old item.
*/
public final void dispatchChangeFinished(ViewHolder item, boolean oldItem) {
onChangeFinished(item, oldItem);
if (mListener != null) {
mListener.onChangeFinished(item);
}
}
/**
* Method to be called by subclasses when a remove animation is being started.
*
* @param item The item being removed
*/
public final void dispatchRemoveStarting(ViewHolder item) {
onRemoveStarting(item);
}
/**
* Method to be called by subclasses when a move animation is being started.
*
* @param item The item being moved
*/
public final void dispatchMoveStarting(ViewHolder item) {
onMoveStarting(item);
}
/**
* Method to be called by subclasses when an add animation is being started.
*
* @param item The item being added
*/
public final void dispatchAddStarting(ViewHolder item) {
onAddStarting(item);
}
/**
* Method to be called by subclasses when a change animation is being started.
*
* @param item The item which has been changed (this method must be called for
* each non-null ViewHolder passed into
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)}).
* @param oldItem true if this is the old item that was changed, false if
* it is the new item that replaced the old item.
*/
public final void dispatchChangeStarting(ViewHolder item, boolean oldItem) {
onChangeStarting(item, oldItem);
}
/**
* Method called when an animation on a view should be ended immediately.
* This could happen when other events, like scrolling, occur, so that
* animating views can be quickly put into their proper end locations.
* Implementations should ensure that any animations running on the item
* are canceled and affected properties are set to their end values.
* Also, appropriate dispatch methods (e.g., {@link #dispatchAddFinished(ViewHolder)}
* should be called since the animations are effectively done when this
* method is called.
*
* @param item The item for which an animation should be stopped.
*/
abstract public void endAnimation(ViewHolder item);
/**
* Method called when all item animations should be ended immediately.
* This could happen when other events, like scrolling, occur, so that
* animating views can be quickly put into their proper end locations.
* Implementations should ensure that any animations running on any items
* are canceled and affected properties are set to their end values.
* Also, appropriate dispatch methods (e.g., {@link #dispatchAddFinished(ViewHolder)}
* should be called since the animations are effectively done when this
* method is called.
*/
abstract public void endAnimations();
/**
* Method which returns whether there are any item animations currently running.
* This method can be used to determine whether to delay other actions until
* animations end.
*
* @return true if there are any item animations currently running, false otherwise.
*/
abstract public boolean isRunning();
/**
* Like {@link #isRunning()}, this method returns whether there are any item
* animations currently running. Addtionally, the listener passed in will be called
* when there are no item animations running, either immediately (before the method
* returns) if no animations are currently running, or when the currently running
* animations are {@link #dispatchAnimationsFinished() finished}.
*
* <p>Note that the listener is transient - it is either called immediately and not
* stored at all, or stored only until it is called when running animations
* are finished sometime later.</p>
*
* @param listener A listener to be called immediately if no animations are running
* or later when currently-running animations have finished. A null listener is
* equivalent to calling {@link #isRunning()}.
* @return true if there are any item animations currently running, false otherwise.
*/
public final boolean isRunning(ItemAnimatorFinishedListener listener) {
boolean running = isRunning();
if (listener != null) {
if (!running) {
listener.onAnimationsFinished();
} else {
mFinishedListeners.add(listener);
}
}
return running;
}
/**
* The interface to be implemented by listeners to animation events from this
* ItemAnimator. This is used internally and is not intended for developers to
* create directly.
*/
interface ItemAnimatorListener {
void onRemoveFinished(ViewHolder item);
void onAddFinished(ViewHolder item);
void onMoveFinished(ViewHolder item);
void onChangeFinished(ViewHolder item);
}
/**
* This method should be called by ItemAnimator implementations to notify
* any listeners that all pending and active item animations are finished.
*/
public final void dispatchAnimationsFinished() {
final int count = mFinishedListeners.size();
for (int i = 0; i < count; ++i) {
mFinishedListeners.get(i).onAnimationsFinished();
}
mFinishedListeners.clear();
}
/**
* This interface is used to inform listeners when all pending or running animations
* in an ItemAnimator are finished. This can be used, for example, to delay an action
* in a data set until currently-running animations are complete.
*
* @see #isRunning(ItemAnimatorFinishedListener)
*/
public interface ItemAnimatorFinishedListener {
void onAnimationsFinished();
}
/**
* Called when a remove animation is being started on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
*/
public void onRemoveStarting(ViewHolder item) {}
/**
* Called when a remove animation has ended on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
*/
public void onRemoveFinished(ViewHolder item) {}
/**
* Called when an add animation is being started on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
*/
public void onAddStarting(ViewHolder item) {}
/**
* Called when an add animation has ended on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
*/
public void onAddFinished(ViewHolder item) {}
/**
* Called when a move animation is being started on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
*/
public void onMoveStarting(ViewHolder item) {}
/**
* Called when a move animation has ended on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
*/
public void onMoveFinished(ViewHolder item) {}
/**
* Called when a change animation is being started on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
* @param oldItem true if this is the old item that was changed, false if
* it is the new item that replaced the old item.
*/
public void onChangeStarting(ViewHolder item, boolean oldItem) {}
/**
* Called when a change animation has ended on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
* @param oldItem true if this is the old item that was changed, false if
* it is the new item that replaced the old item.
*/
public void onChangeFinished(ViewHolder item, boolean oldItem) {}
}
/**
* Internal data structure that holds information about an item's bounds.
* This information is used in calculating item animations.
*/
private static class ItemHolderInfo {
ViewHolder holder;
int left, top, right, bottom;
ItemHolderInfo(ViewHolder holder, int left, int top, int right, int bottom) {
this.holder = holder;
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
}
}
|
v7/recyclerview/src/android/support/v7/widget/RecyclerView.java
|
/*
* Copyright (C) 2013 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 android.support.v7.widget;
import android.content.Context;
import android.database.Observable;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.InputDeviceCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ScrollingView;
import android.support.v4.view.VelocityTrackerCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.view.accessibility.AccessibilityEventCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.view.accessibility.AccessibilityRecordCompat;
import android.support.v4.widget.EdgeEffectCompat;
import android.support.v4.widget.ScrollerCompat;
import static android.support.v7.widget.AdapterHelper.UpdateOp;
import static android.support.v7.widget.AdapterHelper.Callback;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.util.TypedValue;
import android.view.FocusFinder;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.animation.Interpolator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A flexible view for providing a limited window into a large data set.
*
* <h3>Glossary of terms:</h3>
*
* <ul>
* <li><em>Adapter:</em> A subclass of {@link Adapter} responsible for providing views
* that represent items in a data set.</li>
* <li><em>Position:</em> The position of a data item within an <em>Adapter</em>.</li>
* <li><em>Index:</em> The index of an attached child view as used in a call to
* {@link ViewGroup#getChildAt}. Contrast with <em>Position.</em></li>
* <li><em>Binding:</em> The process of preparing a child view to display data corresponding
* to a <em>position</em> within the adapter.</li>
* <li><em>Recycle (view):</em> A view previously used to display data for a specific adapter
* position may be placed in a cache for later reuse to display the same type of data again
* later. This can drastically improve performance by skipping initial layout inflation
* or construction.</li>
* <li><em>Scrap (view):</em> A child view that has entered into a temporarily detached
* state during layout. Scrap views may be reused without becoming fully detached
* from the parent RecyclerView, either unmodified if no rebinding is required or modified
* by the adapter if the view was considered <em>dirty</em>.</li>
* <li><em>Dirty (view):</em> A child view that must be rebound by the adapter before
* being displayed.</li>
* </ul>
*
* <h4>Positions in RecyclerView:</h4>
* <p>
* RecyclerView introduces an additional level of abstraction between the {@link Adapter} and
* {@link LayoutManager} to be able to detect data set changes in batches during a layout
* calculation. This saves LayoutManager from tracking adapter changes to calculate animations.
* It also helps with performance because all view bindings happen at the same time and unnecessary
* bindings are avoided.
* <p>
* For this reason, there are two types of <code>position</code> related methods in RecyclerView:
* <ul>
* <li>layout position: Position of an item in the latest layout calculation. This is the
* position from the LayoutManager's perspective.</li>
* <li>adapter position: Position of an item in the adapter. This is the position from
* the Adapter's perspective.</li>
* </ul>
* <p>
* These two positions are the same except the time between dispatching <code>adapter.notify*
* </code> events and calculating the updated layout.
* <p>
* Methods that return or receive <code>*LayoutPosition*</code> use position as of the latest
* layout calculation (e.g. {@link ViewHolder#getLayoutPosition()},
* {@link #findViewHolderForLayoutPosition(int)}). These positions include all changes until the
* last layout calculation. You can rely on these positions to be consistent with what user is
* currently seeing on the screen. For example, if you have a list of items on the screen and user
* asks for the 5<sup>th</sup> element, you should use these methods as they'll match what user
* is seeing.
* <p>
* The other set of position related methods are in the form of
* <code>*AdapterPosition*</code>. (e.g. {@link ViewHolder#getAdapterPosition()},
* {@link #findViewHolderForAdapterPosition(int)}) You should use these methods when you need to
* work with up-to-date adapter positions even if they may not have been reflected to layout yet.
* For example, if you want to access the item in the adapter on a ViewHolder click, you should use
* {@link ViewHolder#getAdapterPosition()}. Beware that these methods may not be able to calculate
* adapter positions if {@link Adapter#notifyDataSetChanged()} has been called and new layout has
* not yet been calculated. For this reasons, you should carefully handle {@link #NO_POSITION} or
* <code>null</code> results from these methods.
* <p>
* When writing a {@link LayoutManager} you almost always want to use layout positions whereas when
* writing an {@link Adapter}, you probably want to use adapter positions.
*/
public class RecyclerView extends ViewGroup implements ScrollingView {
private static final String TAG = "RecyclerView";
private static final boolean DEBUG = false;
/**
* On Kitkat, there is a bug which prevents DisplayList from being invalidated if a View is two
* levels deep(wrt to ViewHolder.itemView). DisplayList can be invalidated by setting
* View's visibility to INVISIBLE when View is detached. On Kitkat, Recycler recursively
* traverses itemView and invalidates display list for each ViewGroup that matches this
* criteria.
*/
private static final boolean FORCE_INVALIDATE_DISPLAY_LIST = Build.VERSION.SDK_INT == 19 ||
Build.VERSION.SDK_INT == 20;
private static final boolean DISPATCH_TEMP_DETACH = false;
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
public static final int NO_POSITION = -1;
public static final long NO_ID = -1;
public static final int INVALID_TYPE = -1;
/**
* Constant for use with {@link #setScrollingTouchSlop(int)}. Indicates
* that the RecyclerView should use the standard touch slop for smooth,
* continuous scrolling.
*/
public static final int TOUCH_SLOP_DEFAULT = 0;
/**
* Constant for use with {@link #setScrollingTouchSlop(int)}. Indicates
* that the RecyclerView should use the standard touch slop for scrolling
* widgets that snap to a page or other coarse-grained barrier.
*/
public static final int TOUCH_SLOP_PAGING = 1;
private static final int MAX_SCROLL_DURATION = 2000;
private final RecyclerViewDataObserver mObserver = new RecyclerViewDataObserver();
final Recycler mRecycler = new Recycler();
private SavedState mPendingSavedState;
AdapterHelper mAdapterHelper;
ChildHelper mChildHelper;
// we use this like a set
final List<View> mDisappearingViewsInLayoutPass = new ArrayList<View>();
/**
* Prior to L, there is no way to query this variable which is why we override the setter and
* track it here.
*/
private boolean mClipToPadding;
/**
* Note: this Runnable is only ever posted if:
* 1) We've been through first layout
* 2) We know we have a fixed size (mHasFixedSize)
* 3) We're attached
*/
private final Runnable mUpdateChildViewsRunnable = new Runnable() {
public void run() {
if (!mFirstLayoutComplete) {
// a layout request will happen, we should not do layout here.
return;
}
if (mDataSetHasChangedAfterLayout) {
dispatchLayout();
} else if (mAdapterHelper.hasPendingUpdates()) {
eatRequestLayout();
mAdapterHelper.preProcess();
if (!mLayoutRequestEaten) {
// We run this after pre-processing is complete so that ViewHolders have their
// final adapter positions. No need to run it if a layout is already requested.
rebindUpdatedViewHolders();
}
resumeRequestLayout(true);
}
}
};
private final Rect mTempRect = new Rect();
private Adapter mAdapter;
private LayoutManager mLayout;
private RecyclerListener mRecyclerListener;
private final ArrayList<ItemDecoration> mItemDecorations = new ArrayList<ItemDecoration>();
private final ArrayList<OnItemTouchListener> mOnItemTouchListeners =
new ArrayList<OnItemTouchListener>();
private OnItemTouchListener mActiveOnItemTouchListener;
private boolean mIsAttached;
private boolean mHasFixedSize;
private boolean mFirstLayoutComplete;
private boolean mEatRequestLayout;
private boolean mLayoutRequestEaten;
private boolean mAdapterUpdateDuringMeasure;
private final boolean mPostUpdatesOnAnimation;
private final AccessibilityManager mAccessibilityManager;
/**
* Set to true when an adapter data set changed notification is received.
* In that case, we cannot run any animations since we don't know what happened.
*/
private boolean mDataSetHasChangedAfterLayout = false;
/**
* This variable is set to true during a dispatchLayout and/or scroll.
* Some methods should not be called during these periods (e.g. adapter data change).
* Doing so will create hard to find bugs so we better check it and throw an exception.
*
* @see #assertInLayoutOrScroll(String)
* @see #assertNotInLayoutOrScroll(String)
*/
private boolean mRunningLayoutOrScroll = false;
private EdgeEffectCompat mLeftGlow, mTopGlow, mRightGlow, mBottomGlow;
ItemAnimator mItemAnimator = new DefaultItemAnimator();
private static final int INVALID_POINTER = -1;
/**
* The RecyclerView is not currently scrolling.
* @see #getScrollState()
*/
public static final int SCROLL_STATE_IDLE = 0;
/**
* The RecyclerView is currently being dragged by outside input such as user touch input.
* @see #getScrollState()
*/
public static final int SCROLL_STATE_DRAGGING = 1;
/**
* The RecyclerView is currently animating to a final position while not under
* outside control.
* @see #getScrollState()
*/
public static final int SCROLL_STATE_SETTLING = 2;
// Touch/scrolling handling
private int mScrollState = SCROLL_STATE_IDLE;
private int mScrollPointerId = INVALID_POINTER;
private VelocityTracker mVelocityTracker;
private int mInitialTouchX;
private int mInitialTouchY;
private int mLastTouchX;
private int mLastTouchY;
private int mTouchSlop;
private final int mMinFlingVelocity;
private final int mMaxFlingVelocity;
// This value is used when handling generic motion events.
private float mScrollFactor = Float.MIN_VALUE;
private final ViewFlinger mViewFlinger = new ViewFlinger();
final State mState = new State();
private OnScrollListener mScrollListener;
// For use in item animations
boolean mItemsAddedOrRemoved = false;
boolean mItemsChanged = false;
private ItemAnimator.ItemAnimatorListener mItemAnimatorListener =
new ItemAnimatorRestoreListener();
private boolean mPostedAnimatorRunner = false;
private RecyclerViewAccessibilityDelegate mAccessibilityDelegate;
// simple array to keep min and max child position during a layout calculation
// preserved not to create a new one in each layout pass
private final int[] mMinMaxLayoutPositions = new int[2];
private Runnable mItemAnimatorRunner = new Runnable() {
@Override
public void run() {
if (mItemAnimator != null) {
mItemAnimator.runPendingAnimations();
}
mPostedAnimatorRunner = false;
}
};
private static final Interpolator sQuinticInterpolator = new Interpolator() {
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
public RecyclerView(Context context) {
this(context, null);
}
public RecyclerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final int version = Build.VERSION.SDK_INT;
mPostUpdatesOnAnimation = version >= 16;
final ViewConfiguration vc = ViewConfiguration.get(context);
mTouchSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
setWillNotDraw(ViewCompat.getOverScrollMode(this) == ViewCompat.OVER_SCROLL_NEVER);
mItemAnimator.setListener(mItemAnimatorListener);
initAdapterManager();
initChildrenHelper();
// If not explicitly specified this view is important for accessibility.
if (ViewCompat.getImportantForAccessibility(this)
== ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
ViewCompat.setImportantForAccessibility(this,
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
mAccessibilityManager = (AccessibilityManager) getContext()
.getSystemService(Context.ACCESSIBILITY_SERVICE);
setAccessibilityDelegateCompat(new RecyclerViewAccessibilityDelegate(this));
}
/**
* Returns the accessibility delegate compatibility implementation used by the RecyclerView.
* @return An instance of AccessibilityDelegateCompat used by RecyclerView
*/
public RecyclerViewAccessibilityDelegate getCompatAccessibilityDelegate() {
return mAccessibilityDelegate;
}
/**
* Sets the accessibility delegate compatibility implementation used by RecyclerView.
* @param accessibilityDelegate The accessibility delegate to be used by RecyclerView.
*/
public void setAccessibilityDelegateCompat(
RecyclerViewAccessibilityDelegate accessibilityDelegate) {
mAccessibilityDelegate = accessibilityDelegate;
ViewCompat.setAccessibilityDelegate(this, mAccessibilityDelegate);
}
private void initChildrenHelper() {
mChildHelper = new ChildHelper(new ChildHelper.Callback() {
@Override
public int getChildCount() {
return RecyclerView.this.getChildCount();
}
@Override
public void addView(View child, int index) {
RecyclerView.this.addView(child, index);
dispatchChildAttached(child);
}
@Override
public int indexOfChild(View view) {
return RecyclerView.this.indexOfChild(view);
}
@Override
public void removeViewAt(int index) {
final View child = RecyclerView.this.getChildAt(index);
if (child != null) {
dispatchChildDetached(child);
}
RecyclerView.this.removeViewAt(index);
}
@Override
public View getChildAt(int offset) {
return RecyclerView.this.getChildAt(offset);
}
@Override
public void removeAllViews() {
final int count = getChildCount();
for (int i = 0; i < count; i ++) {
dispatchChildDetached(getChildAt(i));
}
RecyclerView.this.removeAllViews();
}
@Override
public ViewHolder getChildViewHolder(View view) {
return getChildViewHolderInt(view);
}
@Override
public void attachViewToParent(View child, int index,
ViewGroup.LayoutParams layoutParams) {
final ViewHolder vh = getChildViewHolderInt(child);
if (vh != null) {
if (!vh.isTmpDetached() && !vh.shouldIgnore()) {
throw new IllegalArgumentException("Called attach on a child which is not"
+ " detached: " + vh);
}
if (DEBUG) {
Log.d(TAG, "reAttach " + vh);
}
vh.clearTmpDetachFlag();
}
RecyclerView.this.attachViewToParent(child, index, layoutParams);
}
@Override
public void detachViewFromParent(int offset) {
final View view = getChildAt(offset);
if (view != null) {
final ViewHolder vh = getChildViewHolderInt(view);
if (vh != null) {
if (vh.isTmpDetached() && !vh.shouldIgnore()) {
throw new IllegalArgumentException("called detach on an already"
+ " detached child " + vh);
}
if (DEBUG) {
Log.d(TAG, "tmpDetach " + vh);
}
vh.addFlags(ViewHolder.FLAG_TMP_DETACHED);
}
}
RecyclerView.this.detachViewFromParent(offset);
}
});
}
void initAdapterManager() {
mAdapterHelper = new AdapterHelper(new Callback() {
@Override
public ViewHolder findViewHolder(int position) {
final ViewHolder vh = findViewHolderForPosition(position, true);
if (vh == null) {
return null;
}
// ensure it is not hidden because for adapter helper, the only thing matter is that
// LM thinks view is a child.
if (mChildHelper.isHidden(vh.itemView)) {
if (DEBUG) {
Log.d(TAG, "assuming view holder cannot be find because it is hidden");
}
return null;
}
return vh;
}
@Override
public void offsetPositionsForRemovingInvisible(int start, int count) {
offsetPositionRecordsForRemove(start, count, true);
mItemsAddedOrRemoved = true;
mState.mDeletedInvisibleItemCountSincePreviousLayout += count;
}
@Override
public void offsetPositionsForRemovingLaidOutOrNewView(int positionStart, int itemCount) {
offsetPositionRecordsForRemove(positionStart, itemCount, false);
mItemsAddedOrRemoved = true;
}
@Override
public void markViewHoldersUpdated(int positionStart, int itemCount) {
viewRangeUpdate(positionStart, itemCount);
mItemsChanged = true;
}
@Override
public void onDispatchFirstPass(UpdateOp op) {
dispatchUpdate(op);
}
void dispatchUpdate(UpdateOp op) {
switch (op.cmd) {
case UpdateOp.ADD:
mLayout.onItemsAdded(RecyclerView.this, op.positionStart, op.itemCount);
break;
case UpdateOp.REMOVE:
mLayout.onItemsRemoved(RecyclerView.this, op.positionStart, op.itemCount);
break;
case UpdateOp.UPDATE:
mLayout.onItemsUpdated(RecyclerView.this, op.positionStart, op.itemCount);
break;
case UpdateOp.MOVE:
mLayout.onItemsMoved(RecyclerView.this, op.positionStart, op.itemCount, 1);
break;
}
}
@Override
public void onDispatchSecondPass(UpdateOp op) {
dispatchUpdate(op);
}
@Override
public void offsetPositionsForAdd(int positionStart, int itemCount) {
offsetPositionRecordsForInsert(positionStart, itemCount);
mItemsAddedOrRemoved = true;
}
@Override
public void offsetPositionsForMove(int from, int to) {
offsetPositionRecordsForMove(from, to);
// should we create mItemsMoved ?
mItemsAddedOrRemoved = true;
}
});
}
/**
* RecyclerView can perform several optimizations if it can know in advance that changes in
* adapter content cannot change the size of the RecyclerView itself.
* If your use of RecyclerView falls into this category, set this to true.
*
* @param hasFixedSize true if adapter changes cannot affect the size of the RecyclerView.
*/
public void setHasFixedSize(boolean hasFixedSize) {
mHasFixedSize = hasFixedSize;
}
/**
* @return true if the app has specified that changes in adapter content cannot change
* the size of the RecyclerView itself.
*/
public boolean hasFixedSize() {
return mHasFixedSize;
}
@Override
public void setClipToPadding(boolean clipToPadding) {
if (clipToPadding != mClipToPadding) {
invalidateGlows();
}
mClipToPadding = clipToPadding;
super.setClipToPadding(clipToPadding);
if (mFirstLayoutComplete) {
requestLayout();
}
}
/**
* Configure the scrolling touch slop for a specific use case.
*
* Set up the RecyclerView's scrolling motion threshold based on common usages.
* Valid arguments are {@link #TOUCH_SLOP_DEFAULT} and {@link #TOUCH_SLOP_PAGING}.
*
* @param slopConstant One of the <code>TOUCH_SLOP_</code> constants representing
* the intended usage of this RecyclerView
*/
public void setScrollingTouchSlop(int slopConstant) {
final ViewConfiguration vc = ViewConfiguration.get(getContext());
switch (slopConstant) {
default:
Log.w(TAG, "setScrollingTouchSlop(): bad argument constant "
+ slopConstant + "; using default value");
// fall-through
case TOUCH_SLOP_DEFAULT:
mTouchSlop = vc.getScaledTouchSlop();
break;
case TOUCH_SLOP_PAGING:
mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(vc);
break;
}
}
/**
* Swaps the current adapter with the provided one. It is similar to
* {@link #setAdapter(Adapter)} but assumes existing adapter and the new adapter uses the same
* {@link ViewHolder} and does not clear the RecycledViewPool.
* <p>
* Note that it still calls onAdapterChanged callbacks.
*
* @param adapter The new adapter to set, or null to set no adapter.
* @param removeAndRecycleExistingViews If set to true, RecyclerView will recycle all existing
* Views. If adapters have stable ids and/or you want to
* animate the disappearing views, you may prefer to set
* this to false.
* @see #setAdapter(Adapter)
*/
public void swapAdapter(Adapter adapter, boolean removeAndRecycleExistingViews) {
setAdapterInternal(adapter, true, removeAndRecycleExistingViews);
setDataSetChangedAfterLayout();
requestLayout();
}
/**
* Set a new adapter to provide child views on demand.
* <p>
* When adapter is changed, all existing views are recycled back to the pool. If the pool has
* only one adapter, it will be cleared.
*
* @param adapter The new adapter to set, or null to set no adapter.
* @see #swapAdapter(Adapter, boolean)
*/
public void setAdapter(Adapter adapter) {
setAdapterInternal(adapter, false, true);
requestLayout();
}
/**
* Replaces the current adapter with the new one and triggers listeners.
* @param adapter The new adapter
* @param compatibleWithPrevious If true, the new adapter is using the same View Holders and
* item types with the current adapter (helps us avoid cache
* invalidation).
* @param removeAndRecycleViews If true, we'll remove and recycle all existing views. If
* compatibleWithPrevious is false, this parameter is ignored.
*/
private void setAdapterInternal(Adapter adapter, boolean compatibleWithPrevious,
boolean removeAndRecycleViews) {
if (mAdapter != null) {
mAdapter.unregisterAdapterDataObserver(mObserver);
mAdapter.onDetachedFromRecyclerView(this);
}
if (!compatibleWithPrevious || removeAndRecycleViews) {
// end all running animations
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
}
// Since animations are ended, mLayout.children should be equal to
// recyclerView.children. This may not be true if item animator's end does not work as
// expected. (e.g. not release children instantly). It is safer to use mLayout's child
// count.
if (mLayout != null) {
mLayout.removeAndRecycleAllViews(mRecycler);
mLayout.removeAndRecycleScrapInt(mRecycler);
}
// we should clear it here before adapters are swapped to ensure correct callbacks.
mRecycler.clear();
}
mAdapterHelper.reset();
final Adapter oldAdapter = mAdapter;
mAdapter = adapter;
if (adapter != null) {
adapter.registerAdapterDataObserver(mObserver);
adapter.onAttachedToRecyclerView(this);
}
if (mLayout != null) {
mLayout.onAdapterChanged(oldAdapter, mAdapter);
}
mRecycler.onAdapterChanged(oldAdapter, mAdapter, compatibleWithPrevious);
mState.mStructureChanged = true;
markKnownViewsInvalid();
}
/**
* Retrieves the previously set adapter or null if no adapter is set.
*
* @return The previously set adapter
* @see #setAdapter(Adapter)
*/
public Adapter getAdapter() {
return mAdapter;
}
/**
* Register a listener that will be notified whenever a child view is recycled.
*
* <p>This listener will be called when a LayoutManager or the RecyclerView decides
* that a child view is no longer needed. If an application associates expensive
* or heavyweight data with item views, this may be a good place to release
* or free those resources.</p>
*
* @param listener Listener to register, or null to clear
*/
public void setRecyclerListener(RecyclerListener listener) {
mRecyclerListener = listener;
}
/**
* Set the {@link LayoutManager} that this RecyclerView will use.
*
* <p>In contrast to other adapter-backed views such as {@link android.widget.ListView}
* or {@link android.widget.GridView}, RecyclerView allows client code to provide custom
* layout arrangements for child views. These arrangements are controlled by the
* {@link LayoutManager}. A LayoutManager must be provided for RecyclerView to function.</p>
*
* <p>Several default strategies are provided for common uses such as lists and grids.</p>
*
* @param layout LayoutManager to use
*/
public void setLayoutManager(LayoutManager layout) {
if (layout == mLayout) {
return;
}
// TODO We should do this switch a dispachLayout pass and animate children. There is a good
// chance that LayoutManagers will re-use views.
if (mLayout != null) {
if (mIsAttached) {
mLayout.onDetachedFromWindow(this, mRecycler);
}
mLayout.setRecyclerView(null);
}
mRecycler.clear();
mChildHelper.removeAllViewsUnfiltered();
mLayout = layout;
if (layout != null) {
if (layout.mRecyclerView != null) {
throw new IllegalArgumentException("LayoutManager " + layout +
" is already attached to a RecyclerView: " + layout.mRecyclerView);
}
mLayout.setRecyclerView(this);
if (mIsAttached) {
mLayout.onAttachedToWindow(this);
}
}
requestLayout();
}
@Override
protected Parcelable onSaveInstanceState() {
SavedState state = new SavedState(super.onSaveInstanceState());
if (mPendingSavedState != null) {
state.copyFrom(mPendingSavedState);
} else if (mLayout != null) {
state.mLayoutState = mLayout.onSaveInstanceState();
} else {
state.mLayoutState = null;
}
return state;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
mPendingSavedState = (SavedState) state;
super.onRestoreInstanceState(mPendingSavedState.getSuperState());
if (mLayout != null && mPendingSavedState.mLayoutState != null) {
mLayout.onRestoreInstanceState(mPendingSavedState.mLayoutState);
}
}
/**
* Adds a view to the animatingViews list.
* mAnimatingViews holds the child views that are currently being kept around
* purely for the purpose of being animated out of view. They are drawn as a regular
* part of the child list of the RecyclerView, but they are invisible to the LayoutManager
* as they are managed separately from the regular child views.
* @param viewHolder The ViewHolder to be removed
*/
private void addAnimatingView(ViewHolder viewHolder) {
final View view = viewHolder.itemView;
final boolean alreadyParented = view.getParent() == this;
mRecycler.unscrapView(getChildViewHolder(view));
if (viewHolder.isTmpDetached()) {
// re-attach
mChildHelper.attachViewToParent(view, -1, view.getLayoutParams(), true);
} else if(!alreadyParented) {
mChildHelper.addView(view, true);
} else {
mChildHelper.hide(view);
}
}
/**
* Removes a view from the animatingViews list.
* @param view The view to be removed
* @see #addAnimatingView(RecyclerView.ViewHolder)
* @return true if an animating view is removed
*/
private boolean removeAnimatingView(View view) {
eatRequestLayout();
final boolean removed = mChildHelper.removeViewIfHidden(view);
if (removed) {
final ViewHolder viewHolder = getChildViewHolderInt(view);
mRecycler.unscrapView(viewHolder);
mRecycler.recycleViewHolderInternal(viewHolder);
if (DEBUG) {
Log.d(TAG, "after removing animated view: " + view + ", " + this);
}
}
resumeRequestLayout(false);
return removed;
}
/**
* Return the {@link LayoutManager} currently responsible for
* layout policy for this RecyclerView.
*
* @return The currently bound LayoutManager
*/
public LayoutManager getLayoutManager() {
return mLayout;
}
/**
* Retrieve this RecyclerView's {@link RecycledViewPool}. This method will never return null;
* if no pool is set for this view a new one will be created. See
* {@link #setRecycledViewPool(RecycledViewPool) setRecycledViewPool} for more information.
*
* @return The pool used to store recycled item views for reuse.
* @see #setRecycledViewPool(RecycledViewPool)
*/
public RecycledViewPool getRecycledViewPool() {
return mRecycler.getRecycledViewPool();
}
/**
* Recycled view pools allow multiple RecyclerViews to share a common pool of scrap views.
* This can be useful if you have multiple RecyclerViews with adapters that use the same
* view types, for example if you have several data sets with the same kinds of item views
* displayed by a {@link android.support.v4.view.ViewPager ViewPager}.
*
* @param pool Pool to set. If this parameter is null a new pool will be created and used.
*/
public void setRecycledViewPool(RecycledViewPool pool) {
mRecycler.setRecycledViewPool(pool);
}
/**
* Sets a new {@link ViewCacheExtension} to be used by the Recycler.
*
* @param extension ViewCacheExtension to be used or null if you want to clear the existing one.
*
* @see {@link ViewCacheExtension#getViewForPositionAndType(Recycler, int, int)}
*/
public void setViewCacheExtension(ViewCacheExtension extension) {
mRecycler.setViewCacheExtension(extension);
}
/**
* Set the number of offscreen views to retain before adding them to the potentially shared
* {@link #getRecycledViewPool() recycled view pool}.
*
* <p>The offscreen view cache stays aware of changes in the attached adapter, allowing
* a LayoutManager to reuse those views unmodified without needing to return to the adapter
* to rebind them.</p>
*
* @param size Number of views to cache offscreen before returning them to the general
* recycled view pool
*/
public void setItemViewCacheSize(int size) {
mRecycler.setViewCacheSize(size);
}
/**
* Return the current scrolling state of the RecyclerView.
*
* @return {@link #SCROLL_STATE_IDLE}, {@link #SCROLL_STATE_DRAGGING} or
* {@link #SCROLL_STATE_SETTLING}
*/
public int getScrollState() {
return mScrollState;
}
private void setScrollState(int state) {
if (state == mScrollState) {
return;
}
if (DEBUG) {
Log.d(TAG, "setting scroll state to " + state + " from " + mScrollState, new Exception());
}
mScrollState = state;
if (state != SCROLL_STATE_SETTLING) {
stopScrollersInternal();
}
if (mScrollListener != null) {
mScrollListener.onScrollStateChanged(this, state);
}
if (mLayout != null) {
mLayout.onScrollStateChanged(state);
}
}
/**
* Add an {@link ItemDecoration} to this RecyclerView. Item decorations can
* affect both measurement and drawing of individual item views.
*
* <p>Item decorations are ordered. Decorations placed earlier in the list will
* be run/queried/drawn first for their effects on item views. Padding added to views
* will be nested; a padding added by an earlier decoration will mean further
* item decorations in the list will be asked to draw/pad within the previous decoration's
* given area.</p>
*
* @param decor Decoration to add
* @param index Position in the decoration chain to insert this decoration at. If this value
* is negative the decoration will be added at the end.
*/
public void addItemDecoration(ItemDecoration decor, int index) {
if (mLayout != null) {
mLayout.assertNotInLayoutOrScroll("Cannot add item decoration during a scroll or"
+ " layout");
}
if (mItemDecorations.isEmpty()) {
setWillNotDraw(false);
}
if (index < 0) {
mItemDecorations.add(decor);
} else {
mItemDecorations.add(index, decor);
}
markItemDecorInsetsDirty();
requestLayout();
}
/**
* Add an {@link ItemDecoration} to this RecyclerView. Item decorations can
* affect both measurement and drawing of individual item views.
*
* <p>Item decorations are ordered. Decorations placed earlier in the list will
* be run/queried/drawn first for their effects on item views. Padding added to views
* will be nested; a padding added by an earlier decoration will mean further
* item decorations in the list will be asked to draw/pad within the previous decoration's
* given area.</p>
*
* @param decor Decoration to add
*/
public void addItemDecoration(ItemDecoration decor) {
addItemDecoration(decor, -1);
}
/**
* Remove an {@link ItemDecoration} from this RecyclerView.
*
* <p>The given decoration will no longer impact the measurement and drawing of
* item views.</p>
*
* @param decor Decoration to remove
* @see #addItemDecoration(ItemDecoration)
*/
public void removeItemDecoration(ItemDecoration decor) {
if (mLayout != null) {
mLayout.assertNotInLayoutOrScroll("Cannot remove item decoration during a scroll or"
+ " layout");
}
mItemDecorations.remove(decor);
if (mItemDecorations.isEmpty()) {
setWillNotDraw(ViewCompat.getOverScrollMode(this) == ViewCompat.OVER_SCROLL_NEVER);
}
markItemDecorInsetsDirty();
requestLayout();
}
/**
* Set a listener that will be notified of any changes in scroll state or position.
*
* @param listener Listener to set or null to clear
*/
public void setOnScrollListener(OnScrollListener listener) {
mScrollListener = listener;
}
/**
* Convenience method to scroll to a certain position.
*
* RecyclerView does not implement scrolling logic, rather forwards the call to
* {@link android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)}
* @param position Scroll to this adapter position
* @see android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)
*/
public void scrollToPosition(int position) {
stopScroll();
if (mLayout == null) {
Log.e(TAG, "Cannot scroll to position a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
return;
}
mLayout.scrollToPosition(position);
awakenScrollBars();
}
/**
* Starts a smooth scroll to an adapter position.
* <p>
* To support smooth scrolling, you must override
* {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} and create a
* {@link SmoothScroller}.
* <p>
* {@link LayoutManager} is responsible for creating the actual scroll action. If you want to
* provide a custom smooth scroll logic, override
* {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} in your
* LayoutManager.
*
* @param position The adapter position to scroll to
* @see LayoutManager#smoothScrollToPosition(RecyclerView, State, int)
*/
public void smoothScrollToPosition(int position) {
if (mLayout == null) {
Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
return;
}
mLayout.smoothScrollToPosition(this, mState, position);
}
@Override
public void scrollTo(int x, int y) {
throw new UnsupportedOperationException(
"RecyclerView does not support scrolling to an absolute position.");
}
@Override
public void scrollBy(int x, int y) {
if (mLayout == null) {
Log.e(TAG, "Cannot scroll without a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
return;
}
final boolean canScrollHorizontal = mLayout.canScrollHorizontally();
final boolean canScrollVertical = mLayout.canScrollVertically();
if (canScrollHorizontal || canScrollVertical) {
scrollByInternal(canScrollHorizontal ? x : 0, canScrollVertical ? y : 0);
}
}
/**
* Helper method reflect data changes to the state.
* <p>
* Adapter changes during a scroll may trigger a crash because scroll assumes no data change
* but data actually changed.
* <p>
* This method consumes all deferred changes to avoid that case.
*/
private void consumePendingUpdateOperations() {
mUpdateChildViewsRunnable.run();
}
/**
* Does not perform bounds checking. Used by internal methods that have already validated input.
*
* @return Whether any scroll was consumed in either direction.
*/
boolean scrollByInternal(int x, int y) {
int overscrollX = 0, overscrollY = 0;
int hresult = 0, vresult = 0;
consumePendingUpdateOperations();
if (mAdapter != null) {
eatRequestLayout();
mRunningLayoutOrScroll = true;
if (x != 0) {
hresult = mLayout.scrollHorizontallyBy(x, mRecycler, mState);
overscrollX = x - hresult;
}
if (y != 0) {
vresult = mLayout.scrollVerticallyBy(y, mRecycler, mState);
overscrollY = y - vresult;
}
if (supportsChangeAnimations()) {
// Fix up shadow views used by changing animations
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; i++) {
View view = mChildHelper.getChildAt(i);
ViewHolder holder = getChildViewHolder(view);
if (holder != null && holder.mShadowingHolder != null) {
ViewHolder shadowingHolder = holder.mShadowingHolder;
View shadowingView = shadowingHolder != null ? shadowingHolder.itemView : null;
if (shadowingView != null) {
int left = view.getLeft();
int top = view.getTop();
if (left != shadowingView.getLeft() || top != shadowingView.getTop()) {
shadowingView.layout(left, top,
left + shadowingView.getWidth(),
top + shadowingView.getHeight());
}
}
}
}
}
mRunningLayoutOrScroll = false;
resumeRequestLayout(false);
}
if (!mItemDecorations.isEmpty()) {
invalidate();
}
if (ViewCompat.getOverScrollMode(this) != ViewCompat.OVER_SCROLL_NEVER) {
considerReleasingGlowsOnScroll(x, y);
pullGlows(overscrollX, overscrollY);
}
if (hresult != 0 || vresult != 0) {
notifyOnScrolled(hresult, vresult);
}
if (!awakenScrollBars()) {
invalidate();
}
return hresult != 0 || vresult != 0;
}
/**
* <p>Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal
* range. This value is used to compute the length of the thumb within the scrollbar's track.
* </p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeHorizontalScrollRange()} and {@link #computeHorizontalScrollExtent()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeHorizontalScrollOffset(RecyclerView.State)} in your
* LayoutManager. </p>
*
* @return The horizontal offset of the scrollbar's thumb
* @see android.support.v7.widget.RecyclerView.LayoutManager#computeHorizontalScrollOffset
* (RecyclerView.Adapter)
*/
@Override
public int computeHorizontalScrollOffset() {
return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollOffset(mState)
: 0;
}
/**
* <p>Compute the horizontal extent of the horizontal scrollbar's thumb within the
* horizontal range. This value is used to compute the length of the thumb within the
* scrollbar's track.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeHorizontalScrollRange()} and {@link #computeHorizontalScrollOffset()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeHorizontalScrollExtent(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The horizontal extent of the scrollbar's thumb
* @see RecyclerView.LayoutManager#computeHorizontalScrollExtent(RecyclerView.State)
*/
@Override
public int computeHorizontalScrollExtent() {
return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollExtent(mState) : 0;
}
/**
* <p>Compute the horizontal range that the horizontal scrollbar represents.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeHorizontalScrollExtent()} and {@link #computeHorizontalScrollOffset()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeHorizontalScrollRange(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The total horizontal range represented by the vertical scrollbar
* @see RecyclerView.LayoutManager#computeHorizontalScrollRange(RecyclerView.State)
*/
@Override
public int computeHorizontalScrollRange() {
return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollRange(mState) : 0;
}
/**
* <p>Compute the vertical offset of the vertical scrollbar's thumb within the vertical range.
* This value is used to compute the length of the thumb within the scrollbar's track. </p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeVerticalScrollRange()} and {@link #computeVerticalScrollExtent()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeVerticalScrollOffset(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The vertical offset of the scrollbar's thumb
* @see android.support.v7.widget.RecyclerView.LayoutManager#computeVerticalScrollOffset
* (RecyclerView.Adapter)
*/
@Override
public int computeVerticalScrollOffset() {
return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollOffset(mState) : 0;
}
/**
* <p>Compute the vertical extent of the vertical scrollbar's thumb within the vertical range.
* This value is used to compute the length of the thumb within the scrollbar's track.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeVerticalScrollRange()} and {@link #computeVerticalScrollOffset()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeVerticalScrollExtent(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The vertical extent of the scrollbar's thumb
* @see RecyclerView.LayoutManager#computeVerticalScrollExtent(RecyclerView.State)
*/
@Override
public int computeVerticalScrollExtent() {
return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollExtent(mState) : 0;
}
/**
* <p>Compute the vertical range that the vertical scrollbar represents.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the units used by
* {@link #computeVerticalScrollExtent()} and {@link #computeVerticalScrollOffset()}.</p>
*
* <p>Default implementation returns 0.</p>
*
* <p>If you want to support scroll bars, override
* {@link RecyclerView.LayoutManager#computeVerticalScrollRange(RecyclerView.State)} in your
* LayoutManager.</p>
*
* @return The total vertical range represented by the vertical scrollbar
* @see RecyclerView.LayoutManager#computeVerticalScrollRange(RecyclerView.State)
*/
@Override
public int computeVerticalScrollRange() {
return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollRange(mState) : 0;
}
void eatRequestLayout() {
if (!mEatRequestLayout) {
mEatRequestLayout = true;
mLayoutRequestEaten = false;
}
}
void resumeRequestLayout(boolean performLayoutChildren) {
if (mEatRequestLayout) {
if (performLayoutChildren && mLayoutRequestEaten &&
mLayout != null && mAdapter != null) {
dispatchLayout();
}
mEatRequestLayout = false;
mLayoutRequestEaten = false;
}
}
/**
* Animate a scroll by the given amount of pixels along either axis.
*
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
*/
public void smoothScrollBy(int dx, int dy) {
if (mLayout == null) {
Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
return;
}
if (!mLayout.canScrollHorizontally()) {
dx = 0;
}
if (!mLayout.canScrollVertically()) {
dy = 0;
}
if (dx != 0 || dy != 0) {
mViewFlinger.smoothScrollBy(dx, dy);
}
}
/**
* Begin a standard fling with an initial velocity along each axis in pixels per second.
* If the velocity given is below the system-defined minimum this method will return false
* and no fling will occur.
*
* @param velocityX Initial horizontal velocity in pixels per second
* @param velocityY Initial vertical velocity in pixels per second
* @return true if the fling was started, false if the velocity was too low to fling or
* LayoutManager does not support scrolling in the axis fling is issued.
*
* @see LayoutManager#canScrollVertically()
* @see LayoutManager#canScrollHorizontally()
*/
public boolean fling(int velocityX, int velocityY) {
if (mLayout == null) {
Log.e(TAG, "Cannot fling without a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
return false;
}
final boolean canScrollHorizontal = mLayout.canScrollHorizontally();
final boolean canScrollVertical = mLayout.canScrollVertically();
if (!canScrollHorizontal || Math.abs(velocityX) < mMinFlingVelocity) {
velocityX = 0;
}
if (!canScrollVertical || Math.abs(velocityY) < mMinFlingVelocity) {
velocityY = 0;
}
velocityX = Math.max(-mMaxFlingVelocity, Math.min(velocityX, mMaxFlingVelocity));
velocityY = Math.max(-mMaxFlingVelocity, Math.min(velocityY, mMaxFlingVelocity));
if (velocityX != 0 || velocityY != 0) {
mViewFlinger.fling(velocityX, velocityY);
return true;
}
return false;
}
/**
* Stop any current scroll in progress, such as one started by
* {@link #smoothScrollBy(int, int)}, {@link #fling(int, int)} or a touch-initiated fling.
*/
public void stopScroll() {
setScrollState(SCROLL_STATE_IDLE);
stopScrollersInternal();
}
/**
* Similar to {@link #stopScroll()} but does not set the state.
*/
private void stopScrollersInternal() {
mViewFlinger.stop();
if (mLayout != null) {
mLayout.stopSmoothScroller();
}
}
/**
* Apply a pull to relevant overscroll glow effects
*/
private void pullGlows(int overscrollX, int overscrollY) {
if (overscrollX < 0) {
ensureLeftGlow();
mLeftGlow.onPull(-overscrollX / (float) getWidth());
} else if (overscrollX > 0) {
ensureRightGlow();
mRightGlow.onPull(overscrollX / (float) getWidth());
}
if (overscrollY < 0) {
ensureTopGlow();
mTopGlow.onPull(-overscrollY / (float) getHeight());
} else if (overscrollY > 0) {
ensureBottomGlow();
mBottomGlow.onPull(overscrollY / (float) getHeight());
}
if (overscrollX != 0 || overscrollY != 0) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
private void releaseGlows() {
boolean needsInvalidate = false;
if (mLeftGlow != null) needsInvalidate = mLeftGlow.onRelease();
if (mTopGlow != null) needsInvalidate |= mTopGlow.onRelease();
if (mRightGlow != null) needsInvalidate |= mRightGlow.onRelease();
if (mBottomGlow != null) needsInvalidate |= mBottomGlow.onRelease();
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
private void considerReleasingGlowsOnScroll(int dx, int dy) {
boolean needsInvalidate = false;
if (mLeftGlow != null && !mLeftGlow.isFinished() && dx > 0) {
needsInvalidate = mLeftGlow.onRelease();
}
if (mRightGlow != null && !mRightGlow.isFinished() && dx < 0) {
needsInvalidate |= mRightGlow.onRelease();
}
if (mTopGlow != null && !mTopGlow.isFinished() && dy > 0) {
needsInvalidate |= mTopGlow.onRelease();
}
if (mBottomGlow != null && !mBottomGlow.isFinished() && dy < 0) {
needsInvalidate |= mBottomGlow.onRelease();
}
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
void absorbGlows(int velocityX, int velocityY) {
if (velocityX < 0) {
ensureLeftGlow();
mLeftGlow.onAbsorb(-velocityX);
} else if (velocityX > 0) {
ensureRightGlow();
mRightGlow.onAbsorb(velocityX);
}
if (velocityY < 0) {
ensureTopGlow();
mTopGlow.onAbsorb(-velocityY);
} else if (velocityY > 0) {
ensureBottomGlow();
mBottomGlow.onAbsorb(velocityY);
}
if (velocityX != 0 || velocityY != 0) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
void ensureLeftGlow() {
if (mLeftGlow != null) {
return;
}
mLeftGlow = new EdgeEffectCompat(getContext());
if (mClipToPadding) {
mLeftGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
getMeasuredWidth() - getPaddingLeft() - getPaddingRight());
} else {
mLeftGlow.setSize(getMeasuredHeight(), getMeasuredWidth());
}
}
void ensureRightGlow() {
if (mRightGlow != null) {
return;
}
mRightGlow = new EdgeEffectCompat(getContext());
if (mClipToPadding) {
mRightGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
getMeasuredWidth() - getPaddingLeft() - getPaddingRight());
} else {
mRightGlow.setSize(getMeasuredHeight(), getMeasuredWidth());
}
}
void ensureTopGlow() {
if (mTopGlow != null) {
return;
}
mTopGlow = new EdgeEffectCompat(getContext());
if (mClipToPadding) {
mTopGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
getMeasuredHeight() - getPaddingTop() - getPaddingBottom());
} else {
mTopGlow.setSize(getMeasuredWidth(), getMeasuredHeight());
}
}
void ensureBottomGlow() {
if (mBottomGlow != null) {
return;
}
mBottomGlow = new EdgeEffectCompat(getContext());
if (mClipToPadding) {
mBottomGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
getMeasuredHeight() - getPaddingTop() - getPaddingBottom());
} else {
mBottomGlow.setSize(getMeasuredWidth(), getMeasuredHeight());
}
}
void invalidateGlows() {
mLeftGlow = mRightGlow = mTopGlow = mBottomGlow = null;
}
// Focus handling
@Override
public View focusSearch(View focused, int direction) {
View result = mLayout.onInterceptFocusSearch(focused, direction);
if (result != null) {
return result;
}
final FocusFinder ff = FocusFinder.getInstance();
result = ff.findNextFocus(this, focused, direction);
if (result == null && mAdapter != null && mLayout != null) {
eatRequestLayout();
result = mLayout.onFocusSearchFailed(focused, direction, mRecycler, mState);
resumeRequestLayout(false);
}
return result != null ? result : super.focusSearch(focused, direction);
}
@Override
public void requestChildFocus(View child, View focused) {
if (!mLayout.onRequestChildFocus(this, mState, child, focused) && focused != null) {
mTempRect.set(0, 0, focused.getWidth(), focused.getHeight());
// get item decor offsets w/o refreshing. If they are invalid, there will be another
// layout pass to fix them, then it is LayoutManager's responsibility to keep focused
// View in viewport.
final LayoutParams lp = (LayoutParams) focused.getLayoutParams();
if (lp != null && !lp.mInsetsDirty) {
final Rect insets = lp.mDecorInsets;
mTempRect.left -= insets.left;
mTempRect.right += insets.right;
mTempRect.top -= insets.top;
mTempRect.bottom += insets.bottom;
}
offsetDescendantRectToMyCoords(focused, mTempRect);
offsetRectIntoDescendantCoords(child, mTempRect);
requestChildRectangleOnScreen(child, mTempRect, !mFirstLayoutComplete);
}
super.requestChildFocus(child, focused);
}
@Override
public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
return mLayout.requestChildRectangleOnScreen(this, child, rect, immediate);
}
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
if (!mLayout.onAddFocusables(this, views, direction, focusableMode)) {
super.addFocusables(views, direction, focusableMode);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mIsAttached = true;
mFirstLayoutComplete = false;
if (mLayout != null) {
mLayout.onAttachedToWindow(this);
}
mPostedAnimatorRunner = false;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
}
mFirstLayoutComplete = false;
stopScroll();
mIsAttached = false;
if (mLayout != null) {
mLayout.onDetachedFromWindow(this, mRecycler);
}
removeCallbacks(mItemAnimatorRunner);
}
/**
* Checks if RecyclerView is in the middle of a layout or scroll and throws an
* {@link IllegalStateException} if it <b>is not</b>.
*
* @param message The message for the exception. Can be null.
* @see #assertNotInLayoutOrScroll(String)
*/
void assertInLayoutOrScroll(String message) {
if (!mRunningLayoutOrScroll) {
if (message == null) {
throw new IllegalStateException("Cannot call this method unless RecyclerView is "
+ "computing a layout or scrolling");
}
throw new IllegalStateException(message);
}
}
/**
* Checks if RecyclerView is in the middle of a layout or scroll and throws an
* {@link IllegalStateException} if it <b>is</b>.
*
* @param message The message for the exception. Can be null.
* @see #assertInLayoutOrScroll(String)
*/
void assertNotInLayoutOrScroll(String message) {
if (mRunningLayoutOrScroll) {
if (message == null) {
throw new IllegalStateException("Cannot call this method while RecyclerView is "
+ "computing a layout or scrolling");
}
throw new IllegalStateException(message);
}
}
/**
* Add an {@link OnItemTouchListener} to intercept touch events before they are dispatched
* to child views or this view's standard scrolling behavior.
*
* <p>Client code may use listeners to implement item manipulation behavior. Once a listener
* returns true from
* {@link OnItemTouchListener#onInterceptTouchEvent(RecyclerView, MotionEvent)} its
* {@link OnItemTouchListener#onTouchEvent(RecyclerView, MotionEvent)} method will be called
* for each incoming MotionEvent until the end of the gesture.</p>
*
* @param listener Listener to add
*/
public void addOnItemTouchListener(OnItemTouchListener listener) {
mOnItemTouchListeners.add(listener);
}
/**
* Remove an {@link OnItemTouchListener}. It will no longer be able to intercept touch events.
*
* @param listener Listener to remove
*/
public void removeOnItemTouchListener(OnItemTouchListener listener) {
mOnItemTouchListeners.remove(listener);
if (mActiveOnItemTouchListener == listener) {
mActiveOnItemTouchListener = null;
}
}
private boolean dispatchOnItemTouchIntercept(MotionEvent e) {
final int action = e.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_DOWN) {
mActiveOnItemTouchListener = null;
}
final int listenerCount = mOnItemTouchListeners.size();
for (int i = 0; i < listenerCount; i++) {
final OnItemTouchListener listener = mOnItemTouchListeners.get(i);
if (listener.onInterceptTouchEvent(this, e) && action != MotionEvent.ACTION_CANCEL) {
mActiveOnItemTouchListener = listener;
return true;
}
}
return false;
}
private boolean dispatchOnItemTouch(MotionEvent e) {
final int action = e.getAction();
if (mActiveOnItemTouchListener != null) {
if (action == MotionEvent.ACTION_DOWN) {
// Stale state from a previous gesture, we're starting a new one. Clear it.
mActiveOnItemTouchListener = null;
} else {
mActiveOnItemTouchListener.onTouchEvent(this, e);
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
// Clean up for the next gesture.
mActiveOnItemTouchListener = null;
}
return true;
}
}
// Listeners will have already received the ACTION_DOWN via dispatchOnItemTouchIntercept
// as called from onInterceptTouchEvent; skip it.
if (action != MotionEvent.ACTION_DOWN) {
final int listenerCount = mOnItemTouchListeners.size();
for (int i = 0; i < listenerCount; i++) {
final OnItemTouchListener listener = mOnItemTouchListeners.get(i);
if (listener.onInterceptTouchEvent(this, e)) {
mActiveOnItemTouchListener = listener;
return true;
}
}
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if (dispatchOnItemTouchIntercept(e)) {
cancelTouch();
return true;
}
final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
final boolean canScrollVertically = mLayout.canScrollVertically();
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(e);
final int action = MotionEventCompat.getActionMasked(e);
final int actionIndex = MotionEventCompat.getActionIndex(e);
switch (action) {
case MotionEvent.ACTION_DOWN:
mScrollPointerId = MotionEventCompat.getPointerId(e, 0);
mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);
if (mScrollState == SCROLL_STATE_SETTLING) {
getParent().requestDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN:
mScrollPointerId = MotionEventCompat.getPointerId(e, actionIndex);
mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, actionIndex) + 0.5f);
mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, actionIndex) + 0.5f);
break;
case MotionEvent.ACTION_MOVE: {
final int index = MotionEventCompat.findPointerIndex(e, mScrollPointerId);
if (index < 0) {
Log.e(TAG, "Error processing scroll; pointer index for id " +
mScrollPointerId + " not found. Did any MotionEvents get skipped?");
return false;
}
final int x = (int) (MotionEventCompat.getX(e, index) + 0.5f);
final int y = (int) (MotionEventCompat.getY(e, index) + 0.5f);
if (mScrollState != SCROLL_STATE_DRAGGING) {
final int dx = x - mInitialTouchX;
final int dy = y - mInitialTouchY;
boolean startScroll = false;
if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) {
mLastTouchX = mInitialTouchX + mTouchSlop * (dx < 0 ? -1 : 1);
startScroll = true;
}
if (canScrollVertically && Math.abs(dy) > mTouchSlop) {
mLastTouchY = mInitialTouchY + mTouchSlop * (dy < 0 ? -1 : 1);
startScroll = true;
}
if (startScroll) {
setScrollState(SCROLL_STATE_DRAGGING);
}
}
} break;
case MotionEventCompat.ACTION_POINTER_UP: {
onPointerUp(e);
} break;
case MotionEvent.ACTION_UP: {
mVelocityTracker.clear();
} break;
case MotionEvent.ACTION_CANCEL: {
cancelTouch();
}
}
return mScrollState == SCROLL_STATE_DRAGGING;
}
@Override
public boolean onTouchEvent(MotionEvent e) {
if (dispatchOnItemTouch(e)) {
cancelTouch();
return true;
}
final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
final boolean canScrollVertically = mLayout.canScrollVertically();
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(e);
final int action = MotionEventCompat.getActionMasked(e);
final int actionIndex = MotionEventCompat.getActionIndex(e);
switch (action) {
case MotionEvent.ACTION_DOWN: {
mScrollPointerId = MotionEventCompat.getPointerId(e, 0);
mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);
} break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
mScrollPointerId = MotionEventCompat.getPointerId(e, actionIndex);
mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, actionIndex) + 0.5f);
mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, actionIndex) + 0.5f);
} break;
case MotionEvent.ACTION_MOVE: {
final int index = MotionEventCompat.findPointerIndex(e, mScrollPointerId);
if (index < 0) {
Log.e(TAG, "Error processing scroll; pointer index for id " +
mScrollPointerId + " not found. Did any MotionEvents get skipped?");
return false;
}
final int x = (int) (MotionEventCompat.getX(e, index) + 0.5f);
final int y = (int) (MotionEventCompat.getY(e, index) + 0.5f);
if (mScrollState != SCROLL_STATE_DRAGGING) {
final int dx = x - mInitialTouchX;
final int dy = y - mInitialTouchY;
boolean startScroll = false;
if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) {
mLastTouchX = mInitialTouchX + mTouchSlop * (dx < 0 ? -1 : 1);
startScroll = true;
}
if (canScrollVertically && Math.abs(dy) > mTouchSlop) {
mLastTouchY = mInitialTouchY + mTouchSlop * (dy < 0 ? -1 : 1);
startScroll = true;
}
if (startScroll) {
setScrollState(SCROLL_STATE_DRAGGING);
}
}
if (mScrollState == SCROLL_STATE_DRAGGING) {
final int dx = x - mLastTouchX;
final int dy = y - mLastTouchY;
if (scrollByInternal(
canScrollHorizontally ? -dx : 0, canScrollVertically ? -dy : 0)) {
getParent().requestDisallowInterceptTouchEvent(true);
}
}
mLastTouchX = x;
mLastTouchY = y;
} break;
case MotionEventCompat.ACTION_POINTER_UP: {
onPointerUp(e);
} break;
case MotionEvent.ACTION_UP: {
mVelocityTracker.computeCurrentVelocity(1000, mMaxFlingVelocity);
final float xvel = canScrollHorizontally ?
-VelocityTrackerCompat.getXVelocity(mVelocityTracker, mScrollPointerId) : 0;
final float yvel = canScrollVertically ?
-VelocityTrackerCompat.getYVelocity(mVelocityTracker, mScrollPointerId) : 0;
if (!((xvel != 0 || yvel != 0) && fling((int) xvel, (int) yvel))) {
setScrollState(SCROLL_STATE_IDLE);
}
mVelocityTracker.clear();
releaseGlows();
} break;
case MotionEvent.ACTION_CANCEL: {
cancelTouch();
} break;
}
return true;
}
private void cancelTouch() {
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
releaseGlows();
setScrollState(SCROLL_STATE_IDLE);
}
private void onPointerUp(MotionEvent e) {
final int actionIndex = MotionEventCompat.getActionIndex(e);
if (MotionEventCompat.getPointerId(e, actionIndex) == mScrollPointerId) {
// Pick a new pointer to pick up the slack.
final int newIndex = actionIndex == 0 ? 1 : 0;
mScrollPointerId = MotionEventCompat.getPointerId(e, newIndex);
mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, newIndex) + 0.5f);
mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, newIndex) + 0.5f);
}
}
// @Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (mLayout == null) {
return false;
}
if ((MotionEventCompat.getSource(event) & InputDeviceCompat.SOURCE_CLASS_POINTER) != 0) {
if (event.getAction() == MotionEventCompat.ACTION_SCROLL) {
final float vScroll, hScroll;
if (mLayout.canScrollVertically()) {
vScroll = MotionEventCompat
.getAxisValue(event, MotionEventCompat.AXIS_VSCROLL);
} else {
vScroll = 0f;
}
if (mLayout.canScrollHorizontally()) {
hScroll = MotionEventCompat
.getAxisValue(event, MotionEventCompat.AXIS_HSCROLL);
} else {
hScroll = 0f;
}
if (vScroll != 0 || hScroll != 0) {
final float scrollFactor = getScrollFactor();
scrollBy((int) (hScroll * scrollFactor), (int) (vScroll * scrollFactor));
}
}
}
return false;
}
/**
* Ported from View.getVerticalScrollFactor.
*/
private float getScrollFactor() {
if (mScrollFactor == Float.MIN_VALUE) {
TypedValue outValue = new TypedValue();
if (getContext().getTheme().resolveAttribute(
android.R.attr.listPreferredItemHeight, outValue, true)) {
mScrollFactor = outValue.getDimension(
getContext().getResources().getDisplayMetrics());
} else {
return 0; //listPreferredItemHeight is not defined, no generic scrolling
}
}
return mScrollFactor;
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
if (mAdapterUpdateDuringMeasure) {
eatRequestLayout();
processAdapterUpdatesAndSetAnimationFlags();
if (mState.mRunPredictiveAnimations) {
// TODO: try to provide a better approach.
// When RV decides to run predictive animations, we need to measure in pre-layout
// state so that pre-layout pass results in correct layout.
// On the other hand, this will prevent the layout manager from resizing properly.
mState.mInPreLayout = true;
} else {
// consume remaining updates to provide a consistent state with the layout pass.
mAdapterHelper.consumeUpdatesInOnePass();
mState.mInPreLayout = false;
}
mAdapterUpdateDuringMeasure = false;
resumeRequestLayout(false);
}
if (mAdapter != null) {
mState.mItemCount = mAdapter.getItemCount();
} else {
mState.mItemCount = 0;
}
if (mLayout == null) {
defaultOnMeasure(widthSpec, heightSpec);
} else {
mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);
}
mState.mInPreLayout = false; // clear
}
/**
* Used when onMeasure is called before layout manager is set
*/
private void defaultOnMeasure(int widthSpec, int heightSpec) {
final int widthMode = MeasureSpec.getMode(widthSpec);
final int heightMode = MeasureSpec.getMode(heightSpec);
final int widthSize = MeasureSpec.getSize(widthSpec);
final int heightSize = MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
switch (widthMode) {
case MeasureSpec.EXACTLY:
case MeasureSpec.AT_MOST:
width = widthSize;
break;
case MeasureSpec.UNSPECIFIED:
default:
width = ViewCompat.getMinimumWidth(this);
break;
}
switch (heightMode) {
case MeasureSpec.EXACTLY:
case MeasureSpec.AT_MOST:
height = heightSize;
break;
case MeasureSpec.UNSPECIFIED:
default:
height = ViewCompat.getMinimumHeight(this);
break;
}
setMeasuredDimension(width, height);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (w != oldw || h != oldh) {
invalidateGlows();
}
}
/**
* Sets the {@link ItemAnimator} that will handle animations involving changes
* to the items in this RecyclerView. By default, RecyclerView instantiates and
* uses an instance of {@link DefaultItemAnimator}. Whether item animations are
* enabled for the RecyclerView depends on the ItemAnimator and whether
* the LayoutManager {@link LayoutManager#supportsPredictiveItemAnimations()
* supports item animations}.
*
* @param animator The ItemAnimator being set. If null, no animations will occur
* when changes occur to the items in this RecyclerView.
*/
public void setItemAnimator(ItemAnimator animator) {
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
mItemAnimator.setListener(null);
}
mItemAnimator = animator;
if (mItemAnimator != null) {
mItemAnimator.setListener(mItemAnimatorListener);
}
}
/**
* Gets the current ItemAnimator for this RecyclerView. A null return value
* indicates that there is no animator and that item changes will happen without
* any animations. By default, RecyclerView instantiates and
* uses an instance of {@link DefaultItemAnimator}.
*
* @return ItemAnimator The current ItemAnimator. If null, no animations will occur
* when changes occur to the items in this RecyclerView.
*/
public ItemAnimator getItemAnimator() {
return mItemAnimator;
}
private boolean supportsChangeAnimations() {
return mItemAnimator != null && mItemAnimator.getSupportsChangeAnimations();
}
/**
* Post a runnable to the next frame to run pending item animations. Only the first such
* request will be posted, governed by the mPostedAnimatorRunner flag.
*/
private void postAnimationRunner() {
if (!mPostedAnimatorRunner && mIsAttached) {
ViewCompat.postOnAnimation(this, mItemAnimatorRunner);
mPostedAnimatorRunner = true;
}
}
private boolean predictiveItemAnimationsEnabled() {
return (mItemAnimator != null && mLayout.supportsPredictiveItemAnimations());
}
/**
* Consumes adapter updates and calculates which type of animations we want to run.
* Called in onMeasure and dispatchLayout.
* <p>
* This method may process only the pre-layout state of updates or all of them.
*/
private void processAdapterUpdatesAndSetAnimationFlags() {
if (mDataSetHasChangedAfterLayout) {
// Processing these items have no value since data set changed unexpectedly.
// Instead, we just reset it.
mAdapterHelper.reset();
markKnownViewsInvalid();
mLayout.onItemsChanged(this);
}
// simple animations are a subset of advanced animations (which will cause a
// pre-layout step)
// If layout supports predictive animations, pre-process to decide if we want to run them
if (mItemAnimator != null && mLayout.supportsPredictiveItemAnimations()) {
mAdapterHelper.preProcess();
} else {
mAdapterHelper.consumeUpdatesInOnePass();
}
boolean animationTypeSupported = (mItemsAddedOrRemoved && !mItemsChanged) ||
(mItemsAddedOrRemoved || (mItemsChanged && supportsChangeAnimations()));
mState.mRunSimpleAnimations = mFirstLayoutComplete && mItemAnimator != null &&
(mDataSetHasChangedAfterLayout || animationTypeSupported ||
mLayout.mRequestedSimpleAnimations) &&
(!mDataSetHasChangedAfterLayout || mAdapter.hasStableIds());
mState.mRunPredictiveAnimations = mState.mRunSimpleAnimations &&
animationTypeSupported && !mDataSetHasChangedAfterLayout &&
predictiveItemAnimationsEnabled();
}
/**
* Wrapper around layoutChildren() that handles animating changes caused by layout.
* Animations work on the assumption that there are five different kinds of items
* in play:
* PERSISTENT: items are visible before and after layout
* REMOVED: items were visible before layout and were removed by the app
* ADDED: items did not exist before layout and were added by the app
* DISAPPEARING: items exist in the data set before/after, but changed from
* visible to non-visible in the process of layout (they were moved off
* screen as a side-effect of other changes)
* APPEARING: items exist in the data set before/after, but changed from
* non-visible to visible in the process of layout (they were moved on
* screen as a side-effect of other changes)
* The overall approach figures out what items exist before/after layout and
* infers one of the five above states for each of the items. Then the animations
* are set up accordingly:
* PERSISTENT views are moved ({@link ItemAnimator#animateMove(ViewHolder, int, int, int, int)})
* REMOVED views are removed ({@link ItemAnimator#animateRemove(ViewHolder)})
* ADDED views are added ({@link ItemAnimator#animateAdd(ViewHolder)})
* DISAPPEARING views are moved off screen
* APPEARING views are moved on screen
*/
void dispatchLayout() {
if (mAdapter == null) {
Log.e(TAG, "No adapter attached; skipping layout");
return;
}
if (mLayout == null) {
Log.e(TAG, "No layout manager attached; skipping layout");
return;
}
mDisappearingViewsInLayoutPass.clear();
eatRequestLayout();
mRunningLayoutOrScroll = true;
processAdapterUpdatesAndSetAnimationFlags();
mState.mOldChangedHolders = mState.mRunSimpleAnimations && mItemsChanged
&& supportsChangeAnimations() ? new ArrayMap<Long, ViewHolder>() : null;
mItemsAddedOrRemoved = mItemsChanged = false;
ArrayMap<View, Rect> appearingViewInitialBounds = null;
mState.mInPreLayout = mState.mRunPredictiveAnimations;
mState.mItemCount = mAdapter.getItemCount();
findMinMaxChildLayoutPositions(mMinMaxLayoutPositions);
if (mState.mRunSimpleAnimations) {
// Step 0: Find out where all non-removed items are, pre-layout
mState.mPreLayoutHolderMap.clear();
mState.mPostLayoutHolderMap.clear();
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.shouldIgnore() || (holder.isInvalid() && !mAdapter.hasStableIds())) {
continue;
}
final View view = holder.itemView;
mState.mPreLayoutHolderMap.put(holder, new ItemHolderInfo(holder,
view.getLeft(), view.getTop(), view.getRight(), view.getBottom()));
}
}
if (mState.mRunPredictiveAnimations) {
// Step 1: run prelayout: This will use the old positions of items. The layout manager
// is expected to layout everything, even removed items (though not to add removed
// items back to the container). This gives the pre-layout position of APPEARING views
// which come into existence as part of the real layout.
// Save old positions so that LayoutManager can run its mapping logic.
saveOldPositions();
// processAdapterUpdatesAndSetAnimationFlags already run pre-layout animations.
if (mState.mOldChangedHolders != null) {
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.isChanged() && !holder.isRemoved() && !holder.shouldIgnore()) {
long key = getChangedHolderKey(holder);
mState.mOldChangedHolders.put(key, holder);
mState.mPreLayoutHolderMap.remove(holder);
}
}
}
final boolean didStructureChange = mState.mStructureChanged;
mState.mStructureChanged = false;
// temporarily disable flag because we are asking for previous layout
mLayout.onLayoutChildren(mRecycler, mState);
mState.mStructureChanged = didStructureChange;
appearingViewInitialBounds = new ArrayMap<View, Rect>();
for (int i = 0; i < mChildHelper.getChildCount(); ++i) {
boolean found = false;
View child = mChildHelper.getChildAt(i);
if (getChildViewHolderInt(child).shouldIgnore()) {
continue;
}
for (int j = 0; j < mState.mPreLayoutHolderMap.size(); ++j) {
ViewHolder holder = mState.mPreLayoutHolderMap.keyAt(j);
if (holder.itemView == child) {
found = true;
break;
}
}
if (!found) {
appearingViewInitialBounds.put(child, new Rect(child.getLeft(), child.getTop(),
child.getRight(), child.getBottom()));
}
}
// we don't process disappearing list because they may re-appear in post layout pass.
clearOldPositions();
mAdapterHelper.consumePostponedUpdates();
} else {
clearOldPositions();
// in case pre layout did run but we decided not to run predictive animations.
mAdapterHelper.consumeUpdatesInOnePass();
if (mState.mOldChangedHolders != null) {
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.isChanged() && !holder.isRemoved() && !holder.shouldIgnore()) {
long key = getChangedHolderKey(holder);
mState.mOldChangedHolders.put(key, holder);
mState.mPreLayoutHolderMap.remove(holder);
}
}
}
}
mState.mItemCount = mAdapter.getItemCount();
mState.mDeletedInvisibleItemCountSincePreviousLayout = 0;
// Step 2: Run layout
mState.mInPreLayout = false;
mLayout.onLayoutChildren(mRecycler, mState);
mState.mStructureChanged = false;
mPendingSavedState = null;
// onLayoutChildren may have caused client code to disable item animations; re-check
mState.mRunSimpleAnimations = mState.mRunSimpleAnimations && mItemAnimator != null;
if (mState.mRunSimpleAnimations) {
// Step 3: Find out where things are now, post-layout
ArrayMap<Long, ViewHolder> newChangedHolders = mState.mOldChangedHolders != null ?
new ArrayMap<Long, ViewHolder>() : null;
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; ++i) {
ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.shouldIgnore()) {
continue;
}
final View view = holder.itemView;
long key = getChangedHolderKey(holder);
if (newChangedHolders != null && mState.mOldChangedHolders.get(key) != null) {
newChangedHolders.put(key, holder);
} else {
mState.mPostLayoutHolderMap.put(holder, new ItemHolderInfo(holder,
view.getLeft(), view.getTop(), view.getRight(), view.getBottom()));
}
}
processDisappearingList(appearingViewInitialBounds);
// Step 4: Animate DISAPPEARING and REMOVED items
int preLayoutCount = mState.mPreLayoutHolderMap.size();
for (int i = preLayoutCount - 1; i >= 0; i--) {
ViewHolder itemHolder = mState.mPreLayoutHolderMap.keyAt(i);
if (!mState.mPostLayoutHolderMap.containsKey(itemHolder)) {
ItemHolderInfo disappearingItem = mState.mPreLayoutHolderMap.valueAt(i);
mState.mPreLayoutHolderMap.removeAt(i);
View disappearingItemView = disappearingItem.holder.itemView;
mRecycler.unscrapView(disappearingItem.holder);
animateDisappearance(disappearingItem);
}
}
// Step 5: Animate APPEARING and ADDED items
int postLayoutCount = mState.mPostLayoutHolderMap.size();
if (postLayoutCount > 0) {
for (int i = postLayoutCount - 1; i >= 0; i--) {
ViewHolder itemHolder = mState.mPostLayoutHolderMap.keyAt(i);
ItemHolderInfo info = mState.mPostLayoutHolderMap.valueAt(i);
if ((mState.mPreLayoutHolderMap.isEmpty() ||
!mState.mPreLayoutHolderMap.containsKey(itemHolder))) {
mState.mPostLayoutHolderMap.removeAt(i);
Rect initialBounds = (appearingViewInitialBounds != null) ?
appearingViewInitialBounds.get(itemHolder.itemView) : null;
animateAppearance(itemHolder, initialBounds,
info.left, info.top);
}
}
}
// Step 6: Animate PERSISTENT items
count = mState.mPostLayoutHolderMap.size();
for (int i = 0; i < count; ++i) {
ViewHolder postHolder = mState.mPostLayoutHolderMap.keyAt(i);
ItemHolderInfo postInfo = mState.mPostLayoutHolderMap.valueAt(i);
ItemHolderInfo preInfo = mState.mPreLayoutHolderMap.get(postHolder);
if (preInfo != null && postInfo != null) {
if (preInfo.left != postInfo.left || preInfo.top != postInfo.top) {
postHolder.setIsRecyclable(false);
if (DEBUG) {
Log.d(TAG, "PERSISTENT: " + postHolder +
" with view " + postHolder.itemView);
}
if (mItemAnimator.animateMove(postHolder,
preInfo.left, preInfo.top, postInfo.left, postInfo.top)) {
postAnimationRunner();
}
}
}
}
// Step 7: Animate CHANGING items
count = mState.mOldChangedHolders != null ? mState.mOldChangedHolders.size() : 0;
// traverse reverse in case view gets recycled while we are traversing the list.
for (int i = count - 1; i >= 0; i--) {
long key = mState.mOldChangedHolders.keyAt(i);
ViewHolder oldHolder = mState.mOldChangedHolders.get(key);
View oldView = oldHolder.itemView;
if (oldHolder.shouldIgnore()) {
continue;
}
// We probably don't need this check anymore since these views are removed from
// the list if they are recycled.
if (mRecycler.mChangedScrap != null &&
mRecycler.mChangedScrap.contains(oldHolder)) {
animateChange(oldHolder, newChangedHolders.get(key));
} else if (DEBUG) {
Log.e(TAG, "cannot find old changed holder in changed scrap :/" + oldHolder);
}
}
}
resumeRequestLayout(false);
mLayout.removeAndRecycleScrapInt(mRecycler);
mState.mPreviousLayoutItemCount = mState.mItemCount;
mDataSetHasChangedAfterLayout = false;
mState.mRunSimpleAnimations = false;
mState.mRunPredictiveAnimations = false;
mRunningLayoutOrScroll = false;
mLayout.mRequestedSimpleAnimations = false;
if (mRecycler.mChangedScrap != null) {
mRecycler.mChangedScrap.clear();
}
mState.mOldChangedHolders = null;
if (didChildRangeChange(mMinMaxLayoutPositions[0], mMinMaxLayoutPositions[1])) {
notifyOnScrolled(0, 0);
}
}
private void findMinMaxChildLayoutPositions(int[] into) {
final int count = mChildHelper.getChildCount();
if (count == 0) {
into[0] = 0;
into[1] = 0;
return;
}
int minPositionPreLayout = Integer.MAX_VALUE;
int maxPositionPreLayout = Integer.MIN_VALUE;
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.shouldIgnore()) {
continue;
}
final int pos = holder.getLayoutPosition();
if (pos < minPositionPreLayout) {
minPositionPreLayout = pos;
}
if (pos > maxPositionPreLayout) {
maxPositionPreLayout = pos;
}
}
into[0] = minPositionPreLayout;
into[1] = maxPositionPreLayout;
}
private boolean didChildRangeChange(int minPositionPreLayout, int maxPositionPreLayout) {
int count = mChildHelper.getChildCount();
if (count == 0) {
return minPositionPreLayout != 0 || maxPositionPreLayout != 0;
}
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
if (holder.shouldIgnore()) {
continue;
}
final int pos = holder.getLayoutPosition();
if (pos < minPositionPreLayout || pos > maxPositionPreLayout) {
return true;
}
}
return false;
}
@Override
protected void removeDetachedView(View child, boolean animate) {
ViewHolder vh = getChildViewHolderInt(child);
if (vh != null) {
if (vh.isTmpDetached()) {
vh.clearTmpDetachFlag();
} else if (!vh.shouldIgnore()) {
throw new IllegalArgumentException("Called removeDetachedView with a view which"
+ " is not flagged as tmp detached." + vh);
}
}
dispatchChildDetached(child);
super.removeDetachedView(child, animate);
}
/**
* Returns a unique key to be used while handling change animations.
* It might be child's position or stable id depending on the adapter type.
*/
long getChangedHolderKey(ViewHolder holder) {
return mAdapter.hasStableIds() ? holder.getItemId() : holder.mPosition;
}
/**
* A LayoutManager may want to layout a view just to animate disappearance.
* This method handles those views and triggers remove animation on them.
*/
private void processDisappearingList(ArrayMap<View, Rect> appearingViews) {
final int count = mDisappearingViewsInLayoutPass.size();
for (int i = 0; i < count; i ++) {
View view = mDisappearingViewsInLayoutPass.get(i);
ViewHolder vh = getChildViewHolderInt(view);
final ItemHolderInfo info = mState.mPreLayoutHolderMap.remove(vh);
if (!mState.isPreLayout()) {
mState.mPostLayoutHolderMap.remove(vh);
}
if (appearingViews.remove(view) != null) {
mLayout.removeAndRecycleView(view, mRecycler);
continue;
}
if (info != null) {
animateDisappearance(info);
} else {
// let it disappear from the position it becomes visible
animateDisappearance(new ItemHolderInfo(vh, view.getLeft(), view.getTop(),
view.getRight(), view.getBottom()));
}
}
mDisappearingViewsInLayoutPass.clear();
}
private void animateAppearance(ViewHolder itemHolder, Rect beforeBounds, int afterLeft,
int afterTop) {
View newItemView = itemHolder.itemView;
if (beforeBounds != null &&
(beforeBounds.left != afterLeft || beforeBounds.top != afterTop)) {
// slide items in if before/after locations differ
itemHolder.setIsRecyclable(false);
if (DEBUG) {
Log.d(TAG, "APPEARING: " + itemHolder + " with view " + newItemView);
}
if (mItemAnimator.animateMove(itemHolder,
beforeBounds.left, beforeBounds.top,
afterLeft, afterTop)) {
postAnimationRunner();
}
} else {
if (DEBUG) {
Log.d(TAG, "ADDED: " + itemHolder + " with view " + newItemView);
}
itemHolder.setIsRecyclable(false);
if (mItemAnimator.animateAdd(itemHolder)) {
postAnimationRunner();
}
}
}
private void animateDisappearance(ItemHolderInfo disappearingItem) {
View disappearingItemView = disappearingItem.holder.itemView;
addAnimatingView(disappearingItem.holder);
int oldLeft = disappearingItem.left;
int oldTop = disappearingItem.top;
int newLeft = disappearingItemView.getLeft();
int newTop = disappearingItemView.getTop();
if (oldLeft != newLeft || oldTop != newTop) {
disappearingItem.holder.setIsRecyclable(false);
disappearingItemView.layout(newLeft, newTop,
newLeft + disappearingItemView.getWidth(),
newTop + disappearingItemView.getHeight());
if (DEBUG) {
Log.d(TAG, "DISAPPEARING: " + disappearingItem.holder +
" with view " + disappearingItemView);
}
if (mItemAnimator.animateMove(disappearingItem.holder, oldLeft, oldTop,
newLeft, newTop)) {
postAnimationRunner();
}
} else {
if (DEBUG) {
Log.d(TAG, "REMOVED: " + disappearingItem.holder +
" with view " + disappearingItemView);
}
disappearingItem.holder.setIsRecyclable(false);
if (mItemAnimator.animateRemove(disappearingItem.holder)) {
postAnimationRunner();
}
}
}
private void animateChange(ViewHolder oldHolder, ViewHolder newHolder) {
oldHolder.setIsRecyclable(false);
addAnimatingView(oldHolder);
oldHolder.mShadowedHolder = newHolder;
mRecycler.unscrapView(oldHolder);
if (DEBUG) {
Log.d(TAG, "CHANGED: " + oldHolder + " with view " + oldHolder.itemView);
}
final int fromLeft = oldHolder.itemView.getLeft();
final int fromTop = oldHolder.itemView.getTop();
final int toLeft, toTop;
if (newHolder == null || newHolder.shouldIgnore()) {
toLeft = fromLeft;
toTop = fromTop;
} else {
toLeft = newHolder.itemView.getLeft();
toTop = newHolder.itemView.getTop();
newHolder.setIsRecyclable(false);
newHolder.mShadowingHolder = oldHolder;
}
if(mItemAnimator.animateChange(oldHolder, newHolder,
fromLeft, fromTop, toLeft, toTop)) {
postAnimationRunner();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
eatRequestLayout();
dispatchLayout();
resumeRequestLayout(false);
mFirstLayoutComplete = true;
}
@Override
public void requestLayout() {
if (!mEatRequestLayout) {
super.requestLayout();
} else {
mLayoutRequestEaten = true;
}
}
void markItemDecorInsetsDirty() {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final View child = mChildHelper.getUnfilteredChildAt(i);
((LayoutParams) child.getLayoutParams()).mInsetsDirty = true;
}
mRecycler.markItemDecorInsetsDirty();
}
@Override
public void draw(Canvas c) {
super.draw(c);
final int count = mItemDecorations.size();
for (int i = 0; i < count; i++) {
mItemDecorations.get(i).onDrawOver(c, this, mState);
}
// TODO If padding is not 0 and chilChildrenToPadding is false, to draw glows properly, we
// need find children closest to edges. Not sure if it is worth the effort.
boolean needsInvalidate = false;
if (mLeftGlow != null && !mLeftGlow.isFinished()) {
final int restore = c.save();
final int padding = mClipToPadding ? getPaddingBottom() : 0;
c.rotate(270);
c.translate(-getHeight() + padding, 0);
needsInvalidate = mLeftGlow != null && mLeftGlow.draw(c);
c.restoreToCount(restore);
}
if (mTopGlow != null && !mTopGlow.isFinished()) {
final int restore = c.save();
if (mClipToPadding) {
c.translate(getPaddingLeft(), getPaddingTop());
}
needsInvalidate |= mTopGlow != null && mTopGlow.draw(c);
c.restoreToCount(restore);
}
if (mRightGlow != null && !mRightGlow.isFinished()) {
final int restore = c.save();
final int width = getWidth();
final int padding = mClipToPadding ? getPaddingTop() : 0;
c.rotate(90);
c.translate(-padding, -width);
needsInvalidate |= mRightGlow != null && mRightGlow.draw(c);
c.restoreToCount(restore);
}
if (mBottomGlow != null && !mBottomGlow.isFinished()) {
final int restore = c.save();
c.rotate(180);
if (mClipToPadding) {
c.translate(-getWidth() + getPaddingRight(), -getHeight() + getPaddingBottom());
} else {
c.translate(-getWidth(), -getHeight());
}
needsInvalidate |= mBottomGlow != null && mBottomGlow.draw(c);
c.restoreToCount(restore);
}
// If some views are animating, ItemDecorators are likely to move/change with them.
// Invalidate RecyclerView to re-draw decorators. This is still efficient because children's
// display lists are not invalidated.
if (!needsInvalidate && mItemAnimator != null && mItemDecorations.size() > 0 &&
mItemAnimator.isRunning()) {
needsInvalidate = true;
}
if (needsInvalidate) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
public void onDraw(Canvas c) {
super.onDraw(c);
final int count = mItemDecorations.size();
for (int i = 0; i < count; i++) {
mItemDecorations.get(i).onDraw(c, this, mState);
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && mLayout.checkLayoutParams((LayoutParams) p);
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
if (mLayout == null) {
throw new IllegalStateException("RecyclerView has no LayoutManager");
}
return mLayout.generateDefaultLayoutParams();
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
if (mLayout == null) {
throw new IllegalStateException("RecyclerView has no LayoutManager");
}
return mLayout.generateLayoutParams(getContext(), attrs);
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
if (mLayout == null) {
throw new IllegalStateException("RecyclerView has no LayoutManager");
}
return mLayout.generateLayoutParams(p);
}
void saveOldPositions() {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (DEBUG && holder.mPosition == -1 && !holder.isRemoved()) {
throw new IllegalStateException("view holder cannot have position -1 unless it"
+ " is removed");
}
if (!holder.shouldIgnore()) {
holder.saveOldPosition();
}
}
}
void clearOldPositions() {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (!holder.shouldIgnore()) {
holder.clearOldPosition();
}
}
mRecycler.clearOldPositions();
}
void offsetPositionRecordsForMove(int from, int to) {
final int childCount = mChildHelper.getUnfilteredChildCount();
final int start, end, inBetweenOffset;
if (from < to) {
start = from;
end = to;
inBetweenOffset = -1;
} else {
start = to;
end = from;
inBetweenOffset = 1;
}
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder == null || holder.mPosition < start || holder.mPosition > end) {
continue;
}
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForMove attached child " + i + " holder " +
holder);
}
if (holder.mPosition == from) {
holder.offsetPosition(to - from, false);
} else {
holder.offsetPosition(inBetweenOffset, false);
}
mState.mStructureChanged = true;
}
mRecycler.offsetPositionRecordsForMove(from, to);
requestLayout();
}
void offsetPositionRecordsForInsert(int positionStart, int itemCount) {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.shouldIgnore() && holder.mPosition >= positionStart) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForInsert attached child " + i + " holder " +
holder + " now at position " + (holder.mPosition + itemCount));
}
holder.offsetPosition(itemCount, false);
mState.mStructureChanged = true;
}
}
mRecycler.offsetPositionRecordsForInsert(positionStart, itemCount);
requestLayout();
}
void offsetPositionRecordsForRemove(int positionStart, int itemCount,
boolean applyToPreLayout) {
final int positionEnd = positionStart + itemCount;
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.shouldIgnore()) {
if (holder.mPosition >= positionEnd) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i +
" holder " + holder + " now at position " +
(holder.mPosition - itemCount));
}
holder.offsetPosition(-itemCount, applyToPreLayout);
mState.mStructureChanged = true;
} else if (holder.mPosition >= positionStart) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i +
" holder " + holder + " now REMOVED");
}
holder.flagRemovedAndOffsetPosition(positionStart - 1, -itemCount,
applyToPreLayout);
mState.mStructureChanged = true;
}
}
}
mRecycler.offsetPositionRecordsForRemove(positionStart, itemCount, applyToPreLayout);
requestLayout();
}
/**
* Rebind existing views for the given range, or create as needed.
*
* @param positionStart Adapter position to start at
* @param itemCount Number of views that must explicitly be rebound
*/
void viewRangeUpdate(int positionStart, int itemCount) {
final int childCount = mChildHelper.getUnfilteredChildCount();
final int positionEnd = positionStart + itemCount;
for (int i = 0; i < childCount; i++) {
final View child = mChildHelper.getUnfilteredChildAt(i);
final ViewHolder holder = getChildViewHolderInt(child);
if (holder == null || holder.shouldIgnore()) {
continue;
}
if (holder.mPosition >= positionStart && holder.mPosition < positionEnd) {
// We re-bind these view holders after pre-processing is complete so that
// ViewHolders have their final positions assigned.
holder.addFlags(ViewHolder.FLAG_UPDATE);
if (supportsChangeAnimations()) {
holder.addFlags(ViewHolder.FLAG_CHANGED);
}
// lp cannot be null since we get ViewHolder from it.
((LayoutParams) child.getLayoutParams()).mInsetsDirty = true;
}
}
mRecycler.viewRangeUpdate(positionStart, itemCount);
}
void rebindUpdatedViewHolders() {
final int childCount = mChildHelper.getChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
// validate type is correct
if (holder == null || holder.shouldIgnore()) {
continue;
}
if (holder.isRemoved() || holder.isInvalid()) {
requestLayout();
} else if (holder.needsUpdate()) {
final int type = mAdapter.getItemViewType(holder.mPosition);
if (holder.getItemViewType() == type) {
// Binding an attached view will request a layout if needed.
if (!holder.isChanged() || !supportsChangeAnimations()) {
mAdapter.bindViewHolder(holder, holder.mPosition);
} else {
// Don't rebind changed holders if change animations are enabled.
// We want the old contents for the animation and will get a new
// holder for the new contents.
requestLayout();
}
} else {
// binding to a new view will need re-layout anyways. We can as well trigger
// it here so that it happens during layout
requestLayout();
break;
}
}
}
}
private void setDataSetChangedAfterLayout() {
if (mDataSetHasChangedAfterLayout) {
return;
}
mDataSetHasChangedAfterLayout = true;
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.shouldIgnore()) {
holder.addFlags(ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN);
}
}
mRecycler.setAdapterPositionsAsUnknown();
}
/**
* Mark all known views as invalid. Used in response to a, "the whole world might have changed"
* data change event.
*/
void markKnownViewsInvalid() {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.shouldIgnore()) {
holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID);
}
}
markItemDecorInsetsDirty();
mRecycler.markKnownViewsInvalid();
}
/**
* Invalidates all ItemDecorations. If RecyclerView has item decorations, calling this method
* will trigger a {@link #requestLayout()} call.
*/
public void invalidateItemDecorations() {
if (mItemDecorations.size() == 0) {
return;
}
if (mLayout != null) {
mLayout.assertNotInLayoutOrScroll("Cannot invalidate item decorations during a scroll"
+ " or layout");
}
markItemDecorInsetsDirty();
requestLayout();
}
/**
* Retrieve the {@link ViewHolder} for the given child view.
*
* @param child Child of this RecyclerView to query for its ViewHolder
* @return The child view's ViewHolder
*/
public ViewHolder getChildViewHolder(View child) {
final ViewParent parent = child.getParent();
if (parent != null && parent != this) {
throw new IllegalArgumentException("View " + child + " is not a direct child of " +
this);
}
return getChildViewHolderInt(child);
}
static ViewHolder getChildViewHolderInt(View child) {
if (child == null) {
return null;
}
return ((LayoutParams) child.getLayoutParams()).mViewHolder;
}
/**
* @deprecated use {@link #getChildAdapterPosition(View)} or
* {@link #getChildLayoutPosition(View)}.
*/
@Deprecated
public int getChildPosition(View child) {
return getChildAdapterPosition(child);
}
/**
* Return the adapter position that the given child view corresponds to.
*
* @param child Child View to query
* @return Adapter position corresponding to the given view or {@link #NO_POSITION}
*/
public int getChildAdapterPosition(View child) {
final ViewHolder holder = getChildViewHolderInt(child);
return holder != null ? holder.getAdapterPosition() : NO_POSITION;
}
/**
* Return the adapter position of the given child view as of the latest completed layout pass.
* <p>
* This position may not be equal to Item's adapter position if there are pending changes
* in the adapter which have not been reflected to the layout yet.
*
* @param child Child View to query
* @return Adapter position of the given View as of last layout pass or {@link #NO_POSITION} if
* the View is representing a removed item.
*/
public int getChildLayoutPosition(View child) {
final ViewHolder holder = getChildViewHolderInt(child);
return holder != null ? holder.getLayoutPosition() : NO_POSITION;
}
/**
* Return the stable item id that the given child view corresponds to.
*
* @param child Child View to query
* @return Item id corresponding to the given view or {@link #NO_ID}
*/
public long getChildItemId(View child) {
if (mAdapter == null || !mAdapter.hasStableIds()) {
return NO_ID;
}
final ViewHolder holder = getChildViewHolderInt(child);
return holder != null ? holder.getItemId() : NO_ID;
}
/**
* @deprecated use {@link #findViewHolderForLayoutPosition(int)} or
* {@link #findViewHolderForAdapterPosition(int)}
*/
@Deprecated
public ViewHolder findViewHolderForPosition(int position) {
return findViewHolderForPosition(position, false);
}
/**
* Return the ViewHolder for the item in the given position of the data set as of the latest
* layout pass.
* <p>
* This method checks only the children of RecyclerView. If the item at the given
* <code>position</code> is not laid out, it <em>will not</em> create a new one.
* <p>
* Note that when Adapter contents change, ViewHolder positions are not updated until the
* next layout calculation. If there are pending adapter updates, the return value of this
* method may not match your adapter contents. You can use
* #{@link ViewHolder#getAdapterPosition()} to get the current adapter position of a ViewHolder.
*
* @param position The position of the item in the data set of the adapter
* @return The ViewHolder at <code>position</code> or null if there is no such item
*/
public ViewHolder findViewHolderForLayoutPosition(int position) {
return findViewHolderForPosition(position, false);
}
/**
* Return the ViewHolder for the item in the given position of the data set. Unlike
* {@link #findViewHolderForLayoutPosition(int)} this method takes into account any pending
* adapter changes that may not be reflected to the layout yet. On the other hand, if
* {@link Adapter#notifyDataSetChanged()} has been called but the new layout has not been
* calculated yet, this method will return <code>null</code> since the new positions of views
* are unknown until the layout is calculated.
* <p>
* This method checks only the children of RecyclerView. If the item at the given
* <code>position</code> is not laid out, it <em>will not</em> create a new one.
*
* @param position The position of the item in the data set of the adapter
* @return The ViewHolder at <code>position</code> or null if there is no such item
*/
public ViewHolder findViewHolderForAdapterPosition(int position) {
if (mDataSetHasChangedAfterLayout) {
return null;
}
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.isRemoved() && getAdapterPositionFor(holder) == position) {
return holder;
}
}
return null;
}
ViewHolder findViewHolderForPosition(int position, boolean checkNewPosition) {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && !holder.isRemoved()) {
if (checkNewPosition) {
if (holder.mPosition == position) {
return holder;
}
} else if (holder.getLayoutPosition() == position) {
return holder;
}
}
}
// This method should not query cached views. It creates a problem during adapter updates
// when we are dealing with already laid out views. Also, for the public method, it is more
// reasonable to return null if position is not laid out.
return null;
}
/**
* Return the ViewHolder for the item with the given id. The RecyclerView must
* use an Adapter with {@link Adapter#setHasStableIds(boolean) stableIds} to
* return a non-null value.
* <p>
* This method checks only the children of RecyclerView. If the item with the given
* <code>id</code> is not laid out, it <em>will not</em> create a new one.
*
* @param id The id for the requested item
* @return The ViewHolder with the given <code>id</code> or null if there is no such item
*/
public ViewHolder findViewHolderForItemId(long id) {
final int childCount = mChildHelper.getUnfilteredChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
if (holder != null && holder.getItemId() == id) {
return holder;
}
}
// this method should not query cached views. They are not children so they
// should not be returned in this public method
return null;
}
/**
* Find the topmost view under the given point.
*
* @param x Horizontal position in pixels to search
* @param y Vertical position in pixels to search
* @return The child view under (x, y) or null if no matching child is found
*/
public View findChildViewUnder(float x, float y) {
final int count = mChildHelper.getChildCount();
for (int i = count - 1; i >= 0; i--) {
final View child = mChildHelper.getChildAt(i);
final float translationX = ViewCompat.getTranslationX(child);
final float translationY = ViewCompat.getTranslationY(child);
if (x >= child.getLeft() + translationX &&
x <= child.getRight() + translationX &&
y >= child.getTop() + translationY &&
y <= child.getBottom() + translationY) {
return child;
}
}
return null;
}
/**
* Offset the bounds of all child views by <code>dy</code> pixels.
* Useful for implementing simple scrolling in {@link LayoutManager LayoutManagers}.
*
* @param dy Vertical pixel offset to apply to the bounds of all child views
*/
public void offsetChildrenVertical(int dy) {
final int childCount = mChildHelper.getChildCount();
for (int i = 0; i < childCount; i++) {
mChildHelper.getChildAt(i).offsetTopAndBottom(dy);
}
}
/**
* Called when an item view is attached to this RecyclerView.
*
* <p>Subclasses of RecyclerView may want to perform extra bookkeeping or modifications
* of child views as they become attached. This will be called before a
* {@link LayoutManager} measures or lays out the view and is a good time to perform these
* changes.</p>
*
* @param child Child view that is now attached to this RecyclerView and its associated window
*/
public void onChildAttachedToWindow(View child) {
}
/**
* Called when an item view is detached from this RecyclerView.
*
* <p>Subclasses of RecyclerView may want to perform extra bookkeeping or modifications
* of child views as they become detached. This will be called as a
* {@link LayoutManager} fully detaches the child view from the parent and its window.</p>
*
* @param child Child view that is now detached from this RecyclerView and its associated window
*/
public void onChildDetachedFromWindow(View child) {
}
/**
* Offset the bounds of all child views by <code>dx</code> pixels.
* Useful for implementing simple scrolling in {@link LayoutManager LayoutManagers}.
*
* @param dx Horizontal pixel offset to apply to the bounds of all child views
*/
public void offsetChildrenHorizontal(int dx) {
final int childCount = mChildHelper.getChildCount();
for (int i = 0; i < childCount; i++) {
mChildHelper.getChildAt(i).offsetLeftAndRight(dx);
}
}
Rect getItemDecorInsetsForChild(View child) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.mInsetsDirty) {
return lp.mDecorInsets;
}
final Rect insets = lp.mDecorInsets;
insets.set(0, 0, 0, 0);
final int decorCount = mItemDecorations.size();
for (int i = 0; i < decorCount; i++) {
mTempRect.set(0, 0, 0, 0);
mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState);
insets.left += mTempRect.left;
insets.top += mTempRect.top;
insets.right += mTempRect.right;
insets.bottom += mTempRect.bottom;
}
lp.mInsetsDirty = false;
return insets;
}
private class ViewFlinger implements Runnable {
private int mLastFlingX;
private int mLastFlingY;
private ScrollerCompat mScroller;
private Interpolator mInterpolator = sQuinticInterpolator;
// When set to true, postOnAnimation callbacks are delayed until the run method completes
private boolean mEatRunOnAnimationRequest = false;
// Tracks if postAnimationCallback should be re-attached when it is done
private boolean mReSchedulePostAnimationCallback = false;
public ViewFlinger() {
mScroller = ScrollerCompat.create(getContext(), sQuinticInterpolator);
}
@Override
public void run() {
disableRunOnAnimationRequests();
consumePendingUpdateOperations();
// keep a local reference so that if it is changed during onAnimation method, it won't
// cause unexpected behaviors
final ScrollerCompat scroller = mScroller;
final SmoothScroller smoothScroller = mLayout.mSmoothScroller;
if (scroller.computeScrollOffset()) {
final int x = scroller.getCurrX();
final int y = scroller.getCurrY();
final int dx = x - mLastFlingX;
final int dy = y - mLastFlingY;
int hresult = 0;
int vresult = 0;
mLastFlingX = x;
mLastFlingY = y;
int overscrollX = 0, overscrollY = 0;
if (mAdapter != null) {
eatRequestLayout();
mRunningLayoutOrScroll = true;
if (dx != 0) {
hresult = mLayout.scrollHorizontallyBy(dx, mRecycler, mState);
overscrollX = dx - hresult;
}
if (dy != 0) {
vresult = mLayout.scrollVerticallyBy(dy, mRecycler, mState);
overscrollY = dy - vresult;
}
if (supportsChangeAnimations()) {
// Fix up shadow views used by changing animations
int count = mChildHelper.getChildCount();
for (int i = 0; i < count; i++) {
View view = mChildHelper.getChildAt(i);
ViewHolder holder = getChildViewHolder(view);
if (holder != null && holder.mShadowingHolder != null) {
View shadowingView = holder.mShadowingHolder.itemView;
int left = view.getLeft();
int top = view.getTop();
if (left != shadowingView.getLeft() ||
top != shadowingView.getTop()) {
shadowingView.layout(left, top,
left + shadowingView.getWidth(),
top + shadowingView.getHeight());
}
}
}
}
if (smoothScroller != null && !smoothScroller.isPendingInitialRun() &&
smoothScroller.isRunning()) {
final int adapterSize = mState.getItemCount();
if (adapterSize == 0) {
smoothScroller.stop();
} else if (smoothScroller.getTargetPosition() >= adapterSize) {
smoothScroller.setTargetPosition(adapterSize - 1);
smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY);
} else {
smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY);
}
}
mRunningLayoutOrScroll = false;
resumeRequestLayout(false);
}
if (!mItemDecorations.isEmpty()) {
invalidate();
}
if (ViewCompat.getOverScrollMode(RecyclerView.this) !=
ViewCompat.OVER_SCROLL_NEVER) {
considerReleasingGlowsOnScroll(dx, dy);
}
if (overscrollX != 0 || overscrollY != 0) {
final int vel = (int) scroller.getCurrVelocity();
int velX = 0;
if (overscrollX != x) {
velX = overscrollX < 0 ? -vel : overscrollX > 0 ? vel : 0;
}
int velY = 0;
if (overscrollY != y) {
velY = overscrollY < 0 ? -vel : overscrollY > 0 ? vel : 0;
}
if (ViewCompat.getOverScrollMode(RecyclerView.this) !=
ViewCompat.OVER_SCROLL_NEVER) {
absorbGlows(velX, velY);
}
if ((velX != 0 || overscrollX == x || scroller.getFinalX() == 0) &&
(velY != 0 || overscrollY == y || scroller.getFinalY() == 0)) {
scroller.abortAnimation();
}
}
if (hresult != 0 || vresult != 0) {
notifyOnScrolled(hresult, vresult);
}
if (!awakenScrollBars()) {
invalidate();
}
final boolean fullyConsumedVertical = dy != 0 && mLayout.canScrollVertically()
&& vresult == dy;
final boolean fullyConsumedHorizontal = dx != 0 && mLayout.canScrollHorizontally()
&& hresult == dx;
final boolean fullyConsumedAny = (dx == 0 && dy == 0) || fullyConsumedHorizontal
|| fullyConsumedVertical;
if (scroller.isFinished() || !fullyConsumedAny) {
setScrollState(SCROLL_STATE_IDLE); // setting state to idle will stop this.
} else {
postOnAnimation();
}
}
// call this after the onAnimation is complete not to have inconsistent callbacks etc.
if (smoothScroller != null && smoothScroller.isPendingInitialRun()) {
smoothScroller.onAnimation(0, 0);
}
enableRunOnAnimationRequests();
}
private void disableRunOnAnimationRequests() {
mReSchedulePostAnimationCallback = false;
mEatRunOnAnimationRequest = true;
}
private void enableRunOnAnimationRequests() {
mEatRunOnAnimationRequest = false;
if (mReSchedulePostAnimationCallback) {
postOnAnimation();
}
}
void postOnAnimation() {
if (mEatRunOnAnimationRequest) {
mReSchedulePostAnimationCallback = true;
} else {
removeCallbacks(this);
ViewCompat.postOnAnimation(RecyclerView.this, this);
}
}
public void fling(int velocityX, int velocityY) {
setScrollState(SCROLL_STATE_SETTLING);
mLastFlingX = mLastFlingY = 0;
mScroller.fling(0, 0, velocityX, velocityY,
Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);
postOnAnimation();
}
public void smoothScrollBy(int dx, int dy) {
smoothScrollBy(dx, dy, 0, 0);
}
public void smoothScrollBy(int dx, int dy, int vx, int vy) {
smoothScrollBy(dx, dy, computeScrollDuration(dx, dy, vx, vy));
}
private float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f; // center the values about 0.
f *= 0.3f * Math.PI / 2.0f;
return (float) Math.sin(f);
}
private int computeScrollDuration(int dx, int dy, int vx, int vy) {
final int absDx = Math.abs(dx);
final int absDy = Math.abs(dy);
final boolean horizontal = absDx > absDy;
final int velocity = (int) Math.sqrt(vx * vx + vy * vy);
final int delta = (int) Math.sqrt(dx * dx + dy * dy);
final int containerSize = horizontal ? getWidth() : getHeight();
final int halfContainerSize = containerSize / 2;
final float distanceRatio = Math.min(1.f, 1.f * delta / containerSize);
final float distance = halfContainerSize + halfContainerSize *
distanceInfluenceForSnapDuration(distanceRatio);
final int duration;
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
float absDelta = (float) (horizontal ? absDx : absDy);
duration = (int) (((absDelta / containerSize) + 1) * 300);
}
return Math.min(duration, MAX_SCROLL_DURATION);
}
public void smoothScrollBy(int dx, int dy, int duration) {
smoothScrollBy(dx, dy, duration, sQuinticInterpolator);
}
public void smoothScrollBy(int dx, int dy, int duration, Interpolator interpolator) {
if (mInterpolator != interpolator) {
mInterpolator = interpolator;
mScroller = ScrollerCompat.create(getContext(), interpolator);
}
setScrollState(SCROLL_STATE_SETTLING);
mLastFlingX = mLastFlingY = 0;
mScroller.startScroll(0, 0, dx, dy, duration);
postOnAnimation();
}
public void stop() {
removeCallbacks(this);
mScroller.abortAnimation();
}
}
private void notifyOnScrolled(int hresult, int vresult) {
// dummy values, View's implementation does not use these.
onScrollChanged(0, 0, 0, 0);
if (mScrollListener != null) {
mScrollListener.onScrolled(this, hresult, vresult);
}
}
private class RecyclerViewDataObserver extends AdapterDataObserver {
@Override
public void onChanged() {
assertNotInLayoutOrScroll(null);
if (mAdapter.hasStableIds()) {
// TODO Determine what actually changed.
// This is more important to implement now since this callback will disable all
// animations because we cannot rely on positions.
mState.mStructureChanged = true;
setDataSetChangedAfterLayout();
} else {
mState.mStructureChanged = true;
setDataSetChangedAfterLayout();
}
if (!mAdapterHelper.hasPendingUpdates()) {
requestLayout();
}
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
assertNotInLayoutOrScroll(null);
if (mAdapterHelper.onItemRangeChanged(positionStart, itemCount)) {
triggerUpdateProcessor();
}
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
assertNotInLayoutOrScroll(null);
if (mAdapterHelper.onItemRangeInserted(positionStart, itemCount)) {
triggerUpdateProcessor();
}
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
assertNotInLayoutOrScroll(null);
if (mAdapterHelper.onItemRangeRemoved(positionStart, itemCount)) {
triggerUpdateProcessor();
}
}
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
assertNotInLayoutOrScroll(null);
if (mAdapterHelper.onItemRangeMoved(fromPosition, toPosition, itemCount)) {
triggerUpdateProcessor();
}
}
void triggerUpdateProcessor() {
if (mPostUpdatesOnAnimation && mHasFixedSize && mIsAttached) {
ViewCompat.postOnAnimation(RecyclerView.this, mUpdateChildViewsRunnable);
} else {
mAdapterUpdateDuringMeasure = true;
requestLayout();
}
}
}
/**
* RecycledViewPool lets you share Views between multiple RecyclerViews.
* <p>
* If you want to recycle views across RecyclerViews, create an instance of RecycledViewPool
* and use {@link RecyclerView#setRecycledViewPool(RecycledViewPool)}.
* <p>
* RecyclerView automatically creates a pool for itself if you don't provide one.
*
*/
public static class RecycledViewPool {
private SparseArray<ArrayList<ViewHolder>> mScrap =
new SparseArray<ArrayList<ViewHolder>>();
private SparseIntArray mMaxScrap = new SparseIntArray();
private int mAttachCount = 0;
private static final int DEFAULT_MAX_SCRAP = 5;
public void clear() {
mScrap.clear();
}
public void setMaxRecycledViews(int viewType, int max) {
mMaxScrap.put(viewType, max);
final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType);
if (scrapHeap != null) {
while (scrapHeap.size() > max) {
scrapHeap.remove(scrapHeap.size() - 1);
}
}
}
public ViewHolder getRecycledView(int viewType) {
final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType);
if (scrapHeap != null && !scrapHeap.isEmpty()) {
final int index = scrapHeap.size() - 1;
final ViewHolder scrap = scrapHeap.get(index);
scrapHeap.remove(index);
return scrap;
}
return null;
}
int size() {
int count = 0;
for (int i = 0; i < mScrap.size(); i ++) {
ArrayList<ViewHolder> viewHolders = mScrap.valueAt(i);
if (viewHolders != null) {
count += viewHolders.size();
}
}
return count;
}
public void putRecycledView(ViewHolder scrap) {
final int viewType = scrap.getItemViewType();
final ArrayList scrapHeap = getScrapHeapForType(viewType);
if (mMaxScrap.get(viewType) <= scrapHeap.size()) {
return;
}
scrap.resetInternal();
scrapHeap.add(scrap);
}
void attach(Adapter adapter) {
mAttachCount++;
}
void detach() {
mAttachCount--;
}
/**
* Detaches the old adapter and attaches the new one.
* <p>
* RecycledViewPool will clear its cache if it has only one adapter attached and the new
* adapter uses a different ViewHolder than the oldAdapter.
*
* @param oldAdapter The previous adapter instance. Will be detached.
* @param newAdapter The new adapter instance. Will be attached.
* @param compatibleWithPrevious True if both oldAdapter and newAdapter are using the same
* ViewHolder and view types.
*/
void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter,
boolean compatibleWithPrevious) {
if (oldAdapter != null) {
detach();
}
if (!compatibleWithPrevious && mAttachCount == 0) {
clear();
}
if (newAdapter != null) {
attach(newAdapter);
}
}
private ArrayList<ViewHolder> getScrapHeapForType(int viewType) {
ArrayList<ViewHolder> scrap = mScrap.get(viewType);
if (scrap == null) {
scrap = new ArrayList<ViewHolder>();
mScrap.put(viewType, scrap);
if (mMaxScrap.indexOfKey(viewType) < 0) {
mMaxScrap.put(viewType, DEFAULT_MAX_SCRAP);
}
}
return scrap;
}
}
/**
* A Recycler is responsible for managing scrapped or detached item views for reuse.
*
* <p>A "scrapped" view is a view that is still attached to its parent RecyclerView but
* that has been marked for removal or reuse.</p>
*
* <p>Typical use of a Recycler by a {@link LayoutManager} will be to obtain views for
* an adapter's data set representing the data at a given position or item ID.
* If the view to be reused is considered "dirty" the adapter will be asked to rebind it.
* If not, the view can be quickly reused by the LayoutManager with no further work.
* Clean views that have not {@link android.view.View#isLayoutRequested() requested layout}
* may be repositioned by a LayoutManager without remeasurement.</p>
*/
public final class Recycler {
final ArrayList<ViewHolder> mAttachedScrap = new ArrayList<ViewHolder>();
private ArrayList<ViewHolder> mChangedScrap = null;
final ArrayList<ViewHolder> mCachedViews = new ArrayList<ViewHolder>();
private final List<ViewHolder>
mUnmodifiableAttachedScrap = Collections.unmodifiableList(mAttachedScrap);
private int mViewCacheMax = DEFAULT_CACHE_SIZE;
private RecycledViewPool mRecyclerPool;
private ViewCacheExtension mViewCacheExtension;
private static final int DEFAULT_CACHE_SIZE = 2;
/**
* Clear scrap views out of this recycler. Detached views contained within a
* recycled view pool will remain.
*/
public void clear() {
mAttachedScrap.clear();
recycleAndClearCachedViews();
}
/**
* Set the maximum number of detached, valid views we should retain for later use.
*
* @param viewCount Number of views to keep before sending views to the shared pool
*/
public void setViewCacheSize(int viewCount) {
mViewCacheMax = viewCount;
// first, try the views that can be recycled
for (int i = mCachedViews.size() - 1; i >= 0 && mCachedViews.size() > viewCount; i--) {
recycleCachedViewAt(i);
}
}
/**
* Returns an unmodifiable list of ViewHolders that are currently in the scrap list.
*
* @return List of ViewHolders in the scrap list.
*/
public List<ViewHolder> getScrapList() {
return mUnmodifiableAttachedScrap;
}
/**
* Helper method for getViewForPosition.
* <p>
* Checks whether a given view holder can be used for the provided position.
*
* @param holder ViewHolder
* @return true if ViewHolder matches the provided position, false otherwise
*/
boolean validateViewHolderForOffsetPosition(ViewHolder holder) {
// if it is a removed holder, nothing to verify since we cannot ask adapter anymore
// if it is not removed, verify the type and id.
if (holder.isRemoved()) {
return true;
}
if (holder.mPosition < 0 || holder.mPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid view holder "
+ "adapter position" + holder);
}
if (!mState.isPreLayout()) {
// don't check type if it is pre-layout.
final int type = mAdapter.getItemViewType(holder.mPosition);
if (type != holder.getItemViewType()) {
return false;
}
}
if (mAdapter.hasStableIds()) {
return holder.getItemId() == mAdapter.getItemId(holder.mPosition);
}
return true;
}
/**
* Binds the given View to the position. The View can be a View previously retrieved via
* {@link #getViewForPosition(int)} or created by
* {@link Adapter#onCreateViewHolder(ViewGroup, int)}.
* <p>
* Generally, a LayoutManager should acquire its views via {@link #getViewForPosition(int)}
* and let the RecyclerView handle caching. This is a helper method for LayoutManager who
* wants to handle its own recycling logic.
* <p>
* Note that, {@link #getViewForPosition(int)} already binds the View to the position so
* you don't need to call this method unless you want to bind this View to another position.
*
* @param view The view to update.
* @param position The position of the item to bind to this View.
*/
public void bindViewToPosition(View view, int position) {
ViewHolder holder = getChildViewHolderInt(view);
if (holder == null) {
throw new IllegalArgumentException("The view does not have a ViewHolder. You cannot"
+ " pass arbitrary views to this method, they should be created by the "
+ "Adapter");
}
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
+ "position " + position + "(offset:" + offsetPosition + ")."
+ "state:" + mState.getItemCount());
}
holder.mOwnerRecyclerView = RecyclerView.this;
mAdapter.bindViewHolder(holder, offsetPosition);
attachAccessibilityDelegate(view);
if (mState.isPreLayout()) {
holder.mPreLayoutPosition = position;
}
final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
final LayoutParams rvLayoutParams;
if (lp == null) {
rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();
holder.itemView.setLayoutParams(rvLayoutParams);
} else if (!checkLayoutParams(lp)) {
rvLayoutParams = (LayoutParams) generateLayoutParams(lp);
holder.itemView.setLayoutParams(rvLayoutParams);
} else {
rvLayoutParams = (LayoutParams) lp;
}
rvLayoutParams.mInsetsDirty = true;
rvLayoutParams.mViewHolder = holder;
rvLayoutParams.mPendingInvalidate = holder.itemView.getParent() == null;
}
/**
* RecyclerView provides artificial position range (item count) in pre-layout state and
* automatically maps these positions to {@link Adapter} positions when
* {@link #getViewForPosition(int)} or {@link #bindViewToPosition(View, int)} is called.
* <p>
* Usually, LayoutManager does not need to worry about this. However, in some cases, your
* LayoutManager may need to call some custom component with item positions in which
* case you need the actual adapter position instead of the pre layout position. You
* can use this method to convert a pre-layout position to adapter (post layout) position.
* <p>
* Note that if the provided position belongs to a deleted ViewHolder, this method will
* return -1.
* <p>
* Calling this method in post-layout state returns the same value back.
*
* @param position The pre-layout position to convert. Must be greater or equal to 0 and
* less than {@link State#getItemCount()}.
*/
public int convertPreLayoutPositionToPostLayout(int position) {
if (position < 0 || position >= mState.getItemCount()) {
throw new IndexOutOfBoundsException("invalid position " + position + ". State "
+ "item count is " + mState.getItemCount());
}
if (!mState.isPreLayout()) {
return position;
}
return mAdapterHelper.findPositionOffset(position);
}
/**
* Obtain a view initialized for the given position.
*
* This method should be used by {@link LayoutManager} implementations to obtain
* views to represent data from an {@link Adapter}.
* <p>
* The Recycler may reuse a scrap or detached view from a shared pool if one is
* available for the correct view type. If the adapter has not indicated that the
* data at the given position has changed, the Recycler will attempt to hand back
* a scrap view that was previously initialized for that data without rebinding.
*
* @param position Position to obtain a view for
* @return A view representing the data at <code>position</code> from <code>adapter</code>
*/
public View getViewForPosition(int position) {
return getViewForPosition(position, false);
}
View getViewForPosition(int position, boolean dryRun) {
if (position < 0 || position >= mState.getItemCount()) {
throw new IndexOutOfBoundsException("Invalid item position " + position
+ "(" + position + "). Item count:" + mState.getItemCount());
}
boolean fromScrap = false;
ViewHolder holder = null;
// 0) If there is a changed scrap, try to find from there
if (mState.isPreLayout()) {
holder = getChangedScrapViewForPosition(position);
fromScrap = holder != null;
}
// 1) Find from scrap by position
if (holder == null) {
holder = getScrapViewForPosition(position, INVALID_TYPE, dryRun);
if (holder != null) {
if (!validateViewHolderForOffsetPosition(holder)) {
// recycle this scrap
if (!dryRun) {
// we would like to recycle this but need to make sure it is not used by
// animation logic etc.
holder.addFlags(ViewHolder.FLAG_INVALID);
if (holder.isScrap()) {
removeDetachedView(holder.itemView, false);
holder.unScrap();
} else if (holder.wasReturnedFromScrap()) {
holder.clearReturnedFromScrapFlag();
}
recycleViewHolderInternal(holder);
}
holder = null;
} else {
fromScrap = true;
}
}
}
if (holder == null) {
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
+ "position " + position + "(offset:" + offsetPosition + ")."
+ "state:" + mState.getItemCount());
}
final int type = mAdapter.getItemViewType(offsetPosition);
// 2) Find from scrap via stable ids, if exists
if (mAdapter.hasStableIds()) {
holder = getScrapViewForId(mAdapter.getItemId(offsetPosition), type, dryRun);
if (holder != null) {
// update position
holder.mPosition = offsetPosition;
fromScrap = true;
}
}
if (holder == null && mViewCacheExtension != null) {
// We are NOT sending the offsetPosition because LayoutManager does not
// know it.
final View view = mViewCacheExtension
.getViewForPositionAndType(this, position, type);
if (view != null) {
holder = getChildViewHolder(view);
if (holder == null) {
throw new IllegalArgumentException("getViewForPositionAndType returned"
+ " a view which does not have a ViewHolder");
} else if (holder.shouldIgnore()) {
throw new IllegalArgumentException("getViewForPositionAndType returned"
+ " a view that is ignored. You must call stopIgnoring before"
+ " returning this view.");
}
}
}
if (holder == null) { // fallback to recycler
// try recycler.
// Head to the shared pool.
if (DEBUG) {
Log.d(TAG, "getViewForPosition(" + position + ") fetching from shared "
+ "pool");
}
holder = getRecycledViewPool().getRecycledView(type);
if (holder != null) {
holder.resetInternal();
if (FORCE_INVALIDATE_DISPLAY_LIST) {
invalidateDisplayListInt(holder);
}
}
}
if (holder == null) {
holder = mAdapter.createViewHolder(RecyclerView.this, type);
if (DEBUG) {
Log.d(TAG, "getViewForPosition created new ViewHolder");
}
}
}
boolean bound = false;
if (mState.isPreLayout() && holder.isBound()) {
// do not update unless we absolutely have to.
holder.mPreLayoutPosition = position;
} else if (!holder.isBound() || holder.needsUpdate() || holder.isInvalid()) {
if (DEBUG && holder.isRemoved()) {
throw new IllegalStateException("Removed holder should be bound and it should"
+ " come here only in pre-layout. Holder: " + holder);
}
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
holder.mOwnerRecyclerView = RecyclerView.this;
mAdapter.bindViewHolder(holder, offsetPosition);
attachAccessibilityDelegate(holder.itemView);
bound = true;
if (mState.isPreLayout()) {
holder.mPreLayoutPosition = position;
}
}
final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
final LayoutParams rvLayoutParams;
if (lp == null) {
rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();
holder.itemView.setLayoutParams(rvLayoutParams);
} else if (!checkLayoutParams(lp)) {
rvLayoutParams = (LayoutParams) generateLayoutParams(lp);
holder.itemView.setLayoutParams(rvLayoutParams);
} else {
rvLayoutParams = (LayoutParams) lp;
}
rvLayoutParams.mViewHolder = holder;
rvLayoutParams.mPendingInvalidate = fromScrap && bound;
return holder.itemView;
}
private void attachAccessibilityDelegate(View itemView) {
if (mAccessibilityManager != null && mAccessibilityManager.isEnabled()) {
if (ViewCompat.getImportantForAccessibility(itemView) ==
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
ViewCompat.setImportantForAccessibility(itemView,
ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
if (!ViewCompat.hasAccessibilityDelegate(itemView)) {
ViewCompat.setAccessibilityDelegate(itemView,
mAccessibilityDelegate.getItemDelegate());
}
}
}
private void invalidateDisplayListInt(ViewHolder holder) {
if (holder.itemView instanceof ViewGroup) {
invalidateDisplayListInt((ViewGroup) holder.itemView, false);
}
}
private void invalidateDisplayListInt(ViewGroup viewGroup, boolean invalidateThis) {
for (int i = viewGroup.getChildCount() - 1; i >= 0; i--) {
final View view = viewGroup.getChildAt(i);
if (view instanceof ViewGroup) {
invalidateDisplayListInt((ViewGroup) view, true);
}
}
if (!invalidateThis) {
return;
}
// we need to force it to become invisible
if (viewGroup.getVisibility() == View.INVISIBLE) {
viewGroup.setVisibility(View.VISIBLE);
viewGroup.setVisibility(View.INVISIBLE);
} else {
final int visibility = viewGroup.getVisibility();
viewGroup.setVisibility(View.INVISIBLE);
viewGroup.setVisibility(visibility);
}
}
/**
* Recycle a detached view. The specified view will be added to a pool of views
* for later rebinding and reuse.
*
* <p>A view must be fully detached (removed from parent) before it may be recycled. If the
* View is scrapped, it will be removed from scrap list.</p>
*
* @param view Removed view for recycling
* @see LayoutManager#removeAndRecycleView(View, Recycler)
*/
public void recycleView(View view) {
// This public recycle method tries to make view recycle-able since layout manager
// intended to recycle this view (e.g. even if it is in scrap or change cache)
ViewHolder holder = getChildViewHolderInt(view);
if (holder.isTmpDetached()) {
removeDetachedView(view, false);
}
if (holder.isScrap()) {
holder.unScrap();
} else if (holder.wasReturnedFromScrap()){
holder.clearReturnedFromScrapFlag();
}
recycleViewHolderInternal(holder);
}
/**
* Internally, use this method instead of {@link #recycleView(android.view.View)} to
* catch potential bugs.
* @param view
*/
void recycleViewInternal(View view) {
recycleViewHolderInternal(getChildViewHolderInt(view));
}
void recycleAndClearCachedViews() {
final int count = mCachedViews.size();
for (int i = count - 1; i >= 0; i--) {
recycleCachedViewAt(i);
}
mCachedViews.clear();
}
/**
* Recycles a cached view and removes the view from the list. Views are added to cache
* if and only if they are recyclable, so this method does not check it again.
* <p>
* A small exception to this rule is when the view does not have an animator reference
* but transient state is true (due to animations created outside ItemAnimator). In that
* case, adapter may choose to recycle it. From RecyclerView's perspective, the view is
* still recyclable since Adapter wants to do so.
*
* @param cachedViewIndex The index of the view in cached views list
*/
void recycleCachedViewAt(int cachedViewIndex) {
if (DEBUG) {
Log.d(TAG, "Recycling cached view at index " + cachedViewIndex);
}
ViewHolder viewHolder = mCachedViews.get(cachedViewIndex);
if (DEBUG) {
Log.d(TAG, "CachedViewHolder to be recycled: " + viewHolder);
}
addViewHolderToRecycledViewPool(viewHolder);
mCachedViews.remove(cachedViewIndex);
}
/**
* internal implementation checks if view is scrapped or attached and throws an exception
* if so.
* Public version un-scraps before calling recycle.
*/
void recycleViewHolderInternal(ViewHolder holder) {
if (holder.isScrap() || holder.itemView.getParent() != null) {
throw new IllegalArgumentException(
"Scrapped or attached views may not be recycled. isScrap:"
+ holder.isScrap() + " isAttached:"
+ (holder.itemView.getParent() != null));
}
if (holder.isTmpDetached()) {
throw new IllegalArgumentException("Tmp detached view should be removed "
+ "from RecyclerView before it can be recycled: " + holder);
}
if (holder.shouldIgnore()) {
throw new IllegalArgumentException("Trying to recycle an ignored view holder. You"
+ " should first call stopIgnoringView(view) before calling recycle.");
}
//noinspection unchecked
final boolean transientStatePreventsRecycling = holder
.doesTransientStatePreventRecycling();
final boolean forceRecycle = mAdapter != null
&& transientStatePreventsRecycling
&& mAdapter.onFailedToRecycleView(holder);
boolean cached = false;
boolean recycled = false;
if (forceRecycle || holder.isRecyclable()) {
if (!holder.isInvalid() && (mState.mInPreLayout || !holder.isRemoved()) &&
!holder.isChanged()) {
// Retire oldest cached view
final int cachedViewSize = mCachedViews.size();
if (cachedViewSize == mViewCacheMax && cachedViewSize > 0) {
recycleCachedViewAt(0);
}
if (cachedViewSize < mViewCacheMax) {
mCachedViews.add(holder);
cached = true;
}
}
if (!cached) {
addViewHolderToRecycledViewPool(holder);
recycled = true;
}
} else if (DEBUG) {
Log.d(TAG, "trying to recycle a non-recycleable holder. Hopefully, it will "
+ "re-visit here. We are still removing it from animation lists");
}
// even if the holder is not removed, we still call this method so that it is removed
// from view holder lists.
mState.onViewRecycled(holder);
if (!cached && !recycled && transientStatePreventsRecycling) {
holder.mOwnerRecyclerView = null;
}
}
void addViewHolderToRecycledViewPool(ViewHolder holder) {
ViewCompat.setAccessibilityDelegate(holder.itemView, null);
dispatchViewRecycled(holder);
holder.mOwnerRecyclerView = null;
getRecycledViewPool().putRecycledView(holder);
}
/**
* Used as a fast path for unscrapping and recycling a view during a bulk operation.
* The caller must call {@link #clearScrap()} when it's done to update the recycler's
* internal bookkeeping.
*/
void quickRecycleScrapView(View view) {
final ViewHolder holder = getChildViewHolderInt(view);
holder.mScrapContainer = null;
holder.clearReturnedFromScrapFlag();
recycleViewHolderInternal(holder);
}
/**
* Mark an attached view as scrap.
*
* <p>"Scrap" views are still attached to their parent RecyclerView but are eligible
* for rebinding and reuse. Requests for a view for a given position may return a
* reused or rebound scrap view instance.</p>
*
* @param view View to scrap
*/
void scrapView(View view) {
final ViewHolder holder = getChildViewHolderInt(view);
holder.setScrapContainer(this);
if (!holder.isChanged() || !supportsChangeAnimations()) {
if (holder.isInvalid() && !holder.isRemoved() && !mAdapter.hasStableIds()) {
throw new IllegalArgumentException("Called scrap view with an invalid view."
+ " Invalid views cannot be reused from scrap, they should rebound from"
+ " recycler pool.");
}
mAttachedScrap.add(holder);
} else {
if (mChangedScrap == null) {
mChangedScrap = new ArrayList<ViewHolder>();
}
mChangedScrap.add(holder);
}
}
/**
* Remove a previously scrapped view from the pool of eligible scrap.
*
* <p>This view will no longer be eligible for reuse until re-scrapped or
* until it is explicitly removed and recycled.</p>
*/
void unscrapView(ViewHolder holder) {
if (!holder.isChanged() || !supportsChangeAnimations() || mChangedScrap == null) {
mAttachedScrap.remove(holder);
} else {
mChangedScrap.remove(holder);
}
holder.mScrapContainer = null;
holder.clearReturnedFromScrapFlag();
}
int getScrapCount() {
return mAttachedScrap.size();
}
View getScrapViewAt(int index) {
return mAttachedScrap.get(index).itemView;
}
void clearScrap() {
mAttachedScrap.clear();
}
ViewHolder getChangedScrapViewForPosition(int position) {
// If pre-layout, check the changed scrap for an exact match.
final int changedScrapSize;
if (mChangedScrap == null || (changedScrapSize = mChangedScrap.size()) == 0) {
return null;
}
// find by position
for (int i = 0; i < changedScrapSize; i++) {
final ViewHolder holder = mChangedScrap.get(i);
if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position) {
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
return holder;
}
}
// find by id
if (mAdapter.hasStableIds()) {
final int offsetPosition = mAdapterHelper.findPositionOffset(position);
if (offsetPosition > 0 && offsetPosition < mAdapter.getItemCount()) {
final long id = mAdapter.getItemId(offsetPosition);
for (int i = 0; i < changedScrapSize; i++) {
final ViewHolder holder = mChangedScrap.get(i);
if (!holder.wasReturnedFromScrap() && holder.getItemId() == id) {
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
return holder;
}
}
}
}
return null;
}
/**
* Returns a scrap view for the position. If type is not INVALID_TYPE, it also checks if
* ViewHolder's type matches the provided type.
*
* @param position Item position
* @param type View type
* @param dryRun Does a dry run, finds the ViewHolder but does not remove
* @return a ViewHolder that can be re-used for this position.
*/
ViewHolder getScrapViewForPosition(int position, int type, boolean dryRun) {
final int scrapCount = mAttachedScrap.size();
// Try first for an exact, non-invalid match from scrap.
for (int i = 0; i < scrapCount; i++) {
final ViewHolder holder = mAttachedScrap.get(i);
if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position
&& !holder.isInvalid() && (mState.mInPreLayout || !holder.isRemoved())) {
if (type != INVALID_TYPE && holder.getItemViewType() != type) {
Log.e(TAG, "Scrap view for position " + position + " isn't dirty but has" +
" wrong view type! (found " + holder.getItemViewType() +
" but expected " + type + ")");
break;
}
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
return holder;
}
}
if (!dryRun) {
View view = mChildHelper.findHiddenNonRemovedView(position, type);
if (view != null) {
// ending the animation should cause it to get recycled before we reuse it
mItemAnimator.endAnimation(getChildViewHolder(view));
}
}
// Search in our first-level recycled view cache.
final int cacheSize = mCachedViews.size();
for (int i = 0; i < cacheSize; i++) {
final ViewHolder holder = mCachedViews.get(i);
// invalid view holders may be in cache if adapter has stable ids as they can be
// retrieved via getScrapViewForId
if (!holder.isInvalid() && holder.getLayoutPosition() == position) {
if (!dryRun) {
mCachedViews.remove(i);
}
if (DEBUG) {
Log.d(TAG, "getScrapViewForPosition(" + position + ", " + type +
") found match in cache: " + holder);
}
return holder;
}
}
return null;
}
ViewHolder getScrapViewForId(long id, int type, boolean dryRun) {
// Look in our attached views first
final int count = mAttachedScrap.size();
for (int i = count - 1; i >= 0; i--) {
final ViewHolder holder = mAttachedScrap.get(i);
if (holder.getItemId() == id && !holder.wasReturnedFromScrap()) {
if (type == holder.getItemViewType()) {
holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
if (holder.isRemoved()) {
// this might be valid in two cases:
// > item is removed but we are in pre-layout pass
// >> do nothing. return as is. make sure we don't rebind
// > item is removed then added to another position and we are in
// post layout.
// >> remove removed and invalid flags, add update flag to rebind
// because item was invisible to us and we don't know what happened in
// between.
if (!mState.isPreLayout()) {
holder.setFlags(ViewHolder.FLAG_UPDATE, ViewHolder.FLAG_UPDATE |
ViewHolder.FLAG_INVALID | ViewHolder.FLAG_REMOVED);
}
}
return holder;
} else if (!dryRun) {
// Recycle this scrap. Type mismatch.
mAttachedScrap.remove(i);
removeDetachedView(holder.itemView, false);
quickRecycleScrapView(holder.itemView);
}
}
}
// Search the first-level cache
final int cacheSize = mCachedViews.size();
for (int i = cacheSize - 1; i >= 0; i--) {
final ViewHolder holder = mCachedViews.get(i);
if (holder.getItemId() == id) {
if (type == holder.getItemViewType()) {
if (!dryRun) {
mCachedViews.remove(i);
}
return holder;
} else if (!dryRun) {
recycleCachedViewAt(i);
}
}
}
return null;
}
void dispatchViewRecycled(ViewHolder holder) {
if (mRecyclerListener != null) {
mRecyclerListener.onViewRecycled(holder);
}
if (mAdapter != null) {
mAdapter.onViewRecycled(holder);
}
if (mState != null) {
mState.onViewRecycled(holder);
}
if (DEBUG) Log.d(TAG, "dispatchViewRecycled: " + holder);
}
void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter,
boolean compatibleWithPrevious) {
clear();
getRecycledViewPool().onAdapterChanged(oldAdapter, newAdapter, compatibleWithPrevious);
}
void offsetPositionRecordsForMove(int from, int to) {
final int start, end, inBetweenOffset;
if (from < to) {
start = from;
end = to;
inBetweenOffset = -1;
} else {
start = to;
end = from;
inBetweenOffset = 1;
}
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder == null || holder.mPosition < start || holder.mPosition > end) {
continue;
}
if (holder.mPosition == from) {
holder.offsetPosition(to - from, false);
} else {
holder.offsetPosition(inBetweenOffset, false);
}
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForMove cached child " + i + " holder " +
holder);
}
}
}
void offsetPositionRecordsForInsert(int insertedAt, int count) {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null && holder.getLayoutPosition() >= insertedAt) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForInsert cached " + i + " holder " +
holder + " now at position " + (holder.mPosition + count));
}
holder.offsetPosition(count, true);
}
}
}
/**
* @param removedFrom Remove start index
* @param count Remove count
* @param applyToPreLayout If true, changes will affect ViewHolder's pre-layout position, if
* false, they'll be applied before the second layout pass
*/
void offsetPositionRecordsForRemove(int removedFrom, int count, boolean applyToPreLayout) {
final int removedEnd = removedFrom + count;
final int cachedCount = mCachedViews.size();
for (int i = cachedCount - 1; i >= 0; i--) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null) {
if (holder.getLayoutPosition() >= removedEnd) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove cached " + i +
" holder " + holder + " now at position " +
(holder.mPosition - count));
}
holder.offsetPosition(-count, applyToPreLayout);
} else if (holder.getLayoutPosition() >= removedFrom) {
// Item for this view was removed. Dump it from the cache.
holder.addFlags(ViewHolder.FLAG_REMOVED);
recycleCachedViewAt(i);
}
}
}
}
void setViewCacheExtension(ViewCacheExtension extension) {
mViewCacheExtension = extension;
}
void setRecycledViewPool(RecycledViewPool pool) {
if (mRecyclerPool != null) {
mRecyclerPool.detach();
}
mRecyclerPool = pool;
if (pool != null) {
mRecyclerPool.attach(getAdapter());
}
}
RecycledViewPool getRecycledViewPool() {
if (mRecyclerPool == null) {
mRecyclerPool = new RecycledViewPool();
}
return mRecyclerPool;
}
void viewRangeUpdate(int positionStart, int itemCount) {
final int positionEnd = positionStart + itemCount;
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder == null) {
continue;
}
final int pos = holder.getLayoutPosition();
if (pos >= positionStart && pos < positionEnd) {
holder.addFlags(ViewHolder.FLAG_UPDATE);
// cached views should not be flagged as changed because this will cause them
// to animate when they are returned from cache.
}
}
}
void setAdapterPositionsAsUnknown() {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null) {
holder.addFlags(ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN);
}
}
}
void markKnownViewsInvalid() {
if (mAdapter != null && mAdapter.hasStableIds()) {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null) {
holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID);
}
}
} else {
// we cannot re-use cached views in this case. Recycle them all
recycleAndClearCachedViews();
}
}
void clearOldPositions() {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
holder.clearOldPosition();
}
final int scrapCount = mAttachedScrap.size();
for (int i = 0; i < scrapCount; i++) {
mAttachedScrap.get(i).clearOldPosition();
}
if (mChangedScrap != null) {
final int changedScrapCount = mChangedScrap.size();
for (int i = 0; i < changedScrapCount; i++) {
mChangedScrap.get(i).clearOldPosition();
}
}
}
void markItemDecorInsetsDirty() {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
LayoutParams layoutParams = (LayoutParams) holder.itemView.getLayoutParams();
if (layoutParams != null) {
layoutParams.mInsetsDirty = true;
}
}
}
}
/**
* ViewCacheExtension is a helper class to provide an additional layer of view caching that can
* ben controlled by the developer.
* <p>
* When {@link Recycler#getViewForPosition(int)} is called, Recycler checks attached scrap and
* first level cache to find a matching View. If it cannot find a suitable View, Recycler will
* call the {@link #getViewForPositionAndType(Recycler, int, int)} before checking
* {@link RecycledViewPool}.
* <p>
* Note that, Recycler never sends Views to this method to be cached. It is developers
* responsibility to decide whether they want to keep their Views in this custom cache or let
* the default recycling policy handle it.
*/
public abstract static class ViewCacheExtension {
/**
* Returns a View that can be binded to the given Adapter position.
* <p>
* This method should <b>not</b> create a new View. Instead, it is expected to return
* an already created View that can be re-used for the given type and position.
* If the View is marked as ignored, it should first call
* {@link LayoutManager#stopIgnoringView(View)} before returning the View.
* <p>
* RecyclerView will re-bind the returned View to the position if necessary.
*
* @param recycler The Recycler that can be used to bind the View
* @param position The adapter position
* @param type The type of the View, defined by adapter
* @return A View that is bound to the given position or NULL if there is no View to re-use
* @see LayoutManager#ignoreView(View)
*/
abstract public View getViewForPositionAndType(Recycler recycler, int position, int type);
}
/**
* Base class for an Adapter
*
* <p>Adapters provide a binding from an app-specific data set to views that are displayed
* within a {@link RecyclerView}.</p>
*/
public static abstract class Adapter<VH extends ViewHolder> {
private final AdapterDataObservable mObservable = new AdapterDataObservable();
private boolean mHasStableIds = false;
/**
* Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent
* an item.
* <p>
* This new ViewHolder should be constructed with a new View that can represent the items
* of the given type. You can either create a new View manually or inflate it from an XML
* layout file.
* <p>
* The new ViewHolder will be used to display items of the adapter using
* {@link #onBindViewHolder(ViewHolder, int)}. Since it will be re-used to display different
* items in the data set, it is a good idea to cache references to sub views of the View to
* avoid unnecessary {@link View#findViewById(int)} calls.
*
* @param parent The ViewGroup into which the new View will be added after it is bound to
* an adapter position.
* @param viewType The view type of the new View.
*
* @return A new ViewHolder that holds a View of the given view type.
* @see #getItemViewType(int)
* @see #onBindViewHolder(ViewHolder, int)
*/
public abstract VH onCreateViewHolder(ViewGroup parent, int viewType);
/**
* Called by RecyclerView to display the data at the specified position. This method
* should update the contents of the {@link ViewHolder#itemView} to reflect the item at
* the given position.
* <p>
* Note that unlike {@link android.widget.ListView}, RecyclerView will not call this
* method again if the position of the item changes in the data set unless the item itself
* is invalidated or the new position cannot be determined. For this reason, you should only
* use the <code>position</code> parameter while acquiring the related data item inside this
* method and should not keep a copy of it. If you need the position of an item later on
* (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will have
* the updated adapter position.
*
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter's data set.
*/
public abstract void onBindViewHolder(VH holder, int position);
/**
* This method calls {@link #onCreateViewHolder(ViewGroup, int)} to create a new
* {@link ViewHolder} and initializes some private fields to be used by RecyclerView.
*
* @see #onCreateViewHolder(ViewGroup, int)
*/
public final VH createViewHolder(ViewGroup parent, int viewType) {
final VH holder = onCreateViewHolder(parent, viewType);
holder.mItemViewType = viewType;
return holder;
}
/**
* This method internally calls {@link #onBindViewHolder(ViewHolder, int)} to update the
* {@link ViewHolder} contents with the item at the given position and also sets up some
* private fields to be used by RecyclerView.
*
* @see #onBindViewHolder(ViewHolder, int)
*/
public final void bindViewHolder(VH holder, int position) {
holder.mPosition = position;
if (hasStableIds()) {
holder.mItemId = getItemId(position);
}
holder.setFlags(ViewHolder.FLAG_BOUND,
ViewHolder.FLAG_BOUND | ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID
| ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN);
onBindViewHolder(holder, position);
}
/**
* Return the view type of the item at <code>position</code> for the purposes
* of view recycling.
*
* <p>The default implementation of this method returns 0, making the assumption of
* a single view type for the adapter. Unlike ListView adapters, types need not
* be contiguous. Consider using id resources to uniquely identify item view types.
*
* @param position position to query
* @return integer value identifying the type of the view needed to represent the item at
* <code>position</code>. Type codes need not be contiguous.
*/
public int getItemViewType(int position) {
return 0;
}
/**
* Indicates whether each item in the data set can be represented with a unique identifier
* of type {@link java.lang.Long}.
*
* @param hasStableIds Whether items in data set have unique identifiers or not.
* @see #hasStableIds()
* @see #getItemId(int)
*/
public void setHasStableIds(boolean hasStableIds) {
if (hasObservers()) {
throw new IllegalStateException("Cannot change whether this adapter has " +
"stable IDs while the adapter has registered observers.");
}
mHasStableIds = hasStableIds;
}
/**
* Return the stable ID for the item at <code>position</code>. If {@link #hasStableIds()}
* would return false this method should return {@link #NO_ID}. The default implementation
* of this method returns {@link #NO_ID}.
*
* @param position Adapter position to query
* @return the stable ID of the item at position
*/
public long getItemId(int position) {
return NO_ID;
}
/**
* Returns the total number of items in the data set hold by the adapter.
*
* @return The total number of items in this adapter.
*/
public abstract int getItemCount();
/**
* Returns true if this adapter publishes a unique <code>long</code> value that can
* act as a key for the item at a given position in the data set. If that item is relocated
* in the data set, the ID returned for that item should be the same.
*
* @return true if this adapter's items have stable IDs
*/
public final boolean hasStableIds() {
return mHasStableIds;
}
/**
* Called when a view created by this adapter has been recycled.
*
* <p>A view is recycled when a {@link LayoutManager} decides that it no longer
* needs to be attached to its parent {@link RecyclerView}. This can be because it has
* fallen out of visibility or a set of cached views represented by views still
* attached to the parent RecyclerView. If an item view has large or expensive data
* bound to it such as large bitmaps, this may be a good place to release those
* resources.</p>
* <p>
* RecyclerView calls this method right before clearing ViewHolder's internal data and
* sending it to RecycledViewPool. This way, if ViewHolder was holding valid information
* before being recycled, you can call {@link ViewHolder#getAdapterPosition()} to get
* its adapter position.
*
* @param holder The ViewHolder for the view being recycled
*/
public void onViewRecycled(VH holder) {
}
/**
* Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycled
* due to its transient state. Upon receiving this callback, Adapter can clear the
* animation(s) that effect the View's transient state and return <code>true</code> so that
* the View can be recycled. Keep in mind that the View in question is already removed from
* the RecyclerView.
* <p>
* In some cases, it is acceptable to recycle a View although it has transient state. Most
* of the time, this is a case where the transient state will be cleared in
* {@link #onBindViewHolder(ViewHolder, int)} call when View is rebound to a new position.
* For this reason, RecyclerView leaves the decision to the Adapter and uses the return
* value of this method to decide whether the View should be recycled or not.
* <p>
* Note that when all animations are created by {@link RecyclerView.ItemAnimator}, you
* should never receive this callback because RecyclerView keeps those Views as children
* until their animations are complete. This callback is useful when children of the item
* views create animations which may not be easy to implement using an {@link ItemAnimator}.
* <p>
* You should <em>never</em> fix this issue by calling
* <code>holder.itemView.setHasTransientState(false);</code> unless you've previously called
* <code>holder.itemView.setHasTransientState(true);</code>. Each
* <code>View.setHasTransientState(true)</code> call must be matched by a
* <code>View.setHasTransientState(false)</code> call, otherwise, the state of the View
* may become inconsistent. You should always prefer to end or cancel animations that are
* triggering the transient state instead of handling it manually.
*
* @param holder The ViewHolder containing the View that could not be recycled due to its
* transient state.
* @return True if the View should be recycled, false otherwise. Note that if this method
* returns <code>true</code>, RecyclerView <em>will ignore</em> the transient state of
* the View and recycle it regardless. If this method returns <code>false</code>,
* RecyclerView will check the View's transient state again before giving a final decision.
* Default implementation returns false.
*/
public boolean onFailedToRecycleView(VH holder) {
return false;
}
/**
* Called when a view created by this adapter has been attached to a window.
*
* <p>This can be used as a reasonable signal that the view is about to be seen
* by the user. If the adapter previously freed any resources in
* {@link #onViewDetachedFromWindow(RecyclerView.ViewHolder) onViewDetachedFromWindow}
* those resources should be restored here.</p>
*
* @param holder Holder of the view being attached
*/
public void onViewAttachedToWindow(VH holder) {
}
/**
* Called when a view created by this adapter has been detached from its window.
*
* <p>Becoming detached from the window is not necessarily a permanent condition;
* the consumer of an Adapter's views may choose to cache views offscreen while they
* are not visible, attaching an detaching them as appropriate.</p>
*
* @param holder Holder of the view being detached
*/
public void onViewDetachedFromWindow(VH holder) {
}
/**
* Returns true if one or more observers are attached to this adapter.
*
* @return true if this adapter has observers
*/
public final boolean hasObservers() {
return mObservable.hasObservers();
}
/**
* Register a new observer to listen for data changes.
*
* <p>The adapter may publish a variety of events describing specific changes.
* Not all adapters may support all change types and some may fall back to a generic
* {@link android.support.v7.widget.RecyclerView.AdapterDataObserver#onChanged()
* "something changed"} event if more specific data is not available.</p>
*
* <p>Components registering observers with an adapter are responsible for
* {@link #unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver)
* unregistering} those observers when finished.</p>
*
* @param observer Observer to register
*
* @see #unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver)
*/
public void registerAdapterDataObserver(AdapterDataObserver observer) {
mObservable.registerObserver(observer);
}
/**
* Unregister an observer currently listening for data changes.
*
* <p>The unregistered observer will no longer receive events about changes
* to the adapter.</p>
*
* @param observer Observer to unregister
*
* @see #registerAdapterDataObserver(RecyclerView.AdapterDataObserver)
*/
public void unregisterAdapterDataObserver(AdapterDataObserver observer) {
mObservable.unregisterObserver(observer);
}
/**
* Called by RecyclerView when it starts observing this Adapter.
* <p>
* Keep in mind that same adapter may be observed by multiple RecyclerViews.
*
* @param recyclerView The RecyclerView instance which started observing this adapter.
* @see #onDetachedFromRecyclerView(RecyclerView)
*/
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
}
/**
* Called by RecyclerView when it stops observing this Adapter.
*
* @param recyclerView The RecyclerView instance which stopped observing this adapter.
* @see #onAttachedToRecyclerView(RecyclerView)
*/
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
}
/**
* Notify any registered observers that the data set has changed.
*
* <p>There are two different classes of data change events, item changes and structural
* changes. Item changes are when a single item has its data updated but no positional
* changes have occurred. Structural changes are when items are inserted, removed or moved
* within the data set.</p>
*
* <p>This event does not specify what about the data set has changed, forcing
* any observers to assume that all existing items and structure may no longer be valid.
* LayoutManagers will be forced to fully rebind and relayout all visible views.</p>
*
* <p><code>RecyclerView</code> will attempt to synthesize visible structural change events
* for adapters that report that they have {@link #hasStableIds() stable IDs} when
* this method is used. This can help for the purposes of animation and visual
* object persistence but individual item views will still need to be rebound
* and relaid out.</p>
*
* <p>If you are writing an adapter it will always be more efficient to use the more
* specific change events if you can. Rely on <code>notifyDataSetChanged()</code>
* as a last resort.</p>
*
* @see #notifyItemChanged(int)
* @see #notifyItemInserted(int)
* @see #notifyItemRemoved(int)
* @see #notifyItemRangeChanged(int, int)
* @see #notifyItemRangeInserted(int, int)
* @see #notifyItemRangeRemoved(int, int)
*/
public final void notifyDataSetChanged() {
mObservable.notifyChanged();
}
/**
* Notify any registered observers that the item at <code>position</code> has changed.
*
* <p>This is an item change event, not a structural change event. It indicates that any
* reflection of the data at <code>position</code> is out of date and should be updated.
* The item at <code>position</code> retains the same identity.</p>
*
* @param position Position of the item that has changed
*
* @see #notifyItemRangeChanged(int, int)
*/
public final void notifyItemChanged(int position) {
mObservable.notifyItemRangeChanged(position, 1);
}
/**
* Notify any registered observers that the <code>itemCount</code> items starting at
* position <code>positionStart</code> have changed.
*
* <p>This is an item change event, not a structural change event. It indicates that
* any reflection of the data in the given position range is out of date and should
* be updated. The items in the given range retain the same identity.</p>
*
* @param positionStart Position of the first item that has changed
* @param itemCount Number of items that have changed
*
* @see #notifyItemChanged(int)
*/
public final void notifyItemRangeChanged(int positionStart, int itemCount) {
mObservable.notifyItemRangeChanged(positionStart, itemCount);
}
/**
* Notify any registered observers that the item reflected at <code>position</code>
* has been newly inserted. The item previously at <code>position</code> is now at
* position <code>position + 1</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param position Position of the newly inserted item in the data set
*
* @see #notifyItemRangeInserted(int, int)
*/
public final void notifyItemInserted(int position) {
mObservable.notifyItemRangeInserted(position, 1);
}
/**
* Notify any registered observers that the item reflected at <code>fromPosition</code>
* has been moved to <code>toPosition</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their
* positions may be altered.</p>
*
* @param fromPosition Previous position of the item.
* @param toPosition New position of the item.
*/
public final void notifyItemMoved(int fromPosition, int toPosition) {
mObservable.notifyItemMoved(fromPosition, toPosition);
}
/**
* Notify any registered observers that the currently reflected <code>itemCount</code>
* items starting at <code>positionStart</code> have been newly inserted. The items
* previously located at <code>positionStart</code> and beyond can now be found starting
* at position <code>positionStart + itemCount</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param positionStart Position of the first item that was inserted
* @param itemCount Number of items inserted
*
* @see #notifyItemInserted(int)
*/
public final void notifyItemRangeInserted(int positionStart, int itemCount) {
mObservable.notifyItemRangeInserted(positionStart, itemCount);
}
/**
* Notify any registered observers that the item previously located at <code>position</code>
* has been removed from the data set. The items previously located at and after
* <code>position</code> may now be found at <code>oldPosition - 1</code>.
*
* <p>This is a structural change event. Representations of other existing items in the
* data set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param position Position of the item that has now been removed
*
* @see #notifyItemRangeRemoved(int, int)
*/
public final void notifyItemRemoved(int position) {
mObservable.notifyItemRangeRemoved(position, 1);
}
/**
* Notify any registered observers that the <code>itemCount</code> items previously
* located at <code>positionStart</code> have been removed from the data set. The items
* previously located at and after <code>positionStart + itemCount</code> may now be found
* at <code>oldPosition - itemCount</code>.
*
* <p>This is a structural change event. Representations of other existing items in the data
* set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* @param positionStart Previous position of the first item that was removed
* @param itemCount Number of items removed from the data set
*/
public final void notifyItemRangeRemoved(int positionStart, int itemCount) {
mObservable.notifyItemRangeRemoved(positionStart, itemCount);
}
}
private void dispatchChildDetached(View child) {
if (mAdapter != null) {
mAdapter.onViewDetachedFromWindow(getChildViewHolderInt(child));
}
onChildDetachedFromWindow(child);
}
private void dispatchChildAttached(View child) {
if (mAdapter != null) {
mAdapter.onViewAttachedToWindow(getChildViewHolderInt(child));
}
onChildAttachedToWindow(child);
}
/**
* A <code>LayoutManager</code> is responsible for measuring and positioning item views
* within a <code>RecyclerView</code> as well as determining the policy for when to recycle
* item views that are no longer visible to the user. By changing the <code>LayoutManager</code>
* a <code>RecyclerView</code> can be used to implement a standard vertically scrolling list,
* a uniform grid, staggered grids, horizontally scrolling collections and more. Several stock
* layout managers are provided for general use.
*/
public static abstract class LayoutManager {
ChildHelper mChildHelper;
RecyclerView mRecyclerView;
@Nullable
SmoothScroller mSmoothScroller;
private boolean mRequestedSimpleAnimations = false;
void setRecyclerView(RecyclerView recyclerView) {
if (recyclerView == null) {
mRecyclerView = null;
mChildHelper = null;
} else {
mRecyclerView = recyclerView;
mChildHelper = recyclerView.mChildHelper;
}
}
/**
* Calls {@code RecyclerView#requestLayout} on the underlying RecyclerView
*/
public void requestLayout() {
if(mRecyclerView != null) {
mRecyclerView.requestLayout();
}
}
/**
* Checks if RecyclerView is in the middle of a layout or scroll and throws an
* {@link IllegalStateException} if it <b>is not</b>.
*
* @param message The message for the exception. Can be null.
* @see #assertNotInLayoutOrScroll(String)
*/
public void assertInLayoutOrScroll(String message) {
if (mRecyclerView != null) {
mRecyclerView.assertInLayoutOrScroll(message);
}
}
/**
* Checks if RecyclerView is in the middle of a layout or scroll and throws an
* {@link IllegalStateException} if it <b>is</b>.
*
* @param message The message for the exception. Can be null.
* @see #assertInLayoutOrScroll(String)
*/
public void assertNotInLayoutOrScroll(String message) {
if (mRecyclerView != null) {
mRecyclerView.assertNotInLayoutOrScroll(message);
}
}
/**
* Returns whether this LayoutManager supports automatic item animations.
* A LayoutManager wishing to support item animations should obey certain
* rules as outlined in {@link #onLayoutChildren(Recycler, State)}.
* The default return value is <code>false</code>, so subclasses of LayoutManager
* will not get predictive item animations by default.
*
* <p>Whether item animations are enabled in a RecyclerView is determined both
* by the return value from this method and the
* {@link RecyclerView#setItemAnimator(ItemAnimator) ItemAnimator} set on the
* RecyclerView itself. If the RecyclerView has a non-null ItemAnimator but this
* method returns false, then simple item animations will be enabled, in which
* views that are moving onto or off of the screen are simply faded in/out. If
* the RecyclerView has a non-null ItemAnimator and this method returns true,
* then there will be two calls to {@link #onLayoutChildren(Recycler, State)} to
* setup up the information needed to more intelligently predict where appearing
* and disappearing views should be animated from/to.</p>
*
* @return true if predictive item animations should be enabled, false otherwise
*/
public boolean supportsPredictiveItemAnimations() {
return false;
}
/**
* Called when this LayoutManager is both attached to a RecyclerView and that RecyclerView
* is attached to a window.
*
* <p>Subclass implementations should always call through to the superclass implementation.
* </p>
*
* @param view The RecyclerView this LayoutManager is bound to
*/
public void onAttachedToWindow(RecyclerView view) {
}
/**
* @deprecated
* override {@link #onDetachedFromWindow(RecyclerView, Recycler)}
*/
@Deprecated
public void onDetachedFromWindow(RecyclerView view) {
}
/**
* Called when this LayoutManager is detached from its parent RecyclerView or when
* its parent RecyclerView is detached from its window.
*
* <p>Subclass implementations should always call through to the superclass implementation.
* </p>
*
* @param view The RecyclerView this LayoutManager is bound to
* @param recycler The recycler to use if you prefer to recycle your children instead of
* keeping them around.
*/
public void onDetachedFromWindow(RecyclerView view, Recycler recycler) {
onDetachedFromWindow(view);
}
/**
* Check if the RecyclerView is configured to clip child views to its padding.
*
* @return true if this RecyclerView clips children to its padding, false otherwise
*/
public boolean getClipToPadding() {
return mRecyclerView != null && mRecyclerView.mClipToPadding;
}
/**
* Lay out all relevant child views from the given adapter.
*
* The LayoutManager is in charge of the behavior of item animations. By default,
* RecyclerView has a non-null {@link #getItemAnimator() ItemAnimator}, and simple
* item animations are enabled. This means that add/remove operations on the
* adapter will result in animations to add new or appearing items, removed or
* disappearing items, and moved items. If a LayoutManager returns false from
* {@link #supportsPredictiveItemAnimations()}, which is the default, and runs a
* normal layout operation during {@link #onLayoutChildren(Recycler, State)}, the
* RecyclerView will have enough information to run those animations in a simple
* way. For example, the default ItemAnimator, {@link DefaultItemAnimator}, will
* simple fade views in and out, whether they are actuall added/removed or whether
* they are moved on or off the screen due to other add/remove operations.
*
* <p>A LayoutManager wanting a better item animation experience, where items can be
* animated onto and off of the screen according to where the items exist when they
* are not on screen, then the LayoutManager should return true from
* {@link #supportsPredictiveItemAnimations()} and add additional logic to
* {@link #onLayoutChildren(Recycler, State)}. Supporting predictive animations
* means that {@link #onLayoutChildren(Recycler, State)} will be called twice;
* once as a "pre" layout step to determine where items would have been prior to
* a real layout, and again to do the "real" layout. In the pre-layout phase,
* items will remember their pre-layout positions to allow them to be laid out
* appropriately. Also, {@link LayoutParams#isItemRemoved() removed} items will
* be returned from the scrap to help determine correct placement of other items.
* These removed items should not be added to the child list, but should be used
* to help calculate correct positioning of other views, including views that
* were not previously onscreen (referred to as APPEARING views), but whose
* pre-layout offscreen position can be determined given the extra
* information about the pre-layout removed views.</p>
*
* <p>The second layout pass is the real layout in which only non-removed views
* will be used. The only additional requirement during this pass is, if
* {@link #supportsPredictiveItemAnimations()} returns true, to note which
* views exist in the child list prior to layout and which are not there after
* layout (referred to as DISAPPEARING views), and to position/layout those views
* appropriately, without regard to the actual bounds of the RecyclerView. This allows
* the animation system to know the location to which to animate these disappearing
* views.</p>
*
* <p>The default LayoutManager implementations for RecyclerView handle all of these
* requirements for animations already. Clients of RecyclerView can either use one
* of these layout managers directly or look at their implementations of
* onLayoutChildren() to see how they account for the APPEARING and
* DISAPPEARING views.</p>
*
* @param recycler Recycler to use for fetching potentially cached views for a
* position
* @param state Transient state of RecyclerView
*/
public void onLayoutChildren(Recycler recycler, State state) {
Log.e(TAG, "You must override onLayoutChildren(Recycler recycler, State state) ");
}
/**
* Create a default <code>LayoutParams</code> object for a child of the RecyclerView.
*
* <p>LayoutManagers will often want to use a custom <code>LayoutParams</code> type
* to store extra information specific to the layout. Client code should subclass
* {@link RecyclerView.LayoutParams} for this purpose.</p>
*
* <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type
* you must also override
* {@link #checkLayoutParams(LayoutParams)},
* {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and
* {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p>
*
* @return A new LayoutParams for a child view
*/
public abstract LayoutParams generateDefaultLayoutParams();
/**
* Determines the validity of the supplied LayoutParams object.
*
* <p>This should check to make sure that the object is of the correct type
* and all values are within acceptable ranges. The default implementation
* returns <code>true</code> for non-null params.</p>
*
* @param lp LayoutParams object to check
* @return true if this LayoutParams object is valid, false otherwise
*/
public boolean checkLayoutParams(LayoutParams lp) {
return lp != null;
}
/**
* Create a LayoutParams object suitable for this LayoutManager, copying relevant
* values from the supplied LayoutParams object if possible.
*
* <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type
* you must also override
* {@link #checkLayoutParams(LayoutParams)},
* {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and
* {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p>
*
* @param lp Source LayoutParams object to copy values from
* @return a new LayoutParams object
*/
public LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
if (lp instanceof LayoutParams) {
return new LayoutParams((LayoutParams) lp);
} else if (lp instanceof MarginLayoutParams) {
return new LayoutParams((MarginLayoutParams) lp);
} else {
return new LayoutParams(lp);
}
}
/**
* Create a LayoutParams object suitable for this LayoutManager from
* an inflated layout resource.
*
* <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type
* you must also override
* {@link #checkLayoutParams(LayoutParams)},
* {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and
* {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p>
*
* @param c Context for obtaining styled attributes
* @param attrs AttributeSet describing the supplied arguments
* @return a new LayoutParams object
*/
public LayoutParams generateLayoutParams(Context c, AttributeSet attrs) {
return new LayoutParams(c, attrs);
}
/**
* Scroll horizontally by dx pixels in screen coordinates and return the distance traveled.
* The default implementation does nothing and returns 0.
*
* @param dx distance to scroll by in pixels. X increases as scroll position
* approaches the right.
* @param recycler Recycler to use for fetching potentially cached views for a
* position
* @param state Transient state of RecyclerView
* @return The actual distance scrolled. The return value will be negative if dx was
* negative and scrolling proceeeded in that direction.
* <code>Math.abs(result)</code> may be less than dx if a boundary was reached.
*/
public int scrollHorizontallyBy(int dx, Recycler recycler, State state) {
return 0;
}
/**
* Scroll vertically by dy pixels in screen coordinates and return the distance traveled.
* The default implementation does nothing and returns 0.
*
* @param dy distance to scroll in pixels. Y increases as scroll position
* approaches the bottom.
* @param recycler Recycler to use for fetching potentially cached views for a
* position
* @param state Transient state of RecyclerView
* @return The actual distance scrolled. The return value will be negative if dy was
* negative and scrolling proceeeded in that direction.
* <code>Math.abs(result)</code> may be less than dy if a boundary was reached.
*/
public int scrollVerticallyBy(int dy, Recycler recycler, State state) {
return 0;
}
/**
* Query if horizontal scrolling is currently supported. The default implementation
* returns false.
*
* @return True if this LayoutManager can scroll the current contents horizontally
*/
public boolean canScrollHorizontally() {
return false;
}
/**
* Query if vertical scrolling is currently supported. The default implementation
* returns false.
*
* @return True if this LayoutManager can scroll the current contents vertically
*/
public boolean canScrollVertically() {
return false;
}
/**
* Scroll to the specified adapter position.
*
* Actual position of the item on the screen depends on the LayoutManager implementation.
* @param position Scroll to this adapter position.
*/
public void scrollToPosition(int position) {
if (DEBUG) {
Log.e(TAG, "You MUST implement scrollToPosition. It will soon become abstract");
}
}
/**
* <p>Smooth scroll to the specified adapter position.</p>
* <p>To support smooth scrolling, override this method, create your {@link SmoothScroller}
* instance and call {@link #startSmoothScroll(SmoothScroller)}.
* </p>
* @param recyclerView The RecyclerView to which this layout manager is attached
* @param state Current State of RecyclerView
* @param position Scroll to this adapter position.
*/
public void smoothScrollToPosition(RecyclerView recyclerView, State state,
int position) {
Log.e(TAG, "You must override smoothScrollToPosition to support smooth scrolling");
}
/**
* <p>Starts a smooth scroll using the provided SmoothScroller.</p>
* <p>Calling this method will cancel any previous smooth scroll request.</p>
* @param smoothScroller Unstance which defines how smooth scroll should be animated
*/
public void startSmoothScroll(SmoothScroller smoothScroller) {
if (mSmoothScroller != null && smoothScroller != mSmoothScroller
&& mSmoothScroller.isRunning()) {
mSmoothScroller.stop();
}
mSmoothScroller = smoothScroller;
mSmoothScroller.start(mRecyclerView, this);
}
/**
* @return true if RecycylerView is currently in the state of smooth scrolling.
*/
public boolean isSmoothScrolling() {
return mSmoothScroller != null && mSmoothScroller.isRunning();
}
/**
* Returns the resolved layout direction for this RecyclerView.
*
* @return {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_RTL} if the layout
* direction is RTL or returns
* {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_LTR} if the layout direction
* is not RTL.
*/
public int getLayoutDirection() {
return ViewCompat.getLayoutDirection(mRecyclerView);
}
/**
* Ends all animations on the view created by the {@link ItemAnimator}.
*
* @param view The View for which the animations should be ended.
* @see RecyclerView.ItemAnimator#endAnimations()
*/
public void endAnimation(View view) {
if (mRecyclerView.mItemAnimator != null) {
mRecyclerView.mItemAnimator.endAnimation(getChildViewHolderInt(view));
}
}
/**
* To be called only during {@link #onLayoutChildren(Recycler, State)} to add a view
* to the layout that is known to be going away, either because it has been
* {@link Adapter#notifyItemRemoved(int) removed} or because it is actually not in the
* visible portion of the container but is being laid out in order to inform RecyclerView
* in how to animate the item out of view.
* <p>
* Views added via this method are going to be invisible to LayoutManager after the
* dispatchLayout pass is complete. They cannot be retrieved via {@link #getChildAt(int)}
* or won't be included in {@link #getChildCount()} method.
*
* @param child View to add and then remove with animation.
*/
public void addDisappearingView(View child) {
addDisappearingView(child, -1);
}
/**
* To be called only during {@link #onLayoutChildren(Recycler, State)} to add a view
* to the layout that is known to be going away, either because it has been
* {@link Adapter#notifyItemRemoved(int) removed} or because it is actually not in the
* visible portion of the container but is being laid out in order to inform RecyclerView
* in how to animate the item out of view.
* <p>
* Views added via this method are going to be invisible to LayoutManager after the
* dispatchLayout pass is complete. They cannot be retrieved via {@link #getChildAt(int)}
* or won't be included in {@link #getChildCount()} method.
*
* @param child View to add and then remove with animation.
* @param index Index of the view.
*/
public void addDisappearingView(View child, int index) {
addViewInt(child, index, true);
}
/**
* Add a view to the currently attached RecyclerView if needed. LayoutManagers should
* use this method to add views obtained from a {@link Recycler} using
* {@link Recycler#getViewForPosition(int)}.
*
* @param child View to add
*/
public void addView(View child) {
addView(child, -1);
}
/**
* Add a view to the currently attached RecyclerView if needed. LayoutManagers should
* use this method to add views obtained from a {@link Recycler} using
* {@link Recycler#getViewForPosition(int)}.
*
* @param child View to add
* @param index Index to add child at
*/
public void addView(View child, int index) {
addViewInt(child, index, false);
}
private void addViewInt(View child, int index, boolean disappearing) {
final ViewHolder holder = getChildViewHolderInt(child);
if (disappearing || holder.isRemoved()) {
// these views will be hidden at the end of the layout pass.
mRecyclerView.addToDisappearingList(child);
} else {
// This may look like unnecessary but may happen if layout manager supports
// predictive layouts and adapter removed then re-added the same item.
// In this case, added version will be visible in the post layout (because add is
// deferred) but RV will still bind it to the same View.
// So if a View re-appears in post layout pass, remove it from disappearing list.
mRecyclerView.removeFromDisappearingList(child);
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (holder.wasReturnedFromScrap() || holder.isScrap()) {
if (holder.isScrap()) {
holder.unScrap();
} else {
holder.clearReturnedFromScrapFlag();
}
mChildHelper.attachViewToParent(child, index, child.getLayoutParams(), false);
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchFinishTemporaryDetach(child);
}
} else if (child.getParent() == mRecyclerView) { // it was not a scrap but a valid child
// ensure in correct position
int currentIndex = mChildHelper.indexOfChild(child);
if (index == -1) {
index = mChildHelper.getChildCount();
}
if (currentIndex == -1) {
throw new IllegalStateException("Added View has RecyclerView as parent but"
+ " view is not a real child. Unfiltered index:"
+ mRecyclerView.indexOfChild(child));
}
if (currentIndex != index) {
mRecyclerView.mLayout.moveView(currentIndex, index);
}
} else {
mChildHelper.addView(child, index, false);
lp.mInsetsDirty = true;
if (mSmoothScroller != null && mSmoothScroller.isRunning()) {
mSmoothScroller.onChildAttachedToWindow(child);
}
}
if (lp.mPendingInvalidate) {
if (DEBUG) {
Log.d(TAG, "consuming pending invalidate on child " + lp.mViewHolder);
}
holder.itemView.invalidate();
lp.mPendingInvalidate = false;
}
}
/**
* Remove a view from the currently attached RecyclerView if needed. LayoutManagers should
* use this method to completely remove a child view that is no longer needed.
* LayoutManagers should strongly consider recycling removed views using
* {@link Recycler#recycleView(android.view.View)}.
*
* @param child View to remove
*/
public void removeView(View child) {
mChildHelper.removeView(child);
}
/**
* Remove a view from the currently attached RecyclerView if needed. LayoutManagers should
* use this method to completely remove a child view that is no longer needed.
* LayoutManagers should strongly consider recycling removed views using
* {@link Recycler#recycleView(android.view.View)}.
*
* @param index Index of the child view to remove
*/
public void removeViewAt(int index) {
final View child = getChildAt(index);
if (child != null) {
mChildHelper.removeViewAt(index);
}
}
/**
* Remove all views from the currently attached RecyclerView. This will not recycle
* any of the affected views; the LayoutManager is responsible for doing so if desired.
*/
public void removeAllViews() {
// Only remove non-animating views
final int childCount = getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
mChildHelper.removeViewAt(i);
}
}
/**
* Returns the adapter position of the item represented by the given View. This does not
* contain any adapter changes that might have happened after the last layout.
*
* @param view The view to query
* @return The adapter position of the item which is rendered by this View.
*/
public int getPosition(View view) {
return ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
}
/**
* Returns the View type defined by the adapter.
*
* @param view The view to query
* @return The type of the view assigned by the adapter.
*/
public int getItemViewType(View view) {
return getChildViewHolderInt(view).getItemViewType();
}
/**
* Finds the view which represents the given adapter position.
* <p>
* This method traverses each child since it has no information about child order.
* Override this method to improve performance if your LayoutManager keeps data about
* child views.
* <p>
* If a view is ignored via {@link #ignoreView(View)}, it is also ignored by this method.
*
* @param position Position of the item in adapter
* @return The child view that represents the given position or null if the position is not
* laid out
*/
public View findViewByPosition(int position) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
ViewHolder vh = getChildViewHolderInt(child);
if (vh == null) {
continue;
}
if (vh.getLayoutPosition() == position && !vh.shouldIgnore() &&
(mRecyclerView.mState.isPreLayout() || !vh.isRemoved())) {
return child;
}
}
return null;
}
/**
* Temporarily detach a child view.
*
* <p>LayoutManagers may want to perform a lightweight detach operation to rearrange
* views currently attached to the RecyclerView. Generally LayoutManager implementations
* will want to use {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)}
* so that the detached view may be rebound and reused.</p>
*
* <p>If a LayoutManager uses this method to detach a view, it <em>must</em>
* {@link #attachView(android.view.View, int, RecyclerView.LayoutParams) reattach}
* or {@link #removeDetachedView(android.view.View) fully remove} the detached view
* before the LayoutManager entry point method called by RecyclerView returns.</p>
*
* @param child Child to detach
*/
public void detachView(View child) {
final int ind = mChildHelper.indexOfChild(child);
if (ind >= 0) {
detachViewInternal(ind, child);
}
}
/**
* Temporarily detach a child view.
*
* <p>LayoutManagers may want to perform a lightweight detach operation to rearrange
* views currently attached to the RecyclerView. Generally LayoutManager implementations
* will want to use {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)}
* so that the detached view may be rebound and reused.</p>
*
* <p>If a LayoutManager uses this method to detach a view, it <em>must</em>
* {@link #attachView(android.view.View, int, RecyclerView.LayoutParams) reattach}
* or {@link #removeDetachedView(android.view.View) fully remove} the detached view
* before the LayoutManager entry point method called by RecyclerView returns.</p>
*
* @param index Index of the child to detach
*/
public void detachViewAt(int index) {
detachViewInternal(index, getChildAt(index));
}
private void detachViewInternal(int index, View view) {
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchStartTemporaryDetach(view);
}
mChildHelper.detachViewFromParent(index);
}
/**
* Reattach a previously {@link #detachView(android.view.View) detached} view.
* This method should not be used to reattach views that were previously
* {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}.
*
* @param child Child to reattach
* @param index Intended child index for child
* @param lp LayoutParams for child
*/
public void attachView(View child, int index, LayoutParams lp) {
ViewHolder vh = getChildViewHolderInt(child);
if (vh.isRemoved()) {
mRecyclerView.addToDisappearingList(child);
} else {
mRecyclerView.removeFromDisappearingList(child);
}
mChildHelper.attachViewToParent(child, index, lp, vh.isRemoved());
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchFinishTemporaryDetach(child);
}
}
/**
* Reattach a previously {@link #detachView(android.view.View) detached} view.
* This method should not be used to reattach views that were previously
* {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}.
*
* @param child Child to reattach
* @param index Intended child index for child
*/
public void attachView(View child, int index) {
attachView(child, index, (LayoutParams) child.getLayoutParams());
}
/**
* Reattach a previously {@link #detachView(android.view.View) detached} view.
* This method should not be used to reattach views that were previously
* {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}.
*
* @param child Child to reattach
*/
public void attachView(View child) {
attachView(child, -1);
}
/**
* Finish removing a view that was previously temporarily
* {@link #detachView(android.view.View) detached}.
*
* @param child Detached child to remove
*/
public void removeDetachedView(View child) {
mRecyclerView.removeDetachedView(child, false);
}
/**
* Moves a View from one position to another.
*
* @param fromIndex The View's initial index
* @param toIndex The View's target index
*/
public void moveView(int fromIndex, int toIndex) {
View view = getChildAt(fromIndex);
if (view == null) {
throw new IllegalArgumentException("Cannot move a child from non-existing index:"
+ fromIndex);
}
detachViewAt(fromIndex);
attachView(view, toIndex);
}
/**
* Detach a child view and add it to a {@link Recycler Recycler's} scrap heap.
*
* <p>Scrapping a view allows it to be rebound and reused to show updated or
* different data.</p>
*
* @param child Child to detach and scrap
* @param recycler Recycler to deposit the new scrap view into
*/
public void detachAndScrapView(View child, Recycler recycler) {
int index = mChildHelper.indexOfChild(child);
scrapOrRecycleView(recycler, index, child);
}
/**
* Detach a child view and add it to a {@link Recycler Recycler's} scrap heap.
*
* <p>Scrapping a view allows it to be rebound and reused to show updated or
* different data.</p>
*
* @param index Index of child to detach and scrap
* @param recycler Recycler to deposit the new scrap view into
*/
public void detachAndScrapViewAt(int index, Recycler recycler) {
final View child = getChildAt(index);
scrapOrRecycleView(recycler, index, child);
}
/**
* Remove a child view and recycle it using the given Recycler.
*
* @param child Child to remove and recycle
* @param recycler Recycler to use to recycle child
*/
public void removeAndRecycleView(View child, Recycler recycler) {
removeView(child);
recycler.recycleView(child);
}
/**
* Remove a child view and recycle it using the given Recycler.
*
* @param index Index of child to remove and recycle
* @param recycler Recycler to use to recycle child
*/
public void removeAndRecycleViewAt(int index, Recycler recycler) {
final View view = getChildAt(index);
removeViewAt(index);
recycler.recycleView(view);
}
/**
* Return the current number of child views attached to the parent RecyclerView.
* This does not include child views that were temporarily detached and/or scrapped.
*
* @return Number of attached children
*/
public int getChildCount() {
return mChildHelper != null ? mChildHelper.getChildCount() : 0;
}
/**
* Return the child view at the given index
* @param index Index of child to return
* @return Child view at index
*/
public View getChildAt(int index) {
return mChildHelper != null ? mChildHelper.getChildAt(index) : null;
}
/**
* Return the width of the parent RecyclerView
*
* @return Width in pixels
*/
public int getWidth() {
return mRecyclerView != null ? mRecyclerView.getWidth() : 0;
}
/**
* Return the height of the parent RecyclerView
*
* @return Height in pixels
*/
public int getHeight() {
return mRecyclerView != null ? mRecyclerView.getHeight() : 0;
}
/**
* Return the left padding of the parent RecyclerView
*
* @return Padding in pixels
*/
public int getPaddingLeft() {
return mRecyclerView != null ? mRecyclerView.getPaddingLeft() : 0;
}
/**
* Return the top padding of the parent RecyclerView
*
* @return Padding in pixels
*/
public int getPaddingTop() {
return mRecyclerView != null ? mRecyclerView.getPaddingTop() : 0;
}
/**
* Return the right padding of the parent RecyclerView
*
* @return Padding in pixels
*/
public int getPaddingRight() {
return mRecyclerView != null ? mRecyclerView.getPaddingRight() : 0;
}
/**
* Return the bottom padding of the parent RecyclerView
*
* @return Padding in pixels
*/
public int getPaddingBottom() {
return mRecyclerView != null ? mRecyclerView.getPaddingBottom() : 0;
}
/**
* Return the start padding of the parent RecyclerView
*
* @return Padding in pixels
*/
public int getPaddingStart() {
return mRecyclerView != null ? ViewCompat.getPaddingStart(mRecyclerView) : 0;
}
/**
* Return the end padding of the parent RecyclerView
*
* @return Padding in pixels
*/
public int getPaddingEnd() {
return mRecyclerView != null ? ViewCompat.getPaddingEnd(mRecyclerView) : 0;
}
/**
* Returns true if the RecyclerView this LayoutManager is bound to has focus.
*
* @return True if the RecyclerView has focus, false otherwise.
* @see View#isFocused()
*/
public boolean isFocused() {
return mRecyclerView != null && mRecyclerView.isFocused();
}
/**
* Returns true if the RecyclerView this LayoutManager is bound to has or contains focus.
*
* @return true if the RecyclerView has or contains focus
* @see View#hasFocus()
*/
public boolean hasFocus() {
return mRecyclerView != null && mRecyclerView.hasFocus();
}
/**
* Returns the item View which has or contains focus.
*
* @return A direct child of RecyclerView which has focus or contains the focused child.
*/
public View getFocusedChild() {
if (mRecyclerView == null) {
return null;
}
final View focused = mRecyclerView.getFocusedChild();
if (focused == null || mChildHelper.isHidden(focused)) {
return null;
}
return focused;
}
/**
* Returns the number of items in the adapter bound to the parent RecyclerView.
* <p>
* Note that this number is not necessarily equal to {@link State#getItemCount()}. In
* methods where State is available, you should use {@link State#getItemCount()} instead.
* For more details, check the documentation for {@link State#getItemCount()}.
*
* @return The number of items in the bound adapter
* @see State#getItemCount()
*/
public int getItemCount() {
final Adapter a = mRecyclerView != null ? mRecyclerView.getAdapter() : null;
return a != null ? a.getItemCount() : 0;
}
/**
* Offset all child views attached to the parent RecyclerView by dx pixels along
* the horizontal axis.
*
* @param dx Pixels to offset by
*/
public void offsetChildrenHorizontal(int dx) {
if (mRecyclerView != null) {
mRecyclerView.offsetChildrenHorizontal(dx);
}
}
/**
* Offset all child views attached to the parent RecyclerView by dy pixels along
* the vertical axis.
*
* @param dy Pixels to offset by
*/
public void offsetChildrenVertical(int dy) {
if (mRecyclerView != null) {
mRecyclerView.offsetChildrenVertical(dy);
}
}
/**
* Flags a view so that it will not be scrapped or recycled.
* <p>
* Scope of ignoring a child is strictly restricted to position tracking, scrapping and
* recyling. Methods like {@link #removeAndRecycleAllViews(Recycler)} will ignore the child
* whereas {@link #removeAllViews()} or {@link #offsetChildrenHorizontal(int)} will not
* ignore the child.
* <p>
* Before this child can be recycled again, you have to call
* {@link #stopIgnoringView(View)}.
* <p>
* You can call this method only if your LayoutManger is in onLayout or onScroll callback.
*
* @param view View to ignore.
* @see #stopIgnoringView(View)
*/
public void ignoreView(View view) {
if (view.getParent() != mRecyclerView || mRecyclerView.indexOfChild(view) == -1) {
// checking this because calling this method on a recycled or detached view may
// cause loss of state.
throw new IllegalArgumentException("View should be fully attached to be ignored");
}
final ViewHolder vh = getChildViewHolderInt(view);
vh.addFlags(ViewHolder.FLAG_IGNORE);
mRecyclerView.mState.onViewIgnored(vh);
}
/**
* View can be scrapped and recycled again.
* <p>
* Note that calling this method removes all information in the view holder.
* <p>
* You can call this method only if your LayoutManger is in onLayout or onScroll callback.
*
* @param view View to ignore.
*/
public void stopIgnoringView(View view) {
final ViewHolder vh = getChildViewHolderInt(view);
vh.stopIgnoring();
vh.resetInternal();
vh.addFlags(ViewHolder.FLAG_INVALID);
}
/**
* Temporarily detach and scrap all currently attached child views. Views will be scrapped
* into the given Recycler. The Recycler may prefer to reuse scrap views before
* other views that were previously recycled.
*
* @param recycler Recycler to scrap views into
*/
public void detachAndScrapAttachedViews(Recycler recycler) {
final int childCount = getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
final View v = getChildAt(i);
scrapOrRecycleView(recycler, i, v);
}
}
private void scrapOrRecycleView(Recycler recycler, int index, View view) {
final ViewHolder viewHolder = getChildViewHolderInt(view);
if (viewHolder.shouldIgnore()) {
if (DEBUG) {
Log.d(TAG, "ignoring view " + viewHolder);
}
return;
}
if (viewHolder.isInvalid() && !viewHolder.isRemoved() && !viewHolder.isChanged() &&
!mRecyclerView.mAdapter.hasStableIds()) {
removeViewAt(index);
recycler.recycleViewHolderInternal(viewHolder);
} else {
detachViewAt(index);
recycler.scrapView(view);
}
}
/**
* Recycles the scrapped views.
* <p>
* When a view is detached and removed, it does not trigger a ViewGroup invalidate. This is
* the expected behavior if scrapped views are used for animations. Otherwise, we need to
* call remove and invalidate RecyclerView to ensure UI update.
*
* @param recycler Recycler
*/
void removeAndRecycleScrapInt(Recycler recycler) {
final int scrapCount = recycler.getScrapCount();
for (int i = 0; i < scrapCount; i++) {
final View scrap = recycler.getScrapViewAt(i);
final ViewHolder vh = getChildViewHolderInt(scrap);
if (vh.shouldIgnore()) {
continue;
}
if (vh.isTmpDetached()) {
mRecyclerView.removeDetachedView(scrap, false);
}
recycler.quickRecycleScrapView(scrap);
}
recycler.clearScrap();
if (scrapCount > 0) {
mRecyclerView.invalidate();
}
}
/**
* Measure a child view using standard measurement policy, taking the padding
* of the parent RecyclerView and any added item decorations into account.
*
* <p>If the RecyclerView can be scrolled in either dimension the caller may
* pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p>
*
* @param child Child view to measure
* @param widthUsed Width in pixels currently consumed by other views, if relevant
* @param heightUsed Height in pixels currently consumed by other views, if relevant
*/
public void measureChild(View child, int widthUsed, int heightUsed) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
widthUsed += insets.left + insets.right;
heightUsed += insets.top + insets.bottom;
final int widthSpec = getChildMeasureSpec(getWidth(),
getPaddingLeft() + getPaddingRight() + widthUsed, lp.width,
canScrollHorizontally());
final int heightSpec = getChildMeasureSpec(getHeight(),
getPaddingTop() + getPaddingBottom() + heightUsed, lp.height,
canScrollVertically());
child.measure(widthSpec, heightSpec);
}
/**
* Measure a child view using standard measurement policy, taking the padding
* of the parent RecyclerView, any added item decorations and the child margins
* into account.
*
* <p>If the RecyclerView can be scrolled in either dimension the caller may
* pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p>
*
* @param child Child view to measure
* @param widthUsed Width in pixels currently consumed by other views, if relevant
* @param heightUsed Height in pixels currently consumed by other views, if relevant
*/
public void measureChildWithMargins(View child, int widthUsed, int heightUsed) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
widthUsed += insets.left + insets.right;
heightUsed += insets.top + insets.bottom;
final int widthSpec = getChildMeasureSpec(getWidth(),
getPaddingLeft() + getPaddingRight() +
lp.leftMargin + lp.rightMargin + widthUsed, lp.width,
canScrollHorizontally());
final int heightSpec = getChildMeasureSpec(getHeight(),
getPaddingTop() + getPaddingBottom() +
lp.topMargin + lp.bottomMargin + heightUsed, lp.height,
canScrollVertically());
child.measure(widthSpec, heightSpec);
}
/**
* Calculate a MeasureSpec value for measuring a child view in one dimension.
*
* @param parentSize Size of the parent view where the child will be placed
* @param padding Total space currently consumed by other elements of parent
* @param childDimension Desired size of the child view, or MATCH_PARENT/WRAP_CONTENT.
* Generally obtained from the child view's LayoutParams
* @param canScroll true if the parent RecyclerView can scroll in this dimension
*
* @return a MeasureSpec value for the child view
*/
public static int getChildMeasureSpec(int parentSize, int padding, int childDimension,
boolean canScroll) {
int size = Math.max(0, parentSize - padding);
int resultSize = 0;
int resultMode = 0;
if (canScroll) {
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else {
// MATCH_PARENT can't be applied since we can scroll in this dimension, wrap
// instead using UNSPECIFIED.
resultSize = 0;
resultMode = MeasureSpec.UNSPECIFIED;
}
} else {
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.FILL_PARENT) {
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
/**
* Returns the measured width of the given child, plus the additional size of
* any insets applied by {@link ItemDecoration ItemDecorations}.
*
* @param child Child view to query
* @return child's measured width plus <code>ItemDecoration</code> insets
*
* @see View#getMeasuredWidth()
*/
public int getDecoratedMeasuredWidth(View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getMeasuredWidth() + insets.left + insets.right;
}
/**
* Returns the measured height of the given child, plus the additional size of
* any insets applied by {@link ItemDecoration ItemDecorations}.
*
* @param child Child view to query
* @return child's measured height plus <code>ItemDecoration</code> insets
*
* @see View#getMeasuredHeight()
*/
public int getDecoratedMeasuredHeight(View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getMeasuredHeight() + insets.top + insets.bottom;
}
/**
* Lay out the given child view within the RecyclerView using coordinates that
* include any current {@link ItemDecoration ItemDecorations}.
*
* <p>LayoutManagers should prefer working in sizes and coordinates that include
* item decoration insets whenever possible. This allows the LayoutManager to effectively
* ignore decoration insets within measurement and layout code. See the following
* methods:</p>
* <ul>
* <li>{@link #measureChild(View, int, int)}</li>
* <li>{@link #measureChildWithMargins(View, int, int)}</li>
* <li>{@link #getDecoratedLeft(View)}</li>
* <li>{@link #getDecoratedTop(View)}</li>
* <li>{@link #getDecoratedRight(View)}</li>
* <li>{@link #getDecoratedBottom(View)}</li>
* <li>{@link #getDecoratedMeasuredWidth(View)}</li>
* <li>{@link #getDecoratedMeasuredHeight(View)}</li>
* </ul>
*
* @param child Child to lay out
* @param left Left edge, with item decoration insets included
* @param top Top edge, with item decoration insets included
* @param right Right edge, with item decoration insets included
* @param bottom Bottom edge, with item decoration insets included
*
* @see View#layout(int, int, int, int)
*/
public void layoutDecorated(View child, int left, int top, int right, int bottom) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
child.layout(left + insets.left, top + insets.top, right - insets.right,
bottom - insets.bottom);
}
/**
* Returns the left edge of the given child view within its parent, offset by any applied
* {@link ItemDecoration ItemDecorations}.
*
* @param child Child to query
* @return Child left edge with offsets applied
* @see #getLeftDecorationWidth(View)
*/
public int getDecoratedLeft(View child) {
return child.getLeft() - getLeftDecorationWidth(child);
}
/**
* Returns the top edge of the given child view within its parent, offset by any applied
* {@link ItemDecoration ItemDecorations}.
*
* @param child Child to query
* @return Child top edge with offsets applied
* @see #getTopDecorationHeight(View)
*/
public int getDecoratedTop(View child) {
return child.getTop() - getTopDecorationHeight(child);
}
/**
* Returns the right edge of the given child view within its parent, offset by any applied
* {@link ItemDecoration ItemDecorations}.
*
* @param child Child to query
* @return Child right edge with offsets applied
* @see #getRightDecorationWidth(View)
*/
public int getDecoratedRight(View child) {
return child.getRight() + getRightDecorationWidth(child);
}
/**
* Returns the bottom edge of the given child view within its parent, offset by any applied
* {@link ItemDecoration ItemDecorations}.
*
* @param child Child to query
* @return Child bottom edge with offsets applied
* @see #getBottomDecorationHeight(View)
*/
public int getDecoratedBottom(View child) {
return child.getBottom() + getBottomDecorationHeight(child);
}
/**
* Calculates the item decor insets applied to the given child and updates the provided
* Rect instance with the inset values.
* <ul>
* <li>The Rect's left is set to the total width of left decorations.</li>
* <li>The Rect's top is set to the total height of top decorations.</li>
* <li>The Rect's right is set to the total width of right decorations.</li>
* <li>The Rect's bottom is set to total height of bottom decorations.</li>
* </ul>
* <p>
* Note that item decorations are automatically calculated when one of the LayoutManager's
* measure child methods is called. If you need to measure the child with custom specs via
* {@link View#measure(int, int)}, you can use this method to get decorations.
*
* @param child The child view whose decorations should be calculated
* @param outRect The Rect to hold result values
*/
public void calculateItemDecorationsForChild(View child, Rect outRect) {
if (mRecyclerView == null) {
outRect.set(0, 0, 0, 0);
return;
}
Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
outRect.set(insets);
}
/**
* Returns the total height of item decorations applied to child's top.
* <p>
* Note that this value is not updated until the View is measured or
* {@link #calculateItemDecorationsForChild(View, Rect)} is called.
*
* @param child Child to query
* @return The total height of item decorations applied to the child's top.
* @see #getDecoratedTop(View)
* @see #calculateItemDecorationsForChild(View, Rect)
*/
public int getTopDecorationHeight(View child) {
return ((LayoutParams) child.getLayoutParams()).mDecorInsets.top;
}
/**
* Returns the total height of item decorations applied to child's bottom.
* <p>
* Note that this value is not updated until the View is measured or
* {@link #calculateItemDecorationsForChild(View, Rect)} is called.
*
* @param child Child to query
* @return The total height of item decorations applied to the child's bottom.
* @see #getDecoratedBottom(View)
* @see #calculateItemDecorationsForChild(View, Rect)
*/
public int getBottomDecorationHeight(View child) {
return ((LayoutParams) child.getLayoutParams()).mDecorInsets.bottom;
}
/**
* Returns the total width of item decorations applied to child's left.
* <p>
* Note that this value is not updated until the View is measured or
* {@link #calculateItemDecorationsForChild(View, Rect)} is called.
*
* @param child Child to query
* @return The total width of item decorations applied to the child's left.
* @see #getDecoratedLeft(View)
* @see #calculateItemDecorationsForChild(View, Rect)
*/
public int getLeftDecorationWidth(View child) {
return ((LayoutParams) child.getLayoutParams()).mDecorInsets.left;
}
/**
* Returns the total width of item decorations applied to child's right.
* <p>
* Note that this value is not updated until the View is measured or
* {@link #calculateItemDecorationsForChild(View, Rect)} is called.
*
* @param child Child to query
* @return The total width of item decorations applied to the child's right.
* @see #getDecoratedRight(View)
* @see #calculateItemDecorationsForChild(View, Rect)
*/
public int getRightDecorationWidth(View child) {
return ((LayoutParams) child.getLayoutParams()).mDecorInsets.right;
}
/**
* Called when searching for a focusable view in the given direction has failed
* for the current content of the RecyclerView.
*
* <p>This is the LayoutManager's opportunity to populate views in the given direction
* to fulfill the request if it can. The LayoutManager should attach and return
* the view to be focused. The default implementation returns null.</p>
*
* @param focused The currently focused view
* @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
* {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
* {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
* or 0 for not applicable
* @param recycler The recycler to use for obtaining views for currently offscreen items
* @param state Transient state of RecyclerView
* @return The chosen view to be focused
*/
public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
State state) {
return null;
}
/**
* This method gives a LayoutManager an opportunity to intercept the initial focus search
* before the default behavior of {@link FocusFinder} is used. If this method returns
* null FocusFinder will attempt to find a focusable child view. If it fails
* then {@link #onFocusSearchFailed(View, int, RecyclerView.Recycler, RecyclerView.State)}
* will be called to give the LayoutManager an opportunity to add new views for items
* that did not have attached views representing them. The LayoutManager should not add
* or remove views from this method.
*
* @param focused The currently focused view
* @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
* {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
* {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
* @return A descendant view to focus or null to fall back to default behavior.
* The default implementation returns null.
*/
public View onInterceptFocusSearch(View focused, int direction) {
return null;
}
/**
* Called when a child of the RecyclerView wants a particular rectangle to be positioned
* onto the screen. See {@link ViewParent#requestChildRectangleOnScreen(android.view.View,
* android.graphics.Rect, boolean)} for more details.
*
* <p>The base implementation will attempt to perform a standard programmatic scroll
* to bring the given rect into view, within the padded area of the RecyclerView.</p>
*
* @param child The direct child making the request.
* @param rect The rectangle in the child's coordinates the child
* wishes to be on the screen.
* @param immediate True to forbid animated or delayed scrolling,
* false otherwise
* @return Whether the group scrolled to handle the operation
*/
public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect,
boolean immediate) {
final int parentLeft = getPaddingLeft();
final int parentTop = getPaddingTop();
final int parentRight = getWidth() - getPaddingRight();
final int parentBottom = getHeight() - getPaddingBottom();
final int childLeft = child.getLeft() + rect.left;
final int childTop = child.getTop() + rect.top;
final int childRight = childLeft + rect.width();
final int childBottom = childTop + rect.height();
final int offScreenLeft = Math.min(0, childLeft - parentLeft);
final int offScreenTop = Math.min(0, childTop - parentTop);
final int offScreenRight = Math.max(0, childRight - parentRight);
final int offScreenBottom = Math.max(0, childBottom - parentBottom);
// Favor the "start" layout direction over the end when bringing one side or the other
// of a large rect into view.
final int dx;
if (ViewCompat.getLayoutDirection(parent) == ViewCompat.LAYOUT_DIRECTION_RTL) {
dx = offScreenRight != 0 ? offScreenRight : offScreenLeft;
} else {
dx = offScreenLeft != 0 ? offScreenLeft : offScreenRight;
}
// Favor bringing the top into view over the bottom
final int dy = offScreenTop != 0 ? offScreenTop : offScreenBottom;
if (dx != 0 || dy != 0) {
if (immediate) {
parent.scrollBy(dx, dy);
} else {
parent.smoothScrollBy(dx, dy);
}
return true;
}
return false;
}
/**
* @deprecated Use {@link #onRequestChildFocus(RecyclerView, State, View, View)}
*/
@Deprecated
public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
// eat the request if we are in the middle of a scroll or layout
return isSmoothScrolling() || parent.mRunningLayoutOrScroll;
}
/**
* Called when a descendant view of the RecyclerView requests focus.
*
* <p>A LayoutManager wishing to keep focused views aligned in a specific
* portion of the view may implement that behavior in an override of this method.</p>
*
* <p>If the LayoutManager executes different behavior that should override the default
* behavior of scrolling the focused child on screen instead of running alongside it,
* this method should return true.</p>
*
* @param parent The RecyclerView hosting this LayoutManager
* @param state Current state of RecyclerView
* @param child Direct child of the RecyclerView containing the newly focused view
* @param focused The newly focused view. This may be the same view as child or it may be
* null
* @return true if the default scroll behavior should be suppressed
*/
public boolean onRequestChildFocus(RecyclerView parent, State state, View child,
View focused) {
return onRequestChildFocus(parent, child, focused);
}
/**
* Called if the RecyclerView this LayoutManager is bound to has a different adapter set.
* The LayoutManager may use this opportunity to clear caches and configure state such
* that it can relayout appropriately with the new data and potentially new view types.
*
* <p>The default implementation removes all currently attached views.</p>
*
* @param oldAdapter The previous adapter instance. Will be null if there was previously no
* adapter.
* @param newAdapter The new adapter instance. Might be null if
* {@link #setAdapter(RecyclerView.Adapter)} is called with {@code null}.
*/
public void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter) {
}
/**
* Called to populate focusable views within the RecyclerView.
*
* <p>The LayoutManager implementation should return <code>true</code> if the default
* behavior of {@link ViewGroup#addFocusables(java.util.ArrayList, int)} should be
* suppressed.</p>
*
* <p>The default implementation returns <code>false</code> to trigger RecyclerView
* to fall back to the default ViewGroup behavior.</p>
*
* @param recyclerView The RecyclerView hosting this LayoutManager
* @param views List of output views. This method should add valid focusable views
* to this list.
* @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
* {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
* {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
* @param focusableMode The type of focusables to be added.
*
* @return true to suppress the default behavior, false to add default focusables after
* this method returns.
*
* @see #FOCUSABLES_ALL
* @see #FOCUSABLES_TOUCH_MODE
*/
public boolean onAddFocusables(RecyclerView recyclerView, ArrayList<View> views,
int direction, int focusableMode) {
return false;
}
/**
* Called when {@link Adapter#notifyDataSetChanged()} is triggered instead of giving
* detailed information on what has actually changed.
*
* @param recyclerView
*/
public void onItemsChanged(RecyclerView recyclerView) {
}
/**
* Called when items have been added to the adapter. The LayoutManager may choose to
* requestLayout if the inserted items would require refreshing the currently visible set
* of child views. (e.g. currently empty space would be filled by appended items, etc.)
*
* @param recyclerView
* @param positionStart
* @param itemCount
*/
public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
}
/**
* Called when items have been removed from the adapter.
*
* @param recyclerView
* @param positionStart
* @param itemCount
*/
public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) {
}
/**
* Called when items have been changed in the adapter.
*
* @param recyclerView
* @param positionStart
* @param itemCount
*/
public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount) {
}
/**
* Called when an item is moved withing the adapter.
* <p>
* Note that, an item may also change position in response to another ADD/REMOVE/MOVE
* operation. This callback is only called if and only if {@link Adapter#notifyItemMoved}
* is called.
*
* @param recyclerView
* @param from
* @param to
* @param itemCount
*/
public void onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount) {
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeHorizontalScrollExtent()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current state of RecyclerView
* @return The horizontal extent of the scrollbar's thumb
* @see RecyclerView#computeHorizontalScrollExtent()
*/
public int computeHorizontalScrollExtent(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeHorizontalScrollOffset()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current State of RecyclerView where you can find total item count
* @return The horizontal offset of the scrollbar's thumb
* @see RecyclerView#computeHorizontalScrollOffset()
*/
public int computeHorizontalScrollOffset(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeHorizontalScrollRange()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current State of RecyclerView where you can find total item count
* @return The total horizontal range represented by the vertical scrollbar
* @see RecyclerView#computeHorizontalScrollRange()
*/
public int computeHorizontalScrollRange(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeVerticalScrollExtent()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current state of RecyclerView
* @return The vertical extent of the scrollbar's thumb
* @see RecyclerView#computeVerticalScrollExtent()
*/
public int computeVerticalScrollExtent(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeVerticalScrollOffset()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current State of RecyclerView where you can find total item count
* @return The vertical offset of the scrollbar's thumb
* @see RecyclerView#computeVerticalScrollOffset()
*/
public int computeVerticalScrollOffset(State state) {
return 0;
}
/**
* <p>Override this method if you want to support scroll bars.</p>
*
* <p>Read {@link RecyclerView#computeVerticalScrollRange()} for details.</p>
*
* <p>Default implementation returns 0.</p>
*
* @param state Current State of RecyclerView where you can find total item count
* @return The total vertical range represented by the vertical scrollbar
* @see RecyclerView#computeVerticalScrollRange()
*/
public int computeVerticalScrollRange(State state) {
return 0;
}
/**
* Measure the attached RecyclerView. Implementations must call
* {@link #setMeasuredDimension(int, int)} before returning.
*
* <p>The default implementation will handle EXACTLY measurements and respect
* the minimum width and height properties of the host RecyclerView if measured
* as UNSPECIFIED. AT_MOST measurements will be treated as EXACTLY and the RecyclerView
* will consume all available space.</p>
*
* @param recycler Recycler
* @param state Transient state of RecyclerView
* @param widthSpec Width {@link android.view.View.MeasureSpec}
* @param heightSpec Height {@link android.view.View.MeasureSpec}
*/
public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) {
mRecyclerView.defaultOnMeasure(widthSpec, heightSpec);
}
/**
* {@link View#setMeasuredDimension(int, int) Set the measured dimensions} of the
* host RecyclerView.
*
* @param widthSize Measured width
* @param heightSize Measured height
*/
public void setMeasuredDimension(int widthSize, int heightSize) {
mRecyclerView.setMeasuredDimension(widthSize, heightSize);
}
/**
* @return The host RecyclerView's {@link View#getMinimumWidth()}
*/
public int getMinimumWidth() {
return ViewCompat.getMinimumWidth(mRecyclerView);
}
/**
* @return The host RecyclerView's {@link View#getMinimumHeight()}
*/
public int getMinimumHeight() {
return ViewCompat.getMinimumHeight(mRecyclerView);
}
/**
* <p>Called when the LayoutManager should save its state. This is a good time to save your
* scroll position, configuration and anything else that may be required to restore the same
* layout state if the LayoutManager is recreated.</p>
* <p>RecyclerView does NOT verify if the LayoutManager has changed between state save and
* restore. This will let you share information between your LayoutManagers but it is also
* your responsibility to make sure they use the same parcelable class.</p>
*
* @return Necessary information for LayoutManager to be able to restore its state
*/
public Parcelable onSaveInstanceState() {
return null;
}
public void onRestoreInstanceState(Parcelable state) {
}
void stopSmoothScroller() {
if (mSmoothScroller != null) {
mSmoothScroller.stop();
}
}
private void onSmoothScrollerStopped(SmoothScroller smoothScroller) {
if (mSmoothScroller == smoothScroller) {
mSmoothScroller = null;
}
}
/**
* RecyclerView calls this method to notify LayoutManager that scroll state has changed.
*
* @param state The new scroll state for RecyclerView
*/
public void onScrollStateChanged(int state) {
}
/**
* Removes all views and recycles them using the given recycler.
* <p>
* If you want to clean cached views as well, you should call {@link Recycler#clear()} too.
* <p>
* If a View is marked as "ignored", it is not removed nor recycled.
*
* @param recycler Recycler to use to recycle children
* @see #removeAndRecycleView(View, Recycler)
* @see #removeAndRecycleViewAt(int, Recycler)
* @see #ignoreView(View)
*/
public void removeAndRecycleAllViews(Recycler recycler) {
for (int i = getChildCount() - 1; i >= 0; i--) {
final View view = getChildAt(i);
if (!getChildViewHolderInt(view).shouldIgnore()) {
removeAndRecycleViewAt(i, recycler);
}
}
}
// called by accessibility delegate
void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfoCompat info) {
onInitializeAccessibilityNodeInfo(mRecyclerView.mRecycler, mRecyclerView.mState,
info);
}
/**
* Called by the AccessibilityDelegate when the information about the current layout should
* be populated.
* <p>
* Default implementation adds a {@link
* android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.CollectionInfoCompat}.
* <p>
* You should override
* {@link #getRowCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)},
* {@link #getColumnCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)},
* {@link #isLayoutHierarchical(RecyclerView.Recycler, RecyclerView.State)} and
* {@link #getSelectionModeForAccessibility(RecyclerView.Recycler, RecyclerView.State)} for
* more accurate accessibility information.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param info The info that should be filled by the LayoutManager
* @see View#onInitializeAccessibilityNodeInfo(
*android.view.accessibility.AccessibilityNodeInfo)
* @see #getRowCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)
* @see #getColumnCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)
* @see #isLayoutHierarchical(RecyclerView.Recycler, RecyclerView.State)
* @see #getSelectionModeForAccessibility(RecyclerView.Recycler, RecyclerView.State)
*/
public void onInitializeAccessibilityNodeInfo(Recycler recycler, State state,
AccessibilityNodeInfoCompat info) {
info.setClassName(RecyclerView.class.getName());
if (ViewCompat.canScrollVertically(mRecyclerView, -1) ||
ViewCompat.canScrollHorizontally(mRecyclerView, -1)) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD);
info.setScrollable(true);
}
if (ViewCompat.canScrollVertically(mRecyclerView, 1) ||
ViewCompat.canScrollHorizontally(mRecyclerView, 1)) {
info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD);
info.setScrollable(true);
}
final AccessibilityNodeInfoCompat.CollectionInfoCompat collectionInfo
= AccessibilityNodeInfoCompat.CollectionInfoCompat
.obtain(getRowCountForAccessibility(recycler, state),
getColumnCountForAccessibility(recycler, state),
isLayoutHierarchical(recycler, state),
getSelectionModeForAccessibility(recycler, state));
info.setCollectionInfo(collectionInfo);
}
// called by accessibility delegate
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
onInitializeAccessibilityEvent(mRecyclerView.mRecycler, mRecyclerView.mState, event);
}
/**
* Called by the accessibility delegate to initialize an accessibility event.
* <p>
* Default implementation adds item count and scroll information to the event.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param event The event instance to initialize
* @see View#onInitializeAccessibilityEvent(android.view.accessibility.AccessibilityEvent)
*/
public void onInitializeAccessibilityEvent(Recycler recycler, State state,
AccessibilityEvent event) {
final AccessibilityRecordCompat record = AccessibilityEventCompat
.asRecord(event);
if (mRecyclerView == null || record == null) {
return;
}
record.setScrollable(ViewCompat.canScrollVertically(mRecyclerView, 1)
|| ViewCompat.canScrollVertically(mRecyclerView, -1)
|| ViewCompat.canScrollHorizontally(mRecyclerView, -1)
|| ViewCompat.canScrollHorizontally(mRecyclerView, 1));
if (mRecyclerView.mAdapter != null) {
record.setItemCount(mRecyclerView.mAdapter.getItemCount());
}
}
// called by accessibility delegate
void onInitializeAccessibilityNodeInfoForItem(View host, AccessibilityNodeInfoCompat info) {
final ViewHolder vh = getChildViewHolderInt(host);
// avoid trying to create accessibility node info for removed children
if (vh != null && !vh.isRemoved()) {
onInitializeAccessibilityNodeInfoForItem(mRecyclerView.mRecycler,
mRecyclerView.mState, host, info);
}
}
/**
* Called by the AccessibilityDelegate when the accessibility information for a specific
* item should be populated.
* <p>
* Default implementation adds basic positioning information about the item.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param host The child for which accessibility node info should be populated
* @param info The info to fill out about the item
* @see android.widget.AbsListView#onInitializeAccessibilityNodeInfoForItem(View, int,
* android.view.accessibility.AccessibilityNodeInfo)
*/
public void onInitializeAccessibilityNodeInfoForItem(Recycler recycler, State state,
View host, AccessibilityNodeInfoCompat info) {
int rowIndexGuess = canScrollVertically() ? getPosition(host) : 0;
int columnIndexGuess = canScrollHorizontally() ? getPosition(host) : 0;
final AccessibilityNodeInfoCompat.CollectionItemInfoCompat itemInfo
= AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain(rowIndexGuess, 1,
columnIndexGuess, 1, false, false);
info.setCollectionItemInfo(itemInfo);
}
/**
* A LayoutManager can call this method to force RecyclerView to run simple animations in
* the next layout pass, even if there is not any trigger to do so. (e.g. adapter data
* change).
* <p>
* Note that, calling this method will not guarantee that RecyclerView will run animations
* at all. For example, if there is not any {@link ItemAnimator} set, RecyclerView will
* not run any animations but will still clear this flag after the layout is complete.
*
*/
public void requestSimpleAnimationsInNextLayout() {
mRequestedSimpleAnimations = true;
}
/**
* Returns the selection mode for accessibility. Should be
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE},
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_SINGLE} or
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_MULTIPLE}.
* <p>
* Default implementation returns
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE}.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @return Selection mode for accessibility. Default implementation returns
* {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE}.
*/
public int getSelectionModeForAccessibility(Recycler recycler, State state) {
return AccessibilityNodeInfoCompat.CollectionInfoCompat.SELECTION_MODE_NONE;
}
/**
* Returns the number of rows for accessibility.
* <p>
* Default implementation returns the number of items in the adapter if LayoutManager
* supports vertical scrolling or 1 if LayoutManager does not support vertical
* scrolling.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @return The number of rows in LayoutManager for accessibility.
*/
public int getRowCountForAccessibility(Recycler recycler, State state) {
if (mRecyclerView == null || mRecyclerView.mAdapter == null) {
return 1;
}
return canScrollVertically() ? mRecyclerView.mAdapter.getItemCount() : 1;
}
/**
* Returns the number of columns for accessibility.
* <p>
* Default implementation returns the number of items in the adapter if LayoutManager
* supports horizontal scrolling or 1 if LayoutManager does not support horizontal
* scrolling.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @return The number of rows in LayoutManager for accessibility.
*/
public int getColumnCountForAccessibility(Recycler recycler, State state) {
if (mRecyclerView == null || mRecyclerView.mAdapter == null) {
return 1;
}
return canScrollHorizontally() ? mRecyclerView.mAdapter.getItemCount() : 1;
}
/**
* Returns whether layout is hierarchical or not to be used for accessibility.
* <p>
* Default implementation returns false.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @return True if layout is hierarchical.
*/
public boolean isLayoutHierarchical(Recycler recycler, State state) {
return false;
}
// called by accessibility delegate
boolean performAccessibilityAction(int action, Bundle args) {
return performAccessibilityAction(mRecyclerView.mRecycler, mRecyclerView.mState,
action, args);
}
/**
* Called by AccessibilityDelegate when an action is requested from the RecyclerView.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param action The action to perform
* @param args Optional action arguments
* @see View#performAccessibilityAction(int, android.os.Bundle)
*/
public boolean performAccessibilityAction(Recycler recycler, State state, int action,
Bundle args) {
if (mRecyclerView == null) {
return false;
}
int vScroll = 0, hScroll = 0;
switch (action) {
case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD:
if (ViewCompat.canScrollVertically(mRecyclerView, -1)) {
vScroll = -(getHeight() - getPaddingTop() - getPaddingBottom());
}
if (ViewCompat.canScrollHorizontally(mRecyclerView, -1)) {
hScroll = -(getWidth() - getPaddingLeft() - getPaddingRight());
}
break;
case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD:
if (ViewCompat.canScrollVertically(mRecyclerView, 1)) {
vScroll = getHeight() - getPaddingTop() - getPaddingBottom();
}
if (ViewCompat.canScrollHorizontally(mRecyclerView, 1)) {
hScroll = getWidth() - getPaddingLeft() - getPaddingRight();
}
break;
}
if (vScroll == 0 && hScroll == 0) {
return false;
}
mRecyclerView.scrollBy(hScroll, vScroll);
return true;
}
// called by accessibility delegate
boolean performAccessibilityActionForItem(View view, int action, Bundle args) {
return performAccessibilityActionForItem(mRecyclerView.mRecycler, mRecyclerView.mState,
view, action, args);
}
/**
* Called by AccessibilityDelegate when an accessibility action is requested on one of the
* children of LayoutManager.
* <p>
* Default implementation does not do anything.
*
* @param recycler The Recycler that can be used to convert view positions into adapter
* positions
* @param state The current state of RecyclerView
* @param view The child view on which the action is performed
* @param action The action to perform
* @param args Optional action arguments
* @return true if action is handled
* @see View#performAccessibilityAction(int, android.os.Bundle)
*/
public boolean performAccessibilityActionForItem(Recycler recycler, State state, View view,
int action, Bundle args) {
return false;
}
}
private void removeFromDisappearingList(View child) {
mDisappearingViewsInLayoutPass.remove(child);
}
private void addToDisappearingList(View child) {
if (!mDisappearingViewsInLayoutPass.contains(child)) {
mDisappearingViewsInLayoutPass.add(child);
}
}
/**
* An ItemDecoration allows the application to add a special drawing and layout offset
* to specific item views from the adapter's data set. This can be useful for drawing dividers
* between items, highlights, visual grouping boundaries and more.
*
* <p>All ItemDecorations are drawn in the order they were added, before the item
* views (in {@link ItemDecoration#onDraw(Canvas, RecyclerView, RecyclerView.State) onDraw()}
* and after the items (in {@link ItemDecoration#onDrawOver(Canvas, RecyclerView,
* RecyclerView.State)}.</p>
*/
public static abstract class ItemDecoration {
/**
* Draw any appropriate decorations into the Canvas supplied to the RecyclerView.
* Any content drawn by this method will be drawn before the item views are drawn,
* and will thus appear underneath the views.
*
* @param c Canvas to draw into
* @param parent RecyclerView this ItemDecoration is drawing into
* @param state The current state of RecyclerView
*/
public void onDraw(Canvas c, RecyclerView parent, State state) {
onDraw(c, parent);
}
/**
* @deprecated
* Override {@link #onDraw(Canvas, RecyclerView, RecyclerView.State)}
*/
@Deprecated
public void onDraw(Canvas c, RecyclerView parent) {
}
/**
* Draw any appropriate decorations into the Canvas supplied to the RecyclerView.
* Any content drawn by this method will be drawn after the item views are drawn
* and will thus appear over the views.
*
* @param c Canvas to draw into
* @param parent RecyclerView this ItemDecoration is drawing into
* @param state The current state of RecyclerView.
*/
public void onDrawOver(Canvas c, RecyclerView parent, State state) {
onDrawOver(c, parent);
}
/**
* @deprecated
* Override {@link #onDrawOver(Canvas, RecyclerView, RecyclerView.State)}
*/
@Deprecated
public void onDrawOver(Canvas c, RecyclerView parent) {
}
/**
* @deprecated
* Use {@link #getItemOffsets(Rect, View, RecyclerView, State)}
*/
@Deprecated
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
outRect.set(0, 0, 0, 0);
}
/**
* Retrieve any offsets for the given item. Each field of <code>outRect</code> specifies
* the number of pixels that the item view should be inset by, similar to padding or margin.
* The default implementation sets the bounds of outRect to 0 and returns.
*
* <p>
* If this ItemDecoration does not affect the positioning of item views, it should set
* all four fields of <code>outRect</code> (left, top, right, bottom) to zero
* before returning.
*
* <p>
* If you need to access Adapter for additional data, you can call
* {@link RecyclerView#getChildAdapterPosition(View)} to get the adapter position of the
* View.
*
* @param outRect Rect to receive the output.
* @param view The child view to decorate
* @param parent RecyclerView this ItemDecoration is decorating
* @param state The current state of RecyclerView.
*/
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
parent);
}
}
/**
* An OnItemTouchListener allows the application to intercept touch events in progress at the
* view hierarchy level of the RecyclerView before those touch events are considered for
* RecyclerView's own scrolling behavior.
*
* <p>This can be useful for applications that wish to implement various forms of gestural
* manipulation of item views within the RecyclerView. OnItemTouchListeners may intercept
* a touch interaction already in progress even if the RecyclerView is already handling that
* gesture stream itself for the purposes of scrolling.</p>
*/
public interface OnItemTouchListener {
/**
* Silently observe and/or take over touch events sent to the RecyclerView
* before they are handled by either the RecyclerView itself or its child views.
*
* <p>The onInterceptTouchEvent methods of each attached OnItemTouchListener will be run
* in the order in which each listener was added, before any other touch processing
* by the RecyclerView itself or child views occurs.</p>
*
* @param e MotionEvent describing the touch event. All coordinates are in
* the RecyclerView's coordinate system.
* @return true if this OnItemTouchListener wishes to begin intercepting touch events, false
* to continue with the current behavior and continue observing future events in
* the gesture.
*/
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e);
/**
* Process a touch event as part of a gesture that was claimed by returning true from
* a previous call to {@link #onInterceptTouchEvent}.
*
* @param e MotionEvent describing the touch event. All coordinates are in
* the RecyclerView's coordinate system.
*/
public void onTouchEvent(RecyclerView rv, MotionEvent e);
}
/**
* An OnScrollListener can be set on a RecyclerView to receive messages
* when a scrolling event has occurred on that RecyclerView.
*
* @see RecyclerView#setOnScrollListener(OnScrollListener)
*/
abstract static public class OnScrollListener {
/**
* Callback method to be invoked when RecyclerView's scroll state changes.
*
* @param recyclerView The RecyclerView whose scroll state has changed.
* @param newState The updated scroll state. One of {@link #SCROLL_STATE_IDLE},
* {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}.
*/
public void onScrollStateChanged(RecyclerView recyclerView, int newState){}
/**
* Callback method to be invoked when the RecyclerView has been scrolled. This will be
* called after the scroll has completed.
* <p>
* This callback will also be called if visible item range changes after a layout
* calculation. In that case, dx and dy will be 0.
*
* @param recyclerView The RecyclerView which scrolled.
* @param dx The amount of horizontal scroll.
* @param dy The amount of vertical scroll.
*/
public void onScrolled(RecyclerView recyclerView, int dx, int dy){}
}
/**
* A RecyclerListener can be set on a RecyclerView to receive messages whenever
* a view is recycled.
*
* @see RecyclerView#setRecyclerListener(RecyclerListener)
*/
public interface RecyclerListener {
/**
* This method is called whenever the view in the ViewHolder is recycled.
*
* RecyclerView calls this method right before clearing ViewHolder's internal data and
* sending it to RecycledViewPool. This way, if ViewHolder was holding valid information
* before being recycled, you can call {@link ViewHolder#getAdapterPosition()} to get
* its adapter position.
*
* @param holder The ViewHolder containing the view that was recycled
*/
public void onViewRecycled(ViewHolder holder);
}
/**
* A ViewHolder describes an item view and metadata about its place within the RecyclerView.
*
* <p>{@link Adapter} implementations should subclass ViewHolder and add fields for caching
* potentially expensive {@link View#findViewById(int)} results.</p>
*
* <p>While {@link LayoutParams} belong to the {@link LayoutManager},
* {@link ViewHolder ViewHolders} belong to the adapter. Adapters should feel free to use
* their own custom ViewHolder implementations to store data that makes binding view contents
* easier. Implementations should assume that individual item views will hold strong references
* to <code>ViewHolder</code> objects and that <code>RecyclerView</code> instances may hold
* strong references to extra off-screen item views for caching purposes</p>
*/
public static abstract class ViewHolder {
public final View itemView;
int mPosition = NO_POSITION;
int mOldPosition = NO_POSITION;
long mItemId = NO_ID;
int mItemViewType = INVALID_TYPE;
int mPreLayoutPosition = NO_POSITION;
// The item that this holder is shadowing during an item change event/animation
ViewHolder mShadowedHolder = null;
// The item that is shadowing this holder during an item change event/animation
ViewHolder mShadowingHolder = null;
/**
* This ViewHolder has been bound to a position; mPosition, mItemId and mItemViewType
* are all valid.
*/
static final int FLAG_BOUND = 1 << 0;
/**
* The data this ViewHolder's view reflects is stale and needs to be rebound
* by the adapter. mPosition and mItemId are consistent.
*/
static final int FLAG_UPDATE = 1 << 1;
/**
* This ViewHolder's data is invalid. The identity implied by mPosition and mItemId
* are not to be trusted and may no longer match the item view type.
* This ViewHolder must be fully rebound to different data.
*/
static final int FLAG_INVALID = 1 << 2;
/**
* This ViewHolder points at data that represents an item previously removed from the
* data set. Its view may still be used for things like outgoing animations.
*/
static final int FLAG_REMOVED = 1 << 3;
/**
* This ViewHolder should not be recycled. This flag is set via setIsRecyclable()
* and is intended to keep views around during animations.
*/
static final int FLAG_NOT_RECYCLABLE = 1 << 4;
/**
* This ViewHolder is returned from scrap which means we are expecting an addView call
* for this itemView. When returned from scrap, ViewHolder stays in the scrap list until
* the end of the layout pass and then recycled by RecyclerView if it is not added back to
* the RecyclerView.
*/
static final int FLAG_RETURNED_FROM_SCRAP = 1 << 5;
/**
* This ViewHolder's contents have changed. This flag is used as an indication that
* change animations may be used, if supported by the ItemAnimator.
*/
static final int FLAG_CHANGED = 1 << 6;
/**
* This ViewHolder is fully managed by the LayoutManager. We do not scrap, recycle or remove
* it unless LayoutManager is replaced.
* It is still fully visible to the LayoutManager.
*/
static final int FLAG_IGNORE = 1 << 7;
/**
* When the View is detached form the parent, we set this flag so that we can take correct
* action when we need to remove it or add it back.
*/
static final int FLAG_TMP_DETACHED = 1 << 8;
/**
* Set when we can no longer determine the adapter position of this ViewHolder until it is
* rebound to a new position. It is different than FLAG_INVALID because FLAG_INVALID is
* set even when the type does not match. Also, FLAG_ADAPTER_POSITION_UNKNOWN is set as soon
* as adapter notification arrives vs FLAG_INVALID is set lazily before layout is
* re-calculated.
*/
static final int FLAG_ADAPTER_POSITION_UNKNOWN = 1 << 9;
private int mFlags;
private int mIsRecyclableCount = 0;
// If non-null, view is currently considered scrap and may be reused for other data by the
// scrap container.
private Recycler mScrapContainer = null;
/**
* Is set when VH is bound from the adapter and cleaned right before it is sent to
* {@link RecycledViewPool}.
*/
RecyclerView mOwnerRecyclerView;
public ViewHolder(View itemView) {
if (itemView == null) {
throw new IllegalArgumentException("itemView may not be null");
}
this.itemView = itemView;
}
void flagRemovedAndOffsetPosition(int mNewPosition, int offset, boolean applyToPreLayout) {
addFlags(ViewHolder.FLAG_REMOVED);
offsetPosition(offset, applyToPreLayout);
mPosition = mNewPosition;
}
void offsetPosition(int offset, boolean applyToPreLayout) {
if (mOldPosition == NO_POSITION) {
mOldPosition = mPosition;
}
if (mPreLayoutPosition == NO_POSITION) {
mPreLayoutPosition = mPosition;
}
if (applyToPreLayout) {
mPreLayoutPosition += offset;
}
mPosition += offset;
if (itemView.getLayoutParams() != null) {
((LayoutParams) itemView.getLayoutParams()).mInsetsDirty = true;
}
}
void clearOldPosition() {
mOldPosition = NO_POSITION;
mPreLayoutPosition = NO_POSITION;
}
void saveOldPosition() {
if (mOldPosition == NO_POSITION) {
mOldPosition = mPosition;
}
}
boolean shouldIgnore() {
return (mFlags & FLAG_IGNORE) != 0;
}
/**
* @deprecated This method is deprecated because its meaning is ambiguous due to the async
* handling of adapter updates. Please use {@link #getLayoutPosition()} or
* {@link #getAdapterPosition()} depending on your use case.
*
* @see #getLayoutPosition()
* @see #getAdapterPosition()
*/
@Deprecated
public final int getPosition() {
return mPreLayoutPosition == NO_POSITION ? mPosition : mPreLayoutPosition;
}
/**
* Returns the position of the ViewHolder in terms of the latest layout pass.
* <p>
* This position is mostly used by RecyclerView components to be consistent while
* RecyclerView lazily processes adapter updates.
* <p>
* For performance and animation reasons, RecyclerView batches all adapter updates until the
* next layout pass. This may cause mismatches between the Adapter position of the item and
* the position it had in the latest layout calculations.
* <p>
* LayoutManagers should always call this method while doing calculations based on item
* positions. All methods in {@link RecyclerView.LayoutManager}, {@link RecyclerView.State},
* {@link RecyclerView.Recycler} that receive a position expect it to be the layout position
* of the item.
* <p>
* If LayoutManager needs to call an external method that requires the adapter position of
* the item, it can use {@link #getAdapterPosition()} or
* {@link RecyclerView.Recycler#convertPreLayoutPositionToPostLayout(int)}.
*
* @return Returns the adapter position of the ViewHolder in the latest layout pass.
* @see #getAdapterPosition()
*/
public final int getLayoutPosition() {
return mPreLayoutPosition == NO_POSITION ? mPosition : mPreLayoutPosition;
}
/**
* Returns the Adapter position of the item represented by this ViewHolder.
* <p>
* Note that this might be different than the {@link #getLayoutPosition()} if there are
* pending adapter updates but a new layout pass has not happened yet.
* <p>
* RecyclerView does not handle any adapter updates until the next layout traversal. This
* may create temporary inconsistencies between what user sees on the screen and what
* adapter contents have. This inconsistency is not important since it will be less than
* 16ms but it might be a problem if you want to use ViewHolder position to access the
* adapter. Sometimes, you may need to get the exact adapter position to do
* some actions in response to user events. In that case, you should use this method which
* will calculate the Adapter position of the ViewHolder.
* <p>
* Note that if you've called {@link RecyclerView.Adapter#notifyDataSetChanged()}, until the
* next layout pass, the return value of this method will be {@link #NO_POSITION}.
*
* @return The adapter position of the item if it still exists in the adapter.
* {@link RecyclerView#NO_POSITION} if item has been removed from the adapter,
* {@link RecyclerView.Adapter#notifyDataSetChanged()} has been called after the last
* layout pass or the ViewHolder has already been recycled.
*/
public final int getAdapterPosition() {
if (mOwnerRecyclerView == null) {
return NO_POSITION;
}
return mOwnerRecyclerView.getAdapterPositionFor(this);
}
/**
* When LayoutManager supports animations, RecyclerView tracks 3 positions for ViewHolders
* to perform animations.
* <p>
* If a ViewHolder was laid out in the previous onLayout call, old position will keep its
* adapter index in the previous layout.
*
* @return The previous adapter index of the Item represented by this ViewHolder or
* {@link #NO_POSITION} if old position does not exists or cleared (pre-layout is
* complete).
*/
public final int getOldPosition() {
return mOldPosition;
}
/**
* Returns The itemId represented by this ViewHolder.
*
* @return The the item's id if adapter has stable ids, {@link RecyclerView#NO_ID}
* otherwise
*/
public final long getItemId() {
return mItemId;
}
/**
* @return The view type of this ViewHolder.
*/
public final int getItemViewType() {
return mItemViewType;
}
boolean isScrap() {
return mScrapContainer != null;
}
void unScrap() {
mScrapContainer.unscrapView(this);
}
boolean wasReturnedFromScrap() {
return (mFlags & FLAG_RETURNED_FROM_SCRAP) != 0;
}
void clearReturnedFromScrapFlag() {
mFlags = mFlags & ~FLAG_RETURNED_FROM_SCRAP;
}
void clearTmpDetachFlag() {
mFlags = mFlags & ~FLAG_TMP_DETACHED;
}
void stopIgnoring() {
mFlags = mFlags & ~FLAG_IGNORE;
}
void setScrapContainer(Recycler recycler) {
mScrapContainer = recycler;
}
boolean isInvalid() {
return (mFlags & FLAG_INVALID) != 0;
}
boolean needsUpdate() {
return (mFlags & FLAG_UPDATE) != 0;
}
boolean isChanged() {
return (mFlags & FLAG_CHANGED) != 0;
}
boolean isBound() {
return (mFlags & FLAG_BOUND) != 0;
}
boolean isRemoved() {
return (mFlags & FLAG_REMOVED) != 0;
}
boolean hasAnyOfTheFlags(int flags) {
return (mFlags & flags) != 0;
}
boolean isTmpDetached() {
return (mFlags & FLAG_TMP_DETACHED) != 0;
}
boolean isAdapterPositionUnknown() {
return (mFlags & FLAG_ADAPTER_POSITION_UNKNOWN) != 0 || isInvalid();
}
void setFlags(int flags, int mask) {
mFlags = (mFlags & ~mask) | (flags & mask);
}
void addFlags(int flags) {
mFlags |= flags;
}
void resetInternal() {
mFlags = 0;
mPosition = NO_POSITION;
mOldPosition = NO_POSITION;
mItemId = NO_ID;
mPreLayoutPosition = NO_POSITION;
mIsRecyclableCount = 0;
mShadowedHolder = null;
mShadowingHolder = null;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ViewHolder{" +
Integer.toHexString(hashCode()) + " position=" + mPosition + " id=" + mItemId +
", oldPos=" + mOldPosition + ", pLpos:" + mPreLayoutPosition);
if (isScrap()) sb.append(" scrap");
if (isInvalid()) sb.append(" invalid");
if (!isBound()) sb.append(" unbound");
if (needsUpdate()) sb.append(" update");
if (isRemoved()) sb.append(" removed");
if (shouldIgnore()) sb.append(" ignored");
if (isChanged()) sb.append(" changed");
if (isTmpDetached()) sb.append(" tmpDetached");
if (!isRecyclable()) sb.append(" not recyclable(" + mIsRecyclableCount + ")");
if (isAdapterPositionUnknown()) sb.append("undefined adapter position");
if (itemView.getParent() == null) sb.append(" no parent");
sb.append("}");
return sb.toString();
}
/**
* Informs the recycler whether this item can be recycled. Views which are not
* recyclable will not be reused for other items until setIsRecyclable() is
* later set to true. Calls to setIsRecyclable() should always be paired (one
* call to setIsRecyclabe(false) should always be matched with a later call to
* setIsRecyclable(true)). Pairs of calls may be nested, as the state is internally
* reference-counted.
*
* @param recyclable Whether this item is available to be recycled. Default value
* is true.
*/
public final void setIsRecyclable(boolean recyclable) {
mIsRecyclableCount = recyclable ? mIsRecyclableCount - 1 : mIsRecyclableCount + 1;
if (mIsRecyclableCount < 0) {
mIsRecyclableCount = 0;
if (DEBUG) {
throw new RuntimeException("isRecyclable decremented below 0: " +
"unmatched pair of setIsRecyable() calls for " + this);
}
Log.e(VIEW_LOG_TAG, "isRecyclable decremented below 0: " +
"unmatched pair of setIsRecyable() calls for " + this);
} else if (!recyclable && mIsRecyclableCount == 1) {
mFlags |= FLAG_NOT_RECYCLABLE;
} else if (recyclable && mIsRecyclableCount == 0) {
mFlags &= ~FLAG_NOT_RECYCLABLE;
}
if (DEBUG) {
Log.d(TAG, "setIsRecyclable val:" + recyclable + ":" + this);
}
}
/**
* @see {@link #setIsRecyclable(boolean)}
*
* @return true if this item is available to be recycled, false otherwise.
*/
public final boolean isRecyclable() {
return (mFlags & FLAG_NOT_RECYCLABLE) == 0 &&
!ViewCompat.hasTransientState(itemView);
}
/**
* Returns whether we have animations referring to this view holder or not.
* This is similar to isRecyclable flag but does not check transient state.
*/
private boolean shouldBeKeptAsChild() {
return (mFlags & FLAG_NOT_RECYCLABLE) != 0;
}
/**
* @return True if ViewHolder is not refenrenced by RecyclerView animations but has
* transient state which will prevent it from being recycled.
*/
private boolean doesTransientStatePreventRecycling() {
return (mFlags & FLAG_NOT_RECYCLABLE) == 0 && ViewCompat.hasTransientState(itemView);
}
}
private int getAdapterPositionFor(ViewHolder viewHolder) {
if (viewHolder.hasAnyOfTheFlags( ViewHolder.FLAG_INVALID |
ViewHolder.FLAG_REMOVED | ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN)
|| !viewHolder.isBound()) {
return RecyclerView.NO_POSITION;
}
return mAdapterHelper.applyPendingUpdatesToPosition(viewHolder.mPosition);
}
/**
* {@link android.view.ViewGroup.MarginLayoutParams LayoutParams} subclass for children of
* {@link RecyclerView}. Custom {@link LayoutManager layout managers} are encouraged
* to create their own subclass of this <code>LayoutParams</code> class
* to store any additional required per-child view metadata about the layout.
*/
public static class LayoutParams extends android.view.ViewGroup.MarginLayoutParams {
ViewHolder mViewHolder;
final Rect mDecorInsets = new Rect();
boolean mInsetsDirty = true;
// Flag is set to true if the view is bound while it is detached from RV.
// In this case, we need to manually call invalidate after view is added to guarantee that
// invalidation is populated through the View hierarchy
boolean mPendingInvalidate = false;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(LayoutParams source) {
super((ViewGroup.LayoutParams) source);
}
/**
* Returns true if the view this LayoutParams is attached to needs to have its content
* updated from the corresponding adapter.
*
* @return true if the view should have its content updated
*/
public boolean viewNeedsUpdate() {
return mViewHolder.needsUpdate();
}
/**
* Returns true if the view this LayoutParams is attached to is now representing
* potentially invalid data. A LayoutManager should scrap/recycle it.
*
* @return true if the view is invalid
*/
public boolean isViewInvalid() {
return mViewHolder.isInvalid();
}
/**
* Returns true if the adapter data item corresponding to the view this LayoutParams
* is attached to has been removed from the data set. A LayoutManager may choose to
* treat it differently in order to animate its outgoing or disappearing state.
*
* @return true if the item the view corresponds to was removed from the data set
*/
public boolean isItemRemoved() {
return mViewHolder.isRemoved();
}
/**
* Returns true if the adapter data item corresponding to the view this LayoutParams
* is attached to has been changed in the data set. A LayoutManager may choose to
* treat it differently in order to animate its changing state.
*
* @return true if the item the view corresponds to was changed in the data set
*/
public boolean isItemChanged() {
return mViewHolder.isChanged();
}
/**
* @deprecated use {@link #getViewLayoutPosition()} or {@link #getViewAdapterPosition()}
*/
public int getViewPosition() {
return mViewHolder.getPosition();
}
/**
* Returns the adapter position that the view this LayoutParams is attached to corresponds
* to as of latest layout calculation.
*
* @return the adapter position this view as of latest layout pass
*/
public int getViewLayoutPosition() {
return mViewHolder.getLayoutPosition();
}
/**
* Returns the up-to-date adapter position that the view this LayoutParams is attached to
* corresponds to.
*
* @return the up-to-date adapter position this view. It may return
* {@link RecyclerView#NO_POSITION} if item represented by this View has been removed or
* its up-to-date position cannot be calculated.
*/
public int getViewAdapterPosition() {
return mViewHolder.getAdapterPosition();
}
}
/**
* Observer base class for watching changes to an {@link Adapter}.
* See {@link Adapter#registerAdapterDataObserver(AdapterDataObserver)}.
*/
public static abstract class AdapterDataObserver {
public void onChanged() {
// Do nothing
}
public void onItemRangeChanged(int positionStart, int itemCount) {
// do nothing
}
public void onItemRangeInserted(int positionStart, int itemCount) {
// do nothing
}
public void onItemRangeRemoved(int positionStart, int itemCount) {
// do nothing
}
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
// do nothing
}
}
/**
* <p>Base class for smooth scrolling. Handles basic tracking of the target view position and
* provides methods to trigger a programmatic scroll.</p>
*
* @see LinearSmoothScroller
*/
public static abstract class SmoothScroller {
private int mTargetPosition = RecyclerView.NO_POSITION;
private RecyclerView mRecyclerView;
private LayoutManager mLayoutManager;
private boolean mPendingInitialRun;
private boolean mRunning;
private View mTargetView;
private final Action mRecyclingAction;
public SmoothScroller() {
mRecyclingAction = new Action(0, 0);
}
/**
* Starts a smooth scroll for the given target position.
* <p>In each animation step, {@link RecyclerView} will check
* for the target view and call either
* {@link #onTargetFound(android.view.View, RecyclerView.State, SmoothScroller.Action)} or
* {@link #onSeekTargetStep(int, int, RecyclerView.State, SmoothScroller.Action)} until
* SmoothScroller is stopped.</p>
*
* <p>Note that if RecyclerView finds the target view, it will automatically stop the
* SmoothScroller. This <b>does not</b> mean that scroll will stop, it only means it will
* stop calling SmoothScroller in each animation step.</p>
*/
void start(RecyclerView recyclerView, LayoutManager layoutManager) {
mRecyclerView = recyclerView;
mLayoutManager = layoutManager;
if (mTargetPosition == RecyclerView.NO_POSITION) {
throw new IllegalArgumentException("Invalid target position");
}
mRecyclerView.mState.mTargetPosition = mTargetPosition;
mRunning = true;
mPendingInitialRun = true;
mTargetView = findViewByPosition(getTargetPosition());
onStart();
mRecyclerView.mViewFlinger.postOnAnimation();
}
public void setTargetPosition(int targetPosition) {
mTargetPosition = targetPosition;
}
/**
* @return The LayoutManager to which this SmoothScroller is attached
*/
public LayoutManager getLayoutManager() {
return mLayoutManager;
}
/**
* Stops running the SmoothScroller in each animation callback. Note that this does not
* cancel any existing {@link Action} updated by
* {@link #onTargetFound(android.view.View, RecyclerView.State, SmoothScroller.Action)} or
* {@link #onSeekTargetStep(int, int, RecyclerView.State, SmoothScroller.Action)}.
*/
final protected void stop() {
if (!mRunning) {
return;
}
onStop();
mRecyclerView.mState.mTargetPosition = RecyclerView.NO_POSITION;
mTargetView = null;
mTargetPosition = RecyclerView.NO_POSITION;
mPendingInitialRun = false;
mRunning = false;
// trigger a cleanup
mLayoutManager.onSmoothScrollerStopped(this);
// clear references to avoid any potential leak by a custom smooth scroller
mLayoutManager = null;
mRecyclerView = null;
}
/**
* Returns true if SmoothScroller has been started but has not received the first
* animation
* callback yet.
*
* @return True if this SmoothScroller is waiting to start
*/
public boolean isPendingInitialRun() {
return mPendingInitialRun;
}
/**
* @return True if SmoothScroller is currently active
*/
public boolean isRunning() {
return mRunning;
}
/**
* Returns the adapter position of the target item
*
* @return Adapter position of the target item or
* {@link RecyclerView#NO_POSITION} if no target view is set.
*/
public int getTargetPosition() {
return mTargetPosition;
}
private void onAnimation(int dx, int dy) {
if (!mRunning || mTargetPosition == RecyclerView.NO_POSITION) {
stop();
}
mPendingInitialRun = false;
if (mTargetView != null) {
// verify target position
if (getChildPosition(mTargetView) == mTargetPosition) {
onTargetFound(mTargetView, mRecyclerView.mState, mRecyclingAction);
mRecyclingAction.runIfNecessary(mRecyclerView);
stop();
} else {
Log.e(TAG, "Passed over target position while smooth scrolling.");
mTargetView = null;
}
}
if (mRunning) {
onSeekTargetStep(dx, dy, mRecyclerView.mState, mRecyclingAction);
mRecyclingAction.runIfNecessary(mRecyclerView);
}
}
/**
* @see RecyclerView#getChildLayoutPosition(android.view.View)
*/
public int getChildPosition(View view) {
return mRecyclerView.getChildLayoutPosition(view);
}
/**
* @see RecyclerView.LayoutManager#getChildCount()
*/
public int getChildCount() {
return mRecyclerView.mLayout.getChildCount();
}
/**
* @see RecyclerView.LayoutManager#findViewByPosition(int)
*/
public View findViewByPosition(int position) {
return mRecyclerView.mLayout.findViewByPosition(position);
}
/**
* @see RecyclerView#scrollToPosition(int)
*/
public void instantScrollToPosition(int position) {
mRecyclerView.scrollToPosition(position);
}
protected void onChildAttachedToWindow(View child) {
if (getChildPosition(child) == getTargetPosition()) {
mTargetView = child;
if (DEBUG) {
Log.d(TAG, "smooth scroll target view has been attached");
}
}
}
/**
* Normalizes the vector.
* @param scrollVector The vector that points to the target scroll position
*/
protected void normalize(PointF scrollVector) {
final double magnitute = Math.sqrt(scrollVector.x * scrollVector.x + scrollVector.y *
scrollVector.y);
scrollVector.x /= magnitute;
scrollVector.y /= magnitute;
}
/**
* Called when smooth scroll is started. This might be a good time to do setup.
*/
abstract protected void onStart();
/**
* Called when smooth scroller is stopped. This is a good place to cleanup your state etc.
* @see #stop()
*/
abstract protected void onStop();
/**
* <p>RecyclerView will call this method each time it scrolls until it can find the target
* position in the layout.</p>
* <p>SmoothScroller should check dx, dy and if scroll should be changed, update the
* provided {@link Action} to define the next scroll.</p>
*
* @param dx Last scroll amount horizontally
* @param dy Last scroll amount verticaully
* @param state Transient state of RecyclerView
* @param action If you want to trigger a new smooth scroll and cancel the previous one,
* update this object.
*/
abstract protected void onSeekTargetStep(int dx, int dy, State state, Action action);
/**
* Called when the target position is laid out. This is the last callback SmoothScroller
* will receive and it should update the provided {@link Action} to define the scroll
* details towards the target view.
* @param targetView The view element which render the target position.
* @param state Transient state of RecyclerView
* @param action Action instance that you should update to define final scroll action
* towards the targetView
*/
abstract protected void onTargetFound(View targetView, State state, Action action);
/**
* Holds information about a smooth scroll request by a {@link SmoothScroller}.
*/
public static class Action {
public static final int UNDEFINED_DURATION = Integer.MIN_VALUE;
private int mDx;
private int mDy;
private int mDuration;
private Interpolator mInterpolator;
private boolean changed = false;
// we track this variable to inform custom implementer if they are updating the action
// in every animation callback
private int consecutiveUpdates = 0;
/**
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
*/
public Action(int dx, int dy) {
this(dx, dy, UNDEFINED_DURATION, null);
}
/**
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
* @param duration Duration of the animation in milliseconds
*/
public Action(int dx, int dy, int duration) {
this(dx, dy, duration, null);
}
/**
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
* @param duration Duration of the animation in milliseconds
* @param interpolator Interpolator to be used when calculating scroll position in each
* animation step
*/
public Action(int dx, int dy, int duration, Interpolator interpolator) {
mDx = dx;
mDy = dy;
mDuration = duration;
mInterpolator = interpolator;
}
private void runIfNecessary(RecyclerView recyclerView) {
if (changed) {
validate();
if (mInterpolator == null) {
if (mDuration == UNDEFINED_DURATION) {
recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy);
} else {
recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration);
}
} else {
recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration, mInterpolator);
}
consecutiveUpdates ++;
if (consecutiveUpdates > 10) {
// A new action is being set in every animation step. This looks like a bad
// implementation. Inform developer.
Log.e(TAG, "Smooth Scroll action is being updated too frequently. Make sure"
+ " you are not changing it unless necessary");
}
changed = false;
} else {
consecutiveUpdates = 0;
}
}
private void validate() {
if (mInterpolator != null && mDuration < 1) {
throw new IllegalStateException("If you provide an interpolator, you must"
+ " set a positive duration");
} else if (mDuration < 1) {
throw new IllegalStateException("Scroll duration must be a positive number");
}
}
public int getDx() {
return mDx;
}
public void setDx(int dx) {
changed = true;
mDx = dx;
}
public int getDy() {
return mDy;
}
public void setDy(int dy) {
changed = true;
mDy = dy;
}
public int getDuration() {
return mDuration;
}
public void setDuration(int duration) {
changed = true;
mDuration = duration;
}
public Interpolator getInterpolator() {
return mInterpolator;
}
/**
* Sets the interpolator to calculate scroll steps
* @param interpolator The interpolator to use. If you specify an interpolator, you must
* also set the duration.
* @see #setDuration(int)
*/
public void setInterpolator(Interpolator interpolator) {
changed = true;
mInterpolator = interpolator;
}
/**
* Updates the action with given parameters.
* @param dx Pixels to scroll horizontally
* @param dy Pixels to scroll vertically
* @param duration Duration of the animation in milliseconds
* @param interpolator Interpolator to be used when calculating scroll position in each
* animation step
*/
public void update(int dx, int dy, int duration, Interpolator interpolator) {
mDx = dx;
mDy = dy;
mDuration = duration;
mInterpolator = interpolator;
changed = true;
}
}
}
static class AdapterDataObservable extends Observable<AdapterDataObserver> {
public boolean hasObservers() {
return !mObservers.isEmpty();
}
public void notifyChanged() {
// since onChanged() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
}
public void notifyItemRangeChanged(int positionStart, int itemCount) {
// since onItemRangeChanged() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeChanged(positionStart, itemCount);
}
}
public void notifyItemRangeInserted(int positionStart, int itemCount) {
// since onItemRangeInserted() is implemented by the app, it could do anything,
// including removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeInserted(positionStart, itemCount);
}
}
public void notifyItemRangeRemoved(int positionStart, int itemCount) {
// since onItemRangeRemoved() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeRemoved(positionStart, itemCount);
}
}
public void notifyItemMoved(int fromPosition, int toPosition) {
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeMoved(fromPosition, toPosition, 1);
}
}
}
static class SavedState extends android.view.View.BaseSavedState {
Parcelable mLayoutState;
/**
* called by CREATOR
*/
SavedState(Parcel in) {
super(in);
mLayoutState = in.readParcelable(LayoutManager.class.getClassLoader());
}
/**
* Called by onSaveInstanceState
*/
SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeParcelable(mLayoutState, 0);
}
private void copyFrom(SavedState other) {
mLayoutState = other.mLayoutState;
}
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
/**
* <p>Contains useful information about the current RecyclerView state like target scroll
* position or view focus. State object can also keep arbitrary data, identified by resource
* ids.</p>
* <p>Often times, RecyclerView components will need to pass information between each other.
* To provide a well defined data bus between components, RecyclerView passes the same State
* object to component callbacks and these components can use it to exchange data.</p>
* <p>If you implement custom components, you can use State's put/get/remove methods to pass
* data between your components without needing to manage their lifecycles.</p>
*/
public static class State {
private int mTargetPosition = RecyclerView.NO_POSITION;
ArrayMap<ViewHolder, ItemHolderInfo> mPreLayoutHolderMap =
new ArrayMap<ViewHolder, ItemHolderInfo>();
ArrayMap<ViewHolder, ItemHolderInfo> mPostLayoutHolderMap =
new ArrayMap<ViewHolder, ItemHolderInfo>();
// nullable
ArrayMap<Long, ViewHolder> mOldChangedHolders = new ArrayMap<Long, ViewHolder>();
private SparseArray<Object> mData;
/**
* Number of items adapter has.
*/
int mItemCount = 0;
/**
* Number of items adapter had in the previous layout.
*/
private int mPreviousLayoutItemCount = 0;
/**
* Number of items that were NOT laid out but has been deleted from the adapter after the
* previous layout.
*/
private int mDeletedInvisibleItemCountSincePreviousLayout = 0;
private boolean mStructureChanged = false;
private boolean mInPreLayout = false;
private boolean mRunSimpleAnimations = false;
private boolean mRunPredictiveAnimations = false;
State reset() {
mTargetPosition = RecyclerView.NO_POSITION;
if (mData != null) {
mData.clear();
}
mItemCount = 0;
mStructureChanged = false;
return this;
}
public boolean isPreLayout() {
return mInPreLayout;
}
/**
* Returns whether RecyclerView will run predictive animations in this layout pass
* or not.
*
* @return true if RecyclerView is calculating predictive animations to be run at the end
* of the layout pass.
*/
public boolean willRunPredictiveAnimations() {
return mRunPredictiveAnimations;
}
/**
* Returns whether RecyclerView will run simple animations in this layout pass
* or not.
*
* @return true if RecyclerView is calculating simple animations to be run at the end of
* the layout pass.
*/
public boolean willRunSimpleAnimations() {
return mRunSimpleAnimations;
}
/**
* Removes the mapping from the specified id, if there was any.
* @param resourceId Id of the resource you want to remove. It is suggested to use R.id.* to
* preserve cross functionality and avoid conflicts.
*/
public void remove(int resourceId) {
if (mData == null) {
return;
}
mData.remove(resourceId);
}
/**
* Gets the Object mapped from the specified id, or <code>null</code>
* if no such data exists.
*
* @param resourceId Id of the resource you want to remove. It is suggested to use R.id.*
* to
* preserve cross functionality and avoid conflicts.
*/
public <T> T get(int resourceId) {
if (mData == null) {
return null;
}
return (T) mData.get(resourceId);
}
/**
* Adds a mapping from the specified id to the specified value, replacing the previous
* mapping from the specified key if there was one.
*
* @param resourceId Id of the resource you want to add. It is suggested to use R.id.* to
* preserve cross functionality and avoid conflicts.
* @param data The data you want to associate with the resourceId.
*/
public void put(int resourceId, Object data) {
if (mData == null) {
mData = new SparseArray<Object>();
}
mData.put(resourceId, data);
}
/**
* If scroll is triggered to make a certain item visible, this value will return the
* adapter index of that item.
* @return Adapter index of the target item or
* {@link RecyclerView#NO_POSITION} if there is no target
* position.
*/
public int getTargetScrollPosition() {
return mTargetPosition;
}
/**
* Returns if current scroll has a target position.
* @return true if scroll is being triggered to make a certain position visible
* @see #getTargetScrollPosition()
*/
public boolean hasTargetScrollPosition() {
return mTargetPosition != RecyclerView.NO_POSITION;
}
/**
* @return true if the structure of the data set has changed since the last call to
* onLayoutChildren, false otherwise
*/
public boolean didStructureChange() {
return mStructureChanged;
}
/**
* Returns the total number of items that can be laid out. Note that this number is not
* necessarily equal to the number of items in the adapter, so you should always use this
* number for your position calculations and never access the adapter directly.
* <p>
* RecyclerView listens for Adapter's notify events and calculates the effects of adapter
* data changes on existing Views. These calculations are used to decide which animations
* should be run.
* <p>
* To support predictive animations, RecyclerView may rewrite or reorder Adapter changes to
* present the correct state to LayoutManager in pre-layout pass.
* <p>
* For example, a newly added item is not included in pre-layout item count because
* pre-layout reflects the contents of the adapter before the item is added. Behind the
* scenes, RecyclerView offsets {@link Recycler#getViewForPosition(int)} calls such that
* LayoutManager does not know about the new item's existence in pre-layout. The item will
* be available in second layout pass and will be included in the item count. Similar
* adjustments are made for moved and removed items as well.
* <p>
* You can get the adapter's item count via {@link LayoutManager#getItemCount()} method.
*
* @return The number of items currently available
* @see LayoutManager#getItemCount()
*/
public int getItemCount() {
return mInPreLayout ?
(mPreviousLayoutItemCount - mDeletedInvisibleItemCountSincePreviousLayout) :
mItemCount;
}
void onViewRecycled(ViewHolder holder) {
mPreLayoutHolderMap.remove(holder);
mPostLayoutHolderMap.remove(holder);
if (mOldChangedHolders != null) {
removeFrom(mOldChangedHolders, holder);
}
// holder cannot be in new list.
}
public void onViewIgnored(ViewHolder holder) {
onViewRecycled(holder);
}
private void removeFrom(ArrayMap<Long, ViewHolder> holderMap, ViewHolder holder) {
for (int i = holderMap.size() - 1; i >= 0; i --) {
if (holder == holderMap.valueAt(i)) {
holderMap.removeAt(i);
return;
}
}
}
@Override
public String toString() {
return "State{" +
"mTargetPosition=" + mTargetPosition +
", mPreLayoutHolderMap=" + mPreLayoutHolderMap +
", mPostLayoutHolderMap=" + mPostLayoutHolderMap +
", mData=" + mData +
", mItemCount=" + mItemCount +
", mPreviousLayoutItemCount=" + mPreviousLayoutItemCount +
", mDeletedInvisibleItemCountSincePreviousLayout="
+ mDeletedInvisibleItemCountSincePreviousLayout +
", mStructureChanged=" + mStructureChanged +
", mInPreLayout=" + mInPreLayout +
", mRunSimpleAnimations=" + mRunSimpleAnimations +
", mRunPredictiveAnimations=" + mRunPredictiveAnimations +
'}';
}
}
/**
* Internal listener that manages items after animations finish. This is how items are
* retained (not recycled) during animations, but allowed to be recycled afterwards.
* It depends on the contract with the ItemAnimator to call the appropriate dispatch*Finished()
* method on the animator's listener when it is done animating any item.
*/
private class ItemAnimatorRestoreListener implements ItemAnimator.ItemAnimatorListener {
@Override
public void onRemoveFinished(ViewHolder item) {
item.setIsRecyclable(true);
if (!removeAnimatingView(item.itemView) && item.isTmpDetached()) {
removeDetachedView(item.itemView, false);
}
}
@Override
public void onAddFinished(ViewHolder item) {
item.setIsRecyclable(true);
if (!item.shouldBeKeptAsChild()) {
removeAnimatingView(item.itemView);
}
}
@Override
public void onMoveFinished(ViewHolder item) {
item.setIsRecyclable(true);
if (!item.shouldBeKeptAsChild()) {
removeAnimatingView(item.itemView);
}
}
@Override
public void onChangeFinished(ViewHolder item) {
item.setIsRecyclable(true);
/**
* We check both shadowed and shadowing because a ViewHolder may get both roles at the
* same time.
*
* Assume this flow:
* item X is represented by VH_1. Then itemX changes, so we create VH_2 .
* RV sets the following and calls item animator:
* VH_1.shadowed = VH_2;
* VH_1.mChanged = true;
* VH_2.shadowing =VH_1;
*
* Then, before the first change finishes, item changes again so we create VH_3.
* RV sets the following and calls item animator:
* VH_2.shadowed = VH_3
* VH_2.mChanged = true
* VH_3.shadowing = VH_2
*
* Because VH_2 already has an animation, it will be cancelled. At this point VH_2 has
* both shadowing and shadowed fields set. Shadowing information is obsolete now
* because the first animation where VH_2 is newViewHolder is not valid anymore.
* We ended up in this case because VH_2 played both roles. On the other hand,
* we DO NOT want to clear its changed flag.
*
* If second change was simply reverting first change, we would find VH_1 in
* {@link Recycler#getScrapViewForPosition(int, int, boolean)} and recycle it before
* re-using
*/
if (item.mShadowedHolder != null && item.mShadowingHolder == null) { // old vh
item.mShadowedHolder = null;
item.setFlags(~ViewHolder.FLAG_CHANGED, item.mFlags);
}
// always null this because an OldViewHolder can never become NewViewHolder w/o being
// recycled.
item.mShadowingHolder = null;
if (!item.shouldBeKeptAsChild()) {
removeAnimatingView(item.itemView);
}
}
};
/**
* This class defines the animations that take place on items as changes are made
* to the adapter.
*
* Subclasses of ItemAnimator can be used to implement custom animations for actions on
* ViewHolder items. The RecyclerView will manage retaining these items while they
* are being animated, but implementors must call the appropriate "Starting"
* ({@link #dispatchRemoveStarting(ViewHolder)}, {@link #dispatchMoveStarting(ViewHolder)},
* {@link #dispatchChangeStarting(ViewHolder, boolean)}, or
* {@link #dispatchAddStarting(ViewHolder)})
* and "Finished" ({@link #dispatchRemoveFinished(ViewHolder)},
* {@link #dispatchMoveFinished(ViewHolder)},
* {@link #dispatchChangeFinished(ViewHolder, boolean)},
* or {@link #dispatchAddFinished(ViewHolder)}) methods when each item animation is
* being started and ended.
*
* <p>By default, RecyclerView uses {@link DefaultItemAnimator}</p>
*
* @see #setItemAnimator(ItemAnimator)
*/
public static abstract class ItemAnimator {
private ItemAnimatorListener mListener = null;
private ArrayList<ItemAnimatorFinishedListener> mFinishedListeners =
new ArrayList<ItemAnimatorFinishedListener>();
private long mAddDuration = 120;
private long mRemoveDuration = 120;
private long mMoveDuration = 250;
private long mChangeDuration = 250;
private boolean mSupportsChangeAnimations = true;
/**
* Gets the current duration for which all move animations will run.
*
* @return The current move duration
*/
public long getMoveDuration() {
return mMoveDuration;
}
/**
* Sets the duration for which all move animations will run.
*
* @param moveDuration The move duration
*/
public void setMoveDuration(long moveDuration) {
mMoveDuration = moveDuration;
}
/**
* Gets the current duration for which all add animations will run.
*
* @return The current add duration
*/
public long getAddDuration() {
return mAddDuration;
}
/**
* Sets the duration for which all add animations will run.
*
* @param addDuration The add duration
*/
public void setAddDuration(long addDuration) {
mAddDuration = addDuration;
}
/**
* Gets the current duration for which all remove animations will run.
*
* @return The current remove duration
*/
public long getRemoveDuration() {
return mRemoveDuration;
}
/**
* Sets the duration for which all remove animations will run.
*
* @param removeDuration The remove duration
*/
public void setRemoveDuration(long removeDuration) {
mRemoveDuration = removeDuration;
}
/**
* Gets the current duration for which all change animations will run.
*
* @return The current change duration
*/
public long getChangeDuration() {
return mChangeDuration;
}
/**
* Sets the duration for which all change animations will run.
*
* @param changeDuration The change duration
*/
public void setChangeDuration(long changeDuration) {
mChangeDuration = changeDuration;
}
/**
* Returns whether this ItemAnimator supports animations of change events.
*
* @return true if change animations are supported, false otherwise
*/
public boolean getSupportsChangeAnimations() {
return mSupportsChangeAnimations;
}
/**
* Sets whether this ItemAnimator supports animations of item change events.
* If you set this property to false, actions on the data set which change the
* contents of items will not be animated. What those animations are is left
* up to the discretion of the ItemAnimator subclass, in its
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} implementation.
* The value of this property is true by default.
*
* @see Adapter#notifyItemChanged(int)
* @see Adapter#notifyItemRangeChanged(int, int)
*
* @param supportsChangeAnimations true if change animations are supported by
* this ItemAnimator, false otherwise. If the property is false, the ItemAnimator
* will not receive a call to
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} when changes occur.
*/
public void setSupportsChangeAnimations(boolean supportsChangeAnimations) {
mSupportsChangeAnimations = supportsChangeAnimations;
}
/**
* Internal only:
* Sets the listener that must be called when the animator is finished
* animating the item (or immediately if no animation happens). This is set
* internally and is not intended to be set by external code.
*
* @param listener The listener that must be called.
*/
void setListener(ItemAnimatorListener listener) {
mListener = listener;
}
/**
* Called when there are pending animations waiting to be started. This state
* is governed by the return values from {@link #animateAdd(ViewHolder) animateAdd()},
* {@link #animateMove(ViewHolder, int, int, int, int) animateMove()}, and
* {@link #animateRemove(ViewHolder) animateRemove()}, which inform the
* RecyclerView that the ItemAnimator wants to be called later to start the
* associated animations. runPendingAnimations() will be scheduled to be run
* on the next frame.
*/
abstract public void runPendingAnimations();
/**
* Called when an item is removed from the RecyclerView. Implementors can choose
* whether and how to animate that change, but must always call
* {@link #dispatchRemoveFinished(ViewHolder)} when done, either
* immediately (if no animation will occur) or after the animation actually finishes.
* The return value indicates whether an animation has been set up and whether the
* ItemAnimator's {@link #runPendingAnimations()} method should be called at the
* next opportunity. This mechanism allows ItemAnimator to set up individual animations
* as separate calls to {@link #animateAdd(ViewHolder) animateAdd()},
* {@link #animateMove(ViewHolder, int, int, int, int) animateMove()},
* {@link #animateRemove(ViewHolder) animateRemove()}, and
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} come in one by one,
* then start the animations together in the later call to {@link #runPendingAnimations()}.
*
* <p>This method may also be called for disappearing items which continue to exist in the
* RecyclerView, but for which the system does not have enough information to animate
* them out of view. In that case, the default animation for removing items is run
* on those items as well.</p>
*
* @param holder The item that is being removed.
* @return true if a later call to {@link #runPendingAnimations()} is requested,
* false otherwise.
*/
abstract public boolean animateRemove(ViewHolder holder);
/**
* Called when an item is added to the RecyclerView. Implementors can choose
* whether and how to animate that change, but must always call
* {@link #dispatchAddFinished(ViewHolder)} when done, either
* immediately (if no animation will occur) or after the animation actually finishes.
* The return value indicates whether an animation has been set up and whether the
* ItemAnimator's {@link #runPendingAnimations()} method should be called at the
* next opportunity. This mechanism allows ItemAnimator to set up individual animations
* as separate calls to {@link #animateAdd(ViewHolder) animateAdd()},
* {@link #animateMove(ViewHolder, int, int, int, int) animateMove()},
* {@link #animateRemove(ViewHolder) animateRemove()}, and
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} come in one by one,
* then start the animations together in the later call to {@link #runPendingAnimations()}.
*
* <p>This method may also be called for appearing items which were already in the
* RecyclerView, but for which the system does not have enough information to animate
* them into view. In that case, the default animation for adding items is run
* on those items as well.</p>
*
* @param holder The item that is being added.
* @return true if a later call to {@link #runPendingAnimations()} is requested,
* false otherwise.
*/
abstract public boolean animateAdd(ViewHolder holder);
/**
* Called when an item is moved in the RecyclerView. Implementors can choose
* whether and how to animate that change, but must always call
* {@link #dispatchMoveFinished(ViewHolder)} when done, either
* immediately (if no animation will occur) or after the animation actually finishes.
* The return value indicates whether an animation has been set up and whether the
* ItemAnimator's {@link #runPendingAnimations()} method should be called at the
* next opportunity. This mechanism allows ItemAnimator to set up individual animations
* as separate calls to {@link #animateAdd(ViewHolder) animateAdd()},
* {@link #animateMove(ViewHolder, int, int, int, int) animateMove()},
* {@link #animateRemove(ViewHolder) animateRemove()}, and
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} come in one by one,
* then start the animations together in the later call to {@link #runPendingAnimations()}.
*
* @param holder The item that is being moved.
* @return true if a later call to {@link #runPendingAnimations()} is requested,
* false otherwise.
*/
abstract public boolean animateMove(ViewHolder holder, int fromX, int fromY,
int toX, int toY);
/**
* Called when an item is changed in the RecyclerView, as indicated by a call to
* {@link Adapter#notifyItemChanged(int)} or
* {@link Adapter#notifyItemRangeChanged(int, int)}.
* <p>
* Implementers can choose whether and how to animate changes, but must always call
* {@link #dispatchChangeFinished(ViewHolder, boolean)} for each non-null ViewHolder,
* either immediately (if no animation will occur) or after the animation actually finishes.
* The return value indicates whether an animation has been set up and whether the
* ItemAnimator's {@link #runPendingAnimations()} method should be called at the
* next opportunity. This mechanism allows ItemAnimator to set up individual animations
* as separate calls to {@link #animateAdd(ViewHolder) animateAdd()},
* {@link #animateMove(ViewHolder, int, int, int, int) animateMove()},
* {@link #animateRemove(ViewHolder) animateRemove()}, and
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} come in one by one,
* then start the animations together in the later call to {@link #runPendingAnimations()}.
*
* @param oldHolder The original item that changed.
* @param newHolder The new item that was created with the changed content. Might be null
* @param fromLeft Left of the old view holder
* @param fromTop Top of the old view holder
* @param toLeft Left of the new view holder
* @param toTop Top of the new view holder
* @return true if a later call to {@link #runPendingAnimations()} is requested,
* false otherwise.
*/
abstract public boolean animateChange(ViewHolder oldHolder,
ViewHolder newHolder, int fromLeft, int fromTop, int toLeft, int toTop);
/**
* Method to be called by subclasses when a remove animation is done.
*
* @param item The item which has been removed
*/
public final void dispatchRemoveFinished(ViewHolder item) {
onRemoveFinished(item);
if (mListener != null) {
mListener.onRemoveFinished(item);
}
}
/**
* Method to be called by subclasses when a move animation is done.
*
* @param item The item which has been moved
*/
public final void dispatchMoveFinished(ViewHolder item) {
onMoveFinished(item);
if (mListener != null) {
mListener.onMoveFinished(item);
}
}
/**
* Method to be called by subclasses when an add animation is done.
*
* @param item The item which has been added
*/
public final void dispatchAddFinished(ViewHolder item) {
onAddFinished(item);
if (mListener != null) {
mListener.onAddFinished(item);
}
}
/**
* Method to be called by subclasses when a change animation is done.
*
* @see #animateChange(ViewHolder, ViewHolder, int, int, int, int)
* @param item The item which has been changed (this method must be called for
* each non-null ViewHolder passed into
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)}).
* @param oldItem true if this is the old item that was changed, false if
* it is the new item that replaced the old item.
*/
public final void dispatchChangeFinished(ViewHolder item, boolean oldItem) {
onChangeFinished(item, oldItem);
if (mListener != null) {
mListener.onChangeFinished(item);
}
}
/**
* Method to be called by subclasses when a remove animation is being started.
*
* @param item The item being removed
*/
public final void dispatchRemoveStarting(ViewHolder item) {
onRemoveStarting(item);
}
/**
* Method to be called by subclasses when a move animation is being started.
*
* @param item The item being moved
*/
public final void dispatchMoveStarting(ViewHolder item) {
onMoveStarting(item);
}
/**
* Method to be called by subclasses when an add animation is being started.
*
* @param item The item being added
*/
public final void dispatchAddStarting(ViewHolder item) {
onAddStarting(item);
}
/**
* Method to be called by subclasses when a change animation is being started.
*
* @param item The item which has been changed (this method must be called for
* each non-null ViewHolder passed into
* {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)}).
* @param oldItem true if this is the old item that was changed, false if
* it is the new item that replaced the old item.
*/
public final void dispatchChangeStarting(ViewHolder item, boolean oldItem) {
onChangeStarting(item, oldItem);
}
/**
* Method called when an animation on a view should be ended immediately.
* This could happen when other events, like scrolling, occur, so that
* animating views can be quickly put into their proper end locations.
* Implementations should ensure that any animations running on the item
* are canceled and affected properties are set to their end values.
* Also, appropriate dispatch methods (e.g., {@link #dispatchAddFinished(ViewHolder)}
* should be called since the animations are effectively done when this
* method is called.
*
* @param item The item for which an animation should be stopped.
*/
abstract public void endAnimation(ViewHolder item);
/**
* Method called when all item animations should be ended immediately.
* This could happen when other events, like scrolling, occur, so that
* animating views can be quickly put into their proper end locations.
* Implementations should ensure that any animations running on any items
* are canceled and affected properties are set to their end values.
* Also, appropriate dispatch methods (e.g., {@link #dispatchAddFinished(ViewHolder)}
* should be called since the animations are effectively done when this
* method is called.
*/
abstract public void endAnimations();
/**
* Method which returns whether there are any item animations currently running.
* This method can be used to determine whether to delay other actions until
* animations end.
*
* @return true if there are any item animations currently running, false otherwise.
*/
abstract public boolean isRunning();
/**
* Like {@link #isRunning()}, this method returns whether there are any item
* animations currently running. Addtionally, the listener passed in will be called
* when there are no item animations running, either immediately (before the method
* returns) if no animations are currently running, or when the currently running
* animations are {@link #dispatchAnimationsFinished() finished}.
*
* <p>Note that the listener is transient - it is either called immediately and not
* stored at all, or stored only until it is called when running animations
* are finished sometime later.</p>
*
* @param listener A listener to be called immediately if no animations are running
* or later when currently-running animations have finished. A null listener is
* equivalent to calling {@link #isRunning()}.
* @return true if there are any item animations currently running, false otherwise.
*/
public final boolean isRunning(ItemAnimatorFinishedListener listener) {
boolean running = isRunning();
if (listener != null) {
if (!running) {
listener.onAnimationsFinished();
} else {
mFinishedListeners.add(listener);
}
}
return running;
}
/**
* The interface to be implemented by listeners to animation events from this
* ItemAnimator. This is used internally and is not intended for developers to
* create directly.
*/
interface ItemAnimatorListener {
void onRemoveFinished(ViewHolder item);
void onAddFinished(ViewHolder item);
void onMoveFinished(ViewHolder item);
void onChangeFinished(ViewHolder item);
}
/**
* This method should be called by ItemAnimator implementations to notify
* any listeners that all pending and active item animations are finished.
*/
public final void dispatchAnimationsFinished() {
final int count = mFinishedListeners.size();
for (int i = 0; i < count; ++i) {
mFinishedListeners.get(i).onAnimationsFinished();
}
mFinishedListeners.clear();
}
/**
* This interface is used to inform listeners when all pending or running animations
* in an ItemAnimator are finished. This can be used, for example, to delay an action
* in a data set until currently-running animations are complete.
*
* @see #isRunning(ItemAnimatorFinishedListener)
*/
public interface ItemAnimatorFinishedListener {
void onAnimationsFinished();
}
/**
* Called when a remove animation is being started on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
*/
public void onRemoveStarting(ViewHolder item) {}
/**
* Called when a remove animation has ended on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
*/
public void onRemoveFinished(ViewHolder item) {}
/**
* Called when an add animation is being started on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
*/
public void onAddStarting(ViewHolder item) {}
/**
* Called when an add animation has ended on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
*/
public void onAddFinished(ViewHolder item) {}
/**
* Called when a move animation is being started on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
*/
public void onMoveStarting(ViewHolder item) {}
/**
* Called when a move animation has ended on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
*/
public void onMoveFinished(ViewHolder item) {}
/**
* Called when a change animation is being started on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
* @param oldItem true if this is the old item that was changed, false if
* it is the new item that replaced the old item.
*/
public void onChangeStarting(ViewHolder item, boolean oldItem) {}
/**
* Called when a change animation has ended on the given ViewHolder.
* The default implementation does nothing. Subclasses may wish to override
* this method to handle any ViewHolder-specific operations linked to animation
* lifecycles.
*
* @param item The ViewHolder being animated.
* @param oldItem true if this is the old item that was changed, false if
* it is the new item that replaced the old item.
*/
public void onChangeFinished(ViewHolder item, boolean oldItem) {}
}
/**
* Internal data structure that holds information about an item's bounds.
* This information is used in calculating item animations.
*/
private static class ItemHolderInfo {
ViewHolder holder;
int left, top, right, bottom;
ItemHolderInfo(ViewHolder holder, int left, int top, int right, int bottom) {
this.holder = holder;
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
}
}
|
am b5c90343: am 9eff2102: Merge "Handle sub view focus in RecyclerView" into lmp-mr1-ub-dev
* commit 'b5c90343d80408973aef96512747cb77ccf62e65':
Handle sub view focus in RecyclerView
|
v7/recyclerview/src/android/support/v7/widget/RecyclerView.java
|
am b5c90343: am 9eff2102: Merge "Handle sub view focus in RecyclerView" into lmp-mr1-ub-dev
|
|
Java
|
apache-2.0
|
e1714ff521a490b629859e73844e76f38a35ccc6
| 0
|
khuxtable/seaglass,archit47/seaglass
|
/*
* Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
*
* This file is part of the SeaGlass Pluggable Look and Feel.
*
* 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.
*
* $Id$
*/
package com.seaglasslookandfeel.painter;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import com.seaglasslookandfeel.painter.AbstractRegionPainter.PaintContext.CacheMode;
/**
* ToolBarPainter implementation.
*
* Parts taken from Nimbus to draw drag handle.
*
* @author Ken Orr
* @author Modified by Kathryn Huxtable for SeaGlass
*/
public class ToolBarPainter extends AbstractRegionPainter {
public static enum Which {
BORDER_ENABLED,
};
private PaintContext ctx;
public ToolBarPainter(Which state) {
super();
this.ctx = new PaintContext(CacheMode.NO_CACHING);
}
protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) {
}
protected PaintContext getPaintContext() {
return ctx;
}
}
|
seaglass/trunk/seaglass/src/main/java/com/seaglasslookandfeel/painter/ToolBarPainter.java
|
/*
* Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
*
* This file is part of the SeaGlass Pluggable Look and Feel.
*
* 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.
*
* $Id$
*/
package com.seaglasslookandfeel.painter;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import com.seaglasslookandfeel.painter.AbstractRegionPainter.PaintContext.CacheMode;
import com.seaglasslookandfeel.state.State;
import com.seaglasslookandfeel.state.ToolBarHasNorthToolBarState;
import com.seaglasslookandfeel.util.PlatformUtils;
/**
* ToolBarPainter implementation.
*
* Parts taken from Nimbus to draw drag handle.
*
* @author Ken Orr
* @author Modified by Kathryn Huxtable for SeaGlass
*/
public class ToolBarPainter extends AbstractRegionPainter {
public static enum Which {
BORDER_NORTH,
BORDER_SOUTH,
BORDER_EAST,
BORDER_WEST,
BORDER_NORTH_ENABLED,
BORDER_SOUTH_ENABLED,
BORDER_EAST_ENABLED,
BORDER_WEST_ENABLED,
};
private Color ACTIVE_TOP_COLOR_T = decodeColor("seaGlassToolBarActiveTopT");
private Color ACTIVE_TOP_COLOR_B = decodeColor("seaGlassToolBarActiveTopB");
private Color INACTIVE_TOP_COLOR_T = decodeColor("seaGlassToolBarInactiveTopT");
private Color INACTIVE_TOP_COLOR_B = decodeColor("seaGlassToolBarInactiveTopB");
private Color ACTIVE_BOTTOM_COLOR_T = decodeColor("seaGlassToolBarActiveBottomT");
private Color ACTIVE_BOTTOM_COLOR_B = decodeColor("seaGlassToolBarActiveBottomB");
private Color INACTIVE_BOTTOM_COLOR_T = decodeColor("seaGlassToolBarInactiveBottomT");
private Color INACTIVE_BOTTOM_COLOR_B = decodeColor("seaGlassToolBarInactiveBottomB");
private static final State hasNorthToolBarState = new ToolBarHasNorthToolBarState();
// Refers to one of the static final ints above
private Which state;
private PaintContext ctx;
public ToolBarPainter(Which state) {
super();
this.state = state;
this.ctx = new PaintContext(CacheMode.NO_CACHING);
}
protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) {
if (PlatformUtils.isMac()) {
paintBackground(g, c, width, height);
}
}
protected PaintContext getPaintContext() {
return ctx;
}
private void paintBackground(Graphics2D g, JComponent c, int width, int height) {
g.setPaint(decodeGradient(state, c, width, height));
g.fillRect(0, 0, width, height);
}
private GradientPaint decodeGradient(Which state, JComponent c, int width, int height) {
switch (state) {
case BORDER_NORTH:
case BORDER_NORTH_ENABLED:
case BORDER_SOUTH:
case BORDER_SOUTH_ENABLED:
return new GradientPaint(0, 0, getTopColor(state, null), 0, height, getBottomColor(state));
case BORDER_EAST:
case BORDER_EAST_ENABLED:
case BORDER_WEST:
case BORDER_WEST_ENABLED:
return new GradientPaint(0, 0, getTopColor(state, c), width, 0, getBottomColor(state));
}
return null;
}
private Color getTopColor(Which state, JComponent c) {
switch (state) {
case BORDER_NORTH:
return INACTIVE_TOP_COLOR_T;
case BORDER_SOUTH:
return INACTIVE_BOTTOM_COLOR_T;
case BORDER_EAST:
case BORDER_WEST:
if (hasNorthToolBarState.isInState(c)) {
return INACTIVE_TOP_COLOR_B;
}
return INACTIVE_TOP_COLOR_T;
case BORDER_NORTH_ENABLED:
return ACTIVE_TOP_COLOR_T;
case BORDER_SOUTH_ENABLED:
return ACTIVE_BOTTOM_COLOR_T;
case BORDER_EAST_ENABLED:
case BORDER_WEST_ENABLED:
if (hasNorthToolBarState.isInState(c)) {
return ACTIVE_TOP_COLOR_B;
}
return ACTIVE_TOP_COLOR_T;
}
return ACTIVE_TOP_COLOR_T;
}
private Color getBottomColor(Which state) {
switch (state) {
case BORDER_NORTH:
return INACTIVE_TOP_COLOR_B;
case BORDER_SOUTH:
return INACTIVE_BOTTOM_COLOR_B;
case BORDER_EAST:
case BORDER_WEST:
return INACTIVE_BOTTOM_COLOR_T;
case BORDER_NORTH_ENABLED:
return ACTIVE_TOP_COLOR_B;
case BORDER_SOUTH_ENABLED:
return ACTIVE_BOTTOM_COLOR_B;
case BORDER_EAST_ENABLED:
case BORDER_WEST_ENABLED:
return ACTIVE_BOTTOM_COLOR_T;
}
return ACTIVE_TOP_COLOR_B;
}
}
|
It turns out that we never want to paint a toolbar. Just let the background show through.
|
seaglass/trunk/seaglass/src/main/java/com/seaglasslookandfeel/painter/ToolBarPainter.java
|
It turns out that we never want to paint a toolbar. Just let the background show through.
|
|
Java
|
apache-2.0
|
025666ab9166803448272e60e1531af70b9aeb35
| 0
|
GoogleCloudPlatform/gcloud-maven-plugin,GoogleCloudPlatform/gcloud-maven-plugin,GoogleCloudPlatform/gcloud-maven-plugin
|
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*/
package com.google.appengine;
import java.io.File;
/**
*
* @author ludo
*/
public class Utils {
public static String getPythonExecutableLocation() {
String pythonLocation = "python"; //default in the path for Linux
boolean isWindows = System.getProperty("os.name").contains("Windows");
if (isWindows) {
pythonLocation = System.getenv("CLOUDSDK_PYTHON");
if (pythonLocation == null) {
// getLog().info("CLOUDSDK_PYTHON env variable is not defined. Choosing a default python.exe interpreter.");
// getLog().info("If this does not work, please set CLOUDSDK_PYTHON to a correct Python interpreter location.");
pythonLocation = "python.exe";
}
} else {
String possibleLinuxPythonLocation = System.getenv("CLOUDSDK_PYTHON");
if (possibleLinuxPythonLocation != null) {
// getLog().info("Found a python interpreter specified via CLOUDSDK_PYTHON at: " + possibleLinuxPythonLocation);
pythonLocation = possibleLinuxPythonLocation;
}
}
return pythonLocation;
}
public static String getCloudSDKLocation() {
String gcloudDir;
boolean isWindows = System.getProperty("os.name").contains("Windows");
if (isWindows) {
String relPath= "\\Google\\Cloud SDK\\google-cloud-sdk";
// first look for user installation under "LOCALAPPDATA"
String localSDK = System.getenv("LOCALAPPDATA") + relPath;
if (new File(localSDK).exists()) {
return localSDK;
}
// then look for globally installed Cloud SDK:
String programFiles = System.getenv("ProgramFiles");
if (programFiles == null) {
programFiles = System.getenv("ProgramFiles(x86)");
}
if (programFiles == null) {
gcloudDir = "cannotFindProgramFiles";
} else {
gcloudDir = programFiles + relPath;
}
} else {
gcloudDir = System.getProperty("user.home") + "/google-cloud-sdk";
if (!new File(gcloudDir).exists()) {
// try devshell VM:
gcloudDir = "/google/google-cloud-sdk";
if (!new File(gcloudDir).exists()) {
// try bitnani Jenkins VM:
gcloudDir = "/usr/local/share/google/google-cloud-sdk";
}
}
}
return gcloudDir;
}
/**
* Checks if either CLOUDSDK_PYTHON_SITEPACKAGES or VIRTUAL_ENV is defined.
*
* <p> If either variable is defined, we shall not disable import of module
* 'site.
*
* @return true if it is OK to disable import of module 'site' (python -S)
*/
public static boolean canDisableImportOfPythonModuleSite() {
String sitePackages = System.getenv("CLOUDSDK_PYTHON_SITEPACKAGES");
String virtualEnv = System.getenv("VIRTUAL_ENV");
boolean noSiteDefined = sitePackages == null || sitePackages.isEmpty();
boolean noVirtEnvDefined = virtualEnv == null || virtualEnv.isEmpty();
if (noSiteDefined && noVirtEnvDefined) {
return true;
}
return false;
}
}
|
src/main/java/com/google/appengine/Utils.java
|
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*/
package com.google.appengine;
import java.io.File;
/**
*
* @author ludo
*/
public class Utils {
public static String getPythonExecutableLocation() {
String pythonLocation = "python"; //default in the path for Linux
boolean isWindows = System.getProperty("os.name").contains("Windows");
if (isWindows) {
pythonLocation = System.getenv("CLOUDSDK_PYTHON");
if (pythonLocation == null) {
// getLog().info("CLOUDSDK_PYTHON env variable is not defined. Choosing a default python.exe interpreter.");
// getLog().info("If this does not work, please set CLOUDSDK_PYTHON to a correct Python interpreter location.");
pythonLocation = "python.exe";
}
} else {
String possibleLinuxPythonLocation = System.getenv("CLOUDSDK_PYTHON");
if (possibleLinuxPythonLocation != null) {
// getLog().info("Found a python interpreter specified via CLOUDSDK_PYTHON at: " + possibleLinuxPythonLocation);
pythonLocation = possibleLinuxPythonLocation;
}
}
return pythonLocation;
}
public static String getCloudSDKLocation() {
String gcloudDir;
boolean isWindows = System.getProperty("os.name").contains("Windows");
if (isWindows) {
String programFiles = System.getenv("ProgramFiles");
if (programFiles == null) {
programFiles = System.getenv("ProgramFiles(x86)");
}
if (programFiles == null) {
gcloudDir = "cannotFindProgramFiles";
} else {
gcloudDir = programFiles + "\\Google\\Cloud SDK\\google-cloud-sdk";
}
} else {
gcloudDir = System.getProperty("user.home") + "/google-cloud-sdk";
if (!new File(gcloudDir).exists()) {
// try devshell VM:
gcloudDir = "/google/google-cloud-sdk";
if (!new File(gcloudDir).exists()) {
// try bitnani Jenkins VM:
gcloudDir = "/usr/local/share/google/google-cloud-sdk";
}
}
}
return gcloudDir;
}
/**
* Checks if either CLOUDSDK_PYTHON_SITEPACKAGES or VIRTUAL_ENV is defined.
*
* <p> If either variable is defined, we shall not disable import of module
* 'site.
*
* @return true if it is OK to disable import of module 'site' (python -S)
*/
public static boolean canDisableImportOfPythonModuleSite() {
String sitePackages = System.getenv("CLOUDSDK_PYTHON_SITEPACKAGES");
String virtualEnv = System.getenv("VIRTUAL_ENV");
boolean noSiteDefined = sitePackages == null || sitePackages.isEmpty();
boolean noVirtEnvDefined = virtualEnv == null || virtualEnv.isEmpty();
if (noSiteDefined && noVirtEnvDefined) {
return true;
}
return false;
}
}
|
Handles new local installation of the Cloud SDK on Windows OS.
|
src/main/java/com/google/appengine/Utils.java
|
Handles new local installation of the Cloud SDK on Windows OS.
|
|
Java
|
apache-2.0
|
8d3141d7dcba7be4a711fd3f5c423aa73f9d0db8
| 0
|
mingsong/GearVRf,nathan-almeida/GearVRf,mwitchwilliams/GearVRf,ragner/GearVRf,douglasalipio/GearVRf,bsmr-android/GearVRf,luxiaoming/GearVRf,noname007/GearVRf,parthmehta209/GearVRf,phi-lira/GearVRf,roshanch/GearVRf,xiechengen/GearVRf,danke-sra/GearVRf,chenchao1407/GearVRf,rahul27/GearVRf,xcaostagit/GearVRf,gaurav-mcl/GearVRf,xiechengen/GearVRf,rodrigodzf/GearVRf,lassehe/GearVRf,rongguodong/GearVRf,nidstang/GearVRf,rahul27/GearVRf,KolorCompany/GearVRf,rongguodong/GearVRf,parthmehta209/GearVRf,phi-lira/GearVRf,gaurav-mcl/GearVRf,mingsong/GearVRf,KolorCompany/GearVRf,xcaostagit/GearVRf,aglne/GearVRf,lassehe/GearVRf,ragner/GearVRf,thomasflynn/GearVRf,Samsung/GearVRf,gaurav-mcl/GearVRf,luxiaoming/GearVRf,mwitchwilliams/GearVRf,thomasflynn/GearVRf,nidstang/GearVRf,roshanch/GearVRf,KolorCompany/GearVRf,noname007/GearVRf,douglasalipio/GearVRf,dattanand/GearVRf,xcaostagit/GearVRf,aglne/GearVRf,nidstang/GearVRf,rongguodong/GearVRf,rongguodong/GearVRf,danke-sra/GearVRf,xcaostagit/GearVRf,NolaDonato/GearVRf,chenchao1407/GearVRf,phi-lira/GearVRf,Maginador/GearVRf,nathan-almeida/GearVRf,rahul27/GearVRf,parthmehta209/GearVRf,phi-lira/GearVRf,luxiaoming/GearVRf,luxiaoming/GearVRf,rongguodong/GearVRf,douglasalipio/GearVRf,noname007/GearVRf,douglasalipio/GearVRf,Maginador/GearVRf,danke-sra/GearVRf,rodrigodzf/GearVRf,parthmehta209/GearVRf,rahul27/GearVRf,noname007/GearVRf,mwitchwilliams/GearVRf,dattanand/GearVRf,thomasflynn/GearVRf,ragner/GearVRf,chenchao1407/GearVRf,Samsung/GearVRf,thomasflynn/GearVRf,rongguodong/GearVRf,chenchao1407/GearVRf,luxiaoming/GearVRf,aglne/GearVRf,KolorCompany/GearVRf,bsmr-android/GearVRf,NolaDonato/GearVRf,dattanand/GearVRf,NolaDonato/GearVRf,xiechengen/GearVRf,gaurav-mcl/GearVRf,xcaostagit/GearVRf,Samsung/GearVRf,Maginador/GearVRf,gaurav-mcl/GearVRf,thomasflynn/GearVRf,xcaostagit/GearVRf,xiechengen/GearVRf,aglne/GearVRf,nathan-almeida/GearVRf,xiechengen/GearVRf,NolaDonato/GearVRf,Maginador/GearVRf,roshanch/GearVRf,KolorCompany/GearVRf,aglne/GearVRf,rodrigodzf/GearVRf,ragner/GearVRf,bsmr-android/GearVRf,rahul27/GearVRf,luxiaoming/GearVRf,rodrigodzf/GearVRf,Maginador/GearVRf,gaurav-mcl/GearVRf,mwitchwilliams/GearVRf,rodrigodzf/GearVRf,dattanand/GearVRf,douglasalipio/GearVRf,luxiaoming/GearVRf,nidstang/GearVRf,bsmr-android/GearVRf,lassehe/GearVRf,rodrigodzf/GearVRf,noname007/GearVRf,NolaDonato/GearVRf,nidstang/GearVRf,gaurav-mcl/GearVRf,gaurav-mcl/GearVRf,aglne/GearVRf,nathan-almeida/GearVRf,rodrigodzf/GearVRf,rahul27/GearVRf,rodrigodzf/GearVRf,chenchao1407/GearVRf,mingsong/GearVRf,chenchao1407/GearVRf,nidstang/GearVRf,xiechengen/GearVRf,KolorCompany/GearVRf,Maginador/GearVRf,mingsong/GearVRf,chenchao1407/GearVRf,Samsung/GearVRf,Maginador/GearVRf,lassehe/GearVRf,ragner/GearVRf,phi-lira/GearVRf,roshanch/GearVRf,dattanand/GearVRf,xiechengen/GearVRf,luxiaoming/GearVRf,noname007/GearVRf,aglne/GearVRf,ragner/GearVRf,mingsong/GearVRf,thomasflynn/GearVRf,bsmr-android/GearVRf,thomasflynn/GearVRf,rongguodong/GearVRf,nathan-almeida/GearVRf,KolorCompany/GearVRf,Maginador/GearVRf,KolorCompany/GearVRf,noname007/GearVRf,Samsung/GearVRf,mwitchwilliams/GearVRf,nidstang/GearVRf,lassehe/GearVRf,chenchao1407/GearVRf,NolaDonato/GearVRf,nidstang/GearVRf,aglne/GearVRf,phi-lira/GearVRf,parthmehta209/GearVRf,Samsung/GearVRf,danke-sra/GearVRf,danke-sra/GearVRf,douglasalipio/GearVRf,nathan-almeida/GearVRf,bsmr-android/GearVRf,mingsong/GearVRf,dattanand/GearVRf,Samsung/GearVRf,phi-lira/GearVRf,danke-sra/GearVRf,roshanch/GearVRf,nathan-almeida/GearVRf,xiechengen/GearVRf,NolaDonato/GearVRf,nathan-almeida/GearVRf,rongguodong/GearVRf,dattanand/GearVRf,noname007/GearVRf
|
/* Copyright 2015 Samsung Electronics Co., LTD
*
* 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.gearvrf;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.EnumSet;
import org.gearvrf.GVRAndroidResource.BitmapTextureCallback;
import org.gearvrf.GVRAndroidResource.CompressedTextureCallback;
import org.gearvrf.GVRAndroidResource.MeshCallback;
import org.gearvrf.GVRAndroidResource.TextureCallback;
import org.gearvrf.GVRImportSettings;
import org.gearvrf.animation.GVRAnimation;
import org.gearvrf.animation.GVRAnimationEngine;
import org.gearvrf.asynchronous.GVRAsynchronousResourceLoader;
import org.gearvrf.asynchronous.GVRCompressedTexture;
import org.gearvrf.asynchronous.GVRCompressedTextureLoader;
import org.gearvrf.jassimp.AiColor;
import org.gearvrf.jassimp.AiMaterial;
import org.gearvrf.jassimp.AiMatrix4f;
import org.gearvrf.jassimp.AiNode;
import org.gearvrf.jassimp.AiScene;
import org.gearvrf.jassimp.AiTextureType;
import org.gearvrf.jassimp.AiWrapperProvider;
import org.gearvrf.jassimp.AiMaterial.Property;
import org.gearvrf.periodic.GVRPeriodicEngine;
import org.gearvrf.utility.Log;
import org.gearvrf.utility.ResourceCache;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.KeyEvent;
/**
* Like the Android {@link Context} class, {@code GVRContext} provides core
* services, and global information about an application environment.
*
* Use {@code GVRContext} to {@linkplain #createQuad(float, float) create} and
* {@linkplain #loadMesh(GVRAndroidResource) load} GL meshes, Android
* {@linkplain #loadBitmap(String) bitmaps}, and
* {@linkplain #loadTexture(GVRAndroidResource) GL textures.} {@code GVRContext}
* also holds the {@linkplain GVRScene main scene} and miscellaneous information
* like {@linkplain #getFrameTime() the frame time.}
*/
public abstract class GVRContext {
private static final String TAG = Log.tag(GVRContext.class);
private final GVRActivity mContext;
/*
* Fields and constants
*/
// Priorities constants, for asynchronous loading
/**
* GVRF can't use every {@code int} as a priority - it needs some sentinel
* values. It will probably never need anywhere near this many, but raising
* the number of reserved values narrows the 'dynamic range' available to
* apps mapping some internal score to the {@link #LOWEST_PRIORITY} to
* {@link #HIGHEST_PRIORITY} range, and might change app behavior in subtle
* ways that seem best avoided.
*
* @since 1.6.1
*/
public static final int RESERVED_PRIORITIES = 1024;
/**
* GVRF can't use every {@code int} as a priority - it needs some sentinel
* values. A simple approach to generating priorities is to score resources
* from 0 to 1, and then map that to the range {@link #LOWEST_PRIORITY} to
* {@link #HIGHEST_PRIORITY}.
*
* @since 1.6.1
*/
public static final int LOWEST_PRIORITY = Integer.MIN_VALUE
+ RESERVED_PRIORITIES;
/**
* GVRF can't use every {@code int} as a priority - it needs some sentinel
* values. A simple approach to generating priorities is to score resources
* from 0 to 1, and then map that to the range {@link #LOWEST_PRIORITY} to
* {@link #HIGHEST_PRIORITY}.
*
* @since 1.6.1
*/
public static final int HIGHEST_PRIORITY = Integer.MAX_VALUE;
/**
* The priority used by
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)}
* and
* {@link #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource)}
*
* @since 1.6.1
*/
public static final int DEFAULT_PRIORITY = 0;
/**
* The ID of the GLthread. We use this ID to prevent non-GL thread from
* calling GL functions.
*
* @since 1.6.5
*/
protected long mGLThreadID;
/**
* The default texture parameter instance for overloading texture methods
*
*/
public final GVRTextureParameters DEFAULT_TEXTURE_PARAMETERS = new GVRTextureParameters(
this);
// true or false based on the support for anisotropy
public boolean isAnisotropicSupported;
// Max anisotropic value if supported and -1 otherwise
public int maxAnisotropicValue = -1;
/*
* Methods
*/
GVRContext(GVRActivity context) {
mContext = context;
}
/**
* Get the Android {@link Context}, which provides access to system services
* and to your application's resources. Since version 2.0.1, this is
* actually your {@link GVRActivity} implementation, but you should probably
* use the new {@link #getActivity()} method, rather than casting this
* method to an {@code (Activity)} or {@code (GVRActivity)}.
*
* @return An Android {@code Context}
*/
public Context getContext() {
return mContext;
}
/**
* Get the Android {@link Activity} which launched your GVRF app.
*
* An {@code Activity} is-a {@link Context} and so provides access to system
* services and to your application's resources; the {@code Activity} class
* also provides additional services, including
* {@link Activity#runOnUiThread(Runnable)}.
*
* @return The {@link GVRActivity} which launched your GVRF app. The
* {@link GVRActivity} class doesn't actually add much useful
* functionality besides
* {@link GVRActivity#setScript(GVRScript, String)}, but returning
* the most-derived class here may prevent someone from having to
* write {@code (GVRActivity) gvrContext.getActivity();}.
*
* @since 2.0.1
*/
public GVRActivity getActivity() {
return mContext;
}
/**
* Loads a file as a {@link GVRMesh}.
*
* Note that this method can be quite slow; we recommend never calling it
* from the GL thread. The asynchronous version
* {@link #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource)} is
* better because it moves most of the work to a background thread, doing as
* little as possible on the GL thread.
*
* @param androidResource
* Basically, a stream containing a 3D model. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @return The file as a GL mesh.
*
* @since 1.6.2
*/
public GVRMesh loadMesh(GVRAndroidResource androidResource) {
return loadMesh(androidResource,
GVRImportSettings.getRecommendedSettings());
}
/**
* Loads a file as a {@link GVRMesh}.
*
* Note that this method can be quite slow; we recommend never calling it
* from the GL thread. The asynchronous version
* {@link #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource)} is
* better because it moves most of the work to a background thread, doing as
* little as possible on the GL thread.
*
* @param androidResource
* Basically, a stream containing a 3D model. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
*
* @param settings
* Additional import {@link GVRImpotSettings settings}.
* @return The file as a GL mesh.
*
* @since 1.6.2
*/
public GVRMesh loadMesh(GVRAndroidResource androidResource,
EnumSet<GVRImportSettings> settings) {
GVRMesh mesh = sMeshCache.get(androidResource);
if (mesh == null) {
GVRAssimpImporter assimpImporter = GVRImporter
.readFileFromResources(this, androidResource, settings);
mesh = assimpImporter.getMesh(0);
sMeshCache.put(androidResource, mesh);
}
return mesh;
}
private final static ResourceCache<GVRMesh> sMeshCache = new ResourceCache<GVRMesh>();
/**
* Loads a mesh file, asynchronously, at a default priority.
*
* This method and the
* {@linkplain #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource, int)
* overload that takes a priority} are generally going to be your best
* choices for loading {@link GVRMesh} resources: mesh loading can take
* hundreds - and even thousands - of milliseconds, and so should not be
* done on the GL thread in either {@link GVRScript#onInit(GVRContext)
* onInit()} or {@link GVRScript#onStep() onStep()}.
*
* <p>
* The asynchronous methods improve throughput in three ways. First, by
* doing all the work on a background thread, then delivering the loaded
* mesh to the GL thread on a {@link #runOnGlThread(Runnable)
* runOnGlThread()} callback. Second, they use a throttler to avoid
* overloading the system and/or running out of memory. Third, they do
* 'request consolidation' - if you issue any requests for a particular file
* while there is still a pending request, the file will only be read once,
* and each callback will get the same {@link GVRMesh}.
*
* @param callback
* App supplied callback, with three different methods.
* <ul>
* <li>Before loading, GVRF may call
* {@link GVRAndroidResource.MeshCallback#stillWanted(GVRAndroidResource)
* stillWanted()} (on a background thread) to give you a chance
* to abort a 'stale' load.
*
* <li>Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread.
*
* <li>Any errors will call
* {@link GVRAndroidResource.MeshCallback#failed(Throwable, GVRAndroidResource)
* failed(),} with no promises about threading.
* </ul>
* @param androidResource
* Basically, a stream containing a 3D model. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @throws IllegalArgumentException
* If either parameter is {@code null} or if you 'abuse' request
* consolidation by passing the same {@link GVRAndroidResource}
* descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
* @since 1.6.2
*/
public void loadMesh(MeshCallback callback,
GVRAndroidResource androidResource) throws IllegalArgumentException {
loadMesh(callback, androidResource, DEFAULT_PRIORITY);
}
/**
* Loads a mesh file, asynchronously, at an explicit priority.
*
* This method and the
* {@linkplain #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource)
* overload that supplies a default priority} are generally going to be your
* best choices for loading {@link GVRMesh} resources: mesh loading can take
* hundreds - and even thousands - of milliseconds, and so should not be
* done on the GL thread in either {@link GVRScript#onInit(GVRContext)
* onInit()} or {@link GVRScript#onStep() onStep()}.
*
* <p>
* The asynchronous methods improve throughput in three ways. First, by
* doing all the work on a background thread, then delivering the loaded
* mesh to the GL thread on a {@link #runOnGlThread(Runnable)
* runOnGlThread()} callback. Second, they use a throttler to avoid
* overloading the system and/or running out of memory. Third, they do
* 'request consolidation' - if you issue any requests for a particular file
* while there is still a pending request, the file will only be read once,
* and each callback will get the same {@link GVRMesh}.
*
* @param callback
* App supplied callback, with three different methods.
* <ul>
* <li>Before loading, GVRF may call
* {@link GVRAndroidResource.MeshCallback#stillWanted(GVRAndroidResource)
* stillWanted()} (on a background thread) to give you a chance
* to abort a 'stale' load.
*
* <li>Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread.
*
* <li>Any errors will call
* {@link GVRAndroidResource.MeshCallback#failed(Throwable, GVRAndroidResource)
* failed(),} with no promises about threading.
* </ul>
* @param resource
* Basically, a stream containing a 3D model. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>.
*
* @throws IllegalArgumentException
* If either {@code callback} or {@code resource} is
* {@code null}, or if {@code priority} is out of range - or if
* you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
* @since 1.6.2
*/
public void loadMesh(MeshCallback callback, GVRAndroidResource resource,
int priority) throws IllegalArgumentException {
GVRAsynchronousResourceLoader.loadMesh(this, callback, resource,
priority);
}
/**
* Simple, high-level method to load a mesh asynchronously, for use with
* {@link GVRRenderData#setMesh(Future)}.
*
* This method uses a default priority; use
* {@link #loadFutureMesh(GVRAndroidResource, int)} to specify a priority;
* use one of the lower-level
* {@link #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource)}
* methods to get more control over loading.
*
* @param resource
* Basically, a stream containing a 3D model. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @return A {@link Future} that you can pass to
* {@link GVRRenderData#setMesh(Future)}
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public Future<GVRMesh> loadFutureMesh(GVRAndroidResource resource) {
return loadFutureMesh(resource, DEFAULT_PRIORITY);
}
/**
* Simple, high-level method to load a mesh asynchronously, for use with
* {@link GVRRenderData#setMesh(Future)}.
*
* This method trades control for convenience; use one of the lower-level
* {@link #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource)}
* methods if, say, you want to do something more than just
* {@link GVRRenderData#setMesh(GVRMesh)} when the mesh loads.
*
* @param resource
* Basically, a stream containing a 3D model. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>.
* @return A {@link Future} that you can pass to
* {@link GVRRenderData#setMesh(Future)}
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public Future<GVRMesh> loadFutureMesh(GVRAndroidResource resource,
int priority) {
return GVRAsynchronousResourceLoader.loadFutureMesh(this, resource,
priority);
}
/**
* Simple, high-level method to load a scene as {@link GVRSceneObject} from
* 3D model.
*
* @param assetRelativeFilename
* A filename, relative to the {@code assets} directory. The file
* can be in a sub-directory of the {@code assets} directory:
* {@code "foo/bar.png"} will open the file
* {@code assets/foo/bar.png}
*
* @return A {@link GVRSceneObject} that contains the meshes with textures
*
* @throws IOException
* File does not exist or cannot be read
*/
public GVRSceneObject getAssimpModel(String assetRelativeFilename)
throws IOException {
return getAssimpModel(assetRelativeFilename,
GVRImportSettings.getRecommendedSettings());
}
/**
* Simple, high-level method to load a scene as {@link GVRSceneObject} from
* 3D model.
*
* @param assetRelativeFilename
* A filename, relative to the {@code assets} directory. The file
* can be in a sub-directory of the {@code assets} directory:
* {@code "foo/bar.png"} will open the file
* {@code assets/foo/bar.png}
*
* @param settings
* Additional import {@link GVRImportSettings settings}
* @return A {@link GVRSceneObject} that contains the meshes with textures
*
* @throws IOException
* File does not exist or cannot be read
*/
public GVRSceneObject getAssimpModel(String assetRelativeFilename,
EnumSet<GVRImportSettings> settings) throws IOException {
GVRAssimpImporter assimpImporter = GVRImporter.readFileFromResources(
this, new GVRAndroidResource(this, assetRelativeFilename),
settings);
GVRSceneObject wholeSceneObject = new GVRSceneObject(this);
AiScene assimpScene = assimpImporter.getAssimpScene();
AiWrapperProvider<byte[], AiMatrix4f, AiColor, AiNode, byte[]> wrapperProvider = new AiWrapperProvider<byte[], AiMatrix4f, AiColor, AiNode, byte[]>() {
/**
* Wraps a RGBA color.
* <p>
*
* A color consists of 4 float values (r,g,b,a) starting from offset
*
* @param buffer
* the buffer to wrap
* @param offset
* the offset into buffer
* @return the wrapped color
*/
@Override
public AiColor wrapColor(ByteBuffer buffer, int offset) {
AiColor color = new AiColor(buffer, offset);
return color;
}
/**
* Wraps a 4x4 matrix of floats.
* <p>
*
* The calling code will allocate a new array for each invocation of
* this method. It is safe to store a reference to the passed in
* array and use the array to store the matrix data.
*
* @param data
* the matrix data in row-major order
* @return the wrapped matrix
*/
@Override
public AiMatrix4f wrapMatrix4f(float[] data) {
AiMatrix4f transformMatrix = new AiMatrix4f(data);
return transformMatrix;
}
/**
* Wraps a quaternion.
* <p>
*
* A quaternion consists of 4 float values (w,x,y,z) starting from
* offset
*
* @param buffer
* the buffer to wrap
* @param offset
* the offset into buffer
* @return the wrapped quaternion
*/
@Override
public byte[] wrapQuaternion(ByteBuffer buffer, int offset) {
byte[] quaternion = new byte[4];
buffer.get(quaternion, offset, 4);
return quaternion;
}
/**
* Wraps a scene graph node.
* <p>
*
* See {@link AiNode} for a description of the scene graph structure
* used by assimp.
* <p>
*
* The parent node is either null or an instance returned by this
* method. It is therefore safe to cast the passed in parent object
* to the implementation specific type
*
* @param parent
* the parent node
* @param matrix
* the transformation matrix
* @param meshReferences
* array of mesh references (indexes)
* @param name
* the name of the node
* @return the wrapped scene graph node
*/
@Override
public AiNode wrapSceneNode(Object parent, Object matrix,
int[] meshReferences, String name) {
AiNode node = new AiNode(null, matrix, meshReferences, name);
return node;
}
/**
* Wraps a vector.
* <p>
*
* Most vectors are 3-dimensional, i.e., with 3 components. The
* exception are texture coordinates, which may be 1- or
* 2-dimensional. A vector consists of numComponents floats (x,y,z)
* starting from offset
*
* @param buffer
* the buffer to wrap
* @param offset
* the offset into buffer
* @param numComponents
* the number of components
* @return the wrapped vector
*/
@Override
public byte[] wrapVector3f(ByteBuffer buffer, int offset,
int numComponents) {
byte[] warpedVector = new byte[numComponents];
buffer.get(warpedVector, offset, numComponents);
return warpedVector;
}
};
AiNode rootNode = assimpScene.getSceneRoot(wrapperProvider);
// Recurse through the entire hierarchy to attache all the meshes as
// Scene Object
this.recurseAssimpNodes(assetRelativeFilename, wholeSceneObject,
rootNode, wrapperProvider);
return wholeSceneObject;
}
/**
* Helper method to recurse through all the assimp nodes and get all their
* meshes that can be used to create {@link GVRSceneObject} to be attached
* to the set of complete scene objects for the assimp model.
*
* @param assetRelativeFilename
* A filename, relative to the {@code assets} directory. The file
* can be in a sub-directory of the {@code assets} directory:
* {@code "foo/bar.png"} will open the file
* {@code assets/foo/bar.png}
*
* @param wholeSceneObject
* A reference of the {@link GVRSceneObject}, to which all other
* scene objects are attached.
*
* @param node
* A reference to the AiNode for which we want to recurse all its
* children and meshes.
*
* @param wrapperProvider
* AiWrapperProvider for unwrapping Jassimp properties.
*
*/
@SuppressWarnings("resource")
private void recurseAssimpNodes(
String assetRelativeFilename,
GVRSceneObject parentSceneObject,
AiNode node,
AiWrapperProvider<byte[], AiMatrix4f, AiColor, AiNode, byte[]> wrapperProvider) {
try {
GVRSceneObject newParentSceneObject = new GVRSceneObject(this);
if (node.getNumMeshes() == 0) {
parentSceneObject.addChildObject(newParentSceneObject);
parentSceneObject = newParentSceneObject;
} else if (node.getNumMeshes() == 1) {
// add the scene object to the scene graph
GVRSceneObject sceneObject = createSceneObject(
assetRelativeFilename, node, 0, wrapperProvider);
parentSceneObject.addChildObject(sceneObject);
parentSceneObject = sceneObject;
} else {
for (int i = 0; i < node.getNumMeshes(); i++) {
GVRSceneObject sceneObject = createSceneObject(
assetRelativeFilename, node, i, wrapperProvider);
newParentSceneObject.addChildObject(sceneObject);
}
parentSceneObject.addChildObject(newParentSceneObject);
parentSceneObject = newParentSceneObject;
}
for (int i = 0; i < node.getNumChildren(); i++) {
this.recurseAssimpNodes(assetRelativeFilename,
parentSceneObject, node.getChildren().get(i),
wrapperProvider);
}
} catch (Exception e) {
// Error while recursing the Scene Graph
e.printStackTrace();
}
}
/**
* Helper method to create a new {@link GVRSceneObject} with either color or texture.
*
* @param assetRelativeFilename
* A filename, relative to the {@code assets} directory. The file
* can be in a sub-directory of the {@code assets} directory:
* {@code "foo/bar.png"} will open the file
* {@code assets/foo/bar.png}
*
* @param node
* A reference to the AiNode for which we want to recurse all its
* children and meshes.
*
* @param index
* The index of the mesh in the array of meshes for that node.
*
* @param wrapperProvider
* AiWrapperProvider for unwrapping Jassimp properties.
*
* @return The new {@link GVRSceneObject} with the mesh at the index
* {@link index} for the node {@link node}
*
* @throws IOException
* File does not exist or cannot be read
*/
private GVRSceneObject createSceneObject(
String assetRelativeFilename,
AiNode node,
int index,
AiWrapperProvider<byte[], AiMatrix4f, AiColor, AiNode, byte[]> wrapperProvider)
throws IOException {
FutureWrapper<GVRMesh> futureMesh = new FutureWrapper<GVRMesh>(
this.getNodeMesh(new GVRAndroidResource(this,
assetRelativeFilename), node.getName(), index));
AiMaterial material = this.getMeshMaterial(new GVRAndroidResource(this,
assetRelativeFilename), node.getName(), index);
Property property = material.getProperty("$tex.file");
if (property != null) {
int textureIndex = property.getIndex();
String texFileName = material.getTextureFile(AiTextureType.DIFFUSE,
textureIndex);
Future<GVRTexture> futureMeshTexture = this
.loadFutureTexture(new GVRAndroidResource(this, texFileName));
GVRSceneObject sceneObject = new GVRSceneObject(this, futureMesh,
futureMeshTexture);
return sceneObject;
} else {
// The case when there is no texture
// This block also takes care for the case when there
// are no texture or color for the mesh as the methods
// that are used for getting the colors of the material
// returns a default when they are not present
AiColor diffuseColor = material.getDiffuseColor(wrapperProvider);
AiColor ambientColor = material.getAmbientColor(wrapperProvider);
float opacity = material.getOpacity();
final String DIFFUSE_COLOR_KEY = "diffuse_color";
final String AMBIENT_COLOR_KEY = "ambient_color";
final String COLOR_OPACITY_KEY = "opacity";
final String VERTEX_SHADER = "attribute vec4 a_position;\n"
+ "uniform mat4 u_mvp;\n" + "void main() {\n"
+ " gl_Position = u_mvp * a_position;\n" + "}\n";
final String FRAGMENT_SHADER = "precision mediump float;\n"
+ "uniform vec4 diffuse_color;\n" //
+ "uniform vec4 ambient_color;\n"
+ "uniform float opacity;\n"
+ "void main() {\n" //
+ " gl_FragColor = ( diffuse_color * opacity ) + ambient_color;\n"
+ "}\n";
GVRCustomMaterialShaderId mShaderId;
GVRMaterialMap mCustomShader = null;
final GVRMaterialShaderManager shaderManager = this
.getMaterialShaderManager();
mShaderId = shaderManager.addShader(VERTEX_SHADER, FRAGMENT_SHADER);
mCustomShader = shaderManager.getShaderMap(mShaderId);
mCustomShader.addUniformVec4Key("diffuse_color", DIFFUSE_COLOR_KEY);
mCustomShader.addUniformVec4Key("ambient_color", AMBIENT_COLOR_KEY);
mCustomShader.addUniformFloatKey("opacity", COLOR_OPACITY_KEY);
GVRMaterial meshMaterial = new GVRMaterial(this, mShaderId);
meshMaterial.setVec4(DIFFUSE_COLOR_KEY, diffuseColor.getRed(),
diffuseColor.getGreen(), diffuseColor.getBlue(),
diffuseColor.getAlpha());
meshMaterial.setVec4(AMBIENT_COLOR_KEY, ambientColor.getRed(),
ambientColor.getGreen(), ambientColor.getBlue(),
ambientColor.getAlpha());
meshMaterial.setFloat(COLOR_OPACITY_KEY, opacity);
GVRSceneObject sceneObject = new GVRSceneObject(this);
GVRRenderData sceneObjectRenderData = new GVRRenderData(this);
sceneObjectRenderData.setMesh(futureMesh);
sceneObjectRenderData.setMaterial(meshMaterial);
sceneObject.attachRenderData(sceneObjectRenderData);
return sceneObject;
}
}
/**
* Retrieves the particular index mesh for the given node.
*
* @return The mesh, encapsulated as a {@link GVRMesh}.
*/
public GVRMesh getNodeMesh(GVRAndroidResource androidResource,
String nodeName, int meshIndex) {
GVRAssimpImporter assimpImporter = GVRImporter.readFileFromResources(
this, androidResource,
GVRImportSettings.getRecommendedSettings());
return assimpImporter.getNodeMesh(nodeName, meshIndex);
}
/**
* Retrieves the material for the mesh of the given node..
*
* @return The material, encapsulated as a {@link AiMaterial}.
*/
public AiMaterial getMeshMaterial(GVRAndroidResource androidResource,
String nodeName, int meshIndex) {
GVRAssimpImporter assimpImporter = GVRImporter.readFileFromResources(
this, androidResource,
GVRImportSettings.getRecommendedSettings());
return assimpImporter.getMeshMaterial(nodeName, meshIndex);
}
/**
* Creates a quad consisting of two triangles, with the specified width and
* height.
*
* @param width
* the quad's width
* @param height
* the quad's height
* @return A 2D, rectangular mesh with four vertices and two triangles
*/
public GVRMesh createQuad(float width, float height) {
GVRMesh mesh = new GVRMesh(this);
float[] vertices = { width * -0.5f, height * 0.5f, 0.0f, width * -0.5f,
height * -0.5f, 0.0f, width * 0.5f, height * 0.5f, 0.0f,
width * 0.5f, height * -0.5f, 0.0f };
mesh.setVertices(vertices);
final float[] normals = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f, 1.0f };
mesh.setNormals(normals);
final float[] texCoords = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,
1.0f };
mesh.setTexCoords(texCoords);
char[] triangles = { 0, 1, 2, 1, 3, 2 };
mesh.setTriangles(triangles);
return mesh;
}
/**
* Loads file placed in the assets folder, as a {@link Bitmap}.
*
* <p>
* Note that this method may take hundreds of milliseconds to return: unless
* the bitmap is quite tiny, you probably don't want to call this directly
* from your {@link GVRScript#onStep() onStep()} callback as that is called
* once per frame, and a long call will cause you to miss frames.
*
* <p>
* Note also that this method does no scaling, and will return a full-size
* {@link Bitmap}. Loading (say) an unscaled photograph may abort your app:
* Use pre-scaled images, or {@link BitmapFactory} methods which give you
* more control over the image size.
*
* @param fileName
* The name of a file, relative to the assets directory. The
* assets directory may contain an arbitrarily complex tree of
* subdirectories; the file name can specify any location in or
* under the assets directory.
* @return The file as a bitmap, or {@code null} if file path does not exist
* or the file can not be decoded into a Bitmap.
*/
public Bitmap loadBitmap(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("File name should not be null.");
}
InputStream stream = null;
Bitmap bitmap = null;
try {
try {
stream = mContext.getAssets().open(fileName);
return bitmap = BitmapFactory.decodeStream(stream);
} finally {
if (stream != null) {
stream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
// Don't discard a valid Bitmap because of an IO error closing the
// file!
return bitmap;
}
}
/**
* Loads file placed in the assets folder, as a {@link GVRBitmapTexture}.
*
* <p>
* Note that this method may take hundreds of milliseconds to return: unless
* the texture is quite tiny, you probably don't want to call this directly
* from your {@link GVRScript#onStep() onStep()} callback as that is called
* once per frame, and a long call will cause you to miss frames. For large
* images, you should use either
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} (faster) or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)}
* (fastest <em>and</em> least memory pressure).
*
* <p>
* Note also that this method does no scaling, and will return a full-size
* {@link Bitmap}. Loading (say) an unscaled photograph may abort your app:
* Use
* <ul>
* <li>Pre-scaled images
* <li>{@link BitmapFactory} methods which give you more control over the
* image size, or
* <li>
* {@link #loadTexture(GVRAndroidResource)} or
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)}
* which automatically scale large images to fit the GPU's restrictions and
* to avoid {@linkplain OutOfMemoryError out of memory errors.}
* </ul>
*
* @param fileName
* The name of a file, relative to the assets directory. The
* assets directory may contain an arbitrarily complex tree of
* sub-directories; the file name can specify any location in or
* under the assets directory.
* @return The file as a texture, or {@code null} if file path does not
* exist or the file can not be decoded into a Bitmap.
*
* @deprecated We will remove this uncached, blocking function during Q3 of
* 2015. We suggest that you switch to
* {@link #loadTexture(GVRAndroidResource)}
*
*/
public GVRBitmapTexture loadTexture(String fileName) {
return loadTexture(fileName, DEFAULT_TEXTURE_PARAMETERS);
}
/**
* Loads file placed in the assets folder, as a {@link GVRBitmapTexture}
* with the user provided texture parameters.
*
* <p>
* Note that this method may take hundreds of milliseconds to return: unless
* the texture is quite tiny, you probably don't want to call this directly
* from your {@link GVRScript#onStep() onStep()} callback as that is called
* once per frame, and a long call will cause you to miss frames. For large
* images, you should use either
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} (faster) or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)}
* (fastest <em>and</em> least memory pressure).
*
* <p>
* Note also that this method does no scaling, and will return a full-size
* {@link Bitmap}. Loading (say) an unscaled photograph may abort your app:
* Use
* <ul>
* <li>Pre-scaled images
* <li>{@link BitmapFactory} methods which give you more control over the
* image size, or
* <li>
* {@link #loadTexture(GVRAndroidResource)} or
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)}
* which automatically scale large images to fit the GPU's restrictions and
* to avoid {@linkplain OutOfMemoryError out of memory errors.}
* </ul>
*
* @param fileName
* The name of a file, relative to the assets directory. The
* assets directory may contain an arbitrarily complex tree of
* sub-directories; the file name can specify any location in or
* under the assets directory.
* @param textureParameters
* The texture parameter object which has all the values that
* were provided by the user for texture enhancement. The
* {@link GVRTextureParameters} class has methods to set all the
* texture filters and wrap states.
* @return The file as a texture, or {@code null} if file path does not
* exist or the file can not be decoded into a Bitmap.
*
* @deprecated We will remove this uncached, blocking function during Q3 of
* 2015. We suggest that you switch to
* {@link #loadTexture(GVRAndroidResource)}
*
*/
@SuppressWarnings("resource")
public GVRBitmapTexture loadTexture(String fileName,
GVRTextureParameters textureParameters) {
assertGLThread();
if (fileName.endsWith(".png")) { // load png directly to texture
return new GVRBitmapTexture(this, fileName);
}
Bitmap bitmap = loadBitmap(fileName);
return bitmap == null ? null : new GVRBitmapTexture(this, bitmap,
textureParameters);
}
/**
* Loads file placed in the assets folder, as a {@link GVRBitmapTexture}.
*
* <p>
* Note that this method may take hundreds of milliseconds to return: unless
* the texture is quite tiny, you probably don't want to call this directly
* from your {@link GVRScript#onStep() onStep()} callback as that is called
* once per frame, and a long call will cause you to miss frames. For large
* images, you should use either
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} (faster) or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)}
* (fastest <em>and</em> least memory pressure).
*
* <p>
* This method automatically scales large images to fit the GPU's
* restrictions and to avoid {@linkplain OutOfMemoryError out of memory
* errors.} </ul>
*
* @param resource
* Basically, a stream containing a bitmap texture. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @return The file as a texture, or {@code null} if the file can not be
* decoded into a Bitmap.
*
* @since 1.6.5
*/
public GVRTexture loadTexture(GVRAndroidResource resource) {
return loadTexture(resource, DEFAULT_TEXTURE_PARAMETERS);
}
/**
* Loads file placed in the assets folder, as a {@link GVRBitmapTexture}
* with the user provided texture parameters.
*
* <p>
* Note that this method may take hundreds of milliseconds to return: unless
* the texture is quite tiny, you probably don't want to call this directly
* from your {@link GVRScript#onStep() onStep()} callback as that is called
* once per frame, and a long call will cause you to miss frames. For large
* images, you should use either
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} (faster) or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)}
* (fastest <em>and</em> least memory pressure).
*
* <p>
* This method automatically scales large images to fit the GPU's
* restrictions and to avoid {@linkplain OutOfMemoryError out of memory
* errors.} </ul>
*
* @param resource
* Basically, a stream containing a bitmap texture. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param textureParameters
* The texture parameter object which has all the values that
* were provided by the user for texture enhancement. The
* {@link GVRTextureParameters} class has methods to set all the
* texture filters and wrap states.
* @return The file as a texture, or {@code null} if the file can not be
* decoded into a Bitmap.
*
*/
public GVRTexture loadTexture(GVRAndroidResource resource,
GVRTextureParameters textureParameters) {
GVRTexture texture = sTextureCache.get(resource);
if (texture == null) {
assertGLThread();
Bitmap bitmap = GVRAsynchronousResourceLoader.decodeStream(
resource.getStream(), false);
resource.closeStream();
texture = bitmap == null ? null : new GVRBitmapTexture(this,
bitmap, textureParameters);
if (texture != null) {
sTextureCache.put(resource, texture);
}
}
return texture;
}
private final static ResourceCache<GVRTexture> sTextureCache = new ResourceCache<GVRTexture>();
/**
* Loads a cube map texture synchronously.
*
* <p>
* Note that this method may take hundreds of milliseconds to return: unless
* the cube map is quite tiny, you probably don't want to call this directly
* from your {@link GVRScript#onStep() onStep()} callback as that is called
* once per frame, and a long call will cause you to miss frames.
*
* @param resourceArray
* An array containing six resources for six bitmaps. The order
* of the bitmaps is important to the correctness of the cube map
* texture. The six bitmaps should correspond to +x, -x, +y, -y,
* +z, and -z faces of the cube map texture respectively.
* @return The cube map texture, or {@code null} if the length of
* rsourceArray is not 6.
*
* @since 1.6.9
*/
/*
* TODO Deprecate, and replace with an overload that takes a single
* GVRAndroidResource which specifies a zip file ... and caches result
*/
public GVRCubemapTexture loadCubemapTexture(
GVRAndroidResource[] resourceArray) {
return loadCubemapTexture(resourceArray, DEFAULT_TEXTURE_PARAMETERS);
}
// Texture parameters
public GVRCubemapTexture loadCubemapTexture(
GVRAndroidResource[] resourceArray,
GVRTextureParameters textureParameters) {
assertGLThread();
if (resourceArray.length != 6) {
return null;
}
Bitmap[] bitmapArray = new Bitmap[6];
for (int i = 0; i < 6; i++) {
bitmapArray[i] = GVRAsynchronousResourceLoader.decodeStream(
resourceArray[i].getStream(), false);
resourceArray[i].closeStream();
}
return new GVRCubemapTexture(this, bitmapArray, textureParameters);
}
/**
* Throws an exception if the current thread is not a GL thread.
*
* @since 1.6.5
*
*/
private void assertGLThread() {
if (Thread.currentThread().getId() != mGLThreadID) {
throw new RuntimeException(
"Should not run GL functions from a non-GL thread!");
}
}
/**
* Load a bitmap, asynchronously, with a default priority.
*
* Because it is asynchronous, this method <em>is</em> a bit harder to use
* than {@link #loadTexture(String)}, but it moves a large amount of work
* (in {@link BitmapFactory#decodeStream(InputStream)} from the GL thread to
* a background thread. Since you <em>can</em> create a
* {@link GVRSceneObject} without a mesh and texture - and set them later -
* using the asynchronous API can improve startup speed and/or reduce frame
* misses (where an {@link GVRScript#onStep() onStep()} takes too long).
* This API may also use less RAM than {@link #loadTexture(String)}.
*
* <p>
* This API will 'consolidate' requests: If you request a texture like
* {@code R.raw.wood_grain} and then - before it has loaded - issue another
* request for {@code R.raw.wood_grain}, GVRF will only read the bitmap file
* once; only create a single {@link GVRTexture}; and then call both
* callbacks, passing each the same texture.
*
* <p>
* Please be aware that {@link BitmapFactory#decodeStream(InputStream)} is a
* comparatively expensive operation: it can take hundreds of milliseconds
* and use several megabytes of temporary RAM. GVRF includes a throttler to
* keep the total load manageable - but
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)}
* is <em>much</em> faster and lighter-weight: that API simply loads the
* compressed texture into a small amount RAM (which doesn't take very long)
* and does some simple parsing to figure out the parameters to pass
* {@code glCompressedTexImage2D()}. The GL hardware does the decoding much
* faster than Android's {@link BitmapFactory}!
*
* <p>
* TODO Take a boolean parameter that controls mipmap generation?
*
* @since 1.6.1
*
* @param callback
* Before loading, GVRF may call
* {@link GVRAndroidResource.BitmapTextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} several times (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread;
*
* any errors will call
* {@link GVRAndroidResource.BitmapTextureCallback#failed(Throwable, GVRAndroidResource)
* failed()}, with no promises about threading.
*
* <p>
* This method uses a throttler to avoid overloading the system.
* If the throttler has threads available, it will run this
* request immediately. Otherwise, it will enqueue the request,
* and call
* {@link GVRAndroidResource.BitmapTextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} at least once (on a background thread) to give
* you a chance to abort a 'stale' load.
* @param resource
* Basically, a stream containing a bitmapped image. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadBitmapTexture(BitmapTextureCallback callback,
GVRAndroidResource resource) {
loadBitmapTexture(callback, resource, DEFAULT_PRIORITY);
}
/**
* Load a bitmap, asynchronously, with an explicit priority.
*
* Because it is asynchronous, this method <em>is</em> a bit harder to use
* than {@link #loadTexture(String)}, but it moves a large amount of work
* (in {@link BitmapFactory#decodeStream(InputStream)} from the GL thread to
* a background thread. Since you <em>can</em> create a
* {@link GVRSceneObject} without a mesh and texture - and set them later -
* using the asynchronous API can improve startup speed and/or reduce frame
* misses, where an {@link GVRScript#onStep() onStep()} takes too long.
*
* <p>
* This API will 'consolidate' requests: If you request a texture like
* {@code R.raw.wood_grain} and then - before it has loaded - issue another
* request for {@code R.raw.wood_grain}, GVRF will only read the bitmap file
* once; only create a single {@link GVRTexture}; and then call both
* callbacks, passing each the same texture.
*
* <p>
* Please be aware that {@link BitmapFactory#decodeStream(InputStream)} is a
* comparatively expensive operation: it can take hundreds of milliseconds
* and use several megabytes of temporary RAM. GVRF includes a throttler to
* keep the total load manageable - but
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)}
* is <em>much</em> faster and lighter-weight: that API simply loads the
* compressed texture into a small amount RAM (which doesn't take very long)
* and does some simple parsing to figure out the parameters to pass
* {@code glCompressedTexImage2D()}. The GL hardware does the decoding much
* faster than Android's {@link BitmapFactory}!
*
* @since 1.6.1
*
* @param callback
* Before loading, GVRF may call
* {@link GVRAndroidResource.BitmapTextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} several times (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread;
*
* any errors will call
* {@link GVRAndroidResource.BitmapTextureCallback#failed(Throwable, GVRAndroidResource)
* failed()}, with no promises about threading.
*
* <p>
* This method uses a throttler to avoid overloading the system.
* If the throttler has threads available, it will run this
* request immediately. Otherwise, it will enqueue the request,
* and call
* {@link GVRAndroidResource.BitmapTextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} at least once (on a background thread) to give
* you a chance to abort a 'stale' load.
* @param resource
* Basically, a stream containing a bitmapped image. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>.
*
* @throws IllegalArgumentException
* If {@code priority} {@literal <} {@link #LOWEST_PRIORITY} or
* {@literal >} {@link #HIGHEST_PRIORITY}, or either of the
* other parameters is {@code null} - or if you 'abuse' request
* consolidation by passing the same {@link GVRAndroidResource}
* descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadBitmapTexture(BitmapTextureCallback callback,
GVRAndroidResource resource, int priority)
throws IllegalArgumentException {
GVRAsynchronousResourceLoader.loadBitmapTexture(this, sTextureCache,
callback, resource, priority);
}
/**
* Load a compressed texture, asynchronously.
*
* GVRF currently supports ASTC, ETC2, and KTX formats: applications can add
* new formats by implementing {@link GVRCompressedTextureLoader}.
*
* <p>
* This method uses the fastest possible rendering. To specify higher
* quality (but slower) rendering, you can use the
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource, int)}
* overload.
*
* @since 1.6.1
*
* @param callback
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread; any errors will call
* {@link GVRAndroidResource.CompressedTextureCallback#failed(Throwable, GVRAndroidResource)
* failed()}, with no promises about threading.
* @param resource
* Basically, a stream containing a compressed texture. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadCompressedTexture(CompressedTextureCallback callback,
GVRAndroidResource resource) {
GVRAsynchronousResourceLoader.loadCompressedTexture(this,
sTextureCache, callback, resource);
}
/**
* Load a compressed texture, asynchronously.
*
* GVRF currently supports ASTC, ETC2, and KTX formats: applications can add
* new formats by implementing {@link GVRCompressedTextureLoader}.
*
* @since 1.6.1
*
* @param callback
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)}
* on the GL thread; any errors will call
* {@link GVRAndroidResource.CompressedTextureCallback#failed(Throwable, GVRAndroidResource)}
* , with no promises about threading.
* @param resource
* Basically, a stream containing a compressed texture. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param quality
* Speed/quality tradeoff: should be one of
* {@link GVRCompressedTexture#SPEED},
* {@link GVRCompressedTexture#BALANCED}, or
* {@link GVRCompressedTexture#QUALITY}, but other values are
* 'clamped' to one of the recognized values.
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadCompressedTexture(CompressedTextureCallback callback,
GVRAndroidResource resource, int quality) {
GVRAsynchronousResourceLoader.loadCompressedTexture(this,
sTextureCache, callback, resource, quality);
}
/**
* A simplified, low-level method that loads a texture asynchronously,
* without making you specify
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)
* loadCompressedTexture()}.
*
* This method can detect whether the resource file holds a compressed
* texture (GVRF currently supports ASTC, ETC2, and KTX formats:
* applications can add new formats by implementing
* {@link GVRCompressedTextureLoader}): if the file is not a compressed
* texture, it is loaded as a normal, bitmapped texture. This format
* detection adds very little to the cost of loading even a compressed
* texture, and it makes your life a lot easier: you can replace, say,
* {@code res/raw/resource.png} with {@code res/raw/resource.etc2} without
* having to change any code.
*
* <p>
* This method uses a default priority and a default render quality: Use
* {@link #loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource, int)}
* to specify an explicit priority, and
* {@link #loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource, int, int)}
* to specify an explicit quality.
*
* <p>
* We will continue to support the {@code loadBitmapTexture()} and
* {@code loadCompressedTexture()} APIs for at least a little while: We
* haven't yet decided whether to deprecate them or not.
*
* @param callback
* Before loading, GVRF may call
* {@link GVRAndroidResource.TextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} several times (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread;
*
* any errors will call
* {@link GVRAndroidResource.TextureCallback#failed(Throwable, GVRAndroidResource)
* failed()}, with no promises about threading.
*
* <p>
* This method uses a throttler to avoid overloading the system.
* If the throttler has threads available, it will run this
* request immediately. Otherwise, it will enqueue the request,
* and call
* {@link GVRAndroidResource.TextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} at least once (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* <p>
* Use {@link #loadFutureTexture(GVRAndroidResource)} to avoid
* having to implement a callback.
* @param resource
* Basically, a stream containing a texture file. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadTexture(TextureCallback callback,
GVRAndroidResource resource) {
loadTexture(callback, resource, DEFAULT_PRIORITY);
}
/**
* A simplified, low-level method that loads a texture asynchronously,
* without making you specify
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)
* loadCompressedTexture()}.
*
* This method can detect whether the resource file holds a compressed
* texture (GVRF currently supports ASTC, ETC2, and KTX formats:
* applications can add new formats by implementing
* {@link GVRCompressedTextureLoader}): if the file is not a compressed
* texture, it is loaded as a normal, bitmapped texture. This format
* detection adds very little to the cost of loading even a compressed
* texture, and it makes your life a lot easier: you can replace, say,
* {@code res/raw/resource.png} with {@code res/raw/resource.etc2} without
* having to change any code.
*
* <p>
* This method uses a default render quality: Use
* {@link #loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource, int, int)}
* to specify an explicit quality.
*
* <p>
* We will continue to support the {@code loadBitmapTexture()} and
* {@code loadCompressedTexture()} APIs for at least a little while: We
* haven't yet decided whether to deprecate them or not.
*
* @param callback
* Before loading, GVRF may call
* {@link GVRAndroidResource.TextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} several times (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread;
*
* any errors will call
* {@link GVRAndroidResource.TextureCallback#failed(Throwable, GVRAndroidResource)
* failed()}, with no promises about threading.
*
* <p>
* This method uses a throttler to avoid overloading the system.
* If the throttler has threads available, it will run this
* request immediately. Otherwise, it will enqueue the request,
* and call
* {@link GVRAndroidResource.TextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} at least once (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* <p>
* Use {@link #loadFutureTexture(GVRAndroidResource)} to avoid
* having to implement a callback.
* @param resource
* Basically, a stream containing a texture file. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>. Also, please note priorities only apply to
* uncompressed textures (standard Android bitmap files, which
* can take hundreds of milliseconds to load): compressed
* textures load so quickly that they are not run through the
* request scheduler.
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadTexture(TextureCallback callback,
GVRAndroidResource resource, int priority) {
loadTexture(callback, resource, priority, GVRCompressedTexture.BALANCED);
}
/**
* A simplified, low-level method that loads a texture asynchronously,
* without making you specify
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)
* loadCompressedTexture()}.
*
* This method can detect whether the resource file holds a compressed
* texture (GVRF currently supports ASTC, ETC2, and KTX formats:
* applications can add new formats by implementing
* {@link GVRCompressedTextureLoader}): if the file is not a compressed
* texture, it is loaded as a normal, bitmapped texture. This format
* detection adds very little to the cost of loading even a compressed
* texture, and it makes your life a lot easier: you can replace, say,
* {@code res/raw/resource.png} with {@code res/raw/resource.etc2} without
* having to change any code.
*
* <p>
* We will continue to support the {@code loadBitmapTexture()} and
* {@code loadCompressedTexture()} APIs for at least a little while: We
* haven't yet decided whether to deprecate them or not.
*
* @param callback
* Before loading, GVRF may call
* {@link GVRAndroidResource.TextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} several times (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread;
*
* any errors will call
* {@link GVRAndroidResource.TextureCallback#failed(Throwable, GVRAndroidResource)
* failed()}, with no promises about threading.
*
* <p>
* This method uses a throttler to avoid overloading the system.
* If the throttler has threads available, it will run this
* request immediately. Otherwise, it will enqueue the request,
* and call
* {@link GVRAndroidResource.TextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} at least once (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* <p>
* Use {@link #loadFutureTexture(GVRAndroidResource)} to avoid
* having to implement a callback.
* @param resource
* Basically, a stream containing a texture file. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>. Also, please note priorities only apply to
* uncompressed textures (standard Android bitmap files, which
* can take hundreds of milliseconds to load): compressed
* textures load so quickly that they are not run through the
* request scheduler.
* @param quality
* The compressed texture {@link GVRCompressedTexture#mQuality
* quality} parameter: should be one of
* {@link GVRCompressedTexture#SPEED},
* {@link GVRCompressedTexture#BALANCED}, or
* {@link GVRCompressedTexture#QUALITY}, but other values are
* 'clamped' to one of the recognized values. Please note that
* this (currently) only applies to compressed textures; normal
* {@linkplain GVRBitmapTexture bitmapped textures} don't take a
* quality parameter.
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadTexture(TextureCallback callback,
GVRAndroidResource resource, int priority, int quality) {
GVRAsynchronousResourceLoader.loadTexture(this, sTextureCache,
callback, resource, priority, quality);
}
/**
* Simple, high-level method to load a texture asynchronously, for use with
* {@link GVRShaders#setMainTexture(Future)} and
* {@link GVRShaders#setTexture(String, Future)}.
*
* This method uses a default priority and a default render quality: use
* {@link #loadFutureTexture(GVRAndroidResource, int)} to specify a priority
* or {@link #loadFutureTexture(GVRAndroidResource, int, int)} to specify a
* priority and render quality.
*
* <p>
* This method is significantly easier to use than
* {@link #loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource)}
* : you don't have to implement a callback; you don't have to pay attention
* to the low-level details of
* {@linkplain GVRSceneObject#attachRenderData(GVRRenderData) attaching} a
* {@link GVRRenderData} to your scene object. What's more, you don't even
* lose any functionality: {@link Future#cancel(boolean)} lets you cancel a
* 'stale' request, just like
* {@link GVRAndroidResource.CancelableCallback#stillWanted(GVRAndroidResource)
* stillWanted()} does. The flip side, of course, is that it <em>is</em> a
* bit more expensive: methods like
* {@link GVRMaterial#setMainTexture(Future)} use an extra thread from the
* thread pool to wait for the blocking {@link Future#get()} call. For
* modest numbers of loads, this overhead is acceptable - but thread
* creation is not free, and if your {@link GVRScript#onInit(GVRContext)
* onInit()} method fires of dozens of future loads, you may well see an
* impact.
*
* @param resource
* Basically, a stream containing a texture file. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @return A {@link Future} that you can pass to methods like
* {@link GVRShaders#setMainTexture(Future)}
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public Future<GVRTexture> loadFutureTexture(GVRAndroidResource resource) {
return loadFutureTexture(resource, DEFAULT_PRIORITY);
}
/**
* Simple, high-level method to load a texture asynchronously, for use with
* {@link GVRShaders#setMainTexture(Future)} and
* {@link GVRShaders#setTexture(String, Future)}.
*
* This method uses a default render quality:
* {@link #loadFutureTexture(GVRAndroidResource, int, int)} to specify
* render quality.
*
* <p>
* This method is significantly easier to use than
* {@link #loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource, int)
* : you don't have to implement a callback; you don't have to pay attention
* to the low-level details of
*{@linkplain GVRSceneObject#attachRenderData(GVRRenderData) attaching} a
* {@link GVRRenderData} to your scene object. What's more, you don't even
* lose any functionality: {@link Future#cancel(boolean)} lets you cancel a
* 'stale' request, just like
* {@link GVRAndroidResource.CancelableCallback#stillWanted(GVRAndroidResource)
* stillWanted()} does. The flip side, of course, is that it <em>is</em> a
* bit more expensive: methods like
* {@link GVRMaterial#setMainTexture(Future)} use an extra thread from the
* thread pool to wait for the blocking {@link Future#get()} call. For
* modest numbers of loads, this overhead is acceptable - but thread
* creation is not free, and if your {@link GVRScript#onInit(GVRContext)
* onInit()} method fires of dozens of future loads, you may well see an
* impact.
*
* @param resource
* Basically, a stream containing a texture file. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>. Also, please note priorities only apply to
* uncompressed textures (standard Android bitmap files, which
* can take hundreds of milliseconds to load): compressed
* textures load so quickly that they are not run through the
* request scheduler.
* @return A {@link Future} that you can pass to methods like
* {@link GVRShaders#setMainTexture(Future)}
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public Future<GVRTexture> loadFutureTexture(GVRAndroidResource resource,
int priority) {
return loadFutureTexture(resource, priority,
GVRCompressedTexture.BALANCED);
}
/**
* Simple, high-level method to load a texture asynchronously, for use with
* {@link GVRShaders#setMainTexture(Future)} and
* {@link GVRShaders#setTexture(String, Future)}.
*
*
* <p>
* This method is significantly easier to use than
* {@link #loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource, int, int)
* : you don't have to implement a callback; you don't have to pay attention
* to the low-level details of
*{@linkplain GVRSceneObject#attachRenderData(GVRRenderData) attaching} a
* {@link GVRRenderData} to your scene object. What's more, you don't even
* lose any functionality: {@link Future#cancel(boolean)} lets you cancel a
* 'stale' request, just like
* {@link GVRAndroidResource.CancelableCallback#stillWanted(GVRAndroidResource)
* stillWanted()} does. The flip side, of course, is that it <em>is</em> a
* bit more expensive: methods like
* {@link GVRMaterial#setMainTexture(Future)} use an extra thread from the
* thread pool to wait for the blocking {@link Future#get()} call. For
* modest numbers of loads, this overhead is acceptable - but thread
* creation is not free, and if your {@link GVRScript#onInit(GVRContext)
* onInit()} method fires of dozens of future loads, you may well see an
* impact.
*
* @param resource
* Basically, a stream containing a texture file. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>. Also, please note priorities only apply to
* uncompressed textures (standard Android bitmap files, which
* can take hundreds of milliseconds to load): compressed
* textures load so quickly that they are not run through the
* request scheduler.
* @param quality
* The compressed texture {@link GVRCompressedTexture#mQuality
* quality} parameter: should be one of
* {@link GVRCompressedTexture#SPEED},
* {@link GVRCompressedTexture#BALANCED}, or
* {@link GVRCompressedTexture#QUALITY}, but other values are
* 'clamped' to one of the recognized values. Please note that
* this (currently) only applies to compressed textures; normal
* {@linkplain GVRBitmapTexture bitmapped textures} don't take a
* quality parameter.
* @return A {@link Future} that you can pass to methods like
* {@link GVRShaders#setMainTexture(Future)}
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public Future<GVRTexture> loadFutureTexture(GVRAndroidResource resource,
int priority, int quality) {
return GVRAsynchronousResourceLoader.loadFutureTexture(this,
sTextureCache, resource, priority, quality);
}
/**
* Simple, high-level method to load a cube map texture asynchronously, for
* use with {@link GVRShaders#setMainTexture(Future)} and
* {@link GVRShaders#setTexture(String, Future)}.
*
* @param resource
* A steam containing a zip file which contains six bitmaps. The
* six bitmaps correspond to +x, -x, +y, -y, +z, and -z faces of
* the cube map texture respectively. The default names of the
* six images are "posx.png", "negx.png", "posy.png", "negx.png",
* "posz.png", and "negz.png", which can be changed by calling
* {@link GVRCubemapTexture#setFaceNames(String[])}.
* @return A {@link Future} that you can pass to methods like
* {@link GVRShaders#setMainTexture(Future)}
*
* @since 1.6.9
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public Future<GVRTexture> loadFutureCubemapTexture(
GVRAndroidResource resource) {
return GVRAsynchronousResourceLoader.loadFutureCubemapTexture(this,
sTextureCache, resource, DEFAULT_PRIORITY,
GVRCubemapTexture.faceIndexMap);
}
/**
* Get the current {@link GVRScene}, which contains the scene graph (a
* hierarchy of {@linkplain GVRSceneObject scene objects}) and the
* {@linkplain GVRCameraRig camera rig}
*
* @return A {@link GVRScene} instance, containing scene and camera
* information
*/
public abstract GVRScene getMainScene();
/** Set the current {@link GVRScene} */
public abstract void setMainScene(GVRScene scene);
/**
* Returns a {@link GVRScene} that you can populate before passing to
* {@link #setMainScene(GVRScene)}.
*
* Implementation maintains a single element buffer, initialized to
* {@code null}. When this method is called, creates a new scene if the
* buffer is {@code null}, then returns the buffered scene. If this buffered
* scene is passed to {@link #setMainScene(GVRScene)}, the buffer is reset
* to {@code null}.
*
* <p>
* One use of this is to build your scene graph while the splash screen is
* visible. If you have called {@linkplain #getNextMainScene()} (so that the
* next-main-scene buffer is non-{@code null} when the splash screen is
* closed) GVRF will automatically switch to the 'pending' main-scene; if
* the buffer is {@code null}, GVRF will simply remove the splash screen
* from the main scene object.
*
* @since 1.6.4
*/
public GVRScene getNextMainScene() {
return getNextMainScene(null);
}
/**
* Returns a {@link GVRScene} that you can populate before passing to
* {@link #setMainScene(GVRScene)}.
*
* Implementation maintains a single element buffer, initialized to
* {@code null}. When this method is called, creates a new scene if the
* buffer is {@code null}, then returns the buffered scene. If this buffered
* scene is passed to {@link #setMainScene(GVRScene)}, the buffer is reset
* to {@code null}.
*
* <p>
* One use of this is to build your scene graph while the splash screen is
* visible. If you have called {@linkplain #getNextMainScene()} (so that the
* next-main-scene buffer is non-{@code null} when the splash screen is
* closed) GVRF will automatically switch to the 'pending' main-scene; if
* the buffer is {@code null}, GVRF will simply remove the splash screen
* from the main scene object.
*
* @param onSwitchMainScene
* Optional (may be {@code null}) {@code Runnable}, called when
* this {@link GVRScene} becomes the new main scene, whether
* {@linkplain #setMainScene(GVRScene) explicitly} or implicitly
* (as, for example, when the splash screen closes). This
* callback lets apps do things like start animations when their
* scene becomes visible, instead of in
* {@link GVRScript#onInit(GVRContext) onInit()} when the scene
* objects may be hidden by the splash screen.
*
* @since 1.6.4
*/
public abstract GVRScene getNextMainScene(Runnable onSwitchMainScene);
/**
* Is the key pressed?
*
* @param keyCode
* An Android {@linkplain KeyEvent#KEYCODE_0 key code}
*/
public abstract boolean isKeyDown(int keyCode);
/**
* The interval between this frame and the previous frame, in seconds: a
* rough gauge of Frames Per Second.
*/
public abstract float getFrameTime();
/**
* Enqueues a callback to be run in the GL thread.
*
* This is how you take data generated on a background thread (or the main
* (GUI) thread) and pass it to the coprocessor, using calls that must be
* made from the GL thread (aka the "GL context"). The callback queue is
* processed before any registered
* {@linkplain #registerDrawFrameListener(GVRDrawFrameListener) frame
* listeners}.
*
* @param runnable
* A bit of code that must run on the GL thread
*/
public abstract void runOnGlThread(Runnable runnable);
/**
* Subscribes a {@link GVRDrawFrameListener}.
*
* Each frame listener is called, once per frame, after any pending
* {@linkplain #runOnGlThread(Runnable) GL callbacks} and before
* {@link GVRScript#onStep()}.
*
* @param frameListener
* A callback that will fire once per frame, until it is
* {@linkplain #unregisterDrawFrameListener(GVRDrawFrameListener)
* unregistered}
*/
public abstract void registerDrawFrameListener(
GVRDrawFrameListener frameListener);
/**
* Remove a previously-subscribed {@link GVRDrawFrameListener}.
*
* @param frameListener
* An instance of a {@link GVRDrawFrameListener} implementation.
* Unsubscribing a listener which is not actually subscribed will
* not throw an exception.
*/
public abstract void unregisterDrawFrameListener(
GVRDrawFrameListener frameListener);
/**
* The {@linkplain GVRMaterialShaderManager object shader manager}
* singleton.
*
* Use the shader manager to define custom GL object shaders, which are used
* to render a scene object's surface.
*
* @return The {@linkplain GVRMaterialShaderManager shader manager}
* singleton.
*/
public GVRMaterialShaderManager getMaterialShaderManager() {
return getRenderBundle().getMaterialShaderManager();
}
/**
* The {@linkplain GVRPostEffectShaderManager scene shader manager}
* singleton.
*
* Use the shader manager to define custom GL scene shaders, which can be
* inserted into the rendering pipeline to apply image processing effects to
* the rendered scene graph. In classic GL programming, this is often
* referred to as a "post effect."
*
* @return The {@linkplain GVRPostEffectShaderManager post effect shader
* manager} singleton.
*/
public GVRPostEffectShaderManager getPostEffectShaderManager() {
return getRenderBundle().getPostEffectShaderManager();
}
/**
* The {@linkplain GVRAnimationEngine animation engine} singleton.
*
* Use the animation engine to start and stop {@linkplain GVRAnimation
* animations}.
*
* @return The {@linkplain GVRAnimationEngine animation engine} singleton.
*/
public GVRAnimationEngine getAnimationEngine() {
return GVRAnimationEngine.getInstance(this);
}
/**
* The {@linkplain GVRPeriodicEngine periodic engine} singleton.
*
* Use the periodic engine to schedule {@linkplain Runnable runnables} to
* run on the GL thread at a future time.
*
* @return The {@linkplain GVRPeriodicEngine periodic engine} singleton.
*/
public GVRPeriodicEngine getPeriodicEngine() {
return GVRPeriodicEngine.getInstance(this);
}
/**
* Register a method that is called every time GVRF creates a new
* {@link GVRContext}.
*
* Android apps aren't mapped 1:1 to Linux processes; the system may keep a
* process loaded even after normal complete shutdown, and call Android
* lifecycle methods to reinitialize it. This causes problems for (in
* particular) lazy-created singletons that are tied to a particular
* {@code GVRContext}. This method lets you register a handler that will be
* called on restart, which can reset your {@code static} variables to the
* compiled-in start state.
*
* <p>
* For example,
*
* <pre>
*
* static YourSingletonClass sInstance;
* static {
* GVRContext.addResetOnRestartHandler(new Runnable() {
*
* @Override
* public void run() {
* sInstance = null;
* }
* });
* }
*
* </pre>
*
* <p>
* GVRF will force an Android garbage collection after running any handlers,
* which will free any remaining native objects from the previous run.
*
* @param handler
* Callback to run on restart.
*/
public synchronized static void addResetOnRestartHandler(Runnable handler) {
sHandlers.add(handler);
}
protected synchronized static void resetOnRestart() {
for (Runnable handler : sHandlers) {
Log.d(TAG, "Running on-restart handler %s", handler);
handler.run();
}
// We've probably just nulled-out a bunch of references, but many GVRF
// apps do relatively little Java memory allocation, so it may actually
// be a longish while before the recyclable references go stale.
System.gc();
// We do NOT want to clear sHandlers - the static initializers won't be
// run again, even if the new run does recreate singletons.
}
private static final List<Runnable> sHandlers = new ArrayList<Runnable>();
abstract GVRRenderBundle getRenderBundle();
/**
* Capture a 2D screenshot from the position in the middle of left eye and
* right eye.
*
* The screenshot capture is done asynchronously -- the function does not
* return the result immediately. Instead, it registers a callback function
* and pass the result (when it is available) to the callback function. The
* callback will happen on a background thread: It will probably not be the
* same thread that calls this method, and it will not be either the GUI or
* the GL thread.
*
* Users should not start a {@code captureScreenCenter} until previous
* {@code captureScreenCenter} callback has returned. Starting a new
* {@code captureScreenCenter} before the previous
* {@code captureScreenCenter} callback returned may cause out of memory
* error.
*
* @param callback
* Callback function to process the capture result. It may not be
* {@code null}.
*/
public abstract void captureScreenCenter(GVRScreenshotCallback callback);
/**
* Capture a 2D screenshot from the position of left eye.
*
* The screenshot capture is done asynchronously -- the function does not
* return the result immediately. Instead, it registers a callback function
* and pass the result (when it is available) to the callback function. The
* callback will happen on a background thread: It will probably not be the
* same thread that calls this method, and it will not be either the GUI or
* the GL thread.
*
* Users should not start a {@code captureScreenLeft} until previous
* {@code captureScreenLeft} callback has returned. Starting a new
* {@code captureScreenLeft} before the previous {@code captureScreenLeft}
* callback returned may cause out of memory error.
*
* @param callback
* Callback function to process the capture result. It may not be
* {@code null}.
*/
public abstract void captureScreenLeft(GVRScreenshotCallback callback);
/**
* Capture a 2D screenshot from the position of right eye.
*
* The screenshot capture is done asynchronously -- the function does not
* return the result immediately. Instead, it registers a callback function
* and pass the result (when it is available) to the callback function. The
* callback will happen on a background thread: It will probably not be the
* same thread that calls this method, and it will not be either the GUI or
* the GL thread.
*
* Users should not start a {@code captureScreenRight} until previous
* {@code captureScreenRight} callback has returned. Starting a new
* {@code captureScreenRight} before the previous {@code captureScreenRight}
* callback returned may cause out of memory error.
*
* @param callback
* Callback function to process the capture result. It may not be
* {@code null}.
*/
public abstract void captureScreenRight(GVRScreenshotCallback callback);
/**
* Capture a 3D screenshot from the position of left eye. The 3D screenshot
* is composed of six images from six directions (i.e. +x, -x, +y, -y, +z,
* and -z).
*
* The screenshot capture is done asynchronously -- the function does not
* return the result immediately. Instead, it registers a callback function
* and pass the result (when it is available) to the callback function. The
* callback will happen on a background thread: It will probably not be the
* same thread that calls this method, and it will not be either the GUI or
* the GL thread.
*
* Users should not start a {@code captureScreen3D} until previous
* {@code captureScreen3D} callback has returned. Starting a new
* {@code captureScreen3D} before the previous {@code captureScreen3D}
* callback returned may cause out of memory error.
*
* @param callback
* Callback function to process the capture result. It may not be
* {@code null}.
*
* @since 1.6.8
*/
public abstract void captureScreen3D(GVRScreenshot3DCallback callback);
}
|
GVRf/Framework/src/org/gearvrf/GVRContext.java
|
/* Copyright 2015 Samsung Electronics Co., LTD
*
* 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.gearvrf;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.EnumSet;
import org.gearvrf.GVRAndroidResource.BitmapTextureCallback;
import org.gearvrf.GVRAndroidResource.CompressedTextureCallback;
import org.gearvrf.GVRAndroidResource.MeshCallback;
import org.gearvrf.GVRAndroidResource.TextureCallback;
import org.gearvrf.GVRImportSettings;
import org.gearvrf.animation.GVRAnimation;
import org.gearvrf.animation.GVRAnimationEngine;
import org.gearvrf.asynchronous.GVRAsynchronousResourceLoader;
import org.gearvrf.asynchronous.GVRCompressedTexture;
import org.gearvrf.asynchronous.GVRCompressedTextureLoader;
import org.gearvrf.jassimp.AiColor;
import org.gearvrf.jassimp.AiMaterial;
import org.gearvrf.jassimp.AiMatrix4f;
import org.gearvrf.jassimp.AiNode;
import org.gearvrf.jassimp.AiScene;
import org.gearvrf.jassimp.AiTextureType;
import org.gearvrf.jassimp.AiWrapperProvider;
import org.gearvrf.jassimp.AiMaterial.Property;
import org.gearvrf.periodic.GVRPeriodicEngine;
import org.gearvrf.utility.Log;
import org.gearvrf.utility.ResourceCache;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.view.KeyEvent;
/**
* Like the Android {@link Context} class, {@code GVRContext} provides core
* services, and global information about an application environment.
*
* Use {@code GVRContext} to {@linkplain #createQuad(float, float) create} and
* {@linkplain #loadMesh(GVRAndroidResource) load} GL meshes, Android
* {@linkplain #loadBitmap(String) bitmaps}, and
* {@linkplain #loadTexture(GVRAndroidResource) GL textures.} {@code GVRContext}
* also holds the {@linkplain GVRScene main scene} and miscellaneous information
* like {@linkplain #getFrameTime() the frame time.}
*/
public abstract class GVRContext {
private static final String TAG = Log.tag(GVRContext.class);
private final GVRActivity mContext;
/*
* Fields and constants
*/
// Priorities constants, for asynchronous loading
/**
* GVRF can't use every {@code int} as a priority - it needs some sentinel
* values. It will probably never need anywhere near this many, but raising
* the number of reserved values narrows the 'dynamic range' available to
* apps mapping some internal score to the {@link #LOWEST_PRIORITY} to
* {@link #HIGHEST_PRIORITY} range, and might change app behavior in subtle
* ways that seem best avoided.
*
* @since 1.6.1
*/
public static final int RESERVED_PRIORITIES = 1024;
/**
* GVRF can't use every {@code int} as a priority - it needs some sentinel
* values. A simple approach to generating priorities is to score resources
* from 0 to 1, and then map that to the range {@link #LOWEST_PRIORITY} to
* {@link #HIGHEST_PRIORITY}.
*
* @since 1.6.1
*/
public static final int LOWEST_PRIORITY = Integer.MIN_VALUE
+ RESERVED_PRIORITIES;
/**
* GVRF can't use every {@code int} as a priority - it needs some sentinel
* values. A simple approach to generating priorities is to score resources
* from 0 to 1, and then map that to the range {@link #LOWEST_PRIORITY} to
* {@link #HIGHEST_PRIORITY}.
*
* @since 1.6.1
*/
public static final int HIGHEST_PRIORITY = Integer.MAX_VALUE;
/**
* The priority used by
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)}
* and
* {@link #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource)}
*
* @since 1.6.1
*/
public static final int DEFAULT_PRIORITY = 0;
/**
* The ID of the GLthread. We use this ID to prevent non-GL thread from
* calling GL functions.
*
* @since 1.6.5
*/
protected long mGLThreadID;
/**
* The default texture parameter instance for overloading texture methods
*
*/
public final GVRTextureParameters DEFAULT_TEXTURE_PARAMETERS = new GVRTextureParameters(
this);
// true or false based on the support for anisotropy
public boolean isAnisotropicSupported;
// Max anisotropic value if supported and -1 otherwise
public int maxAnisotropicValue = -1;
/*
* Methods
*/
GVRContext(GVRActivity context) {
mContext = context;
}
/**
* Get the Android {@link Context}, which provides access to system services
* and to your application's resources. Since version 2.0.1, this is
* actually your {@link GVRActivity} implementation, but you should probably
* use the new {@link #getActivity()} method, rather than casting this
* method to an {@code (Activity)} or {@code (GVRActivity)}.
*
* @return An Android {@code Context}
*/
public Context getContext() {
return mContext;
}
/**
* Get the Android {@link Activity} which launched your GVRF app.
*
* An {@code Activity} is-a {@link Context} and so provides access to system
* services and to your application's resources; the {@code Activity} class
* also provides additional services, including
* {@link Activity#runOnUiThread(Runnable)}.
*
* @return The {@link GVRActivity} which launched your GVRF app. The
* {@link GVRActivity} class doesn't actually add much useful
* functionality besides
* {@link GVRActivity#setScript(GVRScript, String)}, but returning
* the most-derived class here may prevent someone from having to
* write {@code (GVRActivity) gvrContext.getActivity();}.
*
* @since 2.0.1
*/
public GVRActivity getActivity() {
return mContext;
}
/**
* Loads a file as a {@link GVRMesh}.
*
* Note that this method can be quite slow; we recommend never calling it
* from the GL thread. The asynchronous version
* {@link #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource)} is
* better because it moves most of the work to a background thread, doing as
* little as possible on the GL thread.
*
* @param androidResource
* Basically, a stream containing a 3D model. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @return The file as a GL mesh.
*
* @since 1.6.2
*/
public GVRMesh loadMesh(GVRAndroidResource androidResource) {
return loadMesh(androidResource,
GVRImportSettings.getRecommendedSettings());
}
/**
* Loads a file as a {@link GVRMesh}.
*
* Note that this method can be quite slow; we recommend never calling it
* from the GL thread. The asynchronous version
* {@link #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource)} is
* better because it moves most of the work to a background thread, doing as
* little as possible on the GL thread.
*
* @param androidResource
* Basically, a stream containing a 3D model. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
*
* @param settings
* Additional import {@link GVRImpotSettings settings}.
* @return The file as a GL mesh.
*
* @since 1.6.2
*/
public GVRMesh loadMesh(GVRAndroidResource androidResource,
EnumSet<GVRImportSettings> settings) {
GVRMesh mesh = sMeshCache.get(androidResource);
if (mesh == null) {
GVRAssimpImporter assimpImporter = GVRImporter
.readFileFromResources(this, androidResource, settings);
mesh = assimpImporter.getMesh(0);
sMeshCache.put(androidResource, mesh);
}
return mesh;
}
private final static ResourceCache<GVRMesh> sMeshCache = new ResourceCache<GVRMesh>();
/**
* Loads a mesh file, asynchronously, at a default priority.
*
* This method and the
* {@linkplain #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource, int)
* overload that takes a priority} are generally going to be your best
* choices for loading {@link GVRMesh} resources: mesh loading can take
* hundreds - and even thousands - of milliseconds, and so should not be
* done on the GL thread in either {@link GVRScript#onInit(GVRContext)
* onInit()} or {@link GVRScript#onStep() onStep()}.
*
* <p>
* The asynchronous methods improve throughput in three ways. First, by
* doing all the work on a background thread, then delivering the loaded
* mesh to the GL thread on a {@link #runOnGlThread(Runnable)
* runOnGlThread()} callback. Second, they use a throttler to avoid
* overloading the system and/or running out of memory. Third, they do
* 'request consolidation' - if you issue any requests for a particular file
* while there is still a pending request, the file will only be read once,
* and each callback will get the same {@link GVRMesh}.
*
* @param callback
* App supplied callback, with three different methods.
* <ul>
* <li>Before loading, GVRF may call
* {@link GVRAndroidResource.MeshCallback#stillWanted(GVRAndroidResource)
* stillWanted()} (on a background thread) to give you a chance
* to abort a 'stale' load.
*
* <li>Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread.
*
* <li>Any errors will call
* {@link GVRAndroidResource.MeshCallback#failed(Throwable, GVRAndroidResource)
* failed(),} with no promises about threading.
* </ul>
* @param androidResource
* Basically, a stream containing a 3D model. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @throws IllegalArgumentException
* If either parameter is {@code null} or if you 'abuse' request
* consolidation by passing the same {@link GVRAndroidResource}
* descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
* @since 1.6.2
*/
public void loadMesh(MeshCallback callback,
GVRAndroidResource androidResource) throws IllegalArgumentException {
loadMesh(callback, androidResource, DEFAULT_PRIORITY);
}
/**
* Loads a mesh file, asynchronously, at an explicit priority.
*
* This method and the
* {@linkplain #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource)
* overload that supplies a default priority} are generally going to be your
* best choices for loading {@link GVRMesh} resources: mesh loading can take
* hundreds - and even thousands - of milliseconds, and so should not be
* done on the GL thread in either {@link GVRScript#onInit(GVRContext)
* onInit()} or {@link GVRScript#onStep() onStep()}.
*
* <p>
* The asynchronous methods improve throughput in three ways. First, by
* doing all the work on a background thread, then delivering the loaded
* mesh to the GL thread on a {@link #runOnGlThread(Runnable)
* runOnGlThread()} callback. Second, they use a throttler to avoid
* overloading the system and/or running out of memory. Third, they do
* 'request consolidation' - if you issue any requests for a particular file
* while there is still a pending request, the file will only be read once,
* and each callback will get the same {@link GVRMesh}.
*
* @param callback
* App supplied callback, with three different methods.
* <ul>
* <li>Before loading, GVRF may call
* {@link GVRAndroidResource.MeshCallback#stillWanted(GVRAndroidResource)
* stillWanted()} (on a background thread) to give you a chance
* to abort a 'stale' load.
*
* <li>Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread.
*
* <li>Any errors will call
* {@link GVRAndroidResource.MeshCallback#failed(Throwable, GVRAndroidResource)
* failed(),} with no promises about threading.
* </ul>
* @param resource
* Basically, a stream containing a 3D model. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>.
*
* @throws IllegalArgumentException
* If either {@code callback} or {@code resource} is
* {@code null}, or if {@code priority} is out of range - or if
* you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
* @since 1.6.2
*/
public void loadMesh(MeshCallback callback, GVRAndroidResource resource,
int priority) throws IllegalArgumentException {
GVRAsynchronousResourceLoader.loadMesh(this, callback, resource,
priority);
}
/**
* Simple, high-level method to load a mesh asynchronously, for use with
* {@link GVRRenderData#setMesh(Future)}.
*
* This method uses a default priority; use
* {@link #loadFutureMesh(GVRAndroidResource, int)} to specify a priority;
* use one of the lower-level
* {@link #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource)}
* methods to get more control over loading.
*
* @param resource
* Basically, a stream containing a 3D model. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @return A {@link Future} that you can pass to
* {@link GVRRenderData#setMesh(Future)}
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public Future<GVRMesh> loadFutureMesh(GVRAndroidResource resource) {
return loadFutureMesh(resource, DEFAULT_PRIORITY);
}
/**
* Simple, high-level method to load a mesh asynchronously, for use with
* {@link GVRRenderData#setMesh(Future)}.
*
* This method trades control for convenience; use one of the lower-level
* {@link #loadMesh(GVRAndroidResource.MeshCallback, GVRAndroidResource)}
* methods if, say, you want to do something more than just
* {@link GVRRenderData#setMesh(GVRMesh)} when the mesh loads.
*
* @param resource
* Basically, a stream containing a 3D model. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>.
* @return A {@link Future} that you can pass to
* {@link GVRRenderData#setMesh(Future)}
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public Future<GVRMesh> loadFutureMesh(GVRAndroidResource resource,
int priority) {
return GVRAsynchronousResourceLoader.loadFutureMesh(this, resource,
priority);
}
/**
* Simple, high-level method to load a scene as {@link GVRSceneObject} from
* 3D model.
*
* @param assetRelativeFilename
* A filename, relative to the {@code assets} directory. The file
* can be in a sub-directory of the {@code assets} directory:
* {@code "foo/bar.png"} will open the file
* {@code assets/foo/bar.png}
*
* @return A {@link GVRSceneObject} that contains the meshes with textures
*
* @throws IOException
* File does not exist or cannot be read
*/
public GVRSceneObject getAssimpModel(String assetRelativeFilename)
throws IOException {
return getAssimpModel(assetRelativeFilename,
GVRImportSettings.getRecommendedSettings());
}
/**
* Simple, high-level method to load a scene as {@link GVRSceneObject} from
* 3D model.
*
* @param assetRelativeFilename
* A filename, relative to the {@code assets} directory. The file
* can be in a sub-directory of the {@code assets} directory:
* {@code "foo/bar.png"} will open the file
* {@code assets/foo/bar.png}
*
* @param settings
* Additional import {@link GVRImportSettings settings}
* @return A {@link GVRSceneObject} that contains the meshes with textures
*
* @throws IOException
* File does not exist or cannot be read
*/
public GVRSceneObject getAssimpModel(String assetRelativeFilename,
EnumSet<GVRImportSettings> settings) throws IOException {
GVRAssimpImporter assimpImporter = GVRImporter.readFileFromResources(
this, new GVRAndroidResource(this, assetRelativeFilename),
settings);
GVRSceneObject wholeSceneObject = new GVRSceneObject(this);
AiScene assimpScene = assimpImporter.getAssimpScene();
AiWrapperProvider<byte[], AiMatrix4f, AiColor, AiNode, byte[]> wrapperProvider = new AiWrapperProvider<byte[], AiMatrix4f, AiColor, AiNode, byte[]>() {
/**
* Wraps a RGBA color.
* <p>
*
* A color consists of 4 float values (r,g,b,a) starting from offset
*
* @param buffer
* the buffer to wrap
* @param offset
* the offset into buffer
* @return the wrapped color
*/
@Override
public AiColor wrapColor(ByteBuffer buffer, int offset) {
AiColor color = new AiColor(buffer, offset);
return color;
}
/**
* Wraps a 4x4 matrix of floats.
* <p>
*
* The calling code will allocate a new array for each invocation of
* this method. It is safe to store a reference to the passed in
* array and use the array to store the matrix data.
*
* @param data
* the matrix data in row-major order
* @return the wrapped matrix
*/
@Override
public AiMatrix4f wrapMatrix4f(float[] data) {
AiMatrix4f transformMatrix = new AiMatrix4f(data);
return transformMatrix;
}
/**
* Wraps a quaternion.
* <p>
*
* A quaternion consists of 4 float values (w,x,y,z) starting from
* offset
*
* @param buffer
* the buffer to wrap
* @param offset
* the offset into buffer
* @return the wrapped quaternion
*/
@Override
public byte[] wrapQuaternion(ByteBuffer buffer, int offset) {
byte[] quaternion = new byte[4];
buffer.get(quaternion, offset, 4);
return quaternion;
}
/**
* Wraps a scene graph node.
* <p>
*
* See {@link AiNode} for a description of the scene graph structure
* used by assimp.
* <p>
*
* The parent node is either null or an instance returned by this
* method. It is therefore safe to cast the passed in parent object
* to the implementation specific type
*
* @param parent
* the parent node
* @param matrix
* the transformation matrix
* @param meshReferences
* array of mesh references (indexes)
* @param name
* the name of the node
* @return the wrapped scene graph node
*/
@Override
public AiNode wrapSceneNode(Object parent, Object matrix,
int[] meshReferences, String name) {
AiNode node = new AiNode(null, matrix, meshReferences, name);
return node;
}
/**
* Wraps a vector.
* <p>
*
* Most vectors are 3-dimensional, i.e., with 3 components. The
* exception are texture coordinates, which may be 1- or
* 2-dimensional. A vector consists of numComponents floats (x,y,z)
* starting from offset
*
* @param buffer
* the buffer to wrap
* @param offset
* the offset into buffer
* @param numComponents
* the number of components
* @return the wrapped vector
*/
@Override
public byte[] wrapVector3f(ByteBuffer buffer, int offset,
int numComponents) {
byte[] warpedVector = new byte[numComponents];
buffer.get(warpedVector, offset, numComponents);
return warpedVector;
}
};
AiNode rootNode = assimpScene.getSceneRoot(wrapperProvider);
// Recurse through the entire hierarchy to attache all the meshes as
// Scene Object
this.recurseAssimpNodes(assetRelativeFilename, wholeSceneObject,
rootNode, wrapperProvider);
return wholeSceneObject;
}
/**
* Helper method to recurse through all the assimp nodes and get all their
* meshes that can be used to create {@link GVRSceneObject} to be attached
* to the set of complete scene objects for the assimp model.
*
* @param assetRelativeFilename
* A filename, relative to the {@code assets} directory. The file
* can be in a sub-directory of the {@code assets} directory:
* {@code "foo/bar.png"} will open the file
* {@code assets/foo/bar.png}
*
* @param wholeSceneObject
* A reference of the {@link GVRSceneObject}, to which all other
* scene objects are attached.
*
* @param node
* A reference to the AiNode for which we want to recurse all its
* children and meshes.
*
* @param wrapperProvider
* AiWrapperProvider for unwrapping Jassimp properties.
*
*/
private void recurseAssimpNodes(
String assetRelativeFilename,
GVRSceneObject wholeSceneObject,
AiNode node,
AiWrapperProvider<byte[], AiMatrix4f, AiColor, AiNode, byte[]> wrapperProvider) {
try {
for (int i = 0; i < node.getNumMeshes(); i++) {
FutureWrapper<GVRMesh> futureMesh = new FutureWrapper<GVRMesh>(
this.getNodeMesh(new GVRAndroidResource(this,
assetRelativeFilename), node.getName(), i));
AiMaterial material = this.getMeshMaterial(
new GVRAndroidResource(this, assetRelativeFilename),
node.getName(), i);
Property property = material.getProperty("$tex.file");
if (property != null) {
int textureIndex = property.getIndex();
String texFileName = material.getTextureFile(
AiTextureType.DIFFUSE, textureIndex);
Future<GVRTexture> futureMeshTexture = this
.loadFutureTexture(new GVRAndroidResource(this,
texFileName));
GVRSceneObject sceneObject = new GVRSceneObject(this,
futureMesh, futureMeshTexture);
// add the scene object to the scene graph
wholeSceneObject.addChildObject(sceneObject);
} else {
// The case when there is no texture
// This block also takes care for the case when there
// are no texture or color for the mesh as the methods
// that are used for getting the colors of the material
// returns a default when they are not present
AiColor diffuseColor = material
.getDiffuseColor(wrapperProvider);
AiColor ambientColor = material
.getAmbientColor(wrapperProvider);
float opacity = material.getOpacity();
final String DIFFUSE_COLOR_KEY = "diffuse_color";
final String AMBIENT_COLOR_KEY = "ambient_color";
final String COLOR_OPACITY_KEY = "opacity";
final String VERTEX_SHADER = "attribute vec4 a_position;\n"
+ "uniform mat4 u_mvp;\n" + "void main() {\n"
+ " gl_Position = u_mvp * a_position;\n" + "}\n";
final String FRAGMENT_SHADER = "precision mediump float;\n"
+ "uniform vec4 diffuse_color;\n" //
+ "uniform vec4 ambient_color;\n"
+ "uniform float opacity;\n"
+ "void main() {\n" //
+ " gl_FragColor = ( diffuse_color * opacity ) + ambient_color;\n"
+ "}\n";
GVRCustomMaterialShaderId mShaderId;
GVRMaterialMap mCustomShader = null;
final GVRMaterialShaderManager shaderManager = this
.getMaterialShaderManager();
mShaderId = shaderManager.addShader(VERTEX_SHADER,
FRAGMENT_SHADER);
mCustomShader = shaderManager.getShaderMap(mShaderId);
mCustomShader.addUniformVec4Key("diffuse_color",
DIFFUSE_COLOR_KEY);
mCustomShader.addUniformVec4Key("ambient_color",
AMBIENT_COLOR_KEY);
mCustomShader.addUniformFloatKey("opacity",
COLOR_OPACITY_KEY);
GVRMaterial meshMaterial = new GVRMaterial(this, mShaderId);
meshMaterial.setVec4(DIFFUSE_COLOR_KEY,
diffuseColor.getRed(), diffuseColor.getGreen(),
diffuseColor.getBlue(), diffuseColor.getAlpha());
meshMaterial.setVec4(AMBIENT_COLOR_KEY,
ambientColor.getRed(), ambientColor.getGreen(),
ambientColor.getBlue(), ambientColor.getAlpha());
meshMaterial.setFloat(COLOR_OPACITY_KEY, opacity);
GVRSceneObject sceneObject = new GVRSceneObject(this);
GVRRenderData sceneObjectRenderData = new GVRRenderData(
this);
sceneObjectRenderData.setMesh(futureMesh);
sceneObjectRenderData.setMaterial(meshMaterial);
sceneObject.attachRenderData(sceneObjectRenderData);
wholeSceneObject.addChildObject(sceneObject);
}
}
for (int i = 0; i < node.getNumChildren(); i++) {
this.recurseAssimpNodes(assetRelativeFilename,
wholeSceneObject, node.getChildren().get(i),
wrapperProvider);
}
} catch (Exception e) {
// Error while recursing the Scene Graph
e.printStackTrace();
}
}
/**
* Retrieves the particular index mesh for the given node.
*
* @return The mesh, encapsulated as a {@link GVRMesh}.
*/
public GVRMesh getNodeMesh(GVRAndroidResource androidResource,
String nodeName, int meshIndex) {
GVRAssimpImporter assimpImporter = GVRImporter.readFileFromResources(
this, androidResource,
GVRImportSettings.getRecommendedSettings());
return assimpImporter.getNodeMesh(nodeName, meshIndex);
}
/**
* Retrieves the material for the mesh of the given node..
*
* @return The material, encapsulated as a {@link AiMaterial}.
*/
public AiMaterial getMeshMaterial(GVRAndroidResource androidResource,
String nodeName, int meshIndex) {
GVRAssimpImporter assimpImporter = GVRImporter.readFileFromResources(
this, androidResource,
GVRImportSettings.getRecommendedSettings());
return assimpImporter.getMeshMaterial(nodeName, meshIndex);
}
/**
* Creates a quad consisting of two triangles, with the specified width and
* height.
*
* @param width
* the quad's width
* @param height
* the quad's height
* @return A 2D, rectangular mesh with four vertices and two triangles
*/
public GVRMesh createQuad(float width, float height) {
GVRMesh mesh = new GVRMesh(this);
float[] vertices = { width * -0.5f, height * 0.5f, 0.0f, width * -0.5f,
height * -0.5f, 0.0f, width * 0.5f, height * 0.5f, 0.0f,
width * 0.5f, height * -0.5f, 0.0f };
mesh.setVertices(vertices);
final float[] normals = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f, 1.0f };
mesh.setNormals(normals);
final float[] texCoords = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f,
1.0f };
mesh.setTexCoords(texCoords);
char[] triangles = { 0, 1, 2, 1, 3, 2 };
mesh.setTriangles(triangles);
return mesh;
}
/**
* Loads file placed in the assets folder, as a {@link Bitmap}.
*
* <p>
* Note that this method may take hundreds of milliseconds to return: unless
* the bitmap is quite tiny, you probably don't want to call this directly
* from your {@link GVRScript#onStep() onStep()} callback as that is called
* once per frame, and a long call will cause you to miss frames.
*
* <p>
* Note also that this method does no scaling, and will return a full-size
* {@link Bitmap}. Loading (say) an unscaled photograph may abort your app:
* Use pre-scaled images, or {@link BitmapFactory} methods which give you
* more control over the image size.
*
* @param fileName
* The name of a file, relative to the assets directory. The
* assets directory may contain an arbitrarily complex tree of
* subdirectories; the file name can specify any location in or
* under the assets directory.
* @return The file as a bitmap, or {@code null} if file path does not exist
* or the file can not be decoded into a Bitmap.
*/
public Bitmap loadBitmap(String fileName) {
if (fileName == null) {
throw new IllegalArgumentException("File name should not be null.");
}
InputStream stream = null;
Bitmap bitmap = null;
try {
try {
stream = mContext.getAssets().open(fileName);
return bitmap = BitmapFactory.decodeStream(stream);
} finally {
if (stream != null) {
stream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
// Don't discard a valid Bitmap because of an IO error closing the
// file!
return bitmap;
}
}
/**
* Loads file placed in the assets folder, as a {@link GVRBitmapTexture}.
*
* <p>
* Note that this method may take hundreds of milliseconds to return: unless
* the texture is quite tiny, you probably don't want to call this directly
* from your {@link GVRScript#onStep() onStep()} callback as that is called
* once per frame, and a long call will cause you to miss frames. For large
* images, you should use either
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} (faster) or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)}
* (fastest <em>and</em> least memory pressure).
*
* <p>
* Note also that this method does no scaling, and will return a full-size
* {@link Bitmap}. Loading (say) an unscaled photograph may abort your app:
* Use
* <ul>
* <li>Pre-scaled images
* <li>{@link BitmapFactory} methods which give you more control over the
* image size, or
* <li>
* {@link #loadTexture(GVRAndroidResource)} or
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)}
* which automatically scale large images to fit the GPU's restrictions and
* to avoid {@linkplain OutOfMemoryError out of memory errors.}
* </ul>
*
* @param fileName
* The name of a file, relative to the assets directory. The
* assets directory may contain an arbitrarily complex tree of
* sub-directories; the file name can specify any location in or
* under the assets directory.
* @return The file as a texture, or {@code null} if file path does not
* exist or the file can not be decoded into a Bitmap.
*
* @deprecated We will remove this uncached, blocking function during Q3 of
* 2015. We suggest that you switch to
* {@link #loadTexture(GVRAndroidResource)}
*
*/
public GVRBitmapTexture loadTexture(String fileName) {
return loadTexture(fileName, DEFAULT_TEXTURE_PARAMETERS);
}
/**
* Loads file placed in the assets folder, as a {@link GVRBitmapTexture}
* with the user provided texture parameters.
*
* <p>
* Note that this method may take hundreds of milliseconds to return: unless
* the texture is quite tiny, you probably don't want to call this directly
* from your {@link GVRScript#onStep() onStep()} callback as that is called
* once per frame, and a long call will cause you to miss frames. For large
* images, you should use either
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} (faster) or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)}
* (fastest <em>and</em> least memory pressure).
*
* <p>
* Note also that this method does no scaling, and will return a full-size
* {@link Bitmap}. Loading (say) an unscaled photograph may abort your app:
* Use
* <ul>
* <li>Pre-scaled images
* <li>{@link BitmapFactory} methods which give you more control over the
* image size, or
* <li>
* {@link #loadTexture(GVRAndroidResource)} or
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)}
* which automatically scale large images to fit the GPU's restrictions and
* to avoid {@linkplain OutOfMemoryError out of memory errors.}
* </ul>
*
* @param fileName
* The name of a file, relative to the assets directory. The
* assets directory may contain an arbitrarily complex tree of
* sub-directories; the file name can specify any location in or
* under the assets directory.
* @param textureParameters
* The texture parameter object which has all the values that
* were provided by the user for texture enhancement. The
* {@link GVRTextureParameters} class has methods to set all the
* texture filters and wrap states.
* @return The file as a texture, or {@code null} if file path does not
* exist or the file can not be decoded into a Bitmap.
*
* @deprecated We will remove this uncached, blocking function during Q3 of
* 2015. We suggest that you switch to
* {@link #loadTexture(GVRAndroidResource)}
*
*/
@SuppressWarnings("resource")
public GVRBitmapTexture loadTexture(String fileName,
GVRTextureParameters textureParameters) {
assertGLThread();
if (fileName.endsWith(".png")) { // load png directly to texture
return new GVRBitmapTexture(this, fileName);
}
Bitmap bitmap = loadBitmap(fileName);
return bitmap == null ? null : new GVRBitmapTexture(this, bitmap,
textureParameters);
}
/**
* Loads file placed in the assets folder, as a {@link GVRBitmapTexture}.
*
* <p>
* Note that this method may take hundreds of milliseconds to return: unless
* the texture is quite tiny, you probably don't want to call this directly
* from your {@link GVRScript#onStep() onStep()} callback as that is called
* once per frame, and a long call will cause you to miss frames. For large
* images, you should use either
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} (faster) or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)}
* (fastest <em>and</em> least memory pressure).
*
* <p>
* This method automatically scales large images to fit the GPU's
* restrictions and to avoid {@linkplain OutOfMemoryError out of memory
* errors.} </ul>
*
* @param resource
* Basically, a stream containing a bitmap texture. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @return The file as a texture, or {@code null} if the file can not be
* decoded into a Bitmap.
*
* @since 1.6.5
*/
public GVRTexture loadTexture(GVRAndroidResource resource) {
return loadTexture(resource, DEFAULT_TEXTURE_PARAMETERS);
}
/**
* Loads file placed in the assets folder, as a {@link GVRBitmapTexture}
* with the user provided texture parameters.
*
* <p>
* Note that this method may take hundreds of milliseconds to return: unless
* the texture is quite tiny, you probably don't want to call this directly
* from your {@link GVRScript#onStep() onStep()} callback as that is called
* once per frame, and a long call will cause you to miss frames. For large
* images, you should use either
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} (faster) or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)}
* (fastest <em>and</em> least memory pressure).
*
* <p>
* This method automatically scales large images to fit the GPU's
* restrictions and to avoid {@linkplain OutOfMemoryError out of memory
* errors.} </ul>
*
* @param resource
* Basically, a stream containing a bitmap texture. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param textureParameters
* The texture parameter object which has all the values that
* were provided by the user for texture enhancement. The
* {@link GVRTextureParameters} class has methods to set all the
* texture filters and wrap states.
* @return The file as a texture, or {@code null} if the file can not be
* decoded into a Bitmap.
*
*/
public GVRTexture loadTexture(GVRAndroidResource resource,
GVRTextureParameters textureParameters) {
GVRTexture texture = sTextureCache.get(resource);
if (texture == null) {
assertGLThread();
Bitmap bitmap = GVRAsynchronousResourceLoader.decodeStream(
resource.getStream(), false);
resource.closeStream();
texture = bitmap == null ? null : new GVRBitmapTexture(this,
bitmap, textureParameters);
if (texture != null) {
sTextureCache.put(resource, texture);
}
}
return texture;
}
private final static ResourceCache<GVRTexture> sTextureCache = new ResourceCache<GVRTexture>();
/**
* Loads a cube map texture synchronously.
*
* <p>
* Note that this method may take hundreds of milliseconds to return: unless
* the cube map is quite tiny, you probably don't want to call this directly
* from your {@link GVRScript#onStep() onStep()} callback as that is called
* once per frame, and a long call will cause you to miss frames.
*
* @param resourceArray
* An array containing six resources for six bitmaps. The order
* of the bitmaps is important to the correctness of the cube map
* texture. The six bitmaps should correspond to +x, -x, +y, -y,
* +z, and -z faces of the cube map texture respectively.
* @return The cube map texture, or {@code null} if the length of
* rsourceArray is not 6.
*
* @since 1.6.9
*/
/*
* TODO Deprecate, and replace with an overload that takes a single
* GVRAndroidResource which specifies a zip file ... and caches result
*/
public GVRCubemapTexture loadCubemapTexture(
GVRAndroidResource[] resourceArray) {
return loadCubemapTexture(resourceArray, DEFAULT_TEXTURE_PARAMETERS);
}
// Texture parameters
public GVRCubemapTexture loadCubemapTexture(
GVRAndroidResource[] resourceArray,
GVRTextureParameters textureParameters) {
assertGLThread();
if (resourceArray.length != 6) {
return null;
}
Bitmap[] bitmapArray = new Bitmap[6];
for (int i = 0; i < 6; i++) {
bitmapArray[i] = GVRAsynchronousResourceLoader.decodeStream(
resourceArray[i].getStream(), false);
resourceArray[i].closeStream();
}
return new GVRCubemapTexture(this, bitmapArray, textureParameters);
}
/**
* Throws an exception if the current thread is not a GL thread.
*
* @since 1.6.5
*
*/
private void assertGLThread() {
if (Thread.currentThread().getId() != mGLThreadID) {
throw new RuntimeException(
"Should not run GL functions from a non-GL thread!");
}
}
/**
* Load a bitmap, asynchronously, with a default priority.
*
* Because it is asynchronous, this method <em>is</em> a bit harder to use
* than {@link #loadTexture(String)}, but it moves a large amount of work
* (in {@link BitmapFactory#decodeStream(InputStream)} from the GL thread to
* a background thread. Since you <em>can</em> create a
* {@link GVRSceneObject} without a mesh and texture - and set them later -
* using the asynchronous API can improve startup speed and/or reduce frame
* misses (where an {@link GVRScript#onStep() onStep()} takes too long).
* This API may also use less RAM than {@link #loadTexture(String)}.
*
* <p>
* This API will 'consolidate' requests: If you request a texture like
* {@code R.raw.wood_grain} and then - before it has loaded - issue another
* request for {@code R.raw.wood_grain}, GVRF will only read the bitmap file
* once; only create a single {@link GVRTexture}; and then call both
* callbacks, passing each the same texture.
*
* <p>
* Please be aware that {@link BitmapFactory#decodeStream(InputStream)} is a
* comparatively expensive operation: it can take hundreds of milliseconds
* and use several megabytes of temporary RAM. GVRF includes a throttler to
* keep the total load manageable - but
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)}
* is <em>much</em> faster and lighter-weight: that API simply loads the
* compressed texture into a small amount RAM (which doesn't take very long)
* and does some simple parsing to figure out the parameters to pass
* {@code glCompressedTexImage2D()}. The GL hardware does the decoding much
* faster than Android's {@link BitmapFactory}!
*
* <p>
* TODO Take a boolean parameter that controls mipmap generation?
*
* @since 1.6.1
*
* @param callback
* Before loading, GVRF may call
* {@link GVRAndroidResource.BitmapTextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} several times (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread;
*
* any errors will call
* {@link GVRAndroidResource.BitmapTextureCallback#failed(Throwable, GVRAndroidResource)
* failed()}, with no promises about threading.
*
* <p>
* This method uses a throttler to avoid overloading the system.
* If the throttler has threads available, it will run this
* request immediately. Otherwise, it will enqueue the request,
* and call
* {@link GVRAndroidResource.BitmapTextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} at least once (on a background thread) to give
* you a chance to abort a 'stale' load.
* @param resource
* Basically, a stream containing a bitmapped image. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadBitmapTexture(BitmapTextureCallback callback,
GVRAndroidResource resource) {
loadBitmapTexture(callback, resource, DEFAULT_PRIORITY);
}
/**
* Load a bitmap, asynchronously, with an explicit priority.
*
* Because it is asynchronous, this method <em>is</em> a bit harder to use
* than {@link #loadTexture(String)}, but it moves a large amount of work
* (in {@link BitmapFactory#decodeStream(InputStream)} from the GL thread to
* a background thread. Since you <em>can</em> create a
* {@link GVRSceneObject} without a mesh and texture - and set them later -
* using the asynchronous API can improve startup speed and/or reduce frame
* misses, where an {@link GVRScript#onStep() onStep()} takes too long.
*
* <p>
* This API will 'consolidate' requests: If you request a texture like
* {@code R.raw.wood_grain} and then - before it has loaded - issue another
* request for {@code R.raw.wood_grain}, GVRF will only read the bitmap file
* once; only create a single {@link GVRTexture}; and then call both
* callbacks, passing each the same texture.
*
* <p>
* Please be aware that {@link BitmapFactory#decodeStream(InputStream)} is a
* comparatively expensive operation: it can take hundreds of milliseconds
* and use several megabytes of temporary RAM. GVRF includes a throttler to
* keep the total load manageable - but
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)}
* is <em>much</em> faster and lighter-weight: that API simply loads the
* compressed texture into a small amount RAM (which doesn't take very long)
* and does some simple parsing to figure out the parameters to pass
* {@code glCompressedTexImage2D()}. The GL hardware does the decoding much
* faster than Android's {@link BitmapFactory}!
*
* @since 1.6.1
*
* @param callback
* Before loading, GVRF may call
* {@link GVRAndroidResource.BitmapTextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} several times (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread;
*
* any errors will call
* {@link GVRAndroidResource.BitmapTextureCallback#failed(Throwable, GVRAndroidResource)
* failed()}, with no promises about threading.
*
* <p>
* This method uses a throttler to avoid overloading the system.
* If the throttler has threads available, it will run this
* request immediately. Otherwise, it will enqueue the request,
* and call
* {@link GVRAndroidResource.BitmapTextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} at least once (on a background thread) to give
* you a chance to abort a 'stale' load.
* @param resource
* Basically, a stream containing a bitmapped image. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>.
*
* @throws IllegalArgumentException
* If {@code priority} {@literal <} {@link #LOWEST_PRIORITY} or
* {@literal >} {@link #HIGHEST_PRIORITY}, or either of the
* other parameters is {@code null} - or if you 'abuse' request
* consolidation by passing the same {@link GVRAndroidResource}
* descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadBitmapTexture(BitmapTextureCallback callback,
GVRAndroidResource resource, int priority)
throws IllegalArgumentException {
GVRAsynchronousResourceLoader.loadBitmapTexture(this, sTextureCache,
callback, resource, priority);
}
/**
* Load a compressed texture, asynchronously.
*
* GVRF currently supports ASTC, ETC2, and KTX formats: applications can add
* new formats by implementing {@link GVRCompressedTextureLoader}.
*
* <p>
* This method uses the fastest possible rendering. To specify higher
* quality (but slower) rendering, you can use the
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource, int)}
* overload.
*
* @since 1.6.1
*
* @param callback
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread; any errors will call
* {@link GVRAndroidResource.CompressedTextureCallback#failed(Throwable, GVRAndroidResource)
* failed()}, with no promises about threading.
* @param resource
* Basically, a stream containing a compressed texture. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadCompressedTexture(CompressedTextureCallback callback,
GVRAndroidResource resource) {
GVRAsynchronousResourceLoader.loadCompressedTexture(this,
sTextureCache, callback, resource);
}
/**
* Load a compressed texture, asynchronously.
*
* GVRF currently supports ASTC, ETC2, and KTX formats: applications can add
* new formats by implementing {@link GVRCompressedTextureLoader}.
*
* @since 1.6.1
*
* @param callback
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)}
* on the GL thread; any errors will call
* {@link GVRAndroidResource.CompressedTextureCallback#failed(Throwable, GVRAndroidResource)}
* , with no promises about threading.
* @param resource
* Basically, a stream containing a compressed texture. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param quality
* Speed/quality tradeoff: should be one of
* {@link GVRCompressedTexture#SPEED},
* {@link GVRCompressedTexture#BALANCED}, or
* {@link GVRCompressedTexture#QUALITY}, but other values are
* 'clamped' to one of the recognized values.
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadCompressedTexture(CompressedTextureCallback callback,
GVRAndroidResource resource, int quality) {
GVRAsynchronousResourceLoader.loadCompressedTexture(this,
sTextureCache, callback, resource, quality);
}
/**
* A simplified, low-level method that loads a texture asynchronously,
* without making you specify
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)
* loadCompressedTexture()}.
*
* This method can detect whether the resource file holds a compressed
* texture (GVRF currently supports ASTC, ETC2, and KTX formats:
* applications can add new formats by implementing
* {@link GVRCompressedTextureLoader}): if the file is not a compressed
* texture, it is loaded as a normal, bitmapped texture. This format
* detection adds very little to the cost of loading even a compressed
* texture, and it makes your life a lot easier: you can replace, say,
* {@code res/raw/resource.png} with {@code res/raw/resource.etc2} without
* having to change any code.
*
* <p>
* This method uses a default priority and a default render quality: Use
* {@link #loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource, int)}
* to specify an explicit priority, and
* {@link #loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource, int, int)}
* to specify an explicit quality.
*
* <p>
* We will continue to support the {@code loadBitmapTexture()} and
* {@code loadCompressedTexture()} APIs for at least a little while: We
* haven't yet decided whether to deprecate them or not.
*
* @param callback
* Before loading, GVRF may call
* {@link GVRAndroidResource.TextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} several times (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread;
*
* any errors will call
* {@link GVRAndroidResource.TextureCallback#failed(Throwable, GVRAndroidResource)
* failed()}, with no promises about threading.
*
* <p>
* This method uses a throttler to avoid overloading the system.
* If the throttler has threads available, it will run this
* request immediately. Otherwise, it will enqueue the request,
* and call
* {@link GVRAndroidResource.TextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} at least once (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* <p>
* Use {@link #loadFutureTexture(GVRAndroidResource)} to avoid
* having to implement a callback.
* @param resource
* Basically, a stream containing a texture file. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadTexture(TextureCallback callback,
GVRAndroidResource resource) {
loadTexture(callback, resource, DEFAULT_PRIORITY);
}
/**
* A simplified, low-level method that loads a texture asynchronously,
* without making you specify
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)
* loadCompressedTexture()}.
*
* This method can detect whether the resource file holds a compressed
* texture (GVRF currently supports ASTC, ETC2, and KTX formats:
* applications can add new formats by implementing
* {@link GVRCompressedTextureLoader}): if the file is not a compressed
* texture, it is loaded as a normal, bitmapped texture. This format
* detection adds very little to the cost of loading even a compressed
* texture, and it makes your life a lot easier: you can replace, say,
* {@code res/raw/resource.png} with {@code res/raw/resource.etc2} without
* having to change any code.
*
* <p>
* This method uses a default render quality: Use
* {@link #loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource, int, int)}
* to specify an explicit quality.
*
* <p>
* We will continue to support the {@code loadBitmapTexture()} and
* {@code loadCompressedTexture()} APIs for at least a little while: We
* haven't yet decided whether to deprecate them or not.
*
* @param callback
* Before loading, GVRF may call
* {@link GVRAndroidResource.TextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} several times (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread;
*
* any errors will call
* {@link GVRAndroidResource.TextureCallback#failed(Throwable, GVRAndroidResource)
* failed()}, with no promises about threading.
*
* <p>
* This method uses a throttler to avoid overloading the system.
* If the throttler has threads available, it will run this
* request immediately. Otherwise, it will enqueue the request,
* and call
* {@link GVRAndroidResource.TextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} at least once (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* <p>
* Use {@link #loadFutureTexture(GVRAndroidResource)} to avoid
* having to implement a callback.
* @param resource
* Basically, a stream containing a texture file. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>. Also, please note priorities only apply to
* uncompressed textures (standard Android bitmap files, which
* can take hundreds of milliseconds to load): compressed
* textures load so quickly that they are not run through the
* request scheduler.
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadTexture(TextureCallback callback,
GVRAndroidResource resource, int priority) {
loadTexture(callback, resource, priority, GVRCompressedTexture.BALANCED);
}
/**
* A simplified, low-level method that loads a texture asynchronously,
* without making you specify
* {@link #loadBitmapTexture(GVRAndroidResource.BitmapTextureCallback, GVRAndroidResource)
* loadBitmapTexture()} or
* {@link #loadCompressedTexture(GVRAndroidResource.CompressedTextureCallback, GVRAndroidResource)
* loadCompressedTexture()}.
*
* This method can detect whether the resource file holds a compressed
* texture (GVRF currently supports ASTC, ETC2, and KTX formats:
* applications can add new formats by implementing
* {@link GVRCompressedTextureLoader}): if the file is not a compressed
* texture, it is loaded as a normal, bitmapped texture. This format
* detection adds very little to the cost of loading even a compressed
* texture, and it makes your life a lot easier: you can replace, say,
* {@code res/raw/resource.png} with {@code res/raw/resource.etc2} without
* having to change any code.
*
* <p>
* We will continue to support the {@code loadBitmapTexture()} and
* {@code loadCompressedTexture()} APIs for at least a little while: We
* haven't yet decided whether to deprecate them or not.
*
* @param callback
* Before loading, GVRF may call
* {@link GVRAndroidResource.TextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} several times (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* Successful loads will call
* {@link GVRAndroidResource.Callback#loaded(GVRHybridObject, GVRAndroidResource)
* loaded()} on the GL thread;
*
* any errors will call
* {@link GVRAndroidResource.TextureCallback#failed(Throwable, GVRAndroidResource)
* failed()}, with no promises about threading.
*
* <p>
* This method uses a throttler to avoid overloading the system.
* If the throttler has threads available, it will run this
* request immediately. Otherwise, it will enqueue the request,
* and call
* {@link GVRAndroidResource.TextureCallback#stillWanted(GVRAndroidResource)
* stillWanted()} at least once (on a background thread) to give
* you a chance to abort a 'stale' load.
*
* <p>
* Use {@link #loadFutureTexture(GVRAndroidResource)} to avoid
* having to implement a callback.
* @param resource
* Basically, a stream containing a texture file. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>. Also, please note priorities only apply to
* uncompressed textures (standard Android bitmap files, which
* can take hundreds of milliseconds to load): compressed
* textures load so quickly that they are not run through the
* request scheduler.
* @param quality
* The compressed texture {@link GVRCompressedTexture#mQuality
* quality} parameter: should be one of
* {@link GVRCompressedTexture#SPEED},
* {@link GVRCompressedTexture#BALANCED}, or
* {@link GVRCompressedTexture#QUALITY}, but other values are
* 'clamped' to one of the recognized values. Please note that
* this (currently) only applies to compressed textures; normal
* {@linkplain GVRBitmapTexture bitmapped textures} don't take a
* quality parameter.
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public void loadTexture(TextureCallback callback,
GVRAndroidResource resource, int priority, int quality) {
GVRAsynchronousResourceLoader.loadTexture(this, sTextureCache,
callback, resource, priority, quality);
}
/**
* Simple, high-level method to load a texture asynchronously, for use with
* {@link GVRShaders#setMainTexture(Future)} and
* {@link GVRShaders#setTexture(String, Future)}.
*
* This method uses a default priority and a default render quality: use
* {@link #loadFutureTexture(GVRAndroidResource, int)} to specify a priority
* or {@link #loadFutureTexture(GVRAndroidResource, int, int)} to specify a
* priority and render quality.
*
* <p>
* This method is significantly easier to use than
* {@link #loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource)}
* : you don't have to implement a callback; you don't have to pay attention
* to the low-level details of
* {@linkplain GVRSceneObject#attachRenderData(GVRRenderData) attaching} a
* {@link GVRRenderData} to your scene object. What's more, you don't even
* lose any functionality: {@link Future#cancel(boolean)} lets you cancel a
* 'stale' request, just like
* {@link GVRAndroidResource.CancelableCallback#stillWanted(GVRAndroidResource)
* stillWanted()} does. The flip side, of course, is that it <em>is</em> a
* bit more expensive: methods like
* {@link GVRMaterial#setMainTexture(Future)} use an extra thread from the
* thread pool to wait for the blocking {@link Future#get()} call. For
* modest numbers of loads, this overhead is acceptable - but thread
* creation is not free, and if your {@link GVRScript#onInit(GVRContext)
* onInit()} method fires of dozens of future loads, you may well see an
* impact.
*
* @param resource
* Basically, a stream containing a texture file. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @return A {@link Future} that you can pass to methods like
* {@link GVRShaders#setMainTexture(Future)}
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public Future<GVRTexture> loadFutureTexture(GVRAndroidResource resource) {
return loadFutureTexture(resource, DEFAULT_PRIORITY);
}
/**
* Simple, high-level method to load a texture asynchronously, for use with
* {@link GVRShaders#setMainTexture(Future)} and
* {@link GVRShaders#setTexture(String, Future)}.
*
* This method uses a default render quality:
* {@link #loadFutureTexture(GVRAndroidResource, int, int)} to specify
* render quality.
*
* <p>
* This method is significantly easier to use than
* {@link #loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource, int)
* : you don't have to implement a callback; you don't have to pay attention
* to the low-level details of
*{@linkplain GVRSceneObject#attachRenderData(GVRRenderData) attaching} a
* {@link GVRRenderData} to your scene object. What's more, you don't even
* lose any functionality: {@link Future#cancel(boolean)} lets you cancel a
* 'stale' request, just like
* {@link GVRAndroidResource.CancelableCallback#stillWanted(GVRAndroidResource)
* stillWanted()} does. The flip side, of course, is that it <em>is</em> a
* bit more expensive: methods like
* {@link GVRMaterial#setMainTexture(Future)} use an extra thread from the
* thread pool to wait for the blocking {@link Future#get()} call. For
* modest numbers of loads, this overhead is acceptable - but thread
* creation is not free, and if your {@link GVRScript#onInit(GVRContext)
* onInit()} method fires of dozens of future loads, you may well see an
* impact.
*
* @param resource
* Basically, a stream containing a texture file. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>. Also, please note priorities only apply to
* uncompressed textures (standard Android bitmap files, which
* can take hundreds of milliseconds to load): compressed
* textures load so quickly that they are not run through the
* request scheduler.
* @return A {@link Future} that you can pass to methods like
* {@link GVRShaders#setMainTexture(Future)}
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public Future<GVRTexture> loadFutureTexture(GVRAndroidResource resource,
int priority) {
return loadFutureTexture(resource, priority,
GVRCompressedTexture.BALANCED);
}
/**
* Simple, high-level method to load a texture asynchronously, for use with
* {@link GVRShaders#setMainTexture(Future)} and
* {@link GVRShaders#setTexture(String, Future)}.
*
*
* <p>
* This method is significantly easier to use than
* {@link #loadTexture(GVRAndroidResource.TextureCallback, GVRAndroidResource, int, int)
* : you don't have to implement a callback; you don't have to pay attention
* to the low-level details of
*{@linkplain GVRSceneObject#attachRenderData(GVRRenderData) attaching} a
* {@link GVRRenderData} to your scene object. What's more, you don't even
* lose any functionality: {@link Future#cancel(boolean)} lets you cancel a
* 'stale' request, just like
* {@link GVRAndroidResource.CancelableCallback#stillWanted(GVRAndroidResource)
* stillWanted()} does. The flip side, of course, is that it <em>is</em> a
* bit more expensive: methods like
* {@link GVRMaterial#setMainTexture(Future)} use an extra thread from the
* thread pool to wait for the blocking {@link Future#get()} call. For
* modest numbers of loads, this overhead is acceptable - but thread
* creation is not free, and if your {@link GVRScript#onInit(GVRContext)
* onInit()} method fires of dozens of future loads, you may well see an
* impact.
*
* @param resource
* Basically, a stream containing a texture file. The
* {@link GVRAndroidResource} class has six constructors to
* handle a wide variety of Android resource types. Taking a
* {@code GVRAndroidResource} here eliminates six overloads.
* @param priority
* This request's priority. Please see the notes on asynchronous
* priorities in the <a href="package-summary.html#async">package
* description</a>. Also, please note priorities only apply to
* uncompressed textures (standard Android bitmap files, which
* can take hundreds of milliseconds to load): compressed
* textures load so quickly that they are not run through the
* request scheduler.
* @param quality
* The compressed texture {@link GVRCompressedTexture#mQuality
* quality} parameter: should be one of
* {@link GVRCompressedTexture#SPEED},
* {@link GVRCompressedTexture#BALANCED}, or
* {@link GVRCompressedTexture#QUALITY}, but other values are
* 'clamped' to one of the recognized values. Please note that
* this (currently) only applies to compressed textures; normal
* {@linkplain GVRBitmapTexture bitmapped textures} don't take a
* quality parameter.
* @return A {@link Future} that you can pass to methods like
* {@link GVRShaders#setMainTexture(Future)}
*
* @since 1.6.7
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public Future<GVRTexture> loadFutureTexture(GVRAndroidResource resource,
int priority, int quality) {
return GVRAsynchronousResourceLoader.loadFutureTexture(this,
sTextureCache, resource, priority, quality);
}
/**
* Simple, high-level method to load a cube map texture asynchronously, for
* use with {@link GVRShaders#setMainTexture(Future)} and
* {@link GVRShaders#setTexture(String, Future)}.
*
* @param resource
* A steam containing a zip file which contains six bitmaps. The
* six bitmaps correspond to +x, -x, +y, -y, +z, and -z faces of
* the cube map texture respectively. The default names of the
* six images are "posx.png", "negx.png", "posy.png", "negx.png",
* "posz.png", and "negz.png", which can be changed by calling
* {@link GVRCubemapTexture#setFaceNames(String[])}.
* @return A {@link Future} that you can pass to methods like
* {@link GVRShaders#setMainTexture(Future)}
*
* @since 1.6.9
*
* @throws IllegalArgumentException
* If you 'abuse' request consolidation by passing the same
* {@link GVRAndroidResource} descriptor to multiple load calls.
* <p>
* It's fairly common for multiple scene objects to use the same
* texture or the same mesh. Thus, if you try to load, say,
* {@code R.raw.whatever} while you already have a pending
* request for {@code R.raw.whatever}, it will only be loaded
* once; the same resource will be used to satisfy both (all)
* requests. This "consolidation" uses
* {@link GVRAndroidResource#equals(Object)}, <em>not</em>
* {@code ==} (aka "reference equality"): The problem with using
* the same resource descriptor is that if requests can't be
* consolidated (because the later one(s) came in after the
* earlier one(s) had already completed) the resource will be
* reloaded ... but the original descriptor will have been
* closed.
*/
public Future<GVRTexture> loadFutureCubemapTexture(
GVRAndroidResource resource) {
return GVRAsynchronousResourceLoader.loadFutureCubemapTexture(this,
sTextureCache, resource, DEFAULT_PRIORITY,
GVRCubemapTexture.faceIndexMap);
}
/**
* Get the current {@link GVRScene}, which contains the scene graph (a
* hierarchy of {@linkplain GVRSceneObject scene objects}) and the
* {@linkplain GVRCameraRig camera rig}
*
* @return A {@link GVRScene} instance, containing scene and camera
* information
*/
public abstract GVRScene getMainScene();
/** Set the current {@link GVRScene} */
public abstract void setMainScene(GVRScene scene);
/**
* Returns a {@link GVRScene} that you can populate before passing to
* {@link #setMainScene(GVRScene)}.
*
* Implementation maintains a single element buffer, initialized to
* {@code null}. When this method is called, creates a new scene if the
* buffer is {@code null}, then returns the buffered scene. If this buffered
* scene is passed to {@link #setMainScene(GVRScene)}, the buffer is reset
* to {@code null}.
*
* <p>
* One use of this is to build your scene graph while the splash screen is
* visible. If you have called {@linkplain #getNextMainScene()} (so that the
* next-main-scene buffer is non-{@code null} when the splash screen is
* closed) GVRF will automatically switch to the 'pending' main-scene; if
* the buffer is {@code null}, GVRF will simply remove the splash screen
* from the main scene object.
*
* @since 1.6.4
*/
public GVRScene getNextMainScene() {
return getNextMainScene(null);
}
/**
* Returns a {@link GVRScene} that you can populate before passing to
* {@link #setMainScene(GVRScene)}.
*
* Implementation maintains a single element buffer, initialized to
* {@code null}. When this method is called, creates a new scene if the
* buffer is {@code null}, then returns the buffered scene. If this buffered
* scene is passed to {@link #setMainScene(GVRScene)}, the buffer is reset
* to {@code null}.
*
* <p>
* One use of this is to build your scene graph while the splash screen is
* visible. If you have called {@linkplain #getNextMainScene()} (so that the
* next-main-scene buffer is non-{@code null} when the splash screen is
* closed) GVRF will automatically switch to the 'pending' main-scene; if
* the buffer is {@code null}, GVRF will simply remove the splash screen
* from the main scene object.
*
* @param onSwitchMainScene
* Optional (may be {@code null}) {@code Runnable}, called when
* this {@link GVRScene} becomes the new main scene, whether
* {@linkplain #setMainScene(GVRScene) explicitly} or implicitly
* (as, for example, when the splash screen closes). This
* callback lets apps do things like start animations when their
* scene becomes visible, instead of in
* {@link GVRScript#onInit(GVRContext) onInit()} when the scene
* objects may be hidden by the splash screen.
*
* @since 1.6.4
*/
public abstract GVRScene getNextMainScene(Runnable onSwitchMainScene);
/**
* Is the key pressed?
*
* @param keyCode
* An Android {@linkplain KeyEvent#KEYCODE_0 key code}
*/
public abstract boolean isKeyDown(int keyCode);
/**
* The interval between this frame and the previous frame, in seconds: a
* rough gauge of Frames Per Second.
*/
public abstract float getFrameTime();
/**
* Enqueues a callback to be run in the GL thread.
*
* This is how you take data generated on a background thread (or the main
* (GUI) thread) and pass it to the coprocessor, using calls that must be
* made from the GL thread (aka the "GL context"). The callback queue is
* processed before any registered
* {@linkplain #registerDrawFrameListener(GVRDrawFrameListener) frame
* listeners}.
*
* @param runnable
* A bit of code that must run on the GL thread
*/
public abstract void runOnGlThread(Runnable runnable);
/**
* Subscribes a {@link GVRDrawFrameListener}.
*
* Each frame listener is called, once per frame, after any pending
* {@linkplain #runOnGlThread(Runnable) GL callbacks} and before
* {@link GVRScript#onStep()}.
*
* @param frameListener
* A callback that will fire once per frame, until it is
* {@linkplain #unregisterDrawFrameListener(GVRDrawFrameListener)
* unregistered}
*/
public abstract void registerDrawFrameListener(
GVRDrawFrameListener frameListener);
/**
* Remove a previously-subscribed {@link GVRDrawFrameListener}.
*
* @param frameListener
* An instance of a {@link GVRDrawFrameListener} implementation.
* Unsubscribing a listener which is not actually subscribed will
* not throw an exception.
*/
public abstract void unregisterDrawFrameListener(
GVRDrawFrameListener frameListener);
/**
* The {@linkplain GVRMaterialShaderManager object shader manager}
* singleton.
*
* Use the shader manager to define custom GL object shaders, which are used
* to render a scene object's surface.
*
* @return The {@linkplain GVRMaterialShaderManager shader manager}
* singleton.
*/
public GVRMaterialShaderManager getMaterialShaderManager() {
return getRenderBundle().getMaterialShaderManager();
}
/**
* The {@linkplain GVRPostEffectShaderManager scene shader manager}
* singleton.
*
* Use the shader manager to define custom GL scene shaders, which can be
* inserted into the rendering pipeline to apply image processing effects to
* the rendered scene graph. In classic GL programming, this is often
* referred to as a "post effect."
*
* @return The {@linkplain GVRPostEffectShaderManager post effect shader
* manager} singleton.
*/
public GVRPostEffectShaderManager getPostEffectShaderManager() {
return getRenderBundle().getPostEffectShaderManager();
}
/**
* The {@linkplain GVRAnimationEngine animation engine} singleton.
*
* Use the animation engine to start and stop {@linkplain GVRAnimation
* animations}.
*
* @return The {@linkplain GVRAnimationEngine animation engine} singleton.
*/
public GVRAnimationEngine getAnimationEngine() {
return GVRAnimationEngine.getInstance(this);
}
/**
* The {@linkplain GVRPeriodicEngine periodic engine} singleton.
*
* Use the periodic engine to schedule {@linkplain Runnable runnables} to
* run on the GL thread at a future time.
*
* @return The {@linkplain GVRPeriodicEngine periodic engine} singleton.
*/
public GVRPeriodicEngine getPeriodicEngine() {
return GVRPeriodicEngine.getInstance(this);
}
/**
* Register a method that is called every time GVRF creates a new
* {@link GVRContext}.
*
* Android apps aren't mapped 1:1 to Linux processes; the system may keep a
* process loaded even after normal complete shutdown, and call Android
* lifecycle methods to reinitialize it. This causes problems for (in
* particular) lazy-created singletons that are tied to a particular
* {@code GVRContext}. This method lets you register a handler that will be
* called on restart, which can reset your {@code static} variables to the
* compiled-in start state.
*
* <p>
* For example,
*
* <pre>
*
* static YourSingletonClass sInstance;
* static {
* GVRContext.addResetOnRestartHandler(new Runnable() {
*
* @Override
* public void run() {
* sInstance = null;
* }
* });
* }
*
* </pre>
*
* <p>
* GVRF will force an Android garbage collection after running any handlers,
* which will free any remaining native objects from the previous run.
*
* @param handler
* Callback to run on restart.
*/
public synchronized static void addResetOnRestartHandler(Runnable handler) {
sHandlers.add(handler);
}
protected synchronized static void resetOnRestart() {
for (Runnable handler : sHandlers) {
Log.d(TAG, "Running on-restart handler %s", handler);
handler.run();
}
// We've probably just nulled-out a bunch of references, but many GVRF
// apps do relatively little Java memory allocation, so it may actually
// be a longish while before the recyclable references go stale.
System.gc();
// We do NOT want to clear sHandlers - the static initializers won't be
// run again, even if the new run does recreate singletons.
}
private static final List<Runnable> sHandlers = new ArrayList<Runnable>();
abstract GVRRenderBundle getRenderBundle();
/**
* Capture a 2D screenshot from the position in the middle of left eye and
* right eye.
*
* The screenshot capture is done asynchronously -- the function does not
* return the result immediately. Instead, it registers a callback function
* and pass the result (when it is available) to the callback function. The
* callback will happen on a background thread: It will probably not be the
* same thread that calls this method, and it will not be either the GUI or
* the GL thread.
*
* Users should not start a {@code captureScreenCenter} until previous
* {@code captureScreenCenter} callback has returned. Starting a new
* {@code captureScreenCenter} before the previous
* {@code captureScreenCenter} callback returned may cause out of memory
* error.
*
* @param callback
* Callback function to process the capture result. It may not be
* {@code null}.
*/
public abstract void captureScreenCenter(GVRScreenshotCallback callback);
/**
* Capture a 2D screenshot from the position of left eye.
*
* The screenshot capture is done asynchronously -- the function does not
* return the result immediately. Instead, it registers a callback function
* and pass the result (when it is available) to the callback function. The
* callback will happen on a background thread: It will probably not be the
* same thread that calls this method, and it will not be either the GUI or
* the GL thread.
*
* Users should not start a {@code captureScreenLeft} until previous
* {@code captureScreenLeft} callback has returned. Starting a new
* {@code captureScreenLeft} before the previous {@code captureScreenLeft}
* callback returned may cause out of memory error.
*
* @param callback
* Callback function to process the capture result. It may not be
* {@code null}.
*/
public abstract void captureScreenLeft(GVRScreenshotCallback callback);
/**
* Capture a 2D screenshot from the position of right eye.
*
* The screenshot capture is done asynchronously -- the function does not
* return the result immediately. Instead, it registers a callback function
* and pass the result (when it is available) to the callback function. The
* callback will happen on a background thread: It will probably not be the
* same thread that calls this method, and it will not be either the GUI or
* the GL thread.
*
* Users should not start a {@code captureScreenRight} until previous
* {@code captureScreenRight} callback has returned. Starting a new
* {@code captureScreenRight} before the previous {@code captureScreenRight}
* callback returned may cause out of memory error.
*
* @param callback
* Callback function to process the capture result. It may not be
* {@code null}.
*/
public abstract void captureScreenRight(GVRScreenshotCallback callback);
/**
* Capture a 3D screenshot from the position of left eye. The 3D screenshot
* is composed of six images from six directions (i.e. +x, -x, +y, -y, +z,
* and -z).
*
* The screenshot capture is done asynchronously -- the function does not
* return the result immediately. Instead, it registers a callback function
* and pass the result (when it is available) to the callback function. The
* callback will happen on a background thread: It will probably not be the
* same thread that calls this method, and it will not be either the GUI or
* the GL thread.
*
* Users should not start a {@code captureScreen3D} until previous
* {@code captureScreen3D} callback has returned. Starting a new
* {@code captureScreen3D} before the previous {@code captureScreen3D}
* callback returned may cause out of memory error.
*
* @param callback
* Callback function to process the capture result. It may not be
* {@code null}.
*
* @since 1.6.8
*/
public abstract void captureScreen3D(GVRScreenshot3DCallback callback);
}
|
fix: Replicates assimp hierarchy to GVRScene with GVRSceneObject.
|
GVRf/Framework/src/org/gearvrf/GVRContext.java
|
fix: Replicates assimp hierarchy to GVRScene with GVRSceneObject.
|
|
Java
|
apache-2.0
|
568462105671ed5d9d880226581a7120469d14b7
| 0
|
MCUpdater/FastPack
|
package org.mcupdater.fastpack;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.BuiltinHelpFormatter;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.apache.commons.compress.utils.Lists;
import org.mcupdater.model.*;
import org.mcupdater.util.FastPack;
import org.mcupdater.util.MCUpdater;
import org.mcupdater.util.PathWalker;
import org.mcupdater.util.ServerDefinition;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.ConsoleHandler;
import java.util.logging.SimpleFormatter;
public class Main {
public static void main(final String[] args) {
boolean hasForge = false;
boolean debug = false;
boolean doConfigs = true;
boolean onlyOverrides = false;
OptionParser optParser = new OptionParser();
optParser.accepts("help", "Shows this help").isForHelp();
optParser.formatHelpWith(new BuiltinHelpFormatter(200, 3));
ArgumentAcceptingOptionSpec<String> fileSpec = optParser.accepts("file", "Parse a single mod file and exit").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<String> searchPathSpec = optParser.accepts("path", "Path to scan for mods and configs").requiredUnless("help","file").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<String> baseURLSpec = optParser.accepts("baseURL", "Base URL for downloads").requiredUnless("help","file").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<String> MCVersionSpec = optParser.accepts("mc", "Minecraft version").requiredUnless("help","file").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<String> forgeVersionSpec = optParser.accepts("forge", "Forge version").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<String> xmlPathSpec = optParser.accepts("out", "XML file to write").requiredUnless("help","file").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<String> serverAddrSpec = optParser.accepts("mcserver", "Server address").withRequiredArg().ofType(String.class).defaultsTo("");
ArgumentAcceptingOptionSpec<String> serverNameSpec = optParser.accepts("name", "Server name").withRequiredArg().ofType(String.class).defaultsTo("FastPack Instance");
ArgumentAcceptingOptionSpec<String> serverIdSpec = optParser.accepts("id", "Server ID").withRequiredArg().ofType(String.class).defaultsTo("fastpack");
ArgumentAcceptingOptionSpec<String> mainClassSpec = optParser.accepts("mainClass", "Main class for launching Minecraft").withRequiredArg().ofType(String.class).defaultsTo("net.minecraft.launchwrapper.Launch");
ArgumentAcceptingOptionSpec<String> newsURLSpec = optParser.accepts("newsURL", "URL to display in the News tab").withRequiredArg().ofType(String.class).defaultsTo("about:blank");
ArgumentAcceptingOptionSpec<String> iconURLSpec = optParser.accepts("iconURL", "URL of icon to display in instance list").withRequiredArg().ofType(String.class).defaultsTo("");
ArgumentAcceptingOptionSpec<String> revisionSpec = optParser.accepts("revision", "Revision string to display").withRequiredArg().ofType(String.class).defaultsTo("1");
ArgumentAcceptingOptionSpec<Boolean> autoConnectSpec = optParser.accepts("autoConnect", "Auto-connect to server on launch").withRequiredArg().ofType(Boolean.class).defaultsTo(Boolean.TRUE);
ArgumentAcceptingOptionSpec<String> stylesheetSpec = optParser.accepts("xslt", "Path of XSLT file").withRequiredArg().ofType(String.class).defaultsTo("");
ArgumentAcceptingOptionSpec<String> sourcePackURLSpec = optParser.accepts("sourcePackURL", "URL of pack to load - useful with configsOnly").withRequiredArg().ofType(String.class).defaultsTo("");
ArgumentAcceptingOptionSpec<String> sourcePackIdSpec = optParser.accepts("sourcePackId", "Server ID of source pack").requiredIf("sourcePackURL").withRequiredArg().ofType(String.class);
optParser.accepts("noConfigs", "Do not generate ConfigFile entries");
optParser.accepts("configsOnly", "Generate all mods as overrides with ConfigFile entries");
optParser.accepts("debug", "Output full config matching data");
final OptionSet options;
try {
options = optParser.parse(args);
} catch( Exception ex ) {
System.err.println( ex.getMessage() );
return;
}
if( options.has("file")) {
parseOneFile(fileSpec.value(options));
return;
}
if (options.has("help")) {
try {
optParser.printHelpOn(System.out);
return;
} catch (IOException e) {
e.printStackTrace();
}
}
MCUpdater.getInstance();
ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(new SimpleFormatter());
MCUpdater.apiLogger.addHandler(handler);
if (options.has("forge")) {
hasForge = true;
}
if (options.has("debug")) {
debug = true;
}
if (options.has("noConfigs")) {
doConfigs = false;
}
if (options.has("configsOnly")) {
onlyOverrides = true;
}
String sourcePack = sourcePackURLSpec.value(options);
String sourceId = sourcePackIdSpec.value(options);
String serverName = serverNameSpec.value(options);
String serverId = serverIdSpec.value(options);
String serverAddr = serverAddrSpec.value(options);
String mainClass = mainClassSpec.value(options);
String newsURL = newsURLSpec.value(options);
String iconURL = iconURLSpec.value(options);
String revision = revisionSpec.value(options);
Boolean autoConnect = autoConnectSpec.value(options);
String MCVersion = MCVersionSpec.value(options);
String forgeVersion = forgeVersionSpec.value(options);
String stylesheet = stylesheetSpec.value(options);
Path searchPath = new File(searchPathSpec.value(options)).toPath();
Path xmlPath = new File(xmlPathSpec.value(options)).toPath();
String baseURL = baseURLSpec.value(options);
ServerDefinition definition = FastPack.doFastPack(sourcePack, sourceId, serverName, serverId, serverAddr, mainClass, newsURL, iconURL, revision, autoConnect, MCVersion, searchPath, baseURL, debug);
if (hasForge) {
definition.addForge(MCVersion, forgeVersion);
}
List<Module> sortedModules = definition.sortMods();
Map<String,String> issues = new HashMap<>();
if (doConfigs) definition.assignConfigs(issues, debug);
definition.writeServerPack(stylesheet, xmlPath, sortedModules, onlyOverrides);
}
private static void parseOneFile(String fname) {
File f = new File(fname);
if ( f == null || !f.exists() || !f.isFile() ) {
System.out.println("!! Unable to find '"+fname+"'");
return;
}
final Path searchPath;
if( f.getParent() == null ) {
searchPath = new File(".").toPath();
} else {
searchPath = f.getParentFile().toPath();
}
final ServerDefinition definition = new ServerDefinition();
final PathWalker walker = new PathWalker(definition,searchPath,"[PATH]");
try {
walker.visitFile(f.toPath(), null);
} catch (IOException e) {
e.printStackTrace();
return;
}
final BufferedWriter stdout = new BufferedWriter(new OutputStreamWriter(System.out));
try {
stdout.newLine();
ServerDefinition.generateServerDetailXML(stdout, new ArrayList<Import>(), definition.sortMods(), false);
stdout.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
src/main/java/org/mcupdater/fastpack/Main.java
|
package org.mcupdater.fastpack;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.BuiltinHelpFormatter;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.apache.commons.compress.utils.Lists;
import org.mcupdater.model.*;
import org.mcupdater.util.FastPack;
import org.mcupdater.util.MCUpdater;
import org.mcupdater.util.PathWalker;
import org.mcupdater.util.ServerDefinition;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.ConsoleHandler;
import java.util.logging.SimpleFormatter;
public class Main {
public static void main(final String[] args) {
boolean hasForge = false;
boolean debug = false;
boolean doConfigs = true;
boolean onlyOverrides = false;
OptionParser optParser = new OptionParser();
optParser.accepts("help", "Shows this help").isForHelp();
optParser.formatHelpWith(new BuiltinHelpFormatter(200, 3));
ArgumentAcceptingOptionSpec<String> fileSpec = optParser.accepts("file", "Parse a single mod file and exit").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<String> searchPathSpec = optParser.accepts("path", "Path to scan for mods and configs").requiredUnless("help","file").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<String> baseURLSpec = optParser.accepts("baseURL", "Base URL for downloads").requiredUnless("help","file").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<String> MCVersionSpec = optParser.accepts("mc", "Minecraft version").requiredUnless("help","file").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<String> forgeVersionSpec = optParser.accepts("forge", "Forge version").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<String> xmlPathSpec = optParser.accepts("out", "XML file to write").requiredUnless("help","file").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<String> serverAddrSpec = optParser.accepts("mcserver", "Server address").withRequiredArg().ofType(String.class).defaultsTo("");
ArgumentAcceptingOptionSpec<String> serverNameSpec = optParser.accepts("name", "Server name").withRequiredArg().ofType(String.class).defaultsTo("FastPack Instance");
ArgumentAcceptingOptionSpec<String> serverIdSpec = optParser.accepts("id", "Server ID").withRequiredArg().ofType(String.class).defaultsTo("fastpack");
ArgumentAcceptingOptionSpec<String> mainClassSpec = optParser.accepts("mainClass", "Main class for launching Minecraft").withRequiredArg().ofType(String.class).defaultsTo("net.minecraft.launchwrapper.Launch");
ArgumentAcceptingOptionSpec<String> newsURLSpec = optParser.accepts("newsURL", "URL to display in the News tab").withRequiredArg().ofType(String.class).defaultsTo("about:blank");
ArgumentAcceptingOptionSpec<String> iconURLSpec = optParser.accepts("iconURL", "URL of icon to display in instance list").withRequiredArg().ofType(String.class).defaultsTo("");
ArgumentAcceptingOptionSpec<String> revisionSpec = optParser.accepts("revision", "Revision string to display").withRequiredArg().ofType(String.class).defaultsTo("1");
ArgumentAcceptingOptionSpec<Boolean> autoConnectSpec = optParser.accepts("autoConnect", "Auto-connect to server on launch").withRequiredArg().ofType(Boolean.class).defaultsTo(Boolean.TRUE);
ArgumentAcceptingOptionSpec<String> stylesheetSpec = optParser.accepts("xslt", "Path of XSLT file").withRequiredArg().ofType(String.class).defaultsTo("");
ArgumentAcceptingOptionSpec<String> sourcePackURLSpec = optParser.accepts("sourcePackURL", "URL of pack to load - useful with configsOnly").withRequiredArg().ofType(String.class).defaultsTo("");
ArgumentAcceptingOptionSpec<String> sourcePackIdSpec = optParser.accepts("sourcePackId", "Server ID of source pack").requiredIf("sourcePackURL").withRequiredArg().ofType(String.class);
optParser.accepts("noConfigs", "Do not generate ConfigFile entries");
optParser.accepts("configsOnly", "Generate all mods as overrides with ConfigFile entries");
optParser.accepts("debug", "Output full config matching data");
final OptionSet options;
try {
options = optParser.parse(args);
} catch( Exception ex ) {
System.err.println( ex.getMessage() );
return;
}
if( options.has("file")) {
parseOneFile(fileSpec.value(options));
return;
}
if (options.has("help")) {
try {
optParser.printHelpOn(System.out);
return;
} catch (IOException e) {
e.printStackTrace();
}
}
MCUpdater.getInstance();
ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(new SimpleFormatter());
MCUpdater.apiLogger.addHandler(handler);
if (options.has("forge")) {
hasForge = true;
}
if (options.has("debug")) {
debug = true;
}
if (options.has("noConfigs")) {
doConfigs = false;
}
if (options.has("configsOnly")) {
onlyOverrides = true;
}
String sourcePack = sourcePackURLSpec.value(options);
String sourceId = sourcePackIdSpec.value(options);
String serverName = serverNameSpec.value(options);
String serverId = serverIdSpec.value(options);
String serverAddr = serverAddrSpec.value(options);
String mainClass = mainClassSpec.value(options);
String newsURL = newsURLSpec.value(options);
String iconURL = iconURLSpec.value(options);
String revision = revisionSpec.value(options);
Boolean autoConnect = autoConnectSpec.value(options);
String MCVersion = MCVersionSpec.value(options);
String forgeVersion = forgeVersionSpec.value(options);
String stylesheet = stylesheetSpec.value(options);
Path searchPath = new File(searchPathSpec.value(options)).toPath();
Path xmlPath = new File(xmlPathSpec.value(options)).toPath();
String baseURL = baseURLSpec.value(options);
ServerDefinition definition = FastPack.doFastPack(sourcePack, sourceId, serverName, serverId, serverAddr, mainClass, newsURL, iconURL, revision, autoConnect, MCVersion, searchPath, baseURL, debug);
if (hasForge) {
definition.addForge(MCVersion, forgeVersion);
}
List<Module> sortedModules = definition.sortMods();
Map<String,String> issues = new HashMap<>();
if (doConfigs) definition.assignConfigs(issues, debug);
definition.writeServerPack(stylesheet, xmlPath, sortedModules, onlyOverrides);
}
private static void parseOneFile(String fname) {
File f = new File(fname);
if ( f == null || !f.exists() || !f.isFile() ) {
System.out.println("!! Unable to find '"+fname+"'");
return;
}
final Path searchPath = f.getParentFile().toPath();
final ServerDefinition definition = new ServerDefinition();
final PathWalker walker = new PathWalker(definition,searchPath,"[PATH]");
try {
walker.visitFile(f.toPath(), null);
} catch (IOException e) {
e.printStackTrace();
return;
}
final BufferedWriter stdout = new BufferedWriter(new OutputStreamWriter(System.out));
try {
ServerDefinition.generateServerDetailXML(stdout, new ArrayList<Import>(), definition.sortMods(), false);
stdout.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
Fixed issue where a path was mandatory for --file
|
src/main/java/org/mcupdater/fastpack/Main.java
|
Fixed issue where a path was mandatory for --file
|
|
Java
|
apache-2.0
|
173fef222c2639a2001fe9093891310190ac6a22
| 0
|
tmaret/sling,mikibrv/sling,headwirecom/sling,roele/sling,cleliameneghin/sling,tyge68/sling,mikibrv/sling,nleite/sling,mmanski/sling,ieb/sling,tmaret/sling,klcodanr/sling,anchela/sling,ist-dresden/sling,Nimco/sling,anchela/sling,cleliameneghin/sling,plutext/sling,ist-dresden/sling,sdmcraft/sling,tteofili/sling,mcdan/sling,trekawek/sling,klcodanr/sling,ieb/sling,klcodanr/sling,mcdan/sling,SylvesterAbreu/sling,ist-dresden/sling,mcdan/sling,ist-dresden/sling,klcodanr/sling,ffromm/sling,Sivaramvt/sling,sdmcraft/sling,labertasch/sling,tyge68/sling,klcodanr/sling,klcodanr/sling,tteofili/sling,mcdan/sling,Nimco/sling,trekawek/sling,JEBailey/sling,ffromm/sling,wimsymons/sling,mikibrv/sling,sdmcraft/sling,mcdan/sling,vladbailescu/sling,awadheshv/sling,SylvesterAbreu/sling,sdmcraft/sling,labertasch/sling,roele/sling,Nimco/sling,nleite/sling,tmaret/sling,awadheshv/sling,tteofili/sling,ffromm/sling,cleliameneghin/sling,mikibrv/sling,Sivaramvt/sling,Nimco/sling,trekawek/sling,tyge68/sling,cleliameneghin/sling,ffromm/sling,SylvesterAbreu/sling,plutext/sling,ieb/sling,mmanski/sling,mmanski/sling,awadheshv/sling,cleliameneghin/sling,mikibrv/sling,tteofili/sling,nleite/sling,awadheshv/sling,mikibrv/sling,ffromm/sling,anchela/sling,mcdan/sling,gutsy/sling,labertasch/sling,dulvac/sling,wimsymons/sling,headwirecom/sling,dulvac/sling,vladbailescu/sling,tteofili/sling,dulvac/sling,anchela/sling,awadheshv/sling,vladbailescu/sling,SylvesterAbreu/sling,codders/k2-sling-fork,JEBailey/sling,Sivaramvt/sling,trekawek/sling,nleite/sling,dulvac/sling,sdmcraft/sling,SylvesterAbreu/sling,dulvac/sling,wimsymons/sling,nleite/sling,roele/sling,sdmcraft/sling,gutsy/sling,tyge68/sling,ieb/sling,labertasch/sling,tteofili/sling,vladbailescu/sling,JEBailey/sling,JEBailey/sling,ffromm/sling,codders/k2-sling-fork,gutsy/sling,wimsymons/sling,JEBailey/sling,roele/sling,nleite/sling,awadheshv/sling,tmaret/sling,headwirecom/sling,headwirecom/sling,mmanski/sling,plutext/sling,plutext/sling,ieb/sling,gutsy/sling,trekawek/sling,vladbailescu/sling,codders/k2-sling-fork,gutsy/sling,mmanski/sling,headwirecom/sling,Nimco/sling,ieb/sling,Nimco/sling,wimsymons/sling,anchela/sling,labertasch/sling,plutext/sling,mmanski/sling,ist-dresden/sling,wimsymons/sling,plutext/sling,Sivaramvt/sling,dulvac/sling,roele/sling,SylvesterAbreu/sling,tyge68/sling,tmaret/sling,trekawek/sling,Sivaramvt/sling,Sivaramvt/sling,tyge68/sling,gutsy/sling
|
/*
* 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.sling.api.servlets;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.wrappers.SlingHttpServletResponseWrapper;
/**
* Helper base class for read-only Servlets used in Sling. This base class is
* actually just a better implementation of the Servlet API <em>HttpServlet</em>
* class which accounts for extensibility. So extensions of this class have
* great control over what methods to overwrite.
* <p>
* If any of the default HTTP methods is to be implemented just overwrite the
* respective doXXX method. If additional methods should be supported implement
* appropriate doXXX methods and overwrite the
* {@link #mayService(SlingHttpServletRequest, SlingHttpServletResponse)} method
* to dispatch to the doXXX methods as appropriate and overwrite the
* {@link #getAllowedRequestMethods(Map)} to add the new method names.
* <p>
* Please note, that this base class is intended for applications where data is
* only read. As such, this servlet by itself does not support the <em>POST</em>,
* <em>PUT</em> and <em>DELETE</em> methods. Extensions of this class should
* either overwrite any of the doXXX methods of this class or add support for
* other read-only methods only. Applications wishing to support data
* modification should rather use or extend the {@link SlingAllMethodsServlet}
* which also contains support for the <em>POST</em>, <em>PUT</em> and
* <em>DELETE</em> methods. This latter class should also be overwritten to
* add support for HTTP methods modifying data.
* <p>
* Implementors note: The methods in this class are all declared to throw the
* exceptions according to the intentions of the Servlet API rather than
* throwing their Sling RuntimeException counter parts. This is done to easy the
* integration with traditional servlets.
*
* @see SlingAllMethodsServlet
*/
public class SlingSafeMethodsServlet extends GenericServlet {
/**
* Handles the <em>HEAD</em> method.
* <p>
* This base implementation just calls the
* {@link #doGet(HttpServletRequest, HttpServletResponse)} method dropping
* the output. Implementations of this class may overwrite this method if
* they have a more performing implementation. Otherwise, they may just keep
* this base implementation.
*
* @param request The HTTP request
* @param response The HTTP response which only gets the headers set
* @throws ServletException Forwarded from the
* {@link #doGet(HttpServletRequest, HttpServletResponse)}
* method called by this implementation.
* @throws IOException Forwarded from the
* {@link #doGet(HttpServletRequest, HttpServletResponse)}
* method called by this implementation.
*/
protected void doHead(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
// the null-output wrapper
NoBodyResponse wrappedResponse = new NoBodyResponse(response);
// do a normal get request, dropping the output
doGet(request, wrappedResponse);
// ensure the content length is set as gathered by the null-output
wrappedResponse.setContentLength();
}
/**
* Called by the
* {@link #mayService(HttpServletRequest, HttpServletResponse)} method to
* handle an HTTP <em>GET</em> request.
* <p>
* This default implementation reports back to the client that the method is
* not supported.
* <p>
* Implementations of this class should overwrite this method with their
* implementation for the HTTP <em>GET</em> method support.
*
* @param request The HTTP request
* @param response The HTTP response
* @throws ServletException Not thrown by this implementation.
* @throws IOException If the error status cannot be reported back to the
* client.
*/
protected void doGet(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
handleMethodNotImplemented(request, response);
}
/**
* Handles the <em>OPTIONS</em> method by setting the HTTP
* <code>Allow</code> header on the response depending on the methods
* declared in this class.
* <p>
* Extensions of this class should generally not overwrite this method but
* rather the {@link #getAllowedRequestMethods(Map)} method. This method
* gathers all declared public and protected methods for the concrete class
* (upto but not including this class) and calls the
* {@link #getAllowedRequestMethods(Map)} method with the methods gathered.
* The returned value is then used as the value of the <code>Allow</code>
* header set.
*
* @param request The HTTP request object. Not used.
* @param response The HTTP response object on which the header is set.
* @throws ServletException Not thrown by this implementation.
* @throws IOException Not thrown by this implementation.
*/
protected void doOptions(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
Map<String, Method> methods = getAllDeclaredMethods(getClass());
StringBuffer allowBuf = getAllowedRequestMethods(methods);
response.setHeader("Allow", allowBuf.toString());
}
/**
* Handles the <em>TRACE</em> method by just returning the list of all
* header values in the response body.
* <p>
* Extensions of this class do not generally need to overwrite this method
* as it contains all there is to be done to the <em>TRACE</em> method.
*
* @param request The HTTP request whose headers are returned.
* @param response The HTTP response into which the request headers are
* written.
* @throws ServletException Not thrown by this implementation.
* @throws IOException May be thrown if there is an problem sending back the
* request headers in the response stream.
*/
protected void doTrace(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
String CRLF = "\r\n";
StringBuffer responseString = new StringBuffer();
responseString.append("TRACE ").append(request.getRequestURI());
responseString.append(' ').append(request.getProtocol());
Enumeration<?> reqHeaderEnum = request.getHeaderNames();
while (reqHeaderEnum.hasMoreElements()) {
String headerName = (String) reqHeaderEnum.nextElement();
Enumeration<?> reqHeaderValEnum = request.getHeaders(headerName);
while (reqHeaderValEnum.hasMoreElements()) {
responseString.append(CRLF);
responseString.append(headerName).append(": ");
responseString.append(reqHeaderValEnum.nextElement());
}
}
responseString.append(CRLF);
String charset = "UTF-8";
byte[] rawResponse = responseString.toString().getBytes(charset);
int responseLength = rawResponse.length;
response.setContentType("message/http");
response.setCharacterEncoding(charset);
response.setContentLength(responseLength);
ServletOutputStream out = response.getOutputStream();
out.write(rawResponse);
}
/**
* Called by the {@link #service(HttpServletRequest, HttpServletResponse)}
* method to handle a request for an HTTP method, which is not known and
* handled by this class or its extension.
* <p>
* This default implementation reports back to the client that the method is
* not supported.
* <p>
* This method should be overwritten with great care. It is better to
* overwrite the
* {@link #mayService(HttpServletRequest, HttpServletResponse)} method and
* add support for any extension HTTP methods through an additional doXXX
* method.
*
* @param request The HTTP request
* @param response The HTTP response
* @throws ServletException Not thrown by this implementation.
* @throws IOException If the error status cannot be reported back to the
* client.
*/
protected void doGeneric(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
handleMethodNotImplemented(request, response);
}
/**
* Tries to handle the request by calling a Java method implemented for the
* respective HTTP request method.
* <p>
* This base class implentation dispatches the <em>HEAD</em>,
* <em>GET</em>, <em>OPTIONS</em> and <em>TRACE</em> to the
* respective <em>doXXX</em> methods and returns <code>true</code> if
* any of these methods is requested. Otherwise <code>false</code> is just
* returned.
* <p>
* Implementations of this class may overwrite this method but should first
* call this base implementation and in case <code>false</code> is
* returned add handling for any other method and of course return whether
* the requested method was known or not.
*
* @param request The HTTP request
* @param response The HTTP response
* @return <code>true</code> if the requested method (<code>request.getMethod()</code>)
* is known. Otherwise <code>false</code> is returned.
* @throws ServletException Forwarded from any of the dispatched methods
* @throws IOException Forwarded from any of the dispatched methods
*/
protected boolean mayService(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
// assume the method is known for now
boolean methodKnown = true;
String method = request.getMethod();
if (HttpConstants.METHOD_HEAD.equals(method)) {
doHead(request, response);
} else if (HttpConstants.METHOD_GET.equals(method)) {
doGet(request, response);
} else if (HttpConstants.METHOD_OPTIONS.equals(method)) {
doOptions(request, response);
} else if (HttpConstants.METHOD_TRACE.equals(method)) {
doTrace(request, response);
} else {
// actually we do not know the method
methodKnown = false;
}
// return whether we actually knew the request method or not
return methodKnown;
}
/**
* Helper method which causes an appropriate HTTP response to be sent for an
* unhandled HTTP request method. In case of HTTP/1.1 a 405 status code
* (Method Not Allowed) is returned, otherwise a 400 status (Bad Request) is
* returned.
*
* @param request The HTTP request from which the method and protocol values
* are extracted to build the appropriate message.
* @param response The HTTP response to which the error status is sent.
* @throws IOException Thrown if the status cannot be sent to the client.
*/
protected void handleMethodNotImplemented(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws IOException {
String protocol = request.getProtocol();
String msg = "Method " + request.getMethod() + " not supported";
if (protocol.endsWith("1.1")) {
// for HTTP/1.1 use 405 Method Not Allowed
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
// otherwise use 400 Bad Request
response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
/**
* Called by the {@link #service(ServletRequest, ServletResponse)} method to
* handle the HTTP request. This implementation calls the
* {@link #mayService(HttpServletRequest, HttpServletResponse)} method and
* depedending on its return value call the
* {@link #doGeneric(HttpServletRequest, HttpServletResponse)} method. If
* the {@link #mayService(HttpServletRequest, HttpServletResponse)} method
* can handle the request, the
* {@link #doGeneric(HttpServletRequest, HttpServletResponse)} method is not
* called otherwise it is called.
* <p>
* Implementations of this class should not generally overwrite this method.
* Rather the {@link #mayService(HttpServletRequest, HttpServletResponse)}
* method should be overwritten to add support for more HTTP methods.
*
* @param request The HTTP request
* @param response The HTTP response
* @throws ServletException Forwarded from the
* {@link #mayService(HttpServletRequest, HttpServletResponse)}
* or
* {@link #doGeneric(HttpServletRequest, HttpServletResponse)}
* methods.
* @throws IOException Forwarded from the
* {@link #mayService(HttpServletRequest, HttpServletResponse)}
* or
* {@link #doGeneric(HttpServletRequest, HttpServletResponse)}
* methods.
*/
protected void service(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
// first try to handle the request by the known methods
boolean methodKnown = mayService(request, response);
// otherwise try to handle it through generic means
if (!methodKnown) {
doGeneric(request, response);
}
}
/**
* Forwards the request to the
* {@link #service(SlingHttpServletRequest, SlingHttpServletResponse)}
* method if the request is a HTTP request.
* <p>
* Implementations of this class will not generally overwrite this method.
*
* @param req The Servlet request
* @param res The Servlet response
* @throws ServletException If the request is not a HTTP request or
* forwarded from the
* {@link #service(SlingHttpServletRequest, SlingHttpServletResponse)}
* called.
* @throws IOException Forwarded from the
* {@link #service(SlingHttpServletRequest, SlingHttpServletResponse)}
* called.
*/
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
try {
SlingHttpServletRequest request = (SlingHttpServletRequest) req;
SlingHttpServletResponse response = (SlingHttpServletResponse) res;
service(request, response);
} catch (ClassCastException cce) {
throw new ServletException("Not a Sling HTTP request/response");
}
}
/**
* Returns the simple class name of this servlet class. Extensions of this
* class may overwrite to return more specific information.
*/
public String getServletInfo() {
return getClass().getSimpleName();
}
/**
* Helper method called by
* {@link #doOptions(HttpServletRequest, HttpServletResponse)} to calculate
* the value of the <em>Allow</em> header sent as the response to the HTTP
* <em>OPTIONS</em> request.
* <p>
* This base class implementation checks whether any doXXX methods exist for
* <em>GET</em> and <em>HEAD</em> and returns the list of methods
* supported found. The list returned always includes the HTTP
* <em>OPTIONS</em> and <em>TRACE</em> methods.
* <p>
* Implementations of this class may overwrite this method check for more
* methods supported by the extension (generally the same list as used in
* the {@link #mayService(HttpServletRequest, HttpServletResponse)} method).
* This base class implementation should always be called to make sure the
* default HTTP methods are included in the list.
*
* @param declaredMethods The public and protected methods declared in the
* extension of this class.
* @return A <code>StringBuffer</code> containing the list of HTTP methods
* supported.
*/
protected StringBuffer getAllowedRequestMethods(
Map<String, Method> declaredMethods) {
StringBuffer allowBuf = new StringBuffer();
// OPTIONS and TRACE are always supported by this servlet
allowBuf.append(HttpConstants.METHOD_OPTIONS);
allowBuf.append(", ").append(HttpConstants.METHOD_TRACE);
// add more method names depending on the methods found
if (declaredMethods.containsKey("doHead")
&& !declaredMethods.containsKey("doGet")) {
allowBuf.append(", ").append(HttpConstants.METHOD_HEAD);
} else if (declaredMethods.containsKey("doGet")) {
allowBuf.append(", ").append(HttpConstants.METHOD_GET);
allowBuf.append(", ").append(HttpConstants.METHOD_HEAD);
}
return allowBuf;
}
/**
* Returns a map of methods declared by the class indexed by method name.
* This method is called by the
* {@link #doOptions(HttpServletRequest, HttpServletResponse)} method to
* find the methods to be checked by the
* {@link #getAllowedRequestMethods(Map)} method. Note, that only extension
* classes of this class are considered to be sure to not account for the
* default implementations of the doXXX methods in this class.
*
* @param c The <code>Class</code> to get the declared methods from
* @return The Map of methods considered for support checking.
*/
private Map<String, Method> getAllDeclaredMethods(Class<?> c) {
// stop (and do not include) the AbstractSlingServletClass
if (c == null
|| c.getName().equals(SlingSafeMethodsServlet.class.getName())) {
return new HashMap<String, Method>();
}
// get the declared methods from the base class
Map<String, Method> methodSet = getAllDeclaredMethods(c.getSuperclass());
// add declared methods of c (maybe overwrite base class methods)
Method[] declaredMethods = c.getDeclaredMethods();
for (Method method : declaredMethods) {
// only consider public and protected methods
if (Modifier.isProtected(method.getModifiers())
|| Modifier.isPublic(method.getModifiers())) {
methodSet.put(method.getName(), method);
}
}
return methodSet;
}
/**
* A response that includes no body, for use in (dumb) "HEAD" support. This
* just swallows that body, counting the bytes in order to set the content
* length appropriately.
*/
private class NoBodyResponse extends SlingHttpServletResponseWrapper {
/** The byte sink and counter */
private NoBodyOutputStream noBody;
/** Optional writer around the byte sink */
private PrintWriter writer;
/** Whether the request processor set the content length itself or not. */
private boolean didSetContentLength;
NoBodyResponse(SlingHttpServletResponse wrappedResponse) {
super(wrappedResponse);
noBody = new NoBodyOutputStream();
}
/**
* Called at the end of request processing to ensure the content length
* is set. If the processor already set the length, this method does not
* do anything. Otherwise the number of bytes written through the
* null-output is set on the response.
*/
void setContentLength() {
if (!didSetContentLength) {
setContentLength(noBody.getContentLength());
}
}
/**
* Overwrite this to prevent setting the content length at the end of
* the request through {@link #setContentLength()}
*/
public void setContentLength(int len) {
super.setContentLength(len);
didSetContentLength = true;
}
/**
* Just return the null output stream and don't check whether a writer
* has already been acquired.
*/
public ServletOutputStream getOutputStream() {
return noBody;
}
/**
* Just return the writer to the null output stream and don't check
* whether an output stram has already been acquired.
*/
public PrintWriter getWriter() throws UnsupportedEncodingException {
if (writer == null) {
OutputStreamWriter w;
w = new OutputStreamWriter(noBody, getCharacterEncoding());
writer = new PrintWriter(w);
}
return writer;
}
}
/**
* Simple ServletOutputStream which just does not write but counts the bytes
* written through it. This class is used by the NoBodyResponse.
*/
private class NoBodyOutputStream extends ServletOutputStream {
private int contentLength = 0;
/**
* @return the number of bytes "written" through this stream
*/
int getContentLength() {
return contentLength;
}
public void write(int b) {
contentLength++;
}
public void write(byte buf[], int offset, int len) {
if (len >= 0) {
contentLength += len;
} else {
throw new IndexOutOfBoundsException();
}
}
}
}
|
api/src/main/java/org/apache/sling/api/servlets/SlingSafeMethodsServlet.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.sling.api.servlets;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.wrappers.SlingHttpServletResponseWrapper;
/**
* Helper base class for read-only Servlets used in Sling. This base class is
* actually just a better implementation of the Servlet API <em>HttpServlet</em>
* class which accounts for extensibility. So extensions of this class have
* great control over what methods to overwrite.
* <p>
* If any of the default HTTP methods is to be implemented just overwrite the
* respective doXXX method. If additional methods should be supported implement
* appropriate doXXX methods and overwrite the
* {@link #mayService(SlingHttpServletRequest, SlingHttpServletResponse)} method
* to dispatch to the doXXX methods as appropriate and overwrite the
* {@link #getAllowedRequestMethods(Map)} to add the new method names.
* <p>
* Please note, that this base class is intended for applications where data is
* only read. As such, this servlet by itself does not support the <em>POST</em>,
* <em>PUT</em> and <em>DELETE</em> methods. Extensions of this class should
* either overwrite any of the doXXX methods of this class or add support for
* other read-only methods only. Applications wishing to support data
* modification should rather use or extend the {@link SlingAllMethodsServlet}
* which also contains support for the <em>POST</em>, <em>PUT</em> and
* <em>DELETE</em> methods. This latter class should also be overwritten to
* add support for HTTP methods modifying data.
* <p>
* Implementors note: The methods in this class are all declared to throw the
* exceptions according to the intentions of the Servlet API rather than
* throwing their Sling RuntimeException counter parts. This is done to easy the
* integration with traditional servlets.
*
* @see SlingAllMethodsServlet
*/
public class SlingSafeMethodsServlet extends GenericServlet {
/**
* Handles the <em>HEAD</em> method.
* <p>
* This base implementation just calls the
* {@link #doGet(HttpServletRequest, HttpServletResponse)} method dropping
* the output. Implementations of this class may overwrite this method if
* they have a more performing implementation. Otherwise, they may just keep
* this base implementation.
*
* @param request The HTTP request
* @param response The HTTP response which only gets the headers set
* @throws ServletException Forwarded from the
* {@link #doGet(HttpServletRequest, HttpServletResponse)}
* method called by this implementation.
* @throws IOException Forwarded from the
* {@link #doGet(HttpServletRequest, HttpServletResponse)}
* method called by this implementation.
*/
protected void doHead(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
// the null-output wrapper
NoBodyResponse wrappedResponse = new NoBodyResponse(response);
// do a normal get request, dropping the output
doGet(request, wrappedResponse);
// ensure the content length is set as gathered by the null-output
wrappedResponse.setContentLength();
}
/**
* Called by the
* {@link #mayService(HttpServletRequest, HttpServletResponse)} method to
* handle an HTTP <em>GET</em> request.
* <p>
* This default implementation reports back to the client that the method is
* not supported.
* <p>
* Implementations of this class should overwrite this method with their
* implementation for the HTTP <em>GET</em> method support.
*
* @param request The HTTP request
* @param response The HTTP response
* @throws ServletException Not thrown by this implementation.
* @throws IOException If the error status cannot be reported back to the
* client.
*/
protected void doGet(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
handleMethodNotImplemented(request, response);
}
/**
* Handles the <em>OPTIONS</em> method by setting the HTTP
* <code>Allow</code> header on the response depending on the methods
* declared in this class.
* <p>
* Extensions of this class should generally not overwrite this method but
* rather the {@link #getAllowedRequestMethods(Map)} method. This method
* gathers all declared public and protected methods for the concrete class
* (upto but not including this class) and calls the
* {@link #getAllowedRequestMethods(Map)} method with the methods gathered.
* The returned value is then used as the value of the <code>Allow</code>
* header set.
*
* @param request The HTTP request object. Not used.
* @param response The HTTP response object on which the header is set.
* @throws ServletException Not thrown by this implementation.
* @throws IOException Not thrown by this implementation.
*/
protected void doOptions(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
Map<String, Method> methods = getAllDeclaredMethods(getClass());
StringBuffer allowBuf = getAllowedRequestMethods(methods);
response.setHeader("Allow", allowBuf.toString());
}
/**
* Handles the <em>TRACE</em> method by just returning the list of all
* header values in the response body.
* <p>
* Extensions of this class do not generally need to overwrite this method
* as it contains all there is to be done to the <em>TRACE</em> method.
*
* @param request The HTTP request whose headers are returned.
* @param response The HTTP response into which the request headers are
* written.
* @throws ServletException Not thrown by this implementation.
* @throws IOException May be thrown if there is an problem sending back the
* request headers in the response stream.
*/
protected void doTrace(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
String CRLF = "\r\n";
StringBuffer responseString = new StringBuffer();
responseString.append("TRACE ").append(request.getRequestURI());
responseString.append(' ').append(request.getProtocol());
Enumeration<?> reqHeaderEnum = request.getHeaderNames();
while (reqHeaderEnum.hasMoreElements()) {
String headerName = (String) reqHeaderEnum.nextElement();
Enumeration<?> reqHeaderValEnum = request.getHeaders(headerName);
while (reqHeaderValEnum.hasMoreElements()) {
responseString.append(CRLF);
responseString.append(headerName).append(": ");
responseString.append(reqHeaderValEnum.nextElement());
}
}
responseString.append(CRLF);
String charset = "UTF-8";
byte[] rawResponse = responseString.toString().getBytes(charset);
int responseLength = rawResponse.length;
response.setContentType("message/http");
response.setCharacterEncoding(charset);
response.setContentLength(responseLength);
ServletOutputStream out = response.getOutputStream();
out.write(rawResponse);
}
/**
* Called by the {@link #service(HttpServletRequest, HttpServletResponse)}
* method to handle a request for an HTTP method, which is not known and
* handled by this class or its extension.
* <p>
* This default implementation reports back to the client that the method is
* not supported.
* <p>
* This method should be overwritten with great care. It is better to
* overwrite the
* {@link #mayService(HttpServletRequest, HttpServletResponse)} method and
* add support for any extension HTTP methods through an additional doXXX
* method.
*
* @param request The HTTP request
* @param response The HTTP response
* @throws ServletException Not thrown by this implementation.
* @throws IOException If the error status cannot be reported back to the
* client.
*/
protected void doGeneric(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
handleMethodNotImplemented(request, response);
}
/**
* Tries to handle the request by calling a Java method implemented for the
* respective HTTP request method.
* <p>
* This base class implentation dispatches the <em>HEAD</em>,
* <em>GET</em>, <em>OPTIONS</em> and <em>TRACE</em> to the
* respective <em>doXXX</em> methods and returns <code>true</code> if
* any of these methods is requested. Otherwise <code>false</code> is just
* returned.
* <p>
* Implementations of this class may overwrite this method but should first
* call this base implementation and in case <code>false</code> is
* returned add handling for any other method and of course return whether
* the requested method was known or not.
*
* @param request The HTTP request
* @param response The HTTP response
* @return <code>true</code> if the requested method (<code>request.getMethod()</code>)
* is known. Otherwise <code>false</code> is returned.
* @throws ServletException Forwarded from any of the dispatched methods
* @throws IOException Forwarded from any of the dispatched methods
*/
protected boolean mayService(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
// assume the method is known for now
boolean methodKnown = true;
String method = request.getMethod();
if (HttpConstants.METHOD_HEAD.equals(method)) {
doHead(request, response);
} else if (HttpConstants.METHOD_GET.equals(method)) {
doGet(request, response);
} else if (HttpConstants.METHOD_OPTIONS.equals(method)) {
doOptions(request, response);
} else if (HttpConstants.METHOD_TRACE.equals(method)) {
doTrace(request, response);
} else {
// actually we do not know the method
methodKnown = false;
}
// return whether we actually knew the request method or not
return methodKnown;
}
/**
* Helper method which causes an appropriate HTTP response to be sent for an
* unhandled HTTP request method. In case of HTTP/1.1 a 405 status code
* (Method Not Allowed) is returned, otherwise a 400 status (Bad Request) is
* returned.
*
* @param request The HTTP request from which the method and protocol values
* are extracted to build the appropriate message.
* @param response The HTTP response to which the error status is sent.
* @throws IOException Thrown if the status cannot be sent to the client.
*/
protected void handleMethodNotImplemented(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws IOException {
String protocol = request.getProtocol();
String msg = "Method " + request.getMethod() + " not supported";
if (protocol.endsWith("1.1")) {
// for HTTP/1.1 use 405 Method Not Allowed
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
// otherwise use 400 Bad Request
response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
/**
* Called by the {@link #service(ServletRequest, ServletResponse)} method to
* handle the HTTP request. This implementation calls the
* {@link #mayService(HttpServletRequest, HttpServletResponse)} method and
* depedending on its return value call the
* {@link #doGeneric(HttpServletRequest, HttpServletResponse)} method. If
* the {@link #mayService(HttpServletRequest, HttpServletResponse)} method
* can handle the request, the
* {@link #doGeneric(HttpServletRequest, HttpServletResponse)} method is not
* called otherwise it is called.
* <p>
* Implementations of this class should not generally overwrite this method.
* Rather the {@link #mayService(HttpServletRequest, HttpServletResponse)}
* method should be overwritten to add support for more HTTP methods.
*
* @param request The HTTP request
* @param response The HTTP response
* @throws ServletException Forwarded from the
* {@link #mayService(HttpServletRequest, HttpServletResponse)}
* or
* {@link #doGeneric(HttpServletRequest, HttpServletResponse)}
* methods.
* @throws IOException Forwarded from the
* {@link #mayService(HttpServletRequest, HttpServletResponse)}
* or
* {@link #doGeneric(HttpServletRequest, HttpServletResponse)}
* methods.
*/
protected void service(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
// first try to handle the request by the known methods
boolean methodKnown = mayService(request, response);
// otherwise try to handle it through generic means
if (!methodKnown) {
doGeneric(request, response);
}
}
/**
* Forwards the request to the
* {@link #service(SlingHttpServletRequest, SlingHttpServletResponse)}
* method if the request is a HTTP request.
* <p>
* Implementations of this class will not generally overwrite this method.
*
* @param req The Servlet request
* @param res The Servlet response
* @throws ServletException If the request is not a HTTP request or
* forwarded from the
* {@link #service(SlingHttpServletRequest, SlingHttpServletResponse)}
* called.
* @throws IOException Forwarded from the
* {@link #service(SlingHttpServletRequest, SlingHttpServletResponse)}
* called.
*/
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
try {
SlingHttpServletRequest request = (SlingHttpServletRequest) req;
SlingHttpServletResponse response = (SlingHttpServletResponse) res;
service(request, response);
} catch (ClassCastException cce) {
throw new ServletException("Not a Sling HTTP request/response");
}
}
/**
* Helper method called by
* {@link #doOptions(HttpServletRequest, HttpServletResponse)} to calculate
* the value of the <em>Allow</em> header sent as the response to the HTTP
* <em>OPTIONS</em> request.
* <p>
* This base class implementation checks whether any doXXX methods exist for
* <em>GET</em> and <em>HEAD</em> and returns the list of methods
* supported found. The list returned always includes the HTTP
* <em>OPTIONS</em> and <em>TRACE</em> methods.
* <p>
* Implementations of this class may overwrite this method check for more
* methods supported by the extension (generally the same list as used in
* the {@link #mayService(HttpServletRequest, HttpServletResponse)} method).
* This base class implementation should always be called to make sure the
* default HTTP methods are included in the list.
*
* @param declaredMethods The public and protected methods declared in the
* extension of this class.
* @return A <code>StringBuffer</code> containing the list of HTTP methods
* supported.
*/
protected StringBuffer getAllowedRequestMethods(
Map<String, Method> declaredMethods) {
StringBuffer allowBuf = new StringBuffer();
// OPTIONS and TRACE are always supported by this servlet
allowBuf.append(HttpConstants.METHOD_OPTIONS);
allowBuf.append(", ").append(HttpConstants.METHOD_TRACE);
// add more method names depending on the methods found
if (declaredMethods.containsKey("doHead")
&& !declaredMethods.containsKey("doGet")) {
allowBuf.append(", ").append(HttpConstants.METHOD_HEAD);
} else if (declaredMethods.containsKey("doGet")) {
allowBuf.append(", ").append(HttpConstants.METHOD_GET);
allowBuf.append(", ").append(HttpConstants.METHOD_HEAD);
}
return allowBuf;
}
/**
* Returns a map of methods declared by the class indexed by method name.
* This method is called by the
* {@link #doOptions(HttpServletRequest, HttpServletResponse)} method to
* find the methods to be checked by the
* {@link #getAllowedRequestMethods(Map)} method. Note, that only extension
* classes of this class are considered to be sure to not account for the
* default implementations of the doXXX methods in this class.
*
* @param c The <code>Class</code> to get the declared methods from
* @return The Map of methods considered for support checking.
*/
private Map<String, Method> getAllDeclaredMethods(Class<?> c) {
// stop (and do not include) the AbstractSlingServletClass
if (c == null
|| c.getName().equals(SlingSafeMethodsServlet.class.getName())) {
return new HashMap<String, Method>();
}
// get the declared methods from the base class
Map<String, Method> methodSet = getAllDeclaredMethods(c.getSuperclass());
// add declared methods of c (maybe overwrite base class methods)
Method[] declaredMethods = c.getDeclaredMethods();
for (Method method : declaredMethods) {
// only consider public and protected methods
if (Modifier.isProtected(method.getModifiers())
|| Modifier.isPublic(method.getModifiers())) {
methodSet.put(method.getName(), method);
}
}
return methodSet;
}
/**
* A response that includes no body, for use in (dumb) "HEAD" support. This
* just swallows that body, counting the bytes in order to set the content
* length appropriately.
*/
private class NoBodyResponse extends SlingHttpServletResponseWrapper {
/** The byte sink and counter */
private NoBodyOutputStream noBody;
/** Optional writer around the byte sink */
private PrintWriter writer;
/** Whether the request processor set the content length itself or not. */
private boolean didSetContentLength;
NoBodyResponse(SlingHttpServletResponse wrappedResponse) {
super(wrappedResponse);
noBody = new NoBodyOutputStream();
}
/**
* Called at the end of request processing to ensure the content length
* is set. If the processor already set the length, this method does not
* do anything. Otherwise the number of bytes written through the
* null-output is set on the response.
*/
void setContentLength() {
if (!didSetContentLength) {
setContentLength(noBody.getContentLength());
}
}
/**
* Overwrite this to prevent setting the content length at the end of
* the request through {@link #setContentLength()}
*/
public void setContentLength(int len) {
super.setContentLength(len);
didSetContentLength = true;
}
/**
* Just return the null output stream and don't check whether a writer
* has already been acquired.
*/
public ServletOutputStream getOutputStream() {
return noBody;
}
/**
* Just return the writer to the null output stream and don't check
* whether an output stram has already been acquired.
*/
public PrintWriter getWriter() throws UnsupportedEncodingException {
if (writer == null) {
OutputStreamWriter w;
w = new OutputStreamWriter(noBody, getCharacterEncoding());
writer = new PrintWriter(w);
}
return writer;
}
}
/**
* Simple ServletOutputStream which just does not write but counts the bytes
* written through it. This class is used by the NoBodyResponse.
*/
private class NoBodyOutputStream extends ServletOutputStream {
private int contentLength = 0;
/**
* @return the number of bytes "written" through this stream
*/
int getContentLength() {
return contentLength;
}
public void write(int b) {
contentLength++;
}
public void write(byte buf[], int offset, int len) {
if (len >= 0) {
contentLength += len;
} else {
throw new IndexOutOfBoundsException();
}
}
}
}
|
Default implementation of the getServletInfo() method returns the simple
class name of the servlet now
git-svn-id: c3eb811ccca381e673aa62a65336ec26649ed58c@635887 13f79535-47bb-0310-9956-ffa450edef68
|
api/src/main/java/org/apache/sling/api/servlets/SlingSafeMethodsServlet.java
|
Default implementation of the getServletInfo() method returns the simple class name of the servlet now
|
|
Java
|
apache-2.0
|
18edb781e046e22dce9cd3a0c598c7784658e5cf
| 0
|
innoveit/react-native-ble-manager,innoveit/react-native-ble-manager,innoveit/react-native-ble-manager
|
package it.innove;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.util.Log;
import com.facebook.react.bridge.*;
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;
import org.json.JSONException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import static android.app.Activity.RESULT_OK;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread;
class BleManager extends ReactContextBaseJavaModule implements ActivityEventListener {
private static final String LOG_TAG = "logs";
static final int ENABLE_REQUEST = 539;
private BluetoothAdapter bluetoothAdapter;
private Context context;
private ReactContext reactContext;
private Callback enableBluetoothCallback;
// key is the MAC Address
private Map<String, Peripheral> peripherals = new LinkedHashMap<>();
// scan session id
private AtomicInteger scanSessionId = new AtomicInteger();
public BleManager(ReactApplicationContext reactContext) {
super(reactContext);
context = reactContext;
this.reactContext = reactContext;
reactContext.addActivityEventListener(this);
Log.d(LOG_TAG, "BleManager created");
}
@Override
public String getName() {
return "BleManager";
}
private BluetoothAdapter getBluetoothAdapter() {
if (bluetoothAdapter == null) {
BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = manager.getAdapter();
}
return bluetoothAdapter;
}
private void sendEvent(String eventName,
@Nullable WritableMap params) {
getReactApplicationContext()
.getJSModule(RCTNativeAppEventEmitter.class)
.emit(eventName, params);
}
@ReactMethod
public void start(ReadableMap options, Callback callback) {
Log.d(LOG_TAG, "start");
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
context.registerReceiver(mReceiver, filter);
callback.invoke();
Log.d(LOG_TAG, "BleManager initialized");
}
@ReactMethod
public void enableBluetooth(Callback callback) {
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
if (!getBluetoothAdapter().isEnabled()) {
enableBluetoothCallback = callback;
Intent intentEnable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
if (getCurrentActivity() == null)
callback.invoke("Current activity not available");
else
getCurrentActivity().startActivityForResult(intentEnable, ENABLE_REQUEST);
} else
callback.invoke();
}
@ReactMethod
public void scan(ReadableArray serviceUUIDs, final int scanSeconds, boolean allowDuplicates, Callback callback) {
Log.d(LOG_TAG, "scan");
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
if (!getBluetoothAdapter().isEnabled())
return;
for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, Peripheral> entry = iterator.next();
if (!entry.getValue().isConnected()) {
iterator.remove();
}
}
if (Build.VERSION.SDK_INT >= LOLLIPOP) {
scan21(serviceUUIDs, scanSeconds, callback);
} else {
scan19(serviceUUIDs, scanSeconds, callback);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void scan21(ReadableArray serviceUUIDs, final int scanSeconds, Callback callback) {
ScanSettings settings = new ScanSettings.Builder().build();
List<ScanFilter> filters = new ArrayList<>();
if (serviceUUIDs.size() > 0) {
for(int i = 0; i < serviceUUIDs.size(); i++){
ScanFilter.Builder builder = new ScanFilter.Builder();
builder.setServiceUuid(new ParcelUuid(UUIDHelper.uuidFromString(serviceUUIDs.getString(i))));
filters.add(builder.build());
Log.d(LOG_TAG, "Filter service: " + serviceUUIDs.getString(i));
}
}
final ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(final int callbackType, final ScanResult result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i(LOG_TAG, "DiscoverPeripheral: " + result.getDevice().getName());
String address = result.getDevice().getAddress();
if (!peripherals.containsKey(address)) {
Peripheral peripheral = new Peripheral(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes(), reactContext);
peripherals.put(address, peripheral);
BundleJSONConverter bjc = new BundleJSONConverter();
try {
Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject());
WritableMap map = Arguments.fromBundle(bundle);
sendEvent("BleManagerDiscoverPeripheral", map);
} catch (JSONException ignored) {
}
} else {
// this isn't necessary
Peripheral peripheral = peripherals.get(address);
peripheral.updateRssi(result.getRssi());
}
}
});
}
@Override
public void onBatchScanResults(final List<ScanResult> results) {
}
@Override
public void onScanFailed(final int errorCode) {
}
};
getBluetoothAdapter().getBluetoothLeScanner().startScan(filters, settings, mScanCallback);
if (scanSeconds > 0) {
Thread thread = new Thread() {
private int currentScanSession = scanSessionId.incrementAndGet();
@Override
public void run() {
try {
Thread.sleep(scanSeconds * 1000);
} catch (InterruptedException ignored) {
}
runOnUiThread(new Runnable() {
@Override
public void run() {
// check current scan session was not stopped
if (scanSessionId.intValue() == currentScanSession) {
getBluetoothAdapter().getBluetoothLeScanner().stopScan(mScanCallback);
WritableMap map = Arguments.createMap();
sendEvent("BleManagerStopScan", map);
}
}
});
}
};
thread.start();
}
callback.invoke();
}
private void scan19(ReadableArray serviceUUIDs, final int scanSeconds, Callback callback) {
getBluetoothAdapter().startLeScan(mLeScanCallback);
if (scanSeconds > 0) {
Thread thread = new Thread() {
private int currentScanSession = scanSessionId.incrementAndGet();
@Override
public void run() {
try {
Thread.sleep(scanSeconds * 1000);
} catch (InterruptedException ignored) {
}
runOnUiThread(new Runnable() {
@Override
public void run() {
// check current scan session was not stopped
if (scanSessionId.intValue() == currentScanSession) {
getBluetoothAdapter().stopLeScan(mLeScanCallback);
WritableMap map = Arguments.createMap();
sendEvent("BleManagerStopScan", map);
}
}
});
}
};
thread.start();
}
callback.invoke();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void stopScan21(Callback callback) {
final ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(final int callbackType, final ScanResult result) {
}
};
getBluetoothAdapter().getBluetoothLeScanner().stopScan(mScanCallback);
callback.invoke();
}
private void stopScan19(Callback callback) {
getBluetoothAdapter().stopLeScan(mLeScanCallback);
callback.invoke();
}
@ReactMethod
public void stopScan(Callback callback) {
Log.d(LOG_TAG, "Stop scan");
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
if (!getBluetoothAdapter().isEnabled()) {
callback.invoke("Bluetooth not enabled");
return;
}
// update scanSessionId to prevent stopping next scan by running timeout thread
scanSessionId.incrementAndGet();
if (Build.VERSION.SDK_INT >= LOLLIPOP) {
stopScan21(callback);
} else {
stopScan19(callback);
}
}
@ReactMethod
public void connect(String peripheralUUID, Callback callback) {
Log.d(LOG_TAG, "Connect to: " + peripheralUUID );
Peripheral peripheral = peripherals.get(peripheralUUID);
if (peripheral == null) {
if (peripheralUUID != null) {
peripheralUUID = peripheralUUID.toUpperCase();
}
if (bluetoothAdapter.checkBluetoothAddress(peripheralUUID)) {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(peripheralUUID);
peripheral = new Peripheral(device, reactContext);
peripherals.put(peripheralUUID, peripheral);
} else {
callback.invoke("Invalid peripheral uuid");
return;
}
}
peripheral.connect(callback, getCurrentActivity());
}
@ReactMethod
public void disconnect(String peripheralUUID, Callback callback) {
Log.d(LOG_TAG, "Disconnect from: " + peripheralUUID);
Peripheral peripheral = peripherals.get(peripheralUUID);
if (peripheral != null){
peripheral.disconnect();
callback.invoke();
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void startNotification(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) {
Log.d(LOG_TAG, "startNotification");
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null){
peripheral.registerNotify(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void stopNotification(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) {
Log.d(LOG_TAG, "stopNotification");
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null){
peripheral.removeNotify(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void write(String deviceUUID, String serviceUUID, String characteristicUUID, String message, Integer maxByteSize, Callback callback) {
Log.d(LOG_TAG, "Write to: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null){
byte[] decoded = Base64.decode(message.getBytes(), Base64.DEFAULT);
Log.d(LOG_TAG, "Message(" + decoded.length + "): " + bytesToHex(decoded));
peripheral.write(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), decoded, maxByteSize, null, callback, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void writeWithoutResponse(String deviceUUID, String serviceUUID, String characteristicUUID, String message, Integer maxByteSize, Integer queueSleepTime, Callback callback) {
Log.d(LOG_TAG, "Write without response to: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null){
byte[] decoded = Base64.decode(message.getBytes(), Base64.DEFAULT);
Log.d(LOG_TAG, "Message(" + decoded.length + "): " + bytesToHex(decoded));
peripheral.write(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), decoded, maxByteSize, queueSleepTime, callback, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void read(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) {
Log.d(LOG_TAG, "Read from: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null){
peripheral.read(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback);
} else
callback.invoke("Peripheral not found", null);
}
@ReactMethod
public void readRSSI(String deviceUUID, Callback callback) {
Log.d(LOG_TAG, "Read RSSI from: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null){
peripheral.readRSSI(callback);
} else
callback.invoke("Peripheral not found", null);
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi,
final byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i(LOG_TAG, "DiscoverPeripheral: " + device.getName());
String address = device.getAddress();
if (!peripherals.containsKey(address)) {
Peripheral peripheral = new Peripheral(device, rssi, scanRecord, reactContext);
peripherals.put(device.getAddress(), peripheral);
BundleJSONConverter bjc = new BundleJSONConverter();
try {
Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject());
WritableMap map = Arguments.fromBundle(bundle);
sendEvent("BleManagerDiscoverPeripheral", map);
} catch (JSONException ignored) {
}
} else {
// this isn't necessary
Peripheral peripheral = peripherals.get(address);
peripheral.updateRssi(rssi);
}
}
});
}
};
@ReactMethod
public void checkState(){
Log.d(LOG_TAG, "checkState");
BluetoothAdapter adapter = getBluetoothAdapter();
String state = "off";
if (adapter != null) {
switch (adapter.getState()){
case BluetoothAdapter.STATE_ON:
state = "on";
break;
case BluetoothAdapter.STATE_OFF:
state = "off";
}
}
WritableMap map = Arguments.createMap();
map.putString("state", state);
Log.d(LOG_TAG, "state:" + state);
sendEvent("BleManagerDidUpdateState", map);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(LOG_TAG, "onReceive");
final String action = intent.getAction();
String stringState = "";
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
stringState = "off";
break;
case BluetoothAdapter.STATE_TURNING_OFF:
stringState = "turning_off";
break;
case BluetoothAdapter.STATE_ON:
stringState = "on";
break;
case BluetoothAdapter.STATE_TURNING_ON:
stringState = "turning_on";
break;
}
}
WritableMap map = Arguments.createMap();
map.putString("state", stringState);
Log.d(LOG_TAG, "state: " + stringState);
sendEvent("BleManagerDidUpdateState", map);
}
};
@ReactMethod
public void getDiscoveredPeripherals(Callback callback) {
Log.d(LOG_TAG, "Get discovered peripherals");
WritableArray map = Arguments.createArray();
BundleJSONConverter bjc = new BundleJSONConverter();
for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, Peripheral> entry = iterator.next();
Peripheral peripheral = entry.getValue();
try {
Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject());
WritableMap jsonBundle = Arguments.fromBundle(bundle);
map.pushMap(jsonBundle);
} catch (JSONException ignored) {
callback.invoke("Peripheral json conversion error", null);
}
}
callback.invoke(null, map);
}
@ReactMethod
public void getConnectedPeripherals(ReadableArray serviceUUIDs, Callback callback) {
Log.d(LOG_TAG, "Get connected peripherals");
WritableArray map = Arguments.createArray();
BundleJSONConverter bjc = new BundleJSONConverter();
for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, Peripheral> entry = iterator.next();
Peripheral peripheral = entry.getValue();
Boolean accept = false;
if (serviceUUIDs != null && serviceUUIDs.size() > 0) {
for (int i = 0; i < serviceUUIDs.size(); i++) {
accept = peripheral.hasService(UUIDHelper.uuidFromString(serviceUUIDs.getString(i)));
}
} else {
accept = true;
}
if (peripheral.isConnected() && accept) {
try {
Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject());
WritableMap jsonBundle = Arguments.fromBundle(bundle);
map.pushMap(jsonBundle);
} catch (JSONException ignored) {
callback.invoke("Peripheral json conversion error", null);
}
}
}
callback.invoke(null, map);
}
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
Log.d(LOG_TAG, "onActivityResult");
if (requestCode == ENABLE_REQUEST && enableBluetoothCallback != null) {
if (resultCode == RESULT_OK) {
enableBluetoothCallback.invoke();
} else {
enableBluetoothCallback.invoke("User refused to enable");
}
enableBluetoothCallback = null;
}
}
@Override
public void onNewIntent(Intent intent) {
}
}
|
android/src/main/java/it/innove/BleManager.java
|
package it.innove;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.util.Log;
import com.facebook.react.bridge.*;
import com.facebook.react.modules.core.RCTNativeAppEventEmitter;
import org.json.JSONException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import static android.app.Activity.RESULT_OK;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static com.facebook.react.bridge.UiThreadUtil.runOnUiThread;
class BleManager extends ReactContextBaseJavaModule implements ActivityEventListener {
private static final String LOG_TAG = "logs";
static final int ENABLE_REQUEST = 1;
private BluetoothAdapter bluetoothAdapter;
private Context context;
private ReactContext reactContext;
private Callback enableBluetoothCallback;
// key is the MAC Address
private Map<String, Peripheral> peripherals = new LinkedHashMap<>();
// scan session id
private AtomicInteger scanSessionId = new AtomicInteger();
public BleManager(ReactApplicationContext reactContext) {
super(reactContext);
context = reactContext;
this.reactContext = reactContext;
reactContext.addActivityEventListener(this);
Log.d(LOG_TAG, "BleManager created");
}
@Override
public String getName() {
return "BleManager";
}
private BluetoothAdapter getBluetoothAdapter() {
if (bluetoothAdapter == null) {
BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = manager.getAdapter();
}
return bluetoothAdapter;
}
private void sendEvent(String eventName,
@Nullable WritableMap params) {
getReactApplicationContext()
.getJSModule(RCTNativeAppEventEmitter.class)
.emit(eventName, params);
}
@ReactMethod
public void start(ReadableMap options, Callback callback) {
Log.d(LOG_TAG, "start");
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
context.registerReceiver(mReceiver, filter);
callback.invoke();
Log.d(LOG_TAG, "BleManager initialized");
}
@ReactMethod
public void enableBluetooth(Callback callback) {
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
if (!getBluetoothAdapter().isEnabled()) {
enableBluetoothCallback = callback;
Intent intentEnable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
if (getCurrentActivity() == null)
callback.invoke("Current activity not available");
else
getCurrentActivity().startActivityForResult(intentEnable, ENABLE_REQUEST);
} else
callback.invoke();
}
@ReactMethod
public void scan(ReadableArray serviceUUIDs, final int scanSeconds, boolean allowDuplicates, Callback callback) {
Log.d(LOG_TAG, "scan");
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
if (!getBluetoothAdapter().isEnabled())
return;
for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, Peripheral> entry = iterator.next();
if (!entry.getValue().isConnected()) {
iterator.remove();
}
}
if (Build.VERSION.SDK_INT >= LOLLIPOP) {
scan21(serviceUUIDs, scanSeconds, callback);
} else {
scan19(serviceUUIDs, scanSeconds, callback);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void scan21(ReadableArray serviceUUIDs, final int scanSeconds, Callback callback) {
ScanSettings settings = new ScanSettings.Builder().build();
List<ScanFilter> filters = new ArrayList<>();
if (serviceUUIDs.size() > 0) {
for(int i = 0; i < serviceUUIDs.size(); i++){
ScanFilter.Builder builder = new ScanFilter.Builder();
builder.setServiceUuid(new ParcelUuid(UUIDHelper.uuidFromString(serviceUUIDs.getString(i))));
filters.add(builder.build());
Log.d(LOG_TAG, "Filter service: " + serviceUUIDs.getString(i));
}
}
final ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(final int callbackType, final ScanResult result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i(LOG_TAG, "DiscoverPeripheral: " + result.getDevice().getName());
String address = result.getDevice().getAddress();
if (!peripherals.containsKey(address)) {
Peripheral peripheral = new Peripheral(result.getDevice(), result.getRssi(), result.getScanRecord().getBytes(), reactContext);
peripherals.put(address, peripheral);
BundleJSONConverter bjc = new BundleJSONConverter();
try {
Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject());
WritableMap map = Arguments.fromBundle(bundle);
sendEvent("BleManagerDiscoverPeripheral", map);
} catch (JSONException ignored) {
}
} else {
// this isn't necessary
Peripheral peripheral = peripherals.get(address);
peripheral.updateRssi(result.getRssi());
}
}
});
}
@Override
public void onBatchScanResults(final List<ScanResult> results) {
}
@Override
public void onScanFailed(final int errorCode) {
}
};
getBluetoothAdapter().getBluetoothLeScanner().startScan(filters, settings, mScanCallback);
if (scanSeconds > 0) {
Thread thread = new Thread() {
private int currentScanSession = scanSessionId.incrementAndGet();
@Override
public void run() {
try {
Thread.sleep(scanSeconds * 1000);
} catch (InterruptedException ignored) {
}
runOnUiThread(new Runnable() {
@Override
public void run() {
// check current scan session was not stopped
if (scanSessionId.intValue() == currentScanSession) {
getBluetoothAdapter().getBluetoothLeScanner().stopScan(mScanCallback);
WritableMap map = Arguments.createMap();
sendEvent("BleManagerStopScan", map);
}
}
});
}
};
thread.start();
}
callback.invoke();
}
private void scan19(ReadableArray serviceUUIDs, final int scanSeconds, Callback callback) {
getBluetoothAdapter().startLeScan(mLeScanCallback);
if (scanSeconds > 0) {
Thread thread = new Thread() {
private int currentScanSession = scanSessionId.incrementAndGet();
@Override
public void run() {
try {
Thread.sleep(scanSeconds * 1000);
} catch (InterruptedException ignored) {
}
runOnUiThread(new Runnable() {
@Override
public void run() {
// check current scan session was not stopped
if (scanSessionId.intValue() == currentScanSession) {
getBluetoothAdapter().stopLeScan(mLeScanCallback);
WritableMap map = Arguments.createMap();
sendEvent("BleManagerStopScan", map);
}
}
});
}
};
thread.start();
}
callback.invoke();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void stopScan21(Callback callback) {
final ScanCallback mScanCallback = new ScanCallback() {
@Override
public void onScanResult(final int callbackType, final ScanResult result) {
}
};
getBluetoothAdapter().getBluetoothLeScanner().stopScan(mScanCallback);
callback.invoke();
}
private void stopScan19(Callback callback) {
getBluetoothAdapter().stopLeScan(mLeScanCallback);
callback.invoke();
}
@ReactMethod
public void stopScan(Callback callback) {
Log.d(LOG_TAG, "Stop scan");
if (getBluetoothAdapter() == null) {
Log.d(LOG_TAG, "No bluetooth support");
callback.invoke("No bluetooth support");
return;
}
if (!getBluetoothAdapter().isEnabled()) {
callback.invoke("Bluetooth not enabled");
return;
}
// update scanSessionId to prevent stopping next scan by running timeout thread
scanSessionId.incrementAndGet();
if (Build.VERSION.SDK_INT >= LOLLIPOP) {
stopScan21(callback);
} else {
stopScan19(callback);
}
}
@ReactMethod
public void connect(String peripheralUUID, Callback callback) {
Log.d(LOG_TAG, "Connect to: " + peripheralUUID );
Peripheral peripheral = peripherals.get(peripheralUUID);
if (peripheral == null) {
if (peripheralUUID != null) {
peripheralUUID = peripheralUUID.toUpperCase();
}
if (bluetoothAdapter.checkBluetoothAddress(peripheralUUID)) {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(peripheralUUID);
peripheral = new Peripheral(device, reactContext);
peripherals.put(peripheralUUID, peripheral);
} else {
callback.invoke("Invalid peripheral uuid");
return;
}
}
peripheral.connect(callback, getCurrentActivity());
}
@ReactMethod
public void disconnect(String peripheralUUID, Callback callback) {
Log.d(LOG_TAG, "Disconnect from: " + peripheralUUID);
Peripheral peripheral = peripherals.get(peripheralUUID);
if (peripheral != null){
peripheral.disconnect();
callback.invoke();
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void startNotification(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) {
Log.d(LOG_TAG, "startNotification");
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null){
peripheral.registerNotify(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void stopNotification(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) {
Log.d(LOG_TAG, "stopNotification");
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null){
peripheral.removeNotify(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void write(String deviceUUID, String serviceUUID, String characteristicUUID, String message, Integer maxByteSize, Callback callback) {
Log.d(LOG_TAG, "Write to: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null){
byte[] decoded = Base64.decode(message.getBytes(), Base64.DEFAULT);
Log.d(LOG_TAG, "Message(" + decoded.length + "): " + bytesToHex(decoded));
peripheral.write(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), decoded, maxByteSize, null, callback, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void writeWithoutResponse(String deviceUUID, String serviceUUID, String characteristicUUID, String message, Integer maxByteSize, Integer queueSleepTime, Callback callback) {
Log.d(LOG_TAG, "Write without response to: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null){
byte[] decoded = Base64.decode(message.getBytes(), Base64.DEFAULT);
Log.d(LOG_TAG, "Message(" + decoded.length + "): " + bytesToHex(decoded));
peripheral.write(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), decoded, maxByteSize, queueSleepTime, callback, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
} else
callback.invoke("Peripheral not found");
}
@ReactMethod
public void read(String deviceUUID, String serviceUUID, String characteristicUUID, Callback callback) {
Log.d(LOG_TAG, "Read from: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null){
peripheral.read(UUIDHelper.uuidFromString(serviceUUID), UUIDHelper.uuidFromString(characteristicUUID), callback);
} else
callback.invoke("Peripheral not found", null);
}
@ReactMethod
public void readRSSI(String deviceUUID, Callback callback) {
Log.d(LOG_TAG, "Read RSSI from: " + deviceUUID);
Peripheral peripheral = peripherals.get(deviceUUID);
if (peripheral != null){
peripheral.readRSSI(callback);
} else
callback.invoke("Peripheral not found", null);
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi,
final byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i(LOG_TAG, "DiscoverPeripheral: " + device.getName());
String address = device.getAddress();
if (!peripherals.containsKey(address)) {
Peripheral peripheral = new Peripheral(device, rssi, scanRecord, reactContext);
peripherals.put(device.getAddress(), peripheral);
BundleJSONConverter bjc = new BundleJSONConverter();
try {
Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject());
WritableMap map = Arguments.fromBundle(bundle);
sendEvent("BleManagerDiscoverPeripheral", map);
} catch (JSONException ignored) {
}
} else {
// this isn't necessary
Peripheral peripheral = peripherals.get(address);
peripheral.updateRssi(rssi);
}
}
});
}
};
@ReactMethod
public void checkState(){
Log.d(LOG_TAG, "checkState");
BluetoothAdapter adapter = getBluetoothAdapter();
String state = "off";
if (adapter != null) {
switch (adapter.getState()){
case BluetoothAdapter.STATE_ON:
state = "on";
break;
case BluetoothAdapter.STATE_OFF:
state = "off";
}
}
WritableMap map = Arguments.createMap();
map.putString("state", state);
Log.d(LOG_TAG, "state:" + state);
sendEvent("BleManagerDidUpdateState", map);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(LOG_TAG, "onReceive");
final String action = intent.getAction();
String stringState = "";
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
stringState = "off";
break;
case BluetoothAdapter.STATE_TURNING_OFF:
stringState = "turning_off";
break;
case BluetoothAdapter.STATE_ON:
stringState = "on";
break;
case BluetoothAdapter.STATE_TURNING_ON:
stringState = "turning_on";
break;
}
}
WritableMap map = Arguments.createMap();
map.putString("state", stringState);
Log.d(LOG_TAG, "state: " + stringState);
sendEvent("BleManagerDidUpdateState", map);
}
};
@ReactMethod
public void getDiscoveredPeripherals(Callback callback) {
Log.d(LOG_TAG, "Get discovered peripherals");
WritableArray map = Arguments.createArray();
BundleJSONConverter bjc = new BundleJSONConverter();
for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, Peripheral> entry = iterator.next();
Peripheral peripheral = entry.getValue();
try {
Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject());
WritableMap jsonBundle = Arguments.fromBundle(bundle);
map.pushMap(jsonBundle);
} catch (JSONException ignored) {
callback.invoke("Peripheral json conversion error", null);
}
}
callback.invoke(null, map);
}
@ReactMethod
public void getConnectedPeripherals(ReadableArray serviceUUIDs, Callback callback) {
Log.d(LOG_TAG, "Get connected peripherals");
WritableArray map = Arguments.createArray();
BundleJSONConverter bjc = new BundleJSONConverter();
for (Iterator<Map.Entry<String, Peripheral>> iterator = peripherals.entrySet().iterator(); iterator.hasNext(); ) {
Map.Entry<String, Peripheral> entry = iterator.next();
Peripheral peripheral = entry.getValue();
Boolean accept = false;
if (serviceUUIDs != null && serviceUUIDs.size() > 0) {
for (int i = 0; i < serviceUUIDs.size(); i++) {
accept = peripheral.hasService(UUIDHelper.uuidFromString(serviceUUIDs.getString(i)));
}
} else {
accept = true;
}
if (peripheral.isConnected() && accept) {
try {
Bundle bundle = bjc.convertToBundle(peripheral.asJSONObject());
WritableMap jsonBundle = Arguments.fromBundle(bundle);
map.pushMap(jsonBundle);
} catch (JSONException ignored) {
callback.invoke("Peripheral json conversion error", null);
}
}
}
callback.invoke(null, map);
}
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
Log.d(LOG_TAG, "onActivityResult");
if (requestCode == ENABLE_REQUEST && enableBluetoothCallback != null) {
if (resultCode == RESULT_OK) {
enableBluetoothCallback.invoke();
} else {
enableBluetoothCallback.invoke("User refused to enable");
}
enableBluetoothCallback = null;
}
}
@Override
public void onNewIntent(Intent intent) {
}
}
|
changed activity request code
request code 1 is very commonly used as the default, and so there is a high chance for conflicts that can take quite a while to debug (I had a conflict with react-native-android-location-services-dialog-box). It's best to choose a number that's a bit more random.
|
android/src/main/java/it/innove/BleManager.java
|
changed activity request code
|
|
Java
|
apache-2.0
|
89b4f444d97d4fe2d262eba0782edd4862124d00
| 0
|
google/tink,google/tink,google/tink,google/tink,google/tink,google/tink,google/tink,google/tink
|
// 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.crypto.tink.apps.rewardedads;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.crypto.tink.subtle.Base64;
import com.google.crypto.tink.subtle.EcdsaVerifyJce;
import com.google.crypto.tink.subtle.EllipticCurves;
import com.google.crypto.tink.subtle.EllipticCurves.EcdsaEncoding;
import com.google.crypto.tink.subtle.Enums.HashType;
import com.google.crypto.tink.util.KeysDownloader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.interfaces.ECPublicKey;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* An implementation of the verifier side of Server-Side Verification of Google AdMob Rewarded Ads.
*
* <p>Typical usage:
*
* <pre>{@code
* RewardedAdsVerifier verifier = new RewardedAdsVerifier.Builder()
* .fetchVerifyingPublicKeysWith(
* RewardedAdsVerifier.KEYS_DOWNLOADER_INSTANCE_PROD)
* .build();
* String rewardUrl = ...;
* verifier.verify(rewardUrl);
* }</pre>
*
* <p>This usage ensures that you always have the latest public keys, even when the keys were
* recently rotated. It will fetch and cache the latest public keys from {#PUBLIC_KEYS_URL_PROD}.
* When the cache expires, it will re-fetch the public keys. When initializing your server, we also
* recommend that you call {@link KeysDownloader#refreshInBackground()} of {@link
* RewardedAdsVerifier.KEYS_DOWNLOADER_INSTANCE_PROD} to proactively fetch the public keys.
*
* <p>If you've already downloaded the public keys and have other means to manage key rotation, you
* can use {@link RewardedAdsVerifier.Builder#setVerifyingPublicKeys} to set the public keys. The
* Builder also allows you to customize other properties.
*/
public final class RewardedAdsVerifier {
/** Default HTTP transport used by this class. */
private static final NetHttpTransport DEFAULT_HTTP_TRANSPORT =
new NetHttpTransport.Builder().build();
private static final Executor DEFAULT_BACKGROUND_EXECUTOR = Executors.newCachedThreadPool();
private final List<VerifyingPublicKeysProvider> verifyingPublicKeysProviders;
public static final String SIGNATURE_PARAM_NAME = "signature=";
public static final String KEY_ID_PARAM_NAME = "key_id=";
/** URL to fetch keys for environment production. */
public static final String PUBLIC_KEYS_URL_PROD =
"https://www.gstatic.com/admob/reward/verifier-keys.json";
/** URL to fetch keys for environment test. */
public static final String PUBLIC_KEYS_URL_TEST =
"https://www.gstatic.com/admob/reward/verifier-keys-test.json";
/**
* Instance configured to talk to fetch keys from production environment (from {@link
* KeysDownloader#PUBLIC_KEYS_URL_PROD}).
*/
public static final KeysDownloader KEYS_DOWNLOADER_INSTANCE_PROD =
new KeysDownloader(DEFAULT_BACKGROUND_EXECUTOR, DEFAULT_HTTP_TRANSPORT, PUBLIC_KEYS_URL_PROD);
/**
* Instance configured to talk to fetch keys from test environment (from {@link
* KeysDownloader#KEYS_URL_TEST}).
*/
public static final KeysDownloader KEYS_DOWNLOADER_INSTANCE_TEST =
new KeysDownloader(DEFAULT_BACKGROUND_EXECUTOR, DEFAULT_HTTP_TRANSPORT, PUBLIC_KEYS_URL_TEST);
RewardedAdsVerifier(List<VerifyingPublicKeysProvider> verifyingPublicKeysProviders)
throws GeneralSecurityException {
if (verifyingPublicKeysProviders == null || verifyingPublicKeysProviders.isEmpty()) {
throw new IllegalArgumentException(
"must set at least one way to get verifying key using"
+ " Builder.fetchVerifyingPublicKeysWith or Builder.setVerifyingPublicKeys");
}
this.verifyingPublicKeysProviders = verifyingPublicKeysProviders;
}
private RewardedAdsVerifier(Builder builder) throws GeneralSecurityException {
this(builder.verifyingPublicKeysProviders);
}
/**
* Verifies that {@code rewardUrl} has a valid signature.
*
* <p>This method assumes that the name of the last two query parameters of {@code rewardUrl} are
* {@link #SIGNATURE_PARAM_NAME} and {@link #KEY_ID_PARAM_NAME} in that order.
*/
public void verify(String rewardUrl) throws GeneralSecurityException {
URI uri;
try {
uri = new URI(rewardUrl);
} catch (URISyntaxException ex) {
throw new GeneralSecurityException(ex);
}
String queryString = uri.getQuery();
int i = queryString.indexOf(SIGNATURE_PARAM_NAME);
if (i == -1) {
throw new GeneralSecurityException("needs a signature query parameter");
}
byte[] tbsData =
queryString
.substring(0, i - 1 /* i - 1 instead of i because of & */)
.getBytes(Charset.forName("UTF-8"));
String sigAndKeyId = queryString.substring(i);
i = sigAndKeyId.indexOf(KEY_ID_PARAM_NAME);
if (i == -1) {
throw new GeneralSecurityException("needs a key_id query parameter");
}
String sig =
sigAndKeyId.substring(
SIGNATURE_PARAM_NAME.length(), i - 1 /* i - 1 instead of i because of & */);
long keyId = Long.parseLong(sigAndKeyId.substring(i + KEY_ID_PARAM_NAME.length()));
verify(tbsData, keyId, Base64.urlSafeDecode(sig));
}
private void verify(final byte[] tbs, long keyId, final byte[] signature)
throws GeneralSecurityException {
boolean foundKeyId = false;
for (VerifyingPublicKeysProvider provider : verifyingPublicKeysProviders) {
Map<Long, ECPublicKey> publicKeys = provider.get();
if (publicKeys.containsKey(keyId)) {
foundKeyId = true;
ECPublicKey publicKey = publicKeys.get(keyId);
EcdsaVerifyJce verifier = new EcdsaVerifyJce(publicKey, HashType.SHA256, EcdsaEncoding.DER);
verifier.verify(signature, tbs);
}
}
if (!foundKeyId) {
throw new GeneralSecurityException("cannot find verifying key with key id: " + keyId);
}
}
/** Builder for RewardedAdsVerifier. */
public static class Builder {
private final List<VerifyingPublicKeysProvider> verifyingPublicKeysProviders =
new ArrayList<VerifyingPublicKeysProvider>();
public Builder() {}
/**
* Fetches verifying public keys of the sender using {@link KeysDownloader}.
*
* <p>This is the preferred method of specifying the verifying public keys.
*/
public Builder fetchVerifyingPublicKeysWith(final KeysDownloader downloader)
throws GeneralSecurityException {
this.verifyingPublicKeysProviders.add(
new VerifyingPublicKeysProvider() {
@Override
public Map<Long, ECPublicKey> get() throws GeneralSecurityException {
try {
return parsePublicKeysJson(downloader.download());
} catch (IOException e) {
throw new GeneralSecurityException("Failed to fetch keys!", e);
}
}
});
return this;
}
/**
* Sets the trusted verifying public keys of the sender.
*
* <p><b>IMPORTANT</b>: Instead of using this method to set the verifying public keys of the
* sender, prefer calling {@link #fetchVerifyingPublicKeysWith} passing it an instance of {@link
* KeysDownloader}. It will take care of fetching fresh keys and caching in memory. Only use
* this method if you can't use {@link #fetchVerifyingPublicKeysWith} and be aware you will need
* to handle key rotations yourself.
*
* <p>The given string is a JSON object formatted like the following:
*
* <pre>
* {
* "keys": [
* {
* keyId: 1916455855,
* pem: "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUaWMKcBHWdhUE+DncSIHhFCLLEln\nUs0LB9oanZ4K/FNICIM8ltS4nzc9yjmhgVQOlmSS6unqvN9t8sqajRTPcw==\n-----END PUBLIC KEY-----"
* base64: "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUaWMKcBHWdhUE+DncSIHhFCLLElnUs0LB9oanZ4K/FNICIM8ltS4nzc9yjmhgVQOlmSS6unqvN9t8sqajRTPcw=="
* },
* {
* keyId: 3901585526,
* pem: "-----BEGIN PUBLIC KEY-----\nMFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEtxg2BsK/fllIeADtLspezS6YfHFWXZ8tiJncm8LDBa/NxEC84akdWbWDCUrMMGIV27/3/e7UuKSEonjGvaDUsw==\n-----END PUBLIC KEY-----"
* base64: "MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEtxg2BsK/fllIeADtLspezS6YfHFWXZ8tiJncm8LDBa/NxEC84akdWbWDCUrMMGIV27/3/e7UuKSEonjGvaDUsw=="
* },
* ],
* }
* </pre>
*
* <p>Each public key will be a base64 (no wrapping, padded) version of the key encoded in ASN.1
* type SubjectPublicKeyInfo defined in the X.509 standard.
*/
public Builder setVerifyingPublicKeys(final String publicKeysJson)
throws GeneralSecurityException {
this.verifyingPublicKeysProviders.add(
new VerifyingPublicKeysProvider() {
@Override
public Map<Long, ECPublicKey> get() throws GeneralSecurityException {
return parsePublicKeysJson(publicKeysJson);
}
});
return this;
}
/**
* Adds a verifying public key of the sender.
*
* <p><b>IMPORTANT</b>: Instead of using this method to set the verifying public keys of the
* sender, prefer calling {@link #fetchVerifyingPublicKeysWith} passing it an instance of {@link
* KeysDownloader}. It will take care of fetching fresh keys and caching in memory. Only use
* this method if you can't use {@link #fetchVerifyingPublicKeysWith} and be aware you will need
* to handle Google key rotations yourself.
*
* <p>The public key is a base64 (no wrapping, padded) version of the key encoded in ASN.1 type
* SubjectPublicKeyInfo defined in the X.509 standard.
*
* <p>Multiple keys may be added. This utility will then verify any message signed with any of
* the private keys corresponding to the public keys added. Adding multiple keys is useful for
* handling key rotation.
*/
public Builder addVerifyingPublicKey(final long keyId, final String val)
throws GeneralSecurityException {
this.verifyingPublicKeysProviders.add(
new VerifyingPublicKeysProvider() {
@Override
public Map<Long, ECPublicKey> get() throws GeneralSecurityException {
return Collections.singletonMap(
keyId, EllipticCurves.getEcPublicKey(Base64.decode(val)));
}
});
return this;
}
/**
* Adds a verifying public key of the sender.
*
* <p><b>IMPORTANT</b>: Instead of using this method to set the verifying public keys of the
* sender, prefer calling {@link #fetchVerifyingPublicKeysWith} passing it an instance of {@link
* KeysDownloader}. It will take care of fetching fresh keys and caching in memory. Only use
* this method if you can't use {@link #fetchVerifyingPublicKeysWith} and be aware you will need
* to handle Google key rotations yourself.
*/
public Builder addVerifyingPublicKey(final long keyId, final ECPublicKey val)
throws GeneralSecurityException {
this.verifyingPublicKeysProviders.add(
new VerifyingPublicKeysProvider() {
@Override
public Map<Long, ECPublicKey> get() throws GeneralSecurityException {
return Collections.singletonMap(keyId, val);
}
});
return this;
}
public RewardedAdsVerifier build() throws GeneralSecurityException {
return new RewardedAdsVerifier(this);
}
}
private static Map<Long, ECPublicKey> parsePublicKeysJson(String publicKeysJson)
throws GeneralSecurityException {
Map<Long, ECPublicKey> publicKeys = new HashMap<>();
try {
JSONArray keys = new JSONObject(publicKeysJson).getJSONArray("keys");
for (int i = 0; i < keys.length(); i++) {
JSONObject key = keys.getJSONObject(i);
publicKeys.put(
key.getLong("keyId"),
EllipticCurves.getEcPublicKey(Base64.decode(key.getString("base64"))));
}
} catch (JSONException e) {
throw new GeneralSecurityException("failed to extract trusted signing public keys", e);
}
if (publicKeys.isEmpty()) {
throw new GeneralSecurityException("no trusted keys are available for this protocol version");
}
return publicKeys;
}
private interface VerifyingPublicKeysProvider {
Map<Long, ECPublicKey> get() throws GeneralSecurityException;
}
}
|
apps/rewardedads/src/main/java/com/google/crypto/tink/apps/rewardedads/RewardedAdsVerifier.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.crypto.tink.apps.rewardedads;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.crypto.tink.subtle.Base64;
import com.google.crypto.tink.subtle.EcdsaVerifyJce;
import com.google.crypto.tink.subtle.EllipticCurves;
import com.google.crypto.tink.subtle.EllipticCurves.EcdsaEncoding;
import com.google.crypto.tink.subtle.Enums.HashType;
import com.google.crypto.tink.util.KeysDownloader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.interfaces.ECPublicKey;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* An implementation of the verifier side of Server-Side Verification of Google AdMob Rewarded Ads.
*
* <p>Typical usage:
*
* <pre>{@code
* RewardedAdsVerifier verifier = new RewardedAdsVerifier.Builder()
* .fetchVerifyingPublicKeysWith(
* RewardedAdsVerifier.KEYS_DOWNLOADER_INSTANCE_PROD)
* .build();
* String rewardUrl = ...;
* verifier.verify(rewardUrl);
* }</pre>
*
* <p>This usage ensures that you always have the latest public keys, even when the keys were
* recently rotated. It will fetch and cache the latest public keys from {#PUBLIC_KEYS_URL_PROD}.
* When the cache expires, it will re-fetch the public keys. When initializing your server, we also
* recommend that you call {@link KeysDownloader#refreshInBackground()} of {@link
* RewardedAdsVerifier.KEYS_DOWNLOADER_INSTANCE_PROD} to proactively fetch the public keys.
*
* <p>If you've already downloaded the public keys and have other means to manage key rotation, you
* can use {@link RewardedAdsVerifier.Builder#setVerifyingPublicKeys} to set the public keys. The
* Builder also allows you to customize other properties.
*/
public final class RewardedAdsVerifier {
/** Default HTTP transport used by this class. */
private static final NetHttpTransport DEFAULT_HTTP_TRANSPORT =
new NetHttpTransport.Builder().build();
private static final Executor DEFAULT_BACKGROUND_EXECUTOR = Executors.newCachedThreadPool();
private final List<VerifyingPublicKeysProvider> verifyingPublicKeysProviders;
public static final String SIGNATURE_PARAM_NAME = "signature=";
public static final String KEY_ID_PARAM_NAME = "key_id=";
/** URL to fetch keys for environment production. */
public static final String PUBLIC_KEYS_URL_PROD =
"https://www.gstatic.com/admob/reward/verifier-keys.json";
/** URL to fetch keys for environment test. */
public static final String PUBLIC_KEYS_URL_TEST =
"https://www.gstatic.com/admob/reward/verifier-keys-test.json";
/**
* Instance configured to talk to fetch keys from production environment (from {@link
* KeysDownloader#PUBLIC_KEYS_URL_PROD}).
*/
public static final KeysDownloader KEYS_DOWNLOADER_INSTANCE_PROD =
new KeysDownloader(DEFAULT_BACKGROUND_EXECUTOR, DEFAULT_HTTP_TRANSPORT, PUBLIC_KEYS_URL_PROD);
/**
* Instance configured to talk to fetch keys from test environment (from {@link
* KeysDownloader#KEYS_URL_TEST}).
*/
public static final KeysDownloader KEYS_DOWNLOADER_INSTANCE_TEST =
new KeysDownloader(DEFAULT_BACKGROUND_EXECUTOR, DEFAULT_HTTP_TRANSPORT, PUBLIC_KEYS_URL_TEST);
RewardedAdsVerifier(List<VerifyingPublicKeysProvider> verifyingPublicKeysProviders)
throws GeneralSecurityException {
if (verifyingPublicKeysProviders == null || verifyingPublicKeysProviders.isEmpty()) {
throw new IllegalArgumentException(
"must set at least one way to get verifying key using"
+ " Builder.fetchVerifyingPublicKeysWith or Builder.setVerifyingPublicKeys");
}
this.verifyingPublicKeysProviders = verifyingPublicKeysProviders;
}
private RewardedAdsVerifier(Builder builder) throws GeneralSecurityException {
this(builder.verifyingPublicKeysProviders);
}
/**
* Verifies that {@code rewardUrl} has a valid signature.
*
* <p>This method assumes that the name of the last two query parameters of {@code rewardUrl} are
* {@link #SIGNATURE_PARAM_NAME} and {@link #KEY_ID_PARAM_NAME} in that order.
*/
public void verify(String rewardUrl) throws GeneralSecurityException {
URI uri;
try {
uri = new URI(rewardUrl);
} catch (URISyntaxException ex) {
throw new GeneralSecurityException(ex);
}
String queryString = uri.getQuery();
int i = queryString.indexOf(SIGNATURE_PARAM_NAME);
if (i == -1) {
throw new GeneralSecurityException("needs a signature query parameter");
}
byte[] tbsData =
queryString
.substring(0, i - 1 /* i - 1 instead of i because of & */)
.getBytes(Charset.forName("UTF-8"));
String sigAndKeyId = queryString.substring(i);
i = sigAndKeyId.indexOf(KEY_ID_PARAM_NAME);
if (i == -1) {
throw new GeneralSecurityException("needs a key_id query parameter");
}
String sig =
sigAndKeyId.substring(
SIGNATURE_PARAM_NAME.length(), i - 1 /* i - 1 instead of i because of & */);
long keyId = Long.parseLong(sigAndKeyId.substring(i + KEY_ID_PARAM_NAME.length()));
verify(tbsData, keyId, Base64.urlSafeDecode(sig));
}
private void verify(final byte[] tbs, long keyId, final byte[] signature)
throws GeneralSecurityException {
boolean foundKeyId = false;
for (VerifyingPublicKeysProvider provider : verifyingPublicKeysProviders) {
Map<Long, ECPublicKey> publicKeys = provider.get();
if (publicKeys.containsKey(keyId)) {
foundKeyId = true;
ECPublicKey publicKey = publicKeys.get(keyId);
EcdsaVerifyJce verifier = new EcdsaVerifyJce(publicKey, HashType.SHA256, EcdsaEncoding.DER);
verifier.verify(signature, tbs);
}
}
if (!foundKeyId) {
throw new GeneralSecurityException("cannot find verifying key with key id: " + keyId);
}
}
/** Builder for RewardedAdsVerifier. */
public static class Builder {
private final List<VerifyingPublicKeysProvider> verifyingPublicKeysProviders =
new ArrayList<VerifyingPublicKeysProvider>();
public Builder() {}
/**
* Fetches verifying public keys of the sender using {@link KeysDownloader}.
*
* <p>This is the preferred method of specifying the verifying public keys.
*/
public Builder fetchVerifyingPublicKeysWith(final KeysDownloader downloader)
throws GeneralSecurityException {
this.verifyingPublicKeysProviders.add(
new VerifyingPublicKeysProvider() {
@Override
public Map<Long, ECPublicKey> get() throws GeneralSecurityException {
try {
return parsePublicKeysJson(downloader.download());
} catch (IOException e) {
throw new GeneralSecurityException("Failed to fetch keys!", e);
}
}
});
return this;
}
/**
* Sets the trusted verifying public keys of the sender.
*
* <p><b>IMPORTANT</b>: Instead of using this method to set the verifying public keys of the
* sender, prefer calling {@link #fetchVerifyingPublicKeysWith} passing it an instance of {@link
* KeysDownloader}. It will take care of fetching fresh keys and caching in memory. Only use
* this method if you can't use {@link #fetchVerifyingPublicKeysWith} and be aware you will need
* to handle key rotations yourself.
*
* <p>The given string is a JSON object formatted like the following:
*
* <pre>
* {
* "keys": [
* {
* key_id: 1916455855,
* pem: "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUaWMKcBHWdhUE+DncSIHhFCLLEln\nUs0LB9oanZ4K/FNICIM8ltS4nzc9yjmhgVQOlmSS6unqvN9t8sqajRTPcw==\n-----END PUBLIC KEY-----"
* base64: "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUaWMKcBHWdhUE+DncSIHhFCLLElnUs0LB9oanZ4K/FNICIM8ltS4nzc9yjmhgVQOlmSS6unqvN9t8sqajRTPcw=="
* },
* {
* key_id: 3901585526,
* pem: "-----BEGIN PUBLIC KEY-----\nMFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEtxg2BsK/fllIeADtLspezS6YfHFWXZ8tiJncm8LDBa/NxEC84akdWbWDCUrMMGIV27/3/e7UuKSEonjGvaDUsw==\n-----END PUBLIC KEY-----"
* base64: "MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEtxg2BsK/fllIeADtLspezS6YfHFWXZ8tiJncm8LDBa/NxEC84akdWbWDCUrMMGIV27/3/e7UuKSEonjGvaDUsw=="
* },
* ],
* }
* </pre>
*
* <p>Each public key will be a base64 (no wrapping, padded) version of the key encoded in ASN.1
* type SubjectPublicKeyInfo defined in the X.509 standard.
*/
public Builder setVerifyingPublicKeys(final String publicKeysJson)
throws GeneralSecurityException {
this.verifyingPublicKeysProviders.add(
new VerifyingPublicKeysProvider() {
@Override
public Map<Long, ECPublicKey> get() throws GeneralSecurityException {
return parsePublicKeysJson(publicKeysJson);
}
});
return this;
}
/**
* Adds a verifying public key of the sender.
*
* <p><b>IMPORTANT</b>: Instead of using this method to set the verifying public keys of the
* sender, prefer calling {@link #fetchVerifyingPublicKeysWith} passing it an instance of {@link
* KeysDownloader}. It will take care of fetching fresh keys and caching in memory. Only use
* this method if you can't use {@link #fetchVerifyingPublicKeysWith} and be aware you will need
* to handle Google key rotations yourself.
*
* <p>The public key is a base64 (no wrapping, padded) version of the key encoded in ASN.1 type
* SubjectPublicKeyInfo defined in the X.509 standard.
*
* <p>Multiple keys may be added. This utility will then verify any message signed with any of
* the private keys corresponding to the public keys added. Adding multiple keys is useful for
* handling key rotation.
*/
public Builder addVerifyingPublicKey(final long keyId, final String val)
throws GeneralSecurityException {
this.verifyingPublicKeysProviders.add(
new VerifyingPublicKeysProvider() {
@Override
public Map<Long, ECPublicKey> get() throws GeneralSecurityException {
return Collections.singletonMap(
keyId, EllipticCurves.getEcPublicKey(Base64.decode(val)));
}
});
return this;
}
/**
* Adds a verifying public key of the sender.
*
* <p><b>IMPORTANT</b>: Instead of using this method to set the verifying public keys of the
* sender, prefer calling {@link #fetchVerifyingPublicKeysWith} passing it an instance of {@link
* KeysDownloader}. It will take care of fetching fresh keys and caching in memory. Only use
* this method if you can't use {@link #fetchVerifyingPublicKeysWith} and be aware you will need
* to handle Google key rotations yourself.
*/
public Builder addVerifyingPublicKey(final long keyId, final ECPublicKey val)
throws GeneralSecurityException {
this.verifyingPublicKeysProviders.add(
new VerifyingPublicKeysProvider() {
@Override
public Map<Long, ECPublicKey> get() throws GeneralSecurityException {
return Collections.singletonMap(keyId, val);
}
});
return this;
}
public RewardedAdsVerifier build() throws GeneralSecurityException {
return new RewardedAdsVerifier(this);
}
}
private static Map<Long, ECPublicKey> parsePublicKeysJson(String publicKeysJson)
throws GeneralSecurityException {
Map<Long, ECPublicKey> publicKeys = new HashMap<>();
try {
JSONArray keys = new JSONObject(publicKeysJson).getJSONArray("keys");
for (int i = 0; i < keys.length(); i++) {
JSONObject key = keys.getJSONObject(i);
publicKeys.put(
key.getLong("keyId"),
EllipticCurves.getEcPublicKey(Base64.decode(key.getString("base64"))));
}
} catch (JSONException e) {
throw new GeneralSecurityException("failed to extract trusted signing public keys", e);
}
if (publicKeys.isEmpty()) {
throw new GeneralSecurityException("no trusted keys are available for this protocol version");
}
return publicKeys;
}
private interface VerifyingPublicKeysProvider {
Map<Long, ECPublicKey> get() throws GeneralSecurityException;
}
}
|
Fix a typo.
PiperOrigin-RevId: 246600038
|
apps/rewardedads/src/main/java/com/google/crypto/tink/apps/rewardedads/RewardedAdsVerifier.java
|
Fix a typo.
|
|
Java
|
apache-2.0
|
4baec905b3eeb65b950bbe854596da23a466ac32
| 0
|
svn2github/hwmail-mirror,svn2github/hwmail-mirror,svn2github/hwmail-mirror,svn2github/hwmail-mirror
|
package com.hs.mail.smtp.processor.hook;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import com.hs.mail.smtp.message.MailAddress;
public class AccessTable {
private static final String OK = "OK";
private static final String REJECT = "REJECT";
/**
* The lists of rbl servers to be checked to limit spam
*/
private String[] whitelist;
private String[] blacklist;
AccessTable(File config) throws IOException {
readLines(config);
Arrays.sort(whitelist);
Arrays.sort(blacklist);
}
private void readLines(File config) throws IOException {
BufferedReader reader = null;
try {
InputStream in = new FileInputStream(config);
reader = new BufferedReader(new InputStreamReader(in));
List<String> whitelist = new ArrayList<String>();
List<String> blacklist = new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null) {
String str = line.trim();
if (StringUtils.isNotBlank(str)) {
char ch = line.charAt(0);
if (ch != '#') {
String[] tokens = StringUtils.split(line);
String address = tokens[0];
String action = (tokens.length < 2) ? REJECT : tokens[1];
if (OK.equalsIgnoreCase(action)) {
whitelist.add(address.toLowerCase());
} else if (REJECT.equalsIgnoreCase(action)) {
blacklist.add(address.toLowerCase());
}
}
}
}
this.whitelist = whitelist.toArray(new String[whitelist.size()]);
this.blacklist = blacklist.toArray(new String[blacklist.size()]);
} finally {
IOUtils.closeQuietly(reader);
}
}
public boolean isRestricted(MailAddress address) {
if (ArrayUtils.isNotEmpty(whitelist)) {
if (Arrays.binarySearch(whitelist,
StringUtils.lowerCase(address.getMailbox())) >= 0
|| Arrays.binarySearch(whitelist,
StringUtils.lowerCase(address.getHost())) >= 0
|| Arrays.binarySearch(whitelist,
StringUtils.lowerCase(address.getUser()) + "@") >= 0) {
return false;
}
}
if (ArrayUtils.isNotEmpty(blacklist)) {
if (Arrays.binarySearch(blacklist,
StringUtils.lowerCase(address.getMailbox())) >= 0
|| Arrays.binarySearch(blacklist,
StringUtils.lowerCase(address.getHost())) >= 0
|| Arrays.binarySearch(blacklist,
StringUtils.lowerCase(address.getUser()) + "@") >= 0) {
return true;
}
}
return false;
}
}
|
hedwig-server/src/main/java/com/hs/mail/smtp/processor/hook/AccessTable.java
|
package com.hs.mail.smtp.processor.hook;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import com.hs.mail.smtp.message.MailAddress;
public class AccessTable {
private static final String OK = "OK";
private static final String REJECT = "REJECT";
/**
* The lists of rbl servers to be checked to limit spam
*/
private String[] whitelist;
private String[] blacklist;
AccessTable(File config) throws IOException {
readLines(config);
Arrays.sort(whitelist);
Arrays.sort(blacklist);
}
private void readLines(File config) throws IOException {
BufferedReader reader = null;
try {
InputStream in = new FileInputStream(config);
reader = new BufferedReader(new InputStreamReader(in));
List<String> whitelist = new ArrayList<String>();
List<String> blacklist = new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null) {
String str = line.trim();
if (StringUtils.isNotBlank(str)) {
char ch = line.charAt(0);
if (ch != '#') {
String[] tokens = StringUtils.split(line);
String address = tokens[0];
String action = (tokens.length < 2) ? REJECT : tokens[1];
if (OK.equalsIgnoreCase(action)) {
whitelist.add(address);
} else if (REJECT.equalsIgnoreCase(action)) {
blacklist.add(address);
}
}
}
}
this.whitelist = whitelist.toArray(new String[whitelist.size()]);
this.blacklist = blacklist.toArray(new String[blacklist.size()]);
} finally {
IOUtils.closeQuietly(reader);
}
}
public boolean isRestricted(MailAddress address) {
if (ArrayUtils.isNotEmpty(whitelist)) {
if (Arrays.binarySearch(whitelist, address.getMailbox()) >= 0
|| Arrays.binarySearch(whitelist, address.getHost()) >= 0
|| Arrays.binarySearch(whitelist, address.getUser() + "@") >= 0) {
return false;
}
}
if (ArrayUtils.isNotEmpty(blacklist)) {
if (Arrays.binarySearch(blacklist, address.getMailbox()) >= 0
|| Arrays.binarySearch(blacklist, address.getHost()) >= 0
|| Arrays.binarySearch(blacklist, address.getUser() + "@") >= 0) {
return true;
}
}
return false;
}
}
|
git-svn-id: http://svn.code.sf.net/p/hwmail/code/trunk@137 aade673b-a3a6-47a5-a793-c3231508b26e
|
hedwig-server/src/main/java/com/hs/mail/smtp/processor/hook/AccessTable.java
| ||
Java
|
apache-2.0
|
90ff8768b59876490a2fef81ab8544a505a6354e
| 0
|
takahashikzn/indolently,takahashikzn/indolently
|
// Copyright 2014 takahashikzn
//
// 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 jp.root42.indolently;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import jp.root42.indolently.bridge.ObjFactory;
import jp.root42.indolently.ref.IntRef;
import static jp.root42.indolently.Indolently.*;
/**
* Extended {@link List} class for indolent person.
* The name is came from "Sugared List".
*
* @param <T> value type
* @author takahashikzn
*/
public interface SList<T>
extends List<T>, SCol<T, SList<T>>, Cloneable {
/**
* Clone this instance.
*
* @return clone of this instance
* @see Object#clone()
* @see Cloneable
*/
default SList<T> clone() {
return Indolently.list((Iterable<T>) this);
}
/**
* Wrap a list.
* This method is an alias of {@link Indolently#$(List)}.
*
* @param list list to wrap
* @return wrapped list
*/
public static <T> SList<T> of(final List<T> list) {
return Indolently.$(list);
}
/**
* {@inheritDoc}
*
* @see Indolently#freeze(List)
*/
@Override
default SList<T> freeze() {
return Indolently.freeze(this);
}
// for optimization
@Override
default T head() {
return this.get(0);
}
/**
* Return element at the position if exists.
* This method never throws {@link IndexOutOfBoundsException}.
*
* @param index index of the element
* @return the element if exists
*/
default Optional<T> opt(final int index) {
final int i = Indolently.idx(this, index);
return (0 <= i) && (i < this.size()) ? Indolently.opt(this.get(i)) : Optional.empty();
}
/**
* Equivalent to {@code list.subList(idx, list.size())}.
*
* @param from from index. negative index also acceptable.
* @return sub list
*/
default List<T> subList(final int from) {
return this.subList(Indolently.idx(this, from), this.size());
}
@Override
default SList<T> tail() {
return (this.size() <= 1) ? Indolently.list() : Indolently.list(this.subList(1));
}
// for optimization
@Override
default T last() {
return this.get(-1);
}
/**
* convert this list to {@link SSet}. original order is reserved.
*
* @return a set constructed from this instance.
*/
default SSet<T> set() {
return Indolently.$(ObjFactory.getInstance().<T> newFifoSet()).pushAll(this);
}
/**
* convert this list to sorted{@link SSet}.
*
* @param comp a {@link Comparator}
* @return a set constructed from this instance.
*/
default SSet<T> set(final Comparator<T> comp) {
return Indolently.$(ObjFactory.getInstance().<T> newSortedSet(comp)).pushAll(this);
}
/**
* insert value at given index then return this instance.
*
* @param idx insertion position.
* negative index also acceptable. for example, {@code slist.push(-1, "x")} means
* {@code slist.push(slist.size() - 1, "x")}
* @param value value to add
* @return {@code this} instance
*/
@Destructive
default SList<T> push(final int idx, final T value) {
this.add(Indolently.idx(this, idx), value);
return this;
}
/**
* insert all values at given index then return this instance.
*
* @param idx insertion position.
* negative index also acceptable. for example, {@code slist.pushAll(-1, list("x", "y"))} means
* {@code slist.pushAll(slist.size() - 1, list("x", "y"))}
* @param values values to add
* @return {@code this} instance
*/
@Destructive
default SList<T> pushAll(final int idx, final Iterable<? extends T> values) {
// optimization
final Collection<? extends T> vals =
(values instanceof Collection) ? (Collection<? extends T>) values : Indolently.list(values);
this.addAll(Indolently.idx(this, idx), vals);
return this;
}
/**
* insert value at given index then return this instance only if value exists.
* otherwise, do nothing.
*
* @param idx insertion position.
* negative index also acceptable. for example, {@code slist.push(-1, "x")} means
* {@code slist.push(slist.size() - 1, "x")}
* @param value nullable value to add
* @return {@code this} instance
*/
@Destructive
default SList<T> push(final int idx, final Optional<? extends T> value) {
return Indolently.empty(value) ? this : this.push(idx, value.get());
}
/**
* insert all values at given index then return this instance only if values exist.
* otherwise, do nothing.
*
* @param idx insertion position.
* negative index also acceptable. for example, {@code slist.pushAll(-1, list("x", "y"))} means
* {@code slist.pushAll(slist.size() - 1, list("x", "y"))}
* @param values nullable values to add
* @return {@code this} instance
*/
@Destructive
default SList<T> pushAll(final int idx, final Optional<? extends Iterable<? extends T>> values) {
return Indolently.empty(values) ? this : this.pushAll(idx, values.get());
}
/**
* Almost same as {@link #narrow(int)} but returns newly constructed (detached) view.
*
* @param from from index (inclusive)
* @return detached sub list
*/
default SList<T> slice(final int from) {
return this.narrow(from).clone();
}
/**
* Almost same as {@link #narrow(int, int)} but returns newly constructed (detached) view.
*
* @param from from index (inclusive)
* @param to to index (exclusive)
* @return detached sub list
*/
default SList<T> slice(final int from, final int to) {
return this.narrow(from, to).clone();
}
/**
* Almost same as {@link #subList(int, int)} but never throw {@link IllegalArgumentException} and
* {@link IndexOutOfBoundsException}.
*
* @param from from index (inclusive)
* @return the narrowed view of this list
*/
default SList<T> narrow(final int from) {
return this.narrow(from, this.size());
}
/**
* Almost same as {@link #subList(int, int)} but never throw {@link IllegalArgumentException} and
* {@link IndexOutOfBoundsException}.
*
* @param from from index (inclusive)
* @param to to index (exclusive)
* @return the narrowed view of this list
*/
default SList<T> narrow(final int from, final int to) {
int fromIndex = Indolently.idx(this, from);
if (fromIndex < 0) {
fromIndex = 0;
}
int toIndex = Indolently.idx(this, to);
if (((from < 0) && (toIndex == 0)) || (this.size() < toIndex)) {
toIndex = this.size();
}
if (toIndex < fromIndex) {
return Indolently.list();
}
return Indolently.$(this.subList(from, toIndex));
}
/**
* Map operation: map value to another type value.
*
* @param <R> mapped value type
* @param f function
* @return newly constructed list which contains converted values
*/
default <R> SList<R> map(final Function<? super T, ? extends R> f) {
return this.reduce(Indolently.list(), (x, y) -> x.push(f.apply(y)));
}
/**
* Map operation: map value to another type value.
*
* @param <R> mapped value type
* @param f function. first argument is element index, second one is element value
* @return newly constructed list which contains converted values
*/
default <R> SList<R> map(final BiFunction<Integer, ? super T, ? extends R> f) {
final IntRef i = ref(0);
return this.map(x -> f.apply(i.val++, x));
}
@Override
default SList<T> filter(final Predicate<? super T> f) {
return this.reduce(Indolently.list(), (x, y) -> f.test(y) ? x.push(y) : x);
}
/**
* Reverse this list.
*
* @return newly constructed reversed list
*/
default SList<T> reverse() {
final SList<T> rslt = this.clone();
Collections.reverse(rslt);
return rslt;
}
/**
* Flatten this list.
*
* @param f value generator
* @return newly constructed flatten list
*/
default <R> SList<R> flatten(final Function<? super T, ? extends Iterable<? extends R>> f) {
return Indolently.list(this.iterator().flatten(f));
}
/**
* Return this instance if not empty, otherwise return {@code other}.
*
* @param other alternative value
* @return this instance or other
*/
default SList<T> orElse(final List<? extends T> other) {
return this.orElseGet(() -> other);
}
/**
* Return this instance if not empty, otherwise return the invocation result of {@code other}.
*
* @param other alternative value supplier
* @return {@code this} instance or other
*/
default SList<T> orElseGet(final Supplier<? extends List<? extends T>> other) {
return Indolently.nonEmpty(this).orElseGet(() -> Indolently.list(other.get()));
}
@Override
default <K> SMap<K, SList<T>> group(final Function<? super T, ? extends K> fkey) {
return this.reduce(Indolently.$(ObjFactory.getInstance().newFifoMap()), (x, y) -> {
final K key = fkey.apply(y);
if (!x.containsKey(key)) {
x.put(key, Indolently.list());
}
x.get(key).add(y);
return x;
});
}
@Override
default SList<T> sortWith(final Comparator<? super T> comp) {
return Indolently.sort(this, comp);
}
@SuppressWarnings("javadoc")
default SList<T> uniq() {
return Indolently.uniq(this);
}
@SuppressWarnings("javadoc")
default SList<T> uniq(final BiPredicate<? super T, ? super T> f) {
return Indolently.uniq(this, f);
}
/**
* Replace value at the position if exists.
*
* @param idx index of the element
* @param f function
* @param val replacement value
* @return {@code this} instance
*/
@Destructive
default SList<T> update(final int idx, final T val) {
return this.update(idx, x -> val);
}
/**
* Replace value at the position if exists.
*
* @param idx index of the element
* @param f function
* @return {@code this} instance
*/
@Destructive
default SList<T> update(final int idx, final Function<? super T, ? extends T> f) {
this.opt(idx).ifPresent(x -> this.set(Indolently.idx(this, idx), f.apply(x)));
return this;
}
/**
* Replace value at the position if exists.
*
* @param f function
* @return {@code this} instance
*/
@Destructive
default SList<T> update(final Function<? super T, ? extends T> f) {
for (int i = 0; i < this.size(); i++) {
this.update(i, f);
}
return this;
}
/**
* Replace value at the position if exists.
*
* @param idx index of the element
* @param f function
* @return newly constructed list
*/
default SList<T> map(final int idx, final Function<? super T, ? extends T> f) {
return this.clone().update(idx, f);
}
/**
* Test this list starts with given elements or not.
*
* @param col elements
* @return {@code true} when this list starts with given elements
*/
default boolean startsWith(final Collection<T> col) {
return (col != null) && this.narrow(0, col.size()).equals(col);
}
/**
* Test this list ends with given elements or not.
*
* @param col elements
* @return {@code true} when this list ends with given elements
*/
default boolean endsWith(final Collection<T> col) {
return (col != null) && this.narrow(-col.size(), 0).equals(col);
}
/**
* Find first index of the element which satisfies given predication.
*
* @param f predication
* @return found index
*/
default OptionalInt indexOf(final Predicate<T> f) {
return this.head(f).map(this::indexOf).map(OptionalInt::of).orElseGet(OptionalInt::empty);
}
/**
* Find last index of the element which satisfies given predication.
*
* @param f predication
* @return found index
*/
default OptionalInt lastIndexOf(final Predicate<T> f) {
return this.last(f).map(this::lastIndexOf).map(OptionalInt::of).orElseGet(OptionalInt::empty);
}
}
|
src/main/java/jp/root42/indolently/SList.java
|
// Copyright 2014 takahashikzn
//
// 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 jp.root42.indolently;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import jp.root42.indolently.bridge.ObjFactory;
import jp.root42.indolently.ref.IntRef;
import static jp.root42.indolently.Indolently.*;
/**
* Extended {@link List} class for indolent person.
* The name is came from "Sugared List".
*
* @param <T> value type
* @author takahashikzn
*/
public interface SList<T>
extends List<T>, SCol<T, SList<T>>, Cloneable {
/**
* Clone this instance.
*
* @return clone of this instance
* @see Object#clone()
* @see Cloneable
*/
default SList<T> clone() {
return Indolently.list((Iterable<T>) this);
}
/**
* Wrap a list.
* This method is an alias of {@link Indolently#$(List)}.
*
* @param list list to wrap
* @return wrapped list
*/
public static <T> SList<T> of(final List<T> list) {
return Indolently.$(list);
}
/**
* {@inheritDoc}
*
* @see Indolently#freeze(List)
*/
@Override
default SList<T> freeze() {
return Indolently.freeze(this);
}
// for optimization
@Override
default T head() {
return this.get(0);
}
/**
* Return element at the position if exists.
* This method never throws {@link IndexOutOfBoundsException}.
*
* @param index index of the element
* @return the element if exists
*/
default Optional<T> opt(final int index) {
final int i = Indolently.idx(this, index);
return (0 <= i) && (i < this.size()) ? Indolently.opt(this.get(i)) : Optional.empty();
}
/**
* Equivalent to {@code list.subList(idx, list.size())}.
*
* @param from from index. negative index also acceptable.
* @return sub list
*/
default List<T> subList(final int from) {
return this.subList(Indolently.idx(this, from), this.size());
}
@Override
default SList<T> tail() {
return (this.size() <= 1) ? Indolently.list() : Indolently.list(this.subList(1));
}
// for optimization
@Override
default T last() {
return this.get(-1);
}
/**
* convert this list to {@link SSet}. original order is reserved.
*
* @return a set constructed from this instance.
*/
default SSet<T> set() {
return Indolently.$(ObjFactory.getInstance().<T> newFifoSet()).pushAll(this);
}
/**
* convert this list to sorted{@link SSet}.
*
* @param comp a {@link Comparator}
* @return a set constructed from this instance.
*/
default SSet<T> set(final Comparator<T> comp) {
return Indolently.$(ObjFactory.getInstance().<T> newSortedSet(comp)).pushAll(this);
}
/**
* insert value at specified index then return this instance.
*
* @param idx insertion position.
* negative index also acceptable. for example, {@code slist.push(-1, "x")} means
* {@code slist.push(slist.size() - 1, "x")}
* @param value value to add
* @return {@code this} instance
*/
@Destructive
default SList<T> push(final int idx, final T value) {
this.add(Indolently.idx(this, idx), value);
return this;
}
/**
* insert all values at specified index then return this instance.
*
* @param idx insertion position.
* negative index also acceptable. for example, {@code slist.pushAll(-1, list("x", "y"))} means
* {@code slist.pushAll(slist.size() - 1, list("x", "y"))}
* @param values values to add
* @return {@code this} instance
*/
@Destructive
default SList<T> pushAll(final int idx, final Iterable<? extends T> values) {
// optimization
final Collection<? extends T> vals =
(values instanceof Collection) ? (Collection<? extends T>) values : Indolently.list(values);
this.addAll(Indolently.idx(this, idx), vals);
return this;
}
/**
* insert value at specified index then return this instance only if value exists.
* otherwise, do nothing.
*
* @param idx insertion position.
* negative index also acceptable. for example, {@code slist.push(-1, "x")} means
* {@code slist.push(slist.size() - 1, "x")}
* @param value nullable value to add
* @return {@code this} instance
*/
@Destructive
default SList<T> push(final int idx, final Optional<? extends T> value) {
return Indolently.empty(value) ? this : this.push(idx, value.get());
}
/**
* insert all values at specified index then return this instance only if values exist.
* otherwise, do nothing.
*
* @param idx insertion position.
* negative index also acceptable. for example, {@code slist.pushAll(-1, list("x", "y"))} means
* {@code slist.pushAll(slist.size() - 1, list("x", "y"))}
* @param values nullable values to add
* @return {@code this} instance
*/
@Destructive
default SList<T> pushAll(final int idx, final Optional<? extends Iterable<? extends T>> values) {
return Indolently.empty(values) ? this : this.pushAll(idx, values.get());
}
/**
* Almost same as {@link #narrow(int)} but returns newly constructed (detached) view.
*
* @param from from index (inclusive)
* @return detached sub list
*/
default SList<T> slice(final int from) {
return this.narrow(from).clone();
}
/**
* Almost same as {@link #narrow(int, int)} but returns newly constructed (detached) view.
*
* @param from from index (inclusive)
* @param to to index (exclusive)
* @return detached sub list
*/
default SList<T> slice(final int from, final int to) {
return this.narrow(from, to).clone();
}
/**
* Almost same as {@link #subList(int, int)} but never throw {@link IllegalArgumentException} and
* {@link IndexOutOfBoundsException}.
*
* @param from from index (inclusive)
* @return the narrowed view of this list
*/
default SList<T> narrow(final int from) {
return this.narrow(from, this.size());
}
/**
* Almost same as {@link #subList(int, int)} but never throw {@link IllegalArgumentException} and
* {@link IndexOutOfBoundsException}.
*
* @param from from index (inclusive)
* @param to to index (exclusive)
* @return the narrowed view of this list
*/
default SList<T> narrow(final int from, final int to) {
int fromIndex = Indolently.idx(this, from);
if (fromIndex < 0) {
fromIndex = 0;
}
int toIndex = Indolently.idx(this, to);
if (((from < 0) && (toIndex == 0)) || (this.size() < toIndex)) {
toIndex = this.size();
}
if (toIndex < fromIndex) {
return Indolently.list();
}
return Indolently.$(this.subList(from, toIndex));
}
/**
* Map operation: map value to another type value.
*
* @param <R> mapped value type
* @param f function
* @return newly constructed list which contains converted values
*/
default <R> SList<R> map(final Function<? super T, ? extends R> f) {
return this.reduce(Indolently.list(), (x, y) -> x.push(f.apply(y)));
}
/**
* Map operation: map value to another type value.
*
* @param <R> mapped value type
* @param f function. first argument is element index, second one is element value
* @return newly constructed list which contains converted values
*/
default <R> SList<R> map(final BiFunction<Integer, ? super T, ? extends R> f) {
final IntRef i = ref(0);
return this.map(x -> f.apply(i.val++, x));
}
@Override
default SList<T> filter(final Predicate<? super T> f) {
return this.reduce(Indolently.list(), (x, y) -> f.test(y) ? x.push(y) : x);
}
/**
* Reverse this list.
*
* @return newly constructed reversed list
*/
default SList<T> reverse() {
final SList<T> rslt = this.clone();
Collections.reverse(rslt);
return rslt;
}
/**
* Flatten this list.
*
* @param f value generator
* @return newly constructed flatten list
*/
default <R> SList<R> flatten(final Function<? super T, ? extends Iterable<? extends R>> f) {
return Indolently.list(this.iterator().flatten(f));
}
/**
* Return this instance if not empty, otherwise return {@code other}.
*
* @param other alternative value
* @return this instance or other
*/
default SList<T> orElse(final List<? extends T> other) {
return this.orElseGet(() -> other);
}
/**
* Return this instance if not empty, otherwise return the invocation result of {@code other}.
*
* @param other alternative value supplier
* @return {@code this} instance or other
*/
default SList<T> orElseGet(final Supplier<? extends List<? extends T>> other) {
return Indolently.nonEmpty(this).orElseGet(() -> Indolently.list(other.get()));
}
@Override
default <K> SMap<K, SList<T>> group(final Function<? super T, ? extends K> fkey) {
return this.reduce(Indolently.$(ObjFactory.getInstance().newFifoMap()), (x, y) -> {
final K key = fkey.apply(y);
if (!x.containsKey(key)) {
x.put(key, Indolently.list());
}
x.get(key).add(y);
return x;
});
}
@Override
default SList<T> sortWith(final Comparator<? super T> comp) {
return Indolently.sort(this, comp);
}
@SuppressWarnings("javadoc")
default SList<T> uniq() {
return Indolently.uniq(this);
}
@SuppressWarnings("javadoc")
default SList<T> uniq(final BiPredicate<? super T, ? super T> f) {
return Indolently.uniq(this, f);
}
/**
* Replace value at the position if exists.
*
* @param idx index of the element
* @param f function
* @param val replacement value
* @return {@code this} instance
*/
@Destructive
default SList<T> update(final int idx, final T val) {
return this.update(idx, x -> val);
}
/**
* Replace value at the position if exists.
*
* @param idx index of the element
* @param f function
* @return {@code this} instance
*/
@Destructive
default SList<T> update(final int idx, final Function<? super T, ? extends T> f) {
this.opt(idx).ifPresent(x -> this.set(Indolently.idx(this, idx), f.apply(x)));
return this;
}
/**
* Replace value at the position if exists.
*
* @param f function
* @return {@code this} instance
*/
@Destructive
default SList<T> update(final Function<? super T, ? extends T> f) {
for (int i = 0; i < this.size(); i++) {
this.update(i, f);
}
return this;
}
/**
* Replace value at the position if exists.
*
* @param idx index of the element
* @param f function
* @return newly constructed list
*/
default SList<T> map(final int idx, final Function<? super T, ? extends T> f) {
return this.clone().update(idx, f);
}
/**
* Test this list starts with specified elements or not.
*
* @param col elements
* @return {@code true} when this list starts with specified elements
*/
default boolean startsWith(final Collection<T> col) {
return (col != null) && this.narrow(0, col.size()).equals(col);
}
/**
* Test this list ends with specified elements or not.
*
* @param col elements
* @return {@code true} when this list ends with specified elements
*/
default boolean endsWith(final Collection<T> col) {
return (col != null) && this.narrow(-col.size(), 0).equals(col);
}
/**
* Find first index of the element which satisfies given predication.
*
* @param f predication
* @return found index
*/
default OptionalInt indexOf(final Predicate<T> f) {
return this.head(f).map(x -> OptionalInt.of(this.indexOf(x))).orElseGet(OptionalInt::empty);
}
/**
* Find last index of the element which satisfies given predication.
*
* @param f predication
* @return found index
*/
default OptionalInt lastIndexOf(final Predicate<T> f) {
return this.last(f).map(x -> OptionalInt.of(this.lastIndexOf(x))).orElseGet(OptionalInt::empty);
}
}
|
refactoring
|
src/main/java/jp/root42/indolently/SList.java
|
refactoring
|
|
Java
|
apache-2.0
|
151fdea9174147bef02ac402b6e04095a007405f
| 0
|
azuki-framework/azuki-base
|
/**
* 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.azkfw.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* このクラスは、ファイル操作をまとめたユーティリティクラスです。
*
* @since 1.0.0
* @version 1.0.0 2013/06/26
* @author Kawakicchi
*/
public final class FileUtility {
public enum SortMode {
// 列挙子の定義は、コンストラクターに合わせた引数を持たせる。
String(0), Integer(1);
private int value;
private SortMode(int n) {
this.value = n;
}
public int getValue() {
return this.value;
}
}
/**
* コンストラクタ
* <p>
* インスタンス生成を禁止する。
* </p>
*/
private FileUtility() {
}
/**
* 拡張子を除いたファイル名を取得する。
*
* @param aFile ファイル
* @return ファイル名
*/
public static String getFileName(final File aFile) {
String name = aFile.getName();
int index = name.lastIndexOf(".");
if (-1 != index) {
return name.substring(0, index);
} else {
return name;
}
}
/**
* ファイルをコピーする。
* <p>
* コピー処理には
* {@link FileChannel#transferTo(long, long, java.nio.channels.WritableByteChannel)}
* メソッドを利用します。
* </p>
*
* @param aSrcPath コピー元のパス
* @param aDestPath コピー先のパス
* @throws IOException 何らかの入出力処理例外が発生した場合
*/
public static void copy(final String aSrcPath, final String aDestPath) throws IOException {
copy(new File(aSrcPath), new File(aDestPath));
}
/**
* ファイルをコピーする。
* <p>
* コピー処理には
* {@link FileChannel#transferTo(long, long, java.nio.channels.WritableByteChannel)}
* メソッドを利用します。
* </p>
*
* @param aSrcFile コピー元のファイル
* @param aDestFile コピー先のファイル
* @throws IOException 何らかの入出力処理例外が発生した場合
*/
public static void copy(final File aSrcFile, final File aDestFile) throws IOException {
if (aSrcFile.isDirectory()) {
aDestFile.mkdirs();
File[] files = aSrcFile.listFiles();
for (File file : files) {
String srcFile = aSrcFile.getAbsolutePath() + "\\" + file.getName();
String destFile = aDestFile.getAbsolutePath() + "\\" + file.getName();
copy(new File(srcFile), new File(destFile));
}
} else if (aSrcFile.isFile()) {
FileChannel srcChannel = null;
FileChannel destChannel = null;
try {
srcChannel = new FileInputStream(aSrcFile).getChannel();
destChannel = new FileOutputStream(aDestFile).getChannel();
srcChannel.transferTo(0, srcChannel.size(), destChannel);
} finally {
if (null != srcChannel) {
srcChannel.close();
}
if (null != destChannel) {
destChannel.close();
}
}
}
}
/**
* ファイル/ディレクトリを削除する。
* <p>
* このメソッドは、対象配下を再帰的に削除します。
* </p>
*
* @param aRoot 削除対象
*/
public static void remove(final String aRoot) {
remove(new File(aRoot));
}
/**
* ファイル/ディレクトリを削除する。
* <p>
* このメソッドは、対象配下を再帰的に削除します。
* </p>
*
* @param aRoot 削除対象
*/
public static void remove(final File aRoot) {
if (aRoot == null || !aRoot.exists()) {
return;
}
if (aRoot.isFile()) {
if (aRoot.exists() && !aRoot.delete()) {
aRoot.deleteOnExit();
}
} else {
File[] list = aRoot.listFiles();
for (int i = 0; i < list.length; i++) {
remove(list[i]);
}
if (aRoot.exists() && !aRoot.delete()) {
aRoot.deleteOnExit();
}
}
}
/**
* ファイルリストをファイルパスがパターンで同一のものでグルーピングする。
* <p>
* <ul>
* <li>同一ディレクトリ - "^(.*)[0-9]{3}\.csv$"</li>
* </ul>
* </p>
*
* @param aFiles ファイル一覧
* @param aPattern パターン
* @return
*/
public static final Map<String, List<File>> groupFiles(final List<File> aFiles, final Pattern aPattern) {
Map<String, List<File>> groups = new HashMap<String, List<File>>();
for (File file : aFiles) {
String path = file.getAbsolutePath();
String key = extractMatchString(path, aPattern);
List<File> fs = null;
if (groups.containsKey(key)) {
fs = groups.get(key);
} else {
fs = new ArrayList<File>();
groups.put(key, fs);
}
fs.add(file);
}
return groups;
}
/**
* ファイルリストをファイルパスがパターンでソートする。
* <p>
* <ul>
* <li>"^.*([0-9]{3})\.csv$"</li>
* </ul>
* </p>
*
* @param aFiles
* @param aPattern
*/
public static final void sortFiles(final List<File> aFiles, final Pattern aPattern) {
sortFiles(aFiles, aPattern, SortMode.String);
}
/**
* ファイルリストをファイルパスがパターンでソートする。
* <p>
* <ul>
* <li>"^.*([0-9]{3})\.csv$"</li>
* </ul>
* </p>
*
* @param aFiles
* @param aPattern
*/
public static final void sortFiles(final List<File> aFiles, final Pattern aPattern, final SortMode aMode) {
switch (aMode) {
case Integer:
Collections.sort(aFiles, new Comparator<File>() {
public int compare(File obj1, File obj2) {
String val1 = extractMatchString(obj1.getAbsolutePath(), aPattern);
String val2 = extractMatchString(obj2.getAbsolutePath(), aPattern);
int int1 = Integer.parseInt(val1);
int int2 = Integer.parseInt(val2);
return int1 - int2;
}
});
break;
default:
Collections.sort(aFiles, new Comparator<File>() {
public int compare(File obj1, File obj2) {
String val1 = extractMatchString(obj1.getAbsolutePath(), aPattern);
String val2 = extractMatchString(obj2.getAbsolutePath(), aPattern);
return val1.compareTo(val2);
}
});
break;
}
}
private static String extractMatchString(final String aTarget, final Pattern aPattern) {
Matcher matcher = aPattern.matcher(aTarget);
if (matcher.find()) {
return matcher.group(1);
} else {
throw new IllegalStateException("No match found.");
}
}
/**
* 指定されたディレクトリ配下のファイルを再帰的に全て取得する。
*
* @param aDirectory ディレクトリ
* @return ファイル群
*/
public static final List<File> listFiles(final String aDirectory) {
return listFiles(aDirectory, (Pattern) null);
}
/**
* 指定されたディレクトリ配下のファイルを再帰的に全て取得する。
*
* @param aDirectory ディレクトリ
* @return ファイル群
*/
public static final List<File> listFiles(final File aDirectory) {
return listFiles(aDirectory, (Pattern) null);
}
/**
* 指定されたディレクトリ配下のファイルを再帰的にファイルパスがパターンにマッチするもののみ取得する。
* <p>
* パターン例
* <ul>
* <li>CSVファイル - "^.*\.(csv|CSV)$"</li>
* <li>CSVファイルで末3ケタが数値のファイル - "^.*[0-9]{3}\.csv$"</li>
* </ul>
* </p>
*
* @param aDirectory ディレクトリ
* @param aPattern パターン
* @return ファイル群
*/
public static final List<File> listFiles(final String aDirectory, final String aPattern) {
return listFiles(aDirectory, Pattern.compile(aPattern));
}
/**
* 指定されたディレクトリ配下のファイルを再帰的にファイルパスがパターンにマッチするもののみ取得する。
* <p>
* パターン例
* <ul>
* <li>CSVファイル - "^.*\.(csv|CSV)$"</li>
* <li>CSVファイルで末3ケタが数値のファイル - "^.*[0-9]{3}\.csv$"</li>
* </ul>
* </p>
*
* @param aDirectory ディレクトリ
* @param aPattern パターン
* @return ファイル群
*/
public static final List<File> listFiles(final File aDirectory, final String aPattern) {
return listFiles(aDirectory, Pattern.compile(aPattern));
}
/**
* 指定されたディレクトリ配下のファイルを再帰的にファイルパスがパターンにマッチするもののみ取得する。
* <p>
* パターン例
* <ul>
* <li>CSVファイル - "^.*\.(csv|CSV)$"</li>
* </ul>
* </p>
*
* @param aDirectory ディレクトリ
* @param aPattern パターン
* @return ファイル群
*/
public static final List<File> listFiles(final String aDirectory, final Pattern aPattern) {
return listFiles(new File(aDirectory), aPattern);
}
/**
* 指定されたディレクトリ配下のファイルを再帰的にファイルパスがパターンにマッチするもののみ取得する。
* <p>
* パターン例
* <ul>
* <li>CSVファイル - "^.*\.(csv|CSV)$"</li>
* </ul>
* </p>
*
* @param aDirectory ディレクトリ
* @param aPattern パターン
* @return ファイル群
*/
public static final List<File> listFiles(final File aDirectory, final Pattern aPattern) {
List<File> files = new ArrayList<File>();
readDir(aDirectory, aPattern, files);
return files;
}
private static void readDir(final File aDir, final Pattern aPattern, final List<File> aFiles) {
File[] files = aDir.listFiles();
if (files == null) {
return;
}
for (File file : files) {
if (!file.exists()) {
continue;
} else if (file.isDirectory()) {
readDir(file, aPattern, aFiles);
} else if (file.isFile())
readFile(file, aPattern, aFiles);
}
}
private static void readFile(final File aFile, final Pattern aPattern, final List<File> aFiles) {
String path = aFile.getAbsolutePath();
if (null == aPattern || aPattern.matcher(path).matches()) {
aFiles.add(aFile);
}
}
}
|
src/main/java/org/azkfw/util/FileUtility.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.azkfw.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* このクラスは、ファイル操作をまとめたユーティリティクラスです。
*
* @since 1.0.0
* @version 1.0.0 2013/06/26
* @author Kawakicchi
*/
public final class FileUtility {
public enum SortMode {
// 列挙子の定義は、コンストラクターに合わせた引数を持たせる。
String(0), Integer(1);
private int value;
private SortMode(int n) {
this.value = n;
}
public int getValue() {
return this.value;
}
}
/**
* コンストラクタ
* <p>
* インスタンス生成を禁止する。
* </p>
*/
private FileUtility() {
}
/**
* ファイルをコピーする。
* <p>
* コピー処理には
* {@link FileChannel#transferTo(long, long, java.nio.channels.WritableByteChannel)}
* メソッドを利用します。
* </p>
*
* @param aSrcPath コピー元のパス
* @param aDestPath コピー先のパス
* @throws IOException 何らかの入出力処理例外が発生した場合
*/
public static void copy(final String aSrcPath, final String aDestPath) throws IOException {
copy(new File(aSrcPath), new File(aDestPath));
}
/**
* ファイルをコピーする。
* <p>
* コピー処理には
* {@link FileChannel#transferTo(long, long, java.nio.channels.WritableByteChannel)}
* メソッドを利用します。
* </p>
*
* @param aSrcFile コピー元のファイル
* @param aDestFile コピー先のファイル
* @throws IOException 何らかの入出力処理例外が発生した場合
*/
public static void copy(final File aSrcFile, final File aDestFile) throws IOException {
if (aSrcFile.isDirectory()) {
aDestFile.mkdirs();
File[] files = aSrcFile.listFiles();
for (File file : files) {
String srcFile = aSrcFile.getAbsolutePath() + "\\" + file.getName();
String destFile = aDestFile.getAbsolutePath() + "\\" + file.getName();
copy(new File(srcFile), new File(destFile));
}
} else if (aSrcFile.isFile()) {
FileChannel srcChannel = null;
FileChannel destChannel = null;
try {
srcChannel = new FileInputStream(aSrcFile).getChannel();
destChannel = new FileOutputStream(aDestFile).getChannel();
srcChannel.transferTo(0, srcChannel.size(), destChannel);
} finally {
if (null != srcChannel) {
srcChannel.close();
}
if (null != destChannel) {
destChannel.close();
}
}
}
}
/**
* ファイル/ディレクトリを削除する。
* <p>
* このメソッドは、対象配下を再帰的に削除します。
* </p>
*
* @param aRoot 削除対象
*/
public static void remove(final String aRoot) {
remove(new File(aRoot));
}
/**
* ファイル/ディレクトリを削除する。
* <p>
* このメソッドは、対象配下を再帰的に削除します。
* </p>
*
* @param aRoot 削除対象
*/
public static void remove(final File aRoot) {
if (aRoot == null || !aRoot.exists()) {
return;
}
if (aRoot.isFile()) {
if (aRoot.exists() && !aRoot.delete()) {
aRoot.deleteOnExit();
}
} else {
File[] list = aRoot.listFiles();
for (int i = 0; i < list.length; i++) {
remove(list[i]);
}
if (aRoot.exists() && !aRoot.delete()) {
aRoot.deleteOnExit();
}
}
}
/**
* ファイルリストをファイルパスがパターンで同一のものでグルーピングする。
* <p>
* <ul>
* <li>同一ディレクトリ - "^(.*)[0-9]{3}\.csv$"</li>
* </ul>
* </p>
*
* @param aFiles ファイル一覧
* @param aPattern パターン
* @return
*/
public static final Map<String, List<File>> groupFiles(final List<File> aFiles, final Pattern aPattern) {
Map<String, List<File>> groups = new HashMap<String, List<File>>();
for (File file : aFiles) {
String path = file.getAbsolutePath();
String key = extractMatchString(path, aPattern);
List<File> fs = null;
if (groups.containsKey(key)) {
fs = groups.get(key);
} else {
fs = new ArrayList<File>();
groups.put(key, fs);
}
fs.add(file);
}
return groups;
}
/**
* ファイルリストをファイルパスがパターンでソートする。
* <p>
* <ul>
* <li>"^.*([0-9]{3})\.csv$"</li>
* </ul>
* </p>
*
* @param aFiles
* @param aPattern
*/
public static final void sortFiles(final List<File> aFiles, final Pattern aPattern) {
sortFiles(aFiles, aPattern, SortMode.String);
}
/**
* ファイルリストをファイルパスがパターンでソートする。
* <p>
* <ul>
* <li>"^.*([0-9]{3})\.csv$"</li>
* </ul>
* </p>
*
* @param aFiles
* @param aPattern
*/
public static final void sortFiles(final List<File> aFiles, final Pattern aPattern, final SortMode aMode) {
switch (aMode) {
case Integer:
Collections.sort(aFiles, new Comparator<File>() {
public int compare(File obj1, File obj2) {
String val1 = extractMatchString(obj1.getAbsolutePath(), aPattern);
String val2 = extractMatchString(obj2.getAbsolutePath(), aPattern);
int int1 = Integer.parseInt(val1);
int int2 = Integer.parseInt(val2);
return int1 - int2;
}
});
break;
default:
Collections.sort(aFiles, new Comparator<File>() {
public int compare(File obj1, File obj2) {
String val1 = extractMatchString(obj1.getAbsolutePath(), aPattern);
String val2 = extractMatchString(obj2.getAbsolutePath(), aPattern);
return val1.compareTo(val2);
}
});
break;
}
}
private static String extractMatchString(final String aTarget, final Pattern aPattern) {
Matcher matcher = aPattern.matcher(aTarget);
if (matcher.find()) {
return matcher.group(1);
} else {
throw new IllegalStateException("No match found.");
}
}
/**
* 指定されたディレクトリ配下のファイルを再帰的に全て取得する。
*
* @param aDirectory ディレクトリ
* @return ファイル群
*/
public static final List<File> listFiles(final String aDirectory) {
return listFiles(aDirectory, (Pattern) null);
}
/**
* 指定されたディレクトリ配下のファイルを再帰的に全て取得する。
*
* @param aDirectory ディレクトリ
* @return ファイル群
*/
public static final List<File> listFiles(final File aDirectory) {
return listFiles(aDirectory, (Pattern) null);
}
/**
* 指定されたディレクトリ配下のファイルを再帰的にファイルパスがパターンにマッチするもののみ取得する。
* <p>
* パターン例
* <ul>
* <li>CSVファイル - "^.*\.(csv|CSV)$"</li>
* <li>CSVファイルで末3ケタが数値のファイル - "^.*[0-9]{3}\.csv$"</li>
* </ul>
* </p>
*
* @param aDirectory ディレクトリ
* @param aPattern パターン
* @return ファイル群
*/
public static final List<File> listFiles(final String aDirectory, final String aPattern) {
return listFiles(aDirectory, Pattern.compile(aPattern));
}
/**
* 指定されたディレクトリ配下のファイルを再帰的にファイルパスがパターンにマッチするもののみ取得する。
* <p>
* パターン例
* <ul>
* <li>CSVファイル - "^.*\.(csv|CSV)$"</li>
* <li>CSVファイルで末3ケタが数値のファイル - "^.*[0-9]{3}\.csv$"</li>
* </ul>
* </p>
*
* @param aDirectory ディレクトリ
* @param aPattern パターン
* @return ファイル群
*/
public static final List<File> listFiles(final File aDirectory, final String aPattern) {
return listFiles(aDirectory, Pattern.compile(aPattern));
}
/**
* 指定されたディレクトリ配下のファイルを再帰的にファイルパスがパターンにマッチするもののみ取得する。
* <p>
* パターン例
* <ul>
* <li>CSVファイル - "^.*\.(csv|CSV)$"</li>
* </ul>
* </p>
*
* @param aDirectory ディレクトリ
* @param aPattern パターン
* @return ファイル群
*/
public static final List<File> listFiles(final String aDirectory, final Pattern aPattern) {
return listFiles(new File(aDirectory), aPattern);
}
/**
* 指定されたディレクトリ配下のファイルを再帰的にファイルパスがパターンにマッチするもののみ取得する。
* <p>
* パターン例
* <ul>
* <li>CSVファイル - "^.*\.(csv|CSV)$"</li>
* </ul>
* </p>
*
* @param aDirectory ディレクトリ
* @param aPattern パターン
* @return ファイル群
*/
public static final List<File> listFiles(final File aDirectory, final Pattern aPattern) {
List<File> files = new ArrayList<File>();
readDir(aDirectory, aPattern, files);
return files;
}
private static void readDir(final File aDir, final Pattern aPattern, final List<File> aFiles) {
File[] files = aDir.listFiles();
if (files == null) {
return;
}
for (File file : files) {
if (!file.exists()) {
continue;
} else if (file.isDirectory()) {
readDir(file, aPattern, aFiles);
} else if (file.isFile())
readFile(file, aPattern, aFiles);
}
}
private static void readFile(final File aFile, final Pattern aPattern, final List<File> aFiles) {
String path = aFile.getAbsolutePath();
if (null == aPattern || aPattern.matcher(path).matches()) {
aFiles.add(aFile);
}
}
}
|
Precommit.
|
src/main/java/org/azkfw/util/FileUtility.java
|
Precommit.
|
|
Java
|
apache-2.0
|
3f0462510e4edefc7d6ef830b0ea61e1ff623fd4
| 0
|
spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework
|
/*
* Copyright 2002-2010 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 org.springframework.test.context;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* <p>
* <code>TestContextManager</code> is the main entry point into the
* <em>Spring TestContext Framework</em>, which provides support for loading and
* accessing {@link ApplicationContext application contexts}, dependency
* injection of test instances,
* {@link org.springframework.transaction.annotation.Transactional
* transactional} execution of test methods, etc.
* </p>
* <p>
* Specifically, a <code>TestContextManager</code> is responsible for managing a
* single {@link TestContext} and signaling events to all registered
* {@link TestExecutionListener TestExecutionListeners} at well defined test
* execution points:
* </p>
* <ul>
* <li>{@link #beforeTestClass() before test class execution}: prior to any
* <em>before class methods</em> of a particular testing framework (e.g., JUnit
* 4's {@link org.junit.BeforeClass @BeforeClass})</li>
* <li>{@link #prepareTestInstance(Object) test instance preparation}:
* immediately following instantiation of the test instance</li>
* <li>{@link #beforeTestMethod(Object,Method) before test method execution}:
* prior to any <em>before methods</em> of a particular testing framework (e.g.,
* JUnit 4's {@link org.junit.Before @Before})</li>
* <li>{@link #afterTestMethod(Object,Method,Throwable) after test method
* execution}: after any <em>after methods</em> of a particular testing
* framework (e.g., JUnit 4's {@link org.junit.After @After})</li>
* <li>{@link #afterTestClass() after test class execution}: after any
* <em>after class methods</em> of a particular testing framework (e.g., JUnit
* 4's {@link org.junit.AfterClass @AfterClass})</li>
* </ul>
*
* @author Sam Brannen
* @author Juergen Hoeller
* @since 2.5
* @see TestContext
* @see TestExecutionListeners
* @see ContextConfiguration
* @see org.springframework.test.context.transaction.TransactionConfiguration
*/
public class TestContextManager {
private static final String[] DEFAULT_TEST_EXECUTION_LISTENER_CLASS_NAMES = new String[] {
"org.springframework.test.context.support.DependencyInjectionTestExecutionListener",
"org.springframework.test.context.support.DirtiesContextTestExecutionListener",
"org.springframework.test.context.transaction.TransactionalTestExecutionListener" };
private static final Log logger = LogFactory.getLog(TestContextManager.class);
/**
* Cache of Spring application contexts. This needs to be static, as tests
* may be destroyed and recreated between running individual test methods,
* for example with JUnit.
*/
static final ContextCache contextCache = new ContextCache();
private final TestContext testContext;
private final List<TestExecutionListener> testExecutionListeners = new ArrayList<TestExecutionListener>();
/**
* Delegates to {@link #TestContextManager(Class, String)} with a value of
* <code>null</code> for the default <code>ContextLoader</code> class name.
*/
public TestContextManager(Class<?> testClass) {
this(testClass, null);
}
/**
* Constructs a new <code>TestContextManager</code> for the specified {@link Class test class}
* and automatically {@link #registerTestExecutionListeners registers} the
* {@link TestExecutionListener TestExecutionListeners} configured for the test class
* via the {@link TestExecutionListeners @TestExecutionListeners} annotation.
* @param testClass the test class to be managed
* @param defaultContextLoaderClassName the name of the default
* <code>ContextLoader</code> class to use (may be <code>null</code>)
* @see #registerTestExecutionListeners(TestExecutionListener...)
* @see #retrieveTestExecutionListeners(Class)
*/
public TestContextManager(Class<?> testClass, String defaultContextLoaderClassName) {
this.testContext = new TestContext(testClass, contextCache, defaultContextLoaderClassName);
registerTestExecutionListeners(retrieveTestExecutionListeners(testClass));
}
/**
* Returns the {@link TestContext} managed by this
* <code>TestContextManager</code>.
*/
protected final TestContext getTestContext() {
return this.testContext;
}
/**
* Register the supplied {@link TestExecutionListener TestExecutionListeners}
* by appending them to the set of listeners used by this <code>TestContextManager</code>.
*/
public void registerTestExecutionListeners(TestExecutionListener... testExecutionListeners) {
for (TestExecutionListener listener : testExecutionListeners) {
if (logger.isTraceEnabled()) {
logger.trace("Registering TestExecutionListener: " + listener);
}
this.testExecutionListeners.add(listener);
}
}
/**
* Get the current {@link TestExecutionListener TestExecutionListeners}
* registered for this <code>TestContextManager</code>.
* <p>Allows for modifications, e.g. adding a listener to the beginning of the list.
* However, make sure to keep the list stable while actually executing tests.
*/
public final List<TestExecutionListener> getTestExecutionListeners() {
return this.testExecutionListeners;
}
/**
* Get a copy of the {@link TestExecutionListener TestExecutionListeners}
* registered for this <code>TestContextManager</code> in reverse order.
*/
private List<TestExecutionListener> getReversedTestExecutionListeners() {
List<TestExecutionListener> listenersReversed =
new ArrayList<TestExecutionListener>(getTestExecutionListeners());
Collections.reverse(listenersReversed);
return listenersReversed;
}
/**
* Retrieve an array of newly instantiated {@link TestExecutionListener TestExecutionListeners}
* for the specified {@link Class class}. If {@link TestExecutionListeners @TestExecutionListeners}
* is not <em>present</em> on the supplied class, the default listeners will be returned.
* <p>Note that the {@link TestExecutionListeners#inheritListeners() inheritListeners} flag of
* {@link TestExecutionListeners @TestExecutionListeners} will be taken into consideration.
* Specifically, if the <code>inheritListeners</code> flag is set to <code>true</code>, listeners
* defined in the annotated class will be appended to the listeners defined in superclasses.
* @param clazz the test class for which the listeners should be retrieved
* @return an array of TestExecutionListeners for the specified class
*/
private TestExecutionListener[] retrieveTestExecutionListeners(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
Class<TestExecutionListeners> annotationType = TestExecutionListeners.class;
List<Class<? extends TestExecutionListener>> classesList = new ArrayList<Class<? extends TestExecutionListener>>();
Class<?> declaringClass = AnnotationUtils.findAnnotationDeclaringClass(annotationType, clazz);
boolean defaultListeners = false;
// Use defaults?
if (declaringClass == null) {
if (logger.isInfoEnabled()) {
logger.info("@TestExecutionListeners is not present for class [" + clazz + "]: using defaults.");
}
classesList.addAll(getDefaultTestExecutionListenerClasses());
defaultListeners = true;
}
else {
// Traverse the class hierarchy...
while (declaringClass != null) {
TestExecutionListeners testExecutionListeners = declaringClass.getAnnotation(annotationType);
if (logger.isTraceEnabled()) {
logger.trace("Retrieved @TestExecutionListeners [" + testExecutionListeners
+ "] for declaring class [" + declaringClass + "].");
}
Class<? extends TestExecutionListener>[] valueListenerClasses = testExecutionListeners.value();
Class<? extends TestExecutionListener>[] listenerClasses = testExecutionListeners.listeners();
if (!ObjectUtils.isEmpty(valueListenerClasses) && !ObjectUtils.isEmpty(listenerClasses)) {
String msg = String.format(
"Test class [%s] has been configured with @TestExecutionListeners' 'value' [%s] " +
"and 'listeners' [%s] attributes. Use one or the other, but not both.",
declaringClass, ObjectUtils.nullSafeToString(valueListenerClasses),
ObjectUtils.nullSafeToString(listenerClasses));
logger.error(msg);
throw new IllegalStateException(msg);
}
else if (!ObjectUtils.isEmpty(valueListenerClasses)) {
listenerClasses = valueListenerClasses;
}
if (listenerClasses != null) {
classesList.addAll(0, Arrays.<Class<? extends TestExecutionListener>> asList(listenerClasses));
}
declaringClass = (testExecutionListeners.inheritListeners() ?
AnnotationUtils.findAnnotationDeclaringClass(annotationType, declaringClass.getSuperclass()) : null);
}
}
List<TestExecutionListener> listeners = new ArrayList<TestExecutionListener>(classesList.size());
for (Class<? extends TestExecutionListener> listenerClass : classesList) {
try {
listeners.add(BeanUtils.instantiateClass(listenerClass));
}
catch (NoClassDefFoundError err) {
if (defaultListeners) {
if (logger.isDebugEnabled()) {
logger.debug("Could not instantiate default TestExecutionListener class ["
+ listenerClass.getName()
+ "]. Specify custom listener classes or make the default listener classes available.");
}
}
else {
throw err;
}
}
}
return listeners.toArray(new TestExecutionListener[listeners.size()]);
}
/**
* Determine the default {@link TestExecutionListener} classes.
*/
@SuppressWarnings("unchecked")
protected Set<Class<? extends TestExecutionListener>> getDefaultTestExecutionListenerClasses() {
Set<Class<? extends TestExecutionListener>> defaultListenerClasses =
new LinkedHashSet<Class<? extends TestExecutionListener>>();
for (String className : DEFAULT_TEST_EXECUTION_LISTENER_CLASS_NAMES) {
try {
defaultListenerClasses.add(
(Class<? extends TestExecutionListener>) getClass().getClassLoader().loadClass(className));
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Could not load default TestExecutionListener class [" + className
+ "]. Specify custom listener classes or make the default listener classes available.");
}
}
}
return defaultListenerClasses;
}
/**
* Hook for pre-processing a test class <em>before</em> execution of any
* tests within the class. Should be called prior to any framework-specific
* <em>before class methods</em> (e.g., methods annotated with JUnit's
* {@link org.junit.BeforeClass @BeforeClass}).
* <p>An attempt will be made to give each registered
* {@link TestExecutionListener} a chance to pre-process the test class
* execution. If a listener throws an exception, however, the remaining
* registered listeners will <strong>not</strong> be called.
* @throws Exception if a registered TestExecutionListener throws an
* exception
* @see #getTestExecutionListeners()
*/
public void beforeTestClass() throws Exception {
final Class<?> testClass = getTestContext().getTestClass();
if (logger.isTraceEnabled()) {
logger.trace("beforeTestClass(): class [" + testClass + "]");
}
getTestContext().updateState(null, null, null);
for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) {
try {
testExecutionListener.beforeTestClass(getTestContext());
}
catch (Exception ex) {
logger.warn("Caught exception while allowing TestExecutionListener [" + testExecutionListener
+ "] to process 'before class' callback for test class [" + testClass + "]", ex);
throw ex;
}
}
}
/**
* Hook for preparing a test instance prior to execution of any individual
* test methods, for example for injecting dependencies, etc. Should be
* called immediately after instantiation of the test instance.
* <p>The managed {@link TestContext} will be updated with the supplied
* <code>testInstance</code>.
* <p>An attempt will be made to give each registered
* {@link TestExecutionListener} a chance to prepare the test instance. If a
* listener throws an exception, however, the remaining registered listeners
* will <strong>not</strong> be called.
* @param testInstance the test instance to prepare (never <code>null</code>)
* @throws Exception if a registered TestExecutionListener throws an exception
* @see #getTestExecutionListeners()
*/
public void prepareTestInstance(Object testInstance) throws Exception {
Assert.notNull(testInstance, "testInstance must not be null");
if (logger.isTraceEnabled()) {
logger.trace("prepareTestInstance(): instance [" + testInstance + "]");
}
getTestContext().updateState(testInstance, null, null);
for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) {
try {
testExecutionListener.prepareTestInstance(getTestContext());
}
catch (Exception ex) {
logger.error("Caught exception while allowing TestExecutionListener [" + testExecutionListener
+ "] to prepare test instance [" + testInstance + "]", ex);
throw ex;
}
}
}
/**
* Hook for pre-processing a test <em>before</em> execution of the supplied
* {@link Method test method}, for example for setting up test fixtures,
* starting a transaction, etc. Should be called prior to any
* framework-specific <em>before methods</em> (e.g., methods annotated with
* JUnit's {@link org.junit.Before @Before}).
* <p>The managed {@link TestContext} will be updated with the supplied
* <code>testInstance</code> and <code>testMethod</code>.
* <p>An attempt will be made to give each registered
* {@link TestExecutionListener} a chance to pre-process the test method
* execution. If a listener throws an exception, however, the remaining
* registered listeners will <strong>not</strong> be called.
* @param testInstance the current test instance (never <code>null</code>)
* @param testMethod the test method which is about to be executed on the
* test instance
* @throws Exception if a registered TestExecutionListener throws an exception
* @see #getTestExecutionListeners()
*/
public void beforeTestMethod(Object testInstance, Method testMethod) throws Exception {
Assert.notNull(testInstance, "Test instance must not be null");
if (logger.isTraceEnabled()) {
logger.trace("beforeTestMethod(): instance [" + testInstance + "], method [" + testMethod + "]");
}
getTestContext().updateState(testInstance, testMethod, null);
for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) {
try {
testExecutionListener.beforeTestMethod(getTestContext());
}
catch (Exception ex) {
logger.warn("Caught exception while allowing TestExecutionListener [" + testExecutionListener
+ "] to process 'before' execution of test method [" + testMethod + "] for test instance ["
+ testInstance + "]", ex);
throw ex;
}
}
}
/**
* Hook for post-processing a test <em>after</em> execution of the supplied
* {@link Method test method}, for example for tearing down test fixtures,
* ending a transaction, etc. Should be called after any framework-specific
* <em>after methods</em> (e.g., methods annotated with JUnit's
* {@link org.junit.After @After}).
* <p>The managed {@link TestContext} will be updated with the supplied
* <code>testInstance</code>, <code>testMethod</code>, and
* <code>exception</code>.
* <p>Each registered {@link TestExecutionListener} will be given a chance to
* post-process the test method execution. If a listener throws an
* exception, the remaining registered listeners will still be called, but
* the first exception thrown will be tracked and rethrown after all
* listeners have executed. Note that registered listeners will be executed
* in the opposite order in which they were registered.
* @param testInstance the current test instance (never <code>null</code>)
* @param testMethod the test method which has just been executed on the
* test instance
* @param exception the exception that was thrown during execution of the
* test method or by a TestExecutionListener, or <code>null</code> if none
* was thrown
* @throws Exception if a registered TestExecutionListener throws an exception
* @see #getTestExecutionListeners()
*/
public void afterTestMethod(Object testInstance, Method testMethod, Throwable exception) throws Exception {
Assert.notNull(testInstance, "testInstance must not be null");
if (logger.isTraceEnabled()) {
logger.trace("afterTestMethod(): instance [" + testInstance + "], method [" + testMethod + "], exception ["
+ exception + "]");
}
getTestContext().updateState(testInstance, testMethod, exception);
Exception afterTestMethodException = null;
// Traverse the TestExecutionListeners in reverse order to ensure proper
// "wrapper"-style execution of listeners.
for (TestExecutionListener testExecutionListener : getReversedTestExecutionListeners()) {
try {
testExecutionListener.afterTestMethod(getTestContext());
}
catch (Exception ex) {
logger.warn("Caught exception while allowing TestExecutionListener [" + testExecutionListener
+ "] to process 'after' execution for test: method [" + testMethod + "], instance ["
+ testInstance + "], exception [" + exception + "]", ex);
if (afterTestMethodException == null) {
afterTestMethodException = ex;
}
}
}
if (afterTestMethodException != null) {
throw afterTestMethodException;
}
}
/**
* Hook for post-processing a test class <em>after</em> execution of all
* tests within the class. Should be called after any framework-specific
* <em>after class methods</em> (e.g., methods annotated with JUnit's
* {@link org.junit.AfterClass @AfterClass}).
* <p>Each registered {@link TestExecutionListener} will be given a chance to
* post-process the test class. If a listener throws an exception, the
* remaining registered listeners will still be called, but the first
* exception thrown will be tracked and rethrown after all listeners have
* executed. Note that registered listeners will be executed in the opposite
* order in which they were registered.
* @throws Exception if a registered TestExecutionListener throws an exception
* @see #getTestExecutionListeners()
*/
public void afterTestClass() throws Exception {
final Class<?> testClass = getTestContext().getTestClass();
if (logger.isTraceEnabled()) {
logger.trace("afterTestClass(): class [" + testClass + "]");
}
getTestContext().updateState(null, null, null);
Exception afterTestClassException = null;
// Traverse the TestExecutionListeners in reverse order to ensure proper
// "wrapper"-style execution of listeners.
for (TestExecutionListener testExecutionListener : getReversedTestExecutionListeners()) {
try {
testExecutionListener.afterTestClass(getTestContext());
}
catch (Exception ex) {
logger.warn("Caught exception while allowing TestExecutionListener [" + testExecutionListener
+ "] to process 'after class' callback for test class [" + testClass + "]", ex);
if (afterTestClassException == null) {
afterTestClassException = ex;
}
}
}
if (afterTestClassException != null) {
throw afterTestClassException;
}
}
}
|
org.springframework.test/src/main/java/org/springframework/test/context/TestContextManager.java
|
/*
* Copyright 2002-2009 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 org.springframework.test.context;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* <p>
* <code>TestContextManager</code> is the main entry point into the
* <em>Spring TestContext Framework</em>, which provides support for loading and
* accessing {@link ApplicationContext application contexts}, dependency
* injection of test instances,
* {@link org.springframework.transaction.annotation.Transactional
* transactional} execution of test methods, etc.
* </p>
* <p>
* Specifically, a <code>TestContextManager</code> is responsible for managing a
* single {@link TestContext} and signaling events to all registered
* {@link TestExecutionListener TestExecutionListeners} at well defined test
* execution points:
* </p>
* <ul>
* <li>{@link #beforeTestClass() before test class execution}: prior to any
* <em>before class methods</em> of a particular testing framework (e.g., JUnit
* 4's {@link org.junit.BeforeClass @BeforeClass})</li>
* <li>{@link #prepareTestInstance(Object) test instance preparation}:
* immediately following instantiation of the test instance</li>
* <li>{@link #beforeTestMethod(Object,Method) before test method execution}:
* prior to any <em>before methods</em> of a particular testing framework (e.g.,
* JUnit 4's {@link org.junit.Before @Before})</li>
* <li>{@link #afterTestMethod(Object,Method,Throwable) after test method
* execution}: after any <em>after methods</em> of a particular testing
* framework (e.g., JUnit 4's {@link org.junit.After @After})</li>
* <li>{@link #afterTestClass() after test class execution}: after any
* <em>after class methods</em> of a particular testing framework (e.g., JUnit
* 4's {@link org.junit.AfterClass @AfterClass})</li>
* </ul>
*
* @author Sam Brannen
* @author Juergen Hoeller
* @since 2.5
* @see TestContext
* @see TestExecutionListeners
* @see ContextConfiguration
* @see org.springframework.test.context.transaction.TransactionConfiguration
*/
public class TestContextManager {
private static final String[] DEFAULT_TEST_EXECUTION_LISTENER_CLASS_NAMES = new String[] {
"org.springframework.test.context.support.DependencyInjectionTestExecutionListener",
"org.springframework.test.context.support.DirtiesContextTestExecutionListener",
"org.springframework.test.context.transaction.TransactionalTestExecutionListener" };
private static final Log logger = LogFactory.getLog(TestContextManager.class);
/**
* Cache of Spring application contexts. This needs to be static, as tests
* may be destroyed and recreated between running individual test methods,
* for example with JUnit.
*/
static final ContextCache contextCache = new ContextCache();
private final TestContext testContext;
private final List<TestExecutionListener> testExecutionListeners = new ArrayList<TestExecutionListener>();
/**
* Delegates to {@link #TestContextManager(Class, String)} with a value of
* <code>null</code> for the default <code>ContextLoader</code> class name.
*/
public TestContextManager(Class<?> testClass) {
this(testClass, null);
}
/**
* Constructs a new <code>TestContextManager</code> for the specified
* {@link Class test class} and automatically
* {@link #registerTestExecutionListeners(TestExecutionListener...)
* registers} the {@link TestExecutionListener TestExecutionListeners}
* configured for the test class via the {@link TestExecutionListeners
* @TestExecutionListeners} annotation.
*
* @param testClass the test class to be managed
* @param defaultContextLoaderClassName the name of the default
* <code>ContextLoader</code> class to use (may be <code>null</code>)
* @see #registerTestExecutionListeners(TestExecutionListener...)
* @see #retrieveTestExecutionListeners(Class)
*/
public TestContextManager(Class<?> testClass, String defaultContextLoaderClassName) {
this.testContext = new TestContext(testClass, contextCache, defaultContextLoaderClassName);
registerTestExecutionListeners(retrieveTestExecutionListeners(testClass));
}
/**
* Returns the {@link TestContext} managed by this
* <code>TestContextManager</code>.
*/
protected final TestContext getTestContext() {
return this.testContext;
}
/**
* Register the supplied {@link TestExecutionListener
* TestExecutionListeners} by appending them to the set of listeners used by
* this <code>TestContextManager</code>.
*/
public void registerTestExecutionListeners(TestExecutionListener... testExecutionListeners) {
for (TestExecutionListener listener : testExecutionListeners) {
if (logger.isTraceEnabled()) {
logger.trace("Registering TestExecutionListener [" + listener + "]");
}
this.testExecutionListeners.add(listener);
}
}
/**
* Gets an {@link Collections#unmodifiableList(List) unmodifiable} copy of
* the {@link TestExecutionListener TestExecutionListeners} registered for
* this <code>TestContextManager</code>.
*/
public final List<TestExecutionListener> getTestExecutionListeners() {
return Collections.unmodifiableList(this.testExecutionListeners);
}
/**
* Gets a copy of the {@link TestExecutionListener TestExecutionListeners}
* registered for this <code>TestContextManager</code> in reverse order.
*/
private List<TestExecutionListener> getReversedTestExecutionListeners() {
List<TestExecutionListener> listenersReversed = new ArrayList<TestExecutionListener>(
getTestExecutionListeners());
Collections.reverse(listenersReversed);
return listenersReversed;
}
/**
* Retrieves an array of newly instantiated {@link TestExecutionListener
* TestExecutionListeners} for the specified {@link Class class}. If
* {@link TestExecutionListeners @TestExecutionListeners} is not
* <em>present</em> on the supplied class, the default listeners will be
* returned.
* <p>
* Note that the {@link TestExecutionListeners#inheritListeners()
* inheritListeners} flag of {@link TestExecutionListeners
* @TestExecutionListeners} will be taken into consideration.
* Specifically, if the <code>inheritListeners</code> flag is set to
* <code>true</code>, listeners defined in the annotated class will be
* appended to the listeners defined in superclasses.
*
* @param clazz the test class for which the listeners should be retrieved
* @return an array of TestExecutionListeners for the specified class
*/
private TestExecutionListener[] retrieveTestExecutionListeners(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
Class<TestExecutionListeners> annotationType = TestExecutionListeners.class;
List<Class<? extends TestExecutionListener>> classesList = new ArrayList<Class<? extends TestExecutionListener>>();
Class<?> declaringClass = AnnotationUtils.findAnnotationDeclaringClass(annotationType, clazz);
boolean defaultListeners = false;
// Use defaults?
if (declaringClass == null) {
if (logger.isInfoEnabled()) {
logger.info("@TestExecutionListeners is not present for class [" + clazz + "]: using defaults.");
}
classesList.addAll(getDefaultTestExecutionListenerClasses());
defaultListeners = true;
}
else {
// Traverse the class hierarchy...
while (declaringClass != null) {
TestExecutionListeners testExecutionListeners = declaringClass.getAnnotation(annotationType);
if (logger.isTraceEnabled()) {
logger.trace("Retrieved @TestExecutionListeners [" + testExecutionListeners
+ "] for declaring class [" + declaringClass + "].");
}
Class<? extends TestExecutionListener>[] valueListenerClasses = testExecutionListeners.value();
Class<? extends TestExecutionListener>[] listenerClasses = testExecutionListeners.listeners();
if (!ObjectUtils.isEmpty(valueListenerClasses) && !ObjectUtils.isEmpty(listenerClasses)) {
String msg = String.format(
"Test class [%s] has been configured with @TestExecutionListeners' 'value' [%s] and 'listeners' [%s] attributes. Use one or the other, but not both.",
declaringClass, ObjectUtils.nullSafeToString(valueListenerClasses),
ObjectUtils.nullSafeToString(listenerClasses));
logger.error(msg);
throw new IllegalStateException(msg);
}
else if (!ObjectUtils.isEmpty(valueListenerClasses)) {
listenerClasses = valueListenerClasses;
}
if (listenerClasses != null) {
classesList.addAll(0, Arrays.<Class<? extends TestExecutionListener>> asList(listenerClasses));
}
declaringClass = (testExecutionListeners.inheritListeners() ? AnnotationUtils.findAnnotationDeclaringClass(
annotationType, declaringClass.getSuperclass())
: null);
}
}
List<TestExecutionListener> listeners = new ArrayList<TestExecutionListener>(classesList.size());
for (Class<? extends TestExecutionListener> listenerClass : classesList) {
try {
listeners.add((TestExecutionListener) BeanUtils.instantiateClass(listenerClass));
}
catch (NoClassDefFoundError err) {
if (defaultListeners) {
if (logger.isDebugEnabled()) {
logger.debug("Could not instantiate default TestExecutionListener class ["
+ listenerClass.getName()
+ "]. Specify custom listener classes or make the default listener classes available.");
}
}
else {
throw err;
}
}
}
return listeners.toArray(new TestExecutionListener[listeners.size()]);
}
/**
* Determine the default {@link TestExecutionListener} classes.
*/
@SuppressWarnings("unchecked")
protected Set<Class<? extends TestExecutionListener>> getDefaultTestExecutionListenerClasses() {
Set<Class<? extends TestExecutionListener>> defaultListenerClasses = new LinkedHashSet<Class<? extends TestExecutionListener>>();
for (String className : DEFAULT_TEST_EXECUTION_LISTENER_CLASS_NAMES) {
try {
defaultListenerClasses.add((Class<? extends TestExecutionListener>) getClass().getClassLoader().loadClass(
className));
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Could not load default TestExecutionListener class [" + className
+ "]. Specify custom listener classes or make the default listener classes available.");
}
}
}
return defaultListenerClasses;
}
/**
* Hook for pre-processing a test class <em>before</em> execution of any
* tests within the class. Should be called prior to any framework-specific
* <em>before class methods</em> (e.g., methods annotated with JUnit's
* {@link org.junit.BeforeClass @BeforeClass}).
* <p>
* An attempt will be made to give each registered
* {@link TestExecutionListener} a chance to pre-process the test class
* execution. If a listener throws an exception, however, the remaining
* registered listeners will <strong>not</strong> be called.
*
* @throws Exception if a registered TestExecutionListener throws an
* exception
* @see #getTestExecutionListeners()
*/
public void beforeTestClass() throws Exception {
final Class<?> testClass = getTestContext().getTestClass();
if (logger.isTraceEnabled()) {
logger.trace("beforeTestClass(): class [" + testClass + "]");
}
getTestContext().updateState(null, null, null);
for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) {
try {
testExecutionListener.beforeTestClass(getTestContext());
}
catch (Exception ex) {
logger.warn("Caught exception while allowing TestExecutionListener [" + testExecutionListener
+ "] to process 'before class' callback for test class [" + testClass + "]", ex);
throw ex;
}
}
}
/**
* Hook for preparing a test instance prior to execution of any individual
* test methods, for example for injecting dependencies, etc. Should be
* called immediately after instantiation of the test instance.
* <p>
* The managed {@link TestContext} will be updated with the supplied
* <code>testInstance</code>.
* <p>
* An attempt will be made to give each registered
* {@link TestExecutionListener} a chance to prepare the test instance. If a
* listener throws an exception, however, the remaining registered listeners
* will <strong>not</strong> be called.
*
* @param testInstance the test instance to prepare (never <code>null</code>
* )
* @throws Exception if a registered TestExecutionListener throws an
* exception
* @see #getTestExecutionListeners()
*/
public void prepareTestInstance(Object testInstance) throws Exception {
Assert.notNull(testInstance, "testInstance must not be null");
if (logger.isTraceEnabled()) {
logger.trace("prepareTestInstance(): instance [" + testInstance + "]");
}
getTestContext().updateState(testInstance, null, null);
for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) {
try {
testExecutionListener.prepareTestInstance(getTestContext());
}
catch (Exception ex) {
logger.error("Caught exception while allowing TestExecutionListener [" + testExecutionListener
+ "] to prepare test instance [" + testInstance + "]", ex);
throw ex;
}
}
}
/**
* Hook for pre-processing a test <em>before</em> execution of the supplied
* {@link Method test method}, for example for setting up test fixtures,
* starting a transaction, etc. Should be called prior to any
* framework-specific <em>before methods</em> (e.g., methods annotated with
* JUnit's {@link org.junit.Before @Before}).
* <p>
* The managed {@link TestContext} will be updated with the supplied
* <code>testInstance</code> and <code>testMethod</code>.
* <p>
* An attempt will be made to give each registered
* {@link TestExecutionListener} a chance to pre-process the test method
* execution. If a listener throws an exception, however, the remaining
* registered listeners will <strong>not</strong> be called.
*
* @param testInstance the current test instance (never <code>null</code>)
* @param testMethod the test method which is about to be executed on the
* test instance
* @throws Exception if a registered TestExecutionListener throws an
* exception
* @see #getTestExecutionListeners()
*/
public void beforeTestMethod(Object testInstance, Method testMethod) throws Exception {
Assert.notNull(testInstance, "Test instance must not be null");
if (logger.isTraceEnabled()) {
logger.trace("beforeTestMethod(): instance [" + testInstance + "], method [" + testMethod + "]");
}
getTestContext().updateState(testInstance, testMethod, null);
for (TestExecutionListener testExecutionListener : getTestExecutionListeners()) {
try {
testExecutionListener.beforeTestMethod(getTestContext());
}
catch (Exception ex) {
logger.warn("Caught exception while allowing TestExecutionListener [" + testExecutionListener
+ "] to process 'before' execution of test method [" + testMethod + "] for test instance ["
+ testInstance + "]", ex);
throw ex;
}
}
}
/**
* Hook for post-processing a test <em>after</em> execution of the supplied
* {@link Method test method}, for example for tearing down test fixtures,
* ending a transaction, etc. Should be called after any framework-specific
* <em>after methods</em> (e.g., methods annotated with JUnit's
* {@link org.junit.After @After}).
* <p>
* The managed {@link TestContext} will be updated with the supplied
* <code>testInstance</code>, <code>testMethod</code>, and
* <code>exception</code>.
* <p>
* Each registered {@link TestExecutionListener} will be given a chance to
* post-process the test method execution. If a listener throws an
* exception, the remaining registered listeners will still be called, but
* the first exception thrown will be tracked and rethrown after all
* listeners have executed. Note that registered listeners will be executed
* in the opposite order in which they were registered.
*
* @param testInstance the current test instance (never <code>null</code>)
* @param testMethod the test method which has just been executed on the
* test instance
* @param exception the exception that was thrown during execution of the
* test method or by a TestExecutionListener, or <code>null</code> if none
* was thrown
* @throws Exception if a registered TestExecutionListener throws an
* exception
* @see #getTestExecutionListeners()
*/
public void afterTestMethod(Object testInstance, Method testMethod, Throwable exception) throws Exception {
Assert.notNull(testInstance, "testInstance must not be null");
if (logger.isTraceEnabled()) {
logger.trace("afterTestMethod(): instance [" + testInstance + "], method [" + testMethod + "], exception ["
+ exception + "]");
}
getTestContext().updateState(testInstance, testMethod, exception);
Exception afterTestMethodException = null;
// Traverse the TestExecutionListeners in reverse order to ensure proper
// "wrapper"-style execution of listeners.
for (TestExecutionListener testExecutionListener : getReversedTestExecutionListeners()) {
try {
testExecutionListener.afterTestMethod(getTestContext());
}
catch (Exception ex) {
logger.warn("Caught exception while allowing TestExecutionListener [" + testExecutionListener
+ "] to process 'after' execution for test: method [" + testMethod + "], instance ["
+ testInstance + "], exception [" + exception + "]", ex);
if (afterTestMethodException == null) {
afterTestMethodException = ex;
}
}
}
if (afterTestMethodException != null) {
throw afterTestMethodException;
}
}
/**
* Hook for post-processing a test class <em>after</em> execution of all
* tests within the class. Should be called after any framework-specific
* <em>after class methods</em> (e.g., methods annotated with JUnit's
* {@link org.junit.AfterClass @AfterClass}).
* <p>
* Each registered {@link TestExecutionListener} will be given a chance to
* post-process the test class. If a listener throws an exception, the
* remaining registered listeners will still be called, but the first
* exception thrown will be tracked and rethrown after all listeners have
* executed. Note that registered listeners will be executed in the opposite
* order in which they were registered.
*
* @throws Exception if a registered TestExecutionListener throws an
* exception
* @see #getTestExecutionListeners()
*/
public void afterTestClass() throws Exception {
final Class<?> testClass = getTestContext().getTestClass();
if (logger.isTraceEnabled()) {
logger.trace("afterTestClass(): class [" + testClass + "]");
}
getTestContext().updateState(null, null, null);
Exception afterTestClassException = null;
// Traverse the TestExecutionListeners in reverse order to ensure proper
// "wrapper"-style execution of listeners.
for (TestExecutionListener testExecutionListener : getReversedTestExecutionListeners()) {
try {
testExecutionListener.afterTestClass(getTestContext());
}
catch (Exception ex) {
logger.warn("Caught exception while allowing TestExecutionListener [" + testExecutionListener
+ "] to process 'after class' callback for test class [" + testClass + "]", ex);
if (afterTestClassException == null) {
afterTestClassException = ex;
}
}
}
if (afterTestClassException != null) {
throw afterTestClassException;
}
}
}
|
getTestExecutionListeners() returns actual List which allows for iteration as well as modification (SPR-7595)
|
org.springframework.test/src/main/java/org/springframework/test/context/TestContextManager.java
|
getTestExecutionListeners() returns actual List which allows for iteration as well as modification (SPR-7595)
|
|
Java
|
mit
|
299d20509954ea27835c16c5494e5ef33dfd5136
| 0
|
hoqhuuep/IslandCraft
|
package com.github.hoqhuuep.islandcraft.worldguard;
import org.bukkit.Bukkit;
import org.bukkit.World;
import com.github.hoqhuuep.islandcraft.realestate.SerializableRegion;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class WorldGuardManager {
private final WorldGuardPlugin worldGuard;
public WorldGuardManager(final WorldGuardPlugin worldGuard) {
this.worldGuard = worldGuard;
}
public void setPrivate(final SerializableRegion region, final String player) {
final ProtectedRegion protectedRegion = createProtectedRegion(region);
final DefaultDomain owners = new DefaultDomain();
owners.addPlayer(player);
protectedRegion.setOwners(owners);
addProtectedRegion(region.getWorld(), protectedRegion);
}
public void setReserved(final SerializableRegion region) {
final ProtectedRegion protectedRegion = createProtectedRegion(region);
protectedRegion.setFlag(DefaultFlag.BUILD, State.DENY);
addProtectedRegion(region.getWorld(), protectedRegion);
}
public void setPublic(final SerializableRegion region) {
final ProtectedRegion protectedRegion = createProtectedRegion(region);
protectedRegion.setFlag(DefaultFlag.BUILD, State.ALLOW);
addProtectedRegion(region.getWorld(), protectedRegion);
}
private ProtectedRegion createProtectedRegion(final SerializableRegion region) {
final int minX = region.getMinX();
final int minY = region.getMinY();
final int minZ = region.getMinZ();
final int maxX = region.getMaxX();
final int maxY = region.getMaxY();
final int maxZ = region.getMaxZ();
// TODO allow for different id's
final String id = "ic'" + region.getWorld() + "'" + minX + "'" + minY + "'" + minZ + "'" + maxX + "'" + maxY + "'" + maxZ;
final BlockVector p1 = new BlockVector(minX, minY, minZ);
final BlockVector p2 = new BlockVector(maxX - 1, maxY - 1, maxZ - 1);
return new ProtectedCuboidRegion(id, p1, p2);
}
private void addProtectedRegion(final String worldName, final ProtectedRegion protectedRegion) {
final World world = Bukkit.getWorld(worldName);
if (world == null) {
// TODO handle this
return;
}
final RegionManager regionManager = worldGuard.getRegionManager(world);
if (regionManager == null) {
// TODO handle this
return;
}
regionManager.addRegion(protectedRegion);
try {
regionManager.save();
} catch (final ProtectionDatabaseException e) {
// TODO handle this
}
}
}
|
IslandCraft-WorldGuard/src/main/java/com/github/hoqhuuep/islandcraft/worldguard/WorldGuardManager.java
|
package com.github.hoqhuuep.islandcraft.worldguard;
import org.bukkit.Bukkit;
import org.bukkit.World;
import com.github.hoqhuuep.islandcraft.realestate.SerializableRegion;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.domains.DefaultDomain;
import com.sk89q.worldguard.protection.databases.ProtectionDatabaseException;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.flags.StateFlag.State;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
public class WorldGuardManager {
private final WorldGuardPlugin worldGuard;
public WorldGuardManager(final WorldGuardPlugin worldGuard) {
this.worldGuard = worldGuard;
}
public void setPrivate(final SerializableRegion region, final String player) {
final ProtectedRegion protectedRegion = createProtectedRegion(region);
final DefaultDomain owners = new DefaultDomain();
owners.addPlayer(player);
protectedRegion.setOwners(owners);
addProtectedRegion(region.getWorld(), protectedRegion);
}
public void setReserved(final SerializableRegion region) {
final ProtectedRegion protectedRegion = createProtectedRegion(region);
protectedRegion.setFlag(DefaultFlag.BUILD, State.DENY);
addProtectedRegion(region.getWorld(), protectedRegion);
}
public void setPublic(final SerializableRegion region) {
final ProtectedRegion protectedRegion = createProtectedRegion(region);
protectedRegion.setFlag(DefaultFlag.BUILD, State.ALLOW);
addProtectedRegion(region.getWorld(), protectedRegion);
}
private ProtectedRegion createProtectedRegion(final SerializableRegion region) {
final int minX = region.getMinX();
final int minY = region.getMinY();
final int minZ = region.getMinZ();
final int maxX = region.getMaxX();
final int maxY = region.getMaxY();
final int maxZ = region.getMaxZ();
// TODO allow for different id's
final String id = "ic'" + region.getWorld() + "'" + minX + "'" + minY + "'" + minZ + "'" + maxX + "'" + maxY + "'" + maxZ;
final BlockVector p1 = new BlockVector(minX, minY, minZ);
final BlockVector p2 = new BlockVector(maxX, maxY, maxZ);
return new ProtectedCuboidRegion(id, p1, p2);
}
private void addProtectedRegion(final String worldName, final ProtectedRegion protectedRegion) {
final World world = Bukkit.getWorld(worldName);
if (world == null) {
// TODO handle this
return;
}
final RegionManager regionManager = worldGuard.getRegionManager(world);
if (regionManager == null) {
// TODO handle this
return;
}
regionManager.addRegion(protectedRegion);
try {
regionManager.save();
} catch (final ProtectionDatabaseException e) {
// TODO handle this
}
}
}
|
Fixed off-by-1 error in worldguard regions
|
IslandCraft-WorldGuard/src/main/java/com/github/hoqhuuep/islandcraft/worldguard/WorldGuardManager.java
|
Fixed off-by-1 error in worldguard regions
|
|
Java
|
mit
|
2318a5c6d288c7d610ff7f190d9c7aa4af82edc2
| 0
|
fjorum/fjorum,mlrdev/fjorum,fjorum/fjorum,mlrdev/fjorum
|
package org.fjorum.util;
import java.util.function.Predicate;
public class Predicates {
@SafeVarargs
public static <A> Predicate<A> or(Predicate<A>... predicates) {
Predicate<A> result = a -> false;
for (Predicate<A> predicate : predicates) {
result = result.or(predicate);
}
return result;
}
@SafeVarargs
public static <A> Predicate<A> and(Predicate<A>... predicates) {
Predicate<A> result = a -> true;
for (Predicate<A> predicate : predicates) {
result = result.and(predicate);
}
return result;
}
}
|
src/main/java/org/fjorum/util/Predicates.java
|
package org.fjorum.util;
import java.util.Optional;
import java.util.function.Predicate;
public class Predicates {
@SafeVarargs
public static <A> Predicate<A> or(Predicate<A> ... predicates) {
Optional<Predicate<A>> result = Optional.empty();
for(Predicate<A> predicate : predicates) {
result = result.map(r -> r.or(predicate));
}
return result.orElseGet(() -> a -> false);
}
@SafeVarargs
public static <A> Predicate<A> and(Predicate<A> ... predicates) {
Optional<Predicate<A>> result = Optional.empty();
for(Predicate<A> predicate : predicates) {
result = result.map(r -> r.and(predicate));
}
return result.orElseGet(() -> a -> true);
}
}
|
fixed Predicates
|
src/main/java/org/fjorum/util/Predicates.java
|
fixed Predicates
|
|
Java
|
mit
|
ca799630ba948bf9d40ae7e82016698f2368cfb1
| 0
|
sazzad16/jedis,sazzad16/jedis
|
package redis.clients.jedis.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.BinaryJedisCluster.Reset;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisClusterInfoCache;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.*;
import redis.clients.jedis.tests.utils.ClientKillerUtil;
import redis.clients.jedis.tests.utils.JedisClusterTestUtil;
import redis.clients.util.JedisClusterCRC16;
public class JedisClusterTest {
private static Jedis node1;
private static Jedis node2;
private static Jedis node3;
private static Jedis node4;
private static Jedis nodeSlave2;
private String localHost = "127.0.0.1";
private static final int DEFAULT_TIMEOUT = 2000;
private static final int DEFAULT_REDIRECTIONS = 5;
private static final JedisPoolConfig DEFAULT_CONFIG = new JedisPoolConfig();
private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0);
private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1);
private HostAndPort nodeInfo3 = HostAndPortUtil.getClusterServers().get(2);
private HostAndPort nodeInfo4 = HostAndPortUtil.getClusterServers().get(3);
private HostAndPort nodeInfoSlave2 = HostAndPortUtil.getClusterServers().get(4);
protected Logger log = LoggerFactory.getLogger(getClass().getName());
@Before
public void setUp() throws InterruptedException {
node1 = new Jedis(nodeInfo1);
node1.auth("cluster");
node1.flushAll();
node2 = new Jedis(nodeInfo2);
node2.auth("cluster");
node2.flushAll();
node3 = new Jedis(nodeInfo3);
node3.auth("cluster");
node3.flushAll();
node4 = new Jedis(nodeInfo4);
node4.auth("cluster");
node4.flushAll();
nodeSlave2 = new Jedis(nodeInfoSlave2);
nodeSlave2.auth("cluster");
nodeSlave2.flushAll();
// ---- configure cluster
// add nodes to cluster
node1.clusterMeet(localHost, nodeInfo2.getPort());
node1.clusterMeet(localHost, nodeInfo3.getPort());
// split available slots across the three nodes
int slotsPerNode = JedisCluster.HASHSLOTS / 3;
int[] node1Slots = new int[slotsPerNode];
int[] node2Slots = new int[slotsPerNode + 1];
int[] node3Slots = new int[slotsPerNode];
for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < JedisCluster.HASHSLOTS; i++) {
if (i < slotsPerNode) {
node1Slots[slot1++] = i;
} else if (i > slotsPerNode * 2) {
node3Slots[slot3++] = i;
} else {
node2Slots[slot2++] = i;
}
}
node1.clusterAddSlots(node1Slots);
node2.clusterAddSlots(node2Slots);
node3.clusterAddSlots(node3Slots);
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
}
@AfterClass
public static void cleanUp() {
node1.flushDB();
node2.flushDB();
node3.flushDB();
node4.flushDB();
node1.clusterReset(Reset.SOFT);
node2.clusterReset(Reset.SOFT);
node3.clusterReset(Reset.SOFT);
node4.clusterReset(Reset.SOFT);
}
@After
public void tearDown() throws InterruptedException {
cleanUp();
}
@Test(expected = JedisMovedDataException.class)
public void testThrowMovedException() {
node1.set("foo", "bar");
}
@Test
public void testMovedExceptionParameters() {
try {
node1.set("foo", "bar");
} catch (JedisMovedDataException jme) {
assertEquals(12182, jme.getSlot());
assertEquals(new HostAndPort("127.0.0.1", 7381), jme.getTargetNode());
return;
}
fail();
}
@Test(expected = JedisAskDataException.class)
public void testThrowAskException() {
int keySlot = JedisClusterCRC16.getSlot("test");
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
node2.clusterSetSlotMigrating(keySlot, node3Id);
node2.get("test");
}
@Test
public void testDiscoverNodesAutomatically() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
assertEquals(3, jc.getClusterNodes().size());
JedisCluster jc2 = new JedisCluster(Collections.singleton(new HostAndPort("127.0.0.1", 7379)),
DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
assertEquals(3, jc2.getClusterNodes().size());
}
@Test
public void testSetClientName() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
String clientName = "myAppName";
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", clientName, DEFAULT_CONFIG);
Map<String, JedisPool> clusterNodes = jc.getClusterNodes();
Collection<JedisPool> values = clusterNodes.values();
for (JedisPool jedisPool : values) {
Jedis jedis = jedisPool.getResource();
try {
assertEquals(clientName, jedis.clientGetname());
} finally {
jedis.close();
}
}
}
@Test
public void testCalculateConnectionPerSlot() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
jc.set("foo", "bar");
jc.set("test", "test");
assertEquals("bar", node3.get("foo"));
assertEquals("test", node2.get("test"));
JedisCluster jc2 = new JedisCluster(Collections.singleton(new HostAndPort("127.0.0.1", 7379)),
DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
jc2.set("foo", "bar");
jc2.set("test", "test");
assertEquals("bar", node3.get("foo"));
assertEquals("test", node2.get("test"));
}
@Test
public void testReadonly() throws Exception {
node1.clusterMeet(localHost, nodeInfoSlave2.getPort());
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3, nodeSlave2);
for (String nodeInfo : node2.clusterNodes().split("\n")) {
if (nodeInfo.contains("myself")) {
nodeSlave2.clusterReplicate(nodeInfo.split(" ")[0]);
break;
}
}
try {
nodeSlave2.get("test");
fail();
} catch (JedisMovedDataException e) {
}
nodeSlave2.readonly();
nodeSlave2.get("test");
nodeSlave2.clusterReset(Reset.SOFT);
nodeSlave2.flushDB();
}
/**
* slot->nodes 15363 node3 e
*/
@Test
public void testMigrate() {
log.info("test migrate slot");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1);
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node2Id = JedisClusterTestUtil.getNodeId(node2.clusterNodes());
node3.clusterSetSlotMigrating(15363, node2Id);
node2.clusterSetSlotImporting(15363, node3Id);
try {
node2.set("e", "e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()), jme.getTargetNode());
}
try {
node3.set("e", "e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()), jae.getTargetNode());
}
jc.set("e", "e");
try {
node2.get("e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()), jme.getTargetNode());
}
try {
node3.get("e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()), jae.getTargetNode());
}
assertEquals("e", jc.get("e"));
node2.clusterSetSlotNode(15363, node2Id);
node3.clusterSetSlotNode(15363, node2Id);
// assertEquals("e", jc.get("e"));
assertEquals("e", node2.get("e"));
// assertEquals("e", node3.get("e"));
}
@Test
public void testMigrateToNewNode() throws InterruptedException {
log.info("test migrate slot to new node");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1);
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
node4.clusterMeet(localHost, nodeInfo1.getPort());
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node4Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
JedisClusterTestUtil.waitForClusterReady(node4);
node3.clusterSetSlotMigrating(15363, node4Id);
node4.clusterSetSlotImporting(15363, node3Id);
try {
node4.set("e", "e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()), jme.getTargetNode());
}
try {
node3.set("e", "e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()), jae.getTargetNode());
}
jc.set("e", "e");
try {
node4.get("e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()), jme.getTargetNode());
}
try {
node3.get("e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()), jae.getTargetNode());
}
assertEquals("e", jc.get("e"));
node4.clusterSetSlotNode(15363, node4Id);
node3.clusterSetSlotNode(15363, node4Id);
// assertEquals("e", jc.get("e"));
assertEquals("e", node4.get("e"));
// assertEquals("e", node3.get("e"));
}
@Test
public void testRecalculateSlotsWhenMoved() throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
int slot51 = JedisClusterCRC16.getSlot("51");
node2.clusterDelSlots(slot51);
node3.clusterDelSlots(slot51);
node3.clusterAddSlots(slot51);
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
jc.set("51", "foo");
assertEquals("foo", jc.get("51"));
}
@Test
public void testAskResponse() throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
int slot51 = JedisClusterCRC16.getSlot("51");
node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo");
assertEquals("foo", jc.get("51"));
}
@Test(expected = JedisClusterMaxRedirectionsException.class)
public void testRedisClusterMaxRedirections() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
int slot51 = JedisClusterCRC16.getSlot("51");
// This will cause an infinite redirection loop
node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo");
}
@Test
public void testRedisHashtag() {
assertEquals(JedisClusterCRC16.getSlot("{bar"), JedisClusterCRC16.getSlot("foo{{bar}}zap"));
assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"),
JedisClusterCRC16.getSlot("{user1000}.followers"));
assertNotEquals(JedisClusterCRC16.getSlot("foo{}{bar}"), JedisClusterCRC16.getSlot("bar"));
assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"), JedisClusterCRC16.getSlot("bar"));
}
@Test
public void testClusterForgetNode() throws InterruptedException {
// at first, join node4 to cluster
node1.clusterMeet("127.0.0.1", nodeInfo4.getPort());
String node7Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
JedisClusterTestUtil.assertNodeIsKnown(node3, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node1, node7Id, 1000);
assertNodeHandshakeEnded(node3, 1000);
assertNodeHandshakeEnded(node2, 1000);
assertNodeHandshakeEnded(node1, 1000);
assertEquals(4, node1.clusterNodes().split("\n").length);
assertEquals(4, node2.clusterNodes().split("\n").length);
assertEquals(4, node3.clusterNodes().split("\n").length);
// do cluster forget
node1.clusterForget(node7Id);
node2.clusterForget(node7Id);
node3.clusterForget(node7Id);
JedisClusterTestUtil.assertNodeIsUnknown(node1, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node3, node7Id, 1000);
assertEquals(3, node1.clusterNodes().split("\n").length);
assertEquals(3, node2.clusterNodes().split("\n").length);
assertEquals(3, node3.clusterNodes().split("\n").length);
}
@Test
public void testClusterFlushSlots() {
String slotRange = getNodeServingSlotRange(node1.clusterNodes());
assertNotNull(slotRange);
try {
node1.clusterFlushSlots();
assertNull(getNodeServingSlotRange(node1.clusterNodes()));
} finally {
// rollback
String[] rangeInfo = slotRange.split("-");
int lower = Integer.parseInt(rangeInfo[0]);
int upper = Integer.parseInt(rangeInfo[1]);
int[] node1Slots = new int[upper - lower + 1];
for (int i = 0; lower <= upper;) {
node1Slots[i++] = lower++;
}
node1.clusterAddSlots(node1Slots);
}
}
@Test
public void testClusterKeySlot() {
// It assumes JedisClusterCRC16 is correctly implemented
assertEquals(node1.clusterKeySlot("foo{bar}zap}").intValue(),
JedisClusterCRC16.getSlot("foo{bar}zap"));
assertEquals(node1.clusterKeySlot("{user1000}.following").intValue(),
JedisClusterCRC16.getSlot("{user1000}.following"));
}
@Test
public void testClusterCountKeysInSlot() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
for (int index = 0; index < 5; index++) {
jc.set("foo{bar}" + index, "hello");
}
int slot = JedisClusterCRC16.getSlot("foo{bar}");
assertEquals(DEFAULT_REDIRECTIONS, node1.clusterCountKeysInSlot(slot).intValue());
}
@Test
public void testStableSlotWhenMigratingNodeOrImportingNodeIsNotSpecified()
throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
int slot51 = JedisClusterCRC16.getSlot("51");
jc.set("51", "foo");
// node2 is responsible of taking care of slot51 (7186)
node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
assertEquals("foo", jc.get("51"));
node3.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51"));
node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
// assertEquals("foo", jc.get("51")); // it leads Max Redirections
node2.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51"));
}
@Test(expected = JedisExhaustedPoolException.class)
public void testIfPoolConfigAppliesToClusterPools() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(0);
config.setMaxWaitMillis(DEFAULT_TIMEOUT);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", config);
jc.set("52", "poolTestValue");
}
@Test
public void testCloseable() throws IOException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort()));
JedisCluster jc = null;
try {
jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
jc.set("51", "foo");
} finally {
if (jc != null) {
jc.close();
}
}
Iterator<JedisPool> poolIterator = jc.getClusterNodes().values().iterator();
while (poolIterator.hasNext()) {
JedisPool pool = poolIterator.next();
try {
pool.getResource();
fail("JedisCluster's internal pools should be already destroyed");
} catch (JedisConnectionException e) {
// ok to go...
}
}
}
@Test
public void testJedisClusterTimeout() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode, 4000, 4000, DEFAULT_REDIRECTIONS,
"cluster", DEFAULT_CONFIG);
for (JedisPool pool : jc.getClusterNodes().values()) {
Jedis jedis = pool.getResource();
assertEquals(jedis.getClient().getConnectionTimeout(), 4000);
assertEquals(jedis.getClient().getSoTimeout(), 4000);
jedis.close();
}
}
@Test
public void testJedisClusterRunsWithMultithreaded() throws InterruptedException,
ExecutionException, IOException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
final JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
jc.set("foo", "bar");
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 0, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10));
List<Future<String>> futures = new ArrayList<Future<String>>();
for (int i = 0; i < 50; i++) {
executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// FIXME : invalidate slot cache from JedisCluster to test
// random connection also does work
return jc.get("foo");
}
});
}
for (Future<String> future : futures) {
String value = future.get();
assertEquals("bar", value);
}
jc.close();
}
@Test(timeout = DEFAULT_TIMEOUT)
public void testReturnConnectionOnJedisConnectionException() throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisPoolConfig config = DEFAULT_CONFIG;
config.setMaxTotal(1);
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", config);
Jedis j = jc.getClusterNodes().get("127.0.0.1:7380").getResource();
ClientKillerUtil.tagClient(j, "DEAD");
ClientKillerUtil.killClient(j, "DEAD");
j.close();
jc.get("test");
}
@Test(expected = JedisClusterMaxRedirectionsException.class, timeout = DEFAULT_TIMEOUT)
public void testReturnConnectionOnRedirection() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisPoolConfig config = DEFAULT_CONFIG;
config.setMaxTotal(1);
JedisCluster jc = new JedisCluster(jedisClusterNode, 0, 2, DEFAULT_REDIRECTIONS, "cluster",
config);
// This will cause an infinite redirection between node 2 and 3
node3.clusterSetSlotMigrating(15363, JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
jc.get("e");
}
@Test
public void testLocalhostNodeNotAddedWhen127Present() {
HostAndPort localhost = new HostAndPort("localhost", 7379);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
// cluster node is defined as 127.0.0.1; adding localhost should work,
// but shouldn't show up.
jedisClusterNode.add(localhost);
JedisPoolConfig config = DEFAULT_CONFIG;
config.setMaxTotal(1);
JedisCluster jc = new JedisCluster(jedisClusterNode, 0, 2, DEFAULT_REDIRECTIONS, "cluster",
DEFAULT_CONFIG);
Map<String, JedisPool> clusterNodes = jc.getClusterNodes();
assertEquals(3, clusterNodes.size());
assertFalse(clusterNodes.containsKey(JedisClusterInfoCache.getNodeKey(localhost)));
}
@Test
public void testInvalidStartNodeNotAdded() {
HostAndPort invalidHost = new HostAndPort("not-a-real-host", 7379);
Set<HostAndPort> jedisClusterNode = new LinkedHashSet<HostAndPort>();
jedisClusterNode.add(invalidHost);
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisPoolConfig config = DEFAULT_CONFIG;
config.setMaxTotal(1);
JedisCluster jc = new JedisCluster(jedisClusterNode, 0, 2, DEFAULT_REDIRECTIONS, "cluster",
config);
Map<String, JedisPool> clusterNodes = jc.getClusterNodes();
assertEquals(3, clusterNodes.size());
assertFalse(clusterNodes.containsKey(JedisClusterInfoCache.getNodeKey(invalidHost)));
}
private static String getNodeServingSlotRange(String infoOutput) {
// f4f3dc4befda352a4e0beccf29f5e8828438705d 127.0.0.1:7380 master - 0
// 1394372400827 0 connected 5461-10922
for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("myself")) {
try {
return infoLine.split(" ")[8];
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
}
}
return null;
}
private void assertNodeHandshakeEnded(Jedis node, int timeoutMs) {
int sleepInterval = 100;
for (int sleepTime = 0; sleepTime <= timeoutMs; sleepTime += sleepInterval) {
boolean isHandshaking = isAnyNodeHandshaking(node);
if (!isHandshaking) return;
try {
Thread.sleep(sleepInterval);
} catch (InterruptedException e) {
}
}
throw new JedisException("Node handshaking is not ended");
}
private boolean isAnyNodeHandshaking(Jedis node) {
String infoOutput = node.clusterNodes();
for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("handshake")) {
return true;
}
}
return false;
}
}
|
src/test/java/redis/clients/jedis/tests/JedisClusterTest.java
|
package redis.clients.jedis.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.BinaryJedisCluster.Reset;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisClusterInfoCache;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.*;
import redis.clients.jedis.tests.utils.ClientKillerUtil;
import redis.clients.jedis.tests.utils.JedisClusterTestUtil;
import redis.clients.util.JedisClusterCRC16;
public class JedisClusterTest {
private static Jedis node1;
private static Jedis node2;
private static Jedis node3;
private static Jedis node4;
private static Jedis nodeSlave2;
private String localHost = "127.0.0.1";
private static final int DEFAULT_TIMEOUT = 2000;
private static final int DEFAULT_REDIRECTIONS = 5;
private static final JedisPoolConfig DEFAULT_CONFIG = new JedisPoolConfig();
private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0);
private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1);
private HostAndPort nodeInfo3 = HostAndPortUtil.getClusterServers().get(2);
private HostAndPort nodeInfo4 = HostAndPortUtil.getClusterServers().get(3);
private HostAndPort nodeInfoSlave2 = HostAndPortUtil.getClusterServers().get(4);
protected Logger log = LoggerFactory.getLogger(getClass().getName());
@Before
public void setUp() throws InterruptedException {
node1 = new Jedis(nodeInfo1);
node1.auth("cluster");
node1.flushAll();
node2 = new Jedis(nodeInfo2);
node2.auth("cluster");
node2.flushAll();
node3 = new Jedis(nodeInfo3);
node3.auth("cluster");
node3.flushAll();
node4 = new Jedis(nodeInfo4);
node4.auth("cluster");
node4.flushAll();
nodeSlave2 = new Jedis(nodeInfoSlave2);
nodeSlave2.auth("cluster");
nodeSlave2.flushAll();
// ---- configure cluster
// add nodes to cluster
node1.clusterMeet(localHost, nodeInfo2.getPort());
node1.clusterMeet(localHost, nodeInfo3.getPort());
// split available slots across the three nodes
int slotsPerNode = JedisCluster.HASHSLOTS / 3;
int[] node1Slots = new int[slotsPerNode];
int[] node2Slots = new int[slotsPerNode + 1];
int[] node3Slots = new int[slotsPerNode];
for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < JedisCluster.HASHSLOTS; i++) {
if (i < slotsPerNode) {
node1Slots[slot1++] = i;
} else if (i > slotsPerNode * 2) {
node3Slots[slot3++] = i;
} else {
node2Slots[slot2++] = i;
}
}
node1.clusterAddSlots(node1Slots);
node2.clusterAddSlots(node2Slots);
node3.clusterAddSlots(node3Slots);
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
}
@AfterClass
public static void cleanUp() {
node1.flushDB();
node2.flushDB();
node3.flushDB();
node4.flushDB();
node1.clusterReset(Reset.SOFT);
node2.clusterReset(Reset.SOFT);
node3.clusterReset(Reset.SOFT);
node4.clusterReset(Reset.SOFT);
}
@After
public void tearDown() throws InterruptedException {
cleanUp();
}
@Test(expected = JedisMovedDataException.class)
public void testThrowMovedException() {
node1.set("foo", "bar");
}
@Test
public void testMovedExceptionParameters() {
try {
node1.set("foo", "bar");
} catch (JedisMovedDataException jme) {
assertEquals(12182, jme.getSlot());
assertEquals(new HostAndPort("127.0.0.1", 7381), jme.getTargetNode());
return;
}
fail();
}
@Test(expected = JedisAskDataException.class)
public void testThrowAskException() {
int keySlot = JedisClusterCRC16.getSlot("test");
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
node2.clusterSetSlotMigrating(keySlot, node3Id);
node2.get("test");
}
@Test
public void testDiscoverNodesAutomatically() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
assertEquals(3, jc.getClusterNodes().size());
JedisCluster jc2 = new JedisCluster(new HostAndPort("127.0.0.1", 7379), DEFAULT_TIMEOUT,
DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
assertEquals(3, jc2.getClusterNodes().size());
}
@Test
public void testSetClientName() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
String clientName = "myAppName";
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", clientName, DEFAULT_CONFIG);
Map<String, JedisPool> clusterNodes = jc.getClusterNodes();
Collection<JedisPool> values = clusterNodes.values();
for (JedisPool jedisPool : values) {
Jedis jedis = jedisPool.getResource();
try {
assertEquals(clientName, jedis.clientGetname());
} finally {
jedis.close();
}
}
}
@Test
public void testCalculateConnectionPerSlot() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
jc.set("foo", "bar");
jc.set("test", "test");
assertEquals("bar", node3.get("foo"));
assertEquals("test", node2.get("test"));
JedisCluster jc2 = new JedisCluster(new HostAndPort("127.0.0.1", 7379), DEFAULT_TIMEOUT,
DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
jc2.set("foo", "bar");
jc2.set("test", "test");
assertEquals("bar", node3.get("foo"));
assertEquals("test", node2.get("test"));
}
@Test
public void testReadonly() throws Exception {
node1.clusterMeet(localHost, nodeInfoSlave2.getPort());
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3, nodeSlave2);
for (String nodeInfo : node2.clusterNodes().split("\n")) {
if (nodeInfo.contains("myself")) {
nodeSlave2.clusterReplicate(nodeInfo.split(" ")[0]);
break;
}
}
try {
nodeSlave2.get("test");
fail();
} catch (JedisMovedDataException e) {
}
nodeSlave2.readonly();
nodeSlave2.get("test");
nodeSlave2.clusterReset(Reset.SOFT);
nodeSlave2.flushDB();
}
/**
* slot->nodes 15363 node3 e
*/
@Test
public void testMigrate() {
log.info("test migrate slot");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1);
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node2Id = JedisClusterTestUtil.getNodeId(node2.clusterNodes());
node3.clusterSetSlotMigrating(15363, node2Id);
node2.clusterSetSlotImporting(15363, node3Id);
try {
node2.set("e", "e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()), jme.getTargetNode());
}
try {
node3.set("e", "e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()), jae.getTargetNode());
}
jc.set("e", "e");
try {
node2.get("e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()), jme.getTargetNode());
}
try {
node3.get("e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo2.getPort()), jae.getTargetNode());
}
assertEquals("e", jc.get("e"));
node2.clusterSetSlotNode(15363, node2Id);
node3.clusterSetSlotNode(15363, node2Id);
// assertEquals("e", jc.get("e"));
assertEquals("e", node2.get("e"));
// assertEquals("e", node3.get("e"));
}
@Test
public void testMigrateToNewNode() throws InterruptedException {
log.info("test migrate slot to new node");
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(nodeInfo1);
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
node4.clusterMeet(localHost, nodeInfo1.getPort());
String node3Id = JedisClusterTestUtil.getNodeId(node3.clusterNodes());
String node4Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
JedisClusterTestUtil.waitForClusterReady(node4);
node3.clusterSetSlotMigrating(15363, node4Id);
node4.clusterSetSlotImporting(15363, node3Id);
try {
node4.set("e", "e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()), jme.getTargetNode());
}
try {
node3.set("e", "e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()), jae.getTargetNode());
}
jc.set("e", "e");
try {
node4.get("e");
} catch (JedisMovedDataException jme) {
assertEquals(15363, jme.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo3.getPort()), jme.getTargetNode());
}
try {
node3.get("e");
} catch (JedisAskDataException jae) {
assertEquals(15363, jae.getSlot());
assertEquals(new HostAndPort(localHost, nodeInfo4.getPort()), jae.getTargetNode());
}
assertEquals("e", jc.get("e"));
node4.clusterSetSlotNode(15363, node4Id);
node3.clusterSetSlotNode(15363, node4Id);
// assertEquals("e", jc.get("e"));
assertEquals("e", node4.get("e"));
// assertEquals("e", node3.get("e"));
}
@Test
public void testRecalculateSlotsWhenMoved() throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
int slot51 = JedisClusterCRC16.getSlot("51");
node2.clusterDelSlots(slot51);
node3.clusterDelSlots(slot51);
node3.clusterAddSlots(slot51);
JedisClusterTestUtil.waitForClusterReady(node1, node2, node3);
jc.set("51", "foo");
assertEquals("foo", jc.get("51"));
}
@Test
public void testAskResponse() throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
int slot51 = JedisClusterCRC16.getSlot("51");
node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo");
assertEquals("foo", jc.get("51"));
}
@Test(expected = JedisClusterMaxRedirectionsException.class)
public void testRedisClusterMaxRedirections() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
int slot51 = JedisClusterCRC16.getSlot("51");
// This will cause an infinite redirection loop
node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
jc.set("51", "foo");
}
@Test
public void testRedisHashtag() {
assertEquals(JedisClusterCRC16.getSlot("{bar"), JedisClusterCRC16.getSlot("foo{{bar}}zap"));
assertEquals(JedisClusterCRC16.getSlot("{user1000}.following"),
JedisClusterCRC16.getSlot("{user1000}.followers"));
assertNotEquals(JedisClusterCRC16.getSlot("foo{}{bar}"), JedisClusterCRC16.getSlot("bar"));
assertEquals(JedisClusterCRC16.getSlot("foo{bar}{zap}"), JedisClusterCRC16.getSlot("bar"));
}
@Test
public void testClusterForgetNode() throws InterruptedException {
// at first, join node4 to cluster
node1.clusterMeet("127.0.0.1", nodeInfo4.getPort());
String node7Id = JedisClusterTestUtil.getNodeId(node4.clusterNodes());
JedisClusterTestUtil.assertNodeIsKnown(node3, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsKnown(node1, node7Id, 1000);
assertNodeHandshakeEnded(node3, 1000);
assertNodeHandshakeEnded(node2, 1000);
assertNodeHandshakeEnded(node1, 1000);
assertEquals(4, node1.clusterNodes().split("\n").length);
assertEquals(4, node2.clusterNodes().split("\n").length);
assertEquals(4, node3.clusterNodes().split("\n").length);
// do cluster forget
node1.clusterForget(node7Id);
node2.clusterForget(node7Id);
node3.clusterForget(node7Id);
JedisClusterTestUtil.assertNodeIsUnknown(node1, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node2, node7Id, 1000);
JedisClusterTestUtil.assertNodeIsUnknown(node3, node7Id, 1000);
assertEquals(3, node1.clusterNodes().split("\n").length);
assertEquals(3, node2.clusterNodes().split("\n").length);
assertEquals(3, node3.clusterNodes().split("\n").length);
}
@Test
public void testClusterFlushSlots() {
String slotRange = getNodeServingSlotRange(node1.clusterNodes());
assertNotNull(slotRange);
try {
node1.clusterFlushSlots();
assertNull(getNodeServingSlotRange(node1.clusterNodes()));
} finally {
// rollback
String[] rangeInfo = slotRange.split("-");
int lower = Integer.parseInt(rangeInfo[0]);
int upper = Integer.parseInt(rangeInfo[1]);
int[] node1Slots = new int[upper - lower + 1];
for (int i = 0; lower <= upper;) {
node1Slots[i++] = lower++;
}
node1.clusterAddSlots(node1Slots);
}
}
@Test
public void testClusterKeySlot() {
// It assumes JedisClusterCRC16 is correctly implemented
assertEquals(node1.clusterKeySlot("foo{bar}zap}").intValue(),
JedisClusterCRC16.getSlot("foo{bar}zap"));
assertEquals(node1.clusterKeySlot("{user1000}.following").intValue(),
JedisClusterCRC16.getSlot("{user1000}.following"));
}
@Test
public void testClusterCountKeysInSlot() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
for (int index = 0; index < 5; index++) {
jc.set("foo{bar}" + index, "hello");
}
int slot = JedisClusterCRC16.getSlot("foo{bar}");
assertEquals(DEFAULT_REDIRECTIONS, node1.clusterCountKeysInSlot(slot).intValue());
}
@Test
public void testStableSlotWhenMigratingNodeOrImportingNodeIsNotSpecified()
throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
int slot51 = JedisClusterCRC16.getSlot("51");
jc.set("51", "foo");
// node2 is responsible of taking care of slot51 (7186)
node3.clusterSetSlotImporting(slot51, JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
assertEquals("foo", jc.get("51"));
node3.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51"));
node2.clusterSetSlotMigrating(slot51, JedisClusterTestUtil.getNodeId(node3.clusterNodes()));
// assertEquals("foo", jc.get("51")); // it leads Max Redirections
node2.clusterSetSlotStable(slot51);
assertEquals("foo", jc.get("51"));
}
@Test(expected = JedisExhaustedPoolException.class)
public void testIfPoolConfigAppliesToClusterPools() {
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(0);
config.setMaxWaitMillis(DEFAULT_TIMEOUT);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", config);
jc.set("52", "poolTestValue");
}
@Test
public void testCloseable() throws IOException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort()));
JedisCluster jc = null;
try {
jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
jc.set("51", "foo");
} finally {
if (jc != null) {
jc.close();
}
}
Iterator<JedisPool> poolIterator = jc.getClusterNodes().values().iterator();
while (poolIterator.hasNext()) {
JedisPool pool = poolIterator.next();
try {
pool.getResource();
fail("JedisCluster's internal pools should be already destroyed");
} catch (JedisConnectionException e) {
// ok to go...
}
}
}
@Test
public void testJedisClusterTimeout() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort()));
JedisCluster jc = new JedisCluster(jedisClusterNode, 4000, 4000, DEFAULT_REDIRECTIONS,
"cluster", DEFAULT_CONFIG);
for (JedisPool pool : jc.getClusterNodes().values()) {
Jedis jedis = pool.getResource();
assertEquals(jedis.getClient().getConnectionTimeout(), 4000);
assertEquals(jedis.getClient().getSoTimeout(), 4000);
jedis.close();
}
}
@Test
public void testJedisClusterRunsWithMultithreaded() throws InterruptedException,
ExecutionException, IOException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
final JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
jc.set("foo", "bar");
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 0, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10));
List<Future<String>> futures = new ArrayList<Future<String>>();
for (int i = 0; i < 50; i++) {
executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// FIXME : invalidate slot cache from JedisCluster to test
// random connection also does work
return jc.get("foo");
}
});
}
for (Future<String> future : futures) {
String value = future.get();
assertEquals("bar", value);
}
jc.close();
}
@Test(timeout = DEFAULT_TIMEOUT)
public void testReturnConnectionOnJedisConnectionException() throws InterruptedException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisPoolConfig config = DEFAULT_CONFIG;
config.setMaxTotal(1);
JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT,
DEFAULT_REDIRECTIONS, "cluster", config);
Jedis j = jc.getClusterNodes().get("127.0.0.1:7380").getResource();
ClientKillerUtil.tagClient(j, "DEAD");
ClientKillerUtil.killClient(j, "DEAD");
j.close();
jc.get("test");
}
@Test(expected = JedisClusterMaxRedirectionsException.class, timeout = DEFAULT_TIMEOUT)
public void testReturnConnectionOnRedirection() {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisPoolConfig config = DEFAULT_CONFIG;
config.setMaxTotal(1);
JedisCluster jc = new JedisCluster(jedisClusterNode, 0, 2, DEFAULT_REDIRECTIONS, "cluster",
config);
// This will cause an infinite redirection between node 2 and 3
node3.clusterSetSlotMigrating(15363, JedisClusterTestUtil.getNodeId(node2.clusterNodes()));
jc.get("e");
}
@Test
public void testLocalhostNodeNotAddedWhen127Present() {
HostAndPort localhost = new HostAndPort("localhost", 7379);
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
// cluster node is defined as 127.0.0.1; adding localhost should work,
// but shouldn't show up.
jedisClusterNode.add(localhost);
JedisPoolConfig config = DEFAULT_CONFIG;
config.setMaxTotal(1);
JedisCluster jc = new JedisCluster(jedisClusterNode, 0, 2, DEFAULT_REDIRECTIONS, "cluster",
DEFAULT_CONFIG);
Map<String, JedisPool> clusterNodes = jc.getClusterNodes();
assertEquals(3, clusterNodes.size());
assertFalse(clusterNodes.containsKey(JedisClusterInfoCache.getNodeKey(localhost)));
}
@Test
public void testInvalidStartNodeNotAdded() {
HostAndPort invalidHost = new HostAndPort("not-a-real-host", 7379);
Set<HostAndPort> jedisClusterNode = new LinkedHashSet<HostAndPort>();
jedisClusterNode.add(invalidHost);
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
JedisPoolConfig config = DEFAULT_CONFIG;
config.setMaxTotal(1);
JedisCluster jc = new JedisCluster(jedisClusterNode, 0, 2, DEFAULT_REDIRECTIONS, "cluster",
config);
Map<String, JedisPool> clusterNodes = jc.getClusterNodes();
assertEquals(3, clusterNodes.size());
assertFalse(clusterNodes.containsKey(JedisClusterInfoCache.getNodeKey(invalidHost)));
}
private static String getNodeServingSlotRange(String infoOutput) {
// f4f3dc4befda352a4e0beccf29f5e8828438705d 127.0.0.1:7380 master - 0
// 1394372400827 0 connected 5461-10922
for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("myself")) {
try {
return infoLine.split(" ")[8];
} catch (ArrayIndexOutOfBoundsException e) {
return null;
}
}
}
return null;
}
private void assertNodeHandshakeEnded(Jedis node, int timeoutMs) {
int sleepInterval = 100;
for (int sleepTime = 0; sleepTime <= timeoutMs; sleepTime += sleepInterval) {
boolean isHandshaking = isAnyNodeHandshaking(node);
if (!isHandshaking) return;
try {
Thread.sleep(sleepInterval);
} catch (InterruptedException e) {
}
}
throw new JedisException("Node handshaking is not ended");
}
private boolean isAnyNodeHandshaking(Jedis node) {
String infoOutput = node.clusterNodes();
for (String infoLine : infoOutput.split("\n")) {
if (infoLine.contains("handshake")) {
return true;
}
}
return false;
}
}
|
Fix erroneous tests.
|
src/test/java/redis/clients/jedis/tests/JedisClusterTest.java
|
Fix erroneous tests.
|
|
Java
|
mit
|
6971c75a4d35130d54b1f1768d6a3ffca648f461
| 0
|
AzureAD/azure-activedirectory-library-for-android,AzureAD/azure-activedirectory-library-for-android
|
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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 com.microsoft.aad.adal;
import android.content.Context;
import android.os.Handler;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Matching to ADAL.NET It provides helper methods to get the
* authorization_endpoint from resource address.
*/
public class AuthenticationParameters {
/**
* WWW-Authenticate header is missing authorization_uri.
*/
public static final String AUTH_HEADER_MISSING_AUTHORITY = "WWW-Authenticate header is missing authorization_uri.";
/**
* Invalid authentication header format.
*/
public static final String AUTH_HEADER_INVALID_FORMAT = "Invalid authentication header format";
/**
* WWW-Authenticate header was expected in the response.
*/
public static final String AUTH_HEADER_MISSING = "WWW-Authenticate header was expected in the response";
/**
* Unauthorized http response (status code 401) was expected.
*/
public static final String AUTH_HEADER_WRONG_STATUS = "Unauthorized http response (status code 401) was expected";
/**
* Constant Authenticate header: WWW-Authenticate.
*/
public static final String AUTHENTICATE_HEADER = "WWW-Authenticate";
/**
* Constant Bearer.
*/
public static final String BEARER = "bearer";
/**
* Constant Authority key.
*/
public static final String AUTHORITY_KEY = "authorization_uri";
/**
* Constant Resource key.
*/
public static final String RESOURCE_KEY = "resource_id";
private static final String TAG = "AuthenticationParameters";
private String mAuthority;
private String mResource;
/**
* Web request handler interface to test behaviors.
*/
private static IWebRequestHandler sWebRequest = new WebRequestHandler();
/**
* Singled threaded Executor for async work.
*/
private static ExecutorService sThreadExecutor = Executors.newSingleThreadExecutor();
/**
* get authority from the header.
*
* @return Authority extracted from the header.
*/
public String getAuthority() {
return mAuthority;
}
/**
* get resource from the header.
*
* @return resource from the header.
*/
public String getResource() {
return mResource;
}
/**
* Creates AuthenticationParameters.
*/
public AuthenticationParameters() {
}
AuthenticationParameters(String authority, String resource) {
mAuthority = authority;
mResource = resource;
}
/**
* Callback to use for async request.
*/
public interface AuthenticationParamCallback {
/**
* @param exception {@link Exception}
* @param param {@link AuthenticationParameters}
*/
void onCompleted(Exception exception, AuthenticationParameters param);
}
/**
* ADAL will make the call to get authority and resource info.
*
* @param context {@link Context}
* @param resourceUrl Url for resource to query for 401 response.
* @param callback {@link AuthenticationParamCallback}
*/
public static void createFromResourceUrl(Context context, final URL resourceUrl,
final AuthenticationParamCallback callback) {
if (callback == null) {
throw new IllegalArgumentException("callback");
}
Logger.v(TAG, "createFromResourceUrl");
final Handler handler = new Handler(context.getMainLooper());
sThreadExecutor.submit(new Runnable() {
@Override
public void run() {
final Map<String, String> headers = new HashMap<>();
headers.put(WebRequestHandler.HEADER_ACCEPT, WebRequestHandler.HEADER_ACCEPT_JSON);
final HttpWebResponse webResponse;
try {
webResponse = sWebRequest.sendGet(resourceUrl, headers);
try {
onCompleted(null, parseResponse(webResponse));
} catch (ResourceAuthenticationChallengeException exc) {
onCompleted(exc, null);
}
} catch (IOException e) {
onCompleted(e, null);
}
}
void onCompleted(final Exception exception, final AuthenticationParameters param) {
handler.post(new Runnable() {
@Override
public void run() {
callback.onCompleted(exception, param);
}
});
}
});
}
/**
* ADAL will parse the header response to get the authority and the resource
* info.
*
* @param authenticateHeader Header to check authority and resource.
* @return {@link AuthenticationParameters}
* @throws {@link ResourceAuthenticationChallengeException}
*/
public static AuthenticationParameters createFromResponseAuthenticateHeader(final String authenticateHeader)
throws ResourceAuthenticationChallengeException {
if (StringExtensions.isNullOrBlank(authenticateHeader)) {
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_MISSING);
}
//testing...
final List<Challenge> challenges = Challenge.parseChallenges(authenticateHeader);
// Grab the Bearer challenge
Challenge bearerChallenge = null;
for (final Challenge challenge : challenges) {
if (challenge.getScheme().equalsIgnoreCase(BEARER)) {
bearerChallenge = challenge;
break;
}
}
if (null != bearerChallenge) {
final Map<String, String> challengeParams = bearerChallenge.getParameters();
String authority = challengeParams.get(AUTHORITY_KEY);
String resource = challengeParams.get(RESOURCE_KEY);
if (StringExtensions.isNullOrBlank(authority)) {
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_MISSING_AUTHORITY);
}
// Remove wrapping quotes (if present)
authority = authority.replaceAll("^\"|\"$", "");
if (StringExtensions.isNullOrBlank(authority)) {
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_MISSING_AUTHORITY);
}
if (!StringExtensions.isNullOrBlank(resource)) {
resource = resource.replaceAll("^\"|\"$", "");
}
return new AuthenticationParameters(authority, resource);
}
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_INVALID_FORMAT);
}
/**
* An authentication challenge.
* Format follows <a href="https://tools.ietf.org/html/rfc7235#section-4.1">RFC-7235</a>.
*
* @see <a href-"https://tools.ietf.org/html/rfc7617">RFC-7617</a>
* @see <a href="https://tools.ietf.org/html/rfc6750">RFC-6750</a>
*/
private static class Challenge {
/**
* Regex sequence intended to be prefixed with another value. Whichever value precedes it
* will be parsed/grouped-out, assuming it is not bounded by a par of double-quotes ("").
*/
private static final String REGEX_UNQUOTED_LOOKAHEAD = "(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)";
/**
* Regex sequence to parse unquoted equals (=) signs.
*/
private static final String REGEX_SPLIT_UNQUOTED_EQUALS = "=" + REGEX_UNQUOTED_LOOKAHEAD;
/**
* Regex sequence to parse unquoted commas (,).
*/
private static final String REGEX_SPLIT_UNQUOTED_COMMA = "," + REGEX_UNQUOTED_LOOKAHEAD;
/**
* Regex sequence to parse schemes from WWW-Authenticate header values.
*/
private static final String REGEX_STRING_TOKEN_WITH_SCHEME = "^([^\\s|^=]+)[\\s|\\t]+([^=]*=[^=]*)+$";
/**
* Comma+space suffix used to preserve formatting during parsing.
*/
private static final String SUFFIX_COMMA = ", ";
/**
* The authentication scheme of this challenge (ex. Basic, Bearer).
*/
private String mScheme;
/**
* The parameters of this scheme (ex. realm, authoritization_uri, scope).
*/
private Map<String, String> mParameters;
/**
* Constructs a new Challenge.
*
* @param scheme The scheme used by this challenge.
* @param params The params which accompany this challenge.
*/
private Challenge(final String scheme, final Map<String, String> params) {
mScheme = scheme;
mParameters = params;
}
/**
* Gets the scheme.
*
* @return The scheme to get.
*/
public String getScheme() {
return mScheme;
}
/**
* Gets the parameters.
*
* @return The parameters to get.
*/
public Map<String, String> getParameters() {
return mParameters;
}
/**
* Parses a single challenge String, typically the value field of a WWW-Authenticate header.
*
* @param challenge The challenge String to parse.
* @return The Challenge object derived from challenge.
* @throws ResourceAuthenticationChallengeException If a parsing error is encountered or
* the String is malformed.
*/
static Challenge parseChallenge(final String challenge) throws ResourceAuthenticationChallengeException {
final String scheme = parseScheme(challenge);
Logger.d(TAG, "Parsing scheme: " + scheme);
final String challengeSansScheme = challenge.substring(scheme.length() + 1);
final Map<String, String> params = parseParams(challengeSansScheme);
return new Challenge(scheme, params);
}
/**
* Parses the scheme of a challenge String.
*
* @param challenge The challenge String to parse.
* @return The scheme portion of the challenge String.
* @throws ResourceAuthenticationChallengeException If a parsing error is encountered or
* the String is malformed.
*/
private static String parseScheme(String challenge) throws ResourceAuthenticationChallengeException {
final int indexOfFirstSpace = challenge.indexOf(' ');
final int indexOfFirstTab = challenge.indexOf('\t');
// We want to grab the lesser of these values so long as they're > -1...
if (indexOfFirstSpace < 0 && indexOfFirstTab < 0) {
return challenge;
}
// If there is a space and it occurs before the first tab character.
if (indexOfFirstSpace > -1 && (indexOfFirstSpace < indexOfFirstTab || indexOfFirstTab < 0)) {
return challenge.substring(0, indexOfFirstSpace);
}
// If there is a tab character and it occurs before the first space character.
if (indexOfFirstTab > -1 && (indexOfFirstTab < indexOfFirstSpace || indexOfFirstSpace < 0)) {
return challenge.substring(0, indexOfFirstTab);
}
// Unexpected/malformed/missing scheme.
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_INVALID_FORMAT);
}
/**
* Parses the parameters of a challenge String which has had its scheme removed
* (from its prefix).
*
* @param challengeSansScheme The challenge String, minus the scheme.
* @return A Map of the keys/values in the parsed parameters.
* @throws ResourceAuthenticationChallengeException If a parsing error is encountered or
* the String is malformed.
*/
private static Map<String, String> parseParams(String challengeSansScheme) throws ResourceAuthenticationChallengeException {
if (StringExtensions.isNullOrBlank(challengeSansScheme)) {
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_INVALID_FORMAT);
}
// Split on unquoted commas
final Map<String, String> params = new HashMap<>();
final String[] splitOnUnquotedCommas = challengeSansScheme.split(REGEX_SPLIT_UNQUOTED_COMMA, -1);
for (final String paramSet : splitOnUnquotedCommas) {
// Split keys/values by the '='
final String[] splitOnUnquotedEquals = paramSet.split(REGEX_SPLIT_UNQUOTED_EQUALS, -1);
// We should now have a left-side and right-side
if (splitOnUnquotedEquals.length != 2) {
// Is this really what you want?
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_INVALID_FORMAT);
//continue; // If there's no key/value pair, skip this token
}
// Create the keys/values, trimming off any bogus whitespace
final String key = splitOnUnquotedEquals[0].trim();
final String value = splitOnUnquotedEquals[1].trim();
// if there is already a mapping for this key, we've seen this value before
// and should log a warning that this header looks fishy....
if (params.containsKey(key)) {
Logger.w(TAG,
"Key/value pair list contains redundant key. ",
"Redundant key: " + key,
ADALError.DEVELOPER_BEARER_HEADER_MULTIPLE_ITEMS);
}
// Add the key/value to the Map
params.put(key, value);
}
if (params.isEmpty()) { // To match the existing expected behavior, an Exception is thrown.
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_INVALID_FORMAT);
}
return params;
}
/**
* Parses multiple challenges in a single String, typically the value field of a WWW-Authenticate header.
*
* @param strChallenges The challenge String to parse.
* @return The Challenge object derived from challenge.
* @throws ResourceAuthenticationChallengeException If a parsing error is encountered or
* the String is malformed.
*/
static List<Challenge> parseChallenges(final String strChallenges) throws ResourceAuthenticationChallengeException {
// Initialize and out-List for our result.
final List<Challenge> challenges = new ArrayList<>();
try { // Separate the challenges.
List<String> strChallengesList = separateChallenges(strChallenges);
// Add each to the out-List
for (final String challenge : strChallengesList) {
challenges.add(parseChallenge(challenge));
}
} catch (ResourceAuthenticationChallengeException e) {
throw e;
} catch (Exception e) {
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_INVALID_FORMAT);
}
return challenges;
}
/**
* For multiple challenges in a WWW-Authenticate header value, separate them into multiple
* Strings for parsing.
*
* @param challenges The challenge values to parse.
* @return A List of separated challenges.
*/
private static List<String> separateChallenges(final String challenges) {
// Split the supplied String on those commas which are not constrained by quotes
String[] splitOnUnquotedCommas = challenges.split(REGEX_SPLIT_UNQUOTED_COMMA, -1);
sanitizeWhitespace(splitOnUnquotedCommas);
List<String> tokensContainingScheme = extractTokensContainingScheme(splitOnUnquotedCommas);
// init an array to store the out-values
String[] outStrings = new String[tokensContainingScheme.size()];
for (int ii = 0; ii < outStrings.length; ii++) {
outStrings[ii] = "";
}
writeParsedChallenges(splitOnUnquotedCommas, tokensContainingScheme, outStrings);
// Remove the suffix comma from the last element of each list...
sanitizeParsedSuffixes(outStrings);
// Collapse the results to a single list...
return Arrays.asList(outStrings);
}
/**
* Writes the parsed challenges to an output array.
*
* @param splitOnUnquotedCommas The challenge String, split on unquoted commas.
* @param tokensContainingScheme String tokens in the target challenge which contain a
* scheme element.
* @param outStrings The output array, modified in-place.
*/
private static void writeParsedChallenges(String[] splitOnUnquotedCommas, List<String> tokensContainingScheme, String[] outStrings) {
int ii = -1; // Out-value index
for (final String token : splitOnUnquotedCommas) {
if (tokensContainingScheme.contains(token)) {
// this is the start of a challenge...
outStrings[++ii] = token + SUFFIX_COMMA;
} else {
outStrings[ii] += token + SUFFIX_COMMA;
}
}
}
/**
* Removes trailing (suffixed) comma values from Strings in the supplied array.
*
* @param outStrings The String array to sanitize.
*/
private static void sanitizeParsedSuffixes(String[] outStrings) {
for (int jj = 0; jj < outStrings.length; jj++) {
if (outStrings[jj].endsWith(SUFFIX_COMMA)) {
outStrings[jj] = outStrings[jj].substring(0, outStrings[jj].length() - 2);
}
}
}
/**
* Extract a List of String tokens containing scheme elements from the supplied array.
*
* @param strArry The String array to inspect.
* @return A List of scheme-containing String tokens.
*/
private static List<String> extractTokensContainingScheme(final String[] strArry) {
final List<String> tokensContainingScheme = new ArrayList<>();
for (final String token : strArry) {
if (containsScheme(token)) {
tokensContainingScheme.add(token);
}
}
return tokensContainingScheme;
}
/**
* Heuristically check if a given String contains a scheme element.
*
* @param token The String token to inspect.
* @return True, if it contains a scheme. False otherwise.
*/
private static boolean containsScheme(final String token) {
final Pattern startWithScheme = Pattern.compile(REGEX_STRING_TOKEN_WITH_SCHEME);
final Matcher matcher = startWithScheme.matcher(token);
return matcher.matches();
}
/**
* Trim whitespace from each array element.
*
* @param strArray The target String[].
*/
private static void sanitizeWhitespace(String[] strArray) {
for (int ii = 0; ii < strArray.length; ii++) {
strArray[ii] = strArray[ii].trim();
}
}
}
private static AuthenticationParameters parseResponse(HttpWebResponse webResponse) throws ResourceAuthenticationChallengeException {
// Depending on the service side implementation for this resource
if (webResponse.getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
Map<String, List<String>> responseHeaders = webResponse.getResponseHeaders();
if (responseHeaders != null && responseHeaders.containsKey(AUTHENTICATE_HEADER)) {
// HttpUrlConnection sends a list of header values for same key
// if exists
List<String> headers = responseHeaders.get(AUTHENTICATE_HEADER);
if (headers != null && headers.size() > 0) {
return createFromResponseAuthenticateHeader(headers.get(0));
}
}
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_MISSING);
}
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_WRONG_STATUS);
}
}
|
adal/src/main/java/com/microsoft/aad/adal/AuthenticationParameters.java
|
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// 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 com.microsoft.aad.adal;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Matching to ADAL.NET It provides helper methods to get the
* authorization_endpoint from resource address.
*/
public class AuthenticationParameters {
/**
* WWW-Authenticate header is missing authorization_uri.
*/
public static final String AUTH_HEADER_MISSING_AUTHORITY = "WWW-Authenticate header is missing authorization_uri.";
/**
* Invalid authentication header format.
*/
public static final String AUTH_HEADER_INVALID_FORMAT = "Invalid authentication header format";
/**
* WWW-Authenticate header was expected in the response.
*/
public static final String AUTH_HEADER_MISSING = "WWW-Authenticate header was expected in the response";
/**
* Unauthorized http response (status code 401) was expected.
*/
public static final String AUTH_HEADER_WRONG_STATUS = "Unauthorized http response (status code 401) was expected";
/**
* Constant Authenticate header: WWW-Authenticate.
*/
public static final String AUTHENTICATE_HEADER = "WWW-Authenticate";
/**
* Constant Bearer.
*/
public static final String BEARER = "bearer";
/**
* Constant Authority key.
*/
public static final String AUTHORITY_KEY = "authorization_uri";
/**
* Constant Resource key.
*/
public static final String RESOURCE_KEY = "resource_id";
private static final String TAG = "AuthenticationParameters";
private String mAuthority;
private String mResource;
/**
* Web request handler interface to test behaviors.
*/
private static IWebRequestHandler sWebRequest = new WebRequestHandler();
/**
* Singled threaded Executor for async work.
*/
private static ExecutorService sThreadExecutor = Executors.newSingleThreadExecutor();
/**
* get authority from the header.
*
* @return Authority extracted from the header.
*/
public String getAuthority() {
return mAuthority;
}
/**
* get resource from the header.
*
* @return resource from the header.
*/
public String getResource() {
return mResource;
}
/**
* Creates AuthenticationParameters.
*/
public AuthenticationParameters() {
}
AuthenticationParameters(String authority, String resource) {
mAuthority = authority;
mResource = resource;
}
/**
* Callback to use for async request.
*/
public interface AuthenticationParamCallback {
/**
* @param exception {@link Exception}
* @param param {@link AuthenticationParameters}
*/
void onCompleted(Exception exception, AuthenticationParameters param);
}
/**
* ADAL will make the call to get authority and resource info.
*
* @param context {@link Context}
* @param resourceUrl Url for resource to query for 401 response.
* @param callback {@link AuthenticationParamCallback}
*/
public static void createFromResourceUrl(Context context, final URL resourceUrl,
final AuthenticationParamCallback callback) {
if (callback == null) {
throw new IllegalArgumentException("callback");
}
Logger.v(TAG, "createFromResourceUrl");
final Handler handler = new Handler(context.getMainLooper());
sThreadExecutor.submit(new Runnable() {
@Override
public void run() {
final Map<String, String> headers = new HashMap<>();
headers.put(WebRequestHandler.HEADER_ACCEPT, WebRequestHandler.HEADER_ACCEPT_JSON);
final HttpWebResponse webResponse;
try {
webResponse = sWebRequest.sendGet(resourceUrl, headers);
try {
onCompleted(null, parseResponse(webResponse));
} catch (ResourceAuthenticationChallengeException exc) {
onCompleted(exc, null);
}
} catch (IOException e) {
onCompleted(e, null);
}
}
void onCompleted(final Exception exception, final AuthenticationParameters param) {
handler.post(new Runnable() {
@Override
public void run() {
callback.onCompleted(exception, param);
}
});
}
});
}
/**
* ADAL will parse the header response to get the authority and the resource
* info.
*
* @param authenticateHeader Header to check authority and resource.
* @return {@link AuthenticationParameters}
* @throws {@link ResourceAuthenticationChallengeException}
*/
public static AuthenticationParameters createFromResponseAuthenticateHeader(final String authenticateHeader)
throws ResourceAuthenticationChallengeException {
Log.e("TestParser", "Header value: " + authenticateHeader);
if (StringExtensions.isNullOrBlank(authenticateHeader)) {
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_MISSING);
}
//testing...
final List<Challenge> challenges = Challenge.parseChallenges(authenticateHeader);
// Grab the Bearer challenge
Challenge bearerChallenge = null;
for (final Challenge challenge : challenges) {
if (challenge.getScheme().equalsIgnoreCase(BEARER)) {
bearerChallenge = challenge;
break;
}
}
if (null != bearerChallenge) {
final Map<String, String> challengeParams = bearerChallenge.getParameters();
String authority = challengeParams.get(AUTHORITY_KEY);
String resource = challengeParams.get(RESOURCE_KEY);
if (StringExtensions.isNullOrBlank(authority)) {
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_MISSING_AUTHORITY);
}
// Remove wrapping quotes (if present)
authority = authority.replaceAll("^\"|\"$", "");
if (StringExtensions.isNullOrBlank(authority)) {
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_MISSING_AUTHORITY);
}
if (!StringExtensions.isNullOrBlank(resource)) {
resource = resource.replaceAll("^\"|\"$", "");
}
return new AuthenticationParameters(authority, resource);
}
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_INVALID_FORMAT);
}
private static class Challenge {
public static final String TEST_PARSER = "TestParser";
private String mScheme;
private Map<String, String> mParameters;
Challenge(final String scheme, final Map<String, String> params) {
mScheme = scheme;
mParameters = params;
}
public String getScheme() {
return mScheme;
}
public Map<String, String> getParameters() {
return mParameters;
}
static Challenge parseChallenge(final String challenge) throws ResourceAuthenticationChallengeException {
final String scheme = parseScheme(challenge);
Log.e(TEST_PARSER, "Parsing scheme: " + scheme);
final String challengeSansScheme = challenge.substring(scheme.length() + 1);
Log.e(TEST_PARSER, "Parsing schemeless params: " + challengeSansScheme);
final Map<String, String> params = parseParams(challengeSansScheme);
return new Challenge(scheme, params);
}
private static String parseScheme(String challenge) throws ResourceAuthenticationChallengeException {
final int indexOfFirstSpace = challenge.indexOf(' ');
final int indexOfFirstTab = challenge.indexOf('\t');
// We want to grab the lesser of these values so long as they're > -1
if (indexOfFirstSpace < 0 && indexOfFirstTab < 0) {
return challenge;
}
if (indexOfFirstSpace > -1 && (indexOfFirstSpace < indexOfFirstTab || indexOfFirstTab < 0)) {
return challenge.substring(0, indexOfFirstSpace);
}
if (indexOfFirstTab > -1 && (indexOfFirstTab < indexOfFirstSpace || indexOfFirstSpace < 0)) {
return challenge.substring(0, indexOfFirstTab);
}
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_INVALID_FORMAT);
}
private static Map<String, String> parseParams(String challengeSansScheme) throws ResourceAuthenticationChallengeException {
if (StringExtensions.isNullOrBlank(challengeSansScheme)) {
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_INVALID_FORMAT);
}
// Split on unquoted commas
final Map<String, String> params = new HashMap<>();
final String[] splitOnUnquotedCommas = challengeSansScheme.split(REGEX_SPLIT_UNQUOTED_COMMA, -1);
for (final String paramSet : splitOnUnquotedCommas) {
// Split keys/values by the '='
final String[] splitOnUnquotedEquals = paramSet.split(REGEX_SPLIT_UNQUOTED_EQUALS, -1);
// We should now have a left-side and right-side
if (splitOnUnquotedEquals.length != 2) {
// Is this really what you want?
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_INVALID_FORMAT);
//continue; // If there's no key/value pair, skip this token
}
// Create the keys/values, trimming off any bogus whitespace
final String key = splitOnUnquotedEquals[0].trim();
final String value = splitOnUnquotedEquals[1].trim();
// if there is already a mapping for this key, we've seen this value before
// and should log a warning that this header looks fishy....
if (params.containsKey(key)) {
Logger.w(TAG,
"Key/value pair list contains redundant key. ",
"Redundant key: " + key,
ADALError.DEVELOPER_BEARER_HEADER_MULTIPLE_ITEMS);
}
Log.e(TEST_PARSER, "put(" + key + ", " + value + ")");
params.put(key, value);
}
if (params.isEmpty()) {
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_INVALID_FORMAT);
}
return params;
}
static List<Challenge> parseChallenges(final String strChallenges) throws ResourceAuthenticationChallengeException {
final List<Challenge> challenges = new ArrayList<>();
try {
List<String> strChallengesList = separateChallenges(strChallenges);
//
Log.e(TEST_PARSER, "Logging list contents");
for (String s : strChallengesList) {
Log.e(TEST_PARSER, "\t" + s);
}
//
for (final String challenge : strChallengesList) {
challenges.add(parseChallenge(challenge));
}
} catch (ResourceAuthenticationChallengeException e) {
throw e;
} catch (Exception e) {
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_INVALID_FORMAT);
}
return challenges;
}
private static final String REGEX_UNQUOTED_LOOKAHEAD = "(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)";
private static final String REGEX_SPLIT_UNQUOTED_EQUALS = "=" + REGEX_UNQUOTED_LOOKAHEAD;
private static final String REGEX_SPLIT_UNQUOTED_COMMA = "," + REGEX_UNQUOTED_LOOKAHEAD;
private static final String REGEX_STRING_TOKEN_WITH_SCHEME = "^([^\\s|^=]+)[\\s|\\t]+([^=]*=[^=]*)+$";
private static final String SUFFIX_COMMA = ", ";
private static List<String> separateChallenges(final String challenges) {
// Split the supplied String on those commas which are not constrained by quotes
String[] splitOnUnquotedCommas = challenges.split(REGEX_SPLIT_UNQUOTED_COMMA, -1);
sanitizeWhitespace(splitOnUnquotedCommas);
List<String> tokensContainingScheme = extractTokensContainingScheme(splitOnUnquotedCommas);
// init an array to store the out-values
String[] outStrings = new String[tokensContainingScheme.size()];
for (int ii = 0; ii < outStrings.length; ii++) {
outStrings[ii] = "";
}
int ii = -1;
for (final String token : splitOnUnquotedCommas) {
if (tokensContainingScheme.contains(token)) {
// this is the start of a challenge...
outStrings[++ii] = token + SUFFIX_COMMA;
} else {
outStrings[ii] += token + SUFFIX_COMMA;
}
}
// Remove the suffix comma from the last element of each list...
for (int jj = 0; jj < outStrings.length; jj++) {
if (outStrings[jj].endsWith(SUFFIX_COMMA)) {
outStrings[jj] = outStrings[jj].substring(0, outStrings[jj].length() - 2);
}
}
// Collapse the results to a single list...
return Arrays.asList(outStrings);
}
private static List<String> extractTokensContainingScheme(final String[] strArry) {
final List<String> tokensContainingScheme = new ArrayList<>();
for (final String token : strArry) {
if (containsScheme(token)) {
tokensContainingScheme.add(token);
}
}
return tokensContainingScheme;
}
private static boolean containsScheme(final String token) {
final Pattern startWithScheme = Pattern.compile(REGEX_STRING_TOKEN_WITH_SCHEME);
final Matcher matcher = startWithScheme.matcher(token);
Log.e(TEST_PARSER, "Checking String:[" + token + "] containsScheme? " + matcher.matches());
return matcher.matches();
}
private static void sanitizeWhitespace(String[] strArray) {
for (int ii = 0; ii < strArray.length; ii++) {
strArray[ii] = strArray[ii].trim();
}
}
}
private static AuthenticationParameters parseResponse(HttpWebResponse webResponse) throws ResourceAuthenticationChallengeException {
// Depending on the service side implementation for this resource
if (webResponse.getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
Map<String, List<String>> responseHeaders = webResponse.getResponseHeaders();
if (responseHeaders != null && responseHeaders.containsKey(AUTHENTICATE_HEADER)) {
// HttpUrlConnection sends a list of header values for same key
// if exists
List<String> headers = responseHeaders.get(AUTHENTICATE_HEADER);
if (headers != null && headers.size() > 0) {
Log.e("TestParser", "Parsing..." + headers.get(0));
return createFromResponseAuthenticateHeader(headers.get(0));
}
}
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_MISSING);
}
throw new ResourceAuthenticationChallengeException(AUTH_HEADER_WRONG_STATUS);
}
}
|
Refactor/add javadoc
|
adal/src/main/java/com/microsoft/aad/adal/AuthenticationParameters.java
|
Refactor/add javadoc
|
|
Java
|
mit
|
7deaf85e1be43c2842b8a78a951a94d835a3706e
| 0
|
weeryan17/FlareBot,FlareBot/FlareBot,binaryoverload/FlareBot
|
package stream.flarebot.flarebot.objects;
import org.eclipse.jetty.util.ConcurrentHashSet;
import stream.flarebot.flarebot.Language;
import stream.flarebot.flarebot.mod.AutoModGuild;
import java.util.*;
public class GuildWrapperBuilder {
private String guildId;
private AutoModGuild autoModGuild = new AutoModGuild();
private Welcome welcome = null;
private LinkedList<Poll> polls = new LinkedList<>();
private Set<String> autoAssignRoles = new ConcurrentHashSet<>();
private Set<String> selfAssignRoles = new ConcurrentHashSet<>();
private Language.Locales locale = Language.Locales.ENGLISH_UK;
private GuildWrapperBuilder(){}
public GuildWrapperBuilder(String guildId){
this.guildId = guildId;
}
public GuildWrapperBuilder setAutoMod(AutoModGuild autoMod){
this.autoModGuild = autoMod;
return this;
}
public GuildWrapperBuilder setWelcome(Welcome welcome){
this.welcome = welcome;
return this;
}
public GuildWrapperBuilder setPolls(LinkedList<Poll> polls){
this.polls = polls;
return this;
}
public GuildWrapperBuilder addPoll(Poll poll){
this.polls.add(poll);
return this;
}
public GuildWrapperBuilder setSelfAssignRoles(Set<String> roles){
this.selfAssignRoles = roles;
return this;
}
public GuildWrapperBuilder setAutoAssignRoles(Set<String> roles) {
this.autoAssignRoles = roles;
return this;
}
public GuildWrapperBuilder setLanguage(Language.Locales locale){
this.locale = locale;
return this;
}
public GuildWrapper build(){
return new GuildWrapper(guildId, autoModGuild, welcome, polls, autoAssignRoles, selfAssignRoles, locale);
}
}
|
src/main/java/stream/flarebot/flarebot/objects/GuildWrapperBuilder.java
|
package stream.flarebot.flarebot.objects;
import org.eclipse.jetty.util.ConcurrentHashSet;
import stream.flarebot.flarebot.Language;
import stream.flarebot.flarebot.mod.AutoModGuild;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
public class GuildWrapperBuilder {
private String guildId;
private AutoModGuild autoModGuild = new AutoModGuild();
private Welcome welcome = null;
private Set<Poll> polls = new HashSet<>();
private Set<String> autoAssignRoles = new ConcurrentHashSet<>();
private Set<String> selfAssignRoles = new ConcurrentHashSet<>();
private Language.Locales locale = Language.Locales.ENGLISH_UK;
private GuildWrapperBuilder(){}
public GuildWrapperBuilder(String guildId){
this.guildId = guildId;
}
public GuildWrapperBuilder setAutoMod(AutoModGuild autoMod){
this.autoModGuild = autoMod;
return this;
}
public GuildWrapperBuilder setWelcome(Welcome welcome){
this.welcome = welcome;
return this;
}
public GuildWrapperBuilder setPolls(Set<Poll> polls){
this.polls = polls;
return this;
}
public GuildWrapperBuilder addPoll(Poll poll){
this.polls.add(poll);
return this;
}
public GuildWrapperBuilder setSelfAssignRoles(Set<String> roles){
this.selfAssignRoles = roles;
return this;
}
public GuildWrapperBuilder setAutoAssignRoles(Set<String> roles) {
this.autoAssignRoles = roles;
return this;
}
public GuildWrapperBuilder setLanguage(Language.Locales locale){
this.locale = locale;
return this;
}
public GuildWrapper build(){
return new GuildWrapper(guildId, autoModGuild, welcome, polls, autoAssignRoles, selfAssignRoles, locale);
}
}
|
Use linked list instead of set
|
src/main/java/stream/flarebot/flarebot/objects/GuildWrapperBuilder.java
|
Use linked list instead of set
|
|
Java
|
mit
|
3ae35f467f6ac2d729238da9e57e42e54c79fe59
| 0
|
Android-leak/android-vts,AndroidVTS/android-vts,AndroidVTS/android-vts,duo-labs/android-vts,AndroidVTS/android-vts,Android-leak/android-vts,duo-labs/android-vts,Android-leak/android-vts,nowsecure/android-vts,Android-leak/android-vts,nowsecure/android-vts,nowsecure/android-vts,AndroidVTS/android-vts,duo-labs/android-vts,nowsecure/android-vts,duo-labs/android-vts
|
package fuzion24.device.vulnerability.vulnerabilities.system;
import android.content.Context;
import android.content.pm.PackageManager;
import fuzion24.device.vulnerability.util.CPUArch;
import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityTest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class WeakSauce implements VulnerabilityTest {
@Override
public List<CPUArch> getSupportedArchitectures() {
ArrayList<CPUArch> archs = new ArrayList<CPUArch>();
archs.add(CPUArch.ALL);
return archs;
}
@Override
public String getCVEorID() {
return "WeakSauce";
}
private boolean thisHasInternetPermission(Context ctx)
{
String permission = "android.permission.INTERNET";
int res = ctx.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
@Override
public boolean isVulnerable(Context context) throws Exception {
if(!thisHasInternetPermission(context))
throw new Exception("No internet permission assigned to app to perform WeakSauce Test");
File dmAgentSocket = new File("/dev/socket/dmagent");
return dmAgentSocket.exists();
}
}
|
app/src/main/java/fuzion24/device/vulnerability/vulnerabilities/system/WeakSauce.java
|
package fuzion24.device.vulnerability.vulnerabilities.system;
import android.content.Context;
import android.content.pm.PackageManager;
import fuzion24.device.vulnerability.util.CPUArch;
import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityTest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class WeakSauce implements VulnerabilityTest {
@Override
public List<CPUArch> getSupportedArchitectures() {
ArrayList<CPUArch> archs = new ArrayList<CPUArch>();
archs.add(CPUArch.ALL);
return archs;
}
@Override
public String getCVEorID() {
return "WeakSauce";
}
private boolean thisHasInternetPermission(Context ctx)
{
String permission = "android.permission.INTERNET";
int res = ctx.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}
@Override
public boolean isVulnerable(Context context) throws Exception {
if(!thisHasInternetPermission(context))
throw new Exception("No internet permission assigned to app to perform WeakSauce Test");
File dmAgentSocket = new File("/dev/socket/dmagent");
return dmAgentSocket.canWrite() && dmAgentSocket.canRead();
}
}
|
This can sometimes use tcp/ip instead of unix sockets
|
app/src/main/java/fuzion24/device/vulnerability/vulnerabilities/system/WeakSauce.java
|
This can sometimes use tcp/ip instead of unix sockets
|
|
Java
|
mit
|
c249e0ddf2bdd0485535e2e3462a86cda46abee0
| 0
|
xxryan1234/satellizer,bartekmis/satellizer,peterkim-ijet/satellizer,Manumental32/satellizer,suratpyari/satellizer,maciekrb/satellizer,redwood-strategic/satellizer,shubham13jain/satellizer,maciekrb/satellizer,celrenheit/satellizer,eduardomb/satellizer,peterkim-ijet/satellizer,maciekrb/satellizer,amitport/satellizer,gshireesh/satellizer,manojpm/satellizer,redwood-strategic/satellizer,david300/satellizer,david300/satellizer,david300/satellizer,xxryan1234/satellizer,xxryan1234/satellizer,hsr-ba-fs15-dat/satellizer,NikolayGalkin/satellizer,hsr-ba-fs15-dat/satellizer,xscharlie/satellizer,shikhardb/satellizer,jonbgallant/satellizer,celrenheit/satellizer,peterkim-ijet/satellizer,eduardomb/satellizer,hsr-ba-fs15-dat/satellizer,gshireesh/satellizer,xxryan1234/satellizer,jskrzypek/satellizer,marfarma/satellizer,redwood-strategic/satellizer,redwood-strategic/satellizer,celrenheit/satellizer,gshireesh/satellizer,NikolayGalkin/satellizer,xxryan1234/satellizer,m-kostira/satellizer,gshireesh/satellizer,jskrzypek/satellizer,david300/satellizer,SkydiverFL/satellizer,david300/satellizer,hsr-ba-fs15-dat/satellizer,gshireesh/satellizer,jskrzypek/satellizer,xxryan1234/satellizer,david300/satellizer,jskrzypek/satellizer,gshireesh/satellizer,marceldiass/satellizer,david300/satellizer,eduardomb/satellizer,burasu/satellizer,david300/satellizer,peterkim-ijet/satellizer,IRlyDontKnow/satellizer,NikolayGalkin/satellizer,elanperach/satellizer,amitport/satellizer,NikolayGalkin/satellizer,xxryan1234/satellizer,TheOneTheOnlyDavidBrown/satellizer,viniciusferreira/satellizer,andyskw/satellizer,heinbez/satellizer,romcyncynatus/satellizer,celrenheit/satellizer,gshireesh/satellizer,ezzaouia/satellizer,memezilla/satellizer,jskrzypek/satellizer,hsr-ba-fs15-dat/satellizer,amitport/satellizer,amitport/satellizer,NikolayGalkin/satellizer,hsr-ba-fs15-dat/satellizer,hsr-ba-fs15-dat/satellizer,redwood-strategic/satellizer,celrenheit/satellizer,bnicart/satellizer,xxryan1234/satellizer,xxryan1234/satellizer,celrenheit/satellizer,dgoguerra/satellizer,baratheraja/satellizer,peterkim-ijet/satellizer,eduardomb/satellizer,celrenheit/satellizer,maciekrb/satellizer,ABPFrameWorkGroup/satellizer,NikolayGalkin/satellizer,hsr-ba-fs15-dat/satellizer,redwood-strategic/satellizer,maciekrb/satellizer,expertmaksud/satellizer,18098924759/satellizer,AmreeshTyagi/satellizer,redwood-strategic/satellizer,peterkim-ijet/satellizer,sahat/satellizer,vebin/satellizer,rick4470/satellizer,thiagofesta/satellizer,maciekrb/satellizer,raycoding/satellizer,jayzeng/satellizer,thandaanda/satellizer,jskrzypek/satellizer,gshireesh/satellizer,redwood-strategic/satellizer,johan--/satellizer,johan--/satellizer,sahat/satellizer,NikolayGalkin/satellizer,eduardomb/satellizer,amitport/satellizer,amitport/satellizer,peterkim-ijet/satellizer,david300/satellizer,maciekrb/satellizer,themifycloud/satellizer,peterkim-ijet/satellizer,gregoriusxu/satellizer,jskrzypek/satellizer,eduardomb/satellizer,celrenheit/satellizer,maciekrb/satellizer,zawmyolatt/satellizer,eduardomb/satellizer,eduardomb/satellizer,jskrzypek/satellizer,gshireesh/satellizer,romcyncynatus/satellizer,eduardomb/satellizer,amitport/satellizer,redwood-strategic/satellizer,jianwang195823/satellizer,NikolayGalkin/satellizer,jskrzypek/satellizer
|
package com.example.helloworld.resources;
import io.dropwizard.hibernate.UnitOfWork;
import io.dropwizard.jersey.errors.ErrorMessage;
import java.text.ParseException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.example.helloworld.core.User;
import com.example.helloworld.db.UserDAO;
import com.example.helloworld.util.AuthUtils;
import com.google.common.base.Optional;
@Path("/api/me")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class UserResource {
private final UserDAO dao;
public UserResource(UserDAO userDAO) {
this.dao = userDAO;
}
@GET
@UnitOfWork
public Response getUser(@Context HttpServletRequest request) throws ParseException {
Optional<User> foundUser = getAuthUser(request);
if (!foundUser.isPresent()) {
return Response.status(Status.NOT_FOUND).build();
}
return Response.ok().entity(foundUser.get()).build();
}
// for testing
@GET
@Path("/all")
@UnitOfWork
public Response getAllUsers() {
return Response.ok().entity(dao.findAll()).build();
}
@PUT
@UnitOfWork
public Response updateUser(@Valid User user, @Context HttpServletRequest request) throws ParseException {
Optional<User> foundUser = getAuthUser(request.getHeader(AuthUtils.AUTH_HEADER_KEY));
if (!foundUser.isPresent()) {
return Response
.status(Status.NOT_FOUND)
.entity(new ErrorMessage(AuthResource.NOT_FOUND_MSG)).build();
}
User userToUpdate = foundUser.get();
userToUpdate.setDisplayName(user.getDisplayName());
userToUpdate.setEmail(user.getEmail());
dao.save(userToUpdate);
return Response.ok().build();
}
/*
* Helper methods
*/
private Optional<User> getAuthUser(String authHeader) throws ParseException {
String subject = AuthUtils.getSubject(authHeader);
return dao.findById(Long.parseLong(subject));
}
private Optional<User> getAuthUser(HttpServletRequest request) throws ParseException {
String authHeader = request.getHeader(AuthUtils.AUTH_HEADER_KEY);
return getAuthUser(authHeader);
}
}
|
examples/server/java/src/main/java/com/example/helloworld/resources/UserResource.java
|
package com.example.helloworld.resources;
import io.dropwizard.hibernate.UnitOfWork;
import io.dropwizard.jersey.errors.ErrorMessage;
import java.text.ParseException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import com.example.helloworld.core.Token;
import com.example.helloworld.core.User;
import com.example.helloworld.db.UserDAO;
import com.example.helloworld.util.AuthUtils;
import com.google.common.base.Optional;
@Path("/api/me")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class UserResource {
private final UserDAO dao;
public UserResource(UserDAO userDAO) {
this.dao = userDAO;
}
@GET
@UnitOfWork
public Response getUser(@Context HttpServletRequest request) throws ParseException {
Optional<User> foundUser = getAuthUser(request);
if (!foundUser.isPresent()) {
return Response.status(Status.NOT_FOUND).build();
}
return Response.ok().entity(foundUser.get()).build();
}
// for testing
@GET
@Path("/all")
@UnitOfWork
public Response getAllUsers() {
return Response.ok().entity(dao.findAll()).build();
}
@PUT
@UnitOfWork
public Response updateUser(@Valid User user, @Context HttpServletRequest request) throws ParseException {
String authHeader = request.getHeader(AuthUtils.AUTH_HEADER_KEY);
Optional<User> foundUser = getAuthUser(authHeader);
if (!foundUser.isPresent()) {
return Response
.status(Status.NOT_FOUND)
.entity(new ErrorMessage(AuthResource.NOT_FOUND_MSG)).build();
}
User userToUpdate = foundUser.get();
userToUpdate.setDisplayName(user.getDisplayName());
userToUpdate.setEmail(user.getEmail());
dao.save(userToUpdate);
Token token = new Token(AuthUtils.getSerializedToken(authHeader));
return Response.ok().entity(token).build();
}
/*
* Helper methods
*/
private Optional<User> getAuthUser(String authHeader) throws ParseException {
String subject = AuthUtils.getSubject(authHeader);
return dao.findById(Long.parseLong(subject));
}
private Optional<User> getAuthUser(HttpServletRequest request) throws ParseException {
String authHeader = request.getHeader(AuthUtils.AUTH_HEADER_KEY);
return getAuthUser(authHeader);
}
}
|
java: return 200 OK when updating user instead of sending token
|
examples/server/java/src/main/java/com/example/helloworld/resources/UserResource.java
|
java: return 200 OK when updating user instead of sending token
|
|
Java
|
epl-1.0
|
25efbbddf02c225975d2637e470db0de2238dac6
| 0
|
IanMayo/ZigDetector
|
/**
* Created by Bill on 1/23/2015.
*A project to determine the Linear regression for maritime analytic using java
* Modules such as apache commons maths libraries and Jfreechart are used for analysis and visualization
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Transient;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import junit.framework.TestCase;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.data.time.FixedMillisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import flanagan.math.Minimisation;
import flanagan.math.MinimisationFunction;
public class ZigDetector
{
private static final double CONVERGE_TOLERANCE = 1e-5;
final static long tgL1start = 1263297600000L; // 12:00:00 GMT
final static long osL1start = 1263297741000L; // 12:02:21 GMT
final static long tgL1end = 1263300091000L; // 12:41:31 GMT 2010
final static long tgL2start = 1263300279000L; // 12:44:39 GMT
final static long osL1end = 1263301172000L; // 12:59:32 GMT 2010
final static long osL2start = 1263301360000L; // 13:02:40 GMT
final static long tgL2end = 1263303616000L; // 13:40:16 GMT 2010
final static long tgL3start = 1263303804000L; // 13:43:24 GMT
final static long end = 1263304838000L; // 14:00:38 GMT 2010
final static Long timeEnd = null; // osL1end;
final static SimpleDateFormat dateF = new SimpleDateFormat("hh:mm:ss");
final static DecimalFormat numF = new DecimalFormat(
" 0000.0000000;-0000.0000000");
public static void main(String[] args) throws Exception
{
// capture the start time (used for time elapsed at the end)
long startTime = System.currentTimeMillis();
// create a holder for the data
final JFrame frame = createFrame();
frame.setLocation(600, 50);
Container container = frame.getContentPane();
// ok, insert a grid
JPanel inGrid = new JPanel();
container.add(inGrid);
GridLayout grid = new GridLayout(0, 2);
inGrid.setLayout(grid);
plotThis(inGrid, "Scen1");
plotThis(inGrid, "Scen2");
plotThis(inGrid, "Scen3");
plotThis(inGrid, "Scen4");
if(inGrid.getComponentCount() == 1)
grid.setColumns(1);
frame.pack();
long elapsed = System.currentTimeMillis() - startTime;
System.out.println("Elapsed:" + elapsed / 1000 + " secs");
}
public static void plotThis(Container container, String scenario)
throws Exception
{
// load the data
Track ownshipTrack = new Track("data/" + scenario + "_Ownship.csv");
Track targetTrack = new Track("data/" + scenario + "_Target.csv");
Sensor sensor = new Sensor("data/" + scenario + "_Sensor.csv");
// Now, we have to slice the data into ownship legs
List<LegOfData> ownshipLegs = calculateLegs(ownshipTrack);
// ownshipLegs = ownshipLegs.subList(1, 2); // just play with the first leg
// create the combined plot - where we show all our data
CombinedDomainXYPlot combinedPlot = Plotting.createPlot();
// ok create the plots of ownship & target tracks
Plotting.addOwnshipData(combinedPlot, "O/S ", ownshipTrack, ownshipLegs,
null, timeEnd);
// get ready to store the results runs
TimeSeriesCollection legResults = new TimeSeriesCollection();
List<Long> valueMarkers = new ArrayList<Long>();
// ok, work through the legs. In the absence of a Discrete Optimisation
// algorithm we're taking a brue force approach.
// Hopefully Craig can find an optimised alternative to this.
for (Iterator<LegOfData> iterator = ownshipLegs.iterator(); iterator
.hasNext();)
{
LegOfData thisLeg = (LegOfData) iterator.next();
// ok, slice the data for this leg
List<Double> bearings = sensor.extractBearings(thisLeg.getStart(),
thisLeg.getEnd());
List<Long> times = sensor.extractTimes(thisLeg.getStart(),
thisLeg.getEnd());
// find the error score for the overall leg
Minimisation wholeLegOptimiser = optimiseThis(times, bearings,
bearings.get(0));
// look at the individual scores (though they're not of interest)
System.out.println("Whole Leg:" + out(wholeLegOptimiser));
// we will try to beat this score, so set as very high number
double bestScore = Double.MAX_VALUE;
int bestIndex = -1;
Double overallScore = wholeLegOptimiser.getMinimum();
// create a placeholder for the overall score for this leg
TimeSeries straightBar = new TimeSeries("Whole " + thisLeg.getName(),
FixedMillisecond.class);
legResults.addSeries(straightBar);
// create a placeholder for the individual time slice experiments
TimeSeries thisSeries = new TimeSeries(thisLeg.getName(),
FixedMillisecond.class);
legResults.addSeries(thisSeries);
// loop through the values in this leg
// NOTE: this is a brute force algorithm - maybe we can find a
// Discrete Optimisation equivalent
for (int index = 0; index < times.size(); index++)
{
// what's the total score for slicing at this index?
// if(index != 50)
// continue;
int legOneEnd = getEnd(0, times.size(), 5, index);
int legTwoStart = getStart(0, times.size(), 5, index);
// int legOneEnd = index - BUFFER_REGION / 2;
// legOneEnd = Math.max(legOneEnd, 4);
// int legTwoStart = legOneEnd + BUFFER_REGION;
// legTwoStart = Math.min(legTwoStart, endIndex - 4);
double sum = sliceLeg(legOneEnd, index, legTwoStart, bearings, times);
thisSeries.add(new FixedMillisecond(times.get(index)), sum);
straightBar.add(new FixedMillisecond(times.get(index)), overallScore);
// is this better?
if (sum < bestScore)
{
// yes - store it.
bestScore = sum;
bestIndex = index;
}
}
valueMarkers.add(times.get(bestIndex));
}
// ok, also plot the leg attempts
Plotting.addLegResults(combinedPlot, legResults, valueMarkers);
// show the target track (it contains the results)
Plotting.addOwnshipData(combinedPlot, "Tgt ", targetTrack, null,
valueMarkers, timeEnd);
// wrap the combined chart
ChartPanel cp = new ChartPanel(new JFreeChart("Results for " + scenario + " Tol:" + CONVERGE_TOLERANCE,
JFreeChart.DEFAULT_TITLE_FONT, combinedPlot, true))
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
@Transient
public Dimension getPreferredSize()
{
return new Dimension(1100, 400);
}
};
container.add(cp, BorderLayout.CENTER);
// System.exit(0);
}
static Minimisation optimiseThis(List<Long> times, List<Double> bearings,
double initialBearing)
{
// Create instance of Minimisation
Minimisation min = new Minimisation();
// Create instace of class holding function to be minimised
FlanaganArctan funct = new FlanaganArctan(times, bearings);
// initial estimates
Double firstBearing = bearings.get(0);
double[] start ={firstBearing, 0.0D, 0.0D};
// initial step sizes
double[] step =
{ 0.2D, 0.3D, 0.3D };
// convergence tolerance
double ftol = CONVERGE_TOLERANCE;
// Nelder and Mead minimisation procedure
min.nelderMead(funct, start, step, ftol);
return min;
}
/**
* @param trialIndex
* @param bearings
* @param times
* @param overallScore
* the overall score for this leg
* @param BUFFER_REGION
* @param straightBar
* @param thisSeries
* @return
*/
private static double sliceLeg(final int legOneEnd, int trialIndex,
final int legTwoStart, List<Double> bearings, List<Long> times)
{
List<Long> theseTimes = times;
List<Double> theseBearings = bearings;
Date thisD = new Date(times.get(trialIndex));
// if((legOneEnd == -1) || (legTwoStart == -1))
// return Double.MAX_VALUE;
double beforeScore = 0;
double afterScore = 0;
@SuppressWarnings("unused")
String msg = dateF.format(thisD);
if (legOneEnd != -1)
{
List<Long> beforeTimes = theseTimes.subList(0, legOneEnd);
List<Double> beforeBearings = theseBearings.subList(0, legOneEnd);
Minimisation beforeOptimiser = optimiseThis(beforeTimes, beforeBearings,
beforeBearings.get(0));
beforeScore = beforeOptimiser.getMinimum() / beforeTimes.size();
msg += " BEFORE:" + dateF.format(times.get(0))+"-"+dateF.format(times.get(legOneEnd)) + " ";
}
if (legTwoStart != -1)
{
List<Long> afterTimes = theseTimes.subList(legTwoStart,
theseTimes.size() - 1);
List<Double> afterBearings = theseBearings.subList(legTwoStart,
theseTimes.size() - 1);
Minimisation afterOptimiser = optimiseThis(afterTimes, afterBearings,
afterBearings.get(0));
afterScore = afterOptimiser.getMinimum() / afterTimes.size();
msg += " AFTER:" + dateF.format(times.get(legTwoStart))+"-"+dateF.format(times.get(times.size()-1)) + " ";
}
// find the total error sum
double sum = beforeScore + afterScore;
// System.out.println(msg+ "SUM:" + sum);
// DecimalFormat intF = new DecimalFormat("00");
// System.out.println("index:"
// + intF.format(trialIndex)
// // + " time:" + times.get(trialIndex)
// + " " + " Sum:" + numF.format(sum) + " index:"
// + dateF.format(new Date(times.get(trialIndex))) + " before:"
// + outDates(beforeTimes) + out(beforeOptimiser) + " num:"
// + intF.format(beforeTimes.size()) + " after:" + outDates(afterTimes)
// + out(afterOptimiser) + " num:" + intF.format(afterTimes.size()));
return sum;
}
@SuppressWarnings("unused")
private static String outDates(List<Long> times)
{
String res = dateF.format(times.get(0)) + "-"
+ dateF.format(times.get(times.size() - 1));
return res;
}
/**
* slice this data into ownship legs, where the course and speed are
* relatively steady
*
* @param course_degs
* @param speed
* @param bearings
* @param elapsedTimes
* @return
*/
private static List<LegOfData> calculateLegs(Track track)
{
final double COURSE_TOLERANCE = 0.1; // degs / sec (just a guess!!)
final double SPEED_TOLERANCE = 2; // knots / sec (just a guess!!)
double lastCourse = 0;
double lastSpeed = 0;
long lastTime = 0;
List<LegOfData> legs = new ArrayList<LegOfData>();
legs.add(new LegOfData("Leg-1"));
long[] times = track.getDates();
double[] speeds = track.getSpeeds();
double[] courses = track.getCourses();
for (int i = 0; i < times.length; i++)
{
long thisTime = times[i];
double thisSpeed = speeds[i];
double thisCourse = courses[i];
if (i > 0)
{
// ok, check out the course change rate
double timeStepSecs = (thisTime - lastTime) / 1000;
double courseRate = Math.abs(thisCourse - lastCourse) / timeStepSecs;
double speedRate = Math.abs(thisSpeed - lastSpeed) / timeStepSecs;
// are they out of range
if ((courseRate < COURSE_TOLERANCE) && (speedRate < SPEED_TOLERANCE))
{
// ok, we're on a new leg - drop the current one
legs.get(legs.size() - 1).add(thisTime);
}
else
{
// we may be in a turn. create a new leg, if we haven't done
// so already
if (legs.get(legs.size() - 1).size() != 0)
{
legs.add(new LegOfData("Leg-" + (legs.size() + 1)));
}
}
}
// ok, store the values
lastTime = thisTime;
lastCourse = thisCourse;
lastSpeed = thisSpeed;
}
return legs;
}
private static class FlanaganArctan implements MinimisationFunction
{
final private List<Long> _times;
final private List<Double> _bearings;
public FlanaganArctan(List<Long> beforeTimes, List<Double> beforeBearings)
{
_times = beforeTimes;
_bearings = beforeBearings;
}
// evaluation function
public double function(double[] point)
{
double B = point[0];
double P = point[1];
double Q = point[2];
double runningSum = 0;
// ok, loop through the data
for (int i = 0; i < _times.size(); i++)
{
long elapsedMillis = _times.get(i) - _times.get(0);
double elapsedSecs = elapsedMillis / 1000d;
double thisForecast = calcForecast(B, P, Q, elapsedSecs);
double thisMeasured = _bearings.get(i);
double thisError = Math.pow(thisForecast - thisMeasured, 2);
runningSum += thisError;
}
return runningSum / _times.size();
}
private double calcForecast(double B, double P, double Q, double elapsedSecs)
{
double dX = Math.cos(Math.toRadians(B)) + Q * elapsedSecs;
double dY = Math.sin(Math.toRadians(B)) + P * elapsedSecs;
return Math.toDegrees(Math.atan2(dY, dX));
}
}
/**
* @return a frame to contain the results
*/
private static JFrame createFrame()
{
JFrame frame = new JFrame("Results");
frame.pack();
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
System.out.println("Closed");
e.getWindow().dispose();
}
});
frame.setLayout(new BorderLayout());
return frame;
}
public static String out(Minimisation res)
{
double[] key = res.getParamValues();
String out = " B:" + numF.format(key[0]) + " P:" + numF.format(key[1])
+ " Q:" + numF.format(key[2]) + " Sum:" + numF.format(res.getMinimum());
return out;
}
public static int getEnd(int start, int end, int buffer, int index)
{
int res = -1;
int MIN_SIZE = 3;
int semiBuffer = buffer / 2;
int earliestPossibleStartPoint = start + (MIN_SIZE - 1);
if (index - semiBuffer > earliestPossibleStartPoint)
{
res = index - semiBuffer - 1;
}
return res;
}
public static int getStart(int start, int end, int buffer, int index)
{
int res = -1;
int MIN_SIZE = 3;
int semiBuffer = buffer / 2;
int lastPossibleStartPoint = end - (MIN_SIZE - 1);
if (index + semiBuffer < lastPossibleStartPoint)
{
res = index + semiBuffer + 1;
}
return res;
}
public static class TestMe extends TestCase
{
public void testStartTimes()
{
assertEquals(2, 5 / 2);
assertEquals("correct", -1, getEnd(0, 15, 5, 0));
assertEquals("correct", -1, getEnd(0, 15, 5, 1));
assertEquals("correct", -1, getEnd(0, 15, 5, 2));
assertEquals("correct", -1, getEnd(0, 15, 5, 3));
assertEquals("correct", -1, getEnd(0, 15, 5, 4));
assertEquals("correct", 2, getEnd(0, 15, 5, 5));
assertEquals("correct", 3, getEnd(0, 15, 5, 6));
assertEquals("correct", 4, getEnd(0, 15, 5, 7));
assertEquals("correct", 5, getEnd(0, 15, 5, 8));
assertEquals("correct", 6, getEnd(0, 15, 5, 9));
assertEquals("correct", 7, getEnd(0, 15, 5, 10));
assertEquals("correct", 8, getEnd(0, 15, 5, 11));
assertEquals("correct", 9, getEnd(0, 15, 5, 12));
assertEquals("correct", 10, getEnd(0, 15, 5, 13));
assertEquals("correct", 11, getEnd(0, 15, 5, 14));
assertEquals("correct", 12, getEnd(0, 15, 5, 15));
assertEquals("correct", 3, getStart(0, 15, 5, 0));
assertEquals("correct", 4, getStart(0, 15, 5, 1));
assertEquals("correct", 5, getStart(0, 15, 5, 2));
assertEquals("correct", 6, getStart(0, 15, 5, 3));
assertEquals("correct", 7, getStart(0, 15, 5, 4));
assertEquals("correct", 8, getStart(0, 15, 5, 5));
assertEquals("correct", 9, getStart(0, 15, 5, 6));
assertEquals("correct", 10, getStart(0, 15, 5, 7));
assertEquals("correct", 11, getStart(0, 15, 5, 8));
assertEquals("correct", 12, getStart(0, 15, 5, 9));
assertEquals("correct", 13, getStart(0, 15, 5, 10));
assertEquals("correct", -1, getStart(0, 15, 5, 11));
assertEquals("correct", -1, getStart(0, 15, 5, 12));
assertEquals("correct", -1, getStart(0, 15, 5, 13));
assertEquals("correct", -1, getStart(0, 15, 5, 14));
assertEquals("correct", -1, getStart(0, 15, 5, 15));
}
}
}
|
src/ZigDetector.java
|
/**
* Created by Bill on 1/23/2015.
*A project to determine the Linear regression for maritime analytic using java
* Modules such as apache commons maths libraries and Jfreechart are used for analysis and visualization
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Transient;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import junit.framework.TestCase;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.data.time.FixedMillisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import flanagan.math.Minimisation;
import flanagan.math.MinimisationFunction;
public class ZigDetector
{
private static final double CONVERGE_TOLERANCE = 1e-5;
final static long tgL1start = 1263297600000L; // 12:00:00 GMT
final static long osL1start = 1263297741000L; // 12:02:21 GMT
final static long tgL1end = 1263300091000L; // 12:41:31 GMT 2010
final static long tgL2start = 1263300279000L; // 12:44:39 GMT
final static long osL1end = 1263301172000L; // 12:59:32 GMT 2010
final static long osL2start = 1263301360000L; // 13:02:40 GMT
final static long tgL2end = 1263303616000L; // 13:40:16 GMT 2010
final static long tgL3start = 1263303804000L; // 13:43:24 GMT
final static long end = 1263304838000L; // 14:00:38 GMT 2010
final static Long timeEnd = null; // osL1end;
final static SimpleDateFormat dateF = new SimpleDateFormat("hh:mm:ss");
final static DecimalFormat numF = new DecimalFormat(
" 0000.0000000;-0000.0000000");
public static void main(String[] args) throws Exception
{
// capture the start time (used for time elapsed at the end)
long startTime = System.currentTimeMillis();
// create a holder for the data
final JFrame frame = createFrame();
frame.setLocation(600, 50);
Container container = frame.getContentPane();
// ok, insert a grid
JPanel inGrid = new JPanel();
container.add(inGrid);
GridLayout grid = new GridLayout(0, 2);
inGrid.setLayout(grid);
plotThis(inGrid, "Scen1");
plotThis(inGrid, "Scen2");
plotThis(inGrid, "Scen3");
plotThis(inGrid, "Scen4");
if(inGrid.getComponentCount() == 1)
grid.setColumns(1);
frame.pack();
long elapsed = System.currentTimeMillis() - startTime;
System.out.println("Elapsed:" + elapsed / 1000 + " secs");
}
public static void plotThis(Container container, String scenario)
throws Exception
{
// load the data
Track ownshipTrack = new Track("data/" + scenario + "_Ownship.csv");
Track targetTrack = new Track("data/" + scenario + "_Target.csv");
Sensor sensor = new Sensor("data/" + scenario + "_Sensor.csv");
// Now, we have to slice the data into ownship legs
List<LegOfData> ownshipLegs = calculateLegs(ownshipTrack);
// ownshipLegs = ownshipLegs.subList(1, 2); // just play with the first leg
// create the combined plot - where we show all our data
CombinedDomainXYPlot combinedPlot = Plotting.createPlot();
// ok create the plots of ownship & target tracks
Plotting.addOwnshipData(combinedPlot, "O/S ", ownshipTrack, ownshipLegs,
null, timeEnd);
// get ready to store the results runs
TimeSeriesCollection legResults = new TimeSeriesCollection();
List<Long> valueMarkers = new ArrayList<Long>();
// ok, work through the legs. In the absence of a Discrete Optimisation
// algorithm we're taking a brue force approach.
// Hopefully Craig can find an optimised alternative to this.
for (Iterator<LegOfData> iterator = ownshipLegs.iterator(); iterator
.hasNext();)
{
LegOfData thisLeg = (LegOfData) iterator.next();
// ok, slice the data for this leg
List<Double> bearings = sensor.extractBearings(thisLeg.getStart(),
thisLeg.getEnd());
List<Long> times = sensor.extractTimes(thisLeg.getStart(),
thisLeg.getEnd());
// find the error score for the overall leg
Minimisation wholeLegOptimiser = optimiseThis(times, bearings,
bearings.get(0));
// look at the individual scores (though they're not of interest)
System.out.println("Whole Leg:" + out(wholeLegOptimiser));
// we will try to beat this score, so set as very high number
double bestScore = Double.MAX_VALUE;
int bestIndex = -1;
Double overallScore = wholeLegOptimiser.getMinimum();
final int BUFFER_REGION = 2; // the number of measurements to ignore
// whilst the target is turning
// how many points in this leg?
int thisLegSize = times.size();
int startIndex = 2;
int endIndex = thisLegSize - 3;
// create a placeholder for the overall score for this leg
TimeSeries straightBar = new TimeSeries("Whole " + thisLeg.getName(),
FixedMillisecond.class);
legResults.addSeries(straightBar);
// create a placeholder for the individual time slice experiments
TimeSeries thisSeries = new TimeSeries(thisLeg.getName(),
FixedMillisecond.class);
legResults.addSeries(thisSeries);
// loop through the values in this leg
// NOTE: this is a brute force algorithm - maybe we can find a
// Discrete Optimisation equivalent
for (int index = 0; index < times.size(); index++)
{
// what's the total score for slicing at this index?
// if(index != 50)
// continue;
int legOneEnd = getEnd(0, times.size(), 5, index);
int legTwoStart = getStart(0, times.size(), 5, index);
// int legOneEnd = index - BUFFER_REGION / 2;
// legOneEnd = Math.max(legOneEnd, 4);
// int legTwoStart = legOneEnd + BUFFER_REGION;
// legTwoStart = Math.min(legTwoStart, endIndex - 4);
double sum = sliceLeg(legOneEnd, index, legTwoStart, bearings, times);
thisSeries.add(new FixedMillisecond(times.get(index)), sum);
straightBar.add(new FixedMillisecond(times.get(index)), overallScore);
// is this better?
if (sum < bestScore)
{
// yes - store it.
bestScore = sum;
bestIndex = index;
}
}
valueMarkers.add(times.get(bestIndex));
}
// ok, also plot the leg attempts
Plotting.addLegResults(combinedPlot, legResults, valueMarkers);
// show the target track (it contains the results)
Plotting.addOwnshipData(combinedPlot, "Tgt ", targetTrack, null,
valueMarkers, timeEnd);
// wrap the combined chart
ChartPanel cp = new ChartPanel(new JFreeChart("Results for " + scenario + " Tol:" + CONVERGE_TOLERANCE,
JFreeChart.DEFAULT_TITLE_FONT, combinedPlot, true))
{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
@Transient
public Dimension getPreferredSize()
{
return new Dimension(1100, 400);
}
};
container.add(cp, BorderLayout.CENTER);
// System.exit(0);
}
static Minimisation optimiseThis(List<Long> times, List<Double> bearings,
double initialBearing)
{
// Create instance of Minimisation
Minimisation min = new Minimisation();
// Create instace of class holding function to be minimised
FlanaganArctan funct = new FlanaganArctan(times, bearings);
// initial estimates
Double firstBearing = bearings.get(0);
double[] start ={firstBearing, 0.0D, 0.0D};
// initial step sizes
double[] step =
{ 0.2D, 0.3D, 0.3D };
// convergence tolerance
double ftol = CONVERGE_TOLERANCE;
// Nelder and Mead minimisation procedure
min.nelderMead(funct, start, step, ftol);
return min;
}
/**
* @param trialIndex
* @param bearings
* @param times
* @param overallScore
* the overall score for this leg
* @param BUFFER_REGION
* @param straightBar
* @param thisSeries
* @return
*/
private static double sliceLeg(final int legOneEnd, int trialIndex,
final int legTwoStart, List<Double> bearings, List<Long> times)
{
List<Long> theseTimes = times;
List<Double> theseBearings = bearings;
Date thisD = new Date(times.get(trialIndex));
// if((legOneEnd == -1) || (legTwoStart == -1))
// return Double.MAX_VALUE;
double beforeScore = 0;
double afterScore = 0;
String msg = dateF.format(thisD);
if (legOneEnd != -1)
{
List<Long> beforeTimes = theseTimes.subList(0, legOneEnd);
List<Double> beforeBearings = theseBearings.subList(0, legOneEnd);
Minimisation beforeOptimiser = optimiseThis(beforeTimes, beforeBearings,
beforeBearings.get(0));
beforeScore = beforeOptimiser.getMinimum() / beforeTimes.size();
msg += " BEFORE:" + dateF.format(times.get(0))+"-"+dateF.format(times.get(legOneEnd)) + " ";
}
if (legTwoStart != -1)
{
List<Long> afterTimes = theseTimes.subList(legTwoStart,
theseTimes.size() - 1);
List<Double> afterBearings = theseBearings.subList(legTwoStart,
theseTimes.size() - 1);
Minimisation afterOptimiser = optimiseThis(afterTimes, afterBearings,
afterBearings.get(0));
afterScore = afterOptimiser.getMinimum() / afterTimes.size();
msg += " AFTER:" + dateF.format(times.get(legTwoStart))+"-"+dateF.format(times.get(times.size()-1)) + " ";
}
// find the total error sum
double sum = beforeScore + afterScore;
// System.out.println(msg+ "SUM:" + sum);
// DecimalFormat intF = new DecimalFormat("00");
// System.out.println("index:"
// + intF.format(trialIndex)
// // + " time:" + times.get(trialIndex)
// + " " + " Sum:" + numF.format(sum) + " index:"
// + dateF.format(new Date(times.get(trialIndex))) + " before:"
// + outDates(beforeTimes) + out(beforeOptimiser) + " num:"
// + intF.format(beforeTimes.size()) + " after:" + outDates(afterTimes)
// + out(afterOptimiser) + " num:" + intF.format(afterTimes.size()));
return sum;
}
private static String outDates(List<Long> times)
{
String res = dateF.format(times.get(0)) + "-"
+ dateF.format(times.get(times.size() - 1));
return res;
}
/**
* slice this data into ownship legs, where the course and speed are
* relatively steady
*
* @param course_degs
* @param speed
* @param bearings
* @param elapsedTimes
* @return
*/
private static List<LegOfData> calculateLegs(Track track)
{
final double COURSE_TOLERANCE = 0.1; // degs / sec (just a guess!!)
final double SPEED_TOLERANCE = 2; // knots / sec (just a guess!!)
double lastCourse = 0;
double lastSpeed = 0;
long lastTime = 0;
List<LegOfData> legs = new ArrayList<LegOfData>();
legs.add(new LegOfData("Leg-1"));
long[] times = track.getDates();
double[] speeds = track.getSpeeds();
double[] courses = track.getCourses();
for (int i = 0; i < times.length; i++)
{
long thisTime = times[i];
double thisSpeed = speeds[i];
double thisCourse = courses[i];
if (i > 0)
{
// ok, check out the course change rate
double timeStepSecs = (thisTime - lastTime) / 1000;
double courseRate = Math.abs(thisCourse - lastCourse) / timeStepSecs;
double speedRate = Math.abs(thisSpeed - lastSpeed) / timeStepSecs;
// are they out of range
if ((courseRate < COURSE_TOLERANCE) && (speedRate < SPEED_TOLERANCE))
{
// ok, we're on a new leg - drop the current one
legs.get(legs.size() - 1).add(thisTime);
}
else
{
// we may be in a turn. create a new leg, if we haven't done
// so already
if (legs.get(legs.size() - 1).size() != 0)
{
legs.add(new LegOfData("Leg-" + (legs.size() + 1)));
}
}
}
// ok, store the values
lastTime = thisTime;
lastCourse = thisCourse;
lastSpeed = thisSpeed;
}
return legs;
}
private static class FlanaganArctan implements MinimisationFunction
{
final private List<Long> _times;
final private List<Double> _bearings;
public FlanaganArctan(List<Long> beforeTimes, List<Double> beforeBearings)
{
_times = beforeTimes;
_bearings = beforeBearings;
}
// evaluation function
public double function(double[] point)
{
double B = point[0];
double P = point[1];
double Q = point[2];
double runningSum = 0;
// ok, loop through the data
for (int i = 0; i < _times.size(); i++)
{
long elapsedMillis = _times.get(i) - _times.get(0);
double elapsedSecs = elapsedMillis / 1000d;
double thisForecast = calcForecast(B, P, Q, elapsedSecs);
double thisMeasured = _bearings.get(i);
double thisError = Math.pow(thisForecast - thisMeasured, 2);
runningSum += thisError;
}
return runningSum / _times.size();
}
private double calcForecast(double B, double P, double Q, double elapsedSecs)
{
double dX = Math.cos(Math.toRadians(B)) + Q * elapsedSecs;
double dY = Math.sin(Math.toRadians(B)) + P * elapsedSecs;
return Math.toDegrees(Math.atan2(dY, dX));
}
}
/**
* @return a frame to contain the results
*/
private static JFrame createFrame()
{
JFrame frame = new JFrame("Results");
frame.pack();
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
System.out.println("Closed");
e.getWindow().dispose();
}
});
frame.setLayout(new BorderLayout());
return frame;
}
public static String out(Minimisation res)
{
double[] key = res.getParamValues();
String out = " B:" + numF.format(key[0]) + " P:" + numF.format(key[1])
+ " Q:" + numF.format(key[2]) + " Sum:" + numF.format(res.getMinimum());
return out;
}
public static int getEnd(int start, int end, int buffer, int index)
{
int res = -1;
int MIN_SIZE = 3;
int semiBuffer = buffer / 2;
int earliestPossibleStartPoint = start + (MIN_SIZE - 1);
if (index - semiBuffer > earliestPossibleStartPoint)
{
res = index - semiBuffer - 1;
}
return res;
}
public static int getStart(int start, int end, int buffer, int index)
{
int res = -1;
int MIN_SIZE = 3;
int semiBuffer = buffer / 2;
int lastPossibleStartPoint = end - (MIN_SIZE - 1);
if (index + semiBuffer < lastPossibleStartPoint)
{
res = index + semiBuffer + 1;
}
return res;
}
public static class TestMe extends TestCase
{
public void testStartTimes()
{
assertEquals(2, 5 / 2);
assertEquals("correct", -1, getEnd(0, 15, 5, 0));
assertEquals("correct", -1, getEnd(0, 15, 5, 1));
assertEquals("correct", -1, getEnd(0, 15, 5, 2));
assertEquals("correct", -1, getEnd(0, 15, 5, 3));
assertEquals("correct", -1, getEnd(0, 15, 5, 4));
assertEquals("correct", 2, getEnd(0, 15, 5, 5));
assertEquals("correct", 3, getEnd(0, 15, 5, 6));
assertEquals("correct", 4, getEnd(0, 15, 5, 7));
assertEquals("correct", 5, getEnd(0, 15, 5, 8));
assertEquals("correct", 6, getEnd(0, 15, 5, 9));
assertEquals("correct", 7, getEnd(0, 15, 5, 10));
assertEquals("correct", 8, getEnd(0, 15, 5, 11));
assertEquals("correct", 9, getEnd(0, 15, 5, 12));
assertEquals("correct", 10, getEnd(0, 15, 5, 13));
assertEquals("correct", 11, getEnd(0, 15, 5, 14));
assertEquals("correct", 12, getEnd(0, 15, 5, 15));
assertEquals("correct", 3, getStart(0, 15, 5, 0));
assertEquals("correct", 4, getStart(0, 15, 5, 1));
assertEquals("correct", 5, getStart(0, 15, 5, 2));
assertEquals("correct", 6, getStart(0, 15, 5, 3));
assertEquals("correct", 7, getStart(0, 15, 5, 4));
assertEquals("correct", 8, getStart(0, 15, 5, 5));
assertEquals("correct", 9, getStart(0, 15, 5, 6));
assertEquals("correct", 10, getStart(0, 15, 5, 7));
assertEquals("correct", 11, getStart(0, 15, 5, 8));
assertEquals("correct", 12, getStart(0, 15, 5, 9));
assertEquals("correct", 13, getStart(0, 15, 5, 10));
assertEquals("correct", -1, getStart(0, 15, 5, 11));
assertEquals("correct", -1, getStart(0, 15, 5, 12));
assertEquals("correct", -1, getStart(0, 15, 5, 13));
assertEquals("correct", -1, getStart(0, 15, 5, 14));
assertEquals("correct", -1, getStart(0, 15, 5, 15));
}
}
}
|
refactoring to avoid errors
|
src/ZigDetector.java
|
refactoring to avoid errors
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.