lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | 5eaf62d5ea7355679853d5ac94dbdf72f767d521 | 0 | seece/yotris | package com.lofibucket.yotris.ui;
import com.lofibucket.yotris.ui.UserInterface;
import com.lofibucket.yotris.ui.UserInterface;
import com.lofibucket.yotris.util.commands.Command;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
public class UserInterfaceMock implements UserInterface {
private ArrayList<Command> commands;
public int updated;
public UserInterfaceMock() {
commands = new ArrayList<Command>();
updated = 0;
}
@Override
public void start() {
}
@Override
public void stop() {
}
@Override
public void update(Observable o, Object arg) {
updated++;
}
@Override
public void addNewCommand(Command c) {
commands.add(c);
}
@Override
public List<Command> pollCommands() {
return commands;
}
public void clearCommands() {
commands.clear();
}
@Override
public void reset() {
}
}
| yotris/src/test/java/com/lofibucket/yotris/ui/UserInterfaceMock.java | package com.lofibucket.yotris.ui;
import com.lofibucket.yotris.ui.UserInterface;
import com.lofibucket.yotris.ui.UserInterface;
import com.lofibucket.yotris.util.commands.Command;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
public class UserInterfaceMock implements UserInterface {
private ArrayList<Command> commands;
public int updated;
public UserInterfaceMock() {
commands = new ArrayList<Command>();
updated = 0;
}
@Override
public void start() {
}
@Override
public void stop() {
}
@Override
public void update(Observable o, Object arg) {
updated++;
}
@Override
public void addNewCommand(Command c) {
commands.add(c);
}
@Override
public List<Command> pollCommands() {
return commands;
}
public void clearCommands() {
commands.clear();
}
@Override
public void reset() {
}
@Override
public boolean getWaitState() {
return false;
}
}
| fix UserInterfaceMock
| yotris/src/test/java/com/lofibucket/yotris/ui/UserInterfaceMock.java | fix UserInterfaceMock | <ide><path>otris/src/test/java/com/lofibucket/yotris/ui/UserInterfaceMock.java
<ide> public void reset() {
<ide> }
<ide>
<del> @Override
<del> public boolean getWaitState() {
<del> return false;
<del> }
<del>
<ide> } |
|
JavaScript | apache-2.0 | b38813bb12879cd51afdd2ac936f1966c5c32abb | 0 | SignalK/signalk-server-node,webmasterkai/signalk-server-node,sbender9/signalk-server-node,SignalK/signalk-server-node,sbender9/signalk-server-node,webmasterkai/signalk-server-node,webmasterkai/signalk-server-node,SignalK/signalk-server-node,sbender9/signalk-server-node,SignalK/signalk-server-node | /*
* Copyright 2014-2015 Fabian Tollenaar <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var flatMap = require('flatmap')
const _ = require('lodash')
const ports = require('../ports')
var supportedQuerySubscribeValues = ['self', 'all']
module.exports = function (app) {
'use strict'
var _ = require('lodash'),
debug = require('debug')('signalk-server:interfaces:ws'),
Primus = require('primus'),
api = {},
started = false,
primus
api.mdns = {
name: app.config.settings.ssl ? '_signalk-wss' : '_signalk-ws',
type: 'tcp',
port: ports.getExternalPort(app)
}
api.start = function () {
debug('Starting Primus/WS interface')
started = true
primus = new Primus(app.server, {
transformer: 'websockets',
pathname: '/signalk/v1/stream',
pingInterval: false
})
if (app.securityStrategy) {
primus.authorize(function (req, authorized) {
try {
app.securityStrategy.authorizeWS(req)
authorized()
var username = _.get(req, 'user.username')
if (username) {
debug(`authorized username: ${username}`)
req.source = 'ws.' + username.replace(/\./g, '_')
}
} catch (error) {
authorized(error)
}
})
}
primus.on('connection', function (spark) {
debug(spark.id + ' connected with params ' + JSON.stringify(spark.query))
var onChange = function (data) {
spark.write(data)
}
var unsubscribes = []
spark.on('data', function (msg) {
debug('<' + JSON.stringify(msg))
if (msg.updates) {
if (
app.securityStrategy &&
!app.securityStrategy.shouldAllowWrite(spark.request)
) {
debug('security disallowed update')
return
}
app.handleMessage(spark.request.source || 'ws', msg)
}
if (msg.subscribe) {
app.subscriptionmanager.subscribe(
msg,
unsubscribes,
spark.write.bind(this),
spark.write.bind(this)
)
}
if (
msg.unsubscribe &&
msg.context === '*' &&
msg.unsubscribe[0].path === '*'
) {
debug('Unsubscribe all')
unsubscribes.forEach(unsubscribe => unsubscribe())
app.signalk.removeListener('delta', onChange)
}
})
spark.on('end', function () {
unsubscribes.forEach(unsubscribe => unsubscribe())
})
if (!spark.query.subscribe || spark.query.subscribe === 'self') {
onChange = function (msg) {
if (!msg.context || msg.context === app.selfContext) {
spark.write(msg)
}
}
}
if (spark.query.subscribe && spark.query.subscribe === 'none') {
onChange = function () {}
}
var onChangeWrapper = function (msg) {
if (app.securityStrategy) {
try {
app.securityStrategy.verifyWS(spark.request)
} catch (error) {
spark.end(
'{message: "Connection disconnected by security constraint"}',
{ reconnect: true }
)
return
}
}
onChange(msg)
}
app.signalk.on('delta', onChangeWrapper)
spark.onDisconnect = function () {
app.signalk.removeListener('delta', onChangeWrapper)
}
spark.write({
name: app.config.name,
version: app.config.version,
timestamp: new Date(),
self: app.selfId,
roles: ['master', 'main']
})
})
primus.on('disconnection', function (spark) {
spark.onDisconnect()
debug(spark.id + ' disconnected')
})
}
api.stop = function () {
if (primus.destroy && started) {
debug('Destroying primus...')
primus.destroy({
close: false,
timeout: 500
})
}
}
return api
}
function normalizeDelta (delta) {
return flatMap(delta.updates, normalizeUpdate).map(function (update) {
return {
context: delta.context,
updates: [update]
}
})
}
function normalizeUpdate (update) {
return update.values.map(function (value) {
return {
source: update.source,
values: [value]
}
})
}
| lib/interfaces/ws.js | /*
* Copyright 2014-2015 Fabian Tollenaar <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var flatMap = require('flatmap')
const _ = require('lodash')
const ports = require('../ports')
var supportedQuerySubscribeValues = ['self', 'all']
module.exports = function (app) {
'use strict'
var _ = require('lodash'),
debug = require('debug')('signalk-server:interfaces:ws'),
Primus = require('primus'),
api = {},
started = false,
primus
api.mdns = {
name: app.config.settings.ssl ? '_signalk-wss' : '_signalk-ws',
type: 'tcp',
port: ports.getExternalPort(app)
}
api.start = function () {
debug('Starting Primus/WS interface')
started = true
primus = new Primus(app.server, {
transformer: 'websockets',
pathname: '/signalk/v1/stream',
pingInterval: false
})
var source = 'ws'
if (app.securityStrategy) {
primus.authorize(function (req, authorized) {
try {
app.securityStrategy.authorizeWS(req)
authorized()
var username = _.get(req, 'user.username')
if (username) {
source = 'ws.' + username.replace(/\./g, '_')
}
} catch (error) {
authorized(error)
}
})
}
primus.on('connection', function (spark) {
debug(spark.id + ' connected with params ' + JSON.stringify(spark.query))
var onChange = function (data) {
spark.write(data)
}
var unsubscribes = []
spark.on('data', function (msg) {
debug('<' + JSON.stringify(msg))
if (msg.updates) {
if (
app.securityStrategy &&
!app.securityStrategy.shouldAllowWrite(spark.request)
) {
debug('security disallowed update')
return
}
app.handleMessage(source, msg)
}
if (msg.subscribe) {
app.subscriptionmanager.subscribe(
msg,
unsubscribes,
spark.write.bind(this),
spark.write.bind(this)
)
}
if (
msg.unsubscribe &&
msg.context === '*' &&
msg.unsubscribe[0].path === '*'
) {
debug('Unsubscribe all')
unsubscribes.forEach(unsubscribe => unsubscribe())
app.signalk.removeListener('delta', onChange)
}
})
spark.on('end', function () {
unsubscribes.forEach(unsubscribe => unsubscribe())
})
if (!spark.query.subscribe || spark.query.subscribe === 'self') {
onChange = function (msg) {
if (!msg.context || msg.context === app.selfContext) {
spark.write(msg)
}
}
}
if (spark.query.subscribe && spark.query.subscribe === 'none') {
onChange = function () {}
}
var onChangeWrapper = function (msg) {
if (app.securityStrategy) {
try {
app.securityStrategy.verifyWS(spark.request)
} catch (error) {
spark.end(
'{message: "Connection disconnected by security constraint"}',
{ reconnect: true }
)
return
}
}
onChange(msg)
}
app.signalk.on('delta', onChangeWrapper)
spark.onDisconnect = function () {
app.signalk.removeListener('delta', onChangeWrapper)
}
spark.write({
name: app.config.name,
version: app.config.version,
timestamp: new Date(),
self: app.selfId,
roles: ['master', 'main']
})
})
primus.on('disconnection', function (spark) {
spark.onDisconnect()
debug(spark.id + ' disconnected')
})
}
api.stop = function () {
if (primus.destroy && started) {
debug('Destroying primus...')
primus.destroy({
close: false,
timeout: 500
})
}
}
return api
}
function normalizeDelta (delta) {
return flatMap(delta.updates, normalizeUpdate).map(function (update) {
return {
context: delta.context,
updates: [update]
}
})
}
function normalizeUpdate (update) {
return update.values.map(function (value) {
return {
source: update.source,
values: [value]
}
})
}
| fix: ws source for other users getting overwritten by new users (#355)
| lib/interfaces/ws.js | fix: ws source for other users getting overwritten by new users (#355) | <ide><path>ib/interfaces/ws.js
<ide> pingInterval: false
<ide> })
<ide>
<del> var source = 'ws'
<del>
<ide> if (app.securityStrategy) {
<ide> primus.authorize(function (req, authorized) {
<ide> try {
<ide>
<ide> var username = _.get(req, 'user.username')
<ide> if (username) {
<del> source = 'ws.' + username.replace(/\./g, '_')
<add> debug(`authorized username: ${username}`)
<add> req.source = 'ws.' + username.replace(/\./g, '_')
<ide> }
<ide> } catch (error) {
<ide> authorized(error)
<ide> debug('security disallowed update')
<ide> return
<ide> }
<del> app.handleMessage(source, msg)
<add> app.handleMessage(spark.request.source || 'ws', msg)
<ide> }
<ide> if (msg.subscribe) {
<ide> app.subscriptionmanager.subscribe( |
|
Java | apache-2.0 | bb2534fa1b950532ff7f189a40a2a3ce50d53bbd | 0 | SIROK/growthbeat-android,growthbeat/growthbeat-android | package com.growthpush;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.growthbeat.Growthbeat;
import com.growthbeat.Logger;
import com.growthbeat.Preference;
import com.growthbeat.http.GrowthbeatHttpClient;
import com.growthbeat.message.GrowthMessage;
import com.growthbeat.message.handler.ShowMessageHandler;
import com.growthbeat.utils.AppUtils;
import com.growthbeat.utils.DeviceUtils;
import com.growthpush.handler.DefaultReceiveHandler;
import com.growthpush.handler.ReceiveHandler;
import com.growthpush.model.Client;
import com.growthpush.model.Environment;
import com.growthpush.model.Event;
import com.growthpush.model.Tag;
import android.content.Context;
import android.os.Build;
public class GrowthPush {
private static final GrowthPush instance = new GrowthPush();
private final Logger logger = new Logger(GrowthPushConstants.LOGGER_DEFAULT_TAG);
private final GrowthbeatHttpClient httpClient = new GrowthbeatHttpClient(GrowthPushConstants.HTTP_CLIENT_DEFAULT_BASE_URL,
GrowthPushConstants.HTTP_CLIENT_DEFAULT_CONNECT_TIMEOUT, GrowthPushConstants.HTTP_CLIENT_DEFAULT_READ_TIMEOUT);
private final Preference preference = new Preference(GrowthPushConstants.PREFERENCE_DEFAULT_FILE_NAME);
private Client client = null;
private Semaphore semaphore = new Semaphore(1);
private CountDownLatch latch = new CountDownLatch(1);
private ReceiveHandler receiveHandler = new DefaultReceiveHandler();
private String applicationId;
private String credentialId;
private String senderId;
private Environment environment = null;
private boolean initialized = false;
private GrowthPush() {
super();
}
public static GrowthPush getInstance() {
return instance;
}
public void initialize(final Context context, final String applicationId, final String credentialId, final Environment environment) {
this.initialize(context, applicationId, credentialId, environment, true);
}
public void initialize(final Context context, final String applicationId, final String credentialId, final Environment environment,
final boolean adInfoEnabled) {
if (initialized)
return;
initialized = true;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
logger.warning("This SDK not supported this os.");
return;
}
if (context == null) {
logger.warning("The context parameter cannot be null.");
return;
}
this.applicationId = applicationId;
this.credentialId = credentialId;
this.environment = environment;
Growthbeat.getInstance().initialize(context, applicationId, credentialId);
GrowthMessage.getInstance().initialize(context, applicationId, credentialId);
this.preference.setContext(Growthbeat.getInstance().getContext());
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
com.growthbeat.model.Client growthbeatClient = Growthbeat.getInstance().waitClient();
client = Client.load();
if (client != null && client.getGrowthbeatClientId() != null
&& !client.getGrowthbeatClientId().equals(growthbeatClient.getId()))
GrowthPush.this.clearClient();
createClient(growthbeatClient.getId(), null);
if (adInfoEnabled) {
setAdvertisingId();
setTrackingEnabled();
}
}
});
}
public void requestRegistrationId(final String senderId) {
if (!initialized) {
logger.warning("Growth Push must be initilaize.");
return;
}
this.senderId = senderId;
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
String token = registerGCM(Growthbeat.getInstance().getContext());
if (token != null) {
logger.info("GCM registration token: " + token);
registerClient(token);
}
}
});
}
public String registerGCM(final Context context) {
if (this.senderId == null)
return null;
try {
InstanceID instanceID = InstanceID.getInstance(context);
return instanceID.getToken(this.senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
} catch (Exception e) {
return null;
}
}
public void registerClient(final String registrationId, Environment environment) {
this.environment = environment;
registerClient(registrationId);
}
protected void registerClient(final String registrationId) {
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
com.growthbeat.model.Client growthbeatClient = Growthbeat.getInstance().waitClient();
createClient(growthbeatClient.getId(), registrationId);
if ((registrationId != null && !registrationId.equals(client.getToken())) || environment != client.getEnvironment()) {
updateClient(registrationId);
return;
}
logger.info("Client already registered.");
}
});
}
private void createClient(final String growthbeatClientId, final String registrationId) {
try {
semaphore.acquire();
Client loadClient = Client.load();
if (loadClient != null) {
this.client = loadClient;
logger.info(String.format("Client already Created... (growthbeatClientId: %s, token: %s, environment: %s",
growthbeatClientId, registrationId, environment));
return;
}
logger.info(String.format("Create client... (growthbeatClientId: %s, token: %s, environment: %s", growthbeatClientId,
registrationId, environment));
client = Client.create(growthbeatClientId, applicationId, credentialId, registrationId, environment);
logger.info(String.format("Create client success (clientId: %d)", client.getId()));
Client.save(client);
} catch (InterruptedException e) {
} catch (GrowthPushException e) {
logger.error(String.format("Create client fail. %s", e.getMessage()));
} finally {
semaphore.release();
latch.countDown();
}
}
private void updateClient(final String registrationId) {
try {
logger.info(String.format("Updating client... (growthbeatClientId: %s, token: %s, environment: %s)",
client.getGrowthbeatClientId(), registrationId, environment));
client.setToken(registrationId);
client.setEnvironment(environment);
client = Client.update(client.getGrowthbeatClientId(), applicationId, credentialId, registrationId, environment);
logger.info(String.format("Update client success (clientId: %d)", client.getId()));
Client.save(client);
} catch (GrowthPushException e) {
logger.error(String.format("Update client fail. %s", e.getMessage()));
} finally {
latch.countDown();
}
}
public void trackEvent(final String name) {
trackEvent(name, null);
}
public void trackEvent(final String name, final String value) {
trackEvent(name, null, null);
}
public void trackEvent(final String name, final String value, final ShowMessageHandler handler) {
trackEvent(Event.EventType.custom, name, value, handler);
}
public void trackEvent(final Event.EventType type, final String name, final String value, final ShowMessageHandler handler) {
if (!initialized) {
logger.info("call after initialized.");
return;
}
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
if (name == null) {
logger.warning("Event name cannot be null.");
return;
}
waitClientRegistration();
logger.info(String.format("Sending event ... (name: %s)", name));
try {
Event event = Event.create(GrowthPush.getInstance().client.getGrowthbeatClientId(), applicationId,
GrowthPush.getInstance().credentialId, type, name, value);
logger.info(String.format("Sending event success. (timestamp: %s)", event.getTimestamp()));
if (type != Event.EventType.message)
GrowthMessage.getInstance().recevieMessage(event.getGoalId(), client.getGrowthbeatClientId(), handler);
} catch (GrowthPushException e) {
logger.error(String.format("Sending event fail. %s", e.getMessage()));
}
}
});
}
public void setTag(final String name) {
setTag(name, null);
}
public void setTag(final String name, final String value) {
setTag(Tag.TagType.custom, name, value);
}
private void setTag(final Tag.TagType type, final String name, final String value) {
if (!initialized) {
logger.info("call after initialized.");
return;
}
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
if (name == null) {
logger.warning("Tag name cannot be null.");
return;
}
Tag tag = Tag.load(type, name);
if (tag != null && (value == null || value.equalsIgnoreCase(tag.getValue()))) {
logger.info(String.format("Tag exists with the same value. (name: %s, value: %s)", name, value));
return;
}
waitClientRegistration();
logger.info(String.format("Sending tag... (key: %s, value: %s)", name, value));
try {
Tag createdTag = Tag.create(GrowthPush.getInstance().client.getGrowthbeatClientId(), applicationId, credentialId, type,
name, value);
logger.info(String.format("Sending tag success"));
Tag.save(createdTag, type, name);
} catch (GrowthPushException e) {
logger.error(String.format("Sending tag fail. %s", e.getMessage()));
}
}
});
}
public void setDeviceTags() {
setTag("Device", DeviceUtils.getModel());
setTag("OS", "Android " + DeviceUtils.getOsVersion());
setTag("Language", DeviceUtils.getLanguage());
setTag("Time Zone", DeviceUtils.getTimeZone());
setTag("Version", AppUtils.getaAppVersion(Growthbeat.getInstance().getContext()));
setTag("Build", AppUtils.getAppBuild(Growthbeat.getInstance().getContext()));
}
private void setAdvertisingId() {
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
try {
String advertisingId = DeviceUtils.getAdvertisingId().get();
if (advertisingId != null)
setTag(Tag.TagType.custom, "AdvertisingID", advertisingId);
} catch (Exception e) {
logger.warning("Failed to get advertisingId: " + e.getMessage());
}
}
});
}
private void setTrackingEnabled() {
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
try {
Boolean trackingEnabled = DeviceUtils.getTrackingEnabled().get();
if (trackingEnabled != null)
setTag(Tag.TagType.custom, "TrackingEnabled", String.valueOf(trackingEnabled));
} catch (Exception e) {
logger.warning("Failed to get trackingEnabled: " + e.getMessage());
}
}
});
}
private void waitClientRegistration() {
if (client == null) {
try {
latch.await();
} catch (InterruptedException e) {
}
}
}
public ReceiveHandler getReceiveHandler() {
return receiveHandler;
}
public void setReceiveHandler(ReceiveHandler receiveHandler) {
this.receiveHandler = receiveHandler;
}
public Logger getLogger() {
return logger;
}
public GrowthbeatHttpClient getHttpClient() {
return httpClient;
}
public Preference getPreference() {
return preference;
}
private void clearClient() {
this.client = null;
Client.clear();
}
}
| growthbeat/src/main/java/com/growthpush/GrowthPush.java | package com.growthpush;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.growthbeat.Growthbeat;
import com.growthbeat.Logger;
import com.growthbeat.Preference;
import com.growthbeat.http.GrowthbeatHttpClient;
import com.growthbeat.message.GrowthMessage;
import com.growthbeat.message.handler.ShowMessageHandler;
import com.growthbeat.utils.AppUtils;
import com.growthbeat.utils.DeviceUtils;
import com.growthpush.handler.DefaultReceiveHandler;
import com.growthpush.handler.ReceiveHandler;
import com.growthpush.model.Client;
import com.growthpush.model.Environment;
import com.growthpush.model.Event;
import com.growthpush.model.Tag;
import android.content.Context;
import android.os.Build;
public class GrowthPush {
private static final GrowthPush instance = new GrowthPush();
private final Logger logger = new Logger(GrowthPushConstants.LOGGER_DEFAULT_TAG);
private final GrowthbeatHttpClient httpClient = new GrowthbeatHttpClient(GrowthPushConstants.HTTP_CLIENT_DEFAULT_BASE_URL,
GrowthPushConstants.HTTP_CLIENT_DEFAULT_CONNECT_TIMEOUT, GrowthPushConstants.HTTP_CLIENT_DEFAULT_READ_TIMEOUT);
private final Preference preference = new Preference(GrowthPushConstants.PREFERENCE_DEFAULT_FILE_NAME);
private Client client = null;
private Semaphore semaphore = new Semaphore(1);
private CountDownLatch latch = new CountDownLatch(1);
private ReceiveHandler receiveHandler = new DefaultReceiveHandler();
private String applicationId;
private String credentialId;
private String senderId;
private Environment environment = null;
private boolean initialized = false;
private GrowthPush() {
super();
}
public static GrowthPush getInstance() {
return instance;
}
public void initialize(final Context context, final String applicationId, final String credentialId, final Environment environment) {
this.initialize(context, applicationId, credentialId, environment, true);
}
public void initialize(final Context context, final String applicationId, final String credentialId, final Environment environment,
final boolean adInfoEnabled) {
if (initialized)
return;
initialized = true;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
logger.warning("This SDK not supported this os.");
return;
}
if (context == null) {
logger.warning("The context parameter cannot be null.");
return;
}
this.applicationId = applicationId;
this.credentialId = credentialId;
this.environment = environment;
Growthbeat.getInstance().initialize(context, applicationId, credentialId);
GrowthMessage.getInstance().initialize(context, applicationId, credentialId);
this.preference.setContext(Growthbeat.getInstance().getContext());
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
com.growthbeat.model.Client growthbeatClient = Growthbeat.getInstance().waitClient();
client = Client.load();
if (client != null && client.getGrowthbeatClientId() != null
&& !client.getGrowthbeatClientId().equals(growthbeatClient.getId()))
GrowthPush.this.clearClient();
createClient(growthbeatClient.getId(), null);
if (adInfoEnabled) {
setAdvertisingId();
setTrackingEnabled();
}
// TODO インストールイベントいらない or 初回のみイベントロジックの変更
trackEvent(Event.EventType.custom, "Install", null, null);
}
});
}
public void requestRegistrationId(final String senderId) {
if (!initialized) {
logger.warning("Growth Push must be initilaize.");
return;
}
this.senderId = senderId;
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
String token = registerGCM(Growthbeat.getInstance().getContext());
if (token != null) {
logger.info("GCM registration token: " + token);
registerClient(token);
}
}
});
}
public String registerGCM(final Context context) {
if (this.senderId == null)
return null;
try {
InstanceID instanceID = InstanceID.getInstance(context);
return instanceID.getToken(this.senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
} catch (Exception e) {
return null;
}
}
public void registerClient(final String registrationId, Environment environment) {
this.environment = environment;
registerClient(registrationId);
}
protected void registerClient(final String registrationId) {
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
com.growthbeat.model.Client growthbeatClient = Growthbeat.getInstance().waitClient();
createClient(growthbeatClient.getId(), registrationId);
if ((registrationId != null && !registrationId.equals(client.getToken())) || environment != client.getEnvironment()) {
updateClient(registrationId);
return;
}
logger.info("Client already registered.");
}
});
}
private void createClient(final String growthbeatClientId, final String registrationId) {
try {
semaphore.acquire();
Client loadClient = Client.load();
if (loadClient != null) {
this.client = loadClient;
logger.info(String.format("Client already Created... (growthbeatClientId: %s, token: %s, environment: %s",
growthbeatClientId, registrationId, environment));
return;
}
logger.info(String.format("Create client... (growthbeatClientId: %s, token: %s, environment: %s", growthbeatClientId,
registrationId, environment));
client = Client.create(growthbeatClientId, applicationId, credentialId, registrationId, environment);
logger.info(String.format("Create client success (clientId: %d)", client.getId()));
Client.save(client);
} catch (InterruptedException e) {
} catch (GrowthPushException e) {
logger.error(String.format("Create client fail. %s", e.getMessage()));
} finally {
semaphore.release();
latch.countDown();
}
}
private void updateClient(final String registrationId) {
try {
logger.info(String.format("Updating client... (growthbeatClientId: %s, token: %s, environment: %s)",
client.getGrowthbeatClientId(), registrationId, environment));
client.setToken(registrationId);
client.setEnvironment(environment);
client = Client.update(client.getGrowthbeatClientId(), applicationId, credentialId, registrationId, environment);
logger.info(String.format("Update client success (clientId: %d)", client.getId()));
Client.save(client);
} catch (GrowthPushException e) {
logger.error(String.format("Update client fail. %s", e.getMessage()));
} finally {
latch.countDown();
}
}
public void trackEvent(final String name) {
trackEvent(name, null);
}
public void trackEvent(final String name, final String value) {
trackEvent(name, null, null);
}
public void trackEvent(final String name, final String value, final ShowMessageHandler handler) {
trackEvent(Event.EventType.custom, name, value, handler);
}
public void trackEvent(final Event.EventType type, final String name, final String value, final ShowMessageHandler handler) {
if (!initialized) {
logger.info("call after initialized.");
return;
}
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
if (name == null) {
logger.warning("Event name cannot be null.");
return;
}
waitClientRegistration();
logger.info(String.format("Sending event ... (name: %s)", name));
try {
Event event = Event.create(GrowthPush.getInstance().client.getGrowthbeatClientId(), applicationId,
GrowthPush.getInstance().credentialId, type, name, value);
logger.info(String.format("Sending event success. (timestamp: %s)", event.getTimestamp()));
if (type != Event.EventType.message)
GrowthMessage.getInstance().recevieMessage(event.getGoalId(), client.getGrowthbeatClientId(), handler);
} catch (GrowthPushException e) {
logger.error(String.format("Sending event fail. %s", e.getMessage()));
}
}
});
}
public void setTag(final String name) {
setTag(name, null);
}
public void setTag(final String name, final String value) {
setTag(Tag.TagType.custom, name, value);
}
private void setTag(final Tag.TagType type, final String name, final String value) {
if (!initialized) {
logger.info("call after initialized.");
return;
}
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
if (name == null) {
logger.warning("Tag name cannot be null.");
return;
}
Tag tag = Tag.load(type, name);
if (tag != null && (value == null || value.equalsIgnoreCase(tag.getValue()))) {
logger.info(String.format("Tag exists with the same value. (name: %s, value: %s)", name, value));
return;
}
waitClientRegistration();
logger.info(String.format("Sending tag... (key: %s, value: %s)", name, value));
try {
Tag createdTag = Tag.create(GrowthPush.getInstance().client.getGrowthbeatClientId(), applicationId, credentialId, type,
name, value);
logger.info(String.format("Sending tag success"));
Tag.save(createdTag, type, name);
} catch (GrowthPushException e) {
logger.error(String.format("Sending tag fail. %s", e.getMessage()));
}
}
});
}
public void setDeviceTags() {
setTag("Device", DeviceUtils.getModel());
setTag("OS", "Android " + DeviceUtils.getOsVersion());
setTag("Language", DeviceUtils.getLanguage());
setTag("Time Zone", DeviceUtils.getTimeZone());
setTag("Version", AppUtils.getaAppVersion(Growthbeat.getInstance().getContext()));
setTag("Build", AppUtils.getAppBuild(Growthbeat.getInstance().getContext()));
}
private void setAdvertisingId() {
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
try {
String advertisingId = DeviceUtils.getAdvertisingId().get();
if (advertisingId != null)
setTag(Tag.TagType.custom, "AdvertisingID", advertisingId);
} catch (Exception e) {
logger.warning("Failed to get advertisingId: " + e.getMessage());
}
}
});
}
private void setTrackingEnabled() {
Growthbeat.getInstance().getExecutor().execute(new Runnable() {
@Override
public void run() {
try {
Boolean trackingEnabled = DeviceUtils.getTrackingEnabled().get();
if (trackingEnabled != null)
setTag(Tag.TagType.custom, "TrackingEnabled", String.valueOf(trackingEnabled));
} catch (Exception e) {
logger.warning("Failed to get trackingEnabled: " + e.getMessage());
}
}
});
}
private void waitClientRegistration() {
if (client == null) {
try {
latch.await();
} catch (InterruptedException e) {
}
}
}
public ReceiveHandler getReceiveHandler() {
return receiveHandler;
}
public void setReceiveHandler(ReceiveHandler receiveHandler) {
this.receiveHandler = receiveHandler;
}
public Logger getLogger() {
return logger;
}
public GrowthbeatHttpClient getHttpClient() {
return httpClient;
}
public Preference getPreference() {
return preference;
}
private void clearClient() {
this.client = null;
Client.clear();
}
}
| Remove Install Event
| growthbeat/src/main/java/com/growthpush/GrowthPush.java | Remove Install Event | <ide><path>rowthbeat/src/main/java/com/growthpush/GrowthPush.java
<ide> setTrackingEnabled();
<ide> }
<ide>
<del> // TODO インストールイベントいらない or 初回のみイベントロジックの変更
<del> trackEvent(Event.EventType.custom, "Install", null, null);
<del>
<ide> }
<ide> });
<ide> |
|
JavaScript | apache-2.0 | 6ea12b7e758fcaffda8fc021d139136b9d86c13a | 0 | Adobe-Consulting-Services/acs-aem-commons,dfoerderreuther/acs-aem-commons,SachinMali/acs-aem-commons,npeltier/acs-aem-commons,dherges/acs-aem-commons,bstopp/acs-aem-commons,bstopp/acs-aem-commons,cpilsworth/acs-aem-commons,cpilsworth/acs-aem-commons,Adobe-Consulting-Services/acs-aem-commons,MikePfaff/acs-aem-commons,SachinMali/acs-aem-commons,MikePfaff/acs-aem-commons,schoudry/acs-aem-commons,cpilsworth/acs-aem-commons,MikePfaff/acs-aem-commons,dfoerderreuther/acs-aem-commons,SachinMali/acs-aem-commons,steffenrosi/acs-aem-commons,dfoerderreuther/acs-aem-commons,steffenrosi/acs-aem-commons,schoudry/acs-aem-commons,Sivaramvt/acs-aem-commons,Sivaramvt/acs-aem-commons,steffenrosi/acs-aem-commons,dfoerderreuther/acs-aem-commons,Adobe-Consulting-Services/acs-aem-commons,dherges/acs-aem-commons,npeltier/acs-aem-commons,bstopp/acs-aem-commons,badvision/acs-aem-commons,Sivaramvt/acs-aem-commons,npeltier/acs-aem-commons,MikePfaff/acs-aem-commons,bstopp/acs-aem-commons,npeltier/acs-aem-commons,badvision/acs-aem-commons,dherges/acs-aem-commons,cpilsworth/acs-aem-commons,Sivaramvt/acs-aem-commons,dherges/acs-aem-commons,badvision/acs-aem-commons,steffenrosi/acs-aem-commons,schoudry/acs-aem-commons,Adobe-Consulting-Services/acs-aem-commons,schoudry/acs-aem-commons,badvision/acs-aem-commons,SachinMali/acs-aem-commons | /*
* #%L
* ACS AEM Commons Package
* %%
* Copyright (C) 2013 Adobe
* %%
* 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.
* #L%
*/
/*global CQ: false, ACS: false */
/*jslint eval: true
*/
CQ.Ext.ns("ACS.CQ");
ACS.CQ.GraphicIconSelection = CQ.Ext.extend(CQ.form.CompositeField, {
/**
* @cfg {Boolean} allowBlank
* False to validate that an item is selected.<br>
* Defaults to true.
*/
allowBlank: true,
autoEl: { tag: 'div' },
/**
* @cfg {Object[]/String} options
* <p>The options of the selection. An option has the properties "value", "text"
* and "image".</p>
* Example for the object array structure:
* <pre><code>
[
{
value: "pink",
text: "Pink"
}
]
</code></pre>
* <p>If options is a string it is assumed to be an URL pointing to a JSON
* resource that returns the options (same structure as above applies). This
* should be either an absolute URL or it can use the path of the content
* resource being edited using a placeholder
* ({@link #Selection.PATH_PLACEHOLDER} = "$PATH"), for example:
* <code>$PATH.options.json</code>.</p>
* <p>Set {@link #optionsRoot} and
* {@link #optionsTextField}, {@link #optionsValueField} or {@link #optionsImageField}
* if the properties are named differently and/or if the array with the options is
* in a sub-property of the JSON returned from the URL.</p>
*/
options: null,
/**
* @cfg {String} optionsRoot
* <p>Name of the property containing the options array when using a custom JSON URL
* for {@link #options}. Use "." to denote the root object/array of the result itself.</p>
* <p>Only if optionsRoot is set, {@link #optionsTextField}, {@link #optionsValueField} and
* {@link #optionsImageField} will be used. If optionsRoot is <em>not</em> set, the returned
* JSON must be a standard widgets json, "resulting" in the exact format as described in
* {@link #options} - it will also be passed through {@link CQ.Util#formatData}. Not set by default.
*/
optionsRoot: null,
/**
* @cfg {String} optionsTextField
* Name of the field for the options text when using a custom JSON URL for {@link #options}
* (defaults to "text"). Only used if {@link #optionsRoot} is set.
*/
optionsTextField: null,
/**
* @cfg {String} optionsValueField
* name of the field for the options value when using a custom JSON URL for {@link #options}
* (defaults to "value"). Only used if {@link #optionsRoot} is set.
*/
optionsValueField: null,
/**
* @cfg {String} optionsImageField
* Name of the field for the options image when using a custom JSON URL for {@link #options}
* (defaults to "image"). Only used if {@link #optionsRoot} is set.
*/
optionsImageField: null,
/**
* @cfg {Function/String} optionsCallback
* <p>A function or the name of a function that is called on <code>processRecords</code>
* to populate the options.</p>
* <p>The function allows to set or request options that depend on the current
* path or content record.
* <div class="mdetail-params">
* <strong style="font-weight: normal;">The function will be called with the following arguments:</strong>
* <ul><li><code>path</code> : String<div class="sub-desc">The content path</div></li></ul>
* <ul><li><code>record</code> : CQ.Ext.data.Record<div class="sub-desc">The content record</div></li></ul>
* </div>
* @deprecated Use {@link #optionsProvider} instead
*/
optionsCallback: null,
/**
* @cfg {Function/String} optionsProvider
* <p>A function or the name of a function that will be called on <code>processRecords</code>
* to receive the options. The function must return an array of options. See {@link #options}
* for more information on options.</p>
* <p>The options provider allows to set or request options that depend on the current
* path or content record.
* <div class="mdetail-params">
* <strong style="font-weight: normal;">The provider will be called with the following arguments:</strong>
* <ul><li><code>path</code> : String<div class="sub-desc">The content path</div></li></ul>
* <ul><li><code>record</code> : CQ.Ext.data.Record<div class="sub-desc">The content record</div></li></ul>
* </div>
* @since 5.3
*/
optionsProvider: null,
/**
* @cfg {Object} optionsConfig
* The config of the options components. For selections of type "checkbox" and
* "radio" optionsConfig will be passed to every single
* {@link CQ.Ext.form.CheckBox CheckBox} or {@link CQ.Ext.form.Radio Radio}.
* For "select" and "combobox" optionsConfig will be passed to the underlaying
* {@link CQ.Ext.form.ComboBox ComboBox}.<br>
* Please check the underlaying component's config options to see the possible
* properties. Be aware that some properties are set internally and cannot
* be overwritten.
* @type Object
*/
optionsConfig: null,
/**
* @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails
* (for selections of type checkbox only).
* Defaults to "You must select at least one item in this group".
* @since 5.4
*/
blankText : CQ.I18n.getMessage("You must select an item in this group"),
/**
* @cfg {String} sortDir
* The sort direction of the the options. If "ASC" or "DESC" the options will
* be sorted by its (internationalized) text. Defaults to <code>null</code>.
* @since 5.4
*/
sortDir: null,
/**
* Hidden field of selections of type "select".
* @type CQ.Ext.form.Hidden
* @private
*/
hiddenField: null,
/**
* Returns the normalized data value. "undefined" or the combo box'
* {@link CQ.Ext.form.ComboBox#emptyText emptyText} return an empty
* string (""). Type "checkbox" return always an array even if there is
* only single checkbox available.<br>
* To return the raw value see {@link #getRawValue}.
* @return {String/String[]} value The field value
*/
getValue : function(){
if(!this.rendered) {
return this.value !== null ? this.value : "";
}
return this.hiddenField.getValue();
},
/**
* Loads the options of the selection if an optionsProvider is available.
* This method is usually called solely by {@link CQ.Dialog} after its
* content has been loaded.
* @param {String} path content path (optional)
* @private
*/
processPath: function(path) {
var options = [],
p,
url;
if (this.optionsProvider) {
// @since 5.3
if (path === undefined) {
path = null;
}
try {
if (typeof this.optionsProvider !== "function") {
try {
eval("p = " + this.optionsProvider); // jshint ignore:line
options = p.call(this, path);
}
catch (e1) {
CQ.Log.warn("Selection#processPath: failed to evaluate optionsProvider: " + e1.message);
}
} else {
options = this.optionsProvider.call(this, path);
}
this.setOptions(options);
}
catch (e2) {
CQ.Log.warn("Selection#processPath: " + e2.message);
}
} else if (this.optionsCallback) {
// @deprecated
if (path === undefined) {
path = null;
}
try {
if (typeof this.optionsCallback !== "function") {
try {
eval(this.optionsCallback).call(this, path); // jshint ignore:line
}
catch (e3) {
CQ.Log.warn("Selection#processPath: failed to evaluate optionsCallback: " + e3.message);
}
}
else {
this.optionsCallback.call(this, path);
}
} catch (e4) {
CQ.Log.warn("Selection#processPath: failed to call optionsCallback: " + e4.message);
}
} else if (this.contentBasedOptionsURL) {
url = this.contentBasedOptionsURL;
url = url.replace(ACS.CQ.GraphicIconSelection.PATH_PLACEHOLDER_REGEX, path);
this.setOptions(this.fetchOptions(url, this));
}
},
/**
* Sets the options of the selection.
* @param {Object[]} options The options
* <pre><code>
[
{
value: "pink",
text: "Pink",
image: "/etc/project/designs/images/pink-thing.png"
}
]
</code></pre>
*/
setOptions: function(options) {
if (this.rendered) {
this.doLayout();
}
},
/**
* Sorts the options by its title
* @private
*/
sortOptions: function(o) {
if (this.sortDir !== "ASC" && this.sortDir !== "DESC") {
return;
}
var x = this.sortDir === "ASC" ? 1 : -1;
o.sort(function(a, b) {
var ta = a.text.toLowerCase(),
tb = b.text.toLowerCase();
if (ta > tb) {
return x;
}
if (ta < tb) {
return -x;
}
return 0;
});
},
/**
* Sets a data value into the field and validates it. Multiple values for
* selections of type "checkbox" are passed as an array. If an array is
* passed to other types the first value is taken.
* @param {String/String[]} value The value to set
*/
setValue: function(value){
value = value || '';
var jqThis = jQuery(this.getEl().dom),
jqList = jqThis.find('.graphic-selection-list'),
jqCurrent = jqThis.find('.graphic-selection-current'),
jqItems = jqThis.find('.graphic-selection-item'),
currentItem = jqThis.find("[data-value='" + value + "']");
jqItems.removeClass('selected');
currentItem.addClass('selected');
this.hiddenField.setValue(value);
},
/**
* Validates a value according to the field's validation rules and marks the field as invalid
* if the validation fails
* @param {Mixed} value The value to validate
* @return {Boolean} True if the value is valid, else false
*/
validateValue: function(value){
return this.hiddenField.validateValue(value);
},
// TODO - Rework these
// overriding CQ.form.CompositeField#markInvalid
markInvalid : function(msg){
this.fireEvent('invalid', this, msg);
},
// overriding CQ.form.CompositeField#clearInvalid
clearInvalid : function(){
this.fireEvent('valid', this);
},
/**
* Fetches the options via HTTP.
* @private
*/
fetchOptions: function(url, config) {
var options = [],
json,
optVF,
optTF,
optTFXSS,
root,
opt,
i;
try {
json = CQ.HTTP.eval(url); // jshint ignore:line
if (config.optionsRoot) {
// convert ext format to our format
optVF = config.optionsValueField || "value";
optTF = config.optionsTextField || "text";
optTFXSS = CQ.shared.XSS.getXSSPropertyName(optTF);
root = (config.optionsRoot === ".") ? json : json[config.optionsRoot];
for (i = 0; i < root.length; i++) {
opt = {
value: root[i][optVF],
text: root[i][optTF],
text_xss: root[i][optTFXSS]
};
options.push(opt);
}
} else {
options = CQ.Util.formatData(json);
}
}
catch (e) {
CQ.Log.warn("CQ.form.GraphicIconSelection#fetchOptions failed: " + e.message);
options = [];
}
var optionsToReturn = [];
for (i = 0; i < options.length; i++) {
//if(options[i].value !== "") {
optionsToReturn.push(options[i]);
//}
}
return optionsToReturn;
},
constructor: function(config) {
if (config.allowBlank !== undefined) {
this.allowBlank = config.allowBlank;
}
if (config.optionsCallback) {
this.optionsCallback = config.optionsCallback;
if (!config.options) config.options = [];
}
if (typeof config.options == "string") {
if (config.options.indexOf(ACS.CQ.GraphicIconSelection.PATH_PLACEHOLDER) >= 0) {
// if $path as reference to content path is used, we have to delay
// the option fetching until processPath() is called
this.contentBasedOptionsURL = config.options;
config.options = [];
} else {
config.options = this.fetchOptions(config.options, config);
}
}
else if (!config.options) {
config.options = [];
}
this.optionsConfig = config.optionsConfig ? config.optionsConfig : {};
var defaults = {
height: "auto",
hideMode: "display"
};
CQ.Util.applyDefaults(config, defaults);
CQ.form.CompositeField.superclass.constructor.call(this, config);
this.hiddenField = new CQ.Ext.form.Hidden({ name: this.name });
this.add(this.hiddenField);
this.options = config.options;
},
/**
* Initializes the component by registering specific events.
* @private
*/
initComponent: function() {
ACS.CQ.GraphicIconSelection.superclass.initComponent.call(this);
// cq-selection is required to address invalid checkboxes in CSS
this.addClass(CQ.DOM.encodeClass(this.name) + " graphic-selection icon-selection");
this.addEvents(
/**
* @event selectionchanged
* Fires when the user changes the selection/interacts with the selection
* control(s). Note that the event is sent on selection and deselection for
* checkboxes, but only on selection for radiobuttons and comboboxes. Also note
* that the event currently does not get fired for the initial selection of
* a combobox.
* @param {CQ.form.Selection} this
* @param {Mixed} value The raw value of the selected, checked or unchecked
* option or the entered value of a combobox
* @param {Boolean} isChecked <code>false</code> if a checkbox has been unchecked,
* <code>true</code> otherwise
*/
ACS.CQ.GraphicIconSelection.EVENT_SELECTION_CHANGED
);
},
onRender: function(ct, pos) {
ACS.CQ.GraphicIconSelection.superclass.onRender.call(this, ct, pos);
var t = this.tpl || new CQ.Ext.XTemplate(
'<div class="graphic-selection-list clearfix image-staging">' +
'<tpl for=".">' +
'<a href="#" class="graphic-selection-item" data-value="{value}" title="{text}">' +
'<div class="graphic-selection-image">' +
'<i class="fa {value}"></i>' +
'</div>' +
'</a>' +
'</tpl>' +
'</div>'
);
t.append(this.el, this.options);
var extThis = this,
jqThis = jQuery(this.getEl().dom),
jqList = jqThis.find('.graphic-selection-list'),
listItems = jqList.find('.graphic-selection-item'),
listImageContainers = jqList.find('.graphic-selection-image');
listItems.click(function(e) {
e.preventDefault();
if (!this.disabled) {
extThis.setValue($(this).data('value'));
}
});
if (this.value !== null) {
this.setValue(this.value);
}
},
// Overrides the original implementation and disables all composite fields.
disable: function() {
ACS.CQ.GraphicIconSelection.superclass.disable.call(this);
this.disabled = true;
this.addClass('disabled');
return this;
},
// Overrides the original implementation and enables all composite fields.
enable: function() {
ACS.CQ.GraphicIconSelection.superclass.enable.call(this);
this.disabled = false;
this.removeClass('disabled');
return this;
},
focus: CQ.Ext.emptyFn,
blur: CQ.Ext.emptyFn
});
/**
* Name of the "selectionchanged" event which is fired when the user changes the
* value of a selection.
* @static
* @final
* @String
*/
ACS.CQ.GraphicIconSelection.EVENT_SELECTION_CHANGED = "selectionchanged";
/**
* Placeholder to use in "options" config when given as URL. Will be
* replaced with the path to the resource currently being edited in
* a CQ.Dialog.
* @static
* @final
* @String
*/
ACS.CQ.GraphicIconSelection.PATH_PLACEHOLDER = "$PATH";
/**
* Regexp variant of above, including global match/replace. For
* internal use only.
* @static
* @private
* @final
* @String
*/
ACS.CQ.GraphicIconSelection.PATH_PLACEHOLDER_REGEX = /\$PATH/g;
CQ.Ext.reg("graphiciconselection", ACS.CQ.GraphicIconSelection);
| content/src/main/content/jcr_root/apps/acs-commons/widgets/source/js/icon-picker.js | /*
* #%L
* ACS AEM Commons Package
* %%
* Copyright (C) 2013 Adobe
* %%
* 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.
* #L%
*/
/*global CQ: false, ACS: false */
/*jslint eval: true
*/
CQ.Ext.ns("ACS.CQ");
ACS.CQ.GraphicIconSelection = CQ.Ext.extend(CQ.form.CompositeField, {
/**
* @cfg {Boolean} allowBlank
* False to validate that an item is selected.<br>
* Defaults to true.
*/
allowBlank: true,
autoEl: { tag: 'div' },
/**
* @cfg {Object[]/String} options
* <p>The options of the selection. An option has the properties "value", "text"
* and "image".</p>
* Example for the object array structure:
* <pre><code>
[
{
value: "pink",
text: "Pink"
}
]
</code></pre>
* <p>If options is a string it is assumed to be an URL pointing to a JSON
* resource that returns the options (same structure as above applies). This
* should be either an absolute URL or it can use the path of the content
* resource being edited using a placeholder
* ({@link #Selection.PATH_PLACEHOLDER} = "$PATH"), for example:
* <code>$PATH.options.json</code>.</p>
* <p>Set {@link #optionsRoot} and
* {@link #optionsTextField}, {@link #optionsValueField} or {@link #optionsImageField}
* if the properties are named differently and/or if the array with the options is
* in a sub-property of the JSON returned from the URL.</p>
*/
options: null,
/**
* @cfg {String} optionsRoot
* <p>Name of the property containing the options array when using a custom JSON URL
* for {@link #options}. Use "." to denote the root object/array of the result itself.</p>
* <p>Only if optionsRoot is set, {@link #optionsTextField}, {@link #optionsValueField} and
* {@link #optionsImageField} will be used. If optionsRoot is <em>not</em> set, the returned
* JSON must be a standard widgets json, "resulting" in the exact format as described in
* {@link #options} - it will also be passed through {@link CQ.Util#formatData}. Not set by default.
*/
optionsRoot: null,
/**
* @cfg {String} optionsTextField
* Name of the field for the options text when using a custom JSON URL for {@link #options}
* (defaults to "text"). Only used if {@link #optionsRoot} is set.
*/
optionsTextField: null,
/**
* @cfg {String} optionsValueField
* name of the field for the options value when using a custom JSON URL for {@link #options}
* (defaults to "value"). Only used if {@link #optionsRoot} is set.
*/
optionsValueField: null,
/**
* @cfg {String} optionsImageField
* Name of the field for the options image when using a custom JSON URL for {@link #options}
* (defaults to "image"). Only used if {@link #optionsRoot} is set.
*/
optionsImageField: null,
/**
* @cfg {Function/String} optionsCallback
* <p>A function or the name of a function that is called on <code>processRecords</code>
* to populate the options.</p>
* <p>The function allows to set or request options that depend on the current
* path or content record.
* <div class="mdetail-params">
* <strong style="font-weight: normal;">The function will be called with the following arguments:</strong>
* <ul><li><code>path</code> : String<div class="sub-desc">The content path</div></li></ul>
* <ul><li><code>record</code> : CQ.Ext.data.Record<div class="sub-desc">The content record</div></li></ul>
* </div>
* @deprecated Use {@link #optionsProvider} instead
*/
optionsCallback: null,
/**
* @cfg {Function/String} optionsProvider
* <p>A function or the name of a function that will be called on <code>processRecords</code>
* to receive the options. The function must return an array of options. See {@link #options}
* for more information on options.</p>
* <p>The options provider allows to set or request options that depend on the current
* path or content record.
* <div class="mdetail-params">
* <strong style="font-weight: normal;">The provider will be called with the following arguments:</strong>
* <ul><li><code>path</code> : String<div class="sub-desc">The content path</div></li></ul>
* <ul><li><code>record</code> : CQ.Ext.data.Record<div class="sub-desc">The content record</div></li></ul>
* </div>
* @since 5.3
*/
optionsProvider: null,
/**
* @cfg {Object} optionsConfig
* The config of the options components. For selections of type "checkbox" and
* "radio" optionsConfig will be passed to every single
* {@link CQ.Ext.form.CheckBox CheckBox} or {@link CQ.Ext.form.Radio Radio}.
* For "select" and "combobox" optionsConfig will be passed to the underlaying
* {@link CQ.Ext.form.ComboBox ComboBox}.<br>
* Please check the underlaying component's config options to see the possible
* properties. Be aware that some properties are set internally and cannot
* be overwritten.
* @type Object
*/
optionsConfig: null,
/**
* @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails
* (for selections of type checkbox only).
* Defaults to "You must select at least one item in this group".
* @since 5.4
*/
blankText : CQ.I18n.getMessage("You must select an item in this group"),
/**
* @cfg {String} sortDir
* The sort direction of the the options. If "ASC" or "DESC" the options will
* be sorted by its (internationalized) text. Defaults to <code>null</code>.
* @since 5.4
*/
sortDir: null,
/**
* Hidden field of selections of type "select".
* @type CQ.Ext.form.Hidden
* @private
*/
hiddenField: null,
/**
* Returns the normalized data value. "undefined" or the combo box'
* {@link CQ.Ext.form.ComboBox#emptyText emptyText} return an empty
* string (""). Type "checkbox" return always an array even if there is
* only single checkbox available.<br>
* To return the raw value see {@link #getRawValue}.
* @return {String/String[]} value The field value
*/
getValue : function(){
if(!this.rendered) {
return this.value !== null ? this.value : "";
}
return this.hiddenField.getValue();
},
/**
* Loads the options of the selection if an optionsProvider is available.
* This method is usually called solely by {@link CQ.Dialog} after its
* content has been loaded.
* @param {String} path content path (optional)
* @private
*/
processPath: function(path) {
var options = [],
p,
url;
if (this.optionsProvider) {
// @since 5.3
if (path === undefined) {
path = null;
}
try {
if (typeof this.optionsProvider !== "function") {
try {
eval("p = " + this.optionsProvider);
options = p.call(this, path);
}
catch (e1) {
CQ.Log.warn("Selection#processPath: failed to evaluate optionsProvider: " + e1.message);
}
} else {
options = this.optionsProvider.call(this, path);
}
this.setOptions(options);
}
catch (e2) {
CQ.Log.warn("Selection#processPath: " + e2.message);
}
} else if (this.optionsCallback) {
// @deprecated
if (path === undefined) {
path = null;
}
try {
if (typeof this.optionsCallback !== "function") {
try {
eval(this.optionsCallback).call(this, path);
}
catch (e3) {
CQ.Log.warn("Selection#processPath: failed to evaluate optionsCallback: " + e3.message);
}
}
else {
this.optionsCallback.call(this, path);
}
} catch (e4) {
CQ.Log.warn("Selection#processPath: failed to call optionsCallback: " + e4.message);
}
} else if (this.contentBasedOptionsURL) {
url = this.contentBasedOptionsURL;
url = url.replace(ACS.CQ.GraphicIconSelection.PATH_PLACEHOLDER_REGEX, path);
this.setOptions(this.fetchOptions(url, this));
}
},
/**
* Sets the options of the selection.
* @param {Object[]} options The options
* <pre><code>
[
{
value: "pink",
text: "Pink",
image: "/etc/project/designs/images/pink-thing.png"
}
]
</code></pre>
*/
setOptions: function(options) {
if (this.rendered) {
this.doLayout();
}
},
/**
* Sorts the options by its title
* @private
*/
sortOptions: function(o) {
if (this.sortDir !== "ASC" && this.sortDir !== "DESC") {
return;
}
var x = this.sortDir === "ASC" ? 1 : -1;
o.sort(function(a, b) {
var ta = a.text.toLowerCase(),
tb = b.text.toLowerCase();
if (ta > tb) {
return x;
}
if (ta < tb) {
return -x;
}
return 0;
});
},
/**
* Sets a data value into the field and validates it. Multiple values for
* selections of type "checkbox" are passed as an array. If an array is
* passed to other types the first value is taken.
* @param {String/String[]} value The value to set
*/
setValue: function(value){
value = value || '';
var jqThis = jQuery(this.getEl().dom),
jqList = jqThis.find('.graphic-selection-list'),
jqCurrent = jqThis.find('.graphic-selection-current'),
jqItems = jqThis.find('.graphic-selection-item'),
currentItem = jqThis.find("[data-value='" + value + "']");
jqItems.removeClass('selected');
currentItem.addClass('selected');
this.hiddenField.setValue(value);
},
/**
* Validates a value according to the field's validation rules and marks the field as invalid
* if the validation fails
* @param {Mixed} value The value to validate
* @return {Boolean} True if the value is valid, else false
*/
validateValue: function(value){
return this.hiddenField.validateValue(value);
},
// TODO - Rework these
// overriding CQ.form.CompositeField#markInvalid
markInvalid : function(msg){
this.fireEvent('invalid', this, msg);
},
// overriding CQ.form.CompositeField#clearInvalid
clearInvalid : function(){
this.fireEvent('valid', this);
},
/**
* Fetches the options via HTTP.
* @private
*/
fetchOptions: function(url, config) {
var options = [],
json,
optVF,
optTF,
optTFXSS,
root,
opt,
i;
try {
json = CQ.HTTP.eval(url);
if (config.optionsRoot) {
// convert ext format to our format
optVF = config.optionsValueField || "value";
optTF = config.optionsTextField || "text";
optTFXSS = CQ.shared.XSS.getXSSPropertyName(optTF);
root = (config.optionsRoot === ".") ? json : json[config.optionsRoot];
for (i = 0; i < root.length; i++) {
opt = {
value: root[i][optVF],
text: root[i][optTF],
text_xss: root[i][optTFXSS]
};
options.push(opt);
}
} else {
options = CQ.Util.formatData(json);
}
}
catch (e) {
CQ.Log.warn("CQ.form.GraphicIconSelection#fetchOptions failed: " + e.message);
options = [];
}
var optionsToReturn = [];
for (var i=0; i<options.length; i++) {
//if(options[i].value !== "") {
optionsToReturn.push(options[i]);
//}
}
return optionsToReturn;
},
constructor: function(config) {
if (config.allowBlank != undefined) this.allowBlank = config.allowBlank;
if (config.optionsCallback) {
this.optionsCallback = config.optionsCallback;
if (!config.options) config.options = [];
}
if (typeof config.options == "string") {
if (config.options.indexOf(ACS.CQ.GraphicIconSelection.PATH_PLACEHOLDER) >= 0) {
// if $path as reference to content path is used, we have to delay
// the option fetching until processPath() is called
this.contentBasedOptionsURL = config.options;
config.options = [];
} else {
config.options = this.fetchOptions(config.options, config);
}
}
else if (!config.options) {
config.options = [];
}
this.optionsConfig = config.optionsConfig ? config.optionsConfig : {};
var defaults = {
height: "auto",
hideMode: "display"
};
CQ.Util.applyDefaults(config, defaults);
CQ.form.CompositeField.superclass.constructor.call(this, config);
this.hiddenField = new CQ.Ext.form.Hidden({ name: this.name });
this.add(this.hiddenField);
this.options = config.options;
},
/**
* Initializes the component by registering specific events.
* @private
*/
initComponent: function() {
ACS.CQ.GraphicIconSelection.superclass.initComponent.call(this);
// cq-selection is required to address invalid checkboxes in CSS
this.addClass(CQ.DOM.encodeClass(this.name) + " graphic-selection icon-selection");
this.addEvents(
/**
* @event selectionchanged
* Fires when the user changes the selection/interacts with the selection
* control(s). Note that the event is sent on selection and deselection for
* checkboxes, but only on selection for radiobuttons and comboboxes. Also note
* that the event currently does not get fired for the initial selection of
* a combobox.
* @param {CQ.form.Selection} this
* @param {Mixed} value The raw value of the selected, checked or unchecked
* option or the entered value of a combobox
* @param {Boolean} isChecked <code>false</code> if a checkbox has been unchecked,
* <code>true</code> otherwise
*/
ACS.CQ.GraphicIconSelection.EVENT_SELECTION_CHANGED
);
},
onRender: function(ct, pos) {
ACS.CQ.GraphicIconSelection.superclass.onRender.call(this, ct, pos);
var t = this.tpl || new CQ.Ext.XTemplate(
'<div class="graphic-selection-list clearfix image-staging">' +
'<tpl for=".">' +
'<a href="#" class="graphic-selection-item" data-value="{value}" title="{text}">' +
'<div class="graphic-selection-image">' +
'<i class="fa {value}"></i>' +
'</div>' +
'</a>' +
'</tpl>' +
'</div>'
);
t.append(this.el, this.options);
var extThis = this,
jqThis = jQuery(this.getEl().dom),
jqList = jqThis.find('.graphic-selection-list'),
listItems = jqList.find('.graphic-selection-item'),
listImageContainers = jqList.find('.graphic-selection-image');
listItems.click(function(e) {
e.preventDefault();
if (!this.disabled) {
extThis.setValue($(this).data('value'));
}
});
if (this.value != null) {
this.setValue(this.value);
}
},
// Overrides the original implementation and disables all composite fields.
disable: function() {
ACS.CQ.GraphicIconSelection.superclass.disable.call(this);
this.disabled = true;
this.addClass('disabled');
return this;
},
// Overrides the original implementation and enables all composite fields.
enable: function() {
ACS.CQ.GraphicIconSelection.superclass.enable.call(this);
this.disabled = false;
this.removeClass('disabled');
return this;
},
focus: CQ.Ext.emptyFn,
blur: CQ.Ext.emptyFn
});
/**
* Name of the "selectionchanged" event which is fired when the user changes the
* value of a selection.
* @static
* @final
* @String
*/
ACS.CQ.GraphicIconSelection.EVENT_SELECTION_CHANGED = "selectionchanged";
/**
* Placeholder to use in "options" config when given as URL. Will be
* replaced with the path to the resource currently being edited in
* a CQ.Dialog.
* @static
* @final
* @String
*/
ACS.CQ.GraphicIconSelection.PATH_PLACEHOLDER = "$PATH";
/**
* Regexp variant of above, including global match/replace. For
* internal use only.
* @static
* @private
* @final
* @String
*/
ACS.CQ.GraphicIconSelection.PATH_PLACEHOLDER_REGEX = /\$PATH/g;
CQ.Ext.reg("graphiciconselection", ACS.CQ.GraphicIconSelection);
| fixing last few jshint errors
| content/src/main/content/jcr_root/apps/acs-commons/widgets/source/js/icon-picker.js | fixing last few jshint errors | <ide><path>ontent/src/main/content/jcr_root/apps/acs-commons/widgets/source/js/icon-picker.js
<ide> try {
<ide> if (typeof this.optionsProvider !== "function") {
<ide> try {
<del> eval("p = " + this.optionsProvider);
<add> eval("p = " + this.optionsProvider); // jshint ignore:line
<ide> options = p.call(this, path);
<ide> }
<ide> catch (e1) {
<ide> try {
<ide> if (typeof this.optionsCallback !== "function") {
<ide> try {
<del> eval(this.optionsCallback).call(this, path);
<add> eval(this.optionsCallback).call(this, path); // jshint ignore:line
<ide> }
<ide> catch (e3) {
<ide> CQ.Log.warn("Selection#processPath: failed to evaluate optionsCallback: " + e3.message);
<ide> i;
<ide>
<ide> try {
<del> json = CQ.HTTP.eval(url);
<add> json = CQ.HTTP.eval(url); // jshint ignore:line
<ide> if (config.optionsRoot) {
<ide> // convert ext format to our format
<ide> optVF = config.optionsValueField || "value";
<ide>
<ide> var optionsToReturn = [];
<ide>
<del> for (var i=0; i<options.length; i++) {
<add> for (i = 0; i < options.length; i++) {
<ide> //if(options[i].value !== "") {
<ide> optionsToReturn.push(options[i]);
<ide> //}
<ide> },
<ide>
<ide> constructor: function(config) {
<del> if (config.allowBlank != undefined) this.allowBlank = config.allowBlank;
<add> if (config.allowBlank !== undefined) {
<add> this.allowBlank = config.allowBlank;
<add> }
<ide>
<ide> if (config.optionsCallback) {
<ide> this.optionsCallback = config.optionsCallback;
<ide> }
<ide> });
<ide>
<del> if (this.value != null) {
<add> if (this.value !== null) {
<ide> this.setValue(this.value);
<ide> }
<ide> }, |
|
Java | mit | 1402c1196dba2024442f4e9e06ee6b00741491b5 | 0 | Ordinastie/MalisisCore | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Ordinastie
*
* 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 net.malisis.core.renderer.font;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import net.malisis.core.MalisisCore;
import net.malisis.core.client.gui.GuiRenderer;
import net.malisis.core.renderer.MalisisRenderer;
import net.malisis.core.renderer.element.Face;
import net.malisis.core.renderer.element.Shape;
import net.malisis.core.renderer.element.face.SouthFace;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.apache.commons.lang3.StringUtils;
import org.lwjgl.opengl.GL11;
import com.google.common.io.Files;
/**
* @author Ordinastie
*
*/
public class MalisisFont
{
public static MalisisFont minecraftFont = new MinecraftFont();
private static Pattern pattern = Pattern.compile("\\{(.*?)}");
/** AWT font used **/
protected Font font;
/** Font render context **/
protected FontRenderContext frc;
/** Options for the font **/
protected FontGeneratorOptions options = FontGeneratorOptions.DEFAULT;
/** Data for each character **/
protected CharData[] charData = new CharData[256];
/** ResourceLocation for the texture **/
protected ResourceLocation textureRl;
/** Size of the texture (width and height) **/
protected int size;
/** Whether the currently drawn text is the shadow part **/
protected boolean drawingShadow = false;
public MalisisFont(File fontFile)
{
this(load(fontFile, FontGeneratorOptions.DEFAULT), null);
}
public MalisisFont(File fontFile, FontGeneratorOptions options)
{
this(load(fontFile, options), options);
}
public MalisisFont(ResourceLocation fontFile)
{
this(load(fontFile, FontGeneratorOptions.DEFAULT), null);
}
public MalisisFont(ResourceLocation fontFile, FontGeneratorOptions options)
{
this(load(fontFile, options), options);
}
public MalisisFont(Font font)
{
this(font, null);
}
public MalisisFont(Font font, FontGeneratorOptions options)
{
this.font = font;
if (font == null)
return;
if (options != null)
this.options = options;
loadCharacterData();
loadTexture(false);
}
public ResourceLocation getResourceLocation()
{
return textureRl;
}
public void generateTexture(boolean debug)
{
this.options.debug = debug;
loadCharacterData();
loadTexture(true);
}
public CharData getCharData(char c)
{
if (c < 0 || c > charData.length)
c = '?';
return charData[c];
}
public Shape getShape(String text, float fontSize)
{
text = processString(text, null);
List<Face> faces = new ArrayList<>();
float offset = 0;
float factor = options.fontSize / fontSize;
for (int i = 0; i < text.length(); i++)
{
CharData cd = getCharData(text.charAt(i));
if (cd.getChar() != ' ')
{
Face f = new SouthFace();
f.scale(cd.getFullWidth(options) / factor, cd.getFullHeight(options) / factor, 0);
f.translate((offset - options.mx) / factor, -options.my / factor, 0);
f.setTexture(cd.getIcon());
faces.add(f);
}
offset += cd.getCharWidth();
}
return new Shape(faces).storeState();
}
//#region Prepare/Clean
protected void prepare(MalisisRenderer renderer, float x, float y, float z, FontRenderOptions fro)
{
boolean isGui = renderer instanceof GuiRenderer;
renderer.next(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
Minecraft.getMinecraft().getTextureManager().bindTexture(textureRl);
GL11.glPushMatrix();
GL11.glTranslatef(x, y + (isGui ? 0 : fro.fontScale), z);
if (!isGui)
GL11.glScalef(1 / 9F, -1 / 9F, 1 / 9F);
}
protected void clean(MalisisRenderer renderer, boolean isDrawing)
{
if (isDrawing)
renderer.next(MalisisRenderer.malisisVertexFormat);
else
renderer.draw();
if (renderer instanceof GuiRenderer)
Minecraft.getMinecraft().getTextureManager().bindTexture(((GuiRenderer) renderer).getDefaultTexture().getResourceLocation());
GL11.glPopMatrix();
}
protected void prepareShadow(MalisisRenderer renderer)
{
drawingShadow = true;
if (renderer instanceof GuiRenderer)
return;
renderer.next();
GL11.glPolygonOffset(3.0F, 3.0F);
GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
}
protected void cleanShadow(MalisisRenderer renderer)
{
drawingShadow = false;
if (renderer instanceof GuiRenderer)
return;
renderer.next();
GL11.glPolygonOffset(0.0F, 0.0F);
GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
}
protected void prepareLines(MalisisRenderer renderer, FontRenderOptions fro)
{
renderer.next(DefaultVertexFormats.POSITION_COLOR);
renderer.disableTextures();
}
protected void cleanLines(MalisisRenderer renderer)
{
renderer.next();
renderer.enableTextures();
}
//#end Prepare/Clean
public void render(MalisisRenderer renderer, String text, float x, float y, float z, FontRenderOptions fro)
{
if (StringUtils.isEmpty(text))
return;
boolean isDrawing = renderer.isDrawing();
prepare(renderer, x, y, z, fro);
text = processString(text, fro);
if (fro.shadow)
{
prepareShadow(renderer);
drawString(text, fro);
cleanShadow(renderer);
}
drawString(text, fro);
if (hasLines(text, fro))
{
prepareLines(renderer, fro);
if (fro.shadow)
{
prepareShadow(renderer);
drawLines(text, fro);
cleanShadow(renderer);
}
drawLines(text, fro);
cleanLines(renderer);
}
clean(renderer, isDrawing);
}
protected void drawString(String text, FontRenderOptions fro)
{
float x = 0;
fro.resetStylesLine();
StringWalker walker = new StringWalker(text, this, fro);
walker.applyStyles(true);
while (walker.walk())
{
CharData cd = getCharData(walker.getChar());
drawChar(cd, x, 0, fro);
x += walker.getWidth();
}
}
protected void drawChar(CharData cd, float offsetX, float offsetY, FontRenderOptions fro)
{
if (Character.isWhitespace(cd.getChar()))
return;
WorldRenderer wr = Tessellator.getInstance().getWorldRenderer();
float factor = fro.fontScale / options.fontSize * 9;
float w = cd.getFullWidth(options) * factor;
float h = cd.getFullHeight(options) * factor;
float i = fro.italic ? fro.fontScale : 0;
int color = drawingShadow ? fro.getShadowColor() : fro.color;
if (drawingShadow)
{
offsetX += fro.fontScale;
offsetY += fro.fontScale;
}
wr.pos(offsetX + i, offsetY, 0);
wr.tex(cd.u(), cd.v());
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
wr.pos(offsetX - i, offsetY + h, 0);
wr.tex(cd.u(), cd.V());
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
wr.pos(offsetX + w - i, offsetY + h, 0);
wr.tex(cd.U(), cd.V());
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
wr.pos(offsetX + w + i, offsetY, 0);
wr.tex(cd.U(), cd.v());
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
/*
wr.setColorOpaque_I(drawingShadow ? fro.getShadowColor() : fro.color);
wr.setBrightness(Vertex.BRIGHTNESS_MAX);
wr.addVertexWithUV(offsetX + i, offsetY, 0, cd.u(), cd.v());
wr.addVertexWithUV(offsetX - i, offsetY + h, 0, cd.u(), cd.V());
wr.addVertexWithUV(offsetX + w - i, offsetY + h, 0, cd.U(), cd.V());
wr.addVertexWithUV(offsetX + w + i, offsetY, 0, cd.U(), cd.v());
*/
}
protected void drawLines(String text, FontRenderOptions fro)
{
float x = 0;
fro.resetStylesLine();
StringWalker walker = new StringWalker(text, this, fro);
walker.applyStyles(true);
while (walker.walk())
{
if (!walker.isFormatting())
{
CharData cd = getCharData(walker.getChar());
if (fro.underline)
drawLineChar(cd, x, getStringHeight(fro) + fro.fontScale, fro);
if (fro.strikethrough)
drawLineChar(cd, x, getStringHeight(fro) * 0.5F + fro.fontScale, fro);
x += walker.getWidth();
}
}
}
protected void drawLineChar(CharData cd, float offsetX, float offsetY, FontRenderOptions fro)
{
WorldRenderer wr = Tessellator.getInstance().getWorldRenderer();
float factor = fro.fontScale / options.fontSize * 9;
float w = cd.getFullWidth(options) * factor;
float h = cd.getFullHeight(options) / 9F * factor;
int color = drawingShadow ? fro.getShadowColor() : fro.color;
if (drawingShadow)
{
offsetX += fro.fontScale;
offsetY += fro.fontScale;
}
wr.pos(offsetX, offsetY, 0);
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
wr.pos(offsetX, offsetY + h, 0);
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
wr.pos(offsetX + w, offsetY + h, 0);
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
wr.pos(offsetX + w, offsetY, 0);
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
/*
wr.setColorOpaque_I(drawingShadow ? fro.getShadowColor() : fro.color);
wr.addVertex(offsetX, offsetY, 0);
wr.addVertex(offsetX, offsetY + h, 0);
wr.addVertex(offsetX + w, offsetY + h, 0);
wr.addVertex(offsetX + w, offsetY, 0);
*/
}
//#region String processing
/**
* Processes the passed string by translating it and replacing spacing characters and new lines.<br>
* Keeps the formatting if passed at the beginning of the translation key.
*
* @param str the str
* @return the string
*/
public String processString(String str, FontRenderOptions fro)
{
str = translate(str);
//str = str.replaceAll("\r?\n", "").replaceAll("\t", " ");
return str;
}
private String translate(String str)
{
if (str.indexOf('{') == -1 || str.indexOf('{') >= str.indexOf('}'))
return StatCollector.translateToLocal(str);
StringBuffer output = new StringBuffer();
Matcher matcher = pattern.matcher(str);
while (matcher.find())
matcher.appendReplacement(output, StatCollector.translateToLocal(matcher.group(1)));
matcher.appendTail(output);
return output.toString();
}
private boolean hasLines(String text, FontRenderOptions fro)
{
return fro.underline || fro.strikethrough || text.contains(EnumChatFormatting.UNDERLINE.toString())
|| text.contains(EnumChatFormatting.STRIKETHROUGH.toString());
}
/**
* Clips a string to fit in the specified width. The string is translated before clipping.
*
* @param str the str
* @param width the width
* @return the string
*/
public String clipString(String str, int width)
{
return clipString(str, width, null, false);
}
/**
* Clips a string to fit in the specified width. The string is translated before clipping.
*
* @param str the str
* @param width the width
* @param fro the fro
* @return the string
*/
public String clipString(String str, int width, FontRenderOptions fro)
{
return clipString(str, width, fro, false);
}
/**
* Clips a string to fit in the specified width. The string is translated before clipping.
*
* @param str the str
* @param width the width
* @param fro the fro
* @param appendPeriods the append periods
* @return the string
*/
public String clipString(String str, int width, FontRenderOptions fro, boolean appendPeriods)
{
str = processString(str, fro);
if (appendPeriods)
width -= 4;
int pos = (int) getCharPosition(str, fro, width, 0);
return str.substring(0, pos) + (pos < str.length() && appendPeriods ? "..." : "");
}
/**
* Gets rendering width of a string.
*
* @param str the str
* @return the string width
*/
public float getStringWidth(String str)
{
return getStringWidth(str, null);
}
/**
* Gets rendering width of a string according to fontScale.
*
* @param str the str
* @param fro the fro
* @param start the start
* @param end the end
* @return the string width
*/
public float getStringWidth(String str, FontRenderOptions fro, int start, int end)
{
if (start > end)
return 0;
if (fro != null && !fro.disableECF)
str = EnumChatFormatting.getTextWithoutFormattingCodes(str);
if (StringUtils.isEmpty(str))
return 0;
str = processString(str, fro);
return (float) font.getStringBounds(str, frc).getWidth() / options.fontSize * (fro != null ? fro.fontScale : 1) * 9;
}
public float getStringWidth(String str, FontRenderOptions fro)
{
if (StringUtils.isEmpty(str))
return 0;
return getStringWidth(str, fro, 0, 0);
}
/**
* Gets the rendering height of strings.
*
* @return the string height
*/
public float getStringHeight()
{
return getStringHeight(null);
}
/**
* Gets the rendering height of strings according to fontscale.
*
* @param fro the fro
* @return the string height
*/
public float getStringHeight(FontRenderOptions fro)
{
return (fro != null ? fro.fontScale : 1) * 9;
}
/**
* Gets the max string width.
*
* @param strings the strings
* @return the max string width
*/
public float getMaxStringWidth(List<String> strings)
{
return getMaxStringWidth(strings, null);
}
/**
* Gets max rendering width of an array of string.
*
* @param strings the strings
* @param fro the fro
* @return the max string width
*/
public float getMaxStringWidth(List<String> strings, FontRenderOptions fro)
{
float width = 0;
for (String str : strings)
width = Math.max(width, getStringWidth(str, fro));
return width;
}
/**
* Gets the rendering width of a char.
*
* @param c the c
* @return the char width
*/
public float getCharWidth(char c)
{
return getCharWidth(c, null);
}
/**
* Gets the rendering width of a char with the specified fontScale.
*
* @param c the c
* @param fro the fro
* @return the char width
*/
public float getCharWidth(char c, FontRenderOptions fro)
{
if (c == '\r' || c == '\n')
return 0;
if (c == '\t')
return getCharWidth(' ', fro) * 4;
return getCharData(c).getCharWidth() / options.fontSize * (fro != null ? fro.fontScale : 1) * 9;
}
/**
* Determines the character for a given X coordinate.
*
* @param str the str
* @param fro the fro
* @param position the position
* @param charOffset the char offset
* @return position
*/
public float getCharPosition(String str, FontRenderOptions fro, int position, int charOffset)
{
if (StringUtils.isEmpty(str))
return 0;
str = processString(str, fro);
//float fx = position / (fro != null ? fro.fontScale : 1); //factor the position instead of the char widths
StringWalker walker = new StringWalker(str, this, fro);
walker.startIndex(charOffset);
walker.skipChars(true);
return walker.walkTo(position);
}
/**
* Splits the string in multiple lines to fit in the specified maxWidth.
*
* @param text the text
* @param maxWidth the max width
* @return list of lines that won't exceed maxWidth limit
*/
public List<String> wrapText(String text, int maxWidth)
{
return wrapText(text, maxWidth, null);
}
/**
* Splits the string in multiple lines to fit in the specified maxWidth using the specified fontScale.
*
* @param str the str
* @param maxWidth the max width
* @param fro the fro
* @return list of lines that won't exceed maxWidth limit
*/
public List<String> wrapText(String str, int maxWidth, FontRenderOptions fro)
{
List<String> lines = new ArrayList<>();
String[] texts = str.split("\r?(?<=\n)");
if (texts.length > 1)
{
for (String t : texts)
lines.addAll(wrapText(t, maxWidth, fro));
return lines;
}
StringBuilder line = new StringBuilder();
StringBuilder word = new StringBuilder();
//FontRenderOptions fro = new FontRenderOptions();
maxWidth -= 4;
maxWidth /= (fro != null ? fro.fontScale : 1); //factor the position instead of the char widths
float lineWidth = 0;
float wordWidth = 0;
str = processString(str, fro);
StringWalker walker = new StringWalker(str, this, fro);
walker.skipChars(false);
walker.applyStyles(false);
while (walker.walk())
{
char c = walker.getChar();
lineWidth += walker.getWidth();
wordWidth += walker.getWidth();
// if (walker.isFormatting())
// {
// word.append(walker.getFormatting());
// continue;
// }
// else
word.append(c);
//we just ended a new word, add it to the current line
if (c == ' ' || c == '-' || c == '.')
{
line.append(word);
word.setLength(0);
wordWidth = 0;
}
if (lineWidth >= maxWidth)
{
//the first word on the line is too large, split anyway
if (line.length() == 0)
{
line.append(word);
word.setLength(0);
wordWidth = 0;
}
//make a new line
lines.add(line.toString());
line.setLength(0);
lineWidth = wordWidth;
}
}
line.append(word);
lines.add(line.toString());
return lines;
}
//#end String processing
//#region Load font
protected void loadCharacterData()
{
frc = new FontRenderContext(null, true, true);
float totalWidth = 0;
for (char c = 0; c < 256; c++)
{
String s = "" + c;
LineMetrics lm = font.getLineMetrics(s, frc);
Rectangle2D bounds = font.getStringBounds(s, frc);
CharData cd = new CharData(c, lm.getAscent(), (float) bounds.getWidth(), options.fontSize);
charData[c] = cd;
totalWidth += cd.getFullWidth(options);
}
int split = 1;
while (totalWidth / split > options.fontSize * split)
split++;
//size = (int) Math.max(totalWidth / (split - 1), options.fontSize * (split - 1));
size = roundUp((int) totalWidth / (split - 1));
}
protected int roundUp(int n)
{
int r = n - 1;
r |= r >> 1;
r |= r >> 2;
r |= r >> 4;
r |= r >> 8;
r |= r >> 16;
return r + 1;
}
protected void loadTexture(boolean forceGenerate)
{
File textureFile = new File("fonts/" + font.getName() + ".png");
File uvFile = new File("fonts/" + font.getName() + ".bin");
BufferedImage img;
if (!textureFile.exists() || !uvFile.exists() || forceGenerate)
{
MalisisCore.log.info("Generating files for " + font.getName());
img = new FontGenerator(font, charData, options).generate(size, textureFile, uvFile);
}
else
{
MalisisCore.log.info("Loading texture and data for " + font.getName());
img = readTextureFile(textureFile);
readUVFile(uvFile);
}
if (img == null)
return;
if (textureRl != null)
Minecraft.getMinecraft().getTextureManager().deleteTexture(textureRl);
DynamicTexture dynTex = new DynamicTexture(img);
textureRl = Minecraft.getMinecraft().getTextureManager().getDynamicTextureLocation(font.getName(), dynTex);
}
protected BufferedImage readTextureFile(File textureFile)
{
try
{
BufferedImage img = ImageIO.read(textureFile);
if (img == null)
{
MalisisCore.log.error("Failed to read font texture, no image could be read from the file.");
return null;
}
size = img.getWidth();
return img;
}
catch (IOException e)
{
MalisisCore.log.error("Failed to read font texture.", e);
}
return null;
}
protected void readUVFile(File uvFile)
{
int i = 0;
try
{
for (String str : Files.readLines(uvFile, StandardCharsets.UTF_8))
{
String[] split = str.split(";");
CharData cd = charData[i++];
cd.setUVs(Float.parseFloat(split[1]), Float.parseFloat(split[2]), Float.parseFloat(split[3]), Float.parseFloat(split[4]));
}
}
catch (IOException | NumberFormatException e)
{
MalisisCore.log.error("Failed to read font data. (Line " + i + " (" + (char) i + ")", e);
}
}
//#end Load font
//#region Font load
public static Font load(ResourceLocation rl, FontGeneratorOptions options)
{
try
{
return load(Minecraft.getMinecraft().getResourceManager().getResource(rl).getInputStream(), options);
}
catch (IOException e)
{
MalisisCore.log.error("[MalisiFont] Couldn't load font from ResourceLocation.", e);
return null;
}
}
public static Font load(File file, FontGeneratorOptions options)
{
try
{
return load(new FileInputStream(file), options);
}
catch (FileNotFoundException e)
{
MalisisCore.log.error("[MalisiFont] Couldn't load font from File.", e);
return null;
}
}
public static Font load(InputStream is, FontGeneratorOptions options)
{
try
{
Font font = Font.createFont(options.fontType, is);
return font.deriveFont(options.fontSize);
}
catch (IOException | FontFormatException e)
{
MalisisCore.log.error("[MalisiFont] Couldn't load font from InputStream.", e);
return null;
}
}
//#end Font load
}
| src/main/java/net/malisis/core/renderer/font/MalisisFont.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2014 Ordinastie
*
* 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 net.malisis.core.renderer.font;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import net.malisis.core.MalisisCore;
import net.malisis.core.client.gui.GuiRenderer;
import net.malisis.core.renderer.MalisisRenderer;
import net.malisis.core.renderer.element.Face;
import net.malisis.core.renderer.element.Shape;
import net.malisis.core.renderer.element.face.SouthFace;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import org.apache.commons.lang3.StringUtils;
import org.lwjgl.opengl.GL11;
import com.google.common.io.Files;
/**
* @author Ordinastie
*
*/
public class MalisisFont
{
public static MalisisFont minecraftFont = new MinecraftFont();
private static Pattern pattern = Pattern.compile("\\{(.*?)}");
/** AWT font used **/
protected Font font;
/** Font render context **/
protected FontRenderContext frc;
/** Options for the font **/
protected FontGeneratorOptions options = FontGeneratorOptions.DEFAULT;
/** Data for each character **/
protected CharData[] charData = new CharData[256];
/** ResourceLocation for the texture **/
protected ResourceLocation textureRl;
/** Size of the texture (width and height) **/
protected int size;
/** Whether the currently drawn text is the shadow part **/
protected boolean drawingShadow = false;
public MalisisFont(File fontFile)
{
this(load(fontFile, FontGeneratorOptions.DEFAULT), null);
}
public MalisisFont(File fontFile, FontGeneratorOptions options)
{
this(load(fontFile, options), options);
}
public MalisisFont(ResourceLocation fontFile)
{
this(load(fontFile, FontGeneratorOptions.DEFAULT), null);
}
public MalisisFont(ResourceLocation fontFile, FontGeneratorOptions options)
{
this(load(fontFile, options), options);
}
public MalisisFont(Font font)
{
this(font, null);
}
public MalisisFont(Font font, FontGeneratorOptions options)
{
this.font = font;
if (font == null)
return;
if (options != null)
this.options = options;
loadCharacterData();
loadTexture(false);
}
public ResourceLocation getResourceLocation()
{
return textureRl;
}
public void generateTexture(boolean debug)
{
this.options.debug = debug;
loadCharacterData();
loadTexture(true);
}
public CharData getCharData(char c)
{
if (c < 0 || c > charData.length)
c = '?';
return charData[c];
}
public Shape getShape(String text, float fontSize)
{
text = processString(text, null);
List<Face> faces = new ArrayList<>();
float offset = 0;
float factor = options.fontSize / fontSize;
for (int i = 0; i < text.length(); i++)
{
CharData cd = getCharData(text.charAt(i));
if (cd.getChar() != ' ')
{
Face f = new SouthFace();
f.scale(cd.getFullWidth(options) / factor, cd.getFullHeight(options) / factor, 0);
f.translate((offset - options.mx) / factor, -options.my / factor, 0);
f.setTexture(cd.getIcon());
faces.add(f);
}
offset += cd.getCharWidth();
}
return new Shape(faces).storeState();
}
//#region Prepare/Clean
protected void prepare(MalisisRenderer renderer, float x, float y, float z, FontRenderOptions fro)
{
boolean isGui = renderer instanceof GuiRenderer;
renderer.next(GL11.GL_QUADS);
Minecraft.getMinecraft().getTextureManager().bindTexture(textureRl);
GL11.glPushMatrix();
GL11.glTranslatef(x, y + (isGui ? 0 : fro.fontScale), z);
if (!isGui)
GL11.glScalef(1 / 9F, -1 / 9F, 1 / 9F);
}
protected void clean(MalisisRenderer renderer, boolean isDrawing)
{
if (isDrawing)
renderer.next();
else
renderer.draw();
if (renderer instanceof GuiRenderer)
Minecraft.getMinecraft().getTextureManager().bindTexture(((GuiRenderer) renderer).getDefaultTexture().getResourceLocation());
GL11.glPopMatrix();
}
protected void prepareShadow(MalisisRenderer renderer)
{
drawingShadow = true;
if (renderer instanceof GuiRenderer)
return;
renderer.next();
GL11.glPolygonOffset(3.0F, 3.0F);
GL11.glEnable(GL11.GL_POLYGON_OFFSET_FILL);
}
protected void cleanShadow(MalisisRenderer renderer)
{
drawingShadow = false;
if (renderer instanceof GuiRenderer)
return;
renderer.next();
GL11.glPolygonOffset(0.0F, 0.0F);
GL11.glDisable(GL11.GL_POLYGON_OFFSET_FILL);
}
protected void prepareLines(MalisisRenderer renderer, FontRenderOptions fro)
{
renderer.next();
renderer.disableTextures();
}
protected void cleanLines(MalisisRenderer renderer)
{
renderer.next();
renderer.enableTextures();
}
//#end Prepare/Clean
public void render(MalisisRenderer renderer, String text, float x, float y, float z, FontRenderOptions fro)
{
if (StringUtils.isEmpty(text))
return;
boolean isDrawing = renderer.isDrawing();
prepare(renderer, x, y, z, fro);
text = processString(text, fro);
if (fro.shadow)
{
prepareShadow(renderer);
drawString(text, fro);
cleanShadow(renderer);
}
drawString(text, fro);
if (hasLines(text, fro))
{
prepareLines(renderer, fro);
if (fro.shadow)
{
prepareShadow(renderer);
drawLines(text, fro);
cleanShadow(renderer);
}
drawLines(text, fro);
cleanLines(renderer);
}
clean(renderer, isDrawing);
}
protected void drawString(String text, FontRenderOptions fro)
{
float x = 0;
fro.resetStylesLine();
StringWalker walker = new StringWalker(text, this, fro);
walker.applyStyles(true);
while (walker.walk())
{
CharData cd = getCharData(walker.getChar());
drawChar(cd, x, 0, fro);
x += walker.getWidth();
}
}
protected void drawChar(CharData cd, float offsetX, float offsetY, FontRenderOptions fro)
{
if (Character.isWhitespace(cd.getChar()))
return;
WorldRenderer wr = Tessellator.getInstance().getWorldRenderer();
float factor = fro.fontScale / options.fontSize * 9;
float w = cd.getFullWidth(options) * factor;
float h = cd.getFullHeight(options) * factor;
float i = fro.italic ? fro.fontScale : 0;
int color = drawingShadow ? fro.getShadowColor() : fro.color;
if (drawingShadow)
{
offsetX += fro.fontScale;
offsetY += fro.fontScale;
}
wr.pos(offsetX + i, offsetY, 0);
wr.tex(cd.u(), cd.v());
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
wr.pos(offsetX - i, offsetY + h, 0);
wr.tex(cd.u(), cd.V());
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
wr.pos(offsetX + w - i, offsetY + h, 0);
wr.tex(cd.U(), cd.V());
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
wr.pos(offsetX + w + i, offsetY, 0);
wr.tex(cd.U(), cd.v());
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
/*
wr.setColorOpaque_I(drawingShadow ? fro.getShadowColor() : fro.color);
wr.setBrightness(Vertex.BRIGHTNESS_MAX);
wr.addVertexWithUV(offsetX + i, offsetY, 0, cd.u(), cd.v());
wr.addVertexWithUV(offsetX - i, offsetY + h, 0, cd.u(), cd.V());
wr.addVertexWithUV(offsetX + w - i, offsetY + h, 0, cd.U(), cd.V());
wr.addVertexWithUV(offsetX + w + i, offsetY, 0, cd.U(), cd.v());
*/
}
protected void drawLines(String text, FontRenderOptions fro)
{
float x = 0;
fro.resetStylesLine();
StringWalker walker = new StringWalker(text, this, fro);
walker.applyStyles(true);
while (walker.walk())
{
if (!walker.isFormatting())
{
CharData cd = getCharData(walker.getChar());
if (fro.underline)
drawLineChar(cd, x, getStringHeight(fro) + fro.fontScale, fro);
if (fro.strikethrough)
drawLineChar(cd, x, getStringHeight(fro) * 0.5F + fro.fontScale, fro);
x += walker.getWidth();
}
}
}
protected void drawLineChar(CharData cd, float offsetX, float offsetY, FontRenderOptions fro)
{
WorldRenderer wr = Tessellator.getInstance().getWorldRenderer();
float factor = fro.fontScale / options.fontSize * 9;
float w = cd.getFullWidth(options) * factor;
float h = cd.getFullHeight(options) / 9F * factor;
int color = drawingShadow ? fro.getShadowColor() : fro.color;
if (drawingShadow)
{
offsetX += fro.fontScale;
offsetY += fro.fontScale;
}
wr.pos(offsetX, offsetY, 0);
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
wr.pos(offsetX, offsetY + h, 0);
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
wr.pos(offsetX + w, offsetY + h, 0);
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
wr.pos(offsetX + w, offsetY, 0);
wr.color((color >> 16) & 255, (color >> 8) & 255, color & 255, 255);
wr.endVertex();
/*
wr.setColorOpaque_I(drawingShadow ? fro.getShadowColor() : fro.color);
wr.addVertex(offsetX, offsetY, 0);
wr.addVertex(offsetX, offsetY + h, 0);
wr.addVertex(offsetX + w, offsetY + h, 0);
wr.addVertex(offsetX + w, offsetY, 0);
*/
}
//#region String processing
/**
* Processes the passed string by translating it and replacing spacing characters and new lines.<br>
* Keeps the formatting if passed at the beginning of the translation key.
*
* @param str the str
* @return the string
*/
public String processString(String str, FontRenderOptions fro)
{
str = translate(str);
//str = str.replaceAll("\r?\n", "").replaceAll("\t", " ");
return str;
}
private String translate(String str)
{
if (str.indexOf('{') == -1 || str.indexOf('{') >= str.indexOf('}'))
return StatCollector.translateToLocal(str);
StringBuffer output = new StringBuffer();
Matcher matcher = pattern.matcher(str);
while (matcher.find())
matcher.appendReplacement(output, StatCollector.translateToLocal(matcher.group(1)));
matcher.appendTail(output);
return output.toString();
}
private boolean hasLines(String text, FontRenderOptions fro)
{
return fro.underline || fro.strikethrough || text.contains(EnumChatFormatting.UNDERLINE.toString())
|| text.contains(EnumChatFormatting.STRIKETHROUGH.toString());
}
/**
* Clips a string to fit in the specified width. The string is translated before clipping.
*
* @param str the str
* @param width the width
* @return the string
*/
public String clipString(String str, int width)
{
return clipString(str, width, null, false);
}
/**
* Clips a string to fit in the specified width. The string is translated before clipping.
*
* @param str the str
* @param width the width
* @param fro the fro
* @return the string
*/
public String clipString(String str, int width, FontRenderOptions fro)
{
return clipString(str, width, fro, false);
}
/**
* Clips a string to fit in the specified width. The string is translated before clipping.
*
* @param str the str
* @param width the width
* @param fro the fro
* @param appendPeriods the append periods
* @return the string
*/
public String clipString(String str, int width, FontRenderOptions fro, boolean appendPeriods)
{
str = processString(str, fro);
if (appendPeriods)
width -= 4;
int pos = (int) getCharPosition(str, fro, width, 0);
return str.substring(0, pos) + (pos < str.length() && appendPeriods ? "..." : "");
}
/**
* Gets rendering width of a string.
*
* @param str the str
* @return the string width
*/
public float getStringWidth(String str)
{
return getStringWidth(str, null);
}
/**
* Gets rendering width of a string according to fontScale.
*
* @param str the str
* @param fro the fro
* @param start the start
* @param end the end
* @return the string width
*/
public float getStringWidth(String str, FontRenderOptions fro, int start, int end)
{
if (start > end)
return 0;
if (fro != null && !fro.disableECF)
str = EnumChatFormatting.getTextWithoutFormattingCodes(str);
if (StringUtils.isEmpty(str))
return 0;
str = processString(str, fro);
return (float) font.getStringBounds(str, frc).getWidth() / options.fontSize * (fro != null ? fro.fontScale : 1) * 9;
}
public float getStringWidth(String str, FontRenderOptions fro)
{
if (StringUtils.isEmpty(str))
return 0;
return getStringWidth(str, fro, 0, 0);
}
/**
* Gets the rendering height of strings.
*
* @return the string height
*/
public float getStringHeight()
{
return getStringHeight(null);
}
/**
* Gets the rendering height of strings according to fontscale.
*
* @param fro the fro
* @return the string height
*/
public float getStringHeight(FontRenderOptions fro)
{
return (fro != null ? fro.fontScale : 1) * 9;
}
/**
* Gets the max string width.
*
* @param strings the strings
* @return the max string width
*/
public float getMaxStringWidth(List<String> strings)
{
return getMaxStringWidth(strings, null);
}
/**
* Gets max rendering width of an array of string.
*
* @param strings the strings
* @param fro the fro
* @return the max string width
*/
public float getMaxStringWidth(List<String> strings, FontRenderOptions fro)
{
float width = 0;
for (String str : strings)
width = Math.max(width, getStringWidth(str, fro));
return width;
}
/**
* Gets the rendering width of a char.
*
* @param c the c
* @return the char width
*/
public float getCharWidth(char c)
{
return getCharWidth(c, null);
}
/**
* Gets the rendering width of a char with the specified fontScale.
*
* @param c the c
* @param fro the fro
* @return the char width
*/
public float getCharWidth(char c, FontRenderOptions fro)
{
if (c == '\r' || c == '\n')
return 0;
if (c == '\t')
return getCharWidth(' ', fro) * 4;
return getCharData(c).getCharWidth() / options.fontSize * (fro != null ? fro.fontScale : 1) * 9;
}
/**
* Determines the character for a given X coordinate.
*
* @param str the str
* @param fro the fro
* @param position the position
* @param charOffset the char offset
* @return position
*/
public float getCharPosition(String str, FontRenderOptions fro, int position, int charOffset)
{
if (StringUtils.isEmpty(str))
return 0;
str = processString(str, fro);
//float fx = position / (fro != null ? fro.fontScale : 1); //factor the position instead of the char widths
StringWalker walker = new StringWalker(str, this, fro);
walker.startIndex(charOffset);
walker.skipChars(true);
return walker.walkTo(position);
}
/**
* Splits the string in multiple lines to fit in the specified maxWidth.
*
* @param text the text
* @param maxWidth the max width
* @return list of lines that won't exceed maxWidth limit
*/
public List<String> wrapText(String text, int maxWidth)
{
return wrapText(text, maxWidth, null);
}
/**
* Splits the string in multiple lines to fit in the specified maxWidth using the specified fontScale.
*
* @param str the str
* @param maxWidth the max width
* @param fro the fro
* @return list of lines that won't exceed maxWidth limit
*/
public List<String> wrapText(String str, int maxWidth, FontRenderOptions fro)
{
List<String> lines = new ArrayList<>();
String[] texts = str.split("\r?(?<=\n)");
if (texts.length > 1)
{
for (String t : texts)
lines.addAll(wrapText(t, maxWidth, fro));
return lines;
}
StringBuilder line = new StringBuilder();
StringBuilder word = new StringBuilder();
//FontRenderOptions fro = new FontRenderOptions();
maxWidth -= 4;
maxWidth /= (fro != null ? fro.fontScale : 1); //factor the position instead of the char widths
float lineWidth = 0;
float wordWidth = 0;
str = processString(str, fro);
StringWalker walker = new StringWalker(str, this, fro);
walker.skipChars(false);
walker.applyStyles(false);
while (walker.walk())
{
char c = walker.getChar();
lineWidth += walker.getWidth();
wordWidth += walker.getWidth();
// if (walker.isFormatting())
// {
// word.append(walker.getFormatting());
// continue;
// }
// else
word.append(c);
//we just ended a new word, add it to the current line
if (c == ' ' || c == '-' || c == '.')
{
line.append(word);
word.setLength(0);
wordWidth = 0;
}
if (lineWidth >= maxWidth)
{
//the first word on the line is too large, split anyway
if (line.length() == 0)
{
line.append(word);
word.setLength(0);
wordWidth = 0;
}
//make a new line
lines.add(line.toString());
line.setLength(0);
lineWidth = wordWidth;
}
}
line.append(word);
lines.add(line.toString());
return lines;
}
//#end String processing
//#region Load font
protected void loadCharacterData()
{
frc = new FontRenderContext(null, true, true);
float totalWidth = 0;
for (char c = 0; c < 256; c++)
{
String s = "" + c;
LineMetrics lm = font.getLineMetrics(s, frc);
Rectangle2D bounds = font.getStringBounds(s, frc);
CharData cd = new CharData(c, lm.getAscent(), (float) bounds.getWidth(), options.fontSize);
charData[c] = cd;
totalWidth += cd.getFullWidth(options);
}
int split = 1;
while (totalWidth / split > options.fontSize * split)
split++;
//size = (int) Math.max(totalWidth / (split - 1), options.fontSize * (split - 1));
size = roundUp((int) totalWidth / (split - 1));
}
protected int roundUp(int n)
{
int r = n - 1;
r |= r >> 1;
r |= r >> 2;
r |= r >> 4;
r |= r >> 8;
r |= r >> 16;
return r + 1;
}
protected void loadTexture(boolean forceGenerate)
{
File textureFile = new File("fonts/" + font.getName() + ".png");
File uvFile = new File("fonts/" + font.getName() + ".bin");
BufferedImage img;
if (!textureFile.exists() || !uvFile.exists() || forceGenerate)
{
MalisisCore.log.info("Generating files for " + font.getName());
img = new FontGenerator(font, charData, options).generate(size, textureFile, uvFile);
}
else
{
MalisisCore.log.info("Loading texture and data for " + font.getName());
img = readTextureFile(textureFile);
readUVFile(uvFile);
}
if (img == null)
return;
if (textureRl != null)
Minecraft.getMinecraft().getTextureManager().deleteTexture(textureRl);
DynamicTexture dynTex = new DynamicTexture(img);
textureRl = Minecraft.getMinecraft().getTextureManager().getDynamicTextureLocation(font.getName(), dynTex);
}
protected BufferedImage readTextureFile(File textureFile)
{
try
{
BufferedImage img = ImageIO.read(textureFile);
if (img == null)
{
MalisisCore.log.error("Failed to read font texture, no image could be read from the file.");
return null;
}
size = img.getWidth();
return img;
}
catch (IOException e)
{
MalisisCore.log.error("Failed to read font texture.", e);
}
return null;
}
protected void readUVFile(File uvFile)
{
int i = 0;
try
{
for (String str : Files.readLines(uvFile, StandardCharsets.UTF_8))
{
String[] split = str.split(";");
CharData cd = charData[i++];
cd.setUVs(Float.parseFloat(split[1]), Float.parseFloat(split[2]), Float.parseFloat(split[3]), Float.parseFloat(split[4]));
}
}
catch (IOException | NumberFormatException e)
{
MalisisCore.log.error("Failed to read font data. (Line " + i + " (" + (char) i + ")", e);
}
}
//#end Load font
//#region Font load
public static Font load(ResourceLocation rl, FontGeneratorOptions options)
{
try
{
return load(Minecraft.getMinecraft().getResourceManager().getResource(rl).getInputStream(), options);
}
catch (IOException e)
{
MalisisCore.log.error("[MalisiFont] Couldn't load font from ResourceLocation.", e);
return null;
}
}
public static Font load(File file, FontGeneratorOptions options)
{
try
{
return load(new FileInputStream(file), options);
}
catch (FileNotFoundException e)
{
MalisisCore.log.error("[MalisiFont] Couldn't load font from File.", e);
return null;
}
}
public static Font load(InputStream is, FontGeneratorOptions options)
{
try
{
Font font = Font.createFont(options.fontType, is);
return font.deriveFont(options.fontSize);
}
catch (IOException | FontFormatException e)
{
MalisisCore.log.error("[MalisiFont] Couldn't load font from InputStream.", e);
return null;
}
}
//#end Font load
}
| Fixed rendering | src/main/java/net/malisis/core/renderer/font/MalisisFont.java | Fixed rendering | <ide><path>rc/main/java/net/malisis/core/renderer/font/MalisisFont.java
<ide> import net.minecraft.client.renderer.Tessellator;
<ide> import net.minecraft.client.renderer.WorldRenderer;
<ide> import net.minecraft.client.renderer.texture.DynamicTexture;
<add>import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
<ide> import net.minecraft.util.EnumChatFormatting;
<ide> import net.minecraft.util.ResourceLocation;
<ide> import net.minecraft.util.StatCollector;
<ide> protected void prepare(MalisisRenderer renderer, float x, float y, float z, FontRenderOptions fro)
<ide> {
<ide> boolean isGui = renderer instanceof GuiRenderer;
<del> renderer.next(GL11.GL_QUADS);
<add> renderer.next(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
<ide>
<ide> Minecraft.getMinecraft().getTextureManager().bindTexture(textureRl);
<ide> GL11.glPushMatrix();
<ide> protected void clean(MalisisRenderer renderer, boolean isDrawing)
<ide> {
<ide> if (isDrawing)
<del> renderer.next();
<add> renderer.next(MalisisRenderer.malisisVertexFormat);
<ide> else
<ide> renderer.draw();
<ide> if (renderer instanceof GuiRenderer)
<ide>
<ide> protected void prepareLines(MalisisRenderer renderer, FontRenderOptions fro)
<ide> {
<del> renderer.next();
<add> renderer.next(DefaultVertexFormats.POSITION_COLOR);
<ide> renderer.disableTextures();
<ide> }
<ide> |
|
Java | apache-2.0 | 9f9d51de3d62968ab7207231203c2fad10e6a0be | 0 | airbnb/epoxy,airbnb/epoxy,airbnb/epoxy,airbnb/epoxy | package com.airbnb.epoxy;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnLayoutChangeListener;
import com.airbnb.viewmodeladapter.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver;
import androidx.recyclerview.widget.RecyclerView.OnChildAttachStateChangeListener;
import androidx.recyclerview.widget.RecyclerView.OnScrollListener;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
/**
* A simple way to track visibility events on {@link com.airbnb.epoxy.EpoxyModel} within a {@link
* androidx.recyclerview.widget.RecyclerView}.
* <p>
* {@link EpoxyVisibilityTracker} works with any {@link androidx.recyclerview.widget.RecyclerView}
* backed by an Epoxy controller. Once attached the events will be forwarded to the Epoxy model (or
* to the Epoxy view when using annotations).
* <p>
* Note regarding nested lists: The visibility event tracking is not properly handled yet. This is
* on the todo.
* <p>
*
* @see OnVisibilityChanged
* @see OnVisibilityStateChanged
* @see OnModelVisibilityChangedListener
* @see OnModelVisibilityStateChangedListener
*/
public class EpoxyVisibilityTracker {
private static final String TAG = "EpoxyVisibilityTracker";
@IdRes
private static final int TAG_ID = R.id.epoxy_visibility_tracker;
/**
* @param recyclerView the view.
* @return the tracker for the given {@link RecyclerView}. Null if no tracker was attached.
*/
@Nullable
private static EpoxyVisibilityTracker getTracker(@NonNull RecyclerView recyclerView) {
return (EpoxyVisibilityTracker) recyclerView.getTag(TAG_ID);
}
/**
* Store the tracker for the given {@link RecyclerView}.
* @param recyclerView the view
* @param tracker the tracker
*/
private static void setTracker(
@NonNull RecyclerView recyclerView,
@Nullable EpoxyVisibilityTracker tracker) {
recyclerView.setTag(TAG_ID, tracker);
}
// Not actionable at runtime. It is only useful for internal test-troubleshooting.
static final boolean DEBUG_LOG = false;
/** Maintain visibility item indexed by view id (identity hashcode) */
private final SparseArray<EpoxyVisibilityItem> visibilityIdToItemMap = new SparseArray<>();
private final List<EpoxyVisibilityItem> visibilityIdToItems = new ArrayList<>();
/** listener used to process scroll, layout and attach events */
private final Listener listener = new Listener();
/** listener used to process data events */
private final DataObserver observer = new DataObserver();
@Nullable
private RecyclerView attachedRecyclerView = null;
@Nullable
private Adapter lastAdapterSeen = null;
private boolean onChangedEnabled = true;
/** All nested visibility trackers */
private Map<RecyclerView, EpoxyVisibilityTracker> nestedTrackers = new HashMap<>();
/** This flag is for optimizing the process on detach. If detach is from data changed then it
* need to re-process all views, else no need (ex: scroll). */
private boolean visibleDataChanged = false;
/**
* Enable or disable visibility changed event. Default is `true`, disable it if you don't need
* (triggered by every pixel scrolled).
*
* @see OnVisibilityChanged
* @see OnModelVisibilityChangedListener
*/
public void setOnChangedEnabled(boolean enabled) {
onChangedEnabled = enabled;
}
/**
* Attach the tracker.
*
* @param recyclerView The recyclerview that the EpoxyController has its adapter added to.
*/
public void attach(@NonNull RecyclerView recyclerView) {
attachedRecyclerView = recyclerView;
recyclerView.addOnScrollListener(this.listener);
recyclerView.addOnLayoutChangeListener(this.listener);
recyclerView.addOnChildAttachStateChangeListener(this.listener);
setTracker(recyclerView, this);
}
/**
* Detach the tracker
*
* @param recyclerView The recycler view that the EpoxyController has its adapter added to.
*/
public void detach(@NonNull RecyclerView recyclerView) {
recyclerView.removeOnScrollListener(this.listener);
recyclerView.removeOnLayoutChangeListener(this.listener);
recyclerView.removeOnChildAttachStateChangeListener(this.listener);
setTracker(recyclerView, null);
attachedRecyclerView = null;
}
/**
* The tracker is storing visibility states internally and is using if to send events, only the
* difference is sent. Use this method to clear the states and thus regenerate the visibility
* events. This may be useful when you change the adapter on the {@link
* androidx.recyclerview.widget.RecyclerView}
*/
public void clearVisibilityStates() {
// Clear our visibility items
visibilityIdToItemMap.clear();
visibilityIdToItems.clear();
}
private void processChangeEvent(String debug) {
processChangeEventWithDetachedView(null, debug);
}
private void processChangeEventWithDetachedView(@Nullable View detachedView, String debug) {
final RecyclerView recyclerView = attachedRecyclerView;
if (recyclerView != null) {
// On every every events lookup for a new adapter
processNewAdapterIfNecessary();
// Process the detached child if any
if (detachedView != null) {
processChild(detachedView, true, debug);
}
// Process all attached children
for (int i = 0; i < recyclerView.getChildCount(); i++) {
final View child = recyclerView.getChildAt(i);
if (child != null && child != detachedView) {
// Is some case the detached child is still in the recycler view. Don't process it as it
// was already processed.
processChild(child, false, debug);
}
}
}
}
/**
* If there is a new adapter on the attached RecyclerView it will resister the data observer and
* clear the current visibility states
*/
private void processNewAdapterIfNecessary() {
if (attachedRecyclerView != null && attachedRecyclerView.getAdapter() != null) {
if (lastAdapterSeen != attachedRecyclerView.getAdapter()) {
if (lastAdapterSeen != null) {
// Unregister the old adapter
lastAdapterSeen.unregisterAdapterDataObserver(this.observer);
}
// Register the new adapter
attachedRecyclerView.getAdapter().registerAdapterDataObserver(this.observer);
lastAdapterSeen = attachedRecyclerView.getAdapter();
}
}
}
/**
* Don't call this method directly, it is called from
* {@link EpoxyVisibilityTracker#processVisibilityEvents}
*
* @param child the view to process for visibility event
* @param detachEvent true if the child was just detached
* @param eventOriginForDebug a debug strings used for logs
*/
private void processChild(@NonNull View child, boolean detachEvent, String eventOriginForDebug) {
final RecyclerView recyclerView = attachedRecyclerView;
if (recyclerView != null) {
final ViewHolder holder = recyclerView.getChildViewHolder(child);
if (holder instanceof EpoxyViewHolder) {
boolean changed = processVisibilityEvents(
recyclerView,
(EpoxyViewHolder) holder,
detachEvent,
eventOriginForDebug
);
if (changed) {
if (child instanceof RecyclerView) {
EpoxyVisibilityTracker tracker = nestedTrackers.get(child);
if (tracker != null) {
// If view visibility changed and there was a tracker on it then notify it.
tracker.processChangeEvent("parent");
}
}
}
} else {
throw new IllegalEpoxyUsage(
"`EpoxyVisibilityTracker` cannot be used with non-epoxy view holders."
);
}
}
}
/**
* Call this methods every time something related to ui (scroll, layout, ...) or something related
* to data changed.
*
* @param recyclerView the recycler view
* @param epoxyHolder the {@link RecyclerView}
* @param detachEvent true if the event originated from a view detached from the
* recycler view
* @param eventOriginForDebug a debug strings used for logs
* @return true if changed
*/
private boolean processVisibilityEvents(
@NonNull RecyclerView recyclerView,
@NonNull EpoxyViewHolder epoxyHolder,
boolean detachEvent,
String eventOriginForDebug
) {
if (DEBUG_LOG) {
Log.d(TAG, String.format("%s.processVisibilityEvents %s, %s, %s",
eventOriginForDebug,
System.identityHashCode(epoxyHolder),
detachEvent,
epoxyHolder.getAdapterPosition()
));
}
final View itemView = epoxyHolder.itemView;
final int id = System.identityHashCode(itemView);
EpoxyVisibilityItem vi = visibilityIdToItemMap.get(id);
if (vi == null) {
// New view discovered, assign an EpoxyVisibilityItem
vi = new EpoxyVisibilityItem(epoxyHolder.getAdapterPosition());
visibilityIdToItemMap.put(id, vi);
visibilityIdToItems.add(vi);
} else if (epoxyHolder.getAdapterPosition() != RecyclerView.NO_POSITION
&& vi.getAdapterPosition() != epoxyHolder.getAdapterPosition()) {
// EpoxyVisibilityItem being re-used for a different adapter position
vi.reset(epoxyHolder.getAdapterPosition());
}
boolean changed = false;
if (vi.update(itemView, recyclerView, detachEvent)) {
// View is measured, process events
vi.handleVisible(epoxyHolder, detachEvent);
vi.handleFocus(epoxyHolder, detachEvent);
vi.handleFullImpressionVisible(epoxyHolder, detachEvent);
changed = vi.handleChanged(epoxyHolder, onChangedEnabled);
}
return changed;
}
private void processChildRecyclerViewAttached(@NonNull RecyclerView childRecyclerView) {
// Register itself in the EpoxyVisibilityTracker. This will take care of nested list
// tracking (ex: carousel)
EpoxyVisibilityTracker tracker = getTracker(childRecyclerView);
if (tracker == null) {
tracker = new EpoxyVisibilityTracker();
tracker.attach(childRecyclerView);
}
nestedTrackers.put(childRecyclerView, tracker);
}
private void processChildRecyclerViewDetached(@NonNull RecyclerView childRecyclerView) {
nestedTrackers.remove(childRecyclerView);
}
/**
* Helper class that host the {@link androidx.recyclerview.widget.RecyclerView} listener
* implementations
*/
private class Listener extends OnScrollListener
implements OnLayoutChangeListener, OnChildAttachStateChangeListener {
@Override
public void onLayoutChange(
@NonNull View recyclerView,
int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom
) {
processChangeEvent("onLayoutChange");
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
processChangeEvent("onScrolled");
}
@Override
public void onChildViewAttachedToWindow(@NonNull View child) {
if (child instanceof RecyclerView) {
processChildRecyclerViewAttached((RecyclerView) child);
}
processChild(child, false, "onChildViewAttachedToWindow");
}
@Override
public void onChildViewDetachedFromWindow(@NonNull View child) {
if (child instanceof RecyclerView) {
processChildRecyclerViewDetached((RecyclerView) child);
}
if (visibleDataChanged) {
// On detach event caused by data set changed we need to re-process all children because
// the removal caused the others views to changes.
processChangeEventWithDetachedView(child, "onChildViewDetachedFromWindow");
visibleDataChanged = false;
} else {
processChild(child, true, "onChildViewDetachedFromWindow");
}
}
}
/**
* The layout/scroll events are not enough to detect all sort of visibility changes. We also
* need to look at the data events from the adapter.
*/
class DataObserver extends AdapterDataObserver {
/**
* Clear the current visibility statues
*/
@Override
public void onChanged() {
if (notEpoxyManaged(attachedRecyclerView)) {
return;
}
if (DEBUG_LOG) {
Log.d(TAG, "onChanged()");
}
visibilityIdToItemMap.clear();
visibilityIdToItems.clear();
visibleDataChanged = true;
}
/**
* For all items after the inserted range shift each {@link EpoxyVisibilityTracker} adapter
* position by inserted item count.
*/
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
if (notEpoxyManaged(attachedRecyclerView)) {
return;
}
if (DEBUG_LOG) {
Log.d(TAG, String.format("onItemRangeInserted(%d, %d)", positionStart, itemCount));
}
for (EpoxyVisibilityItem item : visibilityIdToItems) {
if (item.getAdapterPosition() >= positionStart) {
visibleDataChanged = true;
item.shiftBy(itemCount);
}
}
}
/**
* For all items after the removed range reverse-shift each {@link EpoxyVisibilityTracker}
* adapter position by removed item count
*/
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
if (notEpoxyManaged(attachedRecyclerView)) {
return;
}
if (DEBUG_LOG) {
Log.d(TAG, String.format("onItemRangeRemoved(%d, %d)", positionStart, itemCount));
}
for (EpoxyVisibilityItem item : visibilityIdToItems) {
if (item.getAdapterPosition() >= positionStart) {
visibleDataChanged = true;
item.shiftBy(-itemCount);
}
}
}
/**
* This is a bit more complex, for move we need to first swap the moved position then shift the
* items between the swap. To simplify we split any range passed to individual item moved.
*
* ps: anyway {@link androidx.recyclerview.widget.AdapterListUpdateCallback}
* does not seem to use range for moved items.
*/
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
if (notEpoxyManaged(attachedRecyclerView)) {
return;
}
for (int i = 0; i < itemCount; i++) {
onItemMoved(fromPosition + i, toPosition + i);
}
}
private void onItemMoved(int fromPosition, int toPosition) {
if (notEpoxyManaged(attachedRecyclerView)) {
return;
}
if (DEBUG_LOG) {
Log.d(TAG,
String.format("onItemRangeMoved(%d, %d, %d)", fromPosition, toPosition, 1));
}
for (EpoxyVisibilityItem item : visibilityIdToItems) {
int position = item.getAdapterPosition();
if (position == fromPosition) {
// We found the item to be moved, just swap the position.
item.shiftBy(toPosition - fromPosition);
visibleDataChanged = true;
} else if (fromPosition < toPosition) {
// Item will be moved down in the list
if (position > fromPosition && position <= toPosition) {
// Item is between the moved from and to indexes, it should move up
item.shiftBy(-1);
visibleDataChanged = true;
}
} else if (fromPosition > toPosition) {
// Item will be moved up in the list
if (position >= toPosition && position < fromPosition) {
// Item is between the moved to and from indexes, it should move down
item.shiftBy(1);
visibleDataChanged = true;
}
}
}
}
/**
* @param recyclerView the recycler view
* @return true if managed by an {@link BaseEpoxyAdapter}
*/
private boolean notEpoxyManaged(@Nullable RecyclerView recyclerView) {
return recyclerView == null || !(recyclerView.getAdapter() instanceof BaseEpoxyAdapter);
}
}
}
| epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyVisibilityTracker.java | package com.airbnb.epoxy;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnLayoutChangeListener;
import com.airbnb.viewmodeladapter.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver;
import androidx.recyclerview.widget.RecyclerView.OnChildAttachStateChangeListener;
import androidx.recyclerview.widget.RecyclerView.OnScrollListener;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
/**
* A simple way to track visibility events on {@link com.airbnb.epoxy.EpoxyModel} within a {@link
* androidx.recyclerview.widget.RecyclerView}.
* <p>
* {@link EpoxyVisibilityTracker} works with any {@link androidx.recyclerview.widget.RecyclerView}
* backed by an Epoxy controller. Once attached the events will be forwarded to the Epoxy model (or
* to the Epoxy view when using annotations).
* <p>
* Note regarding nested lists: The visibility event tracking is not properly handled yet. This is
* on the todo.
* <p>
*
* @see OnVisibilityChanged
* @see OnVisibilityStateChanged
* @see OnModelVisibilityChangedListener
* @see OnModelVisibilityStateChangedListener
*/
public class EpoxyVisibilityTracker {
private static final String TAG = "EpoxyVisibilityTracker";
@IdRes
private static final int TAG_ID = R.id.epoxy_visibility_tracker;
/**
* @param recyclerView the view.
* @return the tracker for the given {@link RecyclerView}. Null if no tracker was attached.
*/
@Nullable
private static EpoxyVisibilityTracker getTracker(@NonNull RecyclerView recyclerView) {
return (EpoxyVisibilityTracker) recyclerView.getTag(TAG_ID);
}
/**
* Store the tracker for the given {@link RecyclerView}.
* @param recyclerView the view
* @param tracker the tracker
*/
private static void setTracker(
@NonNull RecyclerView recyclerView,
@Nullable EpoxyVisibilityTracker tracker) {
recyclerView.setTag(TAG_ID, tracker);
}
// Not actionable at runtime. It is only useful for internal test-troubleshooting.
static final boolean DEBUG_LOG = false;
/** Maintain visibility item indexed by view id (identity hashcode) */
private final SparseArray<EpoxyVisibilityItem> visibilityIdToItemMap = new SparseArray<>();
private final List<EpoxyVisibilityItem> visibilityIdToItems = new ArrayList<>();
/** listener used to process scroll, layout and attach events */
private final Listener listener = new Listener();
/** listener used to process data events */
private final DataObserver observer = new DataObserver();
@Nullable
private RecyclerView attachedRecyclerView = null;
@Nullable
private Adapter lastAdapterSeen = null;
private boolean onChangedEnabled = true;
/** All nested visibility trackers */
private Map<RecyclerView, EpoxyVisibilityTracker> nestedTrackers = new HashMap<>();
/** This flag is for optimizing the process on detach. If detach is from data changed then it
* need to re-process all views, else no need (ex: scroll). */
private boolean visibleDataChanged = false;
/**
* Enable or disable visibility changed event. Default is `true`, disable it if you don't need
* (triggered by every pixel scrolled).
*
* @see OnVisibilityChanged
* @see OnModelVisibilityChangedListener
*/
public void setOnChangedEnabled(boolean enabled) {
onChangedEnabled = enabled;
}
/**
* Attach the tracker.
*
* @param recyclerView The recyclerview that the EpoxyController has its adapter added to.
*/
public void attach(@NonNull RecyclerView recyclerView) {
attachedRecyclerView = recyclerView;
recyclerView.addOnScrollListener(this.listener);
recyclerView.addOnLayoutChangeListener(this.listener);
recyclerView.addOnChildAttachStateChangeListener(this.listener);
setTracker(recyclerView, this);
}
/**
* Detach the tracker
*
* @param recyclerView The recycler view that the EpoxyController has its adapter added to.
*/
public void detach(@NonNull RecyclerView recyclerView) {
recyclerView.removeOnScrollListener(this.listener);
recyclerView.removeOnLayoutChangeListener(this.listener);
recyclerView.removeOnChildAttachStateChangeListener(this.listener);
setTracker(recyclerView, null);
attachedRecyclerView = null;
}
/**
* The tracker is storing visibility states internally and is using if to send events, only the
* difference is sent. Use this method to clear the states and thus regenerate the visibility
* events. This may be useful when you change the adapter on the {@link
* androidx.recyclerview.widget.RecyclerView}
*/
public void clearVisibilityStates() {
// Clear our visibility items
visibilityIdToItemMap.clear();
visibilityIdToItems.clear();
}
private void processChangeEvent(String debug) {
processChangeEventWithDetachedView(null, debug);
}
private void processChangeEventWithDetachedView(@Nullable View detachedView, String debug) {
final RecyclerView recyclerView = attachedRecyclerView;
if (recyclerView != null) {
// On every every events lookup for a new adapter
processNewAdapterIfNecessary();
// Process the detached child if any
if (detachedView != null) {
processChild(detachedView, true, debug);
}
// Process all attached children
for (int i = 0; i < recyclerView.getChildCount(); i++) {
final View child = recyclerView.getChildAt(i);
if (child != null && child != detachedView) {
// Is some case the detached child is still in the recycler view. Don't process it as it
// was already processed.
processChild(child, false, debug);
}
}
}
}
/**
* If there is a new adapter on the attached RecyclerView it will resister the data observer and
* clear the current visibility states
*/
private void processNewAdapterIfNecessary() {
if (attachedRecyclerView != null && attachedRecyclerView.getAdapter() != null) {
if (lastAdapterSeen != attachedRecyclerView.getAdapter()) {
if (lastAdapterSeen != null) {
// Unregister the old adapter
lastAdapterSeen.unregisterAdapterDataObserver(this.observer);
}
// Register the new adapter
attachedRecyclerView.getAdapter().registerAdapterDataObserver(this.observer);
lastAdapterSeen = attachedRecyclerView.getAdapter();
}
}
}
/**
* Don't call this method directly, it is called from
* {@link EpoxyVisibilityTracker#processVisibilityEvents}
*
* @param child the view to process for visibility event
* @param detachEvent true if the child was just detached
* @param eventOriginForDebug a debug strings used for logs
*/
private void processChild(@NonNull View child, boolean detachEvent, String eventOriginForDebug) {
final RecyclerView recyclerView = attachedRecyclerView;
if (recyclerView != null) {
final ViewHolder holder = recyclerView.getChildViewHolder(child);
if (holder instanceof EpoxyViewHolder) {
boolean changed = processVisibilityEvents(
recyclerView,
(EpoxyViewHolder) holder,
detachEvent,
eventOriginForDebug
);
if (changed) {
if (child instanceof RecyclerView) {
EpoxyVisibilityTracker tracker = nestedTrackers.get(child);
if (tracker != null) {
// If view visibility changed and there was a tracker on it then notify it.
tracker.processChangeEvent("parent");
}
}
}
} else {
throw new IllegalEpoxyUsage(
"`EpoxyVisibilityTracker` cannot be used with non-epoxy view holders."
);
}
}
}
/**
* Call this methods every time something related to ui (scroll, layout, ...) or something related
* to data changed.
*
* @param recyclerView the recycler view
* @param epoxyHolder the {@link RecyclerView}
* @param detachEvent true if the event originated from a view detached from the
* recycler view
* @param eventOriginForDebug a debug strings used for logs
* @return true if changed
*/
private boolean processVisibilityEvents(
@NonNull RecyclerView recyclerView,
@NonNull EpoxyViewHolder epoxyHolder,
boolean detachEvent,
String eventOriginForDebug
) {
if (DEBUG_LOG) {
Log.d(TAG, String.format("%s.processVisibilityEvents %s, %s, %s",
eventOriginForDebug,
System.identityHashCode(epoxyHolder),
detachEvent,
epoxyHolder.getAdapterPosition()
));
}
final View itemView = epoxyHolder.itemView;
final int id = System.identityHashCode(itemView);
EpoxyVisibilityItem vi = visibilityIdToItemMap.get(id);
if (vi == null) {
// New view discovered, assign an EpoxyVisibilityItem
vi = new EpoxyVisibilityItem(epoxyHolder.getAdapterPosition());
visibilityIdToItemMap.put(id, vi);
visibilityIdToItems.add(vi);
} else if (epoxyHolder.getAdapterPosition() != RecyclerView.NO_POSITION
&& vi.getAdapterPosition() != epoxyHolder.getAdapterPosition()) {
// EpoxyVisibilityItem being re-used for a different adapter position
vi.reset(epoxyHolder.getAdapterPosition());
}
boolean changed = false;
if (vi.update(itemView, recyclerView, detachEvent)) {
// View is measured, process events
vi.handleVisible(epoxyHolder, detachEvent);
vi.handleFocus(epoxyHolder, detachEvent);
vi.handleFullImpressionVisible(epoxyHolder, detachEvent);
changed = vi.handleChanged(epoxyHolder, onChangedEnabled);
}
return changed;
}
private void processChildRecyclerViewAttached(@NonNull RecyclerView childRecyclerView) {
// Register itself in the EpoxyVisibilityTracker. This will take care of nested list
// tracking (ex: carousel)
EpoxyVisibilityTracker tracker = getTracker(childRecyclerView);
if (tracker == null) {
tracker = new EpoxyVisibilityTracker();
tracker.attach(childRecyclerView);
}
nestedTrackers.put(childRecyclerView, tracker);
}
private void processChildRecyclerViewDetached(@NonNull RecyclerView childRecyclerView) {
nestedTrackers.remove(childRecyclerView);
}
/**
* Helper class that host the {@link androidx.recyclerview.widget.RecyclerView} listener
* implementations
*/
private class Listener extends OnScrollListener
implements OnLayoutChangeListener, OnChildAttachStateChangeListener {
@Override
public void onLayoutChange(
@NonNull View recyclerView,
int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom
) {
processChangeEvent("onLayoutChange");
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
processChangeEvent("onScrolled");
}
@Override
public void onChildViewAttachedToWindow(@NonNull View child) {
if (child instanceof RecyclerView) {
processChildRecyclerViewAttached((RecyclerView) child);
}
processChild(child, false, "onChildViewAttachedToWindow");
}
@Override
public void onChildViewDetachedFromWindow(@NonNull View child) {
if (child instanceof RecyclerView) {
processChildRecyclerViewDetached((RecyclerView) child);
}
if (visibleDataChanged) {
// On detach event caused by data set changed we need to re-process all children because
// the removal caused the others views to changes.
processChangeEventWithDetachedView(child, "onChildViewDetachedFromWindow");
visibleDataChanged = false;
} else {
processChild(child, true, "onChildViewDetachedFromWindow");
}
}
}
/**
* The layout/scroll events are not enough to detect all sort of visibility changes. We also
* need to look at the data events from the adapter.
*/
class DataObserver extends AdapterDataObserver {
/**
* Clear the current visibility statues
*/
@Override
public void onChanged() {
if (notEpoxyManaged(attachedRecyclerView)) {
return;
}
if (DEBUG_LOG) {
Log.d(TAG, "onChanged()");
}
visibilityIdToItemMap.clear();
visibilityIdToItems.clear();
visibleDataChanged = true;
}
/**
* For all items after the inserted range shift each {@link EpoxyVisibilityTracker} adapter
* position by inserted item count.
*/
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
if (notEpoxyManaged(attachedRecyclerView)) {
return;
}
if (DEBUG_LOG) {
Log.d(TAG, String.format("onItemRangeInserted(%d, %d)", positionStart, itemCount));
}
for (EpoxyVisibilityItem item : visibilityIdToItems) {
if (item.getAdapterPosition() >= positionStart) {
visibleDataChanged = true;
item.shiftBy(itemCount);
}
}
}
/**
* For all items after the removed range reverse-shift each {@link EpoxyVisibilityTracker}
* adapter position by removed item count
*/
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
if (notEpoxyManaged(attachedRecyclerView)) {
return;
}
if (DEBUG_LOG) {
Log.d(TAG, String.format("onItemRangeRemoved(%d, %d)", positionStart, itemCount));
}
for (EpoxyVisibilityItem item : visibilityIdToItems) {
if (item.getAdapterPosition() >= positionStart) {
visibleDataChanged = true;
item.shiftBy(-itemCount);
}
}
}
/**
* This is a bit more complex, for move we need to first swap the moved position then shift the
* items between the swap. To simplify we split any range passed to individual item moved.
*
* ps: anyway {@link androidx.recyclerview.widget.AdapterListUpdateCallback}
* does not seem to use range for moved items.
*/
@Override
public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
if (notEpoxyManaged(attachedRecyclerView)) {
return;
}
for (int i = 0; i < itemCount; i++) {
onItemMoved(fromPosition + i, toPosition + i);
}
}
private void onItemMoved(int fromPosition, int toPosition) {
if (notEpoxyManaged(attachedRecyclerView)) {
return;
}
if (DEBUG_LOG) {
Log.d(TAG,
String.format("onItemRangeMoved(%d, %d, %d)", fromPosition, toPosition, 1));
}
for (EpoxyVisibilityItem item : visibilityIdToItems) {
int position = item.getAdapterPosition();
if (position == fromPosition) {
// We found the item to be moved, just swap the position.
item.shiftBy(toPosition - fromPosition);
visibleDataChanged = true;
} else if (fromPosition < toPosition) {
// Item will be moved down in the list
if (position > fromPosition && position <= toPosition) {
// Item is between the moved from and to indexes, it should move up
item.shiftBy(-1);
visibleDataChanged = true;
}
} else if (fromPosition > toPosition) {
// Item will be moved up in the list
if (position >= toPosition && position < fromPosition) {
// Item is between the moved to and from indexes, it should move down
item.shiftBy(1);
visibleDataChanged = true;
}
}
}
}
/**
* @param recyclerView the recycler view
* @return true if managed by an {@link BaseEpoxyAdapter}
*/
private boolean notEpoxyManaged(RecyclerView recyclerView) {
return recyclerView == null || !(recyclerView.getAdapter() instanceof BaseEpoxyAdapter);
}
}
}
| Add missing `@Nullable` (#660)
| epoxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyVisibilityTracker.java | Add missing `@Nullable` (#660) | <ide><path>poxy-adapter/src/main/java/com/airbnb/epoxy/EpoxyVisibilityTracker.java
<ide> * @param recyclerView the recycler view
<ide> * @return true if managed by an {@link BaseEpoxyAdapter}
<ide> */
<del> private boolean notEpoxyManaged(RecyclerView recyclerView) {
<add> private boolean notEpoxyManaged(@Nullable RecyclerView recyclerView) {
<ide> return recyclerView == null || !(recyclerView.getAdapter() instanceof BaseEpoxyAdapter);
<ide> }
<ide> } |
|
JavaScript | mit | fe4a1bde85a696e144fbc6e8ed004f68000895c4 | 0 | MementoHackathon2015/ldf-memento-client,infitude/Client.js | /*! @license ©2014 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */
/* An SparqlIterator returns the results of a SPARQL query. */
var SparqlParser = require('sparqljs').Parser,
Iterator = require('../iterators/Iterator'),
TransformIterator = Iterator.TransformIterator,
ReorderingGraphPatternIterator = require('./ReorderingGraphPatternIterator'),
UnionIterator = require('../iterators/UnionIterator'),
FilterIterator = require('../iterators/FilterIterator'),
SortIterator = require('../iterators/SortIterator'),
LimitIterator = require('../iterators/LimitIterator'),
DistinctIterator = require('../iterators/DistinctIterator'),
SparqlExpressionEvaluator = require('../util/SparqlExpressionEvaluator'),
_ = require('lodash'),
util = require('util'),
rdf = require('../util/RdfUtil');
// Creates an iterator from a SPARQL query
function SparqlIterator(source, queryText, options) {
// Shift arguments if `source` was omitted
if (typeof source === 'string')
options = queryText, queryText = source, source = null;
// Transform the query into a cascade of iterators
try {
// Create an iterator that projects the bindings according to the query type
var query = new SparqlParser(options.prefixes).parse(queryText),
queryIterator, QueryConstructor = queryConstructors[query.queryType];
if (!QueryConstructor)
throw new Error('No iterator available for query type: ' + query.queryType);
queryIterator = new QueryConstructor(true, query, options);
// Create an iterator for bindings of the query's graph pattern
var graphIterator = new SparqlGroupsIterator(source || Iterator.single({}),
queryIterator.patterns || query.where, options);
// Create iterators for each order
for (var i = query.order && (query.order.length - 1); i >= 0; i--) {
var order = SparqlExpressionEvaluator(query.order[i].expression),
ascending = !query.order[i].descending;
graphIterator = new SortIterator(graphIterator, function (a, b) {
var orderA = order(a), orderB = order(b);
if (orderA < orderB) return ascending ? -1 : 1;
if (orderB < orderA) return ascending ? 1 : -1;
return 0;
}, options);
}
queryIterator.setSource(graphIterator);
// Create iterators for modifiers
if (query.distinct)
queryIterator = new DistinctIterator(queryIterator, options);
// Add offsets and limits if requested
if ('offset' in query || 'limit' in query)
queryIterator = new LimitIterator(queryIterator, query.offset, query.limit, options);
queryIterator.queryType = query.queryType;
return queryIterator;
}
catch (error) {
if (/Parse error/.test(error.message))
error = new InvalidQueryError(queryText, error);
else
error = new UnsupportedQueryError(queryText, error);
throw error;
}
}
TransformIterator.inherits(SparqlIterator);
var queryConstructors = {
SELECT: SparqlSelectIterator,
CONSTRUCT: SparqlConstructIterator,
DESCRIBE: SparqlDescribeIterator,
ASK: SparqlAskIterator,
};
// Creates an iterator for a parsed SPARQL SELECT query
function SparqlSelectIterator(source, query, options) {
TransformIterator.call(this, source, options);
this.setProperty('variables', query.variables);
}
SparqlIterator.inherits(SparqlSelectIterator);
// Executes the SELECT projection
SparqlSelectIterator.prototype._transform = function (bindings, done) {
this._push(this.getProperty('variables').reduce(function (row, variable) {
// Project a simple variable by copying its value
if (variable !== '*')
row[variable] = bindings[variable];
// Project a star selector by copying all variable bindings
else
for (variable in bindings)
if (rdf.isVariable(variable))
row[variable] = bindings[variable];
return row;
}, Object.create(null)));
done();
};
// Creates an iterator for a parsed SPARQL CONSTRUCT query
function SparqlConstructIterator(source, query, options) {
TransformIterator.call(this, source, options);
this._template = query.template;
}
SparqlIterator.inherits(SparqlConstructIterator);
// Executes the CONSTRUCT projection
SparqlConstructIterator.prototype._transform = function (bindings, done) {
this._template.forEach(function (triplePattern) {
var triple = rdf.applyBindings(bindings, triplePattern);
if (!rdf.hasVariables(triple))
this._push(triple);
// TODO: blank nodes should get different identifiers on each iteration
// TODO: discard repeated identical bindings of the same variable
}, this);
done();
};
// Creates an iterator for a parsed SPARQL DESCRIBE query
function SparqlDescribeIterator(source, query, options) {
SparqlConstructIterator.call(this, source, query, options);
// Create a template with `?var ?p ?o` patterns for each variable
var variables = query.variables, template = this._template = [];
for (var i = 0, l = variables.length; i < l; i++)
template.push(rdf.triple(variables[i], '?__predicate' + i, '?__object' + i));
// Add the template to this query's patterns
this.patterns = query.where.concat({ type: 'bgp', triples: template });
}
SparqlConstructIterator.inherits(SparqlDescribeIterator);
// Creates an iterator for a parsed SPARQL ASK query
function SparqlAskIterator(source, query, options) {
TransformIterator.call(this, source, options);
}
SparqlIterator.inherits(SparqlAskIterator);
// If an answer to the query exists, end the iterator
SparqlAskIterator.prototype._transform = function (bindings, done) {
this._push(true);
this._push(null);
done();
};
// If the iterator was not ended, no answer exists
SparqlAskIterator.prototype._flush = function () {
if (!this.ended) {
this._push(false);
this._push(null);
}
};
// Creates an iterator for a list of SPARQL groups
function SparqlGroupsIterator(source, groups, options) {
// Chain iterators for each of the graphs in the group
return groups.reduce(function (source, group) {
return new SparqlGroupIterator(source, group, options);
}, source);
}
Iterator.inherits(SparqlGroupIterator);
// Creates an iterator for a SPARQL group
function SparqlGroupIterator(source, group, options) {
// Reset flags on the options for child iterators
var childOptions = options.optional ? _.create(options, { optional: false }) : options;
switch (group.type) {
case 'bgp':
return new ReorderingGraphPatternIterator(source, group.triples, options);
case 'optional':
options = _.create(options, { optional: true });
return new SparqlGroupsIterator(source, group.patterns, options);
case 'union':
return new UnionIterator(group.patterns.map(function (patternToken) {
return new SparqlGroupIterator(source.clone(), patternToken, childOptions);
}), options);
case 'filter':
// An set of bindings matches the filter if it doesn't evaluate to 0 or false
var evaluate = SparqlExpressionEvaluator(group.expression);
return new FilterIterator(source, function (bindings) {
return !/^"false"|^"0"/.test(evaluate(bindings));
}, options);
default:
throw new Error('Unsupported group type: ' + group.type);
}
}
Iterator.inherits(SparqlGroupIterator);
// Error thrown when the query has a syntax error
function InvalidQueryError(query, cause) {
this.name = 'InvalidQueryError';
this.query = query;
this.cause = cause;
this.message = 'Syntax error in query\n' + cause.message;
}
util.inherits(InvalidQueryError, Error);
// Error thrown when no combination of iterators can solve the query
function UnsupportedQueryError(query, cause) {
this.name = 'UnsupportedQueryError';
this.query = query;
this.cause = cause;
this.message = 'The query is not yet supported\n' + cause.message;
}
util.inherits(UnsupportedQueryError, Error);
module.exports = SparqlIterator;
SparqlIterator.InvalidQueryError = InvalidQueryError;
SparqlIterator.UnsupportedQueryError = UnsupportedQueryError;
| lib/triple-pattern-fragments/SparqlIterator.js | /*! @license ©2014 Ruben Verborgh - Multimedia Lab / iMinds / Ghent University */
/* An SparqlIterator returns the results of a SPARQL query. */
var SparqlParser = require('sparqljs').Parser,
Iterator = require('../iterators/Iterator'),
TransformIterator = Iterator.TransformIterator,
ReorderingGraphPatternIterator = require('./ReorderingGraphPatternIterator'),
UnionIterator = require('../iterators/UnionIterator'),
FilterIterator = require('../iterators/FilterIterator'),
SortIterator = require('../iterators/SortIterator'),
LimitIterator = require('../iterators/LimitIterator'),
DistinctIterator = require('../iterators/DistinctIterator'),
SparqlExpressionEvaluator = require('../util/SparqlExpressionEvaluator'),
_ = require('lodash'),
util = require('util'),
rdf = require('../util/RdfUtil');
// Creates an iterator from a SPARQL query
function SparqlIterator(source, queryText, options) {
// Shift arguments if `source` was omitted
if (typeof source === 'string')
options = queryText, queryText = source, source = null;
// Transform the query into a cascade of iterators
try {
// Create an iterator that projects the bindings according to the query type
var query = new SparqlParser(options.prefixes).parse(queryText),
queryIterator, QueryConstructor = queryConstructors[query.queryType];
if (!QueryConstructor)
throw new Error('No iterator available for query type: ' + query.queryType);
queryIterator = new QueryConstructor(true, query, options);
// Create an iterator for bindings of the query's graph pattern
var graphIterator = new SparqlGroupsIterator(source || Iterator.single({}),
queryIterator.patterns || query.where, options);
// Create iterators for each order
for (var i = query.order && (query.order.length - 1); i >= 0; i--) {
var order = SparqlExpressionEvaluator(query.order[i].expression),
ascending = !query.order[i].descending;
graphIterator = new SortIterator(graphIterator, function (a, b) {
var orderA = order(a), orderB = order(b);
if (orderA < orderB) return ascending ? -1 : 1;
if (orderB < orderA) return ascending ? 1 : -1;
return 0;
}, options);
}
queryIterator.setSource(graphIterator);
// Create iterators for modifiers
if (query.distinct)
queryIterator = new DistinctIterator(queryIterator, options);
// Add offsets and limits if requested
if ('offset' in query || 'limit' in query)
queryIterator = new LimitIterator(queryIterator, query.offset, query.limit, options);
queryIterator.queryType = query.queryType;
return queryIterator;
}
catch (error) {
if (/Parse error/.test(error.message))
error = new InvalidQueryError(queryText, error);
else
error = new UnsupportedQueryError(queryText, error);
throw error;
}
}
TransformIterator.inherits(SparqlIterator);
var queryConstructors = {
SELECT: SparqlSelectIterator,
CONSTRUCT: SparqlConstructIterator,
DESCRIBE: SparqlDescribeIterator,
ASK: SparqlAskIterator,
};
// Creates an iterator for a parsed SPARQL SELECT query
function SparqlSelectIterator(source, query, options) {
TransformIterator.call(this, source, options);
this.setProperty('variables', query.variables);
}
SparqlIterator.inherits(SparqlSelectIterator);
// Executes the SELECT projection
SparqlSelectIterator.prototype._transform = function (bindings, done) {
this._push(this.getProperty('variables').reduce(function (row, variable) {
// Project a simple variable by copying its value
if (variable !== '*')
row[variable] = bindings[variable];
// Project a star selector by copying all values
else
for (variable in bindings)
row[variable] = bindings[variable];
return row;
}, Object.create(null)));
done();
};
// Creates an iterator for a parsed SPARQL CONSTRUCT query
function SparqlConstructIterator(source, query, options) {
TransformIterator.call(this, source, options);
this._template = query.template;
}
SparqlIterator.inherits(SparqlConstructIterator);
// Executes the CONSTRUCT projection
SparqlConstructIterator.prototype._transform = function (bindings, done) {
this._template.forEach(function (triplePattern) {
var triple = rdf.applyBindings(bindings, triplePattern);
if (!rdf.hasVariables(triple))
this._push(triple);
// TODO: blank nodes should get different identifiers on each iteration
// TODO: discard repeated identical bindings of the same variable
}, this);
done();
};
// Creates an iterator for a parsed SPARQL DESCRIBE query
function SparqlDescribeIterator(source, query, options) {
SparqlConstructIterator.call(this, source, query, options);
// Create a template with `?var ?p ?o` patterns for each variable
var variables = query.variables, template = this._template = [];
for (var i = 0, l = variables.length; i < l; i++)
template.push(rdf.triple(variables[i], '?__predicate' + i, '?__object' + i));
// Add the template to this query's patterns
this.patterns = query.where.concat({ type: 'bgp', triples: template });
}
SparqlConstructIterator.inherits(SparqlDescribeIterator);
// Creates an iterator for a parsed SPARQL ASK query
function SparqlAskIterator(source, query, options) {
TransformIterator.call(this, source, options);
}
SparqlIterator.inherits(SparqlAskIterator);
// If an answer to the query exists, end the iterator
SparqlAskIterator.prototype._transform = function (bindings, done) {
this._push(true);
this._push(null);
done();
};
// If the iterator was not ended, no answer exists
SparqlAskIterator.prototype._flush = function () {
if (!this.ended) {
this._push(false);
this._push(null);
}
};
// Creates an iterator for a list of SPARQL groups
function SparqlGroupsIterator(source, groups, options) {
// Chain iterators for each of the graphs in the group
return groups.reduce(function (source, group) {
return new SparqlGroupIterator(source, group, options);
}, source);
}
Iterator.inherits(SparqlGroupIterator);
// Creates an iterator for a SPARQL group
function SparqlGroupIterator(source, group, options) {
// Reset flags on the options for child iterators
var childOptions = options.optional ? _.create(options, { optional: false }) : options;
switch (group.type) {
case 'bgp':
return new ReorderingGraphPatternIterator(source, group.triples, options);
case 'optional':
options = _.create(options, { optional: true });
return new SparqlGroupsIterator(source, group.patterns, options);
case 'union':
return new UnionIterator(group.patterns.map(function (patternToken) {
return new SparqlGroupIterator(source.clone(), patternToken, childOptions);
}), options);
case 'filter':
// An set of bindings matches the filter if it doesn't evaluate to 0 or false
var evaluate = SparqlExpressionEvaluator(group.expression);
return new FilterIterator(source, function (bindings) {
return !/^"false"|^"0"/.test(evaluate(bindings));
}, options);
default:
throw new Error('Unsupported group type: ' + group.type);
}
}
Iterator.inherits(SparqlGroupIterator);
// Error thrown when the query has a syntax error
function InvalidQueryError(query, cause) {
this.name = 'InvalidQueryError';
this.query = query;
this.cause = cause;
this.message = 'Syntax error in query\n' + cause.message;
}
util.inherits(InvalidQueryError, Error);
// Error thrown when no combination of iterators can solve the query
function UnsupportedQueryError(query, cause) {
this.name = 'UnsupportedQueryError';
this.query = query;
this.cause = cause;
this.message = 'The query is not yet supported\n' + cause.message;
}
util.inherits(UnsupportedQueryError, Error);
module.exports = SparqlIterator;
SparqlIterator.InvalidQueryError = InvalidQueryError;
SparqlIterator.UnsupportedQueryError = UnsupportedQueryError;
| Don't output blanks with *. | lib/triple-pattern-fragments/SparqlIterator.js | Don't output blanks with *. | <ide><path>ib/triple-pattern-fragments/SparqlIterator.js
<ide> // Project a simple variable by copying its value
<ide> if (variable !== '*')
<ide> row[variable] = bindings[variable];
<del> // Project a star selector by copying all values
<add> // Project a star selector by copying all variable bindings
<ide> else
<ide> for (variable in bindings)
<del> row[variable] = bindings[variable];
<add> if (rdf.isVariable(variable))
<add> row[variable] = bindings[variable];
<ide> return row;
<ide> }, Object.create(null)));
<ide> done(); |
|
Java | mit | fbf65fe181d0cf37fb12fbb137de0180a3be75f7 | 0 | digibib/ls.ext,digibib/ls.ext,digibib/ls.ext,digibib/ls.ext | package no.deichman.services.search;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jamonapi.Monitor;
import com.jamonapi.MonitorFactory;
import no.deichman.services.entity.EntityService;
import no.deichman.services.entity.EntityType;
import no.deichman.services.uridefaults.XURI;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.ResIterator;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.SimpleSelector;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.ServerErrorException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import static com.google.common.collect.ImmutableMap.of;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newConcurrentHashSet;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.URLEncoder.encode;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
import static javax.ws.rs.core.HttpHeaders.CONTENT_LENGTH;
import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE;
import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
import static no.deichman.services.uridefaults.BaseURI.ontology;
import static org.apache.http.entity.ContentType.APPLICATION_JSON;
import static org.apache.http.impl.client.HttpClients.createDefault;
import static org.apache.jena.rdf.model.ResourceFactory.createProperty;
import static org.apache.jena.rdf.model.ResourceFactory.createResource;
/**
* Responsibility: perform indexing and searching.
*/
public class SearchServiceImpl implements SearchService {
public static final Property AGENT = createProperty(ontology("agent"));
private static final Logger LOG = LoggerFactory.getLogger(SearchServiceImpl.class);
private static final String UTF_8 = "UTF-8";
public static final int SIXTY_ONE = 61;
public static final String[] LOCAL_INDEX_SEARCH_FIELDS = {
ontology("name"),
ontology("prefLabel"),
ontology("mainTitle")
};
public static final Resource MAIN_ENTRY = createResource(ontology("MainEntry"));
public static final int SILENT_PERIOD = 100000;
private final EntityService entityService;
private final String elasticSearchBaseUrl;
private ModelToIndexMapper workModelToIndexMapper = new ModelToIndexMapper("work");
private ModelToIndexMapper eventModelToIndexMapper = new ModelToIndexMapper("event");
private ModelToIndexMapper serialModelToIndexMapper = new ModelToIndexMapper("serial");
private ModelToIndexMapper personModelToIndexMapper = new ModelToIndexMapper("person");
private ModelToIndexMapper corporationModelToIndexMapper = new ModelToIndexMapper("corporation");
private ModelToIndexMapper publicationModelToIndexMapper = new ModelToIndexMapper("publication");
public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private int skipped;
private static Set<String> indexedUris;
private static long lastIndexedTime;
public SearchServiceImpl(String elasticSearchBaseUrl, EntityService entityService) {
this.elasticSearchBaseUrl = elasticSearchBaseUrl;
this.entityService = entityService;
getIndexUriBuilder();
}
@Override
public final void index(XURI xuri) throws Exception {
if (indexedUris == null || !indexedUris.contains(xuri.getUri())) {
switch (xuri.getTypeAsEntityType()) {
case WORK:
doIndexWork(xuri, false, false);
break;
case PERSON:
case CORPORATION:
doIndexWorkCreator(xuri, false);
break;
case PUBLICATION:
doIndexPublication(xuri);
break;
case EVENT:
doIndexEvent(xuri);
break;
case SERIAL:
doIndexSerial(xuri);
break;
default:
doIndex(xuri);
}
} else {
LOG.info("Skipping already indexed uri: " + xuri.getUri());
skipped++;
}
if (indexedUris != null) {
indexedUris.add(xuri.getUri());
}
}
public final void indexOnly(XURI xuri) throws Exception {
if (indexedUris == null || !indexedUris.contains(xuri.getUri())) {
switch (xuri.getTypeAsEntityType()) {
case WORK:
doIndexWork(xuri, true, true);
break;
case PERSON:
case CORPORATION:
doIndexWorkCreator(xuri, true);
break;
case PUBLICATION:
doIndexPublication(xuri);
break;
case EVENT:
doIndexEvent(xuri);
break;
case SERIAL:
doIndexSerial(xuri);
break;
default:
doIndex(xuri);
}
} else {
LOG.info("Skipping already indexed uri: " + xuri.getUri());
skipped++;
}
if (indexedUris != null) {
indexedUris.add(xuri.getUri());
}
}
private void doIndexEvent(XURI xuri) {
Model eventModelWithLinkedResources = entityService.retrieveEventWithLinkedResources(xuri);
indexDocument(xuri, eventModelToIndexMapper.createIndexDocument(eventModelWithLinkedResources, xuri));
cacheNameIndex(xuri, eventModelWithLinkedResources);
}
private void doIndexSerial(XURI xuri) {
Model serialModelWithLinkedResources = entityService.retrieveSerialWithLinkedResources(xuri);
indexDocument(xuri, serialModelToIndexMapper.createIndexDocument(serialModelWithLinkedResources, xuri));
cacheNameIndex(xuri, serialModelWithLinkedResources);
}
@Override
public final Response searchPersonWithJson(String json) {
return searchWithJson(json, getPersonSearchUriBuilder());
}
@Override
public final Response searchWorkWithJson(String json, MultivaluedMap<String, String> queryParams) {
return searchWithJson(json, getWorkSearchUriBuilder(queryParams));
}
@Override
public final Response searchPublicationWithJson(String json) {
return searchWithJson(json, getPublicationSearchUriBuilder());
}
@Override
public final Response searchInstrument(String query) {
return doSearch(query, getInstrumentSearchUriBuilder());
}
@Override
public final Response searchCompositionType(String query) {
return doSearch(query, getCompositionTypeSearchUriBuilder());
}
@Override
public final Response searchEvent(String query) {
return doSearch(query, getEventSearchUriBuilder());
}
@Override
public final Response clearIndex() {
try (CloseableHttpClient httpclient = createDefault()) {
URI uri = getIndexUriBuilder().setPath("/search").build();
try (CloseableHttpResponse getExistingIndex = httpclient.execute(new HttpGet(uri))) {
if (getExistingIndex.getStatusLine().getStatusCode() == HTTP_OK) {
try (CloseableHttpResponse delete = httpclient.execute(new HttpDelete(uri))) {
int statusCode = delete.getStatusLine().getStatusCode();
LOG.info("Delete index request returned status " + statusCode);
if (statusCode != HTTP_OK) {
throw new ServerErrorException("Failed to delete elasticsearch index", HTTP_INTERNAL_ERROR);
}
}
}
}
HttpPut createIndexRequest = new HttpPut(uri);
createIndexRequest.setEntity(new InputStreamEntity(getClass().getResourceAsStream("/search_index.json"), APPLICATION_JSON));
try (CloseableHttpResponse create = httpclient.execute(createIndexRequest)) {
int statusCode = create.getStatusLine().getStatusCode();
LOG.info("Create index request returned status " + statusCode);
if (statusCode != HTTP_OK) {
throw new ServerErrorException("Failed to create elasticsearch index", HTTP_INTERNAL_ERROR);
}
}
putIndexMapping(httpclient, "work");
putIndexMapping(httpclient, "person");
putIndexMapping(httpclient, "serial");
putIndexMapping(httpclient, "corporation");
putIndexMapping(httpclient, "place");
putIndexMapping(httpclient, "subject");
putIndexMapping(httpclient, "genre");
putIndexMapping(httpclient, "publication");
putIndexMapping(httpclient, "instrument");
putIndexMapping(httpclient, "compositionType");
putIndexMapping(httpclient, "event");
putIndexMapping(httpclient, "workSeries");
return Response.status(Response.Status.OK).build();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR);
}
}
private void putIndexMapping(CloseableHttpClient httpclient, String type) throws URISyntaxException, IOException {
URI workIndexUri = getIndexUriBuilder().setPath("/search/_mapping/" + type).build();
HttpPut putWorkMappingRequest = new HttpPut(workIndexUri);
putWorkMappingRequest.setEntity(new InputStreamEntity(getClass().getResourceAsStream("/" + type + "_mapping.json"), APPLICATION_JSON));
try (CloseableHttpResponse create = httpclient.execute(putWorkMappingRequest)) {
int statusCode = create.getStatusLine().getStatusCode();
LOG.info("Create mapping request for " + type + " returned status " + statusCode);
if (statusCode != HTTP_OK) {
throw new ServerErrorException("Failed to create elasticsearch mapping for " + type, HTTP_INTERNAL_ERROR);
}
}
}
private Response searchWithJson(String body, URIBuilder searchUriBuilder, Function<String, String>... jsonTranformer) {
try {
HttpPost httpPost = new HttpPost(searchUriBuilder.build());
httpPost.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
httpPost.setHeader(CONTENT_TYPE, "application/json");
Pair<String, Header[]> searchResult = executeHttpRequest(httpPost);
if (jsonTranformer != null && jsonTranformer.length > 0) {
String transformed = jsonTranformer[0].apply(searchResult.getLeft());
Header[] headers = searchResult.getRight();
searchResult = Pair.of(transformed, removeHeader(headers, CONTENT_LENGTH));
}
return createResponse(searchResult);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR);
}
}
private Header[] removeHeader(Header[] headers, String headerName) {
return stream(headers)
.filter(header -> !header
.getName()
.toLowerCase()
.equalsIgnoreCase(headerName))
.toArray(Header[]::new);
}
private Response createResponse(Pair<String, Header[]> searchResult) {
Response.ResponseBuilder responseBuilder = Response.ok(searchResult.getLeft());
for (Header header : searchResult.getRight()) {
responseBuilder = responseBuilder.header(header.getName(), header.getValue());
}
return responseBuilder.build();
}
private Pair<String, Header[]> executeHttpRequest(HttpRequestBase httpRequestBase) throws IOException {
try (CloseableHttpClient httpclient = createDefault();
CloseableHttpResponse response = httpclient.execute(httpRequestBase)) {
HttpEntity responseEntity = response.getEntity();
String jsonContent = IOUtils.toString(responseEntity.getContent());
Header[] headers = response.getAllHeaders();
return Pair.<String, Header[]>of(jsonContent, headers);
} catch (Exception e) {
throw e;
}
}
@Override
public final Response searchWork(String query) {
return doSearch(query, getWorkSearchUriBuilder(null));
}
@Override
public final Response searchPerson(String query) {
return doSearch(query, getPersonSearchUriBuilder());
}
@Override
public final Response searchPlace(String query) {
return doSearch(query, getPlaceUriBuilder());
}
@Override
public final Response searchCorporation(String query) {
return doSearch(query, getCorporationSearchUriBuilder());
}
@Override
public final Response searchSerial(String query) {
return doSearch(query, getSerialSearchUriBuilder());
}
@Override
public final Response searchSubject(String query) {
return doSearch(query, getSubjectSearchUriBuilder());
}
@Override
public final Response searchGenre(String query) {
return doSearch(query, getGenreSearchUriBuilder());
}
@Override
public final Response searchPublication(String query) {
return doSearch(query, getPublicationSearchUriBuilder());
}
@Override
public final void delete(XURI xuri) {
try (CloseableHttpClient httpclient = createDefault()) {
HttpDelete httpDelete = new HttpDelete(getIndexUriBuilder()
.setPath(format("/search/%s/%s", xuri.getType(), encode(xuri.getUri(), UTF_8)))
.build());
try (CloseableHttpResponse putResponse = httpclient.execute(httpDelete)) {
// no-op
}
} catch (Exception e) {
LOG.error(format("Failed to delete %s in elasticsearch", xuri.getUri()), e);
throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR);
}
}
@Override
public final Response sortedList(String type, String prefix, int minSize, String field) {
EntityType entityType = EntityType.get(type);
URIBuilder searchUriBuilder = getIndexUriBuilder().setPath("/search/" + type + "/_search").setParameter("size", Integer.toString(minSize));
switch (entityType) {
case PERSON:
case CORPORATION:
case PLACE:
case SUBJECT:
case EVENT:
case WORK_SERIES:
case SERIAL:
case GENRE:
case MUSICAL_INSTRUMENT:
case MUSICAL_COMPOSITION_TYPE:
Collection<NameEntry> nameEntries = entityService.neighbourhoodOfName(entityType, prefix, minSize);
return searchWithJson(createPreIndexedSearchQuery(minSize, nameEntries),
searchUriBuilder, orderResultByIdOrder(nameEntries
.stream()
.map(NameEntry::getUri)
.collect(toList())));
default:
return searchWithJson(createSortedListQuery(prefix, minSize, field), searchUriBuilder);
}
}
private Function<String, String> orderResultByIdOrder(Collection<String> ids) {
Map<String, Integer> desiredOrder = new HashMap<>(ids.size());
final int[] i = new int[]{0};
ids.forEach(id -> desiredOrder.put(urlEncode(id), i[0]++));
return s -> {
Map fromJson = GSON.fromJson(s, Map.class);
((List) ((Map) fromJson.get("hits")).get("hits")).sort((o1, o2) -> {
String id1 = (String) ((Map) o1).get("_id");
String id2 = (String) ((Map) o2).get("_id");
return desiredOrder.get(id1).compareTo(desiredOrder.get(id2));
});
return GSON.toJson(fromJson);
};
}
private String createSortedListQuery(String prefix, int minSize, String field) {
String sortedListQuery;
List<Map> should = new ArrayList<>();
for (int i = 0; i < prefix.length(); i++) {
should.add(
of("constant_score",
of("boost", 2 << Math.max(prefix.length() - i, SIXTY_ONE), "query",
of("match_phrase_prefix", of(field, prefix.substring(0, prefix.length() - i))))));
}
sortedListQuery = GSON.toJson(of(
"size", minSize,
"query", of(
"bool", of(
"should", should)
)
));
return sortedListQuery;
}
private String createPreIndexedSearchQuery(int minSize, Collection<NameEntry> nameEntries) {
List<Map> should = new ArrayList<>();
should.addAll(nameEntries
.stream()
.filter(NameEntry::isBestMatch)
.map(e -> of(
"ids", of("values", newArrayList(urlEncode(e.getUri())))))
.collect(toList()));
should.add(of(
"ids", of("values",
nameEntries
.stream()
.map(NameEntry::getUri)
.map(SearchServiceImpl::urlEncode)
.collect(toList())
)
));
return GSON.toJson(
of(
"size", minSize,
"query", of(
"bool", of("should", should)
)
)
);
}
private static String urlEncode(String uri) {
return uri.replace(":", "%3A").replace("/", "%2F");
}
@Override
public final Response searchWorkWhereUriIsSubject(String subjectUri, int maxSize) {
String body = GSON.toJson(of(
"size", maxSize,
"query", of(
"nested", of(
"path", "subjects",
"query", of("term", of(
"subjects.uri", subjectUri)
)
)
)
));
return searchWithJson(body, getIndexUriBuilder().setPath("/search/work/_search"));
}
@Override
public final Response searchWorkSeries(String query) {
return doSearch(query, getWorkSeriesSearchUriBuilder());
}
@Override
public final void indexUrisOnlyOnce(boolean indexOnce) {
if (indexOnce) {
LOG.info("Turning on only once uri indexing");
indexedUris = newConcurrentHashSet();
skipped = 0;
} else {
LOG.info("Turning off only once uri indexing after skipping " + skipped + " uris");
indexedUris = null;
lastIndexedTime = 0;
}
}
private URIBuilder getWorkSeriesSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/workSeries/_search");
}
private void doIndexPublication(XURI pubUri) throws Exception {
Model pubModel = entityService.retrieveById(pubUri);
Property publicationOfProperty = createProperty(ontology("publicationOf"));
if (pubModel.getProperty(null, publicationOfProperty) != null) {
String workUri = pubModel.getProperty(createResource(pubUri.toString()), publicationOfProperty).getObject().toString();
XURI workXURI = new XURI(workUri);
pubModel = entityService.retrieveWorkWithLinkedResources(workXURI);
}
indexDocument(pubUri, publicationModelToIndexMapper.createIndexDocument(pubModel, pubUri));
}
private void doIndexWork(XURI xuri, boolean indexedPerson, boolean indexedPublication) throws Exception {
Monitor mon = MonitorFactory.start("doIndexWork1");
Model workModelWithLinkedResources = entityService.retrieveWorkWithLinkedResources(xuri);
indexDocument(xuri, workModelToIndexMapper.createIndexDocument(workModelWithLinkedResources, xuri));
mon.stop();
mon = MonitorFactory.start("doIndexWork2");
if (!indexedPerson) {
workModelWithLinkedResources.listStatements(isMainContributorOfWork(xuri, workModelWithLinkedResources))
.forEachRemaining(stmt -> {
try {
XURI creatorXuri = new XURI(stmt.getObject().asNode().getURI());
doIndexWorkCreatorOnly(creatorXuri);
} catch (Exception e) {
e.printStackTrace();
}
});
}
mon.stop();
if (indexedPublication) {
return;
}
// Index all publications belonging to work
// TODO instead of iterating over all subjects, find only subjects of triples with publicationOf as predicate
mon = MonitorFactory.start("doIndexWork3");
ResIterator subjectIterator = workModelWithLinkedResources.listSubjects();
while (subjectIterator.hasNext()) {
Resource subj = subjectIterator.next();
if (subj.isAnon()) {
continue;
}
if (subj.toString().contains("publication")) {
XURI pubUri = new XURI(subj.toString());
indexDocument(pubUri, publicationModelToIndexMapper.createIndexDocument(workModelWithLinkedResources, pubUri));
}
}
mon.stop();
}
private SimpleSelector isMainContributorOfWork(final XURI xuri, final Model workModelWithLinkedResources) {
return new SimpleSelector() {
@Override
public boolean test(Statement s) {
return (s.getPredicate().equals(AGENT)
&& workModelWithLinkedResources.contains(s.getSubject(), RDF.type, MAIN_ENTRY)
&& workModelWithLinkedResources.contains(
createResource(xuri.getUri()),
createProperty(ontology("contributor")),
s.getSubject())
);
}
};
}
private void doIndexWorkCreator(XURI creatorUri, boolean indexedWork) throws Exception {
Monitor mon = MonitorFactory.start("doIndexWorkCreator");
Model works = entityService.retrieveWorksByCreator(creatorUri);
if (!indexedWork) {
ResIterator subjectIterator = works.listSubjects();
while (subjectIterator.hasNext()) {
Resource subj = subjectIterator.next();
if (subj.isAnon() || subj.toString().indexOf('#') != -1) {
continue;
}
XURI workUri = new XURI(subj.toString());
if (!workUri.getUri().equals(creatorUri.getUri())) {
doIndexWorkOnly(workUri);
}
}
}
switch (creatorUri.getTypeAsEntityType()) {
case PERSON:
indexDocument(creatorUri, personModelToIndexMapper
.createIndexDocument(entityService.retrievePersonWithLinkedResources(creatorUri).add(works), creatorUri));
cacheNameIndex(creatorUri, works);
break;
case CORPORATION:
indexDocument(creatorUri, corporationModelToIndexMapper
.createIndexDocument(entityService.retrieveCorporationWithLinkedResources(creatorUri).add(works), creatorUri));
cacheNameIndex(creatorUri, works);
break;
default:
throw new RuntimeException(format(
"Tried to index work creator of type %1$s. Should be %2$s or %3$s",
creatorUri.getTypeAsEntityType(), EntityType.PERSON, EntityType.CORPORATION
));
}
mon.stop();
}
private void doIndex(XURI xuri) throws Exception {
Model indexModel = entityService.retrieveById(xuri);
Monitor mon = MonitorFactory.start("createIndexDocument");
String indexDocument = new ModelToIndexMapper(xuri.getTypeAsEntityType().getPath()).createIndexDocument(indexModel, xuri);
mon.stop();
indexDocument(xuri, indexDocument);
cacheNameIndex(xuri, indexModel);
}
private void cacheNameIndex(XURI xuri, Model indexModel) {
entityService.statementsInModelAbout(xuri, indexModel, LOCAL_INDEX_SEARCH_FIELDS)
.forEachRemaining(statement -> {
entityService.addIndexedName(
xuri.getTypeAsEntityType(),
statement.getObject().asLiteral().toString(),
statement.getSubject().getURI());
});
}
private void doIndexWorkOnly(XURI xuri) throws Exception {
doIndexWork(xuri, true, false);
}
private void indexDocument(XURI xuri, String document) {
long now = currentTimeMillis();
if (indexedUris != null && lastIndexedTime > 0 && now - lastIndexedTime > SILENT_PERIOD) {
indexUrisOnlyOnce(false);
}
if (indexedUris == null || !indexedUris.contains(xuri.getUri())) {
try (CloseableHttpClient httpclient = createDefault()) {
HttpPut httpPut = new HttpPut(getIndexUriBuilder()
.setPath(format("/search/%s/%s", xuri.getType(), encode(xuri.getUri(), UTF_8))) // TODO drop urlencoded ID, and define _id in mapping from field uri
.build());
httpPut.setEntity(new StringEntity(document, Charset.forName(UTF_8)));
httpPut.setHeader(CONTENT_TYPE, APPLICATION_JSON.withCharset(UTF_8).toString());
Monitor mon = MonitorFactory.start("indexDocument");
try (CloseableHttpResponse putResponse = httpclient.execute(httpPut)) {
// no-op
} finally {
mon.stop();
}
lastIndexedTime = now;
} catch (Exception e) {
LOG.error(format("Failed to index %s in elasticsearch", xuri.getUri()), e);
throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR);
}
} else {
LOG.info("Skipping already indexed uri: " + xuri.getUri());
skipped++;
}
if (indexedUris != null) {
indexedUris.add(xuri.getUri());
}
}
private Response doSearch(String query, URIBuilder searchUriBuilder) {
try {
HttpGet httpGet = new HttpGet(searchUriBuilder
.setParameter("q", query)
.setParameter("size", "100")
.build());
return createResponse(executeHttpRequest(httpGet));
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR);
}
}
private void doIndexWorkCreatorOnly(XURI xuri) throws Exception {
doIndexWorkCreator(xuri, true);
}
private URIBuilder getIndexUriBuilder() {
try {
return new URIBuilder(this.elasticSearchBaseUrl);
} catch (URISyntaxException e) {
LOG.error("Failed to create uri builder for elasticsearch");
throw new RuntimeException(e);
}
}
private URIBuilder getWorkSearchUriBuilder(MultivaluedMap<String, String> queryParams) {
URIBuilder uriBuilder = getIndexUriBuilder().setPath("/search/work/_search");
if (queryParams != null && !queryParams.isEmpty()) {
List<NameValuePair> nvpList = new ArrayList<>(queryParams.size());
queryParams.forEach((key, values) -> {
values.forEach(value -> {
nvpList.add(new BasicNameValuePair(key, value));
});
});
uriBuilder.setParameters(nvpList);
}
return uriBuilder;
}
private URIBuilder getPersonSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/person/_search");
}
public final URIBuilder getPlaceUriBuilder() {
return getIndexUriBuilder().setPath("/search/place/_search");
}
public final URIBuilder getCorporationSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/corporation/_search");
}
public final URIBuilder getSerialSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/serial/_search");
}
public final URIBuilder getSubjectSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/subject/_search");
}
public final URIBuilder getGenreSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/genre/_search");
}
public final URIBuilder getPublicationSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/publication/_search");
}
public final URIBuilder getInstrumentSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/instrument/_search");
}
public final URIBuilder getCompositionTypeSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/compositionType/_search");
}
private URIBuilder getEventSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/event/_search");
}
}
| redef/services/src/main/java/no/deichman/services/search/SearchServiceImpl.java | package no.deichman.services.search;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jamonapi.Monitor;
import com.jamonapi.MonitorFactory;
import no.deichman.services.entity.EntityService;
import no.deichman.services.entity.EntityType;
import no.deichman.services.uridefaults.XURI;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.ResIterator;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.SimpleSelector;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.vocabulary.RDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.ServerErrorException;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import static com.google.common.collect.ImmutableMap.of;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newConcurrentHashSet;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.URLEncoder.encode;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
import static javax.ws.rs.core.HttpHeaders.CONTENT_LENGTH;
import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE;
import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
import static no.deichman.services.uridefaults.BaseURI.ontology;
import static org.apache.http.entity.ContentType.APPLICATION_JSON;
import static org.apache.http.impl.client.HttpClients.createDefault;
import static org.apache.jena.rdf.model.ResourceFactory.createProperty;
import static org.apache.jena.rdf.model.ResourceFactory.createResource;
/**
* Responsibility: perform indexing and searching.
*/
public class SearchServiceImpl implements SearchService {
public static final Property AGENT = createProperty(ontology("agent"));
private static final Logger LOG = LoggerFactory.getLogger(SearchServiceImpl.class);
private static final String UTF_8 = "UTF-8";
public static final int SIXTY_ONE = 61;
public static final String[] LOCAL_INDEX_SEARCH_FIELDS = {
ontology("name"),
ontology("prefLabel"),
ontology("mainTitle")
};
public static final Resource MAIN_ENTRY = createResource(ontology("MainEntry"));
public static final int SILENT_PERIOD = 100000;
private final EntityService entityService;
private final String elasticSearchBaseUrl;
private ModelToIndexMapper workModelToIndexMapper = new ModelToIndexMapper("work");
private ModelToIndexMapper eventModelToIndexMapper = new ModelToIndexMapper("event");
private ModelToIndexMapper serialModelToIndexMapper = new ModelToIndexMapper("serial");
private ModelToIndexMapper personModelToIndexMapper = new ModelToIndexMapper("person");
private ModelToIndexMapper corporationModelToIndexMapper = new ModelToIndexMapper("corporation");
private ModelToIndexMapper publicationModelToIndexMapper = new ModelToIndexMapper("publication");
public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
private int skipped;
private static Set<String> indexedUris;
private static long lastIndexedTime;
public SearchServiceImpl(String elasticSearchBaseUrl, EntityService entityService) {
this.elasticSearchBaseUrl = elasticSearchBaseUrl;
this.entityService = entityService;
getIndexUriBuilder();
}
@Override
public final void index(XURI xuri) throws Exception {
if (indexedUris == null || !indexedUris.contains(xuri.getUri())) {
switch (xuri.getTypeAsEntityType()) {
case WORK:
doIndexWork(xuri, false, false);
break;
case PERSON:
case CORPORATION:
doIndexWorkCreator(xuri, false);
break;
case PUBLICATION:
doIndexPublication(xuri);
break;
case EVENT:
doIndexEvent(xuri);
break;
case SERIAL:
doIndexSerial(xuri);
break;
default:
doIndex(xuri);
}
} else {
LOG.info("Skipping already indexed uri: " + xuri.getUri());
skipped++;
}
if (indexedUris != null) {
indexedUris.add(xuri.getUri());
}
}
public final void indexOnly(XURI xuri) throws Exception {
if (indexedUris == null || !indexedUris.contains(xuri.getUri())) {
switch (xuri.getTypeAsEntityType()) {
case WORK:
doIndexWork(xuri, true, true);
break;
case PERSON:
case CORPORATION:
doIndexWorkCreator(xuri, true);
break;
case PUBLICATION:
doIndexPublication(xuri);
break;
case EVENT:
doIndexEvent(xuri);
break;
case SERIAL:
doIndexSerial(xuri);
break;
default:
doIndex(xuri);
}
} else {
LOG.info("Skipping already indexed uri: " + xuri.getUri());
skipped++;
}
if (indexedUris != null) {
indexedUris.add(xuri.getUri());
}
}
private void doIndexEvent(XURI xuri) {
Model eventModelWithLinkedResources = entityService.retrieveEventWithLinkedResources(xuri);
indexDocument(xuri, eventModelToIndexMapper.createIndexDocument(eventModelWithLinkedResources, xuri));
cacheNameIndex(xuri, eventModelWithLinkedResources);
}
private void doIndexSerial(XURI xuri) {
Model serialModelWithLinkedResources = entityService.retrieveSerialWithLinkedResources(xuri);
indexDocument(xuri, serialModelToIndexMapper.createIndexDocument(serialModelWithLinkedResources, xuri));
cacheNameIndex(xuri, serialModelWithLinkedResources);
}
@Override
public final Response searchPersonWithJson(String json) {
return searchWithJson(json, getPersonSearchUriBuilder());
}
@Override
public final Response searchWorkWithJson(String json, MultivaluedMap<String, String> queryParams) {
return searchWithJson(json, getWorkSearchUriBuilder(queryParams));
}
@Override
public final Response searchPublicationWithJson(String json) {
return searchWithJson(json, getPublicationSearchUriBuilder());
}
@Override
public final Response searchInstrument(String query) {
return doSearch(query, getInstrumentSearchUriBuilder());
}
@Override
public final Response searchCompositionType(String query) {
return doSearch(query, getCompositionTypeSearchUriBuilder());
}
@Override
public final Response searchEvent(String query) {
return doSearch(query, getEventSearchUriBuilder());
}
@Override
public final Response clearIndex() {
try (CloseableHttpClient httpclient = createDefault()) {
URI uri = getIndexUriBuilder().setPath("/search").build();
try (CloseableHttpResponse getExistingIndex = httpclient.execute(new HttpGet(uri))) {
if (getExistingIndex.getStatusLine().getStatusCode() == HTTP_OK) {
try (CloseableHttpResponse delete = httpclient.execute(new HttpDelete(uri))) {
int statusCode = delete.getStatusLine().getStatusCode();
LOG.info("Delete index request returned status " + statusCode);
if (statusCode != HTTP_OK) {
throw new ServerErrorException("Failed to delete elasticsearch index", HTTP_INTERNAL_ERROR);
}
}
}
}
HttpPut createIndexRequest = new HttpPut(uri);
createIndexRequest.setEntity(new InputStreamEntity(getClass().getResourceAsStream("/search_index.json"), APPLICATION_JSON));
try (CloseableHttpResponse create = httpclient.execute(createIndexRequest)) {
int statusCode = create.getStatusLine().getStatusCode();
LOG.info("Create index request returned status " + statusCode);
if (statusCode != HTTP_OK) {
throw new ServerErrorException("Failed to create elasticsearch index", HTTP_INTERNAL_ERROR);
}
}
putIndexMapping(httpclient, "work");
putIndexMapping(httpclient, "person");
putIndexMapping(httpclient, "serial");
putIndexMapping(httpclient, "corporation");
putIndexMapping(httpclient, "place");
putIndexMapping(httpclient, "subject");
putIndexMapping(httpclient, "genre");
putIndexMapping(httpclient, "publication");
putIndexMapping(httpclient, "instrument");
putIndexMapping(httpclient, "compositionType");
putIndexMapping(httpclient, "event");
putIndexMapping(httpclient, "workSeries");
return Response.status(Response.Status.OK).build();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR);
}
}
private void putIndexMapping(CloseableHttpClient httpclient, String type) throws URISyntaxException, IOException {
URI workIndexUri = getIndexUriBuilder().setPath("/search/_mapping/" + type).build();
HttpPut putWorkMappingRequest = new HttpPut(workIndexUri);
putWorkMappingRequest.setEntity(new InputStreamEntity(getClass().getResourceAsStream("/" + type + "_mapping.json"), APPLICATION_JSON));
try (CloseableHttpResponse create = httpclient.execute(putWorkMappingRequest)) {
int statusCode = create.getStatusLine().getStatusCode();
LOG.info("Create mapping request for " + type + " returned status " + statusCode);
if (statusCode != HTTP_OK) {
throw new ServerErrorException("Failed to create elasticsearch mapping for " + type, HTTP_INTERNAL_ERROR);
}
}
}
private Response searchWithJson(String body, URIBuilder searchUriBuilder, Function<String, String>... jsonTranformer) {
try {
HttpPost httpPost = new HttpPost(searchUriBuilder.build());
httpPost.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
httpPost.setHeader(CONTENT_TYPE, "application/json");
Pair<String, Header[]> searchResult = executeHttpRequest(httpPost);
if (jsonTranformer != null && jsonTranformer.length > 0) {
String transformed = jsonTranformer[0].apply(searchResult.getLeft());
Header[] headers = searchResult.getRight();
searchResult = Pair.of(transformed, removeHeader(headers, CONTENT_LENGTH));
}
return createResponse(searchResult);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR);
}
}
private Header[] removeHeader(Header[] headers, String headerName) {
return stream(headers)
.filter(header -> !header
.getName()
.toLowerCase()
.equalsIgnoreCase(headerName))
.toArray(Header[]::new);
}
private Response createResponse(Pair<String, Header[]> searchResult) {
Response.ResponseBuilder responseBuilder = Response.ok(searchResult.getLeft());
for (Header header : searchResult.getRight()) {
responseBuilder = responseBuilder.header(header.getName(), header.getValue());
}
return responseBuilder.build();
}
private Pair<String, Header[]> executeHttpRequest(HttpRequestBase httpRequestBase) throws IOException {
try (CloseableHttpClient httpclient = createDefault();
CloseableHttpResponse response = httpclient.execute(httpRequestBase)) {
HttpEntity responseEntity = response.getEntity();
String jsonContent = IOUtils.toString(responseEntity.getContent());
Header[] headers = response.getAllHeaders();
return Pair.<String, Header[]>of(jsonContent, headers);
} catch (Exception e) {
throw e;
}
}
@Override
public final Response searchWork(String query) {
return doSearch(query, getWorkSearchUriBuilder(null));
}
@Override
public final Response searchPerson(String query) {
return doSearch(query, getPersonSearchUriBuilder());
}
@Override
public final Response searchPlace(String query) {
return doSearch(query, getPlaceUriBuilder());
}
@Override
public final Response searchCorporation(String query) {
return doSearch(query, getCorporationSearchUriBuilder());
}
@Override
public final Response searchSerial(String query) {
return doSearch(query, getSerialSearchUriBuilder());
}
@Override
public final Response searchSubject(String query) {
return doSearch(query, getSubjectSearchUriBuilder());
}
@Override
public final Response searchGenre(String query) {
return doSearch(query, getGenreSearchUriBuilder());
}
@Override
public final Response searchPublication(String query) {
return doSearch(query, getPublicationSearchUriBuilder());
}
@Override
public final void delete(XURI xuri) {
try (CloseableHttpClient httpclient = createDefault()) {
HttpDelete httpDelete = new HttpDelete(getIndexUriBuilder()
.setPath(format("/search/%s/%s", xuri.getType(), encode(xuri.getUri(), UTF_8)))
.build());
try (CloseableHttpResponse putResponse = httpclient.execute(httpDelete)) {
//LOG.debug(putResponse.getStatusLine().toString());
}
} catch (Exception e) {
LOG.error(format("Failed to delete %s in elasticsearch", xuri.getUri()), e);
throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR);
}
}
@Override
public final Response sortedList(String type, String prefix, int minSize, String field) {
EntityType entityType = EntityType.get(type);
URIBuilder searchUriBuilder = getIndexUriBuilder().setPath("/search/" + type + "/_search").setParameter("size", Integer.toString(minSize));
switch (entityType) {
case PERSON:
case CORPORATION:
case PLACE:
case SUBJECT:
case EVENT:
case WORK_SERIES:
case SERIAL:
case GENRE:
case MUSICAL_INSTRUMENT:
case MUSICAL_COMPOSITION_TYPE:
Collection<NameEntry> nameEntries = entityService.neighbourhoodOfName(entityType, prefix, minSize);
return searchWithJson(createPreIndexedSearchQuery(minSize, nameEntries),
searchUriBuilder, orderResultByIdOrder(nameEntries
.stream()
.map(NameEntry::getUri)
.collect(toList())));
default:
return searchWithJson(createSortedListQuery(prefix, minSize, field), searchUriBuilder);
}
}
private Function<String, String> orderResultByIdOrder(Collection<String> ids) {
Map<String, Integer> desiredOrder = new HashMap<>(ids.size());
final int[] i = new int[]{0};
ids.forEach(id -> desiredOrder.put(urlEncode(id), i[0]++));
return s -> {
Map fromJson = GSON.fromJson(s, Map.class);
((List) ((Map) fromJson.get("hits")).get("hits")).sort((o1, o2) -> {
String id1 = (String) ((Map) o1).get("_id");
String id2 = (String) ((Map) o2).get("_id");
return desiredOrder.get(id1).compareTo(desiredOrder.get(id2));
});
return GSON.toJson(fromJson);
};
}
private String createSortedListQuery(String prefix, int minSize, String field) {
String sortedListQuery;
List<Map> should = new ArrayList<>();
for (int i = 0; i < prefix.length(); i++) {
should.add(
of("constant_score",
of("boost", 2 << Math.max(prefix.length() - i, SIXTY_ONE), "query",
of("match_phrase_prefix", of(field, prefix.substring(0, prefix.length() - i))))));
}
sortedListQuery = GSON.toJson(of(
"size", minSize,
"query", of(
"bool", of(
"should", should)
)
));
return sortedListQuery;
}
private String createPreIndexedSearchQuery(int minSize, Collection<NameEntry> nameEntries) {
List<Map> should = new ArrayList<>();
should.addAll(nameEntries
.stream()
.filter(NameEntry::isBestMatch)
.map(e -> of(
"ids", of("values", newArrayList(urlEncode(e.getUri())))))
.collect(toList()));
should.add(of(
"ids", of("values",
nameEntries
.stream()
.map(NameEntry::getUri)
.map(SearchServiceImpl::urlEncode)
.collect(toList())
)
));
return GSON.toJson(
of(
"size", minSize,
"query", of(
"bool", of("should", should)
)
)
);
}
private static String urlEncode(String uri) {
return uri.replace(":", "%3A").replace("/", "%2F");
}
@Override
public final Response searchWorkWhereUriIsSubject(String subjectUri, int maxSize) {
String body = GSON.toJson(of(
"size", maxSize,
"query", of(
"nested", of(
"path", "subjects",
"query", of("term", of(
"subjects.uri", subjectUri)
)
)
)
));
return searchWithJson(body, getIndexUriBuilder().setPath("/search/work/_search"));
}
@Override
public final Response searchWorkSeries(String query) {
return doSearch(query, getWorkSeriesSearchUriBuilder());
}
@Override
public final void indexUrisOnlyOnce(boolean indexOnce) {
if (indexOnce) {
LOG.info("Turning on only once uri indexing");
indexedUris = newConcurrentHashSet();
skipped = 0;
} else {
LOG.info("Turning off only once uri indexing after skipping " + skipped + " uris");
indexedUris = null;
lastIndexedTime = 0;
}
}
private URIBuilder getWorkSeriesSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/workSeries/_search");
}
private void doIndexPublication(XURI pubUri) throws Exception {
Model pubModel = entityService.retrieveById(pubUri);
Property publicationOfProperty = createProperty(ontology("publicationOf"));
if (pubModel.getProperty(null, publicationOfProperty) != null) {
String workUri = pubModel.getProperty(createResource(pubUri.toString()), publicationOfProperty).getObject().toString();
XURI workXURI = new XURI(workUri);
pubModel = entityService.retrieveWorkWithLinkedResources(workXURI);
}
indexDocument(pubUri, publicationModelToIndexMapper.createIndexDocument(pubModel, pubUri));
}
private void doIndexWork(XURI xuri, boolean indexedPerson, boolean indexedPublication) throws Exception {
Monitor mon = MonitorFactory.start("doIndexWork1");
Model workModelWithLinkedResources = entityService.retrieveWorkWithLinkedResources(xuri);
indexDocument(xuri, workModelToIndexMapper.createIndexDocument(workModelWithLinkedResources, xuri));
mon.stop();
mon = MonitorFactory.start("doIndexWork2");
if (!indexedPerson) {
workModelWithLinkedResources.listStatements(isMainContributorOfWork(xuri, workModelWithLinkedResources))
.forEachRemaining(stmt -> {
try {
XURI creatorXuri = new XURI(stmt.getObject().asNode().getURI());
doIndexWorkCreatorOnly(creatorXuri);
} catch (Exception e) {
e.printStackTrace();
}
});
}
mon.stop();
if (indexedPublication) {
return;
}
// Index all publications belonging to work
// TODO instead of iterating over all subjects, find only subjects of triples with publicationOf as predicate
mon = MonitorFactory.start("doIndexWork3");
ResIterator subjectIterator = workModelWithLinkedResources.listSubjects();
while (subjectIterator.hasNext()) {
Resource subj = subjectIterator.next();
if (subj.isAnon()) {
continue;
}
if (subj.toString().contains("publication")) {
XURI pubUri = new XURI(subj.toString());
indexDocument(pubUri, publicationModelToIndexMapper.createIndexDocument(workModelWithLinkedResources, pubUri));
}
}
mon.stop();
}
private SimpleSelector isMainContributorOfWork(final XURI xuri, final Model workModelWithLinkedResources) {
return new SimpleSelector() {
@Override
public boolean test(Statement s) {
return (s.getPredicate().equals(AGENT)
&& workModelWithLinkedResources.contains(s.getSubject(), RDF.type, MAIN_ENTRY)
&& workModelWithLinkedResources.contains(
createResource(xuri.getUri()),
createProperty(ontology("contributor")),
s.getSubject())
);
}
};
}
private void doIndexWorkCreator(XURI creatorUri, boolean indexedWork) throws Exception {
Monitor mon = MonitorFactory.start("doIndexWorkCreator");
Model works = entityService.retrieveWorksByCreator(creatorUri);
if (!indexedWork) {
ResIterator subjectIterator = works.listSubjects();
while (subjectIterator.hasNext()) {
Resource subj = subjectIterator.next();
if (subj.isAnon() || subj.toString().indexOf('#') != -1) {
continue;
}
XURI workUri = new XURI(subj.toString());
if (!workUri.getUri().equals(creatorUri.getUri())) {
doIndexWorkOnly(workUri);
}
}
}
switch (creatorUri.getTypeAsEntityType()) {
case PERSON:
indexDocument(creatorUri, personModelToIndexMapper
.createIndexDocument(entityService.retrievePersonWithLinkedResources(creatorUri).add(works), creatorUri));
cacheNameIndex(creatorUri, works);
break;
case CORPORATION:
indexDocument(creatorUri, corporationModelToIndexMapper
.createIndexDocument(entityService.retrieveCorporationWithLinkedResources(creatorUri).add(works), creatorUri));
cacheNameIndex(creatorUri, works);
break;
default:
throw new RuntimeException(format(
"Tried to index work creator of type %1$s. Should be %2$s or %3$s",
creatorUri.getTypeAsEntityType(), EntityType.PERSON, EntityType.CORPORATION
));
}
mon.stop();
}
private void doIndex(XURI xuri) throws Exception {
Model indexModel = entityService.retrieveById(xuri);
Monitor mon = MonitorFactory.start("createIndexDocument");
String indexDocument = new ModelToIndexMapper(xuri.getTypeAsEntityType().getPath()).createIndexDocument(indexModel, xuri);
mon.stop();
indexDocument(xuri, indexDocument);
cacheNameIndex(xuri, indexModel);
}
private void cacheNameIndex(XURI xuri, Model indexModel) {
entityService.statementsInModelAbout(xuri, indexModel, LOCAL_INDEX_SEARCH_FIELDS)
.forEachRemaining(statement -> {
entityService.addIndexedName(
xuri.getTypeAsEntityType(),
statement.getObject().asLiteral().toString(),
statement.getSubject().getURI());
});
}
private void doIndexWorkOnly(XURI xuri) throws Exception {
doIndexWork(xuri, true, false);
}
private void indexDocument(XURI xuri, String document) {
long now = currentTimeMillis();
if (indexedUris != null && lastIndexedTime > 0 && now - lastIndexedTime > SILENT_PERIOD) {
indexUrisOnlyOnce(false);
}
if (indexedUris == null || !indexedUris.contains(xuri.getUri())) {
try (CloseableHttpClient httpclient = createDefault()) {
HttpPut httpPut = new HttpPut(getIndexUriBuilder()
.setPath(format("/search/%s/%s", xuri.getType(), encode(xuri.getUri(), UTF_8))) // TODO drop urlencoded ID, and define _id in mapping from field uri
.build());
httpPut.setEntity(new StringEntity(document, Charset.forName(UTF_8)));
httpPut.setHeader(CONTENT_TYPE, APPLICATION_JSON.withCharset(UTF_8).toString());
Monitor mon = MonitorFactory.start("indexDocument");
try (CloseableHttpResponse putResponse = httpclient.execute(httpPut)) {
//LOG.debug(putResponse.getStatusLine().toString());
} finally {
mon.stop();
}
lastIndexedTime = now;
} catch (Exception e) {
LOG.error(format("Failed to index %s in elasticsearch", xuri.getUri()), e);
throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR);
}
} else {
LOG.info("Skipping already indexed uri: " + xuri.getUri());
skipped++;
}
if (indexedUris != null) {
indexedUris.add(xuri.getUri());
}
}
private Response doSearch(String query, URIBuilder searchUriBuilder) {
try {
HttpGet httpGet = new HttpGet(searchUriBuilder
.setParameter("q", query)
.setParameter("size", "100")
.build());
return createResponse(executeHttpRequest(httpGet));
} catch (Exception e) {
LOG.error(e.getMessage(), e);
throw new ServerErrorException(e.getMessage(), INTERNAL_SERVER_ERROR);
}
}
private void doIndexWorkCreatorOnly(XURI xuri) throws Exception {
doIndexWorkCreator(xuri, true);
}
private URIBuilder getIndexUriBuilder() {
try {
return new URIBuilder(this.elasticSearchBaseUrl);
} catch (URISyntaxException e) {
LOG.error("Failed to create uri builder for elasticsearch");
throw new RuntimeException(e);
}
}
private URIBuilder getWorkSearchUriBuilder(MultivaluedMap<String, String> queryParams) {
URIBuilder uriBuilder = getIndexUriBuilder().setPath("/search/work/_search");
if (queryParams != null && !queryParams.isEmpty()) {
List<NameValuePair> nvpList = new ArrayList<>(queryParams.size());
queryParams.forEach((key, values) -> {
values.forEach(value -> {
nvpList.add(new BasicNameValuePair(key, value));
});
});
uriBuilder.setParameters(nvpList);
}
return uriBuilder;
}
private URIBuilder getPersonSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/person/_search");
}
public final URIBuilder getPlaceUriBuilder() {
return getIndexUriBuilder().setPath("/search/place/_search");
}
public final URIBuilder getCorporationSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/corporation/_search");
}
public final URIBuilder getSerialSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/serial/_search");
}
public final URIBuilder getSubjectSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/subject/_search");
}
public final URIBuilder getGenreSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/genre/_search");
}
public final URIBuilder getPublicationSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/publication/_search");
}
public final URIBuilder getInstrumentSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/instrument/_search");
}
public final URIBuilder getCompositionTypeSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/compositionType/_search");
}
private URIBuilder getEventSearchUriBuilder() {
return getIndexUriBuilder().setPath("/search/event/_search");
}
}
| services: improve comments
| redef/services/src/main/java/no/deichman/services/search/SearchServiceImpl.java | services: improve comments | <ide><path>edef/services/src/main/java/no/deichman/services/search/SearchServiceImpl.java
<ide> .setPath(format("/search/%s/%s", xuri.getType(), encode(xuri.getUri(), UTF_8)))
<ide> .build());
<ide> try (CloseableHttpResponse putResponse = httpclient.execute(httpDelete)) {
<del> //LOG.debug(putResponse.getStatusLine().toString());
<add> // no-op
<ide> }
<ide> } catch (Exception e) {
<ide> LOG.error(format("Failed to delete %s in elasticsearch", xuri.getUri()), e);
<ide> httpPut.setHeader(CONTENT_TYPE, APPLICATION_JSON.withCharset(UTF_8).toString());
<ide> Monitor mon = MonitorFactory.start("indexDocument");
<ide> try (CloseableHttpResponse putResponse = httpclient.execute(httpPut)) {
<del> //LOG.debug(putResponse.getStatusLine().toString());
<add> // no-op
<ide> } finally {
<ide> mon.stop();
<ide> } |
|
Java | apache-2.0 | 2f26ff4206cadfb92b74c85ea9f8368b7f5ef427 | 0 | amsa-code/risky,amsa-code/risky,amsa-code/risky,amsa-code/risky,amsa-code/risky | package au.gov.amsa.animator;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.wms.WebMapServer;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.map.WMSLayer;
import org.geotools.ows.ServiceException;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.renderer.lite.StreamingRenderer;
import org.geotools.styling.SLD;
import org.geotools.styling.Style;
import org.geotools.swing.JMapPane;
import org.geotools.swing.RenderingExecutorEvent;
import org.geotools.swing.RenderingExecutorListener;
import org.geotools.swing.event.MapMouseAdapter;
import org.geotools.swing.event.MapMouseEvent;
import org.geotools.swing.wms.WMSLayerChooser;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import rx.Observable;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
public class Animator {
private static final float CANBERRA_LAT = -35.3075f;
private static final float CANBERRA_LONG = 149.1244f;
private final Model model = new Model();
private final View view = new View();
private volatile int width, height = 0;
private volatile Image offScreenImage;
private volatile JMapPane mapPane;
private volatile BufferedImage backgroundImage;
public void start() {
// Create a map context and add our shapefile to it
final MapContent map = createMap();
// Now display the map using the custom renderer
// display(map);
// System.exit(0);
width = 800;
height = 600;
Rectangle imageBounds = new Rectangle(0, 0, width, height);
BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D gr = image.createGraphics();
gr.setPaint(Color.WHITE);
gr.fill(imageBounds);
StreamingRenderer renderer = new StreamingRenderer();
renderer.setMapContent(map);
ReferencedEnvelope mapBounds = map.getMaxBounds();
renderer.paint(gr, imageBounds, mapBounds);
backgroundImage = image;
JFrame frame = new JFrame();
final JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage, 0, 0, null);
}
};
panel.setPreferredSize(new Dimension(width, height));
frame.add(panel);
frame.setSize(width, height);
frame.setVisible(true);
// // animate
// offScreenImage = createImage(width, height);
// long timeStep = 0;
// long frameMs = 50;
// while (true) {
// long t = System.currentTimeMillis();
// // mapPane.repaint();
// model.updateModel(timeStep);
// view.draw(model, offScreenImage);
// timeStep++;
// sleep(Math.max(0, t + frameMs - System.currentTimeMillis()));
// }
}
private RenderingExecutorListener createListener(CountDownLatch latch) {
return new RenderingExecutorListener() {
@Override
public void onRenderingStarted(RenderingExecutorEvent ev) {
}
@Override
public void onRenderingFailed(RenderingExecutorEvent ev) {
}
@Override
public void onRenderingCompleted(RenderingExecutorEvent ev) {
latch.countDown();
}
};
}
private static BufferedImage createImage(int width, int height) {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration()
.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
}
private static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private MapContent createMap() {
final MapContent map = new MapContent();
map.setTitle("Animator");
map.getViewport();
map.addLayer(createCoastlineLayer());
map.addLayer(createExtraFeatures());
// addWms(map);
return map;
}
private void display(final MapContent map) {
EventQueue.invokeLater(() -> {
// setup custom rendering over the top of the map
BackgroundRenderer renderer = new BackgroundRenderer();
mapPane = new JMapPane(map) {
int n = 0;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (renderer.worldToScreen() != null) {
Graphics2D g2 = (Graphics2D) g;
n++;
Point2D.Float p = new Point2D.Float(CANBERRA_LONG, CANBERRA_LAT);
Point2D.Float q = new Point2D.Float();
renderer.worldToScreen().transform(p, q);
g2.drawString("Hello", q.x + n % 100, q.y + n % 100);
}
}
};
final JMapFrame frame = new JMapFrame(map, mapPane);
frame.getMapPane().setRenderer(renderer);
frame.enableStatusBar(true);
frame.enableToolBar(true);
frame.initComponents();
frame.setSize(800, 600);
FramePreferences.restoreLocationAndSize(frame, 100, 100, 800, 600, Animator.class);
frame.getMapPane().addMouseListener(new MapMouseAdapter() {
@Override
public void onMouseClicked(MapMouseEvent event) {
DirectPosition2D p = event.getWorldPos();
System.out.println(p);
}
});
frame.setVisible(true);
Observable.interval(20, TimeUnit.MILLISECONDS).forEach(n -> {
frame.getMapPane().repaint();
});
});
}
private Layer createCoastlineLayer() {
try {
// File file = new File(
// "/home/dxm/Downloads/shapefile-australia-coastline-polygon/cstauscd_r.shp");
File file = new File("src/main/resources/shapes/countries.shp");
FileDataStore store = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource featureSource = store.getFeatureSource();
Style style = SLD.createSimpleStyle(featureSource.getSchema());
Layer layer = new FeatureLayer(featureSource, style);
return layer;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static Layer createExtraFeatures() {
SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
b.setName("Location");
b.setCRS(DefaultGeographicCRS.WGS84);
// picture location
b.add("geom", Point.class);
final SimpleFeatureType TYPE = b.buildFeatureType();
GeometryFactory gf = JTSFactoryFinder.getGeometryFactory();
Point point = gf.createPoint(new Coordinate(CANBERRA_LONG, CANBERRA_LAT));
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(TYPE);
builder.add(point);
SimpleFeature feature = builder.buildFeature("Canberra");
DefaultFeatureCollection features = new DefaultFeatureCollection(null, null);
features.add(feature);
Style style = SLD.createPointStyle("Star", Color.BLUE, Color.BLUE, 0.3f, 10);
return new FeatureLayer(features, style);
}
static void addWms(MapContent map) {
// URL wmsUrl = WMSChooser.showChooseWMS();
WebMapServer wms;
try {
String url = "http://129.206.228.72/cached/osm?Request=GetCapabilities";
// String url = "http://sarapps.amsa.gov.au:8080/cts-gis/wms";
wms = new WebMapServer(new URL(url));
} catch (ServiceException | IOException e) {
throw new RuntimeException(e);
}
List<org.geotools.data.ows.Layer> wmsLayers = WMSLayerChooser.showSelectLayer(wms);
for (org.geotools.data.ows.Layer wmsLayer : wmsLayers) {
System.out.println("adding " + wmsLayer.getTitle());
WMSLayer displayLayer = new WMSLayer(wms, wmsLayer);
map.addLayer(displayLayer);
}
}
public static void main(String[] args) throws Exception {
System.setProperty("http.proxyHost", "proxy.amsa.gov.au");
System.setProperty("http.proxyPort", "8080");
System.setProperty("https.proxyHost", "proxy.amsa.gov.au");
System.setProperty("https.proxyPort", "8080");
new Animator().start();
}
} | animator/src/main/java/au/gov/amsa/animator/Animator.java | package au.gov.amsa.animator;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.wms.WebMapServer;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.map.WMSLayer;
import org.geotools.ows.ServiceException;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.renderer.lite.StreamingRenderer;
import org.geotools.styling.SLD;
import org.geotools.styling.Style;
import org.geotools.swing.DefaultRenderingExecutor;
import org.geotools.swing.JMapPane;
import org.geotools.swing.RenderingExecutorEvent;
import org.geotools.swing.RenderingExecutorListener;
import org.geotools.swing.event.MapMouseAdapter;
import org.geotools.swing.event.MapMouseEvent;
import org.geotools.swing.wms.WMSLayerChooser;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import rx.Observable;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
public class Animator {
private static final float CANBERRA_LAT = -35.3075f;
private static final float CANBERRA_LONG = 149.1244f;
private final Model model = new Model();
private final View view = new View();
private volatile int width, height = 0;
private volatile Image offScreenImage;
private volatile JMapPane mapPane;
private volatile BufferedImage backgroundImage;
public void start() {
// Create a map context and add our shapefile to it
final MapContent map = createMap();
// Now display the map using the custom renderer
// display(map);
// System.exit(0);
width = 800;
height = 600;
JMapPane mp = new JMapPane(map);
mp.setSize(width, height);
CountDownLatch latch = new CountDownLatch(1);
backgroundImage = createImage(width, height);
backgroundImage.createGraphics();
// init viewport
DefaultRenderingExecutor renderingExecutor = new DefaultRenderingExecutor();
StreamingRenderer renderer = new StreamingRenderer();
renderingExecutor.submit(map, renderer, (Graphics2D) backgroundImage.getGraphics(),
createListener(latch));
try {
if (latch.await(10, TimeUnit.SECONDS))
throw new RuntimeException();
} catch (InterruptedException e) {
throw new RuntimeException();
}
JFrame frame = new JFrame();
final JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage, 0, 0, null);
}
};
frame.add(panel);
frame.setSize(width, height);
frame.setVisible(true);
// animate
offScreenImage = createImage(width, height);
long timeStep = 0;
long frameMs = 50;
while (true) {
long t = System.currentTimeMillis();
// mapPane.repaint();
model.updateModel(timeStep);
view.draw(model, offScreenImage);
timeStep++;
sleep(Math.max(0, t + frameMs - System.currentTimeMillis()));
}
}
private RenderingExecutorListener createListener(CountDownLatch latch) {
return new RenderingExecutorListener() {
@Override
public void onRenderingStarted(RenderingExecutorEvent ev) {
}
@Override
public void onRenderingFailed(RenderingExecutorEvent ev) {
}
@Override
public void onRenderingCompleted(RenderingExecutorEvent ev) {
latch.countDown();
}
};
}
private static BufferedImage createImage(int width, int height) {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration()
.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
}
private static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private MapContent createMap() {
final MapContent map = new MapContent();
map.setTitle("Animator");
map.getViewport();
map.addLayer(createCoastlineLayer());
map.addLayer(createExtraFeatures());
// addWms(map);
return map;
}
private void display(final MapContent map) {
EventQueue.invokeLater(() -> {
// setup custom rendering over the top of the map
BackgroundRenderer renderer = new BackgroundRenderer();
mapPane = new JMapPane(map) {
int n = 0;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (renderer.worldToScreen() != null) {
Graphics2D g2 = (Graphics2D) g;
n++;
Point2D.Float p = new Point2D.Float(CANBERRA_LONG, CANBERRA_LAT);
Point2D.Float q = new Point2D.Float();
renderer.worldToScreen().transform(p, q);
g2.drawString("Hello", q.x + n % 100, q.y + n % 100);
}
}
};
final JMapFrame frame = new JMapFrame(map, mapPane);
frame.getMapPane().setRenderer(renderer);
frame.enableStatusBar(true);
frame.enableToolBar(true);
frame.initComponents();
frame.setSize(800, 600);
FramePreferences.restoreLocationAndSize(frame, 100, 100, 800, 600, Animator.class);
frame.getMapPane().addMouseListener(new MapMouseAdapter() {
@Override
public void onMouseClicked(MapMouseEvent event) {
DirectPosition2D p = event.getWorldPos();
System.out.println(p);
}
});
frame.setVisible(true);
Observable.interval(20, TimeUnit.MILLISECONDS).forEach(n -> {
frame.getMapPane().repaint();
});
});
}
private Layer createCoastlineLayer() {
try {
// File file = new File(
// "/home/dxm/Downloads/shapefile-australia-coastline-polygon/cstauscd_r.shp");
File file = new File("src/main/resources/shapes/countries.shp");
FileDataStore store = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource featureSource = store.getFeatureSource();
Style style = SLD.createSimpleStyle(featureSource.getSchema());
Layer layer = new FeatureLayer(featureSource, style);
return layer;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static Layer createExtraFeatures() {
SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
b.setName("Location");
b.setCRS(DefaultGeographicCRS.WGS84);
// picture location
b.add("geom", Point.class);
final SimpleFeatureType TYPE = b.buildFeatureType();
GeometryFactory gf = JTSFactoryFinder.getGeometryFactory();
Point point = gf.createPoint(new Coordinate(CANBERRA_LONG, CANBERRA_LAT));
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(TYPE);
builder.add(point);
SimpleFeature feature = builder.buildFeature("Canberra");
DefaultFeatureCollection features = new DefaultFeatureCollection(null, null);
features.add(feature);
Style style = SLD.createPointStyle("Star", Color.BLUE, Color.BLUE, 0.3f, 10);
return new FeatureLayer(features, style);
}
static void addWms(MapContent map) {
// URL wmsUrl = WMSChooser.showChooseWMS();
WebMapServer wms;
try {
String url = "http://129.206.228.72/cached/osm?Request=GetCapabilities";
// String url = "http://sarapps.amsa.gov.au:8080/cts-gis/wms";
wms = new WebMapServer(new URL(url));
} catch (ServiceException | IOException e) {
throw new RuntimeException(e);
}
List<org.geotools.data.ows.Layer> wmsLayers = WMSLayerChooser.showSelectLayer(wms);
for (org.geotools.data.ows.Layer wmsLayer : wmsLayers) {
System.out.println("adding " + wmsLayer.getTitle());
WMSLayer displayLayer = new WMSLayer(wms, wmsLayer);
map.addLayer(displayLayer);
}
}
public static void main(String[] args) throws Exception {
System.setProperty("http.proxyHost", "proxy.amsa.gov.au");
System.setProperty("http.proxyPort", "8080");
System.setProperty("https.proxyHost", "proxy.amsa.gov.au");
System.setProperty("https.proxyPort", "8080");
new Animator().start();
}
} | animator dev
| animator/src/main/java/au/gov/amsa/animator/Animator.java | animator dev | <ide><path>nimator/src/main/java/au/gov/amsa/animator/Animator.java
<ide> package au.gov.amsa.animator;
<ide>
<ide> import java.awt.Color;
<add>import java.awt.Dimension;
<ide> import java.awt.EventQueue;
<ide> import java.awt.Graphics;
<ide> import java.awt.Graphics2D;
<ide> import java.awt.GraphicsEnvironment;
<ide> import java.awt.Image;
<add>import java.awt.Rectangle;
<ide> import java.awt.Transparency;
<ide> import java.awt.geom.Point2D;
<ide> import java.awt.image.BufferedImage;
<ide> import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
<ide> import org.geotools.geometry.DirectPosition2D;
<ide> import org.geotools.geometry.jts.JTSFactoryFinder;
<add>import org.geotools.geometry.jts.ReferencedEnvelope;
<ide> import org.geotools.map.FeatureLayer;
<ide> import org.geotools.map.Layer;
<ide> import org.geotools.map.MapContent;
<ide> import org.geotools.renderer.lite.StreamingRenderer;
<ide> import org.geotools.styling.SLD;
<ide> import org.geotools.styling.Style;
<del>import org.geotools.swing.DefaultRenderingExecutor;
<ide> import org.geotools.swing.JMapPane;
<ide> import org.geotools.swing.RenderingExecutorEvent;
<ide> import org.geotools.swing.RenderingExecutorListener;
<ide> // System.exit(0);
<ide> width = 800;
<ide> height = 600;
<del> JMapPane mp = new JMapPane(map);
<del> mp.setSize(width, height);
<del> CountDownLatch latch = new CountDownLatch(1);
<del> backgroundImage = createImage(width, height);
<del> backgroundImage.createGraphics();
<del> // init viewport
<del> DefaultRenderingExecutor renderingExecutor = new DefaultRenderingExecutor();
<add>
<add> Rectangle imageBounds = new Rectangle(0, 0, width, height);
<add> BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height,
<add> BufferedImage.TYPE_INT_RGB);
<add> Graphics2D gr = image.createGraphics();
<add> gr.setPaint(Color.WHITE);
<add> gr.fill(imageBounds);
<ide> StreamingRenderer renderer = new StreamingRenderer();
<del> renderingExecutor.submit(map, renderer, (Graphics2D) backgroundImage.getGraphics(),
<del> createListener(latch));
<del> try {
<del> if (latch.await(10, TimeUnit.SECONDS))
<del> throw new RuntimeException();
<del> } catch (InterruptedException e) {
<del> throw new RuntimeException();
<del> }
<add> renderer.setMapContent(map);
<add> ReferencedEnvelope mapBounds = map.getMaxBounds();
<add> renderer.paint(gr, imageBounds, mapBounds);
<add> backgroundImage = image;
<ide> JFrame frame = new JFrame();
<ide> final JPanel panel = new JPanel() {
<ide> @Override
<ide> g.drawImage(backgroundImage, 0, 0, null);
<ide> }
<ide> };
<add> panel.setPreferredSize(new Dimension(width, height));
<ide> frame.add(panel);
<ide> frame.setSize(width, height);
<ide> frame.setVisible(true);
<ide>
<del> // animate
<del> offScreenImage = createImage(width, height);
<del> long timeStep = 0;
<del> long frameMs = 50;
<del> while (true) {
<del> long t = System.currentTimeMillis();
<del> // mapPane.repaint();
<del> model.updateModel(timeStep);
<del> view.draw(model, offScreenImage);
<del> timeStep++;
<del> sleep(Math.max(0, t + frameMs - System.currentTimeMillis()));
<del> }
<add> // // animate
<add> // offScreenImage = createImage(width, height);
<add> // long timeStep = 0;
<add> // long frameMs = 50;
<add> // while (true) {
<add> // long t = System.currentTimeMillis();
<add> // // mapPane.repaint();
<add> // model.updateModel(timeStep);
<add> // view.draw(model, offScreenImage);
<add> // timeStep++;
<add> // sleep(Math.max(0, t + frameMs - System.currentTimeMillis()));
<add> // }
<ide> }
<ide>
<ide> private RenderingExecutorListener createListener(CountDownLatch latch) { |
|
Java | apache-2.0 | 51b3ef2c856aa6850d0be621fb5235b61b942fa3 | 0 | KurtStam/syndesis-rest,redhat-ipaas/ipaas-rest,chirino/ipaas-rest,redhat-ipaas/ipaas-rest,KurtStam/syndesis-rest,rhuss/ipaas-rest,KurtStam/ipaas-rest,rhuss/ipaas-rest,rhuss/ipaas-rest,redhat-ipaas/ipaas-rest,KurtStam/ipaas-rest,redhat-ipaas/ipaas-api-java,KurtStam/ipaas-rest,redhat-ipaas/ipaas-api-java,chirino/ipaas-rest,KurtStam/syndesis-rest,chirino/ipaas-rest | /**
* Copyright (C) 2016 Red Hat, 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 io.syndesis.runtime;
import org.junit.rules.ExternalResource;
public class APITokenRule extends ExternalResource {
private static final String EXPIRED_TOKEN = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJGSjg2R2NGM2pUYk5MT2NvNE52WmtVQ0lVbWZZQ3FvcXRPUWVNZmJoTmxFIn0.eyJqdGkiOiIzNTg2M2I4Ny1mMjQ2LTQ3NzItYTMyNy00Yzc3NzY5NjVjNDkiLCJleHAiOjE0ODYzMzQ1MDAsIm5iZiI6MCwiaWF0IjoxNDg2MzM0MjAwLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvaXBhYXMtdGVzdCIsImF1ZCI6ImFkbWluLWNsaSIsInN1YiI6IjliZWRhNjUyLWY0NDYtNGFhZS1iODQ1LWQ1M2VjNDc1OGQ3OCIsInR5cCI6IkJlYXJlciIsImF6cCI6ImFkbWluLWNsaSIsImF1dGhfdGltZSI6MCwic2Vzc2lvbl9zdGF0ZSI6IjU3MzcyMmQ5LTc2NzAtNDhhZi1iMDY4LWUxNGNmNjRjM2U2NCIsImFjciI6IjEiLCJjbGllbnRfc2Vzc2lvbiI6IjAyY2M5ZTVkLTU3NWUtNDEzNi05NDk5LWI5OGY4ZjhjYmFhYiIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlc291cmNlX2FjY2VzcyI6e30sIm5hbWUiOiJTYW1wbGUgVXNlciIsInByZWZlcnJlZF91c2VybmFtZSI6InVzZXIiLCJnaXZlbl9uYW1lIjoiU2FtcGxlIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwiZW1haWwiOiJzYW1wbGUtdXNlckBleGFtcGxlIn0.H2edv1-kUIYd7_nStjR-70hmdy7H6QG3sgjPhJGHhqMM6SMkjBjCHO0BHSkPFiG05fD6ah6kQAsxHIV-Bfd7k0rCoWrF3WH2mwtJDje36WLpGtFXbPNBUv0YFO5F61tkdCUL-gBJS-3VPWD68nskpAZcgabFGhM9TBxbC0geJzA";
private static final String ACCESS_TOKEN = "sometoken";
public APITokenRule() {
}
public String validToken() {
return ACCESS_TOKEN;
}
public String expiredToken() {
return EXPIRED_TOKEN;
}
}
| runtime/src/test/java/io/syndesis/runtime/APITokenRule.java | /**
* Copyright (C) 2016 Red Hat, 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 io.syndesis.runtime;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.rules.ExternalResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
public class APITokenRule extends ExternalResource {
private static final String EXPIRED_TOKEN = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJGSjg2R2NGM2pUYk5MT2NvNE52WmtVQ0lVbWZZQ3FvcXRPUWVNZmJoTmxFIn0.eyJqdGkiOiIzNTg2M2I4Ny1mMjQ2LTQ3NzItYTMyNy00Yzc3NzY5NjVjNDkiLCJleHAiOjE0ODYzMzQ1MDAsIm5iZiI6MCwiaWF0IjoxNDg2MzM0MjAwLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvaXBhYXMtdGVzdCIsImF1ZCI6ImFkbWluLWNsaSIsInN1YiI6IjliZWRhNjUyLWY0NDYtNGFhZS1iODQ1LWQ1M2VjNDc1OGQ3OCIsInR5cCI6IkJlYXJlciIsImF6cCI6ImFkbWluLWNsaSIsImF1dGhfdGltZSI6MCwic2Vzc2lvbl9zdGF0ZSI6IjU3MzcyMmQ5LTc2NzAtNDhhZi1iMDY4LWUxNGNmNjRjM2U2NCIsImFjciI6IjEiLCJjbGllbnRfc2Vzc2lvbiI6IjAyY2M5ZTVkLTU3NWUtNDEzNi05NDk5LWI5OGY4ZjhjYmFhYiIsImFsbG93ZWQtb3JpZ2lucyI6W10sInJlc291cmNlX2FjY2VzcyI6e30sIm5hbWUiOiJTYW1wbGUgVXNlciIsInByZWZlcnJlZF91c2VybmFtZSI6InVzZXIiLCJnaXZlbl9uYW1lIjoiU2FtcGxlIiwiZmFtaWx5X25hbWUiOiJVc2VyIiwiZW1haWwiOiJzYW1wbGUtdXNlckBleGFtcGxlIn0.H2edv1-kUIYd7_nStjR-70hmdy7H6QG3sgjPhJGHhqMM6SMkjBjCHO0BHSkPFiG05fD6ah6kQAsxHIV-Bfd7k0rCoWrF3WH2mwtJDje36WLpGtFXbPNBUv0YFO5F61tkdCUL-gBJS-3VPWD68nskpAZcgabFGhM9TBxbC0geJzA";
private static final String ACCESS_TOKEN = "sometoken";
public APITokenRule() {
}
public String validToken() {
return ACCESS_TOKEN;
}
public String expiredToken() {
return EXPIRED_TOKEN;
}
}
| refactor(code style): remove unused imports
| runtime/src/test/java/io/syndesis/runtime/APITokenRule.java | refactor(code style): remove unused imports | <ide><path>untime/src/test/java/io/syndesis/runtime/APITokenRule.java
<ide> */
<ide> package io.syndesis.runtime;
<ide>
<del>import com.fasterxml.jackson.databind.JsonNode;
<ide> import org.junit.rules.ExternalResource;
<del>import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.HttpStatus;
<del>import org.springframework.http.ResponseEntity;
<del>import org.springframework.util.LinkedMultiValueMap;
<del>import org.springframework.util.MultiValueMap;
<del>import org.springframework.web.client.RestTemplate;
<del>
<del>import static org.assertj.core.api.Assertions.assertThat;
<ide>
<ide> public class APITokenRule extends ExternalResource {
<ide> |
|
Java | apache-2.0 | ae07fc170d8ebadb7a135f7ef2c6183c678f4cf3 | 0 | universsky/mina,weijiangzhu/mina,dongjiaqiang/mina,Vicky01200059/mina,jeffmaury/mina,apache/mina,mway08/mina,yangzhongj/mina,apache/mina,universsky/mina,mway08/mina,dongjiaqiang/mina,Vicky01200059/mina,weijiangzhu/mina,yangzhongj/mina | /*
* 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.mina.transport.socket.apr;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import org.apache.mina.common.AbstractIoProcessor;
import org.apache.mina.common.FileRegion;
import org.apache.mina.common.IoBuffer;
import org.apache.mina.common.RuntimeIoException;
import org.apache.mina.util.CircularQueue;
import org.apache.tomcat.jni.Poll;
import org.apache.tomcat.jni.Pool;
import org.apache.tomcat.jni.Socket;
import org.apache.tomcat.jni.Status;
/**
* The class in charge of processing socket level IO events for the {@link AprConnector}
*
* @author The Apache MINA Project ([email protected])
* @version $Rev$, $Date$
*/
public class AprIoProcessor extends AbstractIoProcessor<AprSession> {
private static final int INITIAL_CAPACITY = 32;
private final Map<Long, AprSession> allSessions =
new HashMap<Long, AprSession>(INITIAL_CAPACITY);
private final Object wakeupLock = new Object();
private long wakeupSocket;
private volatile boolean toBeWakenUp;
private final long bufferPool; // memory pool
private final long pollset; // socket poller
private long[] polledSockets = new long[INITIAL_CAPACITY << 1];
private final List<AprSession> polledSessions =
new CircularQueue<AprSession>(INITIAL_CAPACITY);
public AprIoProcessor(Executor executor) {
super(executor);
try {
wakeupSocket = Socket.create(
Socket.APR_INET, Socket.SOCK_DGRAM, Socket.APR_PROTO_UDP, AprLibrary
.getInstance().getRootPool());
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (Exception e) {
throw new RuntimeIoException("Failed to create a wakeup socket.", e);
}
// initialize a memory pool for APR functions
bufferPool = Pool.create(AprLibrary.getInstance().getRootPool());
boolean success = false;
try {
// TODO : optimize/parameterize those values
pollset = Poll
.create(
INITIAL_CAPACITY,
AprLibrary.getInstance().getRootPool(),
Poll.APR_POLLSET_THREADSAFE,
10000000);
if (pollset < 0) {
if (Status.APR_STATUS_IS_ENOTIMPL(- (int) pollset)) {
throw new RuntimeIoException(
"Thread-safe pollset is not supported in this platform.");
}
}
success = true;
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (Exception e) {
throw new RuntimeIoException("Failed to create a pollset.", e);
} finally {
if (!success) {
dispose();
}
}
}
@Override
protected void doDispose() {
Poll.destroy(pollset);
Pool.destroy(bufferPool);
Socket.close(wakeupSocket);
}
@Override
protected Iterator<AprSession> allSessions() throws Exception {
return allSessions.values().iterator();
}
@Override
protected void init(AprSession session) throws Exception {
long s = session.getAprSocket();
Socket.optSet(s, Socket.APR_SO_NONBLOCK, 1);
Socket.timeoutSet(s, 0);
int rv = Poll.add(pollset, s, Poll.APR_POLLIN);
if (rv != Status.APR_SUCCESS) {
throwException(rv);
}
session.setInterestedInRead(true);
if (allSessions.size() > polledSockets.length >>> 2) {
this.polledSockets = new long[polledSockets.length << 1];
}
allSessions.put(s, session);
}
private void throwException(int code) throws IOException {
throw new IOException(
org.apache.tomcat.jni.Error.strerror(-code) +
" (code: " + code + ")");
}
@Override
protected void destroy(AprSession session) throws Exception {
allSessions.remove(session.getAprSocket());
if (polledSockets.length >= (INITIAL_CAPACITY << 2) &&
allSessions.size() <= polledSockets.length >>> 3) {
this.polledSockets = new long[polledSockets.length >>> 1];
}
int ret = Poll.remove(pollset, session.getAprSocket());
if (ret != Status.APR_SUCCESS) {
try {
throwException(ret);
} finally {
System.out.println("CLOSE");
ret = Socket.close(session.getAprSocket());
if (ret != Status.APR_SUCCESS) {
throwException(ret);
}
}
}
}
@Override
protected boolean isInterestedInRead(AprSession session) throws Exception {
return session.isInterestedInRead();
}
@Override
protected boolean isInterestedInWrite(AprSession session) throws Exception {
return session.isInterestedInWrite();
}
@Override
protected boolean isReadable(AprSession session) throws Exception {
return session.isReadable();
}
@Override
protected boolean isWritable(AprSession session) throws Exception {
return session.isWritable();
}
@Override
protected int read(AprSession session, IoBuffer buffer) throws Exception {
int bytes;
// Using Socket.recv() directly causes memory leak. :-(
ByteBuffer b = Pool.alloc(bufferPool, buffer.remaining());
try {
bytes = Socket.recvb(
session.getAprSocket(), b, 0, b.remaining());
b.flip();
buffer.put(b);
if (bytes > 0) {
buffer.skip(bytes);
}
if (bytes < 0) {
if (Status.APR_STATUS_IS_EOF(-bytes)) {
bytes = -1;
} else if (Status.APR_STATUS_IS_EAGAIN(-bytes)) {
bytes = 0;
} else {
throwException(bytes);
}
}
} finally {
Pool.clear(bufferPool);
}
return bytes;
}
@Override
protected boolean select(int timeout) throws Exception {
int rv = Poll.poll(pollset, 1000 * timeout, polledSockets, false);
if (rv > 0) {
rv <<= 1;
if (!polledSessions.isEmpty()) {
polledSessions.clear();
}
for (int i = 0; i < rv; i ++) {
long flag = polledSockets[i];
long socket = polledSockets[++i];
if (socket == wakeupSocket) {
synchronized (wakeupLock) {
Poll.remove(pollset, wakeupSocket);
toBeWakenUp = false;
}
continue;
}
AprSession session = allSessions.get(socket);
if (session == null) {
continue;
}
session.setReadable((flag & Poll.APR_POLLIN) != 0);
session.setWritable((flag & Poll.APR_POLLOUT) != 0);
polledSessions.add(session);
}
return !polledSessions.isEmpty();
} else if (rv < 0 && rv != -120001) {
throwException(rv);
}
return false;
}
@Override
protected Iterator<AprSession> selectedSessions() throws Exception {
return polledSessions.iterator();
}
@Override
protected void setInterestedInRead(AprSession session, boolean value)
throws Exception {
int rv = Poll.remove(pollset, session.getAprSocket());
if (rv != Status.APR_SUCCESS) {
throwException(rv);
}
int flags = (value ? Poll.APR_POLLIN : 0)
| (session.isInterestedInWrite() ? Poll.APR_POLLOUT : 0);
rv = Poll.add(pollset, session.getAprSocket(), flags);
if (rv == Status.APR_SUCCESS) {
session.setInterestedInRead(value);
} else {
throwException(rv);
}
}
@Override
protected void setInterestedInWrite(AprSession session, boolean value)
throws Exception {
int rv = Poll.remove(pollset, session.getAprSocket());
if (rv != Status.APR_SUCCESS) {
throwException(rv);
}
int flags = (session.isInterestedInRead() ? Poll.APR_POLLIN : 0)
| (value ? Poll.APR_POLLOUT : 0);
rv = Poll.add(pollset, session.getAprSocket(), flags);
if (rv == Status.APR_SUCCESS) {
session.setInterestedInWrite(value);
} else {
throwException(rv);
}
}
@Override
protected SessionState state(AprSession session) {
long socket = session.getAprSocket();
if (socket > 0) {
return SessionState.OPEN;
} else if (allSessions.get(socket) != null) {
return SessionState.PREPARING; // will occur ?
} else {
return SessionState.CLOSED;
}
}
@Override
protected long transferFile(AprSession session, FileRegion region)
throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected void wakeup() {
if (toBeWakenUp) {
return;
}
// Add a dummy socket to the pollset.
synchronized (wakeupLock) {
toBeWakenUp = true;
Poll.add(pollset, wakeupSocket, Poll.APR_POLLOUT);
}
}
@Override
protected int write(AprSession session, IoBuffer buf) throws Exception {
int writtenBytes;
if (buf.isDirect()) {
writtenBytes = Socket.sendb(session.getAprSocket(), buf.buf(), buf
.position(), buf.remaining());
} else {
writtenBytes = Socket.send(session.getAprSocket(), buf.array(), buf
.position(), buf.remaining());
if (writtenBytes > 0) {
buf.skip(writtenBytes);
}
}
if (writtenBytes < 0) {
if (Status.APR_STATUS_IS_EAGAIN(-writtenBytes)) {
writtenBytes = 0;
} else if (Status.APR_STATUS_IS_EOF(-writtenBytes)) {
writtenBytes = 0;
} else {
throwException(writtenBytes);
}
}
return writtenBytes;
}
} | transport-apr/src/main/java/org/apache/mina/transport/socket/apr/AprIoProcessor.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.mina.transport.socket.apr;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import org.apache.mina.common.AbstractIoProcessor;
import org.apache.mina.common.FileRegion;
import org.apache.mina.common.IoBuffer;
import org.apache.mina.common.RuntimeIoException;
import org.apache.mina.util.CircularQueue;
import org.apache.tomcat.jni.Poll;
import org.apache.tomcat.jni.Pool;
import org.apache.tomcat.jni.Socket;
import org.apache.tomcat.jni.Status;
/**
* The class in charge of processing socket level IO events for the {@link AprConnector}
*
* @author The Apache MINA Project ([email protected])
* @version $Rev$, $Date$
*/
public class AprIoProcessor extends AbstractIoProcessor<AprSession> {
private final Map<Long, AprSession> managedSessions = new HashMap<Long, AprSession>();
private final Object wakeupLock = new Object();
private long wakeupSocket;
private volatile boolean toBeWakenUp;
private final long bufferPool; // memory pool
private final long pollset; // socket poller
private long[] polledSockets = new long[64];
private final List<AprSession> polledSessions = new CircularQueue<AprSession>();
public AprIoProcessor(Executor executor) {
super(executor);
try {
wakeupSocket = Socket.create(
Socket.APR_INET, Socket.SOCK_DGRAM, Socket.APR_PROTO_UDP, AprLibrary
.getInstance().getRootPool());
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (Exception e) {
throw new RuntimeIoException("Failed to create a wakeup socket.", e);
}
// initialize a memory pool for APR functions
bufferPool = Pool.create(AprLibrary.getInstance().getRootPool());
boolean success = false;
try {
// TODO : optimize/parameterize those values
pollset = Poll
.create(
2,
AprLibrary.getInstance().getRootPool(),
Poll.APR_POLLSET_THREADSAFE,
10000000);
if (pollset < 0) {
if (Status.APR_STATUS_IS_ENOTIMPL(- (int) pollset)) {
throw new RuntimeIoException(
"Thread-safe pollset is not supported in this platform.");
}
}
success = true;
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (Exception e) {
throw new RuntimeIoException("Failed to create a pollset.", e);
} finally {
if (!success) {
dispose();
}
}
}
@Override
protected void doDispose() {
Poll.destroy(pollset);
Pool.destroy(bufferPool);
Socket.close(wakeupSocket);
}
@Override
protected Iterator<AprSession> allSessions() throws Exception {
return managedSessions.values().iterator();
}
@Override
protected void init(AprSession session) throws Exception {
long s = session.getAprSocket();
Socket.optSet(s, Socket.APR_SO_NONBLOCK, 1);
Socket.timeoutSet(s, 0);
int rv = Poll.add(pollset, s, Poll.APR_POLLIN);
if (rv != Status.APR_SUCCESS) {
throwException(rv);
}
session.setInterestedInRead(true);
if (managedSessions.size() >= polledSockets.length >>> 2) {
this.polledSockets = new long[polledSockets.length << 1];
}
managedSessions.put(s, session);
}
private void throwException(int code) throws IOException {
throw new IOException(
org.apache.tomcat.jni.Error.strerror(-code) +
" (code: " + code + ")");
}
@Override
protected void destroy(AprSession session) throws Exception {
managedSessions.remove(session.getAprSocket());
int ret = Poll.remove(pollset, session.getAprSocket());
if (ret != Status.APR_SUCCESS) {
try {
throwException(ret);
} finally {
System.out.println("CLOSE");
ret = Socket.close(session.getAprSocket());
if (ret != Status.APR_SUCCESS) {
throwException(ret);
}
}
}
}
@Override
protected boolean isInterestedInRead(AprSession session) throws Exception {
return session.isInterestedInRead();
}
@Override
protected boolean isInterestedInWrite(AprSession session) throws Exception {
return session.isInterestedInWrite();
}
@Override
protected boolean isReadable(AprSession session) throws Exception {
return session.isReadable();
}
@Override
protected boolean isWritable(AprSession session) throws Exception {
return session.isWritable();
}
@Override
protected int read(AprSession session, IoBuffer buffer) throws Exception {
int bytes;
// Using Socket.recv() directly causes memory leak. :-(
ByteBuffer b = Pool.alloc(bufferPool, buffer.remaining());
try {
bytes = Socket.recvb(
session.getAprSocket(), b, 0, b.remaining());
b.flip();
buffer.put(b);
if (bytes > 0) {
buffer.skip(bytes);
}
if (bytes < 0) {
if (Status.APR_STATUS_IS_EOF(-bytes)) {
bytes = -1;
} else if (Status.APR_STATUS_IS_EAGAIN(-bytes)) {
bytes = 0;
} else {
throwException(bytes);
}
}
} finally {
Pool.clear(bufferPool);
}
return bytes;
}
@Override
protected boolean select(int timeout) throws Exception {
int rv = Poll.poll(pollset, 1000 * timeout, polledSockets, false);
if (rv > 0) {
rv <<= 1;
if (!polledSessions.isEmpty()) {
polledSessions.clear();
}
for (int i = 0; i < rv; i ++) {
long flag = polledSockets[i];
long socket = polledSockets[++i];
if (socket == wakeupSocket) {
synchronized (wakeupLock) {
Poll.remove(pollset, wakeupSocket);
toBeWakenUp = false;
}
continue;
}
AprSession session = managedSessions.get(socket);
if (session == null) {
continue;
}
session.setReadable((flag & Poll.APR_POLLIN) != 0);
session.setWritable((flag & Poll.APR_POLLOUT) != 0);
polledSessions.add(session);
}
return !polledSessions.isEmpty();
} else if (rv < 0 && rv != -120001) {
throwException(rv);
}
return false;
}
@Override
protected Iterator<AprSession> selectedSessions() throws Exception {
return polledSessions.iterator();
}
@Override
protected void setInterestedInRead(AprSession session, boolean value)
throws Exception {
int rv = Poll.remove(pollset, session.getAprSocket());
if (rv != Status.APR_SUCCESS) {
throwException(rv);
}
int flags = (value ? Poll.APR_POLLIN : 0)
| (session.isInterestedInWrite() ? Poll.APR_POLLOUT : 0);
rv = Poll.add(pollset, session.getAprSocket(), flags);
if (rv == Status.APR_SUCCESS) {
session.setInterestedInRead(value);
} else {
throwException(rv);
}
}
@Override
protected void setInterestedInWrite(AprSession session, boolean value)
throws Exception {
int rv = Poll.remove(pollset, session.getAprSocket());
if (rv != Status.APR_SUCCESS) {
throwException(rv);
}
int flags = (session.isInterestedInRead() ? Poll.APR_POLLIN : 0)
| (value ? Poll.APR_POLLOUT : 0);
rv = Poll.add(pollset, session.getAprSocket(), flags);
if (rv == Status.APR_SUCCESS) {
session.setInterestedInWrite(value);
} else {
throwException(rv);
}
}
@Override
protected SessionState state(AprSession session) {
long socket = session.getAprSocket();
if (socket > 0) {
return SessionState.OPEN;
} else if (managedSessions.get(socket) != null) {
return SessionState.PREPARING; // will occur ?
} else {
return SessionState.CLOSED;
}
}
@Override
protected long transferFile(AprSession session, FileRegion region)
throws Exception {
throw new UnsupportedOperationException();
}
@Override
protected void wakeup() {
if (toBeWakenUp) {
return;
}
// Add a dummy socket to the pollset.
synchronized (wakeupLock) {
toBeWakenUp = true;
Poll.add(pollset, wakeupSocket, Poll.APR_POLLOUT);
}
}
@Override
protected int write(AprSession session, IoBuffer buf) throws Exception {
int writtenBytes;
if (buf.isDirect()) {
writtenBytes = Socket.sendb(session.getAprSocket(), buf.buf(), buf
.position(), buf.remaining());
} else {
writtenBytes = Socket.send(session.getAprSocket(), buf.array(), buf
.position(), buf.remaining());
if (writtenBytes > 0) {
buf.skip(writtenBytes);
}
}
if (writtenBytes < 0) {
if (Status.APR_STATUS_IS_EAGAIN(-writtenBytes)) {
writtenBytes = 0;
} else if (Status.APR_STATUS_IS_EOF(-writtenBytes)) {
writtenBytes = 0;
} else {
throwException(writtenBytes);
}
}
return writtenBytes;
}
} | * Small memory optimization
* renamed managedSessions to allSessions
git-svn-id: b7022df5c975f24f6cce374a8cf09e1bba3b7a2e@596591 13f79535-47bb-0310-9956-ffa450edef68
| transport-apr/src/main/java/org/apache/mina/transport/socket/apr/AprIoProcessor.java | * Small memory optimization * renamed managedSessions to allSessions | <ide><path>ransport-apr/src/main/java/org/apache/mina/transport/socket/apr/AprIoProcessor.java
<ide> */
<ide>
<ide> public class AprIoProcessor extends AbstractIoProcessor<AprSession> {
<add> private static final int INITIAL_CAPACITY = 32;
<ide>
<del> private final Map<Long, AprSession> managedSessions = new HashMap<Long, AprSession>();
<add> private final Map<Long, AprSession> allSessions =
<add> new HashMap<Long, AprSession>(INITIAL_CAPACITY);
<ide>
<ide> private final Object wakeupLock = new Object();
<ide> private long wakeupSocket;
<ide>
<ide> private final long bufferPool; // memory pool
<ide> private final long pollset; // socket poller
<del> private long[] polledSockets = new long[64];
<del> private final List<AprSession> polledSessions = new CircularQueue<AprSession>();
<add> private long[] polledSockets = new long[INITIAL_CAPACITY << 1];
<add> private final List<AprSession> polledSessions =
<add> new CircularQueue<AprSession>(INITIAL_CAPACITY);
<ide>
<ide> public AprIoProcessor(Executor executor) {
<ide> super(executor);
<ide> // TODO : optimize/parameterize those values
<ide> pollset = Poll
<ide> .create(
<del> 2,
<add> INITIAL_CAPACITY,
<ide> AprLibrary.getInstance().getRootPool(),
<ide> Poll.APR_POLLSET_THREADSAFE,
<ide> 10000000);
<ide>
<ide> @Override
<ide> protected Iterator<AprSession> allSessions() throws Exception {
<del> return managedSessions.values().iterator();
<add> return allSessions.values().iterator();
<ide> }
<ide>
<ide> @Override
<ide> }
<ide>
<ide> session.setInterestedInRead(true);
<del> if (managedSessions.size() >= polledSockets.length >>> 2) {
<add> if (allSessions.size() > polledSockets.length >>> 2) {
<ide> this.polledSockets = new long[polledSockets.length << 1];
<ide> }
<del> managedSessions.put(s, session);
<add> allSessions.put(s, session);
<ide> }
<ide>
<ide> private void throwException(int code) throws IOException {
<ide>
<ide> @Override
<ide> protected void destroy(AprSession session) throws Exception {
<del> managedSessions.remove(session.getAprSocket());
<add> allSessions.remove(session.getAprSocket());
<add> if (polledSockets.length >= (INITIAL_CAPACITY << 2) &&
<add> allSessions.size() <= polledSockets.length >>> 3) {
<add> this.polledSockets = new long[polledSockets.length >>> 1];
<add> }
<add>
<ide> int ret = Poll.remove(pollset, session.getAprSocket());
<ide> if (ret != Status.APR_SUCCESS) {
<ide> try {
<ide> }
<ide> continue;
<ide> }
<del> AprSession session = managedSessions.get(socket);
<add> AprSession session = allSessions.get(socket);
<ide> if (session == null) {
<ide> continue;
<ide> }
<ide> long socket = session.getAprSocket();
<ide> if (socket > 0) {
<ide> return SessionState.OPEN;
<del> } else if (managedSessions.get(socket) != null) {
<add> } else if (allSessions.get(socket) != null) {
<ide> return SessionState.PREPARING; // will occur ?
<ide> } else {
<ide> return SessionState.CLOSED; |
|
JavaScript | mit | d0ff248fb8a621b6057a976eb5001ceda897818a | 0 | lfabianosb/travel-advisor-job,lfabianosb/travel-advisor-job,lfabianosb/travel-advisor-job | var casper = require("casper").create({
pageSettings: {
loadImages: false,
loadPlugins: false,
userAgent: 'Mozilla/5.0 (Windows NT 6.1; rv:53.0) Gecko/20100101 Firefox/53.0'
},
logLevel: "info",
verbose: false
});
var system = require('system');
var target = casper.cli.get(0);
var ENCARGO = system.env.ENCARGO || 7;
var TIMEOUT = system.env.SCRAP_TIMEOUT || 45;
var flight = {};
function throwErrorAndStop(msg) {
flight.msg = msg;
console.log(JSON.stringify(flight, null, null));
this.exit();
}
casper.on('error', function(msg, backtrace) {
flight.msg = 'Error message: ' + msg + '\nBacktrace: ' + backtrace;
console.log(JSON.stringify(flight, null, null));
this.exit();
});
casper.start(target, function() {
this.wait(15000);
//Waiting page load
this.waitWhileVisible('#vn-content-view > div.fluxo-content > div > span',
function sucess() {
this.wait(5000);
var totalPassagens = this.evaluate(function() {
return document.querySelector('#vn-content-view > div.fluxo-content > flight-detail > ul > li:nth-child(1) > div.price.sticky_price > div > p.ng-binding > span').textContent;
});
if (totalPassagens == null) {
throwErrorAndStop('Valor das passagens não encontrado.');
}
var fltTotalPassagens = totalPassagens.trim().substring(3).replace('.','').replace(',','.')
var taxasEncargos = this.evaluate(function() {
return document.querySelector('#vn-content-view > div.fluxo-content > flight-detail > ul > li:nth-child(1) > div.price.sticky_price > div > p:nth-child(2) > span').textContent;
});
if (taxasEncargos == null) {
throwErrorAndStop('Valor dos encargos não encontrado.');
}
var fltTaxasEncargos = taxasEncargos.trim().substring(3).replace('.','').replace(',','.');
var cia = this.evaluate(function() {
return document.querySelector('#vn-content-view > div.fluxo-content > flight-detail > ul > li:nth-child(1) > div.flights > ul.ng-scope.ida > li.flight.ng-scope.flight-ida > label > div.list-cias > div > span').textContent;
});
if (cia == null) {
throwErrorAndStop('Companhia aérea não encontrada.');
}
var total = parseFloat((1 - (ENCARGO/100)) * fltTotalPassagens) + parseFloat(fltTaxasEncargos);
var fltTotal = total.toFixed(2);
flight.cia = cia.trim();
flight.valor = fltTotal;
console.log(JSON.stringify(flight, null, null));
},
function fail() {
flight.msg = 'Timeout for ' + target;
console.log(JSON.stringify(flight, null, null));
this.exit();
},
TIMEOUT * 1000
);
});
casper.run(); | viajanet.js | var casper = require("casper").create({
pageSettings: {
loadImages: false,
loadPlugins: false,
userAgent: 'Mozilla/5.0 (Windows NT 6.1; rv:53.0) Gecko/20100101 Firefox/53.0'
},
logLevel: "info",
verbose: false
});
var system = require('system');
var target = casper.cli.get(0);
var ENCARGO = system.env.ENCARGO || 7;
var TIMEOUT = system.env.SCRAP_TIMEOUT || 45;
var flight = {};
function throwErrorAndStop(msg) {
flight.msg = msg;
console.log(JSON.stringify(flight, null, null));
this.exit();
}
casper.on('error', function(msg, backtrace) {
flight.msg = 'Error message: ' + msg + '\nBacktrace: ' + backtrace;
console.log(JSON.stringify(flight, null, null));
this.exit();
});
casper.start(target, function() {
this.wait(10000);
//Waiting page load
this.waitWhileVisible('#vn-content-view > div.fluxo-content > div > span',
function sucess() {
this.wait(5000);
var totalPassagens = this.evaluate(function() {
return document.querySelector('#vn-content-view > div.fluxo-content > flight-detail > ul > li:nth-child(1) > div.price.sticky_price > div > p.ng-binding > span').textContent;
});
if (totalPassagens == null) {
throwErrorAndStop('Valor das passagens não encontrado.');
}
var fltTotalPassagens = totalPassagens.trim().substring(3).replace('.','').replace(',','.')
var taxasEncargos = this.evaluate(function() {
return document.querySelector('#vn-content-view > div.fluxo-content > flight-detail > ul > li:nth-child(1) > div.price.sticky_price > div > p:nth-child(2) > span').textContent;
});
if (taxasEncargos == null) {
throwErrorAndStop('Valor dos encargos não encontrado.');
}
var fltTaxasEncargos = taxasEncargos.trim().substring(3).replace('.','').replace(',','.');
var cia = this.evaluate(function() {
return document.querySelector('#vn-content-view > div.fluxo-content > flight-detail > ul > li:nth-child(1) > div.flights > ul.ng-scope.ida > li.flight.ng-scope.flight-ida > label > div.list-cias > div > span').textContent;
});
if (cia == null) {
throwErrorAndStop('Companhia aérea não encontrada.');
}
var total = parseFloat((1 - (ENCARGO/100)) * fltTotalPassagens) + parseFloat(fltTaxasEncargos);
var fltTotal = total.toFixed(2);
flight.cia = cia.trim();
flight.valor = fltTotal;
console.log(JSON.stringify(flight, null, null));
},
function fail() {
flight.msg = 'Timeout for ' + target;
console.log(JSON.stringify(flight, null, null));
this.exit();
},
TIMEOUT * 1000
);
});
casper.run(); | Increasing time to wait
| viajanet.js | Increasing time to wait | <ide><path>iajanet.js
<ide> });
<ide>
<ide> casper.start(target, function() {
<del> this.wait(10000);
<add> this.wait(15000);
<ide>
<ide> //Waiting page load
<ide> this.waitWhileVisible('#vn-content-view > div.fluxo-content > div > span', |
|
JavaScript | mit | 60c709119430feae37cce4d5254276463ad7e2ce | 0 | Turistforeningen/Hytteadmin,Turistforeningen/Hytteadmin | import Ember from 'ember';
export default Ember.Route.extend({
setupController: function(controller, model) {
var groups = this.store.findAll('group');
this.controllerFor('groups').set('model', groups);
var users = this.store.findAll('user').then(function (users) {
console.log('users', users);
}).catch(function (err) {
if (err.authenticated === false) {
// TODO: Redirect to login
}
});
}
});
| client/app/routes/application.js | import Ember from 'ember';
export default Ember.Route.extend({
setupController: function(controller, model) {
var groups = this.store.findAll('group');
this.controllerFor('groups').set('model', groups);
}
});
| Check for user in application route
| client/app/routes/application.js | Check for user in application route | <ide><path>lient/app/routes/application.js
<ide> setupController: function(controller, model) {
<ide> var groups = this.store.findAll('group');
<ide> this.controllerFor('groups').set('model', groups);
<add>
<add> var users = this.store.findAll('user').then(function (users) {
<add> console.log('users', users);
<add>
<add> }).catch(function (err) {
<add> if (err.authenticated === false) {
<add> // TODO: Redirect to login
<add> }
<add>
<add> });
<add>
<ide> }
<ide> }); |
|
JavaScript | apache-2.0 | d7df3ab6b608af8a5d95f353713a36f9018ca4df | 0 | racker/node-swiz,racker/node-swiz | /*
* Copyright 2011 Rackspace
*
* 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.
*
*/
var swiz = require('../lib/swiz');
var async = require('async');
var V = swiz.Valve;
var C = swiz.Chain;
var O = swiz.struct.Obj;
var F = swiz.struct.Field;
// Mock set of serialization defs
var def = [
O('Node',
{
'fields': [
F('id', {'src': 'hash_id', 'desc': 'hash ID for the node', 'attribute': true,
'val' : C().isString()}),
F('is_active', {'src': 'active', 'desc': 'is the node active?',
'val' : C().toBoolean(), 'coerceTo' : 'boolean'}),
F('name', {'src' : 'get_name', 'desc' : 'name', 'attribute': true,
'val' : C().isString()}),
F('agent_name', {'val' : C().isString().notEmpty()}),
F('ipaddress' , {'src' : 'get_public_address', 'val' : C().isIP()})
],
'plural': 'nodes'
}),
O('Node2',
{
'fields': [
F('id', {'src': 'hash_id', 'desc': 'hash ID for the node', 'attribute': true,
'val' : C().isString()}),
F('is_active', {'src': 'active', 'desc': 'is the node active?',
'val' : C().toBoolean(), 'coerceTo' : 'boolean'}),
F('name', {'src' : 'get_name', 'desc' : 'name', 'attribute': true,
'val' : C().isString()}),
F('agent_name', {'val' : C().isString().notEmpty()}),
F('state', {'enumerated' : {inactive: 0, active: 1, full_no_new_checks: 2}}),
F('ipaddress' , {'src' : 'get_public_address', 'val' : C().isIP()})
],
'plural': 'nodes'
}),
O('NodeOpts',
{
'fields': [
F('option1', {'src': 'opt1', 'val' : C().isString()}),
F('option2', {'src': 'opt2', 'val' : C().isString()}),
F('option3', {'src': 'opt3', 'val' : C().isString()}),
]
}),
];
var exampleNode = {
'id' : 'xkCD366',
'is_active' : true,
'name' : 'exmample',
'agent_name' : 'your mom',
'ipaddress' : '42.24.42.24'
};
var exampleNode2 = {
'id' : 'xkCD366',
'is_active' : true,
'name' : 'exmample',
'agent_name' : 'your mom',
'state': 'active',
'ipaddress' : '42.24.42.24'
};
var compNode = {
'hash_id' : 'xkCD366',
'active' : true,
'get_name' : 'exmample',
'agent_name' : 'your mom',
'get_public_address' : '42.24.42.24'
};
var badExampleNode = {
'id' : 'xkCD366',
'is_active' : true,
'name' : 'exmample',
'agent_name' : 'your mom',
'ipaddress' : '42'
};
var badExampleNode1 = {
'id' : 'xkCD366',
'is_active' : true,
'name' : 'exmample',
'ipaddress' : '42.24.42.24'
};
exports['test_validate_numItems'] = function(test, assert) {
var v1, v2, v3;
v1 = new V({
a: C().isArray(C().isInt()).numItems(1, 5)
});
v2 = new V({
a: C().isHash(C().isString(), C().notEmpty()).numItems(1, 5)
});
v3 = new V({
a: C().isArray(C().isInt()).numItems(2)
});
// Negative test cases (array)
v1.check({'a': [1]}, function(err, cleaned) {
assert.ifError(err);
});
v1.check({'a': [1, 2, 3, 4, 5]}, function(err, cleaned) {
assert.ifError(err);
});
v3.check({'a': [1, 2]}, function(err, cleaned) {
assert.ifError(err);
});
// Positive case (array)
v3.check({'a': [1]}, function(err, cleaned) {
assert.ok(err);
assert.match(err.message, /Object needs to have between 2 and Infinity items/);
});
// Positive test cases (array)
v1.check({'a': []}, function(err, cleaned) {
assert.ok(err);
assert.match(err.message, /Object needs to have between 1 and 5 items/);
});
v1.check({'a': [1, 2, 3, 4, 5, 6]}, function(err, cleaned) {
assert.ok(err);
assert.match(err.message, /Object needs to have between 1 and 5 items/);
});
// Negative test cases (object)
v2.check({'a': {'a': 1}}, function(err, cleaned) {
assert.ifError(err);
});
v2.check({'a': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'f': 5}}, function(err, cleaned) {
assert.ifError(err);
});
// Positive test cases (object)
v2.check({'a': {}}, function(err, cleaned) {
assert.ok(err);
assert.match(err.message, /Object needs to have between 1 and 5 items/);
});
v2.check({'a': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'f': 5, 'g': 6}}, function(err, cleaned) {
assert.ok(err);
assert.match(err.message, /Object needs to have between 1 and 5 items/);
});
test.finish();
};
exports['test_validate_int'] = function(test, assert) {
var v = new V({
a: C().isInt()
});
// positive case
var obj = { a: 1 };
var obj_ext = { a: 1, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'integer test');
});
obj = { a: '1' };
obj_ext = { a: '1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'integer test 2');
});
obj = { a: -17 };
obj_ext = { a: -17, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'integer test 3');
});
// negative case
var neg = { a: 'test' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid integer', 'integer test (negative case)');
});
test.finish();
};
exports['test_check_strict_mode'] = function(test, assert) {
var v = new V({
a: C().isInt()
});
async.series([
function pos1(callback) {
var obj = {'a': 5};
v.check(obj, {'strict': true}, function(err, cleaned) {
assert.ifError(err);
callback();
});
},
function neg1(callback) {
var obj = {'a': 5, 'b': 5};
v.check(obj, {'strict': true}, function(err, cleaned) {
assert.ok(err);
assert.equal(err.key, 'b');
assert.match(err.message, /This key is not allowed/);
callback();
});
}
],
function(err) {
test.finish();
});
};
exports['test_transformation_validator'] = function(test, assert) {
var v = new V({
a: C().isInt().toInt().optional()
});
var obj = { a: '10' };
v.check(obj, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, {'a': 10});
test.finish();
});
};
exports['test_isUnique'] = function(test, assert) {
var v = new V({
a: C().isUnique()
});
// positive case
var obj1 = { a: [1, 2, 3, 4, 5] };
var obj2 = { a: [9, 2, 3, 4, 5] };
v.check(obj1, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj1);
});
v.check(obj2, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj2);
});
// negative case
var obj1Neg = { a: {} };
var obj2Neg = { a: [2, 2, 3, 4, 5] };
v.check(obj1Neg, function(err, cleaned) {
assert.ok(err);
});
v.check(obj2Neg, function(err, cleaned) {
assert.ok(err);
});
test.finish();
};
exports['test_toUnique'] = function(test, assert) {
var v = new V({
a: C().toUnique()
});
var failed = false;
// positive case
var obj1 = { a: [1, 2, 3, 4, 5] };
var obj2 = { a: [9, 2, 3, 4, 5] };
v.check(obj1, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj1);
});
v.check(obj2, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj2);
});
// negative case
var obj1Neg = { a: {} };
var obj2Neg = { a: [2, 2, 3, 3, 3, 3, 4, 5] };
v.check(obj1Neg, function(err, cleaned) {
assert.ok(err);
});
v.check(obj2Neg, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, {a: [2, 3, 4, 5]});
});
test.finish();
};
exports['test_validate_email'] = function(test, assert) {
var v = new V({
a: C().isEmail()
});
// positive case
var obj = { a: '[email protected]' };
var obj_ext = { a: '[email protected]', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'email test');
});
// negative case
var neg = { a: 'invalidemail@' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid email', 'integer test (negative case)');
});
test.finish();
};
exports['test_validate_url'] = function(test, assert) {
var v = new V({
a: C().isUrl()
});
// positive case
var obj = { a: 'http://www.cloudkick.com' };
var obj_ext = { a: 'http://www.cloudkick.com', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'URL test');
});
// negative case
var neg = { a: 'invalid/' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid URL', 'URL test (negative case)');
});
test.finish();
};
exports['test_validate_ipv6'] = function(test, assert) {
var v = new V({
a: C().isIPv6()
});
// positive case
var obj = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
var obj_ext = { a: '2001:0db8:0000:0000:0001:0000:0000:0001', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'IPv6 test');
});
// negative case
var neg = { a: '127.0.0.2' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IPv6', 'IPv6 test (negative case)');
});
neg = {a: '12345' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IPv6', 'IPv6 test (negative case 2)');
});
test.finish();
};
exports['test_validate_hostname'] = function(test, assert) {
var v = new V({
a: C().isHostname()
});
// positive case
var obj1 = { a: 'foo1-bar-2-ck.com' };
var obj2 = { a: 'rackspace.com' };
async.series([
function pos1(callback) {
v.check(obj1, function(err, cleaned) {
assert.ifError(err);
callback();
});
},
function pos2(callback) {
v.check(obj2, function(err, cleaned) {
assert.ifError(err);
callback();
});
},
function neg1(callback) {
var neg = { a: 'hostname.' };
v.check(neg, function(err, cleaned) {
assert.ok(err);
callback();
});
},
function neg2(callback) {
var neg = { a: 'hostname.' };
v.check(neg, function(err, cleaned) {
assert.ok(err);
callback();
});
}
],
function(err) {
test.finish();
});
};
exports['test_isHostnameOrIp'] = function(test, assert) {
var v = new V({
a: C().isHostnameOrIp()
});
async.series([
function pos1(callback) {
var obj = { 'a': '127.0.0.1' };
v.check(obj, function(err, cleaned) {
assert.ifError(err);
callback();
});
},
function pos2(callback) {
var obj = { 'a': '2001:0db8:0000:0000:0001:0000:0000:0001' };
v.check(obj, function(err, cleaned) {
assert.ifError(err);
callback();
});
},
function pos4(callback) {
var obj = { 'a': 'github.com' };
v.check(obj, function(err, cleaned) {
assert.ifError(err);
callback();
});
},
function neg1(callback) {
var neg = { a: 'hostname.' };
v.check(neg, function(err, cleaned) {
assert.ok(err);
callback();
});
}
],
function(err) {
test.finish();
});
};
exports['test_validate_ipv4'] = function(test, assert) {
var v = new V({
a: C().isIPv4()
});
// positive case
var obj = { a: '192.168.0.1' };
var obj_ext = { a: '192.168.0.1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'IP test');
});
// negative case
var neg = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IPv4', 'IPv4 test (negative case)');
});
neg = {a: '12345' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IPv4', 'IPv4 test (negative case 2)');
});
test.finish();
};
exports['test_validate_isAddressPair'] = function(test, assert) {
var v = new V({
a: C().isAddressPair()
});
var obj, obj_ext;
// positive case 1
obj = { a: '192.168.0.1:1111' };
obj_ext = { a: '192.168.0.1:1111' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'isAddressPair test');
});
// positive case 2
obj = { a: '0000:0000:0000:0000:0000:0000:0000:0001:22222' };
obj_ext = { a: '::1:22222' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'isAddressPair test');
});
// negative case 1
obj_ext = { a: '127.0.0.1' };
v.check(obj_ext, function(err, cleaned) {
assert.match(err.message, /Missing semicolon/);
});
// negative case 2
obj_ext = { a: 'a.b:4444' };
v.check(obj_ext, function(err, cleaned) {
assert.match(err.message, /IP address in the address pair is not valid/);
});
// negative case 3
obj_ext = { a: '127.0.0.1:444444' };
v.check(obj_ext, function(err, cleaned) {
assert.match(err.message, /Port in the address pair is out of range/);
});
test.finish();
// positive case 2
};
function invalidIpFailMsgAsserter(assert, msg) {
return function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', msg);
}
}
exports['test_validate_ip'] = function(test, assert) {
var invalidIpFailMsg = invalidIpFailMsgAsserter.bind(null, assert);
var v = new V({
a: C().isIP()
});
// positive test cases
var expected = { a: '192.168.0.1' };
v.check({a: '192.168.0.1', b: 2}, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept dotted-quad syntax for IPv4 addresses');
});
expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
v.check({a: '2001:0db8:0000:0000:0001:0000:0000:0001', b: 2}, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a coloned-octet syntax for IPv6 addresses');
});
expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
v.check({a: '2001:0db8::0001:0000:0000:0001', b: 2}, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a shortened syntax for IPv6 addresses');
});
expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
v.check({a: '2001:0db8:0000:0000:0001::0001', b: 2}, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a shortened syntax for IPv6 addresses');
});
expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
v.check({a: '2001:db8:0:0:1:0:0:1', b: 2}, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a coloned-octet syntax with leading zeros blanked for IPv6 addresses');
});
expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
v.check({a: '2001:db8::1:0:0:1', b: 2}, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a shortened syntax with leading zeros blanked for IPv6 addresses');
});
expected = { a: '1234:0000:0000:0000:0000:0000:0000:0000' };
v.check({a: '1234::', b: 2}, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a tail-truncated address for IPv6 addresses');
});
expected = { a: '0000:0000:0000:0000:0000:0000:0000:1234' };
v.check({a: '::1234', b: 2}, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a head-truncated address for IPv6 addresses');
});
expected = { a: '0000:0000:0000:0000:0000:0000:0000:0000' };
v.check({a: '::', b: 2}, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a nil IPv6 address');
});
expected = { a: '0000:0000:0000:0000:0000:0000:7f00:0001' };
v.check({a: '::7F00:0001', b: 2}, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept an IPv6 address with capital letters');
});
expected = { a: '0000:0000:0000:0000:0000:0000:7f00:0001' };
v.check({a: '::127.0.0.1', b: 2}, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept an IPv4 address embedded in an IPv6 address');
});
// negative test cases
v.check({a: 'invalid/'}, invalidIpFailMsg('IP addresses cannot be strings'));
v.check({a: '12345'}, invalidIpFailMsg('IP addresses cannot be single integers'));
v.check({a: '2001:0db8::1::1'}, invalidIpFailMsg('IPv6 can only have at most one "::" symbol in it.'));
v.check({a: '2001:0db8:0000:0000:0001:0000:0000'}, invalidIpFailMsg('IPv6 coloned-octet notation requires eight hex words.'));
v.check({a: '2001:0db8::1:0:0:00001'}, invalidIpFailMsg('IPv6 hex groups can be at most 4 characters long.'));
v.check({a: {b: null}}, function(err, unused) {
assert.deepEqual(err.message, 'IP address is not a string', 'IP addresses cannot be null or JSON objects');
});
v.check({a: '2001:0db8:0:0:1:0:0:127.0.0.1'}, function(err, unused) {
assert.deepEqual(err.message, 'Incorrect number of groups found', 'Malformed IPv6 address w/ embedded IPv4 address');
});
var stack_attack = "";
var possible = "0123456789.:";
for(var i=0; i < 1048576; i++) {
stack_attack += possible.charAt(Math.floor(Math.random()*possible.length));
}
stack_attack = '1'+stack_attack; // Make sure it starts with a digit
ifFailed = invalidIpFailMsgAsserter.bind(null, assert, 'Stack overflow attacks, to 1MB, should be rejected out of hand.');
v.check({a: stack_attack}, ifFailed);
v.check({a: '2001:0db8:0:0:1:0:0:'+stack_attack}, ifFailed);
v.check({a: '192.168.0.'+stack_attack}, ifFailed);
test.finish();
};
exports['test_validate_ip_blacklist'] = function(test, assert) {
var v = new V({
a: C().isIP().notIPBlacklisted()
});
// positive case
var obj_ext = { a: '173.45.245.32', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err, 'IP blacklist test');
});
// negative case
var neg = { a: 'invalid/' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', 'IP test (negative case 2)');
});
neg = { a: '192.168.0.1' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'IP is blacklisted', 'IP test (negative case 2)');
});
// IPv6
obj_ext = { a: '2001:db8::1:0:0:1'};
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err, 'IPv6 blacklist test');
});
neg = {a: 'fc00:1:0:0:1' };
v.check(neg, function(err, cleaned) {
assert.match(err.message, /Invalid IP/, 'IP test (negative case 2)');
});
test.finish();
};
exports['test_validate_cidr'] = function(test, assert) {
var v = new V({
a: C().isCIDR()
});
// positive case
var obj = { a: '192.168.0.1/2' };
var obj_ext = { a: '192.168.0.1/2', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'CIDR test');
});
// negative case
var neg = { a: 'invalid/' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', 'CIDR test (negative case)');
});
neg = { a: '192.168.0.1/128' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid subnet length', 'CIDR test (negative case 2)');
});
// IPv6 normalization
obj_ext = { a: '2001:db8::1:0:0:1/3'};
obj = { a: '2001:0db8:0000:0000:0001:0000:0000:0001/3' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'IPv6 CIDR test');
});
neg = { a: '2001:db8::1:0:0:1/194' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid subnet length', 'IPv6 CIDR test (negative case)');
});
test.finish();
};
exports['test_validate_alpha'] = function(test, assert) {
var v = new V({
a: C().isAlpha()
});
// positive case
var obj = { a: 'ABC' };
var obj_ext = { a: 'ABC', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'alpha test');
});
// negative case
var neg = { a: 'invalid/' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'alpha test (negative case)');
});
test.finish();
};
exports['test_validate_alphanumeric'] = function(test, assert) {
var v = new V({
a: C().isAlphanumeric()
});
// positive case
var obj = { a: 'ABC123' };
var obj_ext = { a: 'ABC123', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'alphanumeric test');
});
// negative case
var neg = { a: 'invalid/' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'alphanumeric test (negative case)');
});
test.finish();
};
exports['test_validate_numeric'] = function(test, assert) {
var v = new V({
a: C().isNumeric()
});
// positive case
var obj = { a: '123' };
var obj_ext = { a: 123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'numeric test');
});
obj_ext = { a: '123', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'numeric test 2');
});
// negative case
var neg = { a: '/' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid number', 'numeric test (negative case)');
});
neg = { a: 123.4 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid number', 'numeric test (negative case 2)');
});
test.finish();
};
exports['test_validate_lowercase'] = function(test, assert) {
var v = new V({
a: C().isLowercase()
});
// positive case
var obj = { a: 'abc' };
var obj_ext = { a: 'abc', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'lowercase test');
});
// negative case
var neg = { a: 'ABCabc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'lowercase test (negative case)');
});
test.finish();
};
exports['test_validate_uppercase'] = function(test, assert) {
var v = new V({
a: C().isUppercase()
});
// positive case
var obj = { a: 'ABC' };
var obj_ext = { a: 'ABC', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'uppercase test');
});
// negative case
var neg = { a: 'ABCabc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'uppercase test (negative case)');
});
test.finish();
};
exports['test_validate_decimal'] = function(test, assert) {
var v = new V({
a: C().isDecimal()
});
// positive case
var obj = { a: '123.123' };
var obj_ext = { a: 123.123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'decimal test');
});
obj = { a: '123.123' };
obj_ext = { a: '123.123', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'decimal test 2');
});
obj = { a: '-123.123' };
obj_ext = { a: -123.123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'decimal test 3');
});
// negative case
var neg = { a: 'ABCabc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid decimal', 'decimal test (negative case)');
});
test.finish();
};
exports['test_validate_float'] = function(test, assert) {
var v = new V({
a: C().isFloat()
});
// positive case
var obj = { a: 123.123 };
var obj_ext = { a: 123.123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'float test');
});
obj = { a: 123.123 };
obj_ext = { a: '123.123', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'float test 2');
});
obj = { a: -123.123 };
obj_ext = { a: '-123.123', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'float test 3');
});
// negative case
var neg = { a: 'ABCabc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid decimal', 'float test (negative case)');
});
test.finish();
};
exports['test_validate_notnull'] = function(test, assert) {
var v = new V({
a: C().notNull()
});
// positive case
var obj = { a: '1' };
var obj_ext = { a: '1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'notNull test');
});
// negative case
var neg = { a: '' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'notNull test (negative case)');
});
test.finish();
};
exports['test_validate_notempty'] = function(test, assert) {
var v = new V({
a: C().notEmpty()
});
// positive case
var obj = { a: '1' };
var obj_ext = { a: '1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'notEmpty test');
});
// negative case
var neg = { a: ' ' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'String is empty', 'notEmpty test (negative case)');
});
test.finish();
};
exports['test_validate_regex'] = function(test, assert) {
var v = new V({
a: C().regex('^a$')
});
// positive case
var obj = { a: 'a' };
var obj_ext = { a: 'a', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'regex test');
});
// negative case
var neg = { a: 'b' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'regex test (negative case)');
});
test.finish();
};
exports['test_validate_badregex'] = function(test, assert) {
var badValues = new Array('', null, undefined),
throwExceptions = 0;
for (i = 0; i < badValues.length; i++) {
var v = new V({
a: C().regex(badValues[i])
});
var obj = { a: 'sd@#$34f' };
try {
v.check(obj, function(err, cleaned) {});
} catch (x) {
throwExceptions++;
assert.deepEqual(x.message, 'No pattern provided', 'badregex test');
}
}
assert.equal(throwExceptions, badValues.length, 'badregex test');
test.finish();
};
exports['test_validate_notregex'] = function(test, assert) {
var v = new V({
a: C().notRegex(/e/)
});
// positive case
var obj = { a: 'foobar' };
var obj_ext = { a: 'foobar', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'notRegex test');
});
// negative case
var neg = { a: 'cheese' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'notRegex test (negative case)');
});
test.finish();
};
exports['test_validate_len'] = function(test, assert) {
var v = new V({
a: C().len(1, 2)
});
// positive case
var obj = { a: '1' };
var obj_ext = { a: '1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'len test');
});
// negative case
var neg = { a: '' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'String is not in range (1..2)', 'len test (negative case)');
});
neg = { a: 'abc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'String is not in range (1..2)', 'len test (negative case 2)');
});
test.finish();
};
exports['test_validate_null'] = function(test, assert) {
var v = new V({
a: C().isNull()
});
// positive case
var obj = { a: null };
var obj_ext = { a: null, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'null test');
});
obj = { a: '' };
obj_ext = { a: '', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'null test 2');
});
// negative case
var neg = { a: 'not null' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'null test (negative case)');
});
test.finish();
};
exports['test_validate_equals'] = function(test, assert) {
var v = new V({
a: C().equals(123)
});
// positive case
var obj = { a: 123 };
var obj_ext = { a: 123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'equals test');
});
obj_ext = { a: '123' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'equals test 2');
});
// negative case
var neg = { a: 'not 123' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Not equal', 'equals test (negative case)');
});
test.finish();
};
exports['test_validate_notEmpty'] = function(test, assert) {
var v = new V({
a: C().notEmpty()
});
// positive case
var obj = { a: 123 };
var obj_ext = { a: 123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'notEmpty test');
});
// negative case
var neg = { a: '', b: 2 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'String is empty', 'notEmpty test (negative case)');
});
test.finish();
};
exports['test_validate_missingKey'] = function(test, assert) {
var v = new V({
a: C().notEmpty()
});
// positive case
var obj = { a: 123 };
var obj_ext = { a: 123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'missingKey test');
});
// negative case
var neg = { b: 2 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Missing required key (a)', 'missingKey test (negative case)');
});
test.finish();
};
exports['test_validate_contains'] = function(test, assert) {
var v = new V({
a: C().contains('abc')
});
// positive case
var obj = { a: '0abc1'};
var obj_ext = { a: '0abc1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'contains test');
});
// negative case
var neg = { a: '123' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'contains test (negative case)');
});
test.finish();
};
exports['test_validate_not_contains'] = function(test, assert) {
var v = new V({
a: C().notContains('abc')
});
// positive case
var obj = { a: '123'};
var obj_ext = { a: '123', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'notContains test');
});
// negative case
var neg = { a: 'abc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'notContains test (negative case)');
});
test.finish();
};
exports['test_validate_notIn'] = function(test, assert) {
var v = new V({
a: C().notIn(['foo', 'bar'])
});
async.series([
function positiveCaseString(callback) {
var obj = { a: 'ponies'};
v.check(obj, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj);
callback();
});
},
function positiveCaseArray(callback) {
var obj = { a: ['ponies']};
v.check(obj, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj);
callback();
});
},
function positiveCaseObject(callback) {
var obj = { a: {'key': 'ponies'}};
v.check(obj, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj);
callback();
});
},
function negativeCaseString1(callback) {
var obj = { a: 'foo'};
v.check(obj, function(err, cleaned) {
assert.match(err.message, /Value foo is blacklisted/);
callback();
});
},
function negativeCaseString2(callback) {
var obj = { a: 'bar'};
v.check(obj, function(err, cleaned) {
assert.match(err.message, /Value bar is blacklisted/);
callback();
});
},
function negativeCaseArray(callback) {
var obj = { a: ['ponies', 'foo', 'unicorns']};
v.check(obj, function(err, cleaned) {
assert.match(err.message, /Value foo is blacklisted/);
callback();
});
},
function negativeCaseObject(callback) {
var obj = { a: {'key1': 'value1', 'key2': 'value2', 'ponies': 'ponies', 'foo': 'bar'}};
v.check(obj, function(err, cleaned) {
assert.match(err.message, /Value foo is blacklisted/);
callback();
});
}
], test.finish);
};
exports['test_validate_chain'] = function(test, assert) {
var v = new V({
a: C().len(1).isNumeric()
});
// positive case
var obj = { a: '1' };
var obj_ext = { a: '1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'chained validator test');
});
// negative case
var neg = { a: '' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'String is not in range (1..Infinity)', 'notContains test (negative case)');
});
// negative case
neg = { a: 'A' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid number', 'notContains test (negative case)');
});
test.finish();
};
exports['test_array_toInt'] = function(test, assert) {
var v = new V({
a: C().toInt()
});
// positive case
var obj = { a: 1 };
var obj_ext = { a: '1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'array test');
});
obj = { a: NaN };
obj_ext = { a: 'abc', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.ok(isNaN(cleaned.a), 'array test 2');
});
obj = { a: 1 };
obj_ext = { a: '1.23', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'array test 3');
});
test.finish();
};
exports['test_array_tofloat'] = function(test, assert) {
var v = new V({
a: C().isArray(C().isFloat().toFloat())
});
// positive case
var obj = { a: [3.145] };
var obj_ext = { a: ['3.145'], b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'array toFloat test');
});
// negative case
var neg = { a: 'abc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Not an array', 'array toFloat test (negative case)');
});
// negative case
neg = { a: ['abc', 'def'] };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid decimal', 'array toFloat test (negative case 2)');
});
test.finish();
};
exports['test_validate_string'] = function(test, assert) {
var v = new V({
a: C().isString()
});
// positive case
var obj = { a: 'test' };
var obj_ext = { a: 'test', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'string test');
});
// negative case
var neg = { a: 123, b: 2 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Not a string', 'string test (negative case)');
});
test.finish();
};
exports['test_validate_toBoolean'] = function(test, assert) {
var v = new V({
a: C().toBoolean()
});
// positive case
var obj = { a: true };
var obj_ext = { a: 'test', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test');
});
obj = { a: true };
obj_ext = { a: true, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 2');
});
obj = { a: true };
obj_ext = { a: 1, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 3');
});
obj = { a: false };
obj_ext = { a: 'false', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 4');
});
obj = { a: false };
obj_ext = { a: 0, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 5');
});
obj = { a: false };
obj_ext = { a: '', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 6');
});
obj = { a: false };
obj_ext = { a: false, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 7');
});
obj = { a: false };
obj_ext = { a: null, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 8');
});
test.finish();
};
exports['test_validate_toBooleanStrict'] = function(test, assert) {
var v = new V({
a: C().toBooleanStrict()
});
// positive case
var obj = { a: false };
var obj_ext = { a: 'test', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test');
});
obj = { a: true };
obj_ext = { a: true, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 2');
});
obj = { a: true };
obj_ext = { a: 1, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 3');
});
obj = { a: true };
obj_ext = { a: 'true', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 4');
});
obj = { a: false };
obj_ext = { a: 'false', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 5');
});
obj = { a: false };
obj_ext = { a: 0, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 6');
});
obj = { a: false };
obj_ext = { a: '', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 7');
});
obj = { a: false };
obj_ext = { a: false, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 8');
});
obj = { a: false };
obj_ext = { a: null, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 9');
});
test.finish();
};
exports['test_validate_entityDecode'] = function(test, assert) {
var v = new V({
a: C().entityDecode()
});
// positive case
var obj = { a: 'Smith & Wesson' };
var obj_ext = { a: 'Smith & Wesson', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'entityDecode test');
});
test.finish();
};
exports['test_validate_entityEncode'] = function(test, assert) {
var v = new V({
a: C().entityEncode()
});
// positive case
var obj = { a: 'Smith & Wesson' };
var obj_ext = { a: 'Smith & Wesson', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'entityEncode test');
});
test.finish();
};
exports['test_validate_trim'] = function(test, assert) {
var v = new V({
a: C().trim()
});
// positive case
var obj = { a: 'cheese' };
var obj_ext = { a: ' cheese ', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'trim test');
});
v = new V({
a: C().trim('QV')
});
obj = { a: 'cheese' };
obj_ext = { a: 'VQQcheeseQQV', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'trim test 2');
});
obj = { a: 'AcheeseA' };
obj_ext = { a: 'AcheeseA', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'trim test 2');
});
test.finish();
};
exports['test_validate_ltrim'] = function(test, assert) {
var v = new V({
a: C().ltrim()
});
// positive case
var obj = { a: 'cheese ' };
var obj_ext = { a: 'cheese ', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'ltrim test');
});
v = new V({
a: C().ltrim('QV')
});
obj = { a: 'cheeseQQV' };
obj_ext = { a: 'VQQcheeseQQV', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'ltrim test 2');
});
obj = { a: 'AcheeseA' };
obj_ext = { a: 'AcheeseA', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'ltrim test 2');
});
test.finish();
};
exports['test_validate_rtrim'] = function(test, assert) {
var v = new V({
a: C().rtrim()
});
// positive case
var obj = { a: ' cheese' };
var obj_ext = { a: ' cheese ', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'rtrim test');
});
v = new V({
a: C().rtrim('QV')
});
obj = { a: 'VQQcheese' };
obj_ext = { a: 'VQQcheeseVQQ', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'rtrim test 2');
});
obj = { a: 'AcheeseA' };
obj_ext = { a: 'AcheeseA', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'rtrim test 2');
});
test.finish();
};
exports['test_validate_ifNull'] = function(test, assert) {
var v = new V({
a: C().ifNull('foo')
});
// positive case
var obj = { a: 'foo' };
var obj_ext = { a: null, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'ifNull test');
});
test.finish();
};
exports['test_validate_nested_array'] = function(test, assert) {
var v = new V({
a: C().isArray(C().isString())
});
// positive case
var obj = { a: ['test'] };
var obj_ext = { a: ['test'], b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'array-of-strings test');
});
// negative case
var neg = { a: 'abc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Not an array', 'array-of-strings test (negative case)');
});
// negative case
neg = { a: [1, 2] };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Not a string', 'array-of-strings test (negative case 2)');
});
test.finish();
};
exports['test_validate_nested_hash'] = function(test, assert) {
var v = new V({
a: C().isHash(C().isString(), C().isString())
});
// positive case
var obj = { a: {'test' : 'test'} };
var obj_ext = { a: {'test' : 'test'}, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'hash test');
});
// negative case
var neg = { a: { 'test' : 123 } };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, "Value for key 'test': Not a string", 'hash test (negative case)');
});
test.finish();
};
exports['test_validate_enum'] = function(test, assert) {
var v = new V({
a: C().enumerated({inactive: 0, active: 1, full_no_new_checks: 2}).optional()
}),
obj = { a: 2 },
obj_ext = { a: 'full_no_new_checks', b: 2 },
neg = { a: 0 },
obj2 = { };
async.parallel([
function pos1(callback) {
// positive case
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'enum test');
callback();
});
},
function neg1(callback) {
// negative case 1
v.check(neg, function(err, cleaned) {
assert.match(err.message, /Invalid value '0'/, 'enum test (negative case 2)');
callback();
});
},
function pos2(callback) {
// negative case 1
v.check(obj2, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj2);
callback();
});
}
], function (err) {
test.finish();
});
};
exports['test_validate_enum_optional'] = function(test, assert) {
var v = new V({
a: C().enumerated({inactive: 0, active: 1, full_no_new_checks: 2})
});
// positive case
var obj = { a: 2 };
var obj_ext = { a: 'full_no_new_checks', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'enum test');
});
// negative case 1
var neg = { a: 'bogus_key' };
v.check(neg, function(err, cleaned) {
assert.match(err.message, /Invalid value 'bogus_key'/, 'enum test (negative case 1)');
});
// negative case 2
var neg = { a: 0 };
v.check(neg, function(err, cleaned) {
assert.match(err.message, /Invalid value '0'/, 'enum test (negative case 2)');
});
test.finish();
};
exports['test_validate_range'] = function(test, assert) {
var v = new V({
a: C().range(1, 65535)
});
// positive case
var obj = { a: 500 };
var obj_ext = { a: 500, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'range test (number)');
});
// negative case
var neg = { a: 65536 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, "Value out of range (1..65535)", 'range test (negative case)');
});
v = new V({
a: C().range('a', 'c')
});
// positive case
var obj = { a: 'b' };
var obj_ext = { a: 'b', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'range test (string)');
});
test.finish();
};
exports['test_optional_fields'] = function(test, assert) {
var v = new V({
a: C().optional().range(1, 65535)
});
// positive case
var obj = { a: 500 };
var obj_ext = { a: 500, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'optional fields test');
});
// positive case
obj = { };
obj_ext = { b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'optional fields test (missing)');
});
// negative case
var neg = { a: 65536 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, "Value out of range (1..65535)", 'optional fields test (negative case)');
});
test.finish();
};
exports['test_nested_schemas'] = function(test, assert) {
var v = new V({
a: { b: C().optional().range(1, 65535) }
});
// positive case
var obj = { a: { b: 500 } };
var obj_ext = { a: { b: 500}, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'nested schema test');
});
// negative case
var neg = { a: { b: 65536} };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, "Value out of range (1..65535)", 'nested schema test (negative case)');
assert.deepEqual(err.parentKeys, ['a'], 'nested schema test (negative case)');
});
test.finish();
};
exports['test_partial'] = function(test, assert) {
var v = new V({
a: C().isString(),
b: C().isInt()
});
async.parallel([
function(callback) {
var obj = { a: 'foo', b: 1 };
var obj_ext = { a: 'foo', b: 1 };
v.checkPartial(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'checkPartial test');
callback();
});
},
function(callback) {
var obj = { a: 'foo' };
var obj_ext = { a: 'foo' };
v.checkPartial(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'checkPartial test 2');
callback();
});
}
],
function(err) {
assert.ifError(err);
test.finish();
});
};
exports['test_partial_update_required'] = function(test, assert) {
var v = new V({
a: C().isString(),
b: C().updateRequired().isInt()
});
var neg = { a: 'foo' };
v.checkPartial(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Missing required key (b)', 'partial update required');
test.finish();
});
};
exports['test_partial_immutable'] = function(test, assert) {
var v = new V({
a: C().isString(),
b: C().immutable().isInt()
});
var neg = { a: 'bar', b: 1234 };
v.checkPartial(neg, function(err, cleaned) {
assert.ifError(err);
var existing = { a: 'foo', b: 1233, c: 'hello world' };
v.checkUpdate(existing, neg, function(err, cleaned) {
assert.ok(err);
assert.deepEqual(err.message, 'Attempted to mutate immutable field');
assert.equal(err.key, 'b');
assert.deepEqual(existing, {a: 'foo', b: 1233, c: 'hello world'});
test.finish();
});
});
};
exports['test_partial_immutable_unchanged'] = function(test, assert) {
var v = new V({
a: C().isString(),
b: C().immutable().isInt(),
c: C().isString()
});
var neg = { a: 'bar', b: 1234 };
v.checkPartial(neg, function(err, cleaned) {
assert.ifError(err);
var existing = { a: 'foo', b: 1234, c: 'hello world' };
v.checkUpdate(existing, neg, function(err, cleaned) {
assert.ok(!err);
assert.deepEqual(cleaned, {
a: 'bar',
b: 1234,
c: 'hello world'
});
assert.deepEqual(existing, {
a: 'foo',
b: 1234,
c: 'hello world'
});
test.finish();
});
});
};
exports['test_custom'] = function(test, assert) {
var description = 'Is the meaning of life';
V.addChainValidator('isMeaningOfLife',
description,
function(value, baton, callback) {
assert.deepEqual(baton, 'aBaton');
if (value == 42) {
callback(null, 'forty-two');
} else {
callback('incorrect value');
}
});
var v = new V({
a: C().custom('isMeaningOfLife')
});
var obj = { a: 'forty-two' };
var obj_ext = { a: 42, b: 'foo' };
assert.deepEqual(v.help().a[0], description, 'custom help');
v.baton = 'aBaton';
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'custom test');
});
var neg = { a: 43 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'incorrect value', 'custom test (negative case)');
});
assert.throws(function() {
var v = new V({
a: C().custom('bogus')
});
},
/Unknown validator name/,
'custom test (unknown validator)');
assert.throws(function() {
var v = new V({
a: C().custom()
});
},
/Missing/,
'custom test (missing validator)');
test.finish();
};
exports['test_custom_array_with_baton'] = function(test, assert) {
var description = 'Is the meaning of life';
V.addChainValidator('isMeaningOfLife',
description,
function(value, baton, callback) {
assert.deepEqual(baton, 'aBaton');
if (value == 42) {
callback(null, 'forty-two');
} else {
callback('incorrect value');
}
});
var v = new V({
a: C().optional().isArray(C().custom('isMeaningOfLife'))
});
var obj = { a: ['forty-two'] };
var obj_ext = { a: [42], b: 'foo' };
var neg = { a: [43] };
v.baton = 'aBaton';
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'incorrect value', 'custom test (negative case)');
});
assert.throws(function() {
var v = new V({
a: C().custom('bogus')
});
},
/Unknown validator name/,
'custom test (unknown validator)');
assert.throws(function() {
var v = new V({
a: C().custom()
});
},
/Missing/,
'custom test (missing validator)');
test.finish();
};
exports['test_final'] = function(test, assert) {
var v,
finalValidator;
v = new V({
v4: C().optional(),
v6: C().optional()
});
finalValidator = function(obj, callback) {
if ((! obj.v4) && (! obj.v6)) {
callback({
key: 'v4',
parentKeys: null,
message: 'At least one of v4 or v6 must be specified'
});
} else
callback(null, obj);
};
v.addFinalValidator(finalValidator);
var obj = { v4: '1.2.3.4' };
var obj_ext = { v4: '1.2.3.4', b: 'foo' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'final validator test 1');
});
obj = { v6: '1.2.3.4' };
obj_ext = { v6: '1.2.3.4', b: 'foo' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'final validator test 2');
});
obj = { v4: '1.2.3.4', v6: '1.2.3.4' };
obj_ext = { v4: '1.2.3.4', v6: '1.2.3.4', b: 'foo' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'final validator test 3');
});
var neg = { b: 'foo' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message,
'At least one of v4 or v6 must be specified',
'final validator test (negative case)');
});
test.finish();
};
exports['test_schema_translation_1'] = function(test, assert) {
var validity = swiz.defToValve(def),
v = new V(validity.Node);
assert.isDefined(validity.Node);
assert.isDefined(validity.NodeOpts);
v.check(exampleNode, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, compNode, 'schema translation');
v.check(badExampleNode, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP',
'schama translation failure');
test.finish();
});
});
};
exports['test_schema_translation_2'] = function(test, assert) {
var validity = swiz.defToValve(def),
v = new V(validity.Node);
assert.isDefined(validity.Node);
assert.isDefined(validity.NodeOpts);
v.check(badExampleNode1, function(err, cleaned) {
assert.deepEqual(err.message, 'Missing required key (agent_name)',
'schama translation failure (missing agent_key)');
test.finish();
});
};
exports['test_schema_translation_enumerated'] = function(test, assert) {
var validity = swiz.defToValve(def),
v = new V(validity.Node2);
v.check(exampleNode2, function(err, cleaned) {
assert.ifError(err);
assert.equal(cleaned.state, 1);
test.finish();
});
};
exports['test_roundtrip_json_swiz_valve'] = function(test, assert) {
var validity = swiz.defToValve(def),
v = new V(validity.Node),
obj, sw = new swiz.Swiz(def);
v.check(exampleNode, function(err, cleaned) {
assert.ifError(err);
obj = cleaned;
obj.getSerializerType = function() {return 'Node';};
sw.serialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, obj,
function(err, results) {
assert.ifError(err);
sw.deserialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, results, function(err, newObj) {
assert.deepEqual(newObj, exampleNode, 'Round trip json swiz/valve test');
assert.ifError(err);
test.finish();
});
});
});
};
exports['test_roundtrip_xml_swiz_valve'] = function(test, assert) {
var validity = swiz.defToValve(def),
v = new V(validity.Node),
obj, sw = new swiz.Swiz(def);
v.check(exampleNode, function(err, cleaned) {
assert.ifError(err);
obj = cleaned;
obj.getSerializerType = function() {return 'Node';};
sw.serialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, obj,
function(err, xml) {
assert.ifError(err);
sw.deserialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, xml, function(err, newObj) {
assert.deepEqual(newObj, exampleNode, 'Round trip json swiz/valve test');
assert.ifError(err);
test.finish();
});
});
});
};
exports['test_xml_with_whitespace'] = function(test, assert) {
var validity = swiz.defToValve(def),
v = new V(validity.Node),
testxml,
obj, sw = new swiz.Swiz(def);
testxml = sw.deserializeXml('<?xml version="1.0" encoding="utf-8"?><node id="xkCD366" name="exmample"> <is_active>true</is_active><agent_name>your mom</agent_name><ipaddress>42.24.42.24</ipaddress></node>');
v.check(testxml, function(err, cleaned) {
assert.ifError(err);
obj = cleaned;
obj.getSerializerType = function() {return 'Node';};
sw.serialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, obj,
function(err, xml) {
assert.ifError(err);
sw.deserialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, xml, function(err, newObj) {
assert.deepEqual(newObj, exampleNode, 'Round trip json swiz/valve test');
assert.ifError(err);
test.finish();
});
});
});
};
exports['test_boolean'] = function(test, assert) {
var v = new V({
a: C().isBoolean()
});
// positive case
var obj = { a: true };
var obj_ext = { a: 1 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'boolean test');
});
// negative case
var neg = { a: 'notFalse' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, "Not a boolean", 'boolean test');
});
test.finish();
};
exports['test_inArray'] = function(test, assert) {
var v = new V({
a: new C().inArray([1, 2, 3, 4, 5])
});
// positive case
var pos = { a: 1 };
v.check(pos, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, pos, 'isArray test');
});
// negative case
var neg = { a: -1 };
v.check(neg, function(err, cleaned) {
assert.match(err.message, /Invalid value '-1'. Should be one of/, 'inArray test');
});
test.finish();
};
exports['test_port'] = function(test, assert) {
var v = new V({
a: new C().isPort()
});
// positive case
var pos = { a: 1 };
v.check(pos, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, pos, 'isPort test');
});
// negative case
var neg = { a: -1 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, "Value out of range [1,65535]", 'isPort test');
});
test.finish();
};
exports['test_V1UUID'] = function(test, assert) {
var v = new V({
a: new C().isV1UUID()
});
async.series([
function(callback) {
// positive case
var pos = { a: '4b299c10-ab5a-11e1-9f6f-1c8b12469d15' };
v.check(pos, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, pos, 'isV1UUID test');
callback();
});
},
function(callback) {
// negative case 0
var neg0 = { a: 'b299c10-ab5a-11e1-9f6f-1c8b12469d15' };
v.check(neg0, function(err, cleaned) {
assert.deepEqual(err.message, "Invalid UUID", 'isV1UUID test');
callback();
});
},
function(callback) {
// negative case 1
var neg1 = { a: '4@299c10-ab5a-11e1-9f6f-1c8b12469d15' };
v.check(neg1, function(err, cleaned) {
assert.deepEqual(err.message, "Invalid UUID", 'isV1UUID test');
callback();
});
},
function(callback) {
//negative case 2
var neg2 = { a : '4b299c10-ab5a-11e1-4f6f-1c8b12469d15' };
v.check(neg2, function(err, cleaned) {
assert.deepEqual(err.message, "Unsupported UUID variant", 'isV1UUID test');
callback();
});
},
function(callback) {
//negative case 3
var neg3 = { a : '4b299c10-ab5a-21e1-9f6f-1c8b12469d15' };
v.check(neg3, function(err, cleaned) {
assert.deepEqual(err.message, "UUID is not version 1", 'isV1UUID test');
callback();
});
}
],
function(err) {
test.finish();
});
};
exports['test_getValidatorPos_hasValidator_and_getValidatorAtPos'] = function(test, assert) {
var v = new V({
a: C().len(1).isNumeric(),
b: C().len(1).isNumeric().optional()
});
assert.equal(v.schema.a.getValidatorPos('len'), 0);
assert.equal(v.schema.a.getValidatorPos('isNumeric'), 1);
assert.equal(v.schema.a.getValidatorPos('inArray'), -1);
assert.ok(v.schema.a.hasValidator('len'));
assert.ok(v.schema.a.hasValidator('isNumeric'));
assert.ok(!v.schema.a.hasValidator('inArray'));
assert.equal(v.schema.b.getValidatorPos('optional'), 2);
assert.ok(v.schema.b.hasValidator('optional'));
assert.equal(v.schema.b.getValidatorAtPos(2).name, 'optional');
assert.equal(v.schema.b.getValidatorAtPos(6), null);
test.finish();
};
exports['test_optional_string'] = function(test, assert) {
var v = new V({
a: new C().optional().isString().len(1, 5)
});
async.series([
function check1(callback) {
var pos1 = {a: 'abc'};
v.check(pos1, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, pos1);
callback();
});
},
function checknull(callback) {
var pos2 = {a: null};
v.check(pos2, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, pos2);
callback();
});
}
],
function(err) {
test.finish();
});
};
| tests/test-valve.js | /*
* Copyright 2011 Rackspace
*
* 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.
*
*/
var swiz = require('../lib/swiz');
var async = require('async');
var V = swiz.Valve;
var C = swiz.Chain;
var O = swiz.struct.Obj;
var F = swiz.struct.Field;
// Mock set of serialization defs
var def = [
O('Node',
{
'fields': [
F('id', {'src': 'hash_id', 'desc': 'hash ID for the node', 'attribute': true,
'val' : C().isString()}),
F('is_active', {'src': 'active', 'desc': 'is the node active?',
'val' : C().toBoolean(), 'coerceTo' : 'boolean'}),
F('name', {'src' : 'get_name', 'desc' : 'name', 'attribute': true,
'val' : C().isString()}),
F('agent_name', {'val' : C().isString().notEmpty()}),
F('ipaddress' , {'src' : 'get_public_address', 'val' : C().isIP()})
],
'plural': 'nodes'
}),
O('Node2',
{
'fields': [
F('id', {'src': 'hash_id', 'desc': 'hash ID for the node', 'attribute': true,
'val' : C().isString()}),
F('is_active', {'src': 'active', 'desc': 'is the node active?',
'val' : C().toBoolean(), 'coerceTo' : 'boolean'}),
F('name', {'src' : 'get_name', 'desc' : 'name', 'attribute': true,
'val' : C().isString()}),
F('agent_name', {'val' : C().isString().notEmpty()}),
F('state', {'enumerated' : {inactive: 0, active: 1, full_no_new_checks: 2}}),
F('ipaddress' , {'src' : 'get_public_address', 'val' : C().isIP()})
],
'plural': 'nodes'
}),
O('NodeOpts',
{
'fields': [
F('option1', {'src': 'opt1', 'val' : C().isString()}),
F('option2', {'src': 'opt2', 'val' : C().isString()}),
F('option3', {'src': 'opt3', 'val' : C().isString()}),
]
}),
];
var exampleNode = {
'id' : 'xkCD366',
'is_active' : true,
'name' : 'exmample',
'agent_name' : 'your mom',
'ipaddress' : '42.24.42.24'
};
var exampleNode2 = {
'id' : 'xkCD366',
'is_active' : true,
'name' : 'exmample',
'agent_name' : 'your mom',
'state': 'active',
'ipaddress' : '42.24.42.24'
};
var compNode = {
'hash_id' : 'xkCD366',
'active' : true,
'get_name' : 'exmample',
'agent_name' : 'your mom',
'get_public_address' : '42.24.42.24'
};
var badExampleNode = {
'id' : 'xkCD366',
'is_active' : true,
'name' : 'exmample',
'agent_name' : 'your mom',
'ipaddress' : '42'
};
var badExampleNode1 = {
'id' : 'xkCD366',
'is_active' : true,
'name' : 'exmample',
'ipaddress' : '42.24.42.24'
};
exports['test_validate_numItems'] = function(test, assert) {
var v1, v2, v3;
v1 = new V({
a: C().isArray(C().isInt()).numItems(1, 5)
});
v2 = new V({
a: C().isHash(C().isString(), C().notEmpty()).numItems(1, 5)
});
v3 = new V({
a: C().isArray(C().isInt()).numItems(2)
});
// Negative test cases (array)
v1.check({'a': [1]}, function(err, cleaned) {
assert.ifError(err);
});
v1.check({'a': [1, 2, 3, 4, 5]}, function(err, cleaned) {
assert.ifError(err);
});
v3.check({'a': [1, 2]}, function(err, cleaned) {
assert.ifError(err);
});
// Positive case (array)
v3.check({'a': [1]}, function(err, cleaned) {
assert.ok(err);
assert.match(err.message, /Object needs to have between 2 and Infinity items/);
});
// Positive test cases (array)
v1.check({'a': []}, function(err, cleaned) {
assert.ok(err);
assert.match(err.message, /Object needs to have between 1 and 5 items/);
});
v1.check({'a': [1, 2, 3, 4, 5, 6]}, function(err, cleaned) {
assert.ok(err);
assert.match(err.message, /Object needs to have between 1 and 5 items/);
});
// Negative test cases (object)
v2.check({'a': {'a': 1}}, function(err, cleaned) {
assert.ifError(err);
});
v2.check({'a': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'f': 5}}, function(err, cleaned) {
assert.ifError(err);
});
// Positive test cases (object)
v2.check({'a': {}}, function(err, cleaned) {
assert.ok(err);
assert.match(err.message, /Object needs to have between 1 and 5 items/);
});
v2.check({'a': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'f': 5, 'g': 6}}, function(err, cleaned) {
assert.ok(err);
assert.match(err.message, /Object needs to have between 1 and 5 items/);
});
test.finish();
};
exports['test_validate_int'] = function(test, assert) {
var v = new V({
a: C().isInt()
});
// positive case
var obj = { a: 1 };
var obj_ext = { a: 1, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'integer test');
});
obj = { a: '1' };
obj_ext = { a: '1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'integer test 2');
});
obj = { a: -17 };
obj_ext = { a: -17, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'integer test 3');
});
// negative case
var neg = { a: 'test' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid integer', 'integer test (negative case)');
});
test.finish();
};
exports['test_check_strict_mode'] = function(test, assert) {
var v = new V({
a: C().isInt()
});
async.series([
function pos1(callback) {
var obj = {'a': 5};
v.check(obj, {'strict': true}, function(err, cleaned) {
assert.ifError(err);
callback();
});
},
function neg1(callback) {
var obj = {'a': 5, 'b': 5};
v.check(obj, {'strict': true}, function(err, cleaned) {
assert.ok(err);
assert.equal(err.key, 'b');
assert.match(err.message, /This key is not allowed/);
callback();
});
}
],
function(err) {
test.finish();
});
};
exports['test_transformation_validator'] = function(test, assert) {
var v = new V({
a: C().isInt().toInt().optional()
});
var obj = { a: '10' };
v.check(obj, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, {'a': 10});
test.finish();
});
};
exports['test_isUnique'] = function(test, assert) {
var v = new V({
a: C().isUnique()
});
// positive case
var obj1 = { a: [1, 2, 3, 4, 5] };
var obj2 = { a: [9, 2, 3, 4, 5] };
v.check(obj1, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj1);
});
v.check(obj2, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj2);
});
// negative case
var obj1Neg = { a: {} };
var obj2Neg = { a: [2, 2, 3, 4, 5] };
v.check(obj1Neg, function(err, cleaned) {
assert.ok(err);
});
v.check(obj2Neg, function(err, cleaned) {
assert.ok(err);
});
test.finish();
};
exports['test_toUnique'] = function(test, assert) {
var v = new V({
a: C().toUnique()
});
var failed = false;
// positive case
var obj1 = { a: [1, 2, 3, 4, 5] };
var obj2 = { a: [9, 2, 3, 4, 5] };
v.check(obj1, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj1);
});
v.check(obj2, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj2);
});
// negative case
var obj1Neg = { a: {} };
var obj2Neg = { a: [2, 2, 3, 3, 3, 3, 4, 5] };
v.check(obj1Neg, function(err, cleaned) {
assert.ok(err);
});
v.check(obj2Neg, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, {a: [2, 3, 4, 5]});
});
test.finish();
};
exports['test_validate_email'] = function(test, assert) {
var v = new V({
a: C().isEmail()
});
// positive case
var obj = { a: '[email protected]' };
var obj_ext = { a: '[email protected]', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'email test');
});
// negative case
var neg = { a: 'invalidemail@' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid email', 'integer test (negative case)');
});
test.finish();
};
exports['test_validate_url'] = function(test, assert) {
var v = new V({
a: C().isUrl()
});
// positive case
var obj = { a: 'http://www.cloudkick.com' };
var obj_ext = { a: 'http://www.cloudkick.com', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'URL test');
});
// negative case
var neg = { a: 'invalid/' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid URL', 'URL test (negative case)');
});
test.finish();
};
exports['test_validate_ipv6'] = function(test, assert) {
var v = new V({
a: C().isIPv6()
});
// positive case
var obj = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
var obj_ext = { a: '2001:0db8:0000:0000:0001:0000:0000:0001', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'IPv6 test');
});
// negative case
var neg = { a: '127.0.0.2' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IPv6', 'IPv6 test (negative case)');
});
neg = {a: '12345' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IPv6', 'IPv6 test (negative case 2)');
});
test.finish();
};
exports['test_validate_hostname'] = function(test, assert) {
var v = new V({
a: C().isHostname()
});
// positive case
var obj1 = { a: 'foo1-bar-2-ck.com' };
var obj2 = { a: 'rackspace.com' };
async.series([
function pos1(callback) {
v.check(obj1, function(err, cleaned) {
assert.ifError(err);
callback();
});
},
function pos2(callback) {
v.check(obj2, function(err, cleaned) {
assert.ifError(err);
callback();
});
},
function neg1(callback) {
var neg = { a: 'hostname.' };
v.check(neg, function(err, cleaned) {
assert.ok(err);
callback();
});
},
function neg2(callback) {
var neg = { a: 'hostname.' };
v.check(neg, function(err, cleaned) {
assert.ok(err);
callback();
});
}
],
function(err) {
test.finish();
});
};
exports['test_isHostnameOrIp'] = function(test, assert) {
var v = new V({
a: C().isHostnameOrIp()
});
async.series([
function pos1(callback) {
var obj = { 'a': '127.0.0.1' };
v.check(obj, function(err, cleaned) {
assert.ifError(err);
callback();
});
},
function pos2(callback) {
var obj = { 'a': '2001:0db8:0000:0000:0001:0000:0000:0001' };
v.check(obj, function(err, cleaned) {
assert.ifError(err);
callback();
});
},
function pos4(callback) {
var obj = { 'a': 'github.com' };
v.check(obj, function(err, cleaned) {
assert.ifError(err);
callback();
});
},
function neg1(callback) {
var neg = { a: 'hostname.' };
v.check(neg, function(err, cleaned) {
assert.ok(err);
callback();
});
}
],
function(err) {
test.finish();
});
};
exports['test_validate_ipv4'] = function(test, assert) {
var v = new V({
a: C().isIPv4()
});
// positive case
var obj = { a: '192.168.0.1' };
var obj_ext = { a: '192.168.0.1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'IP test');
});
// negative case
var neg = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IPv4', 'IPv4 test (negative case)');
});
neg = {a: '12345' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IPv4', 'IPv4 test (negative case 2)');
});
test.finish();
};
exports['test_validate_isAddressPair'] = function(test, assert) {
var v = new V({
a: C().isAddressPair()
});
var obj, obj_ext;
// positive case 1
obj = { a: '192.168.0.1:1111' };
obj_ext = { a: '192.168.0.1:1111' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'isAddressPair test');
});
// positive case 2
obj = { a: '0000:0000:0000:0000:0000:0000:0000:0001:22222' };
obj_ext = { a: '::1:22222' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'isAddressPair test');
});
// negative case 1
obj_ext = { a: '127.0.0.1' };
v.check(obj_ext, function(err, cleaned) {
assert.match(err.message, /Missing semicolon/);
});
// negative case 2
obj_ext = { a: 'a.b:4444' };
v.check(obj_ext, function(err, cleaned) {
assert.match(err.message, /IP address in the address pair is not valid/);
});
// negative case 3
obj_ext = { a: '127.0.0.1:444444' };
v.check(obj_ext, function(err, cleaned) {
assert.match(err.message, /Port in the address pair is out of range/);
});
test.finish();
// positive case 2
};
exports['test_validate_ip'] = function(test, assert) {
var v = new V({
a: C().isIP()
});
// positive test cases
var expected = { a: '192.168.0.1' };
var provided = { a: '192.168.0.1', b: 2 };
v.check(provided, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept dotted-quad syntax for IPv4 addresses');
});
expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
provided = { a: '2001:0db8:0000:0000:0001:0000:0000:0001', b: 2 };
v.check(provided, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a coloned-octet syntax for IPv6 addresses');
});
expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
provided = { a: '2001:0db8::0001:0000:0000:0001', b: 2 };
v.check(provided, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a shortened syntax for IPv6 addresses');
});
expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
provided = { a: '2001:0db8:0000:0000:0001::0001', b: 2 };
v.check(provided, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a shortened syntax for IPv6 addresses');
});
expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
provided = { a: '2001:db8:0:0:1:0:0:1', b: 2 };
v.check(provided, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a coloned-octet syntax with leading zeros blanked for IPv6 addresses');
});
expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
provided = { a: '2001:db8::1:0:0:1', b: 2 };
v.check(provided, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a shortened syntax with leading zeros blanked for IPv6 addresses');
});
expected = { a: '1234:0000:0000:0000:0000:0000:0000:0000' };
provided = { a: '1234::', b: 2 };
v.check(provided, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a tail-truncated address for IPv6 addresses');
});
expected = { a: '0000:0000:0000:0000:0000:0000:0000:1234' };
provided = { a: '::1234', b: 2 };
v.check(provided, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a head-truncated address for IPv6 addresses');
});
expected = { a: '0000:0000:0000:0000:0000:0000:0000:0000' };
provided = { a: '::', b: 2 };
v.check(provided, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept a nil IPv6 address');
});
expected = { a: '0000:0000:0000:0000:0000:0000:7f00:0001' };
provided = { a: '::7F00:0001', b: 2 };
v.check(provided, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept an IPv6 address with capital letters');
});
expected = { a: '0000:0000:0000:0000:0000:0000:7f00:0001' };
provided = { a: '::127.0.0.1', b: 2 };
v.check(provided, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, expected, 'isIP should accept an IPv4 address embedded in an IPv6 address');
});
// negative test cases
var provided = { a: 'invalid/' };
v.check(provided, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', 'IP test (negative case)');
});
provided = {a: '12345' };
v.check(provided, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', 'IP test (negative case 2)');
});
provided = {a: {b: null} };
v.check(provided, function(err, cleaned) {
assert.deepEqual(err.message, 'IP address is not a string', 'IP test (negative case 3)');
});
provided = {a: '2001:0db8:0:0:1:0:0:127.0.0.1'};
v.check(provided, function(err, cleaned) {
assert.deepEqual(err.message, 'Incorrect number of groups found', 'Malformed IPv6 address w/ embedded IPv4 address');
});
provided = {a: '2001:0db8::1::1' };
v.check(provided, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', 'IPv6 can only have at most one "::" symbol in it.');
});
provided = {a: '2001:0db8:0000:0000:0001:0000:0000'};
v.check(provided, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', 'IPv6 coloned-octet notation requires eight hex words.');
});
provided = {a: '2001:0db8::1:0:0:00001' };
v.check(provided, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', 'IPv6 hex groups can be at most 4 characters long.');
});
var stack_attack = "";
var possible = "0123456789.:";
for(var i=0; i < 1048576; i++) {
stack_attack += possible.charAt(Math.floor(Math.random()*possible.length));
}
stack_attack = '1'+stack_attack; // Make sure it starts with a digit
provided = {a: stack_attack};
v.check(provided, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', 'Stack overflow attacks, to 1MB, should be rejected out of hand.');
});
provided = {a: '2001:0db8:0:0:1:0:0:'+stack_attack};
v.check(provided, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', 'Stack overflow attacks, to 1MB, should be rejected out of hand.');
});
provided = {a: '192.168.0.'+stack_attack};
v.check(provided, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', 'Stack overflow attacks, to 1MB, should be rejected out of hand.');
});
test.finish();
};
exports['test_validate_ip_blacklist'] = function(test, assert) {
var v = new V({
a: C().isIP().notIPBlacklisted()
});
// positive case
var obj_ext = { a: '173.45.245.32', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err, 'IP blacklist test');
});
// negative case
var neg = { a: 'invalid/' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', 'IP test (negative case 2)');
});
neg = { a: '192.168.0.1' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'IP is blacklisted', 'IP test (negative case 2)');
});
// IPv6
obj_ext = { a: '2001:db8::1:0:0:1'};
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err, 'IPv6 blacklist test');
});
neg = {a: 'fc00:1:0:0:1' };
v.check(neg, function(err, cleaned) {
assert.match(err.message, /Invalid IP/, 'IP test (negative case 2)');
});
test.finish();
};
exports['test_validate_cidr'] = function(test, assert) {
var v = new V({
a: C().isCIDR()
});
// positive case
var obj = { a: '192.168.0.1/2' };
var obj_ext = { a: '192.168.0.1/2', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'CIDR test');
});
// negative case
var neg = { a: 'invalid/' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP', 'CIDR test (negative case)');
});
neg = { a: '192.168.0.1/128' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid subnet length', 'CIDR test (negative case 2)');
});
// IPv6 normalization
obj_ext = { a: '2001:db8::1:0:0:1/3'};
obj = { a: '2001:0db8:0000:0000:0001:0000:0000:0001/3' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'IPv6 CIDR test');
});
neg = { a: '2001:db8::1:0:0:1/194' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid subnet length', 'IPv6 CIDR test (negative case)');
});
test.finish();
};
exports['test_validate_alpha'] = function(test, assert) {
var v = new V({
a: C().isAlpha()
});
// positive case
var obj = { a: 'ABC' };
var obj_ext = { a: 'ABC', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'alpha test');
});
// negative case
var neg = { a: 'invalid/' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'alpha test (negative case)');
});
test.finish();
};
exports['test_validate_alphanumeric'] = function(test, assert) {
var v = new V({
a: C().isAlphanumeric()
});
// positive case
var obj = { a: 'ABC123' };
var obj_ext = { a: 'ABC123', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'alphanumeric test');
});
// negative case
var neg = { a: 'invalid/' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'alphanumeric test (negative case)');
});
test.finish();
};
exports['test_validate_numeric'] = function(test, assert) {
var v = new V({
a: C().isNumeric()
});
// positive case
var obj = { a: '123' };
var obj_ext = { a: 123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'numeric test');
});
obj_ext = { a: '123', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'numeric test 2');
});
// negative case
var neg = { a: '/' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid number', 'numeric test (negative case)');
});
neg = { a: 123.4 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid number', 'numeric test (negative case 2)');
});
test.finish();
};
exports['test_validate_lowercase'] = function(test, assert) {
var v = new V({
a: C().isLowercase()
});
// positive case
var obj = { a: 'abc' };
var obj_ext = { a: 'abc', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'lowercase test');
});
// negative case
var neg = { a: 'ABCabc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'lowercase test (negative case)');
});
test.finish();
};
exports['test_validate_uppercase'] = function(test, assert) {
var v = new V({
a: C().isUppercase()
});
// positive case
var obj = { a: 'ABC' };
var obj_ext = { a: 'ABC', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'uppercase test');
});
// negative case
var neg = { a: 'ABCabc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'uppercase test (negative case)');
});
test.finish();
};
exports['test_validate_decimal'] = function(test, assert) {
var v = new V({
a: C().isDecimal()
});
// positive case
var obj = { a: '123.123' };
var obj_ext = { a: 123.123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'decimal test');
});
obj = { a: '123.123' };
obj_ext = { a: '123.123', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'decimal test 2');
});
obj = { a: '-123.123' };
obj_ext = { a: -123.123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'decimal test 3');
});
// negative case
var neg = { a: 'ABCabc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid decimal', 'decimal test (negative case)');
});
test.finish();
};
exports['test_validate_float'] = function(test, assert) {
var v = new V({
a: C().isFloat()
});
// positive case
var obj = { a: 123.123 };
var obj_ext = { a: 123.123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'float test');
});
obj = { a: 123.123 };
obj_ext = { a: '123.123', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'float test 2');
});
obj = { a: -123.123 };
obj_ext = { a: '-123.123', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'float test 3');
});
// negative case
var neg = { a: 'ABCabc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid decimal', 'float test (negative case)');
});
test.finish();
};
exports['test_validate_notnull'] = function(test, assert) {
var v = new V({
a: C().notNull()
});
// positive case
var obj = { a: '1' };
var obj_ext = { a: '1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'notNull test');
});
// negative case
var neg = { a: '' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'notNull test (negative case)');
});
test.finish();
};
exports['test_validate_notempty'] = function(test, assert) {
var v = new V({
a: C().notEmpty()
});
// positive case
var obj = { a: '1' };
var obj_ext = { a: '1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'notEmpty test');
});
// negative case
var neg = { a: ' ' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'String is empty', 'notEmpty test (negative case)');
});
test.finish();
};
exports['test_validate_regex'] = function(test, assert) {
var v = new V({
a: C().regex('^a$')
});
// positive case
var obj = { a: 'a' };
var obj_ext = { a: 'a', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'regex test');
});
// negative case
var neg = { a: 'b' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'regex test (negative case)');
});
test.finish();
};
exports['test_validate_badregex'] = function(test, assert) {
var badValues = new Array('', null, undefined),
throwExceptions = 0;
for (i = 0; i < badValues.length; i++) {
var v = new V({
a: C().regex(badValues[i])
});
var obj = { a: 'sd@#$34f' };
try {
v.check(obj, function(err, cleaned) {});
} catch (x) {
throwExceptions++;
assert.deepEqual(x.message, 'No pattern provided', 'badregex test');
}
}
assert.equal(throwExceptions, badValues.length, 'badregex test');
test.finish();
};
exports['test_validate_notregex'] = function(test, assert) {
var v = new V({
a: C().notRegex(/e/)
});
// positive case
var obj = { a: 'foobar' };
var obj_ext = { a: 'foobar', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'notRegex test');
});
// negative case
var neg = { a: 'cheese' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'notRegex test (negative case)');
});
test.finish();
};
exports['test_validate_len'] = function(test, assert) {
var v = new V({
a: C().len(1, 2)
});
// positive case
var obj = { a: '1' };
var obj_ext = { a: '1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'len test');
});
// negative case
var neg = { a: '' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'String is not in range (1..2)', 'len test (negative case)');
});
neg = { a: 'abc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'String is not in range (1..2)', 'len test (negative case 2)');
});
test.finish();
};
exports['test_validate_null'] = function(test, assert) {
var v = new V({
a: C().isNull()
});
// positive case
var obj = { a: null };
var obj_ext = { a: null, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'null test');
});
obj = { a: '' };
obj_ext = { a: '', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'null test 2');
});
// negative case
var neg = { a: 'not null' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'null test (negative case)');
});
test.finish();
};
exports['test_validate_equals'] = function(test, assert) {
var v = new V({
a: C().equals(123)
});
// positive case
var obj = { a: 123 };
var obj_ext = { a: 123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'equals test');
});
obj_ext = { a: '123' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'equals test 2');
});
// negative case
var neg = { a: 'not 123' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Not equal', 'equals test (negative case)');
});
test.finish();
};
exports['test_validate_notEmpty'] = function(test, assert) {
var v = new V({
a: C().notEmpty()
});
// positive case
var obj = { a: 123 };
var obj_ext = { a: 123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'notEmpty test');
});
// negative case
var neg = { a: '', b: 2 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'String is empty', 'notEmpty test (negative case)');
});
test.finish();
};
exports['test_validate_missingKey'] = function(test, assert) {
var v = new V({
a: C().notEmpty()
});
// positive case
var obj = { a: 123 };
var obj_ext = { a: 123, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'missingKey test');
});
// negative case
var neg = { b: 2 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Missing required key (a)', 'missingKey test (negative case)');
});
test.finish();
};
exports['test_validate_contains'] = function(test, assert) {
var v = new V({
a: C().contains('abc')
});
// positive case
var obj = { a: '0abc1'};
var obj_ext = { a: '0abc1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'contains test');
});
// negative case
var neg = { a: '123' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'contains test (negative case)');
});
test.finish();
};
exports['test_validate_not_contains'] = function(test, assert) {
var v = new V({
a: C().notContains('abc')
});
// positive case
var obj = { a: '123'};
var obj_ext = { a: '123', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'notContains test');
});
// negative case
var neg = { a: 'abc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid characters', 'notContains test (negative case)');
});
test.finish();
};
exports['test_validate_notIn'] = function(test, assert) {
var v = new V({
a: C().notIn(['foo', 'bar'])
});
async.series([
function positiveCaseString(callback) {
var obj = { a: 'ponies'};
v.check(obj, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj);
callback();
});
},
function positiveCaseArray(callback) {
var obj = { a: ['ponies']};
v.check(obj, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj);
callback();
});
},
function positiveCaseObject(callback) {
var obj = { a: {'key': 'ponies'}};
v.check(obj, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj);
callback();
});
},
function negativeCaseString1(callback) {
var obj = { a: 'foo'};
v.check(obj, function(err, cleaned) {
assert.match(err.message, /Value foo is blacklisted/);
callback();
});
},
function negativeCaseString2(callback) {
var obj = { a: 'bar'};
v.check(obj, function(err, cleaned) {
assert.match(err.message, /Value bar is blacklisted/);
callback();
});
},
function negativeCaseArray(callback) {
var obj = { a: ['ponies', 'foo', 'unicorns']};
v.check(obj, function(err, cleaned) {
assert.match(err.message, /Value foo is blacklisted/);
callback();
});
},
function negativeCaseObject(callback) {
var obj = { a: {'key1': 'value1', 'key2': 'value2', 'ponies': 'ponies', 'foo': 'bar'}};
v.check(obj, function(err, cleaned) {
assert.match(err.message, /Value foo is blacklisted/);
callback();
});
}
], test.finish);
};
exports['test_validate_chain'] = function(test, assert) {
var v = new V({
a: C().len(1).isNumeric()
});
// positive case
var obj = { a: '1' };
var obj_ext = { a: '1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'chained validator test');
});
// negative case
var neg = { a: '' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'String is not in range (1..Infinity)', 'notContains test (negative case)');
});
// negative case
neg = { a: 'A' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid number', 'notContains test (negative case)');
});
test.finish();
};
exports['test_array_toInt'] = function(test, assert) {
var v = new V({
a: C().toInt()
});
// positive case
var obj = { a: 1 };
var obj_ext = { a: '1', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'array test');
});
obj = { a: NaN };
obj_ext = { a: 'abc', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.ok(isNaN(cleaned.a), 'array test 2');
});
obj = { a: 1 };
obj_ext = { a: '1.23', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'array test 3');
});
test.finish();
};
exports['test_array_tofloat'] = function(test, assert) {
var v = new V({
a: C().isArray(C().isFloat().toFloat())
});
// positive case
var obj = { a: [3.145] };
var obj_ext = { a: ['3.145'], b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'array toFloat test');
});
// negative case
var neg = { a: 'abc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Not an array', 'array toFloat test (negative case)');
});
// negative case
neg = { a: ['abc', 'def'] };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid decimal', 'array toFloat test (negative case 2)');
});
test.finish();
};
exports['test_validate_string'] = function(test, assert) {
var v = new V({
a: C().isString()
});
// positive case
var obj = { a: 'test' };
var obj_ext = { a: 'test', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'string test');
});
// negative case
var neg = { a: 123, b: 2 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Not a string', 'string test (negative case)');
});
test.finish();
};
exports['test_validate_toBoolean'] = function(test, assert) {
var v = new V({
a: C().toBoolean()
});
// positive case
var obj = { a: true };
var obj_ext = { a: 'test', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test');
});
obj = { a: true };
obj_ext = { a: true, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 2');
});
obj = { a: true };
obj_ext = { a: 1, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 3');
});
obj = { a: false };
obj_ext = { a: 'false', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 4');
});
obj = { a: false };
obj_ext = { a: 0, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 5');
});
obj = { a: false };
obj_ext = { a: '', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 6');
});
obj = { a: false };
obj_ext = { a: false, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 7');
});
obj = { a: false };
obj_ext = { a: null, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBoolean test 8');
});
test.finish();
};
exports['test_validate_toBooleanStrict'] = function(test, assert) {
var v = new V({
a: C().toBooleanStrict()
});
// positive case
var obj = { a: false };
var obj_ext = { a: 'test', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test');
});
obj = { a: true };
obj_ext = { a: true, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 2');
});
obj = { a: true };
obj_ext = { a: 1, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 3');
});
obj = { a: true };
obj_ext = { a: 'true', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 4');
});
obj = { a: false };
obj_ext = { a: 'false', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 5');
});
obj = { a: false };
obj_ext = { a: 0, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 6');
});
obj = { a: false };
obj_ext = { a: '', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 7');
});
obj = { a: false };
obj_ext = { a: false, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 8');
});
obj = { a: false };
obj_ext = { a: null, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'toBooleanStrict test 9');
});
test.finish();
};
exports['test_validate_entityDecode'] = function(test, assert) {
var v = new V({
a: C().entityDecode()
});
// positive case
var obj = { a: 'Smith & Wesson' };
var obj_ext = { a: 'Smith & Wesson', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'entityDecode test');
});
test.finish();
};
exports['test_validate_entityEncode'] = function(test, assert) {
var v = new V({
a: C().entityEncode()
});
// positive case
var obj = { a: 'Smith & Wesson' };
var obj_ext = { a: 'Smith & Wesson', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'entityEncode test');
});
test.finish();
};
exports['test_validate_trim'] = function(test, assert) {
var v = new V({
a: C().trim()
});
// positive case
var obj = { a: 'cheese' };
var obj_ext = { a: ' cheese ', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'trim test');
});
v = new V({
a: C().trim('QV')
});
obj = { a: 'cheese' };
obj_ext = { a: 'VQQcheeseQQV', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'trim test 2');
});
obj = { a: 'AcheeseA' };
obj_ext = { a: 'AcheeseA', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'trim test 2');
});
test.finish();
};
exports['test_validate_ltrim'] = function(test, assert) {
var v = new V({
a: C().ltrim()
});
// positive case
var obj = { a: 'cheese ' };
var obj_ext = { a: 'cheese ', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'ltrim test');
});
v = new V({
a: C().ltrim('QV')
});
obj = { a: 'cheeseQQV' };
obj_ext = { a: 'VQQcheeseQQV', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'ltrim test 2');
});
obj = { a: 'AcheeseA' };
obj_ext = { a: 'AcheeseA', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'ltrim test 2');
});
test.finish();
};
exports['test_validate_rtrim'] = function(test, assert) {
var v = new V({
a: C().rtrim()
});
// positive case
var obj = { a: ' cheese' };
var obj_ext = { a: ' cheese ', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'rtrim test');
});
v = new V({
a: C().rtrim('QV')
});
obj = { a: 'VQQcheese' };
obj_ext = { a: 'VQQcheeseVQQ', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'rtrim test 2');
});
obj = { a: 'AcheeseA' };
obj_ext = { a: 'AcheeseA', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'rtrim test 2');
});
test.finish();
};
exports['test_validate_ifNull'] = function(test, assert) {
var v = new V({
a: C().ifNull('foo')
});
// positive case
var obj = { a: 'foo' };
var obj_ext = { a: null, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'ifNull test');
});
test.finish();
};
exports['test_validate_nested_array'] = function(test, assert) {
var v = new V({
a: C().isArray(C().isString())
});
// positive case
var obj = { a: ['test'] };
var obj_ext = { a: ['test'], b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'array-of-strings test');
});
// negative case
var neg = { a: 'abc' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Not an array', 'array-of-strings test (negative case)');
});
// negative case
neg = { a: [1, 2] };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Not a string', 'array-of-strings test (negative case 2)');
});
test.finish();
};
exports['test_validate_nested_hash'] = function(test, assert) {
var v = new V({
a: C().isHash(C().isString(), C().isString())
});
// positive case
var obj = { a: {'test' : 'test'} };
var obj_ext = { a: {'test' : 'test'}, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'hash test');
});
// negative case
var neg = { a: { 'test' : 123 } };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, "Value for key 'test': Not a string", 'hash test (negative case)');
});
test.finish();
};
exports['test_validate_enum'] = function(test, assert) {
var v = new V({
a: C().enumerated({inactive: 0, active: 1, full_no_new_checks: 2}).optional()
}),
obj = { a: 2 },
obj_ext = { a: 'full_no_new_checks', b: 2 },
neg = { a: 0 },
obj2 = { };
async.parallel([
function pos1(callback) {
// positive case
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'enum test');
callback();
});
},
function neg1(callback) {
// negative case 1
v.check(neg, function(err, cleaned) {
assert.match(err.message, /Invalid value '0'/, 'enum test (negative case 2)');
callback();
});
},
function pos2(callback) {
// negative case 1
v.check(obj2, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj2);
callback();
});
}
], function (err) {
test.finish();
});
};
exports['test_validate_enum_optional'] = function(test, assert) {
var v = new V({
a: C().enumerated({inactive: 0, active: 1, full_no_new_checks: 2})
});
// positive case
var obj = { a: 2 };
var obj_ext = { a: 'full_no_new_checks', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'enum test');
});
// negative case 1
var neg = { a: 'bogus_key' };
v.check(neg, function(err, cleaned) {
assert.match(err.message, /Invalid value 'bogus_key'/, 'enum test (negative case 1)');
});
// negative case 2
var neg = { a: 0 };
v.check(neg, function(err, cleaned) {
assert.match(err.message, /Invalid value '0'/, 'enum test (negative case 2)');
});
test.finish();
};
exports['test_validate_range'] = function(test, assert) {
var v = new V({
a: C().range(1, 65535)
});
// positive case
var obj = { a: 500 };
var obj_ext = { a: 500, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'range test (number)');
});
// negative case
var neg = { a: 65536 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, "Value out of range (1..65535)", 'range test (negative case)');
});
v = new V({
a: C().range('a', 'c')
});
// positive case
var obj = { a: 'b' };
var obj_ext = { a: 'b', b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'range test (string)');
});
test.finish();
};
exports['test_optional_fields'] = function(test, assert) {
var v = new V({
a: C().optional().range(1, 65535)
});
// positive case
var obj = { a: 500 };
var obj_ext = { a: 500, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'optional fields test');
});
// positive case
obj = { };
obj_ext = { b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'optional fields test (missing)');
});
// negative case
var neg = { a: 65536 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, "Value out of range (1..65535)", 'optional fields test (negative case)');
});
test.finish();
};
exports['test_nested_schemas'] = function(test, assert) {
var v = new V({
a: { b: C().optional().range(1, 65535) }
});
// positive case
var obj = { a: { b: 500 } };
var obj_ext = { a: { b: 500}, b: 2 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'nested schema test');
});
// negative case
var neg = { a: { b: 65536} };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, "Value out of range (1..65535)", 'nested schema test (negative case)');
assert.deepEqual(err.parentKeys, ['a'], 'nested schema test (negative case)');
});
test.finish();
};
exports['test_partial'] = function(test, assert) {
var v = new V({
a: C().isString(),
b: C().isInt()
});
async.parallel([
function(callback) {
var obj = { a: 'foo', b: 1 };
var obj_ext = { a: 'foo', b: 1 };
v.checkPartial(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'checkPartial test');
callback();
});
},
function(callback) {
var obj = { a: 'foo' };
var obj_ext = { a: 'foo' };
v.checkPartial(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'checkPartial test 2');
callback();
});
}
],
function(err) {
assert.ifError(err);
test.finish();
});
};
exports['test_partial_update_required'] = function(test, assert) {
var v = new V({
a: C().isString(),
b: C().updateRequired().isInt()
});
var neg = { a: 'foo' };
v.checkPartial(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'Missing required key (b)', 'partial update required');
test.finish();
});
};
exports['test_partial_immutable'] = function(test, assert) {
var v = new V({
a: C().isString(),
b: C().immutable().isInt()
});
var neg = { a: 'bar', b: 1234 };
v.checkPartial(neg, function(err, cleaned) {
assert.ifError(err);
var existing = { a: 'foo', b: 1233, c: 'hello world' };
v.checkUpdate(existing, neg, function(err, cleaned) {
assert.ok(err);
assert.deepEqual(err.message, 'Attempted to mutate immutable field');
assert.equal(err.key, 'b');
assert.deepEqual(existing, {a: 'foo', b: 1233, c: 'hello world'});
test.finish();
});
});
};
exports['test_partial_immutable_unchanged'] = function(test, assert) {
var v = new V({
a: C().isString(),
b: C().immutable().isInt(),
c: C().isString()
});
var neg = { a: 'bar', b: 1234 };
v.checkPartial(neg, function(err, cleaned) {
assert.ifError(err);
var existing = { a: 'foo', b: 1234, c: 'hello world' };
v.checkUpdate(existing, neg, function(err, cleaned) {
assert.ok(!err);
assert.deepEqual(cleaned, {
a: 'bar',
b: 1234,
c: 'hello world'
});
assert.deepEqual(existing, {
a: 'foo',
b: 1234,
c: 'hello world'
});
test.finish();
});
});
};
exports['test_custom'] = function(test, assert) {
var description = 'Is the meaning of life';
V.addChainValidator('isMeaningOfLife',
description,
function(value, baton, callback) {
assert.deepEqual(baton, 'aBaton');
if (value == 42) {
callback(null, 'forty-two');
} else {
callback('incorrect value');
}
});
var v = new V({
a: C().custom('isMeaningOfLife')
});
var obj = { a: 'forty-two' };
var obj_ext = { a: 42, b: 'foo' };
assert.deepEqual(v.help().a[0], description, 'custom help');
v.baton = 'aBaton';
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'custom test');
});
var neg = { a: 43 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'incorrect value', 'custom test (negative case)');
});
assert.throws(function() {
var v = new V({
a: C().custom('bogus')
});
},
/Unknown validator name/,
'custom test (unknown validator)');
assert.throws(function() {
var v = new V({
a: C().custom()
});
},
/Missing/,
'custom test (missing validator)');
test.finish();
};
exports['test_custom_array_with_baton'] = function(test, assert) {
var description = 'Is the meaning of life';
V.addChainValidator('isMeaningOfLife',
description,
function(value, baton, callback) {
assert.deepEqual(baton, 'aBaton');
if (value == 42) {
callback(null, 'forty-two');
} else {
callback('incorrect value');
}
});
var v = new V({
a: C().optional().isArray(C().custom('isMeaningOfLife'))
});
var obj = { a: ['forty-two'] };
var obj_ext = { a: [42], b: 'foo' };
var neg = { a: [43] };
v.baton = 'aBaton';
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, 'incorrect value', 'custom test (negative case)');
});
assert.throws(function() {
var v = new V({
a: C().custom('bogus')
});
},
/Unknown validator name/,
'custom test (unknown validator)');
assert.throws(function() {
var v = new V({
a: C().custom()
});
},
/Missing/,
'custom test (missing validator)');
test.finish();
};
exports['test_final'] = function(test, assert) {
var v,
finalValidator;
v = new V({
v4: C().optional(),
v6: C().optional()
});
finalValidator = function(obj, callback) {
if ((! obj.v4) && (! obj.v6)) {
callback({
key: 'v4',
parentKeys: null,
message: 'At least one of v4 or v6 must be specified'
});
} else
callback(null, obj);
};
v.addFinalValidator(finalValidator);
var obj = { v4: '1.2.3.4' };
var obj_ext = { v4: '1.2.3.4', b: 'foo' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'final validator test 1');
});
obj = { v6: '1.2.3.4' };
obj_ext = { v6: '1.2.3.4', b: 'foo' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'final validator test 2');
});
obj = { v4: '1.2.3.4', v6: '1.2.3.4' };
obj_ext = { v4: '1.2.3.4', v6: '1.2.3.4', b: 'foo' };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'final validator test 3');
});
var neg = { b: 'foo' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message,
'At least one of v4 or v6 must be specified',
'final validator test (negative case)');
});
test.finish();
};
exports['test_schema_translation_1'] = function(test, assert) {
var validity = swiz.defToValve(def),
v = new V(validity.Node);
assert.isDefined(validity.Node);
assert.isDefined(validity.NodeOpts);
v.check(exampleNode, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, compNode, 'schema translation');
v.check(badExampleNode, function(err, cleaned) {
assert.deepEqual(err.message, 'Invalid IP',
'schama translation failure');
test.finish();
});
});
};
exports['test_schema_translation_2'] = function(test, assert) {
var validity = swiz.defToValve(def),
v = new V(validity.Node);
assert.isDefined(validity.Node);
assert.isDefined(validity.NodeOpts);
v.check(badExampleNode1, function(err, cleaned) {
assert.deepEqual(err.message, 'Missing required key (agent_name)',
'schama translation failure (missing agent_key)');
test.finish();
});
};
exports['test_schema_translation_enumerated'] = function(test, assert) {
var validity = swiz.defToValve(def),
v = new V(validity.Node2);
v.check(exampleNode2, function(err, cleaned) {
assert.ifError(err);
assert.equal(cleaned.state, 1);
test.finish();
});
};
exports['test_roundtrip_json_swiz_valve'] = function(test, assert) {
var validity = swiz.defToValve(def),
v = new V(validity.Node),
obj, sw = new swiz.Swiz(def);
v.check(exampleNode, function(err, cleaned) {
assert.ifError(err);
obj = cleaned;
obj.getSerializerType = function() {return 'Node';};
sw.serialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, obj,
function(err, results) {
assert.ifError(err);
sw.deserialize(swiz.SERIALIZATION.SERIALIZATION_JSON, 1, results, function(err, newObj) {
assert.deepEqual(newObj, exampleNode, 'Round trip json swiz/valve test');
assert.ifError(err);
test.finish();
});
});
});
};
exports['test_roundtrip_xml_swiz_valve'] = function(test, assert) {
var validity = swiz.defToValve(def),
v = new V(validity.Node),
obj, sw = new swiz.Swiz(def);
v.check(exampleNode, function(err, cleaned) {
assert.ifError(err);
obj = cleaned;
obj.getSerializerType = function() {return 'Node';};
sw.serialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, obj,
function(err, xml) {
assert.ifError(err);
sw.deserialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, xml, function(err, newObj) {
assert.deepEqual(newObj, exampleNode, 'Round trip json swiz/valve test');
assert.ifError(err);
test.finish();
});
});
});
};
exports['test_xml_with_whitespace'] = function(test, assert) {
var validity = swiz.defToValve(def),
v = new V(validity.Node),
testxml,
obj, sw = new swiz.Swiz(def);
testxml = sw.deserializeXml('<?xml version="1.0" encoding="utf-8"?><node id="xkCD366" name="exmample"> <is_active>true</is_active><agent_name>your mom</agent_name><ipaddress>42.24.42.24</ipaddress></node>');
v.check(testxml, function(err, cleaned) {
assert.ifError(err);
obj = cleaned;
obj.getSerializerType = function() {return 'Node';};
sw.serialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, obj,
function(err, xml) {
assert.ifError(err);
sw.deserialize(swiz.SERIALIZATION.SERIALIZATION_XML, 1, xml, function(err, newObj) {
assert.deepEqual(newObj, exampleNode, 'Round trip json swiz/valve test');
assert.ifError(err);
test.finish();
});
});
});
};
exports['test_boolean'] = function(test, assert) {
var v = new V({
a: C().isBoolean()
});
// positive case
var obj = { a: true };
var obj_ext = { a: 1 };
v.check(obj_ext, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, obj, 'boolean test');
});
// negative case
var neg = { a: 'notFalse' };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, "Not a boolean", 'boolean test');
});
test.finish();
};
exports['test_inArray'] = function(test, assert) {
var v = new V({
a: new C().inArray([1, 2, 3, 4, 5])
});
// positive case
var pos = { a: 1 };
v.check(pos, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, pos, 'isArray test');
});
// negative case
var neg = { a: -1 };
v.check(neg, function(err, cleaned) {
assert.match(err.message, /Invalid value '-1'. Should be one of/, 'inArray test');
});
test.finish();
};
exports['test_port'] = function(test, assert) {
var v = new V({
a: new C().isPort()
});
// positive case
var pos = { a: 1 };
v.check(pos, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, pos, 'isPort test');
});
// negative case
var neg = { a: -1 };
v.check(neg, function(err, cleaned) {
assert.deepEqual(err.message, "Value out of range [1,65535]", 'isPort test');
});
test.finish();
};
exports['test_V1UUID'] = function(test, assert) {
var v = new V({
a: new C().isV1UUID()
});
async.series([
function(callback) {
// positive case
var pos = { a: '4b299c10-ab5a-11e1-9f6f-1c8b12469d15' };
v.check(pos, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, pos, 'isV1UUID test');
callback();
});
},
function(callback) {
// negative case 0
var neg0 = { a: 'b299c10-ab5a-11e1-9f6f-1c8b12469d15' };
v.check(neg0, function(err, cleaned) {
assert.deepEqual(err.message, "Invalid UUID", 'isV1UUID test');
callback();
});
},
function(callback) {
// negative case 1
var neg1 = { a: '4@299c10-ab5a-11e1-9f6f-1c8b12469d15' };
v.check(neg1, function(err, cleaned) {
assert.deepEqual(err.message, "Invalid UUID", 'isV1UUID test');
callback();
});
},
function(callback) {
//negative case 2
var neg2 = { a : '4b299c10-ab5a-11e1-4f6f-1c8b12469d15' };
v.check(neg2, function(err, cleaned) {
assert.deepEqual(err.message, "Unsupported UUID variant", 'isV1UUID test');
callback();
});
},
function(callback) {
//negative case 3
var neg3 = { a : '4b299c10-ab5a-21e1-9f6f-1c8b12469d15' };
v.check(neg3, function(err, cleaned) {
assert.deepEqual(err.message, "UUID is not version 1", 'isV1UUID test');
callback();
});
}
],
function(err) {
test.finish();
});
};
exports['test_getValidatorPos_hasValidator_and_getValidatorAtPos'] = function(test, assert) {
var v = new V({
a: C().len(1).isNumeric(),
b: C().len(1).isNumeric().optional()
});
assert.equal(v.schema.a.getValidatorPos('len'), 0);
assert.equal(v.schema.a.getValidatorPos('isNumeric'), 1);
assert.equal(v.schema.a.getValidatorPos('inArray'), -1);
assert.ok(v.schema.a.hasValidator('len'));
assert.ok(v.schema.a.hasValidator('isNumeric'));
assert.ok(!v.schema.a.hasValidator('inArray'));
assert.equal(v.schema.b.getValidatorPos('optional'), 2);
assert.ok(v.schema.b.hasValidator('optional'));
assert.equal(v.schema.b.getValidatorAtPos(2).name, 'optional');
assert.equal(v.schema.b.getValidatorAtPos(6), null);
test.finish();
};
exports['test_optional_string'] = function(test, assert) {
var v = new V({
a: new C().optional().isString().len(1, 5)
});
async.series([
function check1(callback) {
var pos1 = {a: 'abc'};
v.check(pos1, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, pos1);
callback();
});
},
function checknull(callback) {
var pos2 = {a: null};
v.check(pos2, function(err, cleaned) {
assert.ifError(err);
assert.deepEqual(cleaned, pos2);
callback();
});
}
],
function(err) {
test.finish();
});
};
| Code cleanup
| tests/test-valve.js | Code cleanup | <ide><path>ests/test-valve.js
<ide> // positive case 2
<ide> };
<ide>
<add>function invalidIpFailMsgAsserter(assert, msg) {
<add> return function(err, cleaned) {
<add> assert.deepEqual(err.message, 'Invalid IP', msg);
<add> }
<add>}
<add>
<ide> exports['test_validate_ip'] = function(test, assert) {
<add> var invalidIpFailMsg = invalidIpFailMsgAsserter.bind(null, assert);
<ide> var v = new V({
<ide> a: C().isIP()
<ide> });
<ide>
<ide> // positive test cases
<ide> var expected = { a: '192.168.0.1' };
<del> var provided = { a: '192.168.0.1', b: 2 };
<del> v.check(provided, function(err, cleaned) {
<add> v.check({a: '192.168.0.1', b: 2}, function(err, cleaned) {
<ide> assert.ifError(err);
<ide> assert.deepEqual(cleaned, expected, 'isIP should accept dotted-quad syntax for IPv4 addresses');
<ide> });
<ide>
<ide> expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
<del> provided = { a: '2001:0db8:0000:0000:0001:0000:0000:0001', b: 2 };
<del> v.check(provided, function(err, cleaned) {
<add> v.check({a: '2001:0db8:0000:0000:0001:0000:0000:0001', b: 2}, function(err, cleaned) {
<ide> assert.ifError(err);
<ide> assert.deepEqual(cleaned, expected, 'isIP should accept a coloned-octet syntax for IPv6 addresses');
<ide> });
<ide>
<ide> expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
<del> provided = { a: '2001:0db8::0001:0000:0000:0001', b: 2 };
<del> v.check(provided, function(err, cleaned) {
<add> v.check({a: '2001:0db8::0001:0000:0000:0001', b: 2}, function(err, cleaned) {
<ide> assert.ifError(err);
<ide> assert.deepEqual(cleaned, expected, 'isIP should accept a shortened syntax for IPv6 addresses');
<ide> });
<ide>
<ide> expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
<del> provided = { a: '2001:0db8:0000:0000:0001::0001', b: 2 };
<del> v.check(provided, function(err, cleaned) {
<add> v.check({a: '2001:0db8:0000:0000:0001::0001', b: 2}, function(err, cleaned) {
<ide> assert.ifError(err);
<ide> assert.deepEqual(cleaned, expected, 'isIP should accept a shortened syntax for IPv6 addresses');
<ide> });
<ide>
<ide> expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
<del> provided = { a: '2001:db8:0:0:1:0:0:1', b: 2 };
<del> v.check(provided, function(err, cleaned) {
<add> v.check({a: '2001:db8:0:0:1:0:0:1', b: 2}, function(err, cleaned) {
<ide> assert.ifError(err);
<ide> assert.deepEqual(cleaned, expected, 'isIP should accept a coloned-octet syntax with leading zeros blanked for IPv6 addresses');
<ide> });
<ide>
<ide> expected = { a: '2001:0db8:0000:0000:0001:0000:0000:0001' };
<del> provided = { a: '2001:db8::1:0:0:1', b: 2 };
<del> v.check(provided, function(err, cleaned) {
<add> v.check({a: '2001:db8::1:0:0:1', b: 2}, function(err, cleaned) {
<ide> assert.ifError(err);
<ide> assert.deepEqual(cleaned, expected, 'isIP should accept a shortened syntax with leading zeros blanked for IPv6 addresses');
<ide> });
<ide>
<ide> expected = { a: '1234:0000:0000:0000:0000:0000:0000:0000' };
<del> provided = { a: '1234::', b: 2 };
<del> v.check(provided, function(err, cleaned) {
<add> v.check({a: '1234::', b: 2}, function(err, cleaned) {
<ide> assert.ifError(err);
<ide> assert.deepEqual(cleaned, expected, 'isIP should accept a tail-truncated address for IPv6 addresses');
<ide> });
<ide>
<ide> expected = { a: '0000:0000:0000:0000:0000:0000:0000:1234' };
<del> provided = { a: '::1234', b: 2 };
<del> v.check(provided, function(err, cleaned) {
<add> v.check({a: '::1234', b: 2}, function(err, cleaned) {
<ide> assert.ifError(err);
<ide> assert.deepEqual(cleaned, expected, 'isIP should accept a head-truncated address for IPv6 addresses');
<ide> });
<ide>
<ide> expected = { a: '0000:0000:0000:0000:0000:0000:0000:0000' };
<del> provided = { a: '::', b: 2 };
<del> v.check(provided, function(err, cleaned) {
<add> v.check({a: '::', b: 2}, function(err, cleaned) {
<ide> assert.ifError(err);
<ide> assert.deepEqual(cleaned, expected, 'isIP should accept a nil IPv6 address');
<ide> });
<ide>
<ide> expected = { a: '0000:0000:0000:0000:0000:0000:7f00:0001' };
<del> provided = { a: '::7F00:0001', b: 2 };
<del> v.check(provided, function(err, cleaned) {
<add> v.check({a: '::7F00:0001', b: 2}, function(err, cleaned) {
<ide> assert.ifError(err);
<ide> assert.deepEqual(cleaned, expected, 'isIP should accept an IPv6 address with capital letters');
<ide> });
<ide>
<ide> expected = { a: '0000:0000:0000:0000:0000:0000:7f00:0001' };
<del> provided = { a: '::127.0.0.1', b: 2 };
<del> v.check(provided, function(err, cleaned) {
<add> v.check({a: '::127.0.0.1', b: 2}, function(err, cleaned) {
<ide> assert.ifError(err);
<ide> assert.deepEqual(cleaned, expected, 'isIP should accept an IPv4 address embedded in an IPv6 address');
<ide> });
<ide>
<ide> // negative test cases
<del> var provided = { a: 'invalid/' };
<del> v.check(provided, function(err, cleaned) {
<del> assert.deepEqual(err.message, 'Invalid IP', 'IP test (negative case)');
<del> });
<del>
<del> provided = {a: '12345' };
<del> v.check(provided, function(err, cleaned) {
<del> assert.deepEqual(err.message, 'Invalid IP', 'IP test (negative case 2)');
<del> });
<del>
<del> provided = {a: {b: null} };
<del> v.check(provided, function(err, cleaned) {
<del> assert.deepEqual(err.message, 'IP address is not a string', 'IP test (negative case 3)');
<del> });
<del>
<del> provided = {a: '2001:0db8:0:0:1:0:0:127.0.0.1'};
<del> v.check(provided, function(err, cleaned) {
<del> assert.deepEqual(err.message, 'Incorrect number of groups found', 'Malformed IPv6 address w/ embedded IPv4 address');
<del> });
<del>
<del> provided = {a: '2001:0db8::1::1' };
<del> v.check(provided, function(err, cleaned) {
<del> assert.deepEqual(err.message, 'Invalid IP', 'IPv6 can only have at most one "::" symbol in it.');
<del> });
<del>
<del> provided = {a: '2001:0db8:0000:0000:0001:0000:0000'};
<del> v.check(provided, function(err, cleaned) {
<del> assert.deepEqual(err.message, 'Invalid IP', 'IPv6 coloned-octet notation requires eight hex words.');
<del> });
<del>
<del> provided = {a: '2001:0db8::1:0:0:00001' };
<del> v.check(provided, function(err, cleaned) {
<del> assert.deepEqual(err.message, 'Invalid IP', 'IPv6 hex groups can be at most 4 characters long.');
<add> v.check({a: 'invalid/'}, invalidIpFailMsg('IP addresses cannot be strings'));
<add> v.check({a: '12345'}, invalidIpFailMsg('IP addresses cannot be single integers'));
<add> v.check({a: '2001:0db8::1::1'}, invalidIpFailMsg('IPv6 can only have at most one "::" symbol in it.'));
<add> v.check({a: '2001:0db8:0000:0000:0001:0000:0000'}, invalidIpFailMsg('IPv6 coloned-octet notation requires eight hex words.'));
<add> v.check({a: '2001:0db8::1:0:0:00001'}, invalidIpFailMsg('IPv6 hex groups can be at most 4 characters long.'));
<add>
<add> v.check({a: {b: null}}, function(err, unused) {
<add> assert.deepEqual(err.message, 'IP address is not a string', 'IP addresses cannot be null or JSON objects');
<add> });
<add>
<add> v.check({a: '2001:0db8:0:0:1:0:0:127.0.0.1'}, function(err, unused) {
<add> assert.deepEqual(err.message, 'Incorrect number of groups found', 'Malformed IPv6 address w/ embedded IPv4 address');
<ide> });
<ide>
<ide> var stack_attack = "";
<ide> stack_attack += possible.charAt(Math.floor(Math.random()*possible.length));
<ide> }
<ide> stack_attack = '1'+stack_attack; // Make sure it starts with a digit
<del>
<del> provided = {a: stack_attack};
<del> v.check(provided, function(err, cleaned) {
<del> assert.deepEqual(err.message, 'Invalid IP', 'Stack overflow attacks, to 1MB, should be rejected out of hand.');
<del> });
<del>
<del> provided = {a: '2001:0db8:0:0:1:0:0:'+stack_attack};
<del> v.check(provided, function(err, cleaned) {
<del> assert.deepEqual(err.message, 'Invalid IP', 'Stack overflow attacks, to 1MB, should be rejected out of hand.');
<del> });
<del>
<del> provided = {a: '192.168.0.'+stack_attack};
<del> v.check(provided, function(err, cleaned) {
<del> assert.deepEqual(err.message, 'Invalid IP', 'Stack overflow attacks, to 1MB, should be rejected out of hand.');
<del> });
<del>
<add> ifFailed = invalidIpFailMsgAsserter.bind(null, assert, 'Stack overflow attacks, to 1MB, should be rejected out of hand.');
<add>
<add> v.check({a: stack_attack}, ifFailed);
<add> v.check({a: '2001:0db8:0:0:1:0:0:'+stack_attack}, ifFailed);
<add> v.check({a: '192.168.0.'+stack_attack}, ifFailed);
<ide> test.finish();
<ide> };
<ide> |
|
JavaScript | mit | f6bea77ba6be33a0633ebfe9af9113ca896e3b10 | 0 | Vizzuality/GlobalFishingWatch,Vizzuality/GlobalFishingWatch,Vizzuality/GlobalFishingWatch | import { ADD_CUSTOM_LAYER, TOGGLE_LAYER_VISIBILITY, TOGGLE_LAYER_WORKSPACE_PRESENCE } from 'layers/layersActions';
import { ADD_REPORT_POLYGON, DELETE_REPORT_POLYGON, SET_REPORT_STATUS_SENT, SHOW_POLYGON } from 'report/reportActions';
import { SET_FLAG_FILTERS, CHANGE_SPEED } from 'filters/filtersActions';
import { SET_SEARCH_TERM } from 'search/searchActions';
import { SET_RECENT_VESSELS_VISIBILITY } from 'recentVessels/recentVesselsActions';
import {
GA_DISCARD_REPORT,
GA_EXTERNAL_LINK_CLICKED,
GA_INNER_TIMELINE_DATES_UPDATED,
GA_INNER_TIMELINE_EXTENT_CHANGED,
GA_MAP_CENTER_TILE,
GA_MAP_POINT_CLICKED,
GA_OUTER_TIMELINE_DATES_UPDATED,
GA_PLAY_STATUS_TOGGLED,
GA_SEARCH_RESULT_CLICKED,
GA_SET_LAYER_HUE,
GA_SET_LAYER_OPACITY,
GA_VESSEL_POINT_CLICKED,
GA_RECENT_VESSEL_ADDED
} from 'analytics/analyticsActions';
import isFunction from 'lodash/isFunction';
import { SEARCH_QUERY_MINIMUM_LIMIT, TIMELINE_SPEED_CHANGE } from 'config';
import { FLAGS } from 'app/src/constants';
import { TOGGLE_VESSEL_PIN, SET_PINNED_VESSEL_HUE } from 'actions/vesselInfo';
import { SET_WORKSPACE_ID } from 'actions/workspace';
const GA_ACTION_WHITELIST = [
{
type: TOGGLE_LAYER_VISIBILITY,
category: 'Layer',
action: (action, state) => {
const layerIndex = state.layers.workspaceLayers.findIndex(l => l.id === action.payload.layerId);
const changedLayer = state.layers.workspaceLayers[layerIndex];
const isVisible = action.payload.forceStatus !== null ? action.payload.forceStatus : !changedLayer.visible;
return isVisible ? 'Turn Layer On' : 'Turn Layer Off';
},
getPayload: action => action.payload.layerId
},
{
type: GA_SET_LAYER_OPACITY,
category: 'Layer',
action: 'Set layer opacity',
getPayload: action => `${action.payload.layerId}:${action.payload.opacity}`
},
{
type: GA_SET_LAYER_HUE,
category: 'Layer',
action: 'Set layer hue',
getPayload: action => `${action.payload.layerId}:${action.payload.hue}`
},
{
type: TOGGLE_LAYER_WORKSPACE_PRESENCE,
category: 'Layer',
action: action => (action.payload.added ? 'Add from GFW Library' : 'Remove from GFW Library'),
getPayload: action => action.payload.layerId
},
{
type: ADD_CUSTOM_LAYER,
category: 'Layer',
action: 'Add user generated layer',
getPayload: action => action.payload.layerId
},
{
type: SET_SEARCH_TERM,
category: 'Search',
action: 'Search for vessel',
getPayload: (action) => {
if (action.payload.length >= SEARCH_QUERY_MINIMUM_LIMIT) {
return action.payload;
}
return null;
}
},
{
type: GA_SEARCH_RESULT_CLICKED,
category: 'Search',
action: 'Search result selected',
getPayload: action => action.payload.name
},
{
type: GA_RECENT_VESSEL_ADDED,
category: 'Search',
action: 'Recent Vessels',
getPayload: () => 'Selects a recent vessel to view'
},
{
type: TOGGLE_VESSEL_PIN,
category: 'Search',
action: (action) => {
const actionLabel = (action.payload.pinned === true) ? 'Pin a vessel' : 'Unpin a vessel';
return actionLabel;
},
getPayload: action => `${action.payload.tilesetId}:${action.payload.seriesgroup}:${action.payload.vesselname}`
},
{
type: GA_VESSEL_POINT_CLICKED,
category: 'Map Interaction',
action: 'Loaded a vessel data',
getPayload: action => `${action.payload.name}:${action.payload.tilesetId}:${action.payload.seriesgroup}`
},
{
type: GA_MAP_POINT_CLICKED,
category: 'Map Interaction',
action: 'Click a vessel point',
getPayload: action => `${action.payload.lat}:${action.payload.long}:${action.payload.type}`
},
{
type: GA_OUTER_TIMELINE_DATES_UPDATED,
category: 'Timeline',
action: 'Outer period changed',
getPayload: action => `${action.payload[0].getTime()}:${action.payload[1].getTime()}`
},
{
type: GA_INNER_TIMELINE_DATES_UPDATED,
category: 'Timeline',
action: 'Inner dates changed',
getPayload: action => `${action.payload[0].getTime()}:${action.payload[1].getTime()}`
},
{
type: GA_INNER_TIMELINE_EXTENT_CHANGED,
category: 'Timeline',
action: 'Inner extent changed',
getPayload: action => action.payload.toString()
},
{
type: GA_PLAY_STATUS_TOGGLED,
category: 'Timeline',
action: 'Press Play',
getPayload: (action, state) => {
if (action.payload === false) { // pressed play
return `play:${state.filters.timelineInnerExtent[0].getTime()}`;
}
return `pause:${state.filters.timelineInnerExtent[1].getTime()}`;
}
},
{
type: SET_WORKSPACE_ID,
category: 'Share',
action: 'Share Link',
getPayload: action => action.payload
},
{
type: SET_FLAG_FILTERS,
category: 'Settings',
action: 'Filter by Country',
getPayload: ({ payload }) => {
const filters = payload.flagFilters.filter(flagFilter => typeof flagFilter.flag !== 'undefined');
if (filters.length) {
return filters.map((flagFilter) => {
if (flagFilter.flag) return FLAGS[flagFilter.flag];
return 'ALL';
});
}
return null;
}
},
{
type: GA_EXTERNAL_LINK_CLICKED,
category: 'External Link',
action: 'Click to leave',
getPayload: ({ payload }) => payload
},
{
type: SHOW_POLYGON,
category: 'Report Interaction',
action: 'Click on polygon',
getPayload: (action, state) => `${state.report.layerId}:${action.payload.polygonData.name}`
},
{
type: ADD_REPORT_POLYGON,
category: 'Report Interaction',
action: 'Add polygon to report',
getPayload: (action, state) => `${state.report.layerId}:${state.report.currentPolygon.name}`
},
{
type: DELETE_REPORT_POLYGON,
category: 'Report Interaction',
action: 'Add polygon to report',
getPayload: (action, state) => `${state.report.layerId}:${state.report.polygons[action.payload.polygonIndex].name}`
},
{
type: GA_DISCARD_REPORT,
category: 'Report Interaction',
action: 'Discard report',
getPayload: (action, state) => `${state.report.layerId}:${state.report.polygons.map(elem => elem.name).join(':')}`
},
{
type: SET_REPORT_STATUS_SENT,
category: 'Report Interaction',
action: 'Report sent',
getPayload: (action, state) => `${state.report.layerId}:${state.report.polygons.map(elem => elem.name).join(':')}`
},
{
type: GA_MAP_CENTER_TILE,
category: 'Map Interaction',
action: 'Changed area',
getPayload: action => `${action.payload.x},${action.payload.y}`
},
{
type: CHANGE_SPEED,
category: 'Timeline',
action: 'Speed Control',
getPayload: (action, state) => {
const label = (action.payload.shouldDecrease ? 'Decrease speed to' : 'Increase speed to');
const speedChangeFactor = (action.payload.shouldDecrease ? 1 / TIMELINE_SPEED_CHANGE : TIMELINE_SPEED_CHANGE);
return `${label} ${state.filters.timelineSpeed * speedChangeFactor}x`;
}
},
{
type: SET_PINNED_VESSEL_HUE,
category: 'Settings',
action: 'Change vessel track colour',
getPayload: () => 'user changes colour'
},
{
type: SET_RECENT_VESSELS_VISIBILITY,
category: 'Search',
action: 'Recent Vessels',
getPayload: action => (action.payload ? 'Open infowindow' : null) // Send only if the modal is opened
}
];
const googleAnalyticsMiddleware = store => next => (action) => {
if (typeof window.ga !== 'undefined' && typeof action.type !== 'undefined') {
const state = store.getState();
const gaAction = GA_ACTION_WHITELIST.find(whitelistAction => action.type === whitelistAction.type);
if (gaAction) {
const gaEvent = {
hitType: 'event',
eventCategory: gaAction.category
};
if (isFunction(gaAction.action)) {
gaEvent.eventAction = gaAction.action(action, state);
} else {
gaEvent.eventAction = gaAction.action;
}
if (gaAction.getPayload) {
gaEvent.eventLabel = gaAction.getPayload(action, state);
}
if (gaEvent.eventLabel !== null && typeof gaEvent.eventLabel !== 'undefined') {
window.ga('send', gaEvent);
}
}
}
return next(action);
};
export { googleAnalyticsMiddleware as default };
| app/src/analytics/analyticsMiddleware.js | import { ADD_CUSTOM_LAYER, TOGGLE_LAYER_VISIBILITY, TOGGLE_LAYER_WORKSPACE_PRESENCE } from 'layers/layersActions';
import { ADD_REPORT_POLYGON, DELETE_REPORT_POLYGON, SET_REPORT_STATUS_SENT, SHOW_POLYGON } from 'report/reportActions';
import { SET_FLAG_FILTERS, CHANGE_SPEED } from 'filters/filtersActions';
import { SET_SEARCH_TERM } from 'search/searchActions';
import { SET_RECENT_VESSELS_VISIBILITY } from 'recentVessels/recentVesselsActions';
import {
GA_DISCARD_REPORT,
GA_EXTERNAL_LINK_CLICKED,
GA_INNER_TIMELINE_DATES_UPDATED,
GA_INNER_TIMELINE_EXTENT_CHANGED,
GA_MAP_CENTER_TILE,
GA_MAP_POINT_CLICKED,
GA_OUTER_TIMELINE_DATES_UPDATED,
GA_PLAY_STATUS_TOGGLED,
GA_SEARCH_RESULT_CLICKED,
GA_SET_LAYER_HUE,
GA_SET_LAYER_OPACITY,
GA_VESSEL_POINT_CLICKED,
GA_RECENT_VESSEL_ADDED
} from 'analytics/analyticsActions';
import isFunction from 'lodash/isFunction';
import { SEARCH_QUERY_MINIMUM_LIMIT, TIMELINE_SPEED_CHANGE } from 'config';
import { FLAGS } from 'app/src/constants';
import { TOGGLE_VESSEL_PIN, SET_PINNED_VESSEL_HUE } from 'actions/vesselInfo';
import { SET_WORKSPACE_ID } from 'actions/workspace';
const GA_ACTION_WHITELIST = [
{
type: TOGGLE_LAYER_VISIBILITY,
category: 'Layer',
action: (action, state) => {
const layerIndex = state.layers.workspaceLayers.findIndex(l => l.id === action.payload.layerId);
const changedLayer = state.layers.workspaceLayers[layerIndex];
const isVisible = action.payload.forceStatus !== null ? action.payload.forceStatus : !changedLayer.visible;
return isVisible ? 'Turn Layer On' : 'Turn Layer Off';
},
getPayload: action => action.payload.layerId
},
{
type: GA_SET_LAYER_OPACITY,
category: 'Layer',
action: 'Set layer opacity',
getPayload: action => `${action.payload.layerId}:${action.payload.opacity}`
},
{
type: GA_SET_LAYER_HUE,
category: 'Layer',
action: 'Set layer hue',
getPayload: action => `${action.payload.layerId}:${action.payload.hue}`
},
{
type: TOGGLE_LAYER_WORKSPACE_PRESENCE,
category: 'Layer',
action: action => (action.payload.added ? 'Add from GFW Library' : 'Remove from GFW Library'),
getPayload: action => action.payload.layerId
},
{
type: ADD_CUSTOM_LAYER,
category: 'Layer',
action: 'Add user generated layer',
getPayload: action => action.payload.layerId
},
{
type: SET_SEARCH_TERM,
category: 'Search',
action: 'Search for vessel',
getPayload: (action) => {
if (action.payload.length >= SEARCH_QUERY_MINIMUM_LIMIT) {
return action.payload;
}
return null;
}
},
{
type: GA_SEARCH_RESULT_CLICKED,
category: 'Search',
action: 'Search result selected',
getPayload: action => action.payload.name
},
{
type: GA_RECENT_VESSEL_ADDED,
category: 'Search',
action: 'Recent Vessels',
getPayload: () => 'Selects a recent vessel to view'
},
{
type: TOGGLE_VESSEL_PIN,
category: 'Search',
action: (action) => {
const actionLabel = (action.payload.pinned === true) ? 'Pin a vessel' : 'Unpin a vessel';
return actionLabel;
},
getPayload: action => `${action.payload.tilesetId}:${action.payload.seriesgroup}:${action.payload.vesselname}`
},
{
type: GA_VESSEL_POINT_CLICKED,
category: 'Map Interaction',
action: 'Loaded a vessel data',
getPayload: action => `${action.payload.name}:${action.payload.tilesetId}:${action.payload.seriesgroup}`
},
{
type: GA_MAP_POINT_CLICKED,
category: 'Map Interaction',
action: 'Click a vessel point',
getPayload: action => `${action.payload.lat}:${action.payload.long}:${action.payload.type}`
},
{
type: GA_OUTER_TIMELINE_DATES_UPDATED,
category: 'Timeline',
action: 'Outer period changed',
getPayload: action => `${action.payload[0].getTime()}:${action.payload[1].getTime()}`
},
{
type: GA_INNER_TIMELINE_DATES_UPDATED,
category: 'Timeline',
action: 'Inner dates changed',
getPayload: action => `${action.payload[0].getTime()}:${action.payload[1].getTime()}`
},
{
type: GA_INNER_TIMELINE_EXTENT_CHANGED,
category: 'Timeline',
action: 'Inner extent changed',
getPayload: action => action.payload.toString()
},
{
type: GA_PLAY_STATUS_TOGGLED,
category: 'Timeline',
action: 'Press Play',
getPayload: (action, state) => {
if (action.payload === false) { // pressed play
return `play:${state.filters.timelineInnerExtent[0].getTime()}`;
}
return `pause:${state.filters.timelineInnerExtent[1].getTime()}`;
}
},
{
type: SET_WORKSPACE_ID,
category: 'Share',
action: 'Share Link',
getPayload: action => action.payload
},
{
type: SET_FLAG_FILTERS,
category: 'Settings',
action: 'Filter by Country',
getPayload: ({ payload }) => {
const filters = payload.flagFilters.filter(flagFilter => typeof flagFilter.flag !== 'undefined');
if (filters.length) {
return filters.map((flagFilter) => {
if (flagFilter.flag) return FLAGS[flagFilter.flag];
return 'ALL';
});
}
return null;
}
},
{
type: GA_EXTERNAL_LINK_CLICKED,
category: 'External Link',
action: 'Click to leave',
getPayload: ({ payload }) => payload
},
{
type: SHOW_POLYGON,
category: 'Report Interaction',
action: 'Click on polygon',
getPayload: (action, state) => `${state.report.layerId}:${action.payload.polygonData.name}`
},
{
type: ADD_REPORT_POLYGON,
category: 'Report Interaction',
action: 'Add polygon to report',
getPayload: (action, state) => `${state.report.layerId}:${state.report.currentPolygon.name}`
},
{
type: DELETE_REPORT_POLYGON,
category: 'Report Interaction',
action: 'Add polygon to report',
getPayload: (action, state) => `${state.report.layerId}:${state.report.polygons[action.payload.polygonIndex].name}`
},
{
type: GA_DISCARD_REPORT,
category: 'Report Interaction',
action: 'Discard report',
getPayload: (action, state) => `${state.report.layerId}:${state.report.polygons.map(elem => elem.name).join(':')}`
},
{
type: SET_REPORT_STATUS_SENT,
category: 'Report Interaction',
action: 'Report sent',
getPayload: (action, state) => `${state.report.layerId}:${state.report.polygons.map(elem => elem.name).join(':')}`
},
{
type: GA_MAP_CENTER_TILE,
category: 'Map Interaction',
action: 'Changed area',
getPayload: action => `${action.payload.x},${action.payload.y}`
},
{
type: CHANGE_SPEED,
category: 'Timeline',
action: 'Speed Control',
getPayload: (action, state) => {
const label = (action.payload.shouldDecrease ? 'Decrease speed to' : 'Increase speed to');
const speedChangeFactor = (action.payload.shouldDecrease ? 1 / TIMELINE_SPEED_CHANGE : TIMELINE_SPEED_CHANGE);
return `${label} ${state.filters.timelineSpeed * speedChangeFactor}x`;
}
},
{
type: SET_PINNED_VESSEL_HUE,
category: 'Settings',
action: 'Change vessel track colour',
getPayload: 'user changes colour'
},
{
type: SET_RECENT_VESSELS_VISIBILITY,
category: 'Search',
action: 'Recent Vessels',
getPayload: action => (action.payload ? 'Open infowindow' : null) // Send only if the modal is opened
}
];
const googleAnalyticsMiddleware = store => next => (action) => {
if (typeof window.ga !== 'undefined' && typeof action.type !== 'undefined') {
const state = store.getState();
const gaAction = GA_ACTION_WHITELIST.find(whitelistAction => action.type === whitelistAction.type);
if (gaAction) {
const gaEvent = {
hitType: 'event',
eventCategory: gaAction.category
};
if (isFunction(gaAction.action)) {
gaEvent.eventAction = gaAction.action(action, state);
} else {
gaEvent.eventAction = gaAction.action;
}
if (gaAction.getPayload) {
gaEvent.eventLabel = gaAction.getPayload(action, state);
}
if (gaEvent.eventLabel !== null && typeof gaEvent.eventLabel !== 'undefined') {
window.ga('send', gaEvent);
}
}
}
return next(action);
};
export { googleAnalyticsMiddleware as default };
| tracking the pinned vessel hue was causing an error
| app/src/analytics/analyticsMiddleware.js | tracking the pinned vessel hue was causing an error | <ide><path>pp/src/analytics/analyticsMiddleware.js
<ide> type: SET_PINNED_VESSEL_HUE,
<ide> category: 'Settings',
<ide> action: 'Change vessel track colour',
<del> getPayload: 'user changes colour'
<add> getPayload: () => 'user changes colour'
<ide> },
<ide> {
<ide> type: SET_RECENT_VESSELS_VISIBILITY, |
|
Java | mpl-2.0 | 6a3758386d6fcc812fe2a99cc9e4d69e50e9628d | 0 | seedstack/jpa-addon | /**
* Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.jpa;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.seedstack.business.domain.Repository;
import org.seedstack.business.specification.dsl.SpecificationBuilder;
import org.seedstack.jpa.fixtures.business.domain.product.Product;
import org.seedstack.seed.it.SeedITRunner;
import org.seedstack.seed.transaction.Transactional;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@Transactional
@JpaUnit("business")
@RunWith(SeedITRunner.class)
public class SpecificationIT {
@Inject
@Jpa
private Repository<Product, Long> repository;
@Inject
private SpecificationBuilder specificationBuilder;
private final Product product1 = createProduct(1L, "product1", "picture1", 2d);
private final Product product2 = createProduct(2L, "product2", "picture2", 2d);
private final Product product3 = createProduct(3L, "product3", "picture3", 2d);
private final Product product4 = createProduct(4L, "product4", " picture4", 2d);
private final Product product5 = createProduct(5L, "product5", "picture4 ", 2d);
private final Product product6 = createProduct(6L, "product6", "picture5", 5d);
@Before
public void setUp() throws Exception {
repository.clear();
repository.add(product1);
repository.add(product2);
repository.add(product3);
repository.add(product4);
repository.add(product5);
repository.add(product6);
}
@After
public void tearDown() throws Exception {
repository.clear();
}
@Test
public void testTrue() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.all()
.build())
).containsExactly(product1, product2, product3, product4, product5, product6);
}
@Test
public void testFalse() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.none()
.build())
).isEmpty();
}
@Test
public void testIdentity() throws Exception {
assertThat(repository.get(specificationBuilder.ofAggregate(Product.class)
.identity().is(3L)
.build())
).containsExactly(product3);
assertThat(repository.get(specificationBuilder.ofAggregate(Product.class)
.identity().isNot(3L)
.build())
).containsExactly(product1, product2, product4, product5, product6);
}
@Test
public void testGreaterThan() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("id").greaterThan(3)
.build())
).containsExactly(product4, product5, product6);
}
@Test
public void testLessThan() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("id").lessThan(3)
.build())
).containsExactly(product1, product2);
}
@Test
public void testEquality() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("price").equalTo(2d)
.build())
).containsExactly(product1, product2, product3, product4, product5);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("price").equalTo(5d)
.build())
).containsExactly(product6);
}
@Test
public void testStringEquality() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture1")
.build())
).containsExactly(product1);
}
@Test
public void testStringEqualityWithTrim() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture4")
.build())
).isEmpty();
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture4").leftTrimmed()
.build())
).containsExactly(product4);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture4").rightTrimmed()
.build())
).containsExactly(product5);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture4").trimmed()
.build())
).containsExactly(product4, product5);
}
@Test
public void testStringEqualityIgnoringCase() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("PICTurE3")
.build())
).isEmpty();
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("PICTurE3").ignoringCase()
.build())
).containsExactly(product3);
}
@Test
public void testStringMatching() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("picture?")
.build())
).containsExactly(product1, product2, product3, product6);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("picture*")
.build())
).containsExactly(product1, product2, product3, product5, product6);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("pict?re5")
.build())
).containsExactly(product6);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("pic*re5")
.build())
).containsExactly(product6);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("?ict?re5")
.build())
).containsExactly(product6);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("*cture5")
.build())
).containsExactly(product6);
}
@Test
public void testStringMatchingWithTrim() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("pict?re4")
.build())
).isEmpty();
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("pict?re4").leftTrimmed()
.build())
).containsExactly(product4);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("pict?re4").rightTrimmed()
.build())
).containsExactly(product5);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("pict?re4").trimmed()
.build())
).containsExactly(product4, product5);
}
@Test
public void testStringMatchingIgnoringCase() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("PI*urE3")
.build())
).isEmpty();
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("PI*urE3").ignoringCase()
.build())
).containsExactly(product3);
}
@Test
public void testNot() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").not().equalTo("picture2")
.build())
).containsExactly(product1, product3, product4, product5, product6);
}
@Test
public void testOr() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture2")
.or()
.property("designation").equalTo("product3")
.or()
.property("designation").equalTo("product4")
.build())
).containsExactly(product2, product3, product4);
}
@Test
public void testAnd() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture2")
.and()
.property("designation").equalTo("product2")
.and()
.property("price").equalTo(2d)
.build())
).containsExactly(product2);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture3")
.and()
.property("designation").equalTo("product2")
.build())
).isEmpty();
}
public Product createProduct(long id, String designation, String pictureUrl, double price) {
List<String> pictures = new ArrayList<>();
pictures.add(pictureUrl);
return new Product(id, designation, "summary", "details", pictures, price);
}
}
| src/test/java/org/seedstack/jpa/SpecificationIT.java | /**
* Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.jpa;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.seedstack.business.domain.Repository;
import org.seedstack.business.specification.dsl.SpecificationBuilder;
import org.seedstack.jpa.fixtures.business.domain.product.Product;
import org.seedstack.seed.it.SeedITRunner;
import org.seedstack.seed.transaction.Transactional;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@Transactional
@JpaUnit("business")
@RunWith(SeedITRunner.class)
public class SpecificationIT {
@Inject
@Jpa
private Repository<Product, Long> repository;
@Inject
private SpecificationBuilder specificationBuilder;
private final Product product1 = createProduct(1L, "product1", "picture1", 2d);
private final Product product2 = createProduct(2L, "product2", "picture2", 2d);
private final Product product3 = createProduct(3L, "product3", "picture3", 2d);
private final Product product4 = createProduct(4L, "product4", " picture4", 2d);
private final Product product5 = createProduct(5L, "product5", "picture4 ", 2d);
private final Product product6 = createProduct(6L, "product6", "picture5", 5d);
@Before
public void setUp() throws Exception {
repository.clear();
repository.add(product1);
repository.add(product2);
repository.add(product3);
repository.add(product4);
repository.add(product5);
repository.add(product6);
}
@After
public void tearDown() throws Exception {
repository.clear();
}
@Test
public void testGreaterThan() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("id").greaterThan("3")
.build())
).containsExactly(product4, product5, product6);
}
@Test
public void testLessThan() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("id").lessThan("3")
.build())
).containsExactly(product1, product2);
}
@Test
public void testEquality() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("price").equalTo(2d)
.build())
).containsExactly(product1, product2, product3, product4, product5);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("price").equalTo(5d)
.build())
).containsExactly(product6);
}
@Test
public void testStringEquality() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture1")
.build())
).containsExactly(product1);
}
@Test
public void testStringEqualityWithTrim() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture4")
.build())
).isEmpty();
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture4").leftTrimmed()
.build())
).containsExactly(product4);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture4").rightTrimmed()
.build())
).containsExactly(product5);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture4").trimmed()
.build())
).containsExactly(product4, product5);
}
@Test
public void testStringEqualityIgnoringCase() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("PICTurE3")
.build())
).isEmpty();
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("PICTurE3").ignoringCase()
.build())
).containsExactly(product3);
}
@Test
public void testStringMatching() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("picture?")
.build())
).containsExactly(product1, product2, product3, product6);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("picture*")
.build())
).containsExactly(product1, product2, product3, product5, product6);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("pict?re5")
.build())
).containsExactly(product6);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("pic*re5")
.build())
).containsExactly(product6);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("?ict?re5")
.build())
).containsExactly(product6);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("*cture5")
.build())
).containsExactly(product6);
}
@Test
public void testStringMatchingWithTrim() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("pict?re4")
.build())
).isEmpty();
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("pict?re4").leftTrimmed()
.build())
).containsExactly(product4);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("pict?re4").rightTrimmed()
.build())
).containsExactly(product5);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("pict?re4").trimmed()
.build())
).containsExactly(product4, product5);
}
@Test
public void testStringMatchingIgnoringCase() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("PI*urE3")
.build())
).isEmpty();
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").matching("PI*urE3").ignoringCase()
.build())
).containsExactly(product3);
}
@Test
public void testNot() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").not().equalTo("picture2")
.build())
).containsExactly(product1, product3, product4, product5, product6);
}
@Test
public void testOr() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture2")
.or()
.property("designation").equalTo("product3")
.or()
.property("designation").equalTo("product4")
.build())
).containsExactly(product2, product3, product4);
}
@Test
public void testAnd() throws Exception {
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture2")
.and()
.property("designation").equalTo("product2")
.and()
.property("price").equalTo(2d)
.build())
).containsExactly(product2);
assertThat(repository.get(specificationBuilder.of(Product.class)
.property("pictures.name").equalTo("picture3")
.and()
.property("designation").equalTo("product2")
.build())
).isEmpty();
}
public Product createProduct(long id, String designation, String pictureUrl, double price) {
List<String> pictures = new ArrayList<>();
pictures.add(pictureUrl);
return new Product(id, designation, "summary", "details", pictures, price);
}
}
| Improve spec test
| src/test/java/org/seedstack/jpa/SpecificationIT.java | Improve spec test | <ide><path>rc/test/java/org/seedstack/jpa/SpecificationIT.java
<ide> }
<ide>
<ide> @Test
<add> public void testTrue() throws Exception {
<add> assertThat(repository.get(specificationBuilder.of(Product.class)
<add> .all()
<add> .build())
<add> ).containsExactly(product1, product2, product3, product4, product5, product6);
<add> }
<add>
<add> @Test
<add> public void testFalse() throws Exception {
<add> assertThat(repository.get(specificationBuilder.of(Product.class)
<add> .none()
<add> .build())
<add> ).isEmpty();
<add> }
<add>
<add> @Test
<add> public void testIdentity() throws Exception {
<add> assertThat(repository.get(specificationBuilder.ofAggregate(Product.class)
<add> .identity().is(3L)
<add> .build())
<add> ).containsExactly(product3);
<add> assertThat(repository.get(specificationBuilder.ofAggregate(Product.class)
<add> .identity().isNot(3L)
<add> .build())
<add> ).containsExactly(product1, product2, product4, product5, product6);
<add> }
<add>
<add> @Test
<ide> public void testGreaterThan() throws Exception {
<ide> assertThat(repository.get(specificationBuilder.of(Product.class)
<del> .property("id").greaterThan("3")
<add> .property("id").greaterThan(3)
<ide> .build())
<ide> ).containsExactly(product4, product5, product6);
<ide> }
<ide> @Test
<ide> public void testLessThan() throws Exception {
<ide> assertThat(repository.get(specificationBuilder.of(Product.class)
<del> .property("id").lessThan("3")
<add> .property("id").lessThan(3)
<ide> .build())
<ide> ).containsExactly(product1, product2);
<ide> } |
|
JavaScript | apache-2.0 | 2b8646a855626283758a3e19ccdcd6a9a32f9d17 | 0 | joequant/etherpad-lite,lpagliari/etherpad-lite,aptivate/etherpad-lite,joequant/etherpad-lite,storytouch/etherpad-lite,cloudfoundry-community/etherpad-lite-cf,lpagliari/etherpad-lite,lpagliari/etherpad-lite,storytouch/etherpad-lite,ether/etherpad-lite,cloudfoundry-community/etherpad-lite-cf,aptivate/etherpad-lite,aptivate/etherpad-lite,cloudfoundry-community/etherpad-lite-cf,storytouch/etherpad-lite,ether/etherpad-lite,aptivate/etherpad-lite,lpagliari/etherpad-lite,University-of-Potsdam-MM/etherpad-lite,joequant/etherpad-lite,University-of-Potsdam-MM/etherpad-lite,cloudfoundry-community/etherpad-lite-cf,ether/etherpad-lite,University-of-Potsdam-MM/etherpad-lite,University-of-Potsdam-MM/etherpad-lite,joequant/etherpad-lite | /**
* The AuthorManager controlls all information about the Pad authors
*/
/*
* 2011 Peter 'Pita' Martischka (Primary Technology 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.
*/
var ERR = require("async-stacktrace");
var db = require("./DB").db;
var customError = require("../utils/customError");
var randomString = require('ep_etherpad-lite/static/js/pad_utils').randomString;
exports.getColorPalette = function(){
return ["#ffc7c7", "#fff1c7", "#e3ffc7", "#c7ffd5", "#c7ffff", "#c7d5ff", "#e3c7ff", "#ffc7f1", "#ffa8a8", "#ffe699", "#cfff9e", "#99ffb3", "#a3ffff", "#99b3ff", "#cc99ff", "#ff99e5", "#e7b1b1", "#e9dcAf", "#cde9af", "#bfedcc", "#b1e7e7", "#c3cdee", "#d2b8ea", "#eec3e6", "#e9cece", "#e7e0ca", "#d3e5c7", "#bce1c5", "#c1e2e2", "#c1c9e2", "#cfc1e2", "#e0bdd9", "#baded3", "#a0f8eb", "#b1e7e0", "#c3c8e4", "#cec5e2", "#b1d5e7", "#cda8f0", "#f0f0a8", "#f2f2a6", "#f5a8eb", "#c5f9a9", "#ececbb", "#e7c4bc", "#daf0b2", "#b0a0fd", "#bce2e7", "#cce2bb", "#ec9afe", "#edabbd", "#aeaeea", "#c4e7b1", "#d722bb", "#f3a5e7", "#ffa8a8", "#d8c0c5", "#eaaedd", "#adc6eb", "#bedad1", "#dee9af", "#e9afc2", "#f8d2a0", "#b3b3e6"];
};
/**
* Checks if the author exists
*/
exports.doesAuthorExists = function (authorID, callback)
{
//check if the database entry of this author exists
db.get("globalAuthor:" + authorID, function (err, author)
{
if(ERR(err, callback)) return;
callback(null, author != null);
});
}
/**
* Returns the AuthorID for a token.
* @param {String} token The token
* @param {Function} callback callback (err, author)
*/
exports.getAuthor4Token = function (token, callback)
{
mapAuthorWithDBKey("token2author", token, function(err, author)
{
if(ERR(err, callback)) return;
//return only the sub value authorID
callback(null, author ? author.authorID : author);
});
}
/**
* Returns the AuthorID for a mapper.
* @param {String} token The mapper
* @param {String} name The name of the author (optional)
* @param {Function} callback callback (err, author)
*/
exports.createAuthorIfNotExistsFor = function (authorMapper, name, callback)
{
mapAuthorWithDBKey("mapper2author", authorMapper, function(err, author)
{
if(ERR(err, callback)) return;
//set the name of this author
if(name)
exports.setAuthorName(author.authorID, name);
//return the authorID
callback(null, author);
});
}
/**
* Returns the AuthorID for a mapper. We can map using a mapperkey,
* so far this is token2author and mapper2author
* @param {String} mapperkey The database key name for this mapper
* @param {String} mapper The mapper
* @param {Function} callback callback (err, author)
*/
function mapAuthorWithDBKey (mapperkey, mapper, callback)
{
//try to map to an author
db.get(mapperkey + ":" + mapper, function (err, author)
{
if(ERR(err, callback)) return;
//there is no author with this mapper, so create one
if(author == null)
{
exports.createAuthor(null, function(err, author)
{
if(ERR(err, callback)) return;
//create the token2author relation
db.set(mapperkey + ":" + mapper, author.authorID);
//return the author
callback(null, author);
});
return;
}
//there is a author with this mapper
//update the timestamp of this author
db.setSub("globalAuthor:" + author, ["timestamp"], new Date().getTime());
//return the author
callback(null, {authorID: author});
});
}
/**
* Internal function that creates the database entry for an author
* @param {String} name The name of the author
*/
exports.createAuthor = function(name, callback)
{
//create the new author name
var author = "a." + randomString(16);
//create the globalAuthors db entry
var authorObj = {"colorId" : Math.floor(Math.random()*(exports.getColorPalette().length)), "name": name, "timestamp": new Date().getTime()};
//set the global author db entry
db.set("globalAuthor:" + author, authorObj);
callback(null, {authorID: author});
}
/**
* Returns the Author Obj of the author
* @param {String} author The id of the author
* @param {Function} callback callback(err, authorObj)
*/
exports.getAuthor = function (author, callback)
{
db.get("globalAuthor:" + author, callback);
}
/**
* Returns the color Id of the author
* @param {String} author The id of the author
* @param {Function} callback callback(err, colorId)
*/
exports.getAuthorColorId = function (author, callback)
{
db.getSub("globalAuthor:" + author, ["colorId"], callback);
}
/**
* Sets the color Id of the author
* @param {String} author The id of the author
* @param {String} colorId The color id of the author
* @param {Function} callback (optional)
*/
exports.setAuthorColorId = function (author, colorId, callback)
{
db.setSub("globalAuthor:" + author, ["colorId"], colorId, callback);
}
/**
* Returns the name of the author
* @param {String} author The id of the author
* @param {Function} callback callback(err, name)
*/
exports.getAuthorName = function (author, callback)
{
db.getSub("globalAuthor:" + author, ["name"], callback);
}
/**
* Sets the name of the author
* @param {String} author The id of the author
* @param {String} name The name of the author
* @param {Function} callback (optional)
*/
exports.setAuthorName = function (author, name, callback)
{
db.setSub("globalAuthor:" + author, ["name"], name, callback);
}
/**
* Returns an array of all pads this author contributed to
* @param {String} author The id of the author
* @param {Function} callback (optional)
*/
exports.listPadsOfAuthor = function (authorID, callback)
{
/* There are two other places where this array is manipulated:
* (1) When the author is added to a pad, the author object is also updated
* (2) When a pad is deleted, each author of that pad is also updated
*/
//get the globalAuthor
db.get("globalAuthor:" + authorID, function(err, author)
{
if(ERR(err, callback)) return;
//author does not exists
if(author == null)
{
callback(new customError("authorID does not exist","apierror"))
}
//everything is fine, return the pad IDs
else
{
var pads = [];
if(author.padIDs != null)
{
for (var padId in author.padIDs)
{
pads.push(padId);
}
}
callback(null, {padIDs: pads});
}
});
}
/**
* Adds a new pad to the list of contributions
* @param {String} author The id of the author
* @param {String} padID The id of the pad the author contributes to
*/
exports.addPad = function (authorID, padID)
{
//get the entry
db.get("globalAuthor:" + authorID, function(err, author)
{
if(ERR(err)) return;
if(author == null) return;
//the entry doesn't exist so far, let's create it
if(author.padIDs == null)
{
author.padIDs = {};
}
//add the entry for this pad
author.padIDs[padID] = 1;// anything, because value is not used
//save the new element back
db.set("globalAuthor:" + authorID, author);
});
}
/**
* Removes a pad from the list of contributions
* @param {String} author The id of the author
* @param {String} padID The id of the pad the author contributes to
*/
exports.removePad = function (authorID, padID)
{
db.get("globalAuthor:" + authorID, function (err, author)
{
if(ERR(err)) return;
if(author == null) return;
if(author.padIDs != null)
{
//remove pad from author
delete author.padIDs[padID];
db.set("globalAuthor:" + authorID, author);
}
});
}
| src/node/db/AuthorManager.js | /**
* The AuthorManager controlls all information about the Pad authors
*/
/*
* 2011 Peter 'Pita' Martischka (Primary Technology 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.
*/
var ERR = require("async-stacktrace");
var db = require("./DB").db;
var customError = require("../utils/customError");
var randomString = require('ep_etherpad-lite/static/js/pad_utils').randomString;
exports.getColorPalette = function(){
return ["#ffc7c7", "#fff1c7", "#e3ffc7", "#c7ffd5", "#c7ffff", "#c7d5ff", "#e3c7ff", "#ffc7f1", "#ffa8a8", "#ffe699", "#cfff9e", "#99ffb3", "#a3ffff", "#99b3ff", "#cc99ff", "#ff99e5", "#e7b1b1", "#e9dcAf", "#cde9af", "#bfedcc", "#b1e7e7", "#c3cdee", "#d2b8ea", "#eec3e6", "#e9cece", "#e7e0ca", "#d3e5c7", "#bce1c5", "#c1e2e2", "#c1c9e2", "#cfc1e2", "#e0bdd9", "#baded3", "#a0f8eb", "#b1e7e0", "#c3c8e4", "#cec5e2", "#b1d5e7", "#cda8f0", "#f0f0a8", "#f2f2a6", "#f5a8eb", "#c5f9a9", "#ececbb", "#e7c4bc", "#daf0b2", "#b0a0fd", "#bce2e7", "#cce2bb", "#ec9afe", "#edabbd", "#aeaeea", "#c4e7b1", "#d722bb", "#f3a5e7", "#ffa8a8", "#d8c0c5", "#eaaedd", "#adc6eb", "#bedad1", "#dee9af", "#e9afc2", "#f8d2a0", "#b3b3e6"];
};
/**
* Checks if the author exists
*/
exports.doesAuthorExists = function (authorID, callback)
{
//check if the database entry of this author exists
db.get("globalAuthor:" + authorID, function (err, author)
{
if(ERR(err, callback)) return;
callback(null, author != null);
});
}
/**
* Returns the AuthorID for a token.
* @param {String} token The token
* @param {Function} callback callback (err, author)
*/
exports.getAuthor4Token = function (token, callback)
{
mapAuthorWithDBKey("token2author", token, function(err, author)
{
if(ERR(err, callback)) return;
//return only the sub value authorID
callback(null, author ? author.authorID : author);
});
}
/**
* Returns the AuthorID for a mapper.
* @param {String} token The mapper
* @param {String} name The name of the author (optional)
* @param {Function} callback callback (err, author)
*/
exports.createAuthorIfNotExistsFor = function (authorMapper, name, callback)
{
mapAuthorWithDBKey("mapper2author", authorMapper, function(err, author)
{
if(ERR(err, callback)) return;
//set the name of this author
if(name)
exports.setAuthorName(author.authorID, name);
//return the authorID
callback(null, author);
});
}
/**
* Returns the AuthorID for a mapper. We can map using a mapperkey,
* so far this is token2author and mapper2author
* @param {String} mapperkey The database key name for this mapper
* @param {String} mapper The mapper
* @param {Function} callback callback (err, author)
*/
function mapAuthorWithDBKey (mapperkey, mapper, callback)
{
//try to map to an author
db.get(mapperkey + ":" + mapper, function (err, author)
{
if(ERR(err, callback)) return;
//there is no author with this mapper, so create one
if(author == null)
{
exports.createAuthor(null, function(err, author)
{
if(ERR(err, callback)) return;
//create the token2author relation
db.set(mapperkey + ":" + mapper, author.authorID);
//return the author
callback(null, author);
});
}
//there is a author with this mapper
else
{
//update the timestamp of this author
db.setSub("globalAuthor:" + author, ["timestamp"], new Date().getTime());
//return the author
callback(null, {authorID: author});
}
});
}
/**
* Internal function that creates the database entry for an author
* @param {String} name The name of the author
*/
exports.createAuthor = function(name, callback)
{
//create the new author name
var author = "a." + randomString(16);
//create the globalAuthors db entry
var authorObj = {"colorId" : Math.floor(Math.random()*(exports.getColorPalette().length)), "name": name, "timestamp": new Date().getTime()};
//set the global author db entry
db.set("globalAuthor:" + author, authorObj);
callback(null, {authorID: author});
}
/**
* Returns the Author Obj of the author
* @param {String} author The id of the author
* @param {Function} callback callback(err, authorObj)
*/
exports.getAuthor = function (author, callback)
{
db.get("globalAuthor:" + author, callback);
}
/**
* Returns the color Id of the author
* @param {String} author The id of the author
* @param {Function} callback callback(err, colorId)
*/
exports.getAuthorColorId = function (author, callback)
{
db.getSub("globalAuthor:" + author, ["colorId"], callback);
}
/**
* Sets the color Id of the author
* @param {String} author The id of the author
* @param {String} colorId The color id of the author
* @param {Function} callback (optional)
*/
exports.setAuthorColorId = function (author, colorId, callback)
{
db.setSub("globalAuthor:" + author, ["colorId"], colorId, callback);
}
/**
* Returns the name of the author
* @param {String} author The id of the author
* @param {Function} callback callback(err, name)
*/
exports.getAuthorName = function (author, callback)
{
db.getSub("globalAuthor:" + author, ["name"], callback);
}
/**
* Sets the name of the author
* @param {String} author The id of the author
* @param {String} name The name of the author
* @param {Function} callback (optional)
*/
exports.setAuthorName = function (author, name, callback)
{
db.setSub("globalAuthor:" + author, ["name"], name, callback);
}
/**
* Returns an array of all pads this author contributed to
* @param {String} author The id of the author
* @param {Function} callback (optional)
*/
exports.listPadsOfAuthor = function (authorID, callback)
{
/* There are two other places where this array is manipulated:
* (1) When the author is added to a pad, the author object is also updated
* (2) When a pad is deleted, each author of that pad is also updated
*/
//get the globalAuthor
db.get("globalAuthor:" + authorID, function(err, author)
{
if(ERR(err, callback)) return;
//author does not exists
if(author == null)
{
callback(new customError("authorID does not exist","apierror"))
}
//everything is fine, return the pad IDs
else
{
var pads = [];
if(author.padIDs != null)
{
for (var padId in author.padIDs)
{
pads.push(padId);
}
}
callback(null, {padIDs: pads});
}
});
}
/**
* Adds a new pad to the list of contributions
* @param {String} author The id of the author
* @param {String} padID The id of the pad the author contributes to
*/
exports.addPad = function (authorID, padID)
{
//get the entry
db.get("globalAuthor:" + authorID, function(err, author)
{
if(ERR(err)) return;
if(author == null) return;
//the entry doesn't exist so far, let's create it
if(author.padIDs == null)
{
author.padIDs = {};
}
//add the entry for this pad
author.padIDs[padID] = 1;// anything, because value is not used
//save the new element back
db.set("globalAuthor:" + authorID, author);
});
}
/**
* Removes a pad from the list of contributions
* @param {String} author The id of the author
* @param {String} padID The id of the pad the author contributes to
*/
exports.removePad = function (authorID, padID)
{
db.get("globalAuthor:" + authorID, function (err, author)
{
if(ERR(err)) return;
if(author == null) return;
if(author.padIDs != null)
{
//remove pad from author
delete author.padIDs[padID];
db.set("globalAuthor:" + authorID, author);
}
});
}
| db/AuthorManager: early return, no functional changes
| src/node/db/AuthorManager.js | db/AuthorManager: early return, no functional changes | <ide><path>rc/node/db/AuthorManager.js
<ide> //return the author
<ide> callback(null, author);
<ide> });
<del> }
<add>
<add> return;
<add> }
<add>
<ide> //there is a author with this mapper
<del> else
<del> {
<del> //update the timestamp of this author
<del> db.setSub("globalAuthor:" + author, ["timestamp"], new Date().getTime());
<del>
<del> //return the author
<del> callback(null, {authorID: author});
<del> }
<add> //update the timestamp of this author
<add> db.setSub("globalAuthor:" + author, ["timestamp"], new Date().getTime());
<add>
<add> //return the author
<add> callback(null, {authorID: author});
<ide> });
<ide> }
<ide> |
|
Java | lgpl-2.1 | dc1f5e5975ff3d43fb907c4a7ea86747d41ed497 | 0 | aruanruan/hivedb,britt/hivedb | package org.hivedb.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface IndexParam {
String value();
}
| src/main/java/org/hivedb/annotations/IndexParam.java | package org.hivedb.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.hivedb.annotations.IndexRangeParam.Extreme;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface IndexParam {
String value();
}
| fix
git-svn-id: 844d946efecc0c73e9bbe621f4e6d7ad48f82261@650 8f33570f-f526-0410-8023-93ba2dbcbd24
| src/main/java/org/hivedb/annotations/IndexParam.java | fix | <ide><path>rc/main/java/org/hivedb/annotations/IndexParam.java
<ide> import java.lang.annotation.RetentionPolicy;
<ide> import java.lang.annotation.Target;
<ide>
<del>import org.hivedb.annotations.IndexRangeParam.Extreme;
<del>
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @Target(ElementType.PARAMETER)
<ide> public @interface IndexParam { |
|
Java | apache-2.0 | 4ca34c0b1bcb9deab6fe38b9825c7ca78ce35fd7 | 0 | MovingBlocks/Terasology,Nanoware/Terasology,Nanoware/Terasology,Malanius/Terasology,MovingBlocks/Terasology,Malanius/Terasology,MovingBlocks/Terasology,Nanoware/Terasology | /*
* Copyright 2013 MovingBlocks
*
* 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.terasology.math;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import org.joml.Vector3ic;
import org.terasology.math.geom.Vector3f;
import org.terasology.math.geom.Vector3i;
import java.util.EnumMap;
import java.util.EnumSet;
/**
* The six sides of a block and a slew of related utility.
* <br><br>
* Note that the FRONT of the block faces towards the player - this means Left and Right are a player's right and left.
* See Direction for an enumeration of directions in terms of the player's perspective.
*
*/
public enum Side {
TOP(Vector3i.up(), true, false, true),
BOTTOM(Vector3i.down(), true, false, true),
LEFT(new Vector3i(-1, 0, 0), false, true, true),
RIGHT(new Vector3i(1, 0, 0), false, true, true),
FRONT(new Vector3i(0, 0, -1), true, true, false),
BACK(new Vector3i(0, 0, 1), true, true, false);
private static final EnumSet<Side> ALL_SIDES = EnumSet.allOf(Side.class);
private static final EnumMap<Side, Side> REVERSE_MAP;
private static final ImmutableList<Side> HORIZONTAL_SIDES;
private static final ImmutableList<Side> VERTICAL_SIDES;
private static final EnumMap<Side, Side> CLOCKWISE_YAW_SIDE;
private static final EnumMap<Side, Side> ANTICLOCKWISE_YAW_SIDE;
private static final EnumMap<Side, Side> CLOCKWISE_PITCH_SIDE;
private static final EnumMap<Side, Side> ANTICLOCKWISE_PITCH_SIDE;
private static final EnumMap<Side, Side> CLOCKWISE_ROLL_SIDE;
private static final EnumMap<Side, Side> ANTICLOCKWISE_ROLL_SIDE;
private static final EnumMap<Side, Direction> CONVERSION_MAP;
private static final EnumMap<Side, ImmutableList<Side>> TANGENTS;
static {
TANGENTS = new EnumMap<>(Side.class);
TANGENTS.put(TOP, ImmutableList.of(LEFT, RIGHT, FRONT, BACK));
TANGENTS.put(BOTTOM, ImmutableList.of(LEFT, RIGHT, FRONT, BACK));
TANGENTS.put(LEFT, ImmutableList.of(TOP, BOTTOM, FRONT, BACK));
TANGENTS.put(RIGHT, ImmutableList.of(TOP, BOTTOM, FRONT, BACK));
TANGENTS.put(FRONT, ImmutableList.of(TOP, BOTTOM, LEFT, RIGHT));
TANGENTS.put(BACK, ImmutableList.of(TOP, BOTTOM, LEFT, RIGHT));
REVERSE_MAP = new EnumMap<>(Side.class);
REVERSE_MAP.put(TOP, BOTTOM);
REVERSE_MAP.put(LEFT, RIGHT);
REVERSE_MAP.put(RIGHT, LEFT);
REVERSE_MAP.put(FRONT, BACK);
REVERSE_MAP.put(BACK, FRONT);
REVERSE_MAP.put(BOTTOM, TOP);
CONVERSION_MAP = new EnumMap<>(Side.class);
CONVERSION_MAP.put(TOP, Direction.UP);
CONVERSION_MAP.put(BOTTOM, Direction.DOWN);
CONVERSION_MAP.put(BACK, Direction.FORWARD);
CONVERSION_MAP.put(FRONT, Direction.BACKWARD);
CONVERSION_MAP.put(RIGHT, Direction.LEFT);
CONVERSION_MAP.put(LEFT, Direction.RIGHT);
CLOCKWISE_YAW_SIDE = new EnumMap<>(Side.class);
ANTICLOCKWISE_YAW_SIDE = new EnumMap<>(Side.class);
CLOCKWISE_YAW_SIDE.put(Side.FRONT, Side.LEFT);
ANTICLOCKWISE_YAW_SIDE.put(Side.FRONT, Side.RIGHT);
CLOCKWISE_YAW_SIDE.put(Side.RIGHT, Side.FRONT);
ANTICLOCKWISE_YAW_SIDE.put(Side.RIGHT, Side.BACK);
CLOCKWISE_YAW_SIDE.put(Side.BACK, Side.RIGHT);
ANTICLOCKWISE_YAW_SIDE.put(Side.BACK, Side.LEFT);
CLOCKWISE_YAW_SIDE.put(Side.LEFT, Side.BACK);
ANTICLOCKWISE_YAW_SIDE.put(Side.LEFT, Side.FRONT);
CLOCKWISE_PITCH_SIDE = Maps.newEnumMap(Side.class);
ANTICLOCKWISE_PITCH_SIDE = Maps.newEnumMap(Side.class);
CLOCKWISE_PITCH_SIDE.put(Side.FRONT, Side.TOP);
ANTICLOCKWISE_PITCH_SIDE.put(Side.FRONT, Side.BOTTOM);
CLOCKWISE_PITCH_SIDE.put(Side.BOTTOM, Side.FRONT);
ANTICLOCKWISE_PITCH_SIDE.put(Side.BOTTOM, Side.BACK);
CLOCKWISE_PITCH_SIDE.put(Side.BACK, Side.BOTTOM);
ANTICLOCKWISE_PITCH_SIDE.put(Side.BACK, Side.TOP);
CLOCKWISE_PITCH_SIDE.put(Side.TOP, Side.BACK);
ANTICLOCKWISE_PITCH_SIDE.put(Side.TOP, Side.FRONT);
CLOCKWISE_ROLL_SIDE = Maps.newEnumMap(Side.class);
ANTICLOCKWISE_ROLL_SIDE = Maps.newEnumMap(Side.class);
CLOCKWISE_ROLL_SIDE.put(Side.TOP, Side.LEFT);
ANTICLOCKWISE_ROLL_SIDE.put(Side.TOP, Side.RIGHT);
CLOCKWISE_ROLL_SIDE.put(Side.LEFT, Side.BOTTOM);
ANTICLOCKWISE_ROLL_SIDE.put(Side.LEFT, Side.TOP);
CLOCKWISE_ROLL_SIDE.put(Side.BOTTOM, Side.RIGHT);
ANTICLOCKWISE_ROLL_SIDE.put(Side.BOTTOM, Side.LEFT);
CLOCKWISE_ROLL_SIDE.put(Side.RIGHT, Side.TOP);
ANTICLOCKWISE_ROLL_SIDE.put(Side.RIGHT, Side.BOTTOM);
HORIZONTAL_SIDES = ImmutableList.of(LEFT, RIGHT, FRONT, BACK);
VERTICAL_SIDES = ImmutableList.of(TOP, BOTTOM);
}
private final Vector3i vector3iDir;
private final boolean canYaw;
private final boolean canPitch;
private final boolean canRoll;
Side(Vector3i vector3i, boolean canPitch, boolean canYaw, boolean canRoll) {
this.vector3iDir = vector3i;
this.canPitch = canPitch;
this.canYaw = canYaw;
this.canRoll = canRoll;
}
/**
* @return The horizontal sides, for iteration
*/
public static ImmutableList<Side> horizontalSides() {
return HORIZONTAL_SIDES;
}
/**
* @return The vertical sides, for iteration
*/
public static ImmutableList<Side> verticalSides() {
return VERTICAL_SIDES;
}
public static Side inDirection(int x, int y, int z) {
if (TeraMath.fastAbs(x) > TeraMath.fastAbs(y)) {
if (TeraMath.fastAbs(x) > TeraMath.fastAbs(z)) {
return (x > 0) ? RIGHT : LEFT;
}
} else if (TeraMath.fastAbs(y) > TeraMath.fastAbs(z)) {
return (y > 0) ? TOP : BOTTOM;
}
return (z > 0) ? BACK : FRONT;
}
public static Side inDirection(Vector3f dir) {
return inDirection(dir.x, dir.y, dir.z);
}
/**
* Determines which direction the player is facing
*
* @param x right/left
* @param y top/bottom
* @param z back/front
* @return Side enum with the appropriate direction
*/
public static Side inDirection(double x, double y, double z) {
if (TeraMath.fastAbs(x) > TeraMath.fastAbs(y)) {
if (TeraMath.fastAbs(x) > TeraMath.fastAbs(z)) {
return (x > 0) ? RIGHT : LEFT;
}
} else if (TeraMath.fastAbs(y) > TeraMath.fastAbs(z)) {
return (y > 0) ? TOP : BOTTOM;
}
return (z > 0) ? BACK : FRONT;
}
/**
* Determines which horizontal direction the player is facing
*
* @param x right/left
* @param z back/front
* @return Side enum with the appropriate direction
*/
public static Side inHorizontalDirection(double x, double z) {
if (TeraMath.fastAbs(x) > TeraMath.fastAbs(z)) {
return (x > 0) ? RIGHT : LEFT;
}
return (z > 0) ? BACK : FRONT;
}
/**
* This provides a static EnumSet of all Sides defined in the enumeration. The result contains the same values as
* calling {@code Side#values} but this does not create a new copy on every call.
* <br/>
* <b>Warning:</b> Do not change the content of the returned enum set! It will be reflected on all calls to this method.
* @return All available sides
*/
public static EnumSet<Side> getAllSides() {
return ALL_SIDES;
}
/**
* @return The vector3i in the direction of the side. Do not modify.
* @deprecated This method is scheduled for removal in an upcoming version.
* Use the JOML implementation instead: {@link #direction()} .
*/
@Deprecated
public Vector3i getVector3i() {
return vector3iDir;
}
/**
* the normal vector in the direction of the side
* @return a normalized vector
*/
public Vector3ic direction() {
return JomlUtil.from(vector3iDir);
}
/**
* @return Whether this is one of the horizontal directions (LEFT, FRONT, RIGHT, BACK).
*/
public boolean isHorizontal() {
return canYaw;
}
/**
* @return Whether this is one of the vertical directions (TOP, BOTTOM).
*/
public boolean isVertical() {
return !canYaw;
}
/**
* @return The opposite side to this side.
*/
public Side reverse() {
return REVERSE_MAP.get(this);
}
public Side yawClockwise(int turns) {
if (!canYaw) {
return this;
}
int steps = turns;
if (steps < 0) {
steps = -steps + 2;
}
steps = steps % 4;
switch (steps) {
case 1:
return CLOCKWISE_YAW_SIDE.get(this);
case 2:
return REVERSE_MAP.get(this);
case 3:
return ANTICLOCKWISE_YAW_SIDE.get(this);
default:
return this;
}
}
public Side pitchClockwise(int turns) {
if (!canPitch) {
return this;
}
int steps = turns;
if (steps < 0) {
steps = -steps + 2;
}
steps = steps % 4;
switch (steps) {
case 1:
return CLOCKWISE_PITCH_SIDE.get(this);
case 2:
return REVERSE_MAP.get(this);
case 3:
return ANTICLOCKWISE_PITCH_SIDE.get(this);
default:
return this;
}
}
public Direction toDirection() {
return CONVERSION_MAP.get(this);
}
public Side rollClockwise(int turns) {
if (!canRoll) {
return this;
}
int steps = turns;
if (steps < 0) {
steps = -steps + 2;
}
steps = steps % 4;
switch (steps) {
case 1:
return CLOCKWISE_ROLL_SIDE.get(this);
case 2:
return REVERSE_MAP.get(this);
case 3:
return ANTICLOCKWISE_ROLL_SIDE.get(this);
default:
return this;
}
}
/**
*
* @param position
* @return
* @deprecated This method is scheduled for removal in an upcoming version.
* Use the JOML implementation instead: {@link #getAdjacentPos(Vector3ic, org.joml.Vector3i)} .
*
**/
@Deprecated
public Vector3i getAdjacentPos(Vector3i position) {
Vector3i result = new Vector3i(position);
result.add(vector3iDir);
return result;
}
/**
* take the current pos and add the direction
*
* @param pos current position
* @param dest will hold the result
* @return dest
*/
public org.joml.Vector3i getAdjacentPos(Vector3ic pos, org.joml.Vector3i dest){
return dest.set(pos).add(direction());
}
public Side getRelativeSide(Direction direction) {
if (direction == Direction.UP) {
return pitchClockwise(1);
} else if (direction == Direction.DOWN) {
return pitchClockwise(-1);
} else if (direction == Direction.LEFT) {
return yawClockwise(1);
} else if (direction == Direction.RIGHT) {
return yawClockwise(-1);
} else if (direction == Direction.BACKWARD) {
return reverse();
} else {
return this;
}
}
public Iterable<Side> tangents() {
return TANGENTS.get(this);
}
}
| engine/src/main/java/org/terasology/math/Side.java | /*
* Copyright 2013 MovingBlocks
*
* 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.terasology.math;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import org.terasology.math.geom.Vector3f;
import org.terasology.math.geom.Vector3i;
import java.util.EnumMap;
import java.util.EnumSet;
/**
* The six sides of a block and a slew of related utility.
* <br><br>
* Note that the FRONT of the block faces towards the player - this means Left and Right are a player's right and left.
* See Direction for an enumeration of directions in terms of the player's perspective.
*
*/
public enum Side {
TOP(Vector3i.up(), true, false, true),
BOTTOM(Vector3i.down(), true, false, true),
LEFT(new Vector3i(-1, 0, 0), false, true, true),
RIGHT(new Vector3i(1, 0, 0), false, true, true),
FRONT(new Vector3i(0, 0, -1), true, true, false),
BACK(new Vector3i(0, 0, 1), true, true, false);
private static final EnumSet<Side> ALL_SIDES = EnumSet.allOf(Side.class);
private static final EnumMap<Side, Side> REVERSE_MAP;
private static final ImmutableList<Side> HORIZONTAL_SIDES;
private static final ImmutableList<Side> VERTICAL_SIDES;
private static final EnumMap<Side, Side> CLOCKWISE_YAW_SIDE;
private static final EnumMap<Side, Side> ANTICLOCKWISE_YAW_SIDE;
private static final EnumMap<Side, Side> CLOCKWISE_PITCH_SIDE;
private static final EnumMap<Side, Side> ANTICLOCKWISE_PITCH_SIDE;
private static final EnumMap<Side, Side> CLOCKWISE_ROLL_SIDE;
private static final EnumMap<Side, Side> ANTICLOCKWISE_ROLL_SIDE;
private static final EnumMap<Side, Direction> CONVERSION_MAP;
private static final EnumMap<Side, ImmutableList<Side>> TANGENTS;
static {
TANGENTS = new EnumMap<>(Side.class);
TANGENTS.put(TOP, ImmutableList.of(LEFT, RIGHT, FRONT, BACK));
TANGENTS.put(BOTTOM, ImmutableList.of(LEFT, RIGHT, FRONT, BACK));
TANGENTS.put(LEFT, ImmutableList.of(TOP, BOTTOM, FRONT, BACK));
TANGENTS.put(RIGHT, ImmutableList.of(TOP, BOTTOM, FRONT, BACK));
TANGENTS.put(FRONT, ImmutableList.of(TOP, BOTTOM, LEFT, RIGHT));
TANGENTS.put(BACK, ImmutableList.of(TOP, BOTTOM, LEFT, RIGHT));
REVERSE_MAP = new EnumMap<>(Side.class);
REVERSE_MAP.put(TOP, BOTTOM);
REVERSE_MAP.put(LEFT, RIGHT);
REVERSE_MAP.put(RIGHT, LEFT);
REVERSE_MAP.put(FRONT, BACK);
REVERSE_MAP.put(BACK, FRONT);
REVERSE_MAP.put(BOTTOM, TOP);
CONVERSION_MAP = new EnumMap<>(Side.class);
CONVERSION_MAP.put(TOP, Direction.UP);
CONVERSION_MAP.put(BOTTOM, Direction.DOWN);
CONVERSION_MAP.put(BACK, Direction.FORWARD);
CONVERSION_MAP.put(FRONT, Direction.BACKWARD);
CONVERSION_MAP.put(RIGHT, Direction.LEFT);
CONVERSION_MAP.put(LEFT, Direction.RIGHT);
CLOCKWISE_YAW_SIDE = new EnumMap<>(Side.class);
ANTICLOCKWISE_YAW_SIDE = new EnumMap<>(Side.class);
CLOCKWISE_YAW_SIDE.put(Side.FRONT, Side.LEFT);
ANTICLOCKWISE_YAW_SIDE.put(Side.FRONT, Side.RIGHT);
CLOCKWISE_YAW_SIDE.put(Side.RIGHT, Side.FRONT);
ANTICLOCKWISE_YAW_SIDE.put(Side.RIGHT, Side.BACK);
CLOCKWISE_YAW_SIDE.put(Side.BACK, Side.RIGHT);
ANTICLOCKWISE_YAW_SIDE.put(Side.BACK, Side.LEFT);
CLOCKWISE_YAW_SIDE.put(Side.LEFT, Side.BACK);
ANTICLOCKWISE_YAW_SIDE.put(Side.LEFT, Side.FRONT);
CLOCKWISE_PITCH_SIDE = Maps.newEnumMap(Side.class);
ANTICLOCKWISE_PITCH_SIDE = Maps.newEnumMap(Side.class);
CLOCKWISE_PITCH_SIDE.put(Side.FRONT, Side.TOP);
ANTICLOCKWISE_PITCH_SIDE.put(Side.FRONT, Side.BOTTOM);
CLOCKWISE_PITCH_SIDE.put(Side.BOTTOM, Side.FRONT);
ANTICLOCKWISE_PITCH_SIDE.put(Side.BOTTOM, Side.BACK);
CLOCKWISE_PITCH_SIDE.put(Side.BACK, Side.BOTTOM);
ANTICLOCKWISE_PITCH_SIDE.put(Side.BACK, Side.TOP);
CLOCKWISE_PITCH_SIDE.put(Side.TOP, Side.BACK);
ANTICLOCKWISE_PITCH_SIDE.put(Side.TOP, Side.FRONT);
CLOCKWISE_ROLL_SIDE = Maps.newEnumMap(Side.class);
ANTICLOCKWISE_ROLL_SIDE = Maps.newEnumMap(Side.class);
CLOCKWISE_ROLL_SIDE.put(Side.TOP, Side.LEFT);
ANTICLOCKWISE_ROLL_SIDE.put(Side.TOP, Side.RIGHT);
CLOCKWISE_ROLL_SIDE.put(Side.LEFT, Side.BOTTOM);
ANTICLOCKWISE_ROLL_SIDE.put(Side.LEFT, Side.TOP);
CLOCKWISE_ROLL_SIDE.put(Side.BOTTOM, Side.RIGHT);
ANTICLOCKWISE_ROLL_SIDE.put(Side.BOTTOM, Side.LEFT);
CLOCKWISE_ROLL_SIDE.put(Side.RIGHT, Side.TOP);
ANTICLOCKWISE_ROLL_SIDE.put(Side.RIGHT, Side.BOTTOM);
HORIZONTAL_SIDES = ImmutableList.of(LEFT, RIGHT, FRONT, BACK);
VERTICAL_SIDES = ImmutableList.of(TOP, BOTTOM);
}
private final Vector3i vector3iDir;
private final boolean canYaw;
private final boolean canPitch;
private final boolean canRoll;
Side(Vector3i vector3i, boolean canPitch, boolean canYaw, boolean canRoll) {
this.vector3iDir = vector3i;
this.canPitch = canPitch;
this.canYaw = canYaw;
this.canRoll = canRoll;
}
/**
* @return The horizontal sides, for iteration
*/
public static ImmutableList<Side> horizontalSides() {
return HORIZONTAL_SIDES;
}
/**
* @return The vertical sides, for iteration
*/
public static ImmutableList<Side> verticalSides() {
return VERTICAL_SIDES;
}
public static Side inDirection(int x, int y, int z) {
if (TeraMath.fastAbs(x) > TeraMath.fastAbs(y)) {
if (TeraMath.fastAbs(x) > TeraMath.fastAbs(z)) {
return (x > 0) ? RIGHT : LEFT;
}
} else if (TeraMath.fastAbs(y) > TeraMath.fastAbs(z)) {
return (y > 0) ? TOP : BOTTOM;
}
return (z > 0) ? BACK : FRONT;
}
public static Side inDirection(Vector3f dir) {
return inDirection(dir.x, dir.y, dir.z);
}
/**
* Determines which direction the player is facing
*
* @param x right/left
* @param y top/bottom
* @param z back/front
* @return Side enum with the appropriate direction
*/
public static Side inDirection(double x, double y, double z) {
if (TeraMath.fastAbs(x) > TeraMath.fastAbs(y)) {
if (TeraMath.fastAbs(x) > TeraMath.fastAbs(z)) {
return (x > 0) ? RIGHT : LEFT;
}
} else if (TeraMath.fastAbs(y) > TeraMath.fastAbs(z)) {
return (y > 0) ? TOP : BOTTOM;
}
return (z > 0) ? BACK : FRONT;
}
/**
* Determines which horizontal direction the player is facing
*
* @param x right/left
* @param z back/front
* @return Side enum with the appropriate direction
*/
public static Side inHorizontalDirection(double x, double z) {
if (TeraMath.fastAbs(x) > TeraMath.fastAbs(z)) {
return (x > 0) ? RIGHT : LEFT;
}
return (z > 0) ? BACK : FRONT;
}
/**
* This provides a static EnumSet of all Sides defined in the enumeration. The result contains the same values as
* calling {@code Side#values} but this does not create a new copy on every call.
* <br/>
* <b>Warning:</b> Do not change the content of the returned enum set! It will be reflected on all calls to this method.
* @return All available sides
*/
public static EnumSet<Side> getAllSides() {
return ALL_SIDES;
}
/**
* @return The vector3i in the direction of the side. Do not modify.
*/
public Vector3i getVector3i() {
return vector3iDir;
}
/**
* @return Whether this is one of the horizontal directions (LEFT, FRONT, RIGHT, BACK).
*/
public boolean isHorizontal() {
return canYaw;
}
/**
* @return Whether this is one of the vertical directions (TOP, BOTTOM).
*/
public boolean isVertical() {
return !canYaw;
}
/**
* @return The opposite side to this side.
*/
public Side reverse() {
return REVERSE_MAP.get(this);
}
public Side yawClockwise(int turns) {
if (!canYaw) {
return this;
}
int steps = turns;
if (steps < 0) {
steps = -steps + 2;
}
steps = steps % 4;
switch (steps) {
case 1:
return CLOCKWISE_YAW_SIDE.get(this);
case 2:
return REVERSE_MAP.get(this);
case 3:
return ANTICLOCKWISE_YAW_SIDE.get(this);
default:
return this;
}
}
public Side pitchClockwise(int turns) {
if (!canPitch) {
return this;
}
int steps = turns;
if (steps < 0) {
steps = -steps + 2;
}
steps = steps % 4;
switch (steps) {
case 1:
return CLOCKWISE_PITCH_SIDE.get(this);
case 2:
return REVERSE_MAP.get(this);
case 3:
return ANTICLOCKWISE_PITCH_SIDE.get(this);
default:
return this;
}
}
public Direction toDirection() {
return CONVERSION_MAP.get(this);
}
public Side rollClockwise(int turns) {
if (!canRoll) {
return this;
}
int steps = turns;
if (steps < 0) {
steps = -steps + 2;
}
steps = steps % 4;
switch (steps) {
case 1:
return CLOCKWISE_ROLL_SIDE.get(this);
case 2:
return REVERSE_MAP.get(this);
case 3:
return ANTICLOCKWISE_ROLL_SIDE.get(this);
default:
return this;
}
}
public Vector3i getAdjacentPos(Vector3i position) {
Vector3i result = new Vector3i(position);
result.add(vector3iDir);
return result;
}
public Side getRelativeSide(Direction direction) {
if (direction == Direction.UP) {
return pitchClockwise(1);
} else if (direction == Direction.DOWN) {
return pitchClockwise(-1);
} else if (direction == Direction.LEFT) {
return yawClockwise(1);
} else if (direction == Direction.RIGHT) {
return yawClockwise(-1);
} else if (direction == Direction.BACKWARD) {
return reverse();
} else {
return this;
}
}
public Iterable<Side> tangents() {
return TANGENTS.get(this);
}
}
| feat(JOML) Migrate side
| engine/src/main/java/org/terasology/math/Side.java | feat(JOML) Migrate side | <ide><path>ngine/src/main/java/org/terasology/math/Side.java
<ide>
<ide> import com.google.common.collect.ImmutableList;
<ide> import com.google.common.collect.Maps;
<add>import org.joml.Vector3ic;
<ide> import org.terasology.math.geom.Vector3f;
<ide> import org.terasology.math.geom.Vector3i;
<ide>
<ide>
<ide> /**
<ide> * @return The vector3i in the direction of the side. Do not modify.
<del> */
<add> * @deprecated This method is scheduled for removal in an upcoming version.
<add> * Use the JOML implementation instead: {@link #direction()} .
<add> */
<add> @Deprecated
<ide> public Vector3i getVector3i() {
<ide> return vector3iDir;
<add> }
<add>
<add> /**
<add> * the normal vector in the direction of the side
<add> * @return a normalized vector
<add> */
<add> public Vector3ic direction() {
<add> return JomlUtil.from(vector3iDir);
<ide> }
<ide>
<ide> /**
<ide> }
<ide> }
<ide>
<add> /**
<add> *
<add> * @param position
<add> * @return
<add> * @deprecated This method is scheduled for removal in an upcoming version.
<add> * Use the JOML implementation instead: {@link #getAdjacentPos(Vector3ic, org.joml.Vector3i)} .
<add> *
<add> **/
<add> @Deprecated
<ide> public Vector3i getAdjacentPos(Vector3i position) {
<ide> Vector3i result = new Vector3i(position);
<ide> result.add(vector3iDir);
<ide> return result;
<add> }
<add>
<add> /**
<add> * take the current pos and add the direction
<add> *
<add> * @param pos current position
<add> * @param dest will hold the result
<add> * @return dest
<add> */
<add> public org.joml.Vector3i getAdjacentPos(Vector3ic pos, org.joml.Vector3i dest){
<add> return dest.set(pos).add(direction());
<ide> }
<ide>
<ide> public Side getRelativeSide(Direction direction) { |
|
Java | apache-2.0 | f7c45aaede7a048ab42686edeea0c7b1f9aa4f51 | 0 | eliasku/intellij-haxe,HaxeFoundation/intellij-haxe,TiVo/intellij-haxe,EricBishton/intellij-haxe,winmain/intellij-haxe,EricBishton/intellij-haxe,winmain/intellij-haxe,eliasku/intellij-haxe,winmain/intellij-haxe,EricBishton/intellij-haxe,TiVo/intellij-haxe,TiVo/intellij-haxe,eliasku/intellij-haxe,HaxeFoundation/intellij-haxe,HaxeFoundation/intellij-haxe | /*
* Copyright 2017 Eric Bishton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.plugins.haxe.util;
import javax.management.RuntimeErrorException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Track modifications to an entity.
*
* This class is intended to be used in two ways:
*
* - to keep track of modifications by creating "stamps" that can be captured and
* compared (for uniqueness) against another stamp. This is used in caches and
* whatnot to quickly check whether the state of an object has changed and the
* cache needs to be invalidated. A lightweight and lazy approach to tracking
* cohesion as opposed to a Listener interface.
*
* - (Not yet implemented) to act as a Listener registrant and notifier.
* TODO: Add the listener interface to this.
*
* Created by ebishton on 9/7/2017.
*/
public class HaxeModificationTracker {
// XXX: Maybe add a "disposed" state and set it true with the underlying object is no longer valid/used?
private static HaxeDebugLogger LOG = HaxeDebugLogger.getLogger();
private AtomicInteger updateCounter = new AtomicInteger(0);
private final String debugName;
private static int debugCount = 0;
public HaxeModificationTracker(String debugName) {
debugCount++;
this.debugName = debugName + "(" + Integer.toString(debugCount) + ")";
}
public Stamp getStamp() {
return new Stamp(updateCounter.get());
}
public boolean isModifiedSince(HaxeTrackedModifiable.Stamp s) {
if (s instanceof HaxeModificationTracker.Stamp) {
return isModifiedSince((HaxeModificationTracker.Stamp)s);
}
return true; // invalid stamp; always modified.
}
public boolean isModifiedSince(Stamp stamp) {
if (null == stamp) {
return true; // invalid stamp; always modified.
}
if (stamp.tracker != this) {
String msg = "Stamps can only be compared to their allocating Tracker.";
LOG.error(msg);
}
return this != stamp.tracker || updateCounter.get() != stamp.value;
}
public void notifyUpdated() {
updateCounter.incrementAndGet();
}
public class Stamp implements HaxeTrackedModifiable.Stamp {
private final int value;
private final HaxeModificationTracker tracker;
private Stamp(int value) {
this.value = value;
this.tracker = HaxeModificationTracker.this;
}
public boolean isOutOfDate() {
return tracker.isModifiedSince(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Stamp stamp = (Stamp)o;
if (value != stamp.value) return false;
return tracker.equals(stamp.tracker);
}
@Override
public int hashCode() {
int result = value;
result = 31 * result + tracker.hashCode();
return result;
}
}
}
| src/common/com/intellij/plugins/haxe/util/HaxeModificationTracker.java | /*
* Copyright 2017 Eric Bishton
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.plugins.haxe.util;
import javax.management.RuntimeErrorException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Track modifications to an entity.
*
* This class is intended to be used in two ways:
*
* - to keep track of modifications by creating "stamps" that can be captured and
* compared (for uniqueness) against another stamp. This is used in caches and
* whatnot to quickly check whether the state of an object has changed and the
* cache needs to be invalidated. A lightweight and lazy approach to tracking
* cohesion as opposed to a Listener interface.
*
* - (Not yet implemented) to act as a Listener registrant and notifier.
* TODO: Add the listener interface to this.
*
* Created by ebishton on 9/7/2017.
*/
public class HaxeModificationTracker {
// XXX: Maybe add a "disposed" state and set it true with the underlying object is no longer valid/used?
private static HaxeDebugLogger LOG = HaxeDebugLogger.getLogger();
private AtomicInteger updateCounter = new AtomicInteger(0);
private final String debugName;
private static int debugCount = 0;
public HaxeModificationTracker(String debugName) {
debugCount++;
this.debugName = debugName + "(" + Integer.toString(debugCount) + ")";
}
public Stamp getStamp() {
return new Stamp(updateCounter.get());
}
public boolean isModifiedSince(HaxeTrackedModifiable.Stamp s) {
if (s instanceof HaxeModificationTracker.Stamp) {
return isModifiedSince((HaxeModificationTracker.Stamp)s);
}
return true; // invalid stamp; always modified.
}
public boolean isModifiedSince(Stamp stamp) {
if (stamp.tracker != this) {
String msg = "Stamps can only be compared to their allocating Tracker.";
LOG.error(msg);
}
return this != stamp.tracker || updateCounter.get() != stamp.value;
}
public void notifyUpdated() {
updateCounter.incrementAndGet();
}
public class Stamp implements HaxeTrackedModifiable.Stamp {
private final int value;
private final HaxeModificationTracker tracker;
private Stamp(int value) {
this.value = value;
this.tracker = HaxeModificationTracker.this;
}
public boolean isOutOfDate() {
return tracker.isModifiedSince(this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Stamp stamp = (Stamp)o;
if (value != stamp.value) return false;
return tracker.equals(stamp.tracker);
}
@Override
public int hashCode() {
int result = value;
result = 31 * result + tracker.hashCode();
return result;
}
}
}
| isModifiedSince() now returns true for null Stamps.
| src/common/com/intellij/plugins/haxe/util/HaxeModificationTracker.java | isModifiedSince() now returns true for null Stamps. | <ide><path>rc/common/com/intellij/plugins/haxe/util/HaxeModificationTracker.java
<ide> }
<ide>
<ide> public boolean isModifiedSince(Stamp stamp) {
<add> if (null == stamp) {
<add> return true; // invalid stamp; always modified.
<add> }
<add>
<ide> if (stamp.tracker != this) {
<ide> String msg = "Stamps can only be compared to their allocating Tracker.";
<ide> LOG.error(msg); |
|
Java | apache-2.0 | 6bf869fa8458192da4ed97f84d94aef711664bb8 | 0 | hmusavi/jpo-ode,hmusavi/jpo-ode,hmusavi/jpo-ode,hmusavi/jpo-ode,hmusavi/jpo-ode | package us.dot.its.jpo.ode.udp.isd;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.tomcat.util.buf.HexUtils;
import com.oss.asn1.AbstractData;
import com.oss.asn1.DecodeFailedException;
import com.oss.asn1.DecodeNotSupportedException;
import com.oss.asn1.EncodeFailedException;
import com.oss.asn1.EncodeNotSupportedException;
import com.oss.asn1.INTEGER;
import us.dot.its.jpo.ode.OdeProperties;
import us.dot.its.jpo.ode.asn1.j2735.J2735Util;
import us.dot.its.jpo.ode.dds.AbstractSubscriberDepositor;
import us.dot.its.jpo.ode.dds.TrustManager.TrustManagerException;
import us.dot.its.jpo.ode.j2735.J2735;
import us.dot.its.jpo.ode.j2735.semi.DataReceipt;
import us.dot.its.jpo.ode.j2735.semi.IntersectionSituationData;
import us.dot.its.jpo.ode.j2735.semi.IntersectionSituationDataAcceptance;
import us.dot.its.jpo.ode.j2735.semi.SemiDialogID;
import us.dot.its.jpo.ode.j2735.semi.SemiSequenceID;
public class IsdDepositor extends AbstractSubscriberDepositor<String, byte[]> {
public IsdDepositor(OdeProperties odeProps) {
super(odeProps, odeProps.getIsdDepositorPort(), SemiDialogID.intersectionSitDataDep);
}
@Override
protected byte[] deposit() {
/*
* The record.value() will return an encoded ISD
*/
byte[] encodedIsd = record.value();
try {
logger.debug("Depositor received ISD: {}",
((IntersectionSituationData) J2735.getPERUnalignedCoder()
.decode(new ByteArrayInputStream((byte[]) record.value()), new IntersectionSituationData()))
.toString());
logger.debug("Sending Isd to SDC IP: {}:{} from port: {}", odeProperties.getSdcIp(),
odeProperties.getSdcPort(), socket.getLocalPort());
socket.send(new DatagramPacket(encodedIsd, encodedIsd.length,
new InetSocketAddress(odeProperties.getSdcIp(), odeProperties.getSdcPort())));
messagesDeposited++;
} catch (IOException | DecodeFailedException | DecodeNotSupportedException e) {
logger.error("Error Sending Isd to SDC", e);
return new byte[0];
}
// If we've sent at least 5 messages, get a data receipt
if (messagesDeposited < 5) {
trustMgr.setTrustEstablished(false);
return encodedIsd;
}
/*
* Send an ISDAcceptance message to confirm deposit
*/
IntersectionSituationDataAcceptance acceptance = new IntersectionSituationDataAcceptance();
acceptance.dialogID = dialogId;
acceptance.groupID = groupId;
acceptance.seqID = SemiSequenceID.accept;
acceptance.recordsSent = new INTEGER(messagesDeposited);
try {
// must reuse the requestID from the ISD
acceptance.requestID = ((IntersectionSituationData) J2735.getPERUnalignedCoder()
.decode(new ByteArrayInputStream(encodedIsd), new IntersectionSituationData())).requestID;
logger.info("Extracted requestID from ISD for ISD acceptance message {}",
HexUtils.toHexString(acceptance.requestID.byteArrayValue()));
logger.info("Sending Data Acceptance message to SDC: {} ", acceptance.toString());
} catch (DecodeFailedException | DecodeNotSupportedException e) {
logger.error("Failed to extract requestID from ISD ", e);
return new byte[0];
}
ByteArrayOutputStream sink = new ByteArrayOutputStream();
try {
J2735.getPERUnalignedCoder().encode(acceptance, sink);
} catch (EncodeFailedException | EncodeNotSupportedException e) {
logger.error("Error encoding ISD Acceptance message", e);
}
byte[] encodedAccept = sink.toByteArray();
try {
logger.debug("Sending ISD Acceptance message to SDC.");
ExecutorService executorService = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
Future<Object> f = executorService.submit(new DataReceiptReceiver(odeProperties, socket));
socket.send(new DatagramPacket(encodedAccept, encodedAccept.length,
new InetSocketAddress(odeProperties.getSdcIp(), odeProperties.getSdcPort())));
f.get(odeProperties.getServiceRespExpirationSeconds(), TimeUnit.SECONDS);
} catch (IOException | InterruptedException | ExecutionException e) {
logger.error("Error sending ISD Acceptance message to SDC", e);
} catch (TimeoutException e) {
logger.error("Did not receive ISD data receipt within alotted "
+ +odeProperties.getServiceRespExpirationSeconds() + " seconds " + e);
}
return encodedIsd;
}
}
| jpo-ode-svcs/src/main/java/us/dot/its/jpo/ode/udp/isd/IsdDepositor.java | package us.dot.its.jpo.ode.udp.isd;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.tomcat.util.buf.HexUtils;
import com.oss.asn1.AbstractData;
import com.oss.asn1.DecodeFailedException;
import com.oss.asn1.DecodeNotSupportedException;
import com.oss.asn1.EncodeFailedException;
import com.oss.asn1.EncodeNotSupportedException;
import com.oss.asn1.INTEGER;
import us.dot.its.jpo.ode.OdeProperties;
import us.dot.its.jpo.ode.asn1.j2735.J2735Util;
import us.dot.its.jpo.ode.dds.AbstractSubscriberDepositor;
import us.dot.its.jpo.ode.dds.TrustManager.TrustManagerException;
import us.dot.its.jpo.ode.j2735.J2735;
import us.dot.its.jpo.ode.j2735.semi.DataReceipt;
import us.dot.its.jpo.ode.j2735.semi.IntersectionSituationData;
import us.dot.its.jpo.ode.j2735.semi.IntersectionSituationDataAcceptance;
import us.dot.its.jpo.ode.j2735.semi.SemiDialogID;
import us.dot.its.jpo.ode.j2735.semi.SemiSequenceID;
public class IsdDepositor extends AbstractSubscriberDepositor<String, byte[]> {
public IsdDepositor(OdeProperties odeProps) {
super(odeProps, odeProps.getIsdDepositorPort(), SemiDialogID.intersectionSitDataDep);
}
@Override
protected byte[] deposit() {
/*
* The record.value() will return an encoded ISD
*/
byte[] encodedIsd = record.value();
try {
logger.debug("Depositor received ISD: {}",
((IntersectionSituationData) J2735.getPERUnalignedCoder()
.decode(new ByteArrayInputStream((byte[]) record.value()), new IntersectionSituationData()))
.toString());
logger.debug("Sending Isd to SDC IP: {}:{} from port: {}", odeProperties.getSdcIp(),
odeProperties.getSdcPort(), socket.getLocalPort());
socket.send(new DatagramPacket(encodedIsd, encodedIsd.length,
new InetSocketAddress(odeProperties.getSdcIp(), odeProperties.getSdcPort())));
messagesDeposited++;
} catch (IOException | DecodeFailedException | DecodeNotSupportedException e) {
logger.error("Error Sending Isd to SDC", e);
return new byte[0];
}
// If we've sent at least 5 messages, get a data receipt
if (messagesDeposited < 5) {
return encodedIsd;
}
/*
* Send an ISDAcceptance message to confirm deposit
*/
IntersectionSituationDataAcceptance acceptance = new IntersectionSituationDataAcceptance();
acceptance.dialogID = dialogId;
acceptance.groupID = groupId;
acceptance.seqID = SemiSequenceID.accept;
acceptance.recordsSent = new INTEGER(messagesDeposited);
try {
// must reuse the requestID from the ISD
acceptance.requestID = ((IntersectionSituationData) J2735.getPERUnalignedCoder()
.decode(new ByteArrayInputStream(encodedIsd), new IntersectionSituationData())).requestID;
logger.info("Extracted requestID from ISD for ISD acceptance message {}",
HexUtils.toHexString(acceptance.requestID.byteArrayValue()));
logger.info("Sending Data Acceptance message to SDC: {} ", acceptance.toString());
} catch (DecodeFailedException | DecodeNotSupportedException e) {
logger.error("Failed to extract requestID from ISD ", e);
return new byte[0];
}
ByteArrayOutputStream sink = new ByteArrayOutputStream();
try {
J2735.getPERUnalignedCoder().encode(acceptance, sink);
} catch (EncodeFailedException | EncodeNotSupportedException e) {
logger.error("Error encoding ISD Acceptance message", e);
}
byte[] encodedAccept = sink.toByteArray();
try {
logger.debug("Sending ISD Acceptance message to SDC.");
ExecutorService executorService = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
Future<Object> f = executorService.submit(new DataReceiptReceiver(odeProperties, socket));
socket.send(new DatagramPacket(encodedAccept, encodedAccept.length,
new InetSocketAddress(odeProperties.getSdcIp(), odeProperties.getSdcPort())));
f.get(odeProperties.getServiceRespExpirationSeconds(), TimeUnit.SECONDS);
} catch (IOException | InterruptedException | ExecutionException e) {
logger.error("Error sending ISD Acceptance message to SDC", e);
} catch (TimeoutException e) {
logger.error("Did not receive Service Response within alotted "
+ +odeProperties.getServiceRespExpirationSeconds() + " seconds " + e);
}
return encodedIsd;
}
}
| ODE-314 changing to send non-repudiation once per trust established
| jpo-ode-svcs/src/main/java/us/dot/its/jpo/ode/udp/isd/IsdDepositor.java | ODE-314 changing to send non-repudiation once per trust established | <ide><path>po-ode-svcs/src/main/java/us/dot/its/jpo/ode/udp/isd/IsdDepositor.java
<ide>
<ide> // If we've sent at least 5 messages, get a data receipt
<ide> if (messagesDeposited < 5) {
<add> trustMgr.setTrustEstablished(false);
<ide> return encodedIsd;
<ide> }
<ide>
<ide> } catch (IOException | InterruptedException | ExecutionException e) {
<ide> logger.error("Error sending ISD Acceptance message to SDC", e);
<ide> } catch (TimeoutException e) {
<del> logger.error("Did not receive Service Response within alotted "
<add> logger.error("Did not receive ISD data receipt within alotted "
<ide> + +odeProperties.getServiceRespExpirationSeconds() + " seconds " + e);
<ide> }
<ide> |
|
Java | apache-2.0 | 84466f08c549187d60b22f1f4f69d54b1ba52586 | 0 | GerritCodeReview/plugins_importer,GerritCodeReview/plugins_importer,GerritCodeReview/plugins_importer,GerritCodeReview/plugins_importer | // Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.importer;
import com.google.common.base.CharMatcher;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpSession {
protected final String url;
private final String user;
private final String pass;
private HttpClient client;
public HttpSession(String url, String user, String pass) {
this.url = CharMatcher.is('/').trimTrailingFrom(url);
this.user = user;
this.pass = pass;
}
public HttpResponse get(String path) throws IOException {
HttpGet get = new HttpGet(url + path);
return new HttpResponse(getClient().execute(get));
}
protected HttpClient getClient() throws IOException {
if (client == null) {
URI uri = URI.create(url);
BasicCredentialsProvider creds = new BasicCredentialsProvider();
creds.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
new UsernamePasswordCredentials(user, pass));
SSLContext context;
try {
final TrustManager[] trustAllCerts =
new TrustManager[] {new DummyX509TrustManager()};
context = SSLContext.getInstance("TLS");
context.init(null, trustAllCerts, null);
} catch (KeyManagementException e) {
throw new IOException(e.getMessage());
} catch (NoSuchAlgorithmException e) {
throw new IOException(e.getMessage());
}
SSLConnectionSocketFactory sf;
sf = new SSLConnectionSocketFactory(context, new DummyHostnameVerifier());
client = HttpClients
.custom()
.setSSLSocketFactory(sf)
.setDefaultCredentialsProvider(creds)
.setMaxConnPerRoute(10)
.setMaxConnTotal(1024)
.build();
}
return client;
}
private static class DummyX509TrustManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// no check
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// no check
}
}
private static class DummyHostnameVerifier implements X509HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
// always accept
return true;
}
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
// no check
}
@Override
public void verify(String host, X509Certificate cert) throws SSLException {
// no check
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts)
throws SSLException {
// no check
}
}
}
| src/main/java/com/googlesource/gerrit/plugins/importer/HttpSession.java | // Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.googlesource.gerrit.plugins.importer;
import com.google.common.base.CharMatcher;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
import java.net.URI;
public class HttpSession {
protected final String url;
private final String user;
private final String pass;
private HttpClient client;
public HttpSession(String url, String user, String pass) {
this.url = CharMatcher.is('/').trimTrailingFrom(url);
this.user = user;
this.pass = pass;
}
public HttpResponse get(String path) throws IOException {
HttpGet get = new HttpGet(url + path);
return new HttpResponse(getClient().execute(get));
}
protected HttpClient getClient() {
if (client == null) {
URI uri = URI.create(url);
BasicCredentialsProvider creds = new BasicCredentialsProvider();
creds.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
new UsernamePasswordCredentials(user, pass));
client = HttpClientBuilder
.create()
.setDefaultCredentialsProvider(creds)
.setMaxConnPerRoute(10)
.setMaxConnTotal(1024)
.build();
}
return client;
}
}
| Skip SSL verification
We do not want the queries to fail if the remote has a self signed
certificate, so we skip SSL verification.
A part of the code is copied from JGit.
Change-Id: I45ac9a17d4fd2638822af967710e1cd52d76c769
| src/main/java/com/googlesource/gerrit/plugins/importer/HttpSession.java | Skip SSL verification | <ide><path>rc/main/java/com/googlesource/gerrit/plugins/importer/HttpSession.java
<ide> import org.apache.http.auth.UsernamePasswordCredentials;
<ide> import org.apache.http.client.HttpClient;
<ide> import org.apache.http.client.methods.HttpGet;
<add>import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
<add>import org.apache.http.conn.ssl.X509HostnameVerifier;
<ide> import org.apache.http.impl.client.BasicCredentialsProvider;
<del>import org.apache.http.impl.client.HttpClientBuilder;
<add>import org.apache.http.impl.client.HttpClients;
<ide>
<ide> import java.io.IOException;
<ide> import java.net.URI;
<add>import java.security.KeyManagementException;
<add>import java.security.NoSuchAlgorithmException;
<add>import java.security.cert.X509Certificate;
<add>
<add>import javax.net.ssl.SSLContext;
<add>import javax.net.ssl.SSLException;
<add>import javax.net.ssl.SSLSession;
<add>import javax.net.ssl.SSLSocket;
<add>import javax.net.ssl.TrustManager;
<add>import javax.net.ssl.X509TrustManager;
<ide>
<ide> public class HttpSession {
<ide>
<ide> return new HttpResponse(getClient().execute(get));
<ide> }
<ide>
<del> protected HttpClient getClient() {
<add> protected HttpClient getClient() throws IOException {
<ide> if (client == null) {
<ide> URI uri = URI.create(url);
<ide> BasicCredentialsProvider creds = new BasicCredentialsProvider();
<ide> creds.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
<ide> new UsernamePasswordCredentials(user, pass));
<del> client = HttpClientBuilder
<del> .create()
<add>
<add> SSLContext context;
<add> try {
<add> final TrustManager[] trustAllCerts =
<add> new TrustManager[] {new DummyX509TrustManager()};
<add> context = SSLContext.getInstance("TLS");
<add> context.init(null, trustAllCerts, null);
<add> } catch (KeyManagementException e) {
<add> throw new IOException(e.getMessage());
<add> } catch (NoSuchAlgorithmException e) {
<add> throw new IOException(e.getMessage());
<add> }
<add>
<add> SSLConnectionSocketFactory sf;
<add> sf = new SSLConnectionSocketFactory(context, new DummyHostnameVerifier());
<add> client = HttpClients
<add> .custom()
<add> .setSSLSocketFactory(sf)
<ide> .setDefaultCredentialsProvider(creds)
<ide> .setMaxConnPerRoute(10)
<ide> .setMaxConnTotal(1024)
<ide> .build();
<add>
<ide> }
<ide> return client;
<ide> }
<add>
<add> private static class DummyX509TrustManager implements X509TrustManager {
<add> public X509Certificate[] getAcceptedIssuers() {
<add> return null;
<add> }
<add>
<add> public void checkClientTrusted(X509Certificate[] certs, String authType) {
<add> // no check
<add> }
<add>
<add> public void checkServerTrusted(X509Certificate[] certs, String authType) {
<add> // no check
<add> }
<add> }
<add>
<add> private static class DummyHostnameVerifier implements X509HostnameVerifier {
<add> @Override
<add> public boolean verify(String hostname, SSLSession session) {
<add> // always accept
<add> return true;
<add> }
<add>
<add> @Override
<add> public void verify(String host, SSLSocket ssl) throws IOException {
<add> // no check
<add> }
<add>
<add> @Override
<add> public void verify(String host, X509Certificate cert) throws SSLException {
<add> // no check
<add> }
<add>
<add> @Override
<add> public void verify(String host, String[] cns, String[] subjectAlts)
<add> throws SSLException {
<add> // no check
<add> }
<add> }
<add>
<ide> } |
|
Java | mit | ca67e2d5ce235517fa47e632658985203cd45afe | 0 | tkuhn/memetools,tkuhn/memetools | package ch.tkuhn.memetools;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.supercsv.io.CsvListReader;
import org.supercsv.io.CsvListWriter;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
public class CalculatePaperSuccess {
@Parameter(description = "chronologically-sorted-input-file", required = true)
private List<String> parameters = new ArrayList<String>();
private File inputFile;
@Parameter(names = "-t", description = "File with terms", required = true)
private File termsFile;
@Parameter(names = "-tcol", description = "Index or name of column to read terms (if term file is in CSV format)")
private String termCol = "TERM";
@Parameter(names = "-y", description = "Number of years for which to count article citations")
private int citationYears = 3;
@Parameter(names = "-d", description = "Set delta parameter (controlled noise level)")
private int delta = 3;
@Parameter(names = "-r", description = "Relative frequency threshold")
private double relFreqThreshold = 0.15;
private File logFile;
public static final void main(String[] args) {
CalculatePaperSuccess obj = new CalculatePaperSuccess();
JCommander jc = new JCommander(obj);
try {
jc.parse(args);
} catch (ParameterException ex) {
jc.usage();
System.exit(1);
}
if (obj.parameters.size() != 1) {
System.err.println("ERROR: Exactly one main argument is needed");
jc.usage();
System.exit(1);
}
obj.inputFile = new File(obj.parameters.get(0));
obj.run();
}
private File outputTempFile, outputFile, outputMatrixFile;
private int pubcount;
private MemeScorer ms;
private List<String> terms;
private BufferedReader reader;
private Map<String,Long> paperDates;
private Map<String,Integer> paperCitations;
private Map<String,String> cpyMapKeys;
private Map<String,Long> cpyLastDay;
private Map<String,Long> cpyPaperDays;
private Map<String,Integer> cpyPaperCount;
private Map<String,Integer> cpyCitationCount;
private long firstDay;
private long lastDay;
public CalculatePaperSuccess() {
}
public void run() {
init();
try {
readTerms();
processEntries();
writeSuccessColumn();
} catch (Throwable th) {
log(th);
System.exit(1);
}
log("Finished");
}
private void init() {
logFile = new File(MemeUtils.getLogDir(), getOutputFileName() + ".log");
log("==========");
outputTempFile = new File(MemeUtils.getOutputDataDir(), getOutputFileName() + "-temp.csv");
outputFile = new File(MemeUtils.getOutputDataDir(), getOutputFileName() + ".csv");
outputMatrixFile = new File(MemeUtils.getOutputDataDir(), getOutputFileName() + "-matrix.csv");
ms = new MemeScorer(MemeScorer.GIVEN_TERMLIST_MODE);
terms = new ArrayList<String>();
paperDates = new HashMap<String,Long>();
paperCitations = new HashMap<String,Integer>();
cpyMapKeys = new HashMap<String,String>();
cpyLastDay = new HashMap<String,Long>();
cpyPaperDays = new HashMap<String,Long>();
cpyPaperCount = new HashMap<String,Integer>();
cpyCitationCount = new HashMap<String,Integer>();
pubcount = 0;
firstDay = 0;
}
private void readTerms() throws IOException {
log("Reading terms from " + termsFile + " ...");
if (termsFile.toString().endsWith(".csv")) {
readTermsCsv();
} else {
readTermsTxt();
}
log("Number of terms: " + terms.size());
}
private void readTermsTxt() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(termsFile));
String line;
while ((line = reader.readLine()) != null) {
String term = MemeUtils.normalize(line);
ms.addTerm(term);
terms.add(term);
}
reader.close();
}
private void readTermsCsv() throws IOException {
BufferedReader r = new BufferedReader(new FileReader(termsFile));
CsvListReader csvReader = new CsvListReader(r, MemeUtils.getCsvPreference());
List<String> header = csvReader.read();
int col;
if (termCol.matches("[0-9]+")) {
col = Integer.parseInt(termCol);
} else {
col = header.indexOf(termCol);
}
List<String> line;
while ((line = csvReader.read()) != null) {
String term = MemeUtils.normalize(line.get(col));
ms.addTerm(term);
terms.add(term);
}
csvReader.close();
}
private void processEntries() throws IOException {
CsvListWriter csvWriter = null;
try {
log("Processing entries and writing CSV file...");
Writer w = new BufferedWriter(new FileWriter(outputTempFile));
csvWriter = new CsvListWriter(w, MemeUtils.getCsvPreference());
csvWriter.write("ID", "JOURNAL-C/PY", "FIRSTAUTHOR-C/PY", "AUTHOR-MAX-C/PY", "SELFCIT-MAX-C/Y", "TIME-ABS", "TIME-REL", "TOP-MS", "TOP-MS-MEME");
reader = new BufferedReader(new FileReader(inputFile));
int progress = 0;
String line;
while ((line = reader.readLine()) != null) {
progress++;
logProgress(progress);
DataEntry d = new DataEntry(line);
// Calculate C/PY values
long thisDay = getDayCount(d.getDate());
if (firstDay == 0) firstDay = thisDay;
pubcount++;
String doi = d.getId();
paperDates.put(doi, thisDay);
paperCitations.put(doi, 0);
List<String> authList = Arrays.asList(d.getAuthors().split(" "));
String journal = PrepareApsData.getJournalFromDoi(doi);
String journalKey = "J:" + journal;
double journalCpy = updateCpyData(journalKey, thisDay);
double firstAuthorCpy = -2.0;
double authorMaxCpy = -2.0;
for (String author : authList) {
String authorKey = "A:" + author;
double authorCpy = updateCpyData(authorKey, thisDay);
if (firstAuthorCpy == -2.0) {
firstAuthorCpy = authorCpy;
}
if (authorCpy > authorMaxCpy) {
authorMaxCpy = authorCpy;
}
}
double selfcitMaxCy = 0.0;
for (String cit : d.getCitations().split(" ")) {
// Ignore citations that are not backwards in time:
if (!cpyMapKeys.containsKey(cit)) continue;
for (String k : cpyMapKeys.get(cit).split(" ")) {
if (!k.startsWith("A:")) continue;
k = k.substring(2);
if (authList.contains(k)) {
double selfcitCy = getPaperCy(cit, thisDay);
if (selfcitCy > selfcitMaxCy) selfcitMaxCy = selfcitCy;
continue;
}
}
}
// Calculate meme scores
List<String> memes = new ArrayList<String>();
ms.recordTerms(d, memes);
double topMs = 0;
String topMsMeme = "";
for (String meme : memes) {
if (ms.getRelF(meme) > relFreqThreshold) continue; // ignore frequent terms
double[] msValues = ms.calculateMemeScoreValues(meme, delta);
double thisMs = msValues[3];
if (thisMs > topMs) {
topMs = thisMs;
topMsMeme = meme;
}
}
csvWriter.write(doi, journalCpy, firstAuthorCpy, authorMaxCpy, selfcitMaxCy, thisDay - firstDay, pubcount, topMs, topMsMeme);
addCpyPaper(journalKey);
String cpyKeys = journalKey;
for (String author : authList) {
String authorKey = "A:" + author;
addCpyPaper(authorKey);
cpyKeys += " " + authorKey;
}
String[] citList = d.getCitations().split(" ");
for (String cit : citList) {
// Ignore citations that are not backwards in time:
if (!cpyMapKeys.containsKey(cit)) continue;
for (String k : cpyMapKeys.get(cit).split(" ")) {
addCpyCitation(k);
}
long date = paperDates.get(cit);
if (thisDay < date + 365*citationYears) {
paperCitations.put(cit, paperCitations.get(cit) + 1);
}
}
cpyMapKeys.put(doi, cpyKeys);
lastDay = thisDay;
}
} finally {
if (csvWriter != null) csvWriter.close();
if (reader != null) reader.close();
}
}
private void writeSuccessColumn() throws IOException {
BufferedReader r = new BufferedReader(new FileReader(outputTempFile));
CsvListReader csvReader = new CsvListReader(r, MemeUtils.getCsvPreference());
Writer w = new BufferedWriter(new FileWriter(outputFile));
CsvListWriter csvWriter = new CsvListWriter(w, MemeUtils.getCsvPreference());
Writer wm = new BufferedWriter(new FileWriter(outputMatrixFile));
CsvListWriter csvMatrixWriter = new CsvListWriter(wm, MemeUtils.getCsvPreference());
// Process header:
List<String> line = csvReader.read();
line.add("CITATIONS-" + citationYears + "Y");
csvWriter.write(line);
line.remove(line.size()-2);
line.remove(0);
csvMatrixWriter.write(line);
while ((line = csvReader.read()) != null) {
String doi = line.get(0);
long date = paperDates.get(doi);
boolean completeRow = false;
if (lastDay >= date + 365*citationYears) {
line.add(paperCitations.get(doi).toString());
completeRow = true;
} else {
line.add("-1");
}
csvWriter.write(line);
if (completeRow) {
line.remove(line.size()-2);
line.remove(0);
csvMatrixWriter.write(line);
}
}
csvWriter.close();
csvMatrixWriter.close();
csvReader.close();
}
private double updateCpyData(String key, long thisDay) {
Long lastDay = cpyLastDay.get(key);
if (lastDay == null) lastDay = 0l;
long dayDiff = thisDay - lastDay;
Integer paperCount = cpyPaperCount.get(key);
if (paperCount == null) paperCount = 0;
Integer citationCount = cpyCitationCount.get(key);
if (citationCount == null) citationCount = 0;
Long paperDays = cpyPaperDays.get(key);
if (paperDays == null) paperDays = 0l;
paperDays = paperDays + paperCount*dayDiff;
cpyPaperDays.put(key, paperDays);
cpyLastDay.put(key, thisDay);
return (citationCount * 365.0) / (paperDays + 1);
}
private double getPaperCy(String doi, long thisDay) {
long dayDiff = thisDay - paperDates.get(doi);
return (paperCitations.get(doi) * 365.0) / (dayDiff + 1);
}
private void addCpyPaper(String key) {
Integer paperCount = cpyPaperCount.get(key);
if (paperCount == null) paperCount = 0;
cpyPaperCount.put(key, paperCount + 1);
}
private void addCpyCitation(String key) {
Integer citationCount = cpyCitationCount.get(key);
if (citationCount == null) citationCount = 0;
cpyCitationCount.put(key, citationCount + 1);
}
private static long getDayCount(String date) {
return TimeUnit.DAYS.convert(parseDate(date).getTime(), TimeUnit.MILLISECONDS);
}
private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
private static Date parseDate(String s) {
try {
return formatter.parse(s);
} catch (ParseException ex) {
throw new RuntimeException(ex);
}
}
private String getOutputFileName() {
return "su-" + inputFile.getName().replaceAll("-chronologic", "").replaceAll("\\..*$", "");
}
private void logProgress(int p) {
if (p % 100000 == 0) log(p + "...");
}
private void log(Object obj) {
MemeUtils.log(logFile, obj);
}
}
| src/main/java/ch/tkuhn/memetools/CalculatePaperSuccess.java | package ch.tkuhn.memetools;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.supercsv.io.CsvListReader;
import org.supercsv.io.CsvListWriter;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
public class CalculatePaperSuccess {
@Parameter(description = "chronologically-sorted-input-file", required = true)
private List<String> parameters = new ArrayList<String>();
private File inputFile;
@Parameter(names = "-t", description = "File with terms", required = true)
private File termsFile;
@Parameter(names = "-tcol", description = "Index or name of column to read terms (if term file is in CSV format)")
private String termCol = "TERM";
@Parameter(names = "-y", description = "Number of years for which to count article citations")
private int citationYears = 3;
@Parameter(names = "-d", description = "Set delta parameter (controlled noise level)")
private int delta = 3;
@Parameter(names = "-r", description = "Relative frequency threshold")
private double relFreqThreshold = 0.15;
private File logFile;
public static final void main(String[] args) {
CalculatePaperSuccess obj = new CalculatePaperSuccess();
JCommander jc = new JCommander(obj);
try {
jc.parse(args);
} catch (ParameterException ex) {
jc.usage();
System.exit(1);
}
if (obj.parameters.size() != 1) {
System.err.println("ERROR: Exactly one main argument is needed");
jc.usage();
System.exit(1);
}
obj.inputFile = new File(obj.parameters.get(0));
obj.run();
}
private File outputTempFile, outputFile, outputMatrixFile;
private MemeScorer ms;
private List<String> terms;
private BufferedReader reader;
private Map<String,Long> paperDates;
private Map<String,Integer> paperCitations;
private Map<String,String> cpyMapKeys;
private Map<String,Long> cpyLastDay;
private Map<String,Long> cpyPaperDays;
private Map<String,Integer> cpyPaperCount;
private Map<String,Integer> cpyCitationCount;
private long lastDay;
public CalculatePaperSuccess() {
}
public void run() {
init();
try {
readTerms();
processEntries();
writeSuccessColumn();
} catch (Throwable th) {
log(th);
System.exit(1);
}
log("Finished");
}
private void init() {
logFile = new File(MemeUtils.getLogDir(), getOutputFileName() + ".log");
log("==========");
outputTempFile = new File(MemeUtils.getOutputDataDir(), getOutputFileName() + "-temp.csv");
outputFile = new File(MemeUtils.getOutputDataDir(), getOutputFileName() + ".csv");
outputMatrixFile = new File(MemeUtils.getOutputDataDir(), getOutputFileName() + "-matrix.csv");
ms = new MemeScorer(MemeScorer.GIVEN_TERMLIST_MODE);
terms = new ArrayList<String>();
paperDates = new HashMap<String,Long>();
paperCitations = new HashMap<String,Integer>();
cpyMapKeys = new HashMap<String,String>();
cpyLastDay = new HashMap<String,Long>();
cpyPaperDays = new HashMap<String,Long>();
cpyPaperCount = new HashMap<String,Integer>();
cpyCitationCount = new HashMap<String,Integer>();
}
private void readTerms() throws IOException {
log("Reading terms from " + termsFile + " ...");
if (termsFile.toString().endsWith(".csv")) {
readTermsCsv();
} else {
readTermsTxt();
}
log("Number of terms: " + terms.size());
}
private void readTermsTxt() throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(termsFile));
String line;
while ((line = reader.readLine()) != null) {
String term = MemeUtils.normalize(line);
ms.addTerm(term);
terms.add(term);
}
reader.close();
}
private void readTermsCsv() throws IOException {
BufferedReader r = new BufferedReader(new FileReader(termsFile));
CsvListReader csvReader = new CsvListReader(r, MemeUtils.getCsvPreference());
List<String> header = csvReader.read();
int col;
if (termCol.matches("[0-9]+")) {
col = Integer.parseInt(termCol);
} else {
col = header.indexOf(termCol);
}
List<String> line;
while ((line = csvReader.read()) != null) {
String term = MemeUtils.normalize(line.get(col));
ms.addTerm(term);
terms.add(term);
}
csvReader.close();
}
private void processEntries() throws IOException {
CsvListWriter csvWriter = null;
try {
log("Processing entries and writing CSV file...");
Writer w = new BufferedWriter(new FileWriter(outputTempFile));
csvWriter = new CsvListWriter(w, MemeUtils.getCsvPreference());
csvWriter.write("ID", "JOURNAL-C/PY", "FIRSTAUTHOR-C/PY", "AUTHOR-MAX-C/PY", "SELFCIT-MAX-C/Y", "TOP-PS-MEME", "TOP-MS", "TOP-MS-MEME");
reader = new BufferedReader(new FileReader(inputFile));
int progress = 0;
String line;
while ((line = reader.readLine()) != null) {
progress++;
logProgress(progress);
DataEntry d = new DataEntry(line);
// Calculate C/PY values
long thisDay = getDayCount(d.getDate());
String doi = d.getId();
paperDates.put(doi, thisDay);
paperCitations.put(doi, 0);
List<String> authList = Arrays.asList(d.getAuthors().split(" "));
String journal = PrepareApsData.getJournalFromDoi(doi);
String journalKey = "J:" + journal;
double journalCpy = updateCpyData(journalKey, thisDay);
double firstAuthorCpy = -2.0;
double authorMaxCpy = -2.0;
for (String author : authList) {
String authorKey = "A:" + author;
double authorCpy = updateCpyData(authorKey, thisDay);
if (firstAuthorCpy == -2.0) {
firstAuthorCpy = authorCpy;
}
if (authorCpy > authorMaxCpy) {
authorMaxCpy = authorCpy;
}
}
double selfcitMaxCy = 0.0;
for (String cit : d.getCitations().split(" ")) {
// Ignore citations that are not backwards in time:
if (!cpyMapKeys.containsKey(cit)) continue;
for (String k : cpyMapKeys.get(cit).split(" ")) {
if (!k.startsWith("A:")) continue;
k = k.substring(2);
if (authList.contains(k)) {
double selfcitCy = getPaperCy(cit, thisDay);
if (selfcitCy > selfcitMaxCy) selfcitMaxCy = selfcitCy;
continue;
}
}
}
// Calculate meme scores
List<String> memes = new ArrayList<String>();
ms.recordTerms(d, memes);
double topMs = 0;
String topMsMeme = "";
for (String meme : memes) {
if (ms.getRelF(meme) > relFreqThreshold) continue; // ignore frequent terms
double[] msValues = ms.calculateMemeScoreValues(meme, delta);
double thisMs = msValues[3];
if (thisMs > topMs) {
topMs = thisMs;
topMsMeme = meme;
}
}
csvWriter.write(doi, journalCpy, firstAuthorCpy, authorMaxCpy, selfcitMaxCy, topMs, topMsMeme);
addCpyPaper(journalKey);
String cpyKeys = journalKey;
for (String author : authList) {
String authorKey = "A:" + author;
addCpyPaper(authorKey);
cpyKeys += " " + authorKey;
}
String[] citList = d.getCitations().split(" ");
for (String cit : citList) {
// Ignore citations that are not backwards in time:
if (!cpyMapKeys.containsKey(cit)) continue;
for (String k : cpyMapKeys.get(cit).split(" ")) {
addCpyCitation(k);
}
long date = paperDates.get(cit);
if (thisDay < date + 365*citationYears) {
paperCitations.put(cit, paperCitations.get(cit) + 1);
}
}
cpyMapKeys.put(doi, cpyKeys);
lastDay = thisDay;
}
} finally {
if (csvWriter != null) csvWriter.close();
if (reader != null) reader.close();
}
}
private void writeSuccessColumn() throws IOException {
BufferedReader r = new BufferedReader(new FileReader(outputTempFile));
CsvListReader csvReader = new CsvListReader(r, MemeUtils.getCsvPreference());
Writer w = new BufferedWriter(new FileWriter(outputFile));
CsvListWriter csvWriter = new CsvListWriter(w, MemeUtils.getCsvPreference());
Writer wm = new BufferedWriter(new FileWriter(outputMatrixFile));
CsvListWriter csvMatrixWriter = new CsvListWriter(wm, MemeUtils.getCsvPreference());
// Process header:
List<String> line = csvReader.read();
line.add("CITATIONS-" + citationYears + "Y");
csvWriter.write(line);
line.remove(line.size()-2);
line.remove(0);
csvMatrixWriter.write(line);
while ((line = csvReader.read()) != null) {
String doi = line.get(0);
long date = paperDates.get(doi);
boolean completeRow = false;
if (lastDay >= date + 365*citationYears) {
line.add(paperCitations.get(doi).toString());
completeRow = true;
} else {
line.add("-1");
}
csvWriter.write(line);
if (completeRow) {
line.remove(line.size()-2);
line.remove(0);
csvMatrixWriter.write(line);
}
}
csvWriter.close();
csvMatrixWriter.close();
csvReader.close();
}
private double updateCpyData(String key, long thisDay) {
Long lastDay = cpyLastDay.get(key);
if (lastDay == null) lastDay = 0l;
long dayDiff = thisDay - lastDay;
Integer paperCount = cpyPaperCount.get(key);
if (paperCount == null) paperCount = 0;
Integer citationCount = cpyCitationCount.get(key);
if (citationCount == null) citationCount = 0;
Long paperDays = cpyPaperDays.get(key);
if (paperDays == null) paperDays = 0l;
paperDays = paperDays + paperCount*dayDiff;
cpyPaperDays.put(key, paperDays);
cpyLastDay.put(key, thisDay);
return (citationCount * 365.0) / (paperDays + 1);
}
private double getPaperCy(String doi, long thisDay) {
long dayDiff = thisDay - paperDates.get(doi);
return (paperCitations.get(doi) * 365.0) / (dayDiff + 1);
}
private void addCpyPaper(String key) {
Integer paperCount = cpyPaperCount.get(key);
if (paperCount == null) paperCount = 0;
cpyPaperCount.put(key, paperCount + 1);
}
private void addCpyCitation(String key) {
Integer citationCount = cpyCitationCount.get(key);
if (citationCount == null) citationCount = 0;
cpyCitationCount.put(key, citationCount + 1);
}
private static long getDayCount(String date) {
return TimeUnit.DAYS.convert(parseDate(date).getTime(), TimeUnit.MILLISECONDS);
}
private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
private static Date parseDate(String s) {
try {
return formatter.parse(s);
} catch (ParseException ex) {
throw new RuntimeException(ex);
}
}
private String getOutputFileName() {
return "su-" + inputFile.getName().replaceAll("-chronologic", "").replaceAll("\\..*$", "");
}
private void logProgress(int p) {
if (p % 100000 == 0) log(p + "...");
}
private void log(Object obj) {
MemeUtils.log(logFile, obj);
}
}
| Add time variables | src/main/java/ch/tkuhn/memetools/CalculatePaperSuccess.java | Add time variables | <ide><path>rc/main/java/ch/tkuhn/memetools/CalculatePaperSuccess.java
<ide>
<ide> private File outputTempFile, outputFile, outputMatrixFile;
<ide>
<add> private int pubcount;
<ide> private MemeScorer ms;
<ide> private List<String> terms;
<ide> private BufferedReader reader;
<ide> private Map<String,Long> cpyPaperDays;
<ide> private Map<String,Integer> cpyPaperCount;
<ide> private Map<String,Integer> cpyCitationCount;
<add> private long firstDay;
<ide> private long lastDay;
<ide>
<ide> public CalculatePaperSuccess() {
<ide> cpyPaperDays = new HashMap<String,Long>();
<ide> cpyPaperCount = new HashMap<String,Integer>();
<ide> cpyCitationCount = new HashMap<String,Integer>();
<add> pubcount = 0;
<add> firstDay = 0;
<ide> }
<ide>
<ide> private void readTerms() throws IOException {
<ide> log("Processing entries and writing CSV file...");
<ide> Writer w = new BufferedWriter(new FileWriter(outputTempFile));
<ide> csvWriter = new CsvListWriter(w, MemeUtils.getCsvPreference());
<del> csvWriter.write("ID", "JOURNAL-C/PY", "FIRSTAUTHOR-C/PY", "AUTHOR-MAX-C/PY", "SELFCIT-MAX-C/Y", "TOP-PS-MEME", "TOP-MS", "TOP-MS-MEME");
<add> csvWriter.write("ID", "JOURNAL-C/PY", "FIRSTAUTHOR-C/PY", "AUTHOR-MAX-C/PY", "SELFCIT-MAX-C/Y", "TIME-ABS", "TIME-REL", "TOP-MS", "TOP-MS-MEME");
<ide>
<ide> reader = new BufferedReader(new FileReader(inputFile));
<ide> int progress = 0;
<ide>
<ide> // Calculate C/PY values
<ide> long thisDay = getDayCount(d.getDate());
<add> if (firstDay == 0) firstDay = thisDay;
<add> pubcount++;
<ide> String doi = d.getId();
<ide> paperDates.put(doi, thisDay);
<ide> paperCitations.put(doi, 0);
<ide> }
<ide> }
<ide>
<del> csvWriter.write(doi, journalCpy, firstAuthorCpy, authorMaxCpy, selfcitMaxCy, topMs, topMsMeme);
<add> csvWriter.write(doi, journalCpy, firstAuthorCpy, authorMaxCpy, selfcitMaxCy, thisDay - firstDay, pubcount, topMs, topMsMeme);
<ide>
<ide> addCpyPaper(journalKey);
<ide> String cpyKeys = journalKey; |
|
Java | lgpl-2.1 | error: pathspec 'src/opendap/coreServlet/OpendapContentHeaders.java' did not match any file(s) known to git
| 2cd439c65afe79d3a30db52348ce0ab2423fcf63 | 1 | OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs | /////////////////////////////////////////////////////////////////////////////
// This file is part of the "Server4" project, a Java implementation of the
// OPeNDAP Data Access Protocol.
//
// Copyright (c) 2006 OPeNDAP, Inc.
// Author: Nathan David Potter <[email protected]>
//
// 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
/////////////////////////////////////////////////////////////////////////////
package opendap.coreServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
/**
* User: ndp
* Date: Apr 20, 2007
* Time: 10:18:02 AM
*/
public interface OpendapContentHeaders {
public void setOpendapMimeHeaders(HttpServletRequest request,
HttpServletResponse response)
throws Exception;
}
| src/opendap/coreServlet/OpendapContentHeaders.java | olfs:
Refactored Dispatch. Major changes to code and configurations.
| src/opendap/coreServlet/OpendapContentHeaders.java | olfs: Refactored Dispatch. Major changes to code and configurations. | <ide><path>rc/opendap/coreServlet/OpendapContentHeaders.java
<add>/////////////////////////////////////////////////////////////////////////////
<add>// This file is part of the "Server4" project, a Java implementation of the
<add>// OPeNDAP Data Access Protocol.
<add>//
<add>// Copyright (c) 2006 OPeNDAP, Inc.
<add>// Author: Nathan David Potter <[email protected]>
<add>//
<add>// This library is free software; you can redistribute it and/or
<add>// modify it under the terms of the GNU Lesser General Public
<add>// License as published by the Free Software Foundation; either
<add>// version 2.1 of the License, or (at your option) any later version.
<add>//
<add>// This library is distributed in the hope that it will be useful,
<add>// but WITHOUT ANY WARRANTY; without even the implied warranty of
<add>// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
<add>// Lesser General Public License for more details.
<add>//
<add>// You should have received a copy of the GNU Lesser General Public
<add>// License along with this library; if not, write to the Free Software
<add>// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
<add>//
<add>// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
<add>/////////////////////////////////////////////////////////////////////////////
<add>
<add>package opendap.coreServlet;
<add>
<add>import javax.servlet.http.HttpServletResponse;
<add>import javax.servlet.http.HttpServletRequest;
<add>
<add>/**
<add> * User: ndp
<add> * Date: Apr 20, 2007
<add> * Time: 10:18:02 AM
<add> */
<add>public interface OpendapContentHeaders {
<add> public void setOpendapMimeHeaders(HttpServletRequest request,
<add> HttpServletResponse response)
<add> throws Exception;
<add>
<add>} |
|
Java | mit | cded794908652f093eca22ab5d941e752506fdeb | 0 | joshgarde/SpongeAPI,kenzierocks/SpongeAPI,kenzierocks/SpongeAPI,Lergin/SpongeAPI,caseif/SpongeAPI,Kiskae/SpongeAPI,gabizou/SpongeAPI,ryantheleach/SpongeAPI,jonk1993/SpongeAPI,Lergin/SpongeAPI,kashike/SpongeAPI,kashike/SpongeAPI,SpongePowered/SpongeAPI,AlphaModder/SpongeAPI,boomboompower/SpongeAPI,SpongePowered/SpongeAPI,Kiskae/SpongeAPI,AlphaModder/SpongeAPI,gabizou/SpongeAPI,caseif/SpongeAPI,ryantheleach/SpongeAPI,modwizcode/SpongeAPI,joshgarde/SpongeAPI,jamierocks/SpongeAPI,DDoS/SpongeAPI,modwizcode/SpongeAPI,SpongePowered/SpongeAPI,jamierocks/SpongeAPI,JBYoshi/SpongeAPI,jonk1993/SpongeAPI,boomboompower/SpongeAPI,DDoS/SpongeAPI,JBYoshi/SpongeAPI | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.util.command.dispatcher;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.util.command.CommandCallable;
import org.spongepowered.api.util.command.CommandException;
import org.spongepowered.api.util.command.CommandMapping;
import org.spongepowered.api.util.command.CommandSource;
import org.spongepowered.api.util.command.ImmutableCommandMapping;
import org.spongepowered.api.util.command.InvocationCommandException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A simple implementation of a {@link Dispatcher}.
*/
public class SimpleDispatcher implements Dispatcher {
private final Map<String, CommandMapping> commands = Maps.newHashMap();
private final String shortDescription;
private final Text help;
/**
* Creates a new dispatcher without any help messages.
*/
public SimpleDispatcher() {
this.shortDescription = "";
this.help = Texts.of();
}
/**
* Creates a new dispatcher with a description and a help message.
*
* @param shortDescription A short one-line description
* @param help A formatted help message
*/
public SimpleDispatcher(String shortDescription, Text help) {
checkNotNull(shortDescription);
checkNotNull(help);
this.shortDescription = shortDescription;
this.help = help;
}
/**
* Register a given command using the given list of aliases.
*
* <p>If there is a conflict with one of the aliases (i.e. that alias
* is already assigned to another command), then the alias will be skipped.
* It is possible for there to be no alias to be available out of
* the provided list of aliases, which would mean that the command would not
* be assigned to any aliases.</p>
*
* <p>The first non-conflicted alias becomes the "primary alias."</p>
*
* @param callable The command
* @param alias An array of aliases
* @return The registered command mapping, unless no aliases could be registered
*/
public Optional<CommandMapping> register(CommandCallable callable, String... alias) {
checkNotNull(alias);
return register(callable, Arrays.asList(alias));
}
/**
* Register a given command using the given list of aliases.
*
* <p>If there is a conflict with one of the aliases (i.e. that alias
* is already assigned to another command), then the alias will be skipped.
* It is possible for there to be no alias to be available out of
* the provided list of aliases, which would mean that the command would not
* be assigned to any aliases.</p>
*
* <p>The first non-conflicted alias becomes the "primary alias."</p>
*
* @param callable The command
* @param aliases A list of aliases
* @return The registered command mapping, unless no aliases could be registered
*/
public Optional<CommandMapping> register(CommandCallable callable, List<String> aliases) {
return register(callable, aliases, Functions.<List<String>>identity());
}
/**
* Register a given command using a given list of aliases.
*
* <p>The provided callback function will be called with a list of aliases
* that are not taken (from the list of aliases that were requested) and
* it should return a list of aliases to actually register. Aliases may be
* removed, and if no aliases remain, then the command will not be
* registered. It may be possible that no aliases are available, and thus
* the callback would receive an empty list. New aliases should not be added
* to the list in the callback as this may cause
* {@link IllegalArgumentException} to be thrown.</p>
*
* <p>The first non-conflicted alias becomes the "primary alias."</p>
*
* @param callable The command
* @param aliases A list of aliases
* @param callback The callback
* @return The registered command mapping, unless no aliases could be registered
* @throws IllegalArgumentException Thrown if new conflicting aliases are added in the callback
*/
public synchronized Optional<CommandMapping> register(CommandCallable callable, List<String> aliases,
Function<List<String>, List<String>> callback) {
checkNotNull(aliases);
checkNotNull(callable);
checkNotNull(callback);
List<String> free = new ArrayList<String>();
// Filter out commands that are already registered
for (String alias : aliases) {
if (!this.commands.containsKey(alias.toLowerCase())) {
free.add(alias);
}
}
// Invoke the callback with the commands that /can/ be registered
//noinspection ConstantConditions
free = new ArrayList<String>(callback.apply(free));
if (!free.isEmpty()) {
// The callback should /not/ have added any new commands
for (String alias : free) {
if (this.commands.containsKey(alias.toLowerCase())) {
throw new IllegalArgumentException("A command by the name of '" + alias + "' already exists");
}
}
String primary = free.get(0);
List<String> secondary = free.subList(1, free.size());
CommandMapping mapping = new ImmutableCommandMapping(callable, primary, secondary);
for (String alias : free) {
this.commands.put(alias.toLowerCase(), mapping);
}
return Optional.of(mapping);
} else {
return Optional.absent();
}
}
/**
* Remove a mapping identified by the given alias.
*
* @param alias The alias
* @return The previous mapping associated with the alias, if one was found
*/
public synchronized Optional<CommandMapping> remove(String alias) {
return Optional.of(this.commands.remove(alias.toLowerCase()));
}
/**
* Remove all mappings identified by the given aliases.
*
* @param c A collection of aliases
* @return Whether any were found
*/
public synchronized boolean removeAll(Collection<?> c) {
checkNotNull(c);
boolean found = false;
for (Object alias : c) {
this.commands.remove(alias.toString().toLowerCase());
found = true;
}
return found;
}
/**
* Remove a command identified by the given mapping.
*
* @param mapping The mapping
* @return The previous mapping associated with the alias, if one was found
*/
public synchronized Optional<CommandMapping> removeMapping(CommandMapping mapping) {
checkNotNull(mapping);
CommandMapping found = null;
Iterator<CommandMapping> it = this.commands.values().iterator();
while (it.hasNext()) {
CommandMapping current = it.next();
if (current.equals(mapping)) {
it.remove();
found = current;
}
}
return Optional.fromNullable(found);
}
/**
* Remove all mappings contained with the given collection.
*
* @param c The collection
* @return Whether the at least one command was removed
*/
public synchronized boolean removeMappings(Collection<?> c) {
checkNotNull(c);
boolean found = false;
Iterator<CommandMapping> it = this.commands.values().iterator();
while (it.hasNext()) {
if (c.contains(it.next())) {
it.remove();
found = true;
}
}
return found;
}
@Override
public synchronized Set<CommandMapping> getCommands() {
return ImmutableSet.copyOf(this.commands.values());
}
@Override
public synchronized Set<String> getPrimaryAliases() {
Set<String> aliases = new HashSet<String>();
for (CommandMapping mapping : this.commands.values()) {
aliases.add(mapping.getPrimaryAlias());
}
return Collections.unmodifiableSet(aliases);
}
@Override
public synchronized Set<String> getAliases() {
Set<String> aliases = new HashSet<String>();
for (CommandMapping mapping : this.commands.values()) {
aliases.addAll(mapping.getAllAliases());
}
return Collections.unmodifiableSet(aliases);
}
@Override
public synchronized Optional<CommandMapping> get(String alias) {
return Optional.fromNullable(this.commands.get(alias.toLowerCase()));
}
@Override
public synchronized boolean containsAlias(String alias) {
return this.commands.containsKey(alias.toLowerCase());
}
@Override
public boolean containsMapping(CommandMapping mapping) {
checkNotNull(mapping);
for (CommandMapping test : this.commands.values()) {
if (mapping.equals(test)) {
return true;
}
}
return false;
}
/**
* Get the number of registered aliases.
*
* @return The number of aliases
*/
public synchronized int size() {
return this.commands.size();
}
@Override
public boolean call(CommandSource source, String arguments, List<String> parents) throws CommandException {
String[] parts = arguments.split(" +", 2);
Optional<CommandMapping> mapping = get(parts[0]);
if (mapping.isPresent()) {
List<String> passedParents = new ArrayList<String>(parents.size() + 1);
passedParents.addAll(parents);
passedParents.add(parts[0]);
try {
mapping.get().getCallable().call(source, parts.length > 1 ? parts[1] : "", Collections.unmodifiableList(passedParents));
} catch (CommandException c) {
throw c;
} catch (Throwable t) {
throw new InvocationCommandException(t);
}
return true;
} else {
return false;
}
}
@Override
public synchronized boolean testPermission(CommandSource source) {
for (CommandMapping mapping : this.commands.values()) {
if (!mapping.getCallable().testPermission(source)) {
return false;
}
}
return true;
}
@Override
public List<String> getSuggestions(CommandSource source, String arguments) throws CommandException {
String[] parts = arguments.split(" +", 2);
List<String> suggestions = new ArrayList<String>();
if (parts.length == 1) { // Auto completing commands
String incompleteCommand = parts[0].toLowerCase();
synchronized (this) {
for (CommandMapping mapping : this.commands.values()) {
for (String alias : mapping.getAllAliases()) {
if (alias.toLowerCase().startsWith(incompleteCommand)) {
suggestions.add(alias);
}
}
}
}
} else { // Complete using subcommand
Optional<CommandMapping> mapping = get(parts[0]);
if (mapping.isPresent()) {
List<String> ret = mapping.get().getCallable().getSuggestions(source, parts.length > 1 ? parts[1] : "");
if (ret != null) {
suggestions.addAll(ret);
}
}
}
return Collections.unmodifiableList(suggestions);
}
@Override
public String getShortDescription(CommandSource source) {
return this.shortDescription;
}
@Override
public Text getHelp(CommandSource source) {
return this.help;
}
@Override
public String getUsage(CommandSource source) {
return "<sub-command>"; // @TODO: Translate
}
}
| src/main/java/org/spongepowered/api/util/command/dispatcher/SimpleDispatcher.java | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.util.command.dispatcher;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.util.command.CommandCallable;
import org.spongepowered.api.util.command.CommandException;
import org.spongepowered.api.util.command.CommandMapping;
import org.spongepowered.api.util.command.CommandSource;
import org.spongepowered.api.util.command.ImmutableCommandMapping;
import org.spongepowered.api.util.command.InvocationCommandException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A simple implementation of a {@link Dispatcher}.
*/
public class SimpleDispatcher implements Dispatcher {
private final Map<String, CommandMapping> commands = Maps.newHashMap();
private final String shortDescription;
private final Text help;
/**
* Creates a new dispatcher without any help messages.
*/
public SimpleDispatcher() {
this.shortDescription = "";
this.help = Texts.of();
}
/**
* Creates a new dispatcher with a description and a help message.
*
* @param shortDescription A short one-line description
* @param help A formatted help message
*/
public SimpleDispatcher(String shortDescription, Text help) {
checkNotNull(shortDescription);
checkNotNull(help);
this.shortDescription = shortDescription;
this.help = help;
}
/**
* Register a given command using the given list of aliases.
*
* <p>If there is a conflict with one of the aliases (i.e. that alias
* is already assigned to another command), then the alias will be skipped.
* It is possible for there to be no alias to be available out of
* the provided list of aliases, which would mean that the command would not
* be assigned to any aliases.</p>
*
* <p>The first non-conflicted alias becomes the "primary alias."</p>
*
* @param callable The command
* @param alias An array of aliases
* @return The registered command mapping, unless no aliases could be registered
*/
public Optional<CommandMapping> register(CommandCallable callable, String... alias) {
checkNotNull(alias);
return register(callable, Arrays.asList(alias));
}
/**
* Register a given command using the given list of aliases.
*
* <p>If there is a conflict with one of the aliases (i.e. that alias
* is already assigned to another command), then the alias will be skipped.
* It is possible for there to be no alias to be available out of
* the provided list of aliases, which would mean that the command would not
* be assigned to any aliases.</p>
*
* <p>The first non-conflicted alias becomes the "primary alias."</p>
*
* @param callable The command
* @param aliases A list of aliases
* @return The registered command mapping, unless no aliases could be registered
*/
public Optional<CommandMapping> register(CommandCallable callable, List<String> aliases) {
return register(callable, aliases, Functions.<List<String>>identity());
}
/**
* Register a given command using a given list of aliases.
*
* <p>The provided callback function will be called with a list of aliases
* that are not taken (from the list of aliases that were requested) and
* it should return a list of aliases to actually register. Aliases may be
* removed, and if no aliases remain, then the command will not be
* registered. It may be possible that no aliases are available, and thus
* the callback would receive an empty list. New aliases should not be added
* to the list in the callback as this may cause
* {@link IllegalArgumentException} to be thrown.</p>
*
* <p>The first non-conflicted alias becomes the "primary alias."</p>
*
* @param callable The command
* @param aliases A list of aliases
* @param callback The callback
* @return The registered command mapping, unless no aliases could be registered
* @throws IllegalArgumentException Thrown if new conflicting aliases are added in the callback
*/
public synchronized Optional<CommandMapping> register(CommandCallable callable, List<String> aliases,
Function<List<String>, List<String>> callback) {
checkNotNull(aliases);
checkNotNull(callable);
checkNotNull(callback);
List<String> free = new ArrayList<String>();
// Filter out commands that are already registered
for (String alias : aliases) {
if (!this.commands.containsKey(alias.toLowerCase())) {
free.add(alias);
}
}
// Invoke the callback with the commands that /can/ be registered
//noinspection ConstantConditions
free = new ArrayList<String>(callback.apply(free));
if (!free.isEmpty()) {
// The callback should /not/ have added any new commands
for (String alias : free) {
if (this.commands.containsKey(alias.toLowerCase())) {
throw new IllegalArgumentException("A command by the name of '" + alias + "' already exists");
}
}
String primary = free.get(0);
List<String> secondary = free.subList(1, free.size());
CommandMapping mapping = new ImmutableCommandMapping(callable, primary, secondary);
for (String alias : free) {
this.commands.put(alias.toLowerCase(), mapping);
}
return Optional.of(mapping);
} else {
return Optional.absent();
}
}
/**
* Remove a mapping identified by the given alias.
*
* @param alias The alias
* @return The previous mapping associated with the alias, if one was found
*/
public synchronized Optional<CommandMapping> remove(String alias) {
return Optional.of(this.commands.remove(alias.toLowerCase()));
}
/**
* Remove all mappings identified by the given aliases.
*
* @param c A collection of aliases
* @return Whether any were found
*/
public synchronized boolean removeAll(Collection<?> c) {
checkNotNull(c);
boolean found = false;
for (Object alias : c) {
this.commands.remove(alias.toString().toLowerCase());
found = true;
}
return found;
}
/**
* Remove a command identified by the given mapping.
*
* @param mapping The mapping
* @return The previous mapping associated with the alias, if one was found
*/
public synchronized Optional<CommandMapping> removeMapping(CommandMapping mapping) {
checkNotNull(mapping);
CommandMapping found = null;
Iterator<CommandMapping> it = this.commands.values().iterator();
while (it.hasNext()) {
CommandMapping current = it.next();
if (current.equals(mapping)) {
it.remove();
found = current;
}
}
return Optional.fromNullable(found);
}
/**
* Remove all mappings contained with the given collection.
*
* @param c The collection
* @return Whether the at least one command was removed
*/
public synchronized boolean removeMappings(Collection<?> c) {
checkNotNull(c);
boolean found = false;
Iterator<CommandMapping> it = this.commands.values().iterator();
while (it.hasNext()) {
if (c.contains(it.next())) {
it.remove();
found = true;
}
}
return found;
}
@Override
public synchronized Set<CommandMapping> getCommands() {
return ImmutableSet.copyOf(this.commands.values());
}
@Override
public synchronized Set<String> getPrimaryAliases() {
Set<String> aliases = new HashSet<String>();
for (CommandMapping mapping : this.commands.values()) {
aliases.add(mapping.getPrimaryAlias());
}
return Collections.unmodifiableSet(aliases);
}
@Override
public synchronized Set<String> getAliases() {
Set<String> aliases = new HashSet<String>();
for (CommandMapping mapping : this.commands.values()) {
aliases.addAll(mapping.getAllAliases());
}
return Collections.unmodifiableSet(aliases);
}
@Override
public synchronized Optional<CommandMapping> get(String alias) {
return Optional.fromNullable(this.commands.get(alias.toLowerCase()));
}
@Override
public synchronized boolean containsAlias(String alias) {
return this.commands.containsKey(alias.toLowerCase());
}
@Override
public boolean containsMapping(CommandMapping mapping) {
checkNotNull(mapping);
for (CommandMapping test : this.commands.values()) {
if (mapping.equals(test)) {
return true;
}
}
return false;
}
/**
* Get the number of registered aliases.
*
* @return The number of aliases
*/
public synchronized int size() {
return this.commands.size();
}
@Override
public boolean call(CommandSource source, String arguments, List<String> parents) throws CommandException {
String[] parts = arguments.split(" +", 2);
Optional<CommandMapping> mapping = get(parts[0]);
if (mapping.isPresent()) {
List<String> passedParents = new ArrayList<String>(parents.size() + 1);
passedParents.addAll(parents);
passedParents.add(parts[0]);
try {
mapping.get().getCallable().call(source, parts.length > 1 ? parts[1] : "", Collections.unmodifiableList(passedParents));
} catch (CommandException c) {
throw c;
} catch (Throwable t) {
throw new InvocationCommandException(t);
}
return true;
} else {
return false;
}
}
@Override
public synchronized boolean testPermission(CommandSource source) {
for (CommandMapping mapping : this.commands.values()) {
if (!mapping.getCallable().testPermission(source)) {
return false;
}
}
return true;
}
@Override
public List<String> getSuggestions(CommandSource source, String arguments) throws CommandException {
String[] parts = arguments.split(" +", 2);
List<String> suggestions = new ArrayList<String>();
if (parts.length == 1) { // Auto completing commands
String incompleteCommand = parts[0].toLowerCase();
synchronized (this) {
for (CommandMapping mapping : this.commands.values()) {
for (String alias : mapping.getAllAliases()) {
if (alias.toLowerCase().startsWith(incompleteCommand)) {
suggestions.add(alias);
}
}
}
}
} else { // Complete using subcommand
Optional<CommandMapping> mapping = get(parts[0]);
if (mapping.isPresent()) {
List<String> ret = mapping.get().getCallable().getSuggestions(source, parts.length > 1 ? parts[1] : "");
if (ret == null) {
suggestions.addAll(ret);
}
}
}
return Collections.unmodifiableList(suggestions);
}
@Override
public String getShortDescription(CommandSource source) {
return this.shortDescription;
}
@Override
public Text getHelp(CommandSource source) {
return this.help;
}
@Override
public String getUsage(CommandSource source) {
return "<sub-command>"; // @TODO: Translate
}
}
| Fix null tab completions
| src/main/java/org/spongepowered/api/util/command/dispatcher/SimpleDispatcher.java | Fix null tab completions | <ide><path>rc/main/java/org/spongepowered/api/util/command/dispatcher/SimpleDispatcher.java
<ide>
<ide> if (mapping.isPresent()) {
<ide> List<String> ret = mapping.get().getCallable().getSuggestions(source, parts.length > 1 ? parts[1] : "");
<del> if (ret == null) {
<add> if (ret != null) {
<ide> suggestions.addAll(ret);
<ide> }
<ide> } |
|
Java | apache-2.0 | 8f57f00b0df9d430f138c5ade0e4188ee1c87d20 | 0 | tombolaltd/cordova-plugin-inappbrowser,tombolaltd/cordova-plugin-inappbrowser,tombolaltd/cordova-plugin-inappbrowser | /*
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.cordova.inappbrowser;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.provider.Browser;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaHttpAuthHandler;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginManager;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
//Note to future devs - if you have any c# experience
//This looks weird. Java doesn't have the equivalent
//of delegates, this is the way to do it.
//default is like internal in c#
interface NativeScriptResultHandler
{
public boolean handle(String scriptResult);
}
@SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
private static final String NULL = "null";
protected static final String LOG_TAG = "InAppBrowser";
private static final String SELF = "_self";
private static final String SYSTEM = "_system";
private static final String EXIT_EVENT = "exit";
private static final String HIDDEN_EVENT = "hidden";
private static final String UNHIDDEN_EVENT = "unhidden";
private static final String LOAD_START_EVENT = "loadstart";
private static final String LOAD_STOP_EVENT = "loadstop";
private static final String LOAD_ERROR_EVENT = "loaderror";
private static final String POLL_RESULT_EVENT = "pollresult";
private static final String BLANK_PAGE_URL = "about:blank";
private InAppBrowserDialog dialog;
private WebView inAppWebView;
private EditText edittext;
private CallbackContext callbackContext;
private boolean showLocationBar = true;
private boolean showZoomControls = true;
private boolean openWindowHidden = false;
private boolean clearAllCache = false;
private boolean clearSessionCache = false;
private boolean hadwareBackButton = true;
private boolean mediaPlaybackRequiresUserGesture = false;
private boolean destroyHistoryOnNextPageFinished = false;
private boolean reOpenOnNextPageFinished = false;
private NativeScriptResultHandler nativeScriptResultHandler = new NativeScriptResultHandler(){
private void sendPollResult(String scriptResult){
try {
JSONObject responseObject = new JSONObject();
responseObject.put("type", "pollresult");
responseObject.put("data", scriptResult);
sendOKUpdate(responseObject);
} catch (JSONException ex){
Log.d(LOG_TAG, "Should never happen");
}
}
public boolean handle(String scriptResult) {
Log.d(LOG_TAG, "Result = " + scriptResult);
try {
JSONArray returnedArray = new JSONArray(scriptResult);
Log.d(LOG_TAG, "Parsed OK");
JSONArray innerArray= returnedArray.optJSONArray(0);
if(innerArray == null || innerArray.length() != 1) {
sendPollResult(scriptResult);
return true;
}
JSONObject commandObject = innerArray.optJSONObject(0);
if(commandObject == null) {
sendPollResult(scriptResult);
return true;
}
String action = commandObject.optString("InAppBrowserAction");
if(action == null){
sendPollResult(scriptResult);
return true;
}
if(action.equalsIgnoreCase("close")) {
stopPoll();
closeDialog();
return true;
}
if(action.equalsIgnoreCase("hide")) {
hideDialog(true);
return true
}
Log.d("The poll script return value looked like it shoud be handled natively, but was not formed correctly (unhandled action) - returning json directly to JS");
sendPollResult(scriptResult);
return true;
}
catch(JSONException ex){
Log.d(LOG_TAG, "Parse Error = " + ex.getMessage());
try {
JSONObject error = new JSONObject();
error.put("message", ex.getMessage());
sendErrorUpdate(error);
return false;
}
catch(JSONException ex2) {
Log.d(LOG_TAG, "Should never happen");
}
}
return false;
}
};
/**
* Executes the request and returns PluginResult.
*
* @param action the action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext the callbackContext used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("open")) {
this.callbackContext = callbackContext;
final String url = args.getString(0);
String t = args.optString(1);
if (t == null || t.equals("") || t.equals(NULL)) {
t = SELF;
}
final String target = t;
final HashMap<String, Boolean> features = parseFeature(args.optString(2));
Log.d(LOG_TAG, "target = " + target);
OpenOnNewThread(url, target, features);
return true;
}
if (action.equals("close")) {
closeDialog();
return true;
}
if (action.equals("injectScriptCode")) {
injectScriptCode(args.getString(0), args.getBoolean(1), callbackContext.getCallbackId());
return true;
}
if (action.equals("injectScriptFile")) {
injectScriptFile(args.getString(0), args.getBoolean(1), callbackContext.getCallbackId());
return true;
}
if (action.equals("injectStyleCode")) {
injectStyleCode(args.getString(0), args.getBoolean(1), callbackContext.getCallbackId());
return true;
}
if (action.equals("injectStyleFile")) {
final String callbackContextId = callbackContext.getCallbackId();
injectStyleFile(args.getString(0), args.getBoolean(1), callbackContext.getCallbackId());
return true;
}
if (action.equals("show")) {
showDialogue();
return true;
}
if (action.equals("hide")) {
final boolean releaseResources = args.isNull(1) ? false : args.getBoolean(1);
final boolean goToBlank = args.isNull(1) ? false : args.getBoolean(1);
hideDialog(goToBlank);
return true;
}
if (action.equals("unHide")) {
final String url = args.isNull(0) ? null : args.getString(0);
unHideDialog(url);
return true;
}
if (action.equals("startPoll")) {
if (args.isNull(0) || args.isNull(1)) {
Log.w(LOG_TAG, "Attempt to start poll with missin function or interval");
return true;
}
final String pollFunction = args.getString(0);
final long pollInterval = args.getLong(1);
startPoll(pollInterval, pollFunction);
return true;
}
if (action.equals("stopPoll")){
stopPoll();
return true;
}
return false;
}
private void startPoll(final long pollInterval, final String pollFunction) {
//TODO: If polling - stop.
//TODO: Set last poll function/interval
//TODO: call poll
TimerTask currentTask = new TimerTask(){
@Override
public void run() {
final String jsWrapper = "(function(){prompt(JSON.stringify([eval(%s)]), 'gap-iab-native://poll')})()";
injectDeferredObject(pollFunction, jsWrapper);
}
};
Timer currentTimer = new Timer();
currentTimer.scheduleAtFixedRate(currentTask, 0L, pollInterval);
sendOKUpdate();
}
private void stopPoll() {
//TODO: Cancel Timer
//TODO: Destroy timer object
//TODO: Clear last poll interval/function
Log.d(LOG_TAG, "TODO: stopPoll");
sendOKUpdate();
}
private void OpenOnNewThread(final String url, final String target, final HashMap<String, Boolean> features) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
String result = "";
// SELF
if (SELF.equals(target)) {
LOG.d(LOG_TAG, "in self");
/* This code exists for compatibility between 3.x and 4.x versions of Cordova.
* Previously the Config class had a static method, isUrlWhitelisted(). That
* responsibility has been moved to the plugins, with an aggregating method in
* PluginManager.
*/
Boolean shouldAllowNavigation = shouldAllowNavigation(url);
// load in webview
if (Boolean.TRUE.equals(shouldAllowNavigation)) {
Log.d(LOG_TAG, "loading in webview");
webView.loadUrl(url);
}
//Load the dialer
else if (url.startsWith(WebView.SCHEME_TEL))
{
try {
Log.d(LOG_TAG, "loading in dialer");
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
}
// load in InAppBrowser
else {
Log.d(LOG_TAG, "loading in InAppBrowser");
result = showWebPage(url, features);
}
}
// BLANK - or anything else
else {
Log.d(LOG_TAG, "in blank");
result = showWebPage(url, features);
}
sendOKUpdate(result);
}
});
}
private void injectStyleFile(String sourceFile, boolean hasCallBack, String callbackContextId) {
String jsWrapper;
if (hasCallBack) {
jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContextId);
} else {
jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
}
injectDeferredObject(sourceFile, jsWrapper);
}
private void injectStyleCode(String cssCode, boolean hasCallBack, String callbackContextId) {
String jsWrapper;
if (hasCallBack) {
jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContextId);
} else {
jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(cssCode, jsWrapper);
}
private void injectScriptFile(String sourceFile, boolean hasCallBack, String callbackContextId) {
String jsWrapper;
if (hasCallBack) {
jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContextId);
} else {
jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(sourceFile, jsWrapper);
}
private void injectScriptCode(String jsCode, boolean hasCallBack, String callbackContextId) {
String jsWrapper = hasCallBack ? String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContextId) : null;
injectDeferredObject(jsCode, jsWrapper);
}
/**
* Called when the view navigates.
*/
@Override
public void onReset() {
closeDialog();
}
/**
* Called by AccelBroker when listener is to be shut down.
* Stop listener.
*/
public void onDestroy() {
closeDialog();
}
/**
* Inject an object (script or style) into the InAppBrowser WebView.
*
* This is a helper method for the inject{Script|Style}{Code|File} API calls, which
* provides a consistent method for injecting JavaScript code into the document.
*
* If a wrapper string is supplied, then the source string will be JSON-encoded (adding
* quotes) and wrapped using string formatting. (The wrapper string should have a single
* '%s' marker)
*
* @param source The source object (filename or script/style text) to inject into
* the document.
* @param jsWrapper A JavaScript string to wrap the source string in, so that the object
* is properly injected, or null if the source string is JavaScript text
* which should be executed directly.
*/
private void injectDeferredObject(String source, String jsWrapper) {
String scriptToInject;
if (jsWrapper != null) {
org.json.JSONArray jsonEsc = new org.json.JSONArray();
jsonEsc.put(source);
String jsonRepr = jsonEsc.toString();
String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1);
scriptToInject = String.format(jsWrapper, jsonSourceString);
} else {
scriptToInject = source;
}
final String finalScriptToInject = scriptToInject;
Log.d(LOG_TAG, "Script To Inject=" + finalScriptToInject);
this.cordova.getActivity().runOnUiThread(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
Log.d(LOG_TAG, "Running KitKat or below");
// This action will have the side-effect of blurring the currently focused element
inAppWebView.loadUrl("javascript:" + finalScriptToInject);
} else {
Log.d(LOG_TAG, "Running above kitkat");
inAppWebView.evaluateJavascript(finalScriptToInject, null);
}
}
});
}
/**
* Put the list of features into a hash map
*
* @param optString
* @return
*/
private HashMap<String, Boolean> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
}
return map;
}
}
/**
* hides the dialog without destroying the instance if goToBlank is true
* the browser is navigated to about blank, this can be used to preserve
* system resources
*
* @param goToBlank
* @return
*/
private void hideDialog(final boolean goToBlank) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(null == inAppWebView){
return;
}
if(dialog != null) {
dialog.hide();
if(goToBlank){
destroyHistoryOnNextPageFinished = true;
inAppWebView.loadUrl(BLANK_PAGE_URL);
}
}
try {
JSONObject obj = new JSONObject();
obj.put("type", HIDDEN_EVENT);
sendOKUpdate(obj);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
}
/**
* un-hides the dialog - will work if the dialog has been started hidden
* and not show. Passing a URL will navigate to that page and, when the
* on loaded event is raised show it.
* system resources
*
* @param url
* @return
*/
private void unHideDialog(final String url) {
if (url == null || url.equals("") || url.equals(NULL)) {
showDialogue();
try {
JSONObject obj = new JSONObject();
obj.put("type", UNHIDDEN_EVENT);
sendOKUpdate(obj);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
return;
}
if(!shouldAllowNavigation(url, "shouldAllowRequest") ) {
return;
}
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(null == inAppWebView || null == inAppWebView.getUrl()){
return;
}
if(inAppWebView.getUrl().equals(url)){
showDialogue();
}
else {
reOpenOnNextPageFinished = true;
navigate(url);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", UNHIDDEN_EVENT);
sendOKUpdate(obj);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
}
/**
* Shows the dialog in the standard way
*
* @param
* @return
*/
private void showDialogue() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(dialog != null) {
dialog.show();
}
}
});
}
/**
* Determines whether the dialog can navigate to the URL
*
* @param url
* @return true if navigable, otherwise false or null
*/
public Boolean shouldAllowNavigation(String url) {
return shouldAllowNavigation(url, "shouldAllowNavigation");
}
/**
* Determines whether the dialog can navigate to the URL
* This allows us to specifiy the type of navgation
*
* @param url
* @return true if navigable, otherwise false or null
*/
private Boolean shouldAllowNavigation(final String url, final String pluginManagerMethod) {
Boolean shouldAllowNavigation = null;
if (url.startsWith("javascript:")) {
shouldAllowNavigation = true;
}
if (shouldAllowNavigation == null) {
try {
Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
shouldAllowNavigation = (Boolean)iuw.invoke(null, url);
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
if (shouldAllowNavigation == null) {
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
PluginManager pm = (PluginManager)gpm.invoke(webView);
Method san = pm.getClass().getMethod(pluginManagerMethod, String.class);
shouldAllowNavigation = (Boolean)san.invoke(pm, url);
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return shouldAllowNavigation;
}
/**
* Closes the dialog
*/
public void closeDialog() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final WebView childView = inAppWebView;
// The JS protects against multiple calls, so this should happen only when
// closeDialog() is called by other native code.
if (childView == null) {
return;
}
childView.setWebViewClient(new WebViewClient() {
// NB: wait for about:blank before dismissing
public void onPageFinished(WebView view, String url) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
childView.destroy();
}
}
});
// NB: From SDK 19: "If you call methods on WebView from any thread
// other than your app's UI thread, it can cause unexpected results."
// http://developer.android.com/guide/webapps/migrating.html#Threads
childView.loadUrl(BLANK_PAGE_URL);
try {
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendClosingUpdate(obj);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
}
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
public void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
/**
* Can the web browser go back?
* @return boolean
*/
public boolean canGoBack() {
return this.inAppWebView.canGoBack();
}
/**
* Has the user set the hardware back button to go back
* @return boolean
*/
public boolean hardwareBack() {
return hadwareBackButton;
}
/**
* Checks to see if it is possible to go forward one page in history, then does so.
*/
private void goForward() {
if (this.inAppWebView.canGoForward()) {
this.inAppWebView.goForward();
}
}
/**
* Navigate to the new page
*
* @param url to load
*/
private void navigate(String url) {
InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
if (!url.startsWith("http") && !url.startsWith("file:")) {
this.inAppWebView.loadUrl("http://" + url);
} else {
this.inAppWebView.loadUrl(url);
}
this.inAppWebView.requestFocus();
}
/**
* Should we show the location bar?
*
* @return boolean
*/
private boolean getShowLocationBar() {
return this.showLocationBar;
}
private InAppBrowser getInAppBrowser(){
return this;
}
/**
* Display a new browser with the specified URL.
*
* @param url the url to load.
* @param features jsonObject
*/
public String showWebPage(final String url, HashMap<String, Boolean> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
showZoomControls = true;
openWindowHidden = false;
mediaPlaybackRequiresUserGesture = false;
final String LOCATION = "location";
final String ZOOM = "zoom";
final String HIDDEN = "hidden";
final String HARDWARE_BACK_BUTTON = "hardwareback";
final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction";
final String CLEAR_ALL_CACHE = "clearcache";
final String CLEAR_SESSION_CACHE = "clearsessioncache";
if (features != null) {
Boolean show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
}
Boolean zoom = features.get(ZOOM);
if (zoom != null) {
showZoomControls = zoom.booleanValue();
}
Boolean hidden = features.get(HIDDEN);
if (hidden != null) {
openWindowHidden = hidden.booleanValue();
}
Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
if (hardwareBack != null) {
hadwareBackButton = hardwareBack.booleanValue();
}
Boolean mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION);
if (mediaPlayback != null) {
mediaPlaybackRequiresUserGesture = mediaPlayback.booleanValue();
}
Boolean cache = features.get(CLEAR_ALL_CACHE);
if (cache != null) {
clearAllCache = cache.booleanValue();
} else {
cache = features.get(CLEAR_SESSION_CACHE);
if (cache != null) {
clearSessionCache = cache.booleanValue();
}
}
}
final CordovaWebView thatWebView = this.webView;
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* @return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
);
return value;
}
@SuppressLint("NewApi")
public void run() {
// CB-6702 InAppBrowser hangs when opening more than one instance
if (dialog != null) {
dialog.dismiss();
};
// Let's create the main dialog
dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setInAppBroswer(getInAppBrowser());
// Main container layout
LinearLayout main = new LinearLayout(cordova.getActivity());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
//Please, no more black!
toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(Integer.valueOf(1));
// Back button
ImageButton back = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(Integer.valueOf(2));
Resources activityRes = cordova.getActivity().getResources();
int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName());
Drawable backIcon = activityRes.getDrawable(backResId);
back.setBackground(null);
back.setImageDrawable(backIcon);
back.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
back.getAdjustViewBounds();
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
ImageButton forward = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(Integer.valueOf(3));
int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName());
Drawable fwdIcon = activityRes.getDrawable(fwdResId);
forward.setBackground(null);
forward.setImageDrawable(fwdIcon);
forward.setScaleType(ImageView.ScaleType.FIT_CENTER);
forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
forward.getAdjustViewBounds();
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(cordova.getActivity());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(Integer.valueOf(4));
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Close/Done button
ImageButton close = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
close.setLayoutParams(closeLayoutParams);
forward.setContentDescription("Close Button");
close.setId(Integer.valueOf(5));
int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName());
Drawable closeIcon = activityRes.getDrawable(closeResId);
close.setBackground(null);
close.setImageDrawable(closeIcon);
close.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
close.getAdjustViewBounds();
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setId(Integer.valueOf(6));
//TODO
inAppWebView.setWebChromeClient(new InAppChromeClient(nativeScriptResultHandler, thatWebView));
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(showZoomControls);
settings.setPluginState(android.webkit.WebSettings.PluginState.ON);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture);
}
String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
String appendUserAgent = preferences.getString("AppendUserAgent", null);
if (overrideUserAgent != null) {
settings.setUserAgentString(overrideUserAgent);
}
if (appendUserAgent != null) {
settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent);
}
//Toggle whether this is enabled or not!
Bundle appSettings = cordova.getActivity().getIntent().getExtras();
boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
if (enableDatabase) {
String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
settings.setDatabaseEnabled(true);
}
settings.setDomStorageEnabled(true);
if (clearAllCache) {
CookieManager.getInstance().removeAllCookie();
} else if (clearSessionCache) {
CookieManager.getInstance().removeSessionCookie();
}
inAppWebView.loadUrl(url);
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(true);
inAppWebView.requestFocus();
inAppWebView.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar
toolbar.addView(actionButtonContainer);
toolbar.addView(edittext);
toolbar.addView(close);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
main.addView(inAppWebView);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
// the goal of openhidden is to load the url and not display it
// Show() needs to be called to cause the URL to be loaded
if(openWindowHidden) {
dialog.hide();
}
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
private void sendClosingUpdate(JSONObject obj) {
sendUpdate(obj, false, PluginResult.Status.OK);
}
private void sendErrorUpdate(JSONObject obj) {
sendUpdate(obj, true, PluginResult.Status.ERROR);
}
private void sendOKUpdate() {
sendOKUpdate("");
}
private void sendOKUpdate(String response) {
sendUpdate(response, true, PluginResult.Status.OK);
}
private void sendUpdate(String response, boolean keepCallback, PluginResult.Status status) {
if (callbackContext != null) {
PluginResult pluginResult = new PluginResult(status, response);
pluginResult.setKeepCallback(keepCallback);
this.callbackContext.sendPluginResult(pluginResult);
}
}
/**
* Create a new plugin success result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
*/
private void sendOKUpdate(JSONObject obj) {
sendUpdate(obj, true, PluginResult.Status.OK);
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
* @param status the status code to return to the JavaScript environment
*/
private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
if (callbackContext != null) {
PluginResult result = new PluginResult(status, obj);
result.setKeepCallback(keepCallback);
callbackContext.sendPluginResult(result);
if (!keepCallback) {
callbackContext = null;
}
}
}
/**
* The webview client receives notifications about appView
*/
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
/**
* Constructor.
*
* @param webView
* @param mEditText
*/
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
this.webView = webView;
this.edittext = mEditText;
}
/**
* Override the URL that should be loaded
*
* This handles a small subset of all the URIs that would be encountered.
*
* @param webView
* @param url
*/
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
} else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
} else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:" + address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
}
}
return false;
}
/*
* onPageStarted fires the LOAD_START_EVENT
*
* @param view
* @param url
* @param favicon
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String newloc = "";
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
newloc = url;
}
else
{
// Assume that everything is HTTP at this point, because if we don't specify,
// it really should be. Complain loudly about this!!!
LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI");
newloc = "http://" + url;
}
// Update the UI if we haven't already
if (!newloc.equals(edittext.getText().toString())) {
edittext.setText(newloc);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_START_EVENT);
obj.put("url", newloc);
sendOKUpdate(obj);
} catch (JSONException ex) {
LOG.e(LOG_TAG, "URI passed in has caused a JSON error.");
}
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush();
} else {
CookieSyncManager.getInstance().sync();
}
if(reOpenOnNextPageFinished){
reOpenOnNextPageFinished = false;
if(destroyHistoryOnNextPageFinished){
destroyHistoryOnNextPageFinished = false;
view.clearHistory();
}
showDialogue();
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_STOP_EVENT);
obj.put("url", url);
sendOKUpdate(obj);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_ERROR_EVENT);
obj.put("url", failingUrl);
obj.put("code", errorCode);
obj.put("message", description);
sendErrorUpdate(obj);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
/**
* On received http auth request.
*/
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
// Check if there is some plugin which can resolve this auth challenge
PluginManager pluginManager = null;
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
pluginManager = (PluginManager)gpm.invoke(webView);
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
if (pluginManager == null) {
try {
Field pmf = webView.getClass().getField("pluginManager");
pluginManager = (PluginManager)pmf.get(webView);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
}
if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) {
return;
}
// By default handle 401 like we'd normally do!
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
}
} | src/android/InAppBrowser.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.cordova.inappbrowser;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.provider.Browser;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.Config;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaHttpAuthHandler;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginManager;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
//Note to future devs - if you have any c# experience
//This looks weird. Java doesn't have the equivalent
//of delegates, this is the way to do it.
//default is like internal in c#
interface NativeScriptResultHandler
{
public boolean handle(String scriptResult);
}
@SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
private static final String NULL = "null";
protected static final String LOG_TAG = "InAppBrowser";
private static final String SELF = "_self";
private static final String SYSTEM = "_system";
private static final String EXIT_EVENT = "exit";
private static final String HIDDEN_EVENT = "hidden";
private static final String UNHIDDEN_EVENT = "unhidden";
private static final String LOAD_START_EVENT = "loadstart";
private static final String LOAD_STOP_EVENT = "loadstop";
private static final String LOAD_ERROR_EVENT = "loaderror";
private static final String POLL_RESULT_EVENT = "pollresult";
private static final String BLANK_PAGE_URL = "about:blank";
private InAppBrowserDialog dialog;
private WebView inAppWebView;
private EditText edittext;
private CallbackContext callbackContext;
private boolean showLocationBar = true;
private boolean showZoomControls = true;
private boolean openWindowHidden = false;
private boolean clearAllCache = false;
private boolean clearSessionCache = false;
private boolean hadwareBackButton = true;
private boolean mediaPlaybackRequiresUserGesture = false;
private boolean destroyHistoryOnNextPageFinished = false;
private boolean reOpenOnNextPageFinished = false;
private NativeScriptResultHandler nativeScriptResultHandler = new NativeScriptResultHandler(){
private void sendPollResult(String scriptResult){
try {
JSONObject responseObject = new JSONObject();
responseObject.put("type", "pollresult");
responseObject.put("data", scriptResult);
sendOKUpdate(responseObject);
} catch (JSONException ex){
Log.d(LOG_TAG, "Should never happen");
}
}
public boolean handle(String scriptResult) {
Log.d(LOG_TAG, "Result = " + scriptResult);
try {
JSONArray returnedArray = new JSONArray(scriptResult);
Log.d(LOG_TAG, "Parsed OK");
JSONArray innerArray= returnedArray.optJSONArray(0);
if(innerArray == null || innerArray.length() != 1) {
sendPollResult(scriptResult);
return true;
}
JSONObject commandObject = innerArray.optJSONObject(0);
if(commandObject == null) {
sendPollResult(scriptResult);
return true;
}
String action = commandObject.optString("InAppBrowserAction");
if(action == null){
sendPollResult(scriptResult);
return true;
}
if(action.equalsIgnoreCase("close")) {
stopPoll();
closeDialog();
return;
}
if(action.equalsIgnoreCase("hide")) {
hideDialog(true);
return;
}
else {
Log.d("The poll script return value looked like it shoud be handled natively, but was not formed correctly (unhandled action) - returning json directly to JS");
sendPollResult(scriptResult);
}
return true;
}
catch(JSONException ex){
Log.d(LOG_TAG, "Parse Error = " + ex.getMessage());
try {
JSONObject error = new JSONObject();
error.put("message", ex.getMessage());
sendErrorUpdate(error);
return false;
}
catch(JSONException ex2) {
Log.d(LOG_TAG, "Should never happen");
}
}
return false;
}
};
/**
* Executes the request and returns PluginResult.
*
* @param action the action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext the callbackContext used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("open")) {
this.callbackContext = callbackContext;
final String url = args.getString(0);
String t = args.optString(1);
if (t == null || t.equals("") || t.equals(NULL)) {
t = SELF;
}
final String target = t;
final HashMap<String, Boolean> features = parseFeature(args.optString(2));
Log.d(LOG_TAG, "target = " + target);
OpenOnNewThread(url, target, features);
return true;
}
if (action.equals("close")) {
closeDialog();
return true;
}
if (action.equals("injectScriptCode")) {
injectScriptCode(args.getString(0), args.getBoolean(1), callbackContext.getCallbackId());
return true;
}
if (action.equals("injectScriptFile")) {
injectScriptFile(args.getString(0), args.getBoolean(1), callbackContext.getCallbackId());
return true;
}
if (action.equals("injectStyleCode")) {
injectStyleCode(args.getString(0), args.getBoolean(1), callbackContext.getCallbackId());
return true;
}
if (action.equals("injectStyleFile")) {
final String callbackContextId = callbackContext.getCallbackId();
injectStyleFile(args.getString(0), args.getBoolean(1), callbackContext.getCallbackId());
return true;
}
if (action.equals("show")) {
showDialogue();
return true;
}
if (action.equals("hide")) {
final boolean releaseResources = args.isNull(1) ? false : args.getBoolean(1);
final boolean goToBlank = args.isNull(1) ? false : args.getBoolean(1);
hideDialog(goToBlank);
return true;
}
if (action.equals("unHide")) {
final String url = args.isNull(0) ? null : args.getString(0);
unHideDialog(url);
return true;
}
if (action.equals("startPoll")) {
if (args.isNull(0) || args.isNull(1)) {
Log.w(LOG_TAG, "Attempt to start poll with missin function or interval");
return true;
}
final String pollFunction = args.getString(0);
final long pollInterval = args.getLong(1);
startPoll(pollInterval, pollFunction);
return true;
}
if (action.equals("stopPoll")){
stopPoll();
return true;
}
return false;
}
private void startPoll(final long pollInterval, final String pollFunction) {
//TODO: If polling - stop.
//TODO: Set last poll function/interval
//TODO: call poll
TimerTask currentTask = new TimerTask(){
@Override
public void run() {
final String jsWrapper = "(function(){prompt(JSON.stringify([eval(%s)]), 'gap-iab-native://poll')})()";
injectDeferredObject(pollFunction, jsWrapper);
}
};
Timer currentTimer = new Timer();
currentTimer.scheduleAtFixedRate(currentTask, 0L, pollInterval);
sendOKUpdate();
}
private void stopPoll() {
//TODO: Cancel Timer
//TODO: Destroy timer object
//TODO: Clear last poll interval/function
Log.d(LOG_TAG, "TODO: stopPoll");
sendOKUpdate();
}
private void OpenOnNewThread(final String url, final String target, final HashMap<String, Boolean> features) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
String result = "";
// SELF
if (SELF.equals(target)) {
LOG.d(LOG_TAG, "in self");
/* This code exists for compatibility between 3.x and 4.x versions of Cordova.
* Previously the Config class had a static method, isUrlWhitelisted(). That
* responsibility has been moved to the plugins, with an aggregating method in
* PluginManager.
*/
Boolean shouldAllowNavigation = shouldAllowNavigation(url);
// load in webview
if (Boolean.TRUE.equals(shouldAllowNavigation)) {
Log.d(LOG_TAG, "loading in webview");
webView.loadUrl(url);
}
//Load the dialer
else if (url.startsWith(WebView.SCHEME_TEL))
{
try {
Log.d(LOG_TAG, "loading in dialer");
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
}
// load in InAppBrowser
else {
Log.d(LOG_TAG, "loading in InAppBrowser");
result = showWebPage(url, features);
}
}
// BLANK - or anything else
else {
Log.d(LOG_TAG, "in blank");
result = showWebPage(url, features);
}
sendOKUpdate(result);
}
});
}
private void injectStyleFile(String sourceFile, boolean hasCallBack, String callbackContextId) {
String jsWrapper;
if (hasCallBack) {
jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContextId);
} else {
jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
}
injectDeferredObject(sourceFile, jsWrapper);
}
private void injectStyleCode(String cssCode, boolean hasCallBack, String callbackContextId) {
String jsWrapper;
if (hasCallBack) {
jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContextId);
} else {
jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(cssCode, jsWrapper);
}
private void injectScriptFile(String sourceFile, boolean hasCallBack, String callbackContextId) {
String jsWrapper;
if (hasCallBack) {
jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContextId);
} else {
jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(sourceFile, jsWrapper);
}
private void injectScriptCode(String jsCode, boolean hasCallBack, String callbackContextId) {
String jsWrapper = hasCallBack ? String.format("(function(){prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')})()", callbackContextId) : null;
injectDeferredObject(jsCode, jsWrapper);
}
/**
* Called when the view navigates.
*/
@Override
public void onReset() {
closeDialog();
}
/**
* Called by AccelBroker when listener is to be shut down.
* Stop listener.
*/
public void onDestroy() {
closeDialog();
}
/**
* Inject an object (script or style) into the InAppBrowser WebView.
*
* This is a helper method for the inject{Script|Style}{Code|File} API calls, which
* provides a consistent method for injecting JavaScript code into the document.
*
* If a wrapper string is supplied, then the source string will be JSON-encoded (adding
* quotes) and wrapped using string formatting. (The wrapper string should have a single
* '%s' marker)
*
* @param source The source object (filename or script/style text) to inject into
* the document.
* @param jsWrapper A JavaScript string to wrap the source string in, so that the object
* is properly injected, or null if the source string is JavaScript text
* which should be executed directly.
*/
private void injectDeferredObject(String source, String jsWrapper) {
String scriptToInject;
if (jsWrapper != null) {
org.json.JSONArray jsonEsc = new org.json.JSONArray();
jsonEsc.put(source);
String jsonRepr = jsonEsc.toString();
String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1);
scriptToInject = String.format(jsWrapper, jsonSourceString);
} else {
scriptToInject = source;
}
final String finalScriptToInject = scriptToInject;
Log.d(LOG_TAG, "Script To Inject=" + finalScriptToInject);
this.cordova.getActivity().runOnUiThread(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
Log.d(LOG_TAG, "Running KitKat or below");
// This action will have the side-effect of blurring the currently focused element
inAppWebView.loadUrl("javascript:" + finalScriptToInject);
} else {
Log.d(LOG_TAG, "Running above kitkat");
inAppWebView.evaluateJavascript(finalScriptToInject, null);
}
}
});
}
/**
* Put the list of features into a hash map
*
* @param optString
* @return
*/
private HashMap<String, Boolean> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
}
return map;
}
}
/**
* hides the dialog without destroying the instance if goToBlank is true
* the browser is navigated to about blank, this can be used to preserve
* system resources
*
* @param goToBlank
* @return
*/
private void hideDialog(final boolean goToBlank) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(null == inAppWebView){
return;
}
if(dialog != null) {
dialog.hide();
if(goToBlank){
destroyHistoryOnNextPageFinished = true;
inAppWebView.loadUrl(BLANK_PAGE_URL);
}
}
try {
JSONObject obj = new JSONObject();
obj.put("type", HIDDEN_EVENT);
sendOKUpdate(obj);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
}
/**
* un-hides the dialog - will work if the dialog has been started hidden
* and not show. Passing a URL will navigate to that page and, when the
* on loaded event is raised show it.
* system resources
*
* @param url
* @return
*/
private void unHideDialog(final String url) {
if (url == null || url.equals("") || url.equals(NULL)) {
showDialogue();
try {
JSONObject obj = new JSONObject();
obj.put("type", UNHIDDEN_EVENT);
sendOKUpdate(obj);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
return;
}
if(!shouldAllowNavigation(url, "shouldAllowRequest") ) {
return;
}
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(null == inAppWebView || null == inAppWebView.getUrl()){
return;
}
if(inAppWebView.getUrl().equals(url)){
showDialogue();
}
else {
reOpenOnNextPageFinished = true;
navigate(url);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", UNHIDDEN_EVENT);
sendOKUpdate(obj);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
}
/**
* Shows the dialog in the standard way
*
* @param
* @return
*/
private void showDialogue() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if(dialog != null) {
dialog.show();
}
}
});
}
/**
* Determines whether the dialog can navigate to the URL
*
* @param url
* @return true if navigable, otherwise false or null
*/
public Boolean shouldAllowNavigation(String url) {
return shouldAllowNavigation(url, "shouldAllowNavigation");
}
/**
* Determines whether the dialog can navigate to the URL
* This allows us to specifiy the type of navgation
*
* @param url
* @return true if navigable, otherwise false or null
*/
private Boolean shouldAllowNavigation(final String url, final String pluginManagerMethod) {
Boolean shouldAllowNavigation = null;
if (url.startsWith("javascript:")) {
shouldAllowNavigation = true;
}
if (shouldAllowNavigation == null) {
try {
Method iuw = Config.class.getMethod("isUrlWhiteListed", String.class);
shouldAllowNavigation = (Boolean)iuw.invoke(null, url);
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
if (shouldAllowNavigation == null) {
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
PluginManager pm = (PluginManager)gpm.invoke(webView);
Method san = pm.getClass().getMethod(pluginManagerMethod, String.class);
shouldAllowNavigation = (Boolean)san.invoke(pm, url);
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return shouldAllowNavigation;
}
/**
* Closes the dialog
*/
public void closeDialog() {
this.cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
final WebView childView = inAppWebView;
// The JS protects against multiple calls, so this should happen only when
// closeDialog() is called by other native code.
if (childView == null) {
return;
}
childView.setWebViewClient(new WebViewClient() {
// NB: wait for about:blank before dismissing
public void onPageFinished(WebView view, String url) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
childView.destroy();
}
}
});
// NB: From SDK 19: "If you call methods on WebView from any thread
// other than your app's UI thread, it can cause unexpected results."
// http://developer.android.com/guide/webapps/migrating.html#Threads
childView.loadUrl(BLANK_PAGE_URL);
try {
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendClosingUpdate(obj);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
}
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
public void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
/**
* Can the web browser go back?
* @return boolean
*/
public boolean canGoBack() {
return this.inAppWebView.canGoBack();
}
/**
* Has the user set the hardware back button to go back
* @return boolean
*/
public boolean hardwareBack() {
return hadwareBackButton;
}
/**
* Checks to see if it is possible to go forward one page in history, then does so.
*/
private void goForward() {
if (this.inAppWebView.canGoForward()) {
this.inAppWebView.goForward();
}
}
/**
* Navigate to the new page
*
* @param url to load
*/
private void navigate(String url) {
InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
if (!url.startsWith("http") && !url.startsWith("file:")) {
this.inAppWebView.loadUrl("http://" + url);
} else {
this.inAppWebView.loadUrl(url);
}
this.inAppWebView.requestFocus();
}
/**
* Should we show the location bar?
*
* @return boolean
*/
private boolean getShowLocationBar() {
return this.showLocationBar;
}
private InAppBrowser getInAppBrowser(){
return this;
}
/**
* Display a new browser with the specified URL.
*
* @param url the url to load.
* @param features jsonObject
*/
public String showWebPage(final String url, HashMap<String, Boolean> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
showZoomControls = true;
openWindowHidden = false;
mediaPlaybackRequiresUserGesture = false;
final String LOCATION = "location";
final String ZOOM = "zoom";
final String HIDDEN = "hidden";
final String HARDWARE_BACK_BUTTON = "hardwareback";
final String MEDIA_PLAYBACK_REQUIRES_USER_ACTION = "mediaPlaybackRequiresUserAction";
final String CLEAR_ALL_CACHE = "clearcache";
final String CLEAR_SESSION_CACHE = "clearsessioncache";
if (features != null) {
Boolean show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
}
Boolean zoom = features.get(ZOOM);
if (zoom != null) {
showZoomControls = zoom.booleanValue();
}
Boolean hidden = features.get(HIDDEN);
if (hidden != null) {
openWindowHidden = hidden.booleanValue();
}
Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
if (hardwareBack != null) {
hadwareBackButton = hardwareBack.booleanValue();
}
Boolean mediaPlayback = features.get(MEDIA_PLAYBACK_REQUIRES_USER_ACTION);
if (mediaPlayback != null) {
mediaPlaybackRequiresUserGesture = mediaPlayback.booleanValue();
}
Boolean cache = features.get(CLEAR_ALL_CACHE);
if (cache != null) {
clearAllCache = cache.booleanValue();
} else {
cache = features.get(CLEAR_SESSION_CACHE);
if (cache != null) {
clearSessionCache = cache.booleanValue();
}
}
}
final CordovaWebView thatWebView = this.webView;
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* @return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
);
return value;
}
@SuppressLint("NewApi")
public void run() {
// CB-6702 InAppBrowser hangs when opening more than one instance
if (dialog != null) {
dialog.dismiss();
};
// Let's create the main dialog
dialog = new InAppBrowserDialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setInAppBroswer(getInAppBrowser());
// Main container layout
LinearLayout main = new LinearLayout(cordova.getActivity());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
//Please, no more black!
toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(Integer.valueOf(1));
// Back button
ImageButton back = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(Integer.valueOf(2));
Resources activityRes = cordova.getActivity().getResources();
int backResId = activityRes.getIdentifier("ic_action_previous_item", "drawable", cordova.getActivity().getPackageName());
Drawable backIcon = activityRes.getDrawable(backResId);
back.setBackground(null);
back.setImageDrawable(backIcon);
back.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
back.getAdjustViewBounds();
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
ImageButton forward = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(Integer.valueOf(3));
int fwdResId = activityRes.getIdentifier("ic_action_next_item", "drawable", cordova.getActivity().getPackageName());
Drawable fwdIcon = activityRes.getDrawable(fwdResId);
forward.setBackground(null);
forward.setImageDrawable(fwdIcon);
forward.setScaleType(ImageView.ScaleType.FIT_CENTER);
forward.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
forward.getAdjustViewBounds();
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(cordova.getActivity());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(Integer.valueOf(4));
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Close/Done button
ImageButton close = new ImageButton(cordova.getActivity());
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
close.setLayoutParams(closeLayoutParams);
forward.setContentDescription("Close Button");
close.setId(Integer.valueOf(5));
int closeResId = activityRes.getIdentifier("ic_action_remove", "drawable", cordova.getActivity().getPackageName());
Drawable closeIcon = activityRes.getDrawable(closeResId);
close.setBackground(null);
close.setImageDrawable(closeIcon);
close.setScaleType(ImageView.ScaleType.FIT_CENTER);
back.setPadding(0, this.dpToPixels(10), 0, this.dpToPixels(10));
close.getAdjustViewBounds();
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setId(Integer.valueOf(6));
//TODO
inAppWebView.setWebChromeClient(new InAppChromeClient(nativeScriptResultHandler, thatWebView));
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(showZoomControls);
settings.setPluginState(android.webkit.WebSettings.PluginState.ON);
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
settings.setMediaPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture);
}
String overrideUserAgent = preferences.getString("OverrideUserAgent", null);
String appendUserAgent = preferences.getString("AppendUserAgent", null);
if (overrideUserAgent != null) {
settings.setUserAgentString(overrideUserAgent);
}
if (appendUserAgent != null) {
settings.setUserAgentString(settings.getUserAgentString() + appendUserAgent);
}
//Toggle whether this is enabled or not!
Bundle appSettings = cordova.getActivity().getIntent().getExtras();
boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
if (enableDatabase) {
String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
settings.setDatabaseEnabled(true);
}
settings.setDomStorageEnabled(true);
if (clearAllCache) {
CookieManager.getInstance().removeAllCookie();
} else if (clearSessionCache) {
CookieManager.getInstance().removeSessionCookie();
}
inAppWebView.loadUrl(url);
inAppWebView.setId(Integer.valueOf(6));
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(true);
inAppWebView.requestFocus();
inAppWebView.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar
toolbar.addView(actionButtonContainer);
toolbar.addView(edittext);
toolbar.addView(close);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
main.addView(inAppWebView);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
// the goal of openhidden is to load the url and not display it
// Show() needs to be called to cause the URL to be loaded
if(openWindowHidden) {
dialog.hide();
}
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
private void sendClosingUpdate(JSONObject obj) {
sendUpdate(obj, false, PluginResult.Status.OK);
}
private void sendErrorUpdate(JSONObject obj) {
sendUpdate(obj, true, PluginResult.Status.ERROR);
}
private void sendOKUpdate() {
sendOKUpdate("");
}
private void sendOKUpdate(String response) {
sendUpdate(response, true, PluginResult.Status.OK);
}
private void sendUpdate(String response, boolean keepCallback, PluginResult.Status status) {
if (callbackContext != null) {
PluginResult pluginResult = new PluginResult(status, response);
pluginResult.setKeepCallback(keepCallback);
this.callbackContext.sendPluginResult(pluginResult);
}
}
/**
* Create a new plugin success result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
*/
private void sendOKUpdate(JSONObject obj) {
sendUpdate(obj, true, PluginResult.Status.OK);
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
* @param status the status code to return to the JavaScript environment
*/
private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
if (callbackContext != null) {
PluginResult result = new PluginResult(status, obj);
result.setKeepCallback(keepCallback);
callbackContext.sendPluginResult(result);
if (!keepCallback) {
callbackContext = null;
}
}
}
/**
* The webview client receives notifications about appView
*/
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
/**
* Constructor.
*
* @param webView
* @param mEditText
*/
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
this.webView = webView;
this.edittext = mEditText;
}
/**
* Override the URL that should be loaded
*
* This handles a small subset of all the URIs that would be encountered.
*
* @param webView
* @param url
*/
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
} else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
} else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:" + address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
cordova.getActivity().startActivity(intent);
return true;
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
}
}
return false;
}
/*
* onPageStarted fires the LOAD_START_EVENT
*
* @param view
* @param url
* @param favicon
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String newloc = "";
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
newloc = url;
}
else
{
// Assume that everything is HTTP at this point, because if we don't specify,
// it really should be. Complain loudly about this!!!
LOG.e(LOG_TAG, "Possible Uncaught/Unknown URI");
newloc = "http://" + url;
}
// Update the UI if we haven't already
if (!newloc.equals(edittext.getText().toString())) {
edittext.setText(newloc);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_START_EVENT);
obj.put("url", newloc);
sendOKUpdate(obj);
} catch (JSONException ex) {
LOG.e(LOG_TAG, "URI passed in has caused a JSON error.");
}
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// CB-10395 InAppBrowser's WebView not storing cookies reliable to local device storage
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush();
} else {
CookieSyncManager.getInstance().sync();
}
if(reOpenOnNextPageFinished){
reOpenOnNextPageFinished = false;
if(destroyHistoryOnNextPageFinished){
destroyHistoryOnNextPageFinished = false;
view.clearHistory();
}
showDialogue();
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_STOP_EVENT);
obj.put("url", url);
sendOKUpdate(obj);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_ERROR_EVENT);
obj.put("url", failingUrl);
obj.put("code", errorCode);
obj.put("message", description);
sendErrorUpdate(obj);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
/**
* On received http auth request.
*/
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
// Check if there is some plugin which can resolve this auth challenge
PluginManager pluginManager = null;
try {
Method gpm = webView.getClass().getMethod("getPluginManager");
pluginManager = (PluginManager)gpm.invoke(webView);
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
if (pluginManager == null) {
try {
Field pmf = webView.getClass().getField("pluginManager");
pluginManager = (PluginManager)pmf.get(webView);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
}
if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(webView, new CordovaHttpAuthHandler(handler), host, realm)) {
return;
}
// By default handle 401 like we'd normally do!
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
}
} | Trying to react to poll result
| src/android/InAppBrowser.java | Trying to react to poll result | <ide><path>rc/android/InAppBrowser.java
<ide> if(action.equalsIgnoreCase("close")) {
<ide> stopPoll();
<ide> closeDialog();
<del> return;
<add> return true;
<ide> }
<ide> if(action.equalsIgnoreCase("hide")) {
<ide> hideDialog(true);
<del> return;
<del> }
<del> else {
<del> Log.d("The poll script return value looked like it shoud be handled natively, but was not formed correctly (unhandled action) - returning json directly to JS");
<del> sendPollResult(scriptResult);
<del>
<del> }
<add> return true
<add> }
<add>
<add> Log.d("The poll script return value looked like it shoud be handled natively, but was not formed correctly (unhandled action) - returning json directly to JS");
<add> sendPollResult(scriptResult);
<add>
<ide> return true;
<ide> }
<ide> catch(JSONException ex){ |
|
JavaScript | mit | 0e36b8addc5c56907f6719f3b7d7e875b3039309 | 0 | ReissJarvis/localr,ReissJarvis/localr,ReissJarvis/localr | localr = (function() {
'use strict'
var credentials = "",
name = "",
password = "",
httpRequest = "";
return {
getDetails: function(type) {
if(type == "users") {
localr.setCred("users");
var url = 'http://api.adam-holt.co.uk/users/get?username=' + name;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('GET', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('Content-Type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log('In the get req');
console.log(response);
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
} else if(type == "business") {
localr.setCred("business");
var url = 'http://api.adam-holt.co.uk/business/get?businessname=' + name;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('GET', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('Content-Type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log('In the get req');
console.log(response);
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
} else {
console.log("Error, Invalid Type!");
};
},
register: function(type) {
if(type == "users") {
localr.setCred("users");
var url = 'http://api.adam-holt.co.uk/users/register?username=' + name;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('PUT', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('content-type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log(response);
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
} else if(type == "business") {
localr.setCred("business");
var url = 'http://api.adam-holt.co.uk/business/register?businessname=' + name;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('PUT', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('content-type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log(response);
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
} else {
console.log("Error, Invalid Type!");
};
},
setCred: function(type) {
if(type == "users") {
name = document.getElementById("username").value;
console.log(name);
password = document.getElementById("userpassword").value;
console.log(password);
localr.getBasic();
} else if(type == "business") {
name = document.getElementById("businessname").value;
console.log(name);
password = document.getElementById("businesspassword").value;
console.log(password);
localr.getBasic();
} else {
console.log("Error, Invalid Type!");
};
},
getBasic: function() {
credentials = "Basic " + btoa(name + ":" + password);
console.log(credentials);
},
checkin: function() {
var points = document.getElementById("points").value
var url = 'http://api.adam-holt.co.uk/users/checkin?username=' + name + '&points=' + points;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('PUT', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('content-type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log(response)
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
},
delete: function(type) {
if(type == "users") {
localr.setCred("users");
var url = 'http://api.adam-holt.co.uk/users/delete?username=' + name;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('DELETE', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('Content-Type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log('In the delete req');
console.log(response);
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
} else if(type == "business") {
localr.setCred("business");
var url = 'http://api.adam-holt.co.uk/business/delete?businessname=' + name;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('GET', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('Content-Type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log('In the get req');
console.log(response);
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
} else {
console.log("Error, Invalid Type!");
}
}
}
})() | debug_and_test/js/debug.js | localr = (function() {
'use strict'
var credentials = "",
name = "",
password = "",
httpRequest = "";
return {
getDetails: function(type) {
if(type == "users") {
localr.setCred("users");
var url = 'http://178.62.31.30:8080/users/get?username=' + name;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('GET', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('Content-Type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log('In the get req');
console.log(response);
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
} else if(type == "business") {
localr.setCred("business");
var url = 'http://178.62.31.30:8080/business/get?businessname=' + name;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('GET', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('Content-Type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log('In the get req');
console.log(response);
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
} else {
console.log("Error, Invalid Type!");
};
},
register: function(type) {
if(type == "users") {
localr.setCred("users");
var url = 'http://178.62.31.30:8080/users/register?username=' + name;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('PUT', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('content-type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log(response);
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
} else if(type == "business") {
localr.setCred("business");
var url = 'http://178.62.31.30:8080/business/register?businessname=' + name;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('PUT', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('content-type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log(response);
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
} else {
console.log("Error, Invalid Type!");
};
},
setCred: function(type) {
if(type == "users") {
name = document.getElementById("username").value;
console.log(name);
password = document.getElementById("userpassword").value;
console.log(password);
localr.getBasic();
} else if(type == "business") {
name = document.getElementById("businessname").value;
console.log(name);
password = document.getElementById("businesspassword").value;
console.log(password);
localr.getBasic();
} else {
console.log("Error, Invalid Type!");
};
},
getBasic: function() {
credentials = "Basic " + btoa(name + ":" + password);
console.log(credentials);
},
checkin: function() {
var points = document.getElementById("points").value
var url = 'http://178.62.31.30:8080/users/checkin?username=' + name + '&points=' + points;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('PUT', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('content-type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log(response)
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
},
delete: function(type) {
if(type == "users") {
localr.setCred("users");
var url = 'http://178.62.31.30:8080/users/delete?username=' + name;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('DELETE', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('Content-Type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log('In the delete req');
console.log(response);
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
} else if(type == "business") {
localr.setCred("business");
var url = 'http://178.62.31.30:8080/business/delete?businessname=' + name;
if(window.XMLHttpRequest) { // mozilla, safari,...
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = ("Microsoft.XMLHTTP");
}
httpRequest.open('GET', url);
httpRequest.setRequestHeader('Authorization', credentials);
httpRequest.setRequestHeader('Content-Type', "application/json");
httpRequest.onload = function() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
console.log('In the get req');
console.log(response);
} else {
console.log(httpRequest.statusText);
}
};
httpRequest.send();
} else {
console.log("Error, Invalid Type!");
}
}
}
})() | Updated debug.js to use api.adam-holt.co.uk
| debug_and_test/js/debug.js | Updated debug.js to use api.adam-holt.co.uk | <ide><path>ebug_and_test/js/debug.js
<ide> getDetails: function(type) {
<ide> if(type == "users") {
<ide> localr.setCred("users");
<del> var url = 'http://178.62.31.30:8080/users/get?username=' + name;
<add> var url = 'http://api.adam-holt.co.uk/users/get?username=' + name;
<ide> if(window.XMLHttpRequest) { // mozilla, safari,...
<ide> httpRequest = new XMLHttpRequest();
<ide> } else if(window.ActiveXObject) {
<ide> httpRequest.send();
<ide> } else if(type == "business") {
<ide> localr.setCred("business");
<del> var url = 'http://178.62.31.30:8080/business/get?businessname=' + name;
<add> var url = 'http://api.adam-holt.co.uk/business/get?businessname=' + name;
<ide> if(window.XMLHttpRequest) { // mozilla, safari,...
<ide> httpRequest = new XMLHttpRequest();
<ide> } else if(window.ActiveXObject) {
<ide> register: function(type) {
<ide> if(type == "users") {
<ide> localr.setCred("users");
<del> var url = 'http://178.62.31.30:8080/users/register?username=' + name;
<add> var url = 'http://api.adam-holt.co.uk/users/register?username=' + name;
<ide> if(window.XMLHttpRequest) { // mozilla, safari,...
<ide> httpRequest = new XMLHttpRequest();
<ide> } else if(window.ActiveXObject) {
<ide> httpRequest.send();
<ide> } else if(type == "business") {
<ide> localr.setCred("business");
<del> var url = 'http://178.62.31.30:8080/business/register?businessname=' + name;
<add> var url = 'http://api.adam-holt.co.uk/business/register?businessname=' + name;
<ide> if(window.XMLHttpRequest) { // mozilla, safari,...
<ide> httpRequest = new XMLHttpRequest();
<ide> } else if(window.ActiveXObject) {
<ide> },
<ide> checkin: function() {
<ide> var points = document.getElementById("points").value
<del> var url = 'http://178.62.31.30:8080/users/checkin?username=' + name + '&points=' + points;
<add> var url = 'http://api.adam-holt.co.uk/users/checkin?username=' + name + '&points=' + points;
<ide> if(window.XMLHttpRequest) { // mozilla, safari,...
<ide> httpRequest = new XMLHttpRequest();
<ide> } else if(window.ActiveXObject) {
<ide> delete: function(type) {
<ide> if(type == "users") {
<ide> localr.setCred("users");
<del> var url = 'http://178.62.31.30:8080/users/delete?username=' + name;
<add> var url = 'http://api.adam-holt.co.uk/users/delete?username=' + name;
<ide> if(window.XMLHttpRequest) { // mozilla, safari,...
<ide> httpRequest = new XMLHttpRequest();
<ide> } else if(window.ActiveXObject) {
<ide> httpRequest.send();
<ide> } else if(type == "business") {
<ide> localr.setCred("business");
<del> var url = 'http://178.62.31.30:8080/business/delete?businessname=' + name;
<add> var url = 'http://api.adam-holt.co.uk/business/delete?businessname=' + name;
<ide> if(window.XMLHttpRequest) { // mozilla, safari,...
<ide> httpRequest = new XMLHttpRequest();
<ide> } else if(window.ActiveXObject) { |
|
Java | mit | 7fa2ff2d1dde4e62715f882b299667cab167a90e | 0 | amiyajima/voogasalad_VOOGirlsGeneration,mzhu22/TurnBasedStrategy | package utilities.leapMotion;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.ResourceBundle;
import com.leapmotion.leap.Controller;
import com.leapmotion.leap.Frame;
import com.leapmotion.leap.Gesture;
import com.leapmotion.leap.Listener;
public class LeapMotionListener extends Listener{
private ResourceBundle myGestures;
private Robot myRobot;
private ILeapMouse myLeapMouse;
public static final String PACKAGE_FILEPATH = "";
public static final String GESTURE_BUNDLE = "Untitled.properties";
public static final String MOUSE_MOVE_FLAG = "mouse";
public void onConnect (Controller controller){
initializeRobot();
myGestures = ResourceBundle.getBundle(PACKAGE_FILEPATH+GESTURE_BUNDLE);
enableGestures(controller);
}
private void enableGestures(Controller controller){
for(String gestureName : myGestures.keySet()){
if(gestureName.equals(MOUSE_MOVE_FLAG)){
try {
Class c = Class.forName(PACKAGE_FILEPATH+myGestures.getString(gestureName));
myLeapMouse = (ILeapMouse) c.getDeclaredConstructor().newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
}
}
for (Gesture.Type type: Gesture.Type.values()){
if(type.toString().equals(gestureName)){
controller.enableGesture(type);
}
}
}
}
private void initializeRobot () {
try {
myRobot = new Robot();
} catch (AWTException e) {
}
}
public void onFrame (Controller controller) {
Frame frame = controller.frame();
myLeapMouse.moveMouse(frame, myRobot);
for(Gesture gesture: frame.gestures()){
for(String gestureName : myGestures.keySet()){
if(gesture.type().toString().equals(gestureName)){
performAction(gestureName);
}
}
}
}
private void performAction(String gestureName){
// int input = Integer.parseInt(myGestures.getString(gestureName));
int input = gestureName.charAt(0);
try {
myRobot.mousePress(input);
} catch (Exception e) {
myRobot.keyPress(input);
}
}
}
| src/utilities/leapMotion/LeapMotionListener.java | package utilities.leapMotion;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.ResourceBundle;
import com.leapmotion.leap.Controller;
import com.leapmotion.leap.Frame;
import com.leapmotion.leap.Gesture;
import com.leapmotion.leap.Listener;
public class LeapMotionListener extends Listener{
private ResourceBundle myGestures;
private Robot myRobot;
private ILeapMouse myLeapMouse;
public static final String GESTURES_FILEPATH = "";
public static final String MOUSE_MOVE_FLAG = "mouse";
public void onConnect (Controller controller){
initializeRobot();
myGestures = ResourceBundle.getBundle(GESTURES_FILEPATH);
enableGestures(controller);
}
private void enableGestures(Controller controller){
for(String gestureName : myGestures.keySet()){
if(gestureName.equals(MOUSE_MOVE_FLAG)){
try {
Class c = Class.forName("utilities.leapMotion."+myGestures.getString(gestureName));
myLeapMouse = (ILeapMouse) c.getDeclaredConstructor().newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
}
}
for (Gesture.Type type: Gesture.Type.values()){
if(type.toString().equals(gestureName)){
controller.enableGesture(type);
}
}
}
}
private void initializeRobot () {
try {
myRobot = new Robot();
} catch (AWTException e) {
}
}
public void onFrame (Controller controller) {
Frame frame = controller.frame();
myLeapMouse.moveMouse(frame, myRobot);
for(Gesture gesture: frame.gestures()){
for(String gestureName : myGestures.keySet()){
if(gesture.type().toString().equals(gestureName)){
performAction(gestureName);
}
}
}
}
private void performAction(String gestureName){
// int input = Integer.parseInt(myGestures.getString(gestureName));
int input = gestureName.charAt(0);
try {
myRobot.mousePress(input);
} catch (Exception e) {
myRobot.keyPress(input);
}
}
}
| resource address fixed
| src/utilities/leapMotion/LeapMotionListener.java | resource address fixed | <ide><path>rc/utilities/leapMotion/LeapMotionListener.java
<ide> private ResourceBundle myGestures;
<ide> private Robot myRobot;
<ide> private ILeapMouse myLeapMouse;
<del> public static final String GESTURES_FILEPATH = "";
<add> public static final String PACKAGE_FILEPATH = "";
<add> public static final String GESTURE_BUNDLE = "Untitled.properties";
<ide> public static final String MOUSE_MOVE_FLAG = "mouse";
<ide>
<ide>
<ide> public void onConnect (Controller controller){
<ide>
<ide> initializeRobot();
<del> myGestures = ResourceBundle.getBundle(GESTURES_FILEPATH);
<add> myGestures = ResourceBundle.getBundle(PACKAGE_FILEPATH+GESTURE_BUNDLE);
<ide>
<ide> enableGestures(controller);
<ide> }
<ide> for(String gestureName : myGestures.keySet()){
<ide> if(gestureName.equals(MOUSE_MOVE_FLAG)){
<ide> try {
<del> Class c = Class.forName("utilities.leapMotion."+myGestures.getString(gestureName));
<add> Class c = Class.forName(PACKAGE_FILEPATH+myGestures.getString(gestureName));
<ide> myLeapMouse = (ILeapMouse) c.getDeclaredConstructor().newInstance();
<ide> } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
<ide> |
|
Java | apache-2.0 | eafa87146952f0fa0655ec9a6d64f3c7a89e62db | 0 | Jasig/uPortal-start,cousquer/uPortal,stalele/uPortal,jl1955/uPortal5,Jasig/uPortal,jhelmer-unicon/uPortal,jonathanmtran/uPortal,kole9273/uPortal,ASU-Capstone/uPortal,ASU-Capstone/uPortal,MichaelVose2/uPortal,Jasig/uPortal,ASU-Capstone/uPortal,GIP-RECIA/esup-uportal,chasegawa/uPortal,mgillian/uPortal,Jasig/SSP-Platform,pspaude/uPortal,kole9273/uPortal,chasegawa/uPortal,Jasig/SSP-Platform,chasegawa/uPortal,EsupPortail/esup-uportal,jameswennmacher/uPortal,joansmith/uPortal,kole9273/uPortal,Jasig/uPortal,groybal/uPortal,Jasig/SSP-Platform,joansmith/uPortal,kole9273/uPortal,GIP-RECIA/esco-portail,ChristianMurphy/uPortal,mgillian/uPortal,Jasig/SSP-Platform,phillips1021/uPortal,timlevett/uPortal,GIP-RECIA/esco-portail,stalele/uPortal,doodelicious/uPortal,Jasig/uPortal-start,drewwills/uPortal,MichaelVose2/uPortal,pspaude/uPortal,jl1955/uPortal5,cousquer/uPortal,groybal/uPortal,apetro/uPortal,Mines-Albi/esup-uportal,stalele/uPortal,jhelmer-unicon/uPortal,apetro/uPortal,Mines-Albi/esup-uportal,doodelicious/uPortal,ASU-Capstone/uPortal-Forked,stalele/uPortal,joansmith/uPortal,pspaude/uPortal,EdiaEducationTechnology/uPortal,kole9273/uPortal,apetro/uPortal,jonathanmtran/uPortal,vbonamy/esup-uportal,bjagg/uPortal,drewwills/uPortal,vertein/uPortal,Mines-Albi/esup-uportal,andrewstuart/uPortal,ASU-Capstone/uPortal-Forked,EdiaEducationTechnology/uPortal,jameswennmacher/uPortal,ASU-Capstone/uPortal,groybal/uPortal,MichaelVose2/uPortal,Mines-Albi/esup-uportal,jhelmer-unicon/uPortal,GIP-RECIA/esco-portail,EsupPortail/esup-uportal,groybal/uPortal,timlevett/uPortal,groybal/uPortal,Jasig/SSP-Platform,andrewstuart/uPortal,stalele/uPortal,EsupPortail/esup-uportal,jl1955/uPortal5,jameswennmacher/uPortal,jhelmer-unicon/uPortal,doodelicious/uPortal,vertein/uPortal,MichaelVose2/uPortal,doodelicious/uPortal,GIP-RECIA/esup-uportal,drewwills/uPortal,doodelicious/uPortal,joansmith/uPortal,ASU-Capstone/uPortal,EdiaEducationTechnology/uPortal,andrewstuart/uPortal,vertein/uPortal,phillips1021/uPortal,vertein/uPortal,drewwills/uPortal,andrewstuart/uPortal,jl1955/uPortal5,chasegawa/uPortal,phillips1021/uPortal,ASU-Capstone/uPortal-Forked,vbonamy/esup-uportal,ASU-Capstone/uPortal-Forked,timlevett/uPortal,chasegawa/uPortal,jhelmer-unicon/uPortal,phillips1021/uPortal,Mines-Albi/esup-uportal,ChristianMurphy/uPortal,GIP-RECIA/esup-uportal,jonathanmtran/uPortal,EsupPortail/esup-uportal,bjagg/uPortal,pspaude/uPortal,mgillian/uPortal,GIP-RECIA/esup-uportal,EsupPortail/esup-uportal,ChristianMurphy/uPortal,cousquer/uPortal,apetro/uPortal,ASU-Capstone/uPortal-Forked,apetro/uPortal,andrewstuart/uPortal,vbonamy/esup-uportal,jl1955/uPortal5,bjagg/uPortal,jameswennmacher/uPortal,jameswennmacher/uPortal,timlevett/uPortal,EdiaEducationTechnology/uPortal,MichaelVose2/uPortal,phillips1021/uPortal,vbonamy/esup-uportal,GIP-RECIA/esup-uportal,vbonamy/esup-uportal,joansmith/uPortal | package org.jasig.portal.channels;
import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.objectspace.xml.*;
import org.jasig.portal.*;
import org.jasig.portal.layout.*;
import java.net.*;
/**
* This is a user-defined channel for rendering a web page in an IFrame.
* For Browsers without support for Inline Frames the channel just presents
* a link to open in a separate window.
*
* @author Susan Bramhall
* @version $Revision$
*/
public class CInlineFrame implements org.jasig.portal.IChannel
{
protected String m_sUrl = null;
private ChannelConfig chConfig = null;
private static Vector params = null;
public CInlineFrame()
{
params = new Vector();
params.addElement(new ParameterField("URL", "url", "50", "70", "You have chosen to publish a channel that requires you to provide a URL. Please enter the URL for the channel you wish to publish below.") );
params.addElement(new ParameterField("Height", "height", "3", "4", "The channel width will be determined by its layout but you must specify the height in pixels. " +
"Please enter the height below.") );
params.addElement(new ParameterField("Name", "name", "30", "40", "Please enter a decriptive name below.") );
}
public void init (ChannelConfig chConfig) {this.chConfig = chConfig;}
public String getName () {return (String) chConfig.get ("name");}
public boolean isMinimizable () {return true;}
public boolean isDetachable () {return true;}
public boolean isRemovable () {return true;}
public boolean isEditable () {return false;}
public boolean hasHelp () {return false;}
public int getDefaultDetachWidth () {return 0;}
public int getDefaultDetachHeight () {return 0;}
public Vector getParameters()
{
return params;
}
public void render (HttpServletRequest req, HttpServletResponse res, JspWriter out)
{
try
{
String sBrowser = req.getHeader("User-Agent");
String sHeight = (String) chConfig.get ("height");
m_sUrl = (String) chConfig.get ("url");
String sLine = null;
URL url = new URL (m_sUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
BufferedReader theHTML = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
StringBuffer sbHTML = new StringBuffer (1024);
while ((sLine = theHTML.readLine()) != null)
sbHTML.append (sLine);
String sHTML = sbHTML.toString ();
if (sHTML != null)
{
// This test gets IE 4 and 5 and Netscape 6 into the Iframe world
// all others get just a link. This could undoubtedly get refined.
// IE3 also handled Iframes but I'm not sure of the string it returns.
if ((sBrowser.indexOf("MSIE 3")>=0)||
(sBrowser.indexOf(" MSIE 4")>=0) ||
(sBrowser.indexOf("MSIE 5")>=0) ||
(sBrowser.indexOf("Mozilla/5")>=0) )
sHTML = "<IFRAME height=" + sHeight + " width=100% frameborder='no' src='" +
m_sUrl + "'></IFRAME>";
else
sHTML = "<p>This browser does not support inline frames.</p>" +
"<A href="+ m_sUrl +
" target='IFrame_Window'>Click this link to view content</A> in a separate window.";
out.println (sHTML);
}
else
{
out.println ("<p>The page you chose cannot be rendered within a channel. Please choose another. <p><i>Note: Pages containing framesets are not allowed.</i>");
}
}
catch (Exception e)
{
try
{
out.println ("<b>" + m_sUrl + "</b> is currently unreachable.");
out.println ("Please choose another.");
}
catch (Exception ex)
{
Logger.log (Logger.ERROR, e);
}
Logger.log (Logger.ERROR, e);
}
}
public void edit (HttpServletRequest req, HttpServletResponse res, JspWriter out)
{
// This channel is not editable
}
public void help (HttpServletRequest req, HttpServletResponse res, JspWriter out)
{
// This channel has no help
}
} | source/org/jasig/portal/channels/CInlineFrame.java | package org.jasig.portal.channels;
import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.objectspace.xml.*;
import org.jasig.portal.*;
import org.jasig.portal.layout.*;
import java.net.*;
/**
* This is a user-defined channel for rendering a web page in an IFrame.
* For Browsers without support for Inline Frames the channel just presents
* a link to open in a separate window.
*
*/
public class CInlineFrame implements org.jasig.portal.IChannel
{
protected String m_sUrl = null;
private ChannelConfig chConfig = null;
private static Vector params = null;
public CInlineFrame()
{
params = new Vector();
params.addElement(new ParameterField("URL", "url", "50", "70", "You have chosen to publish a channel that requires you to provide a URL. Please enter the URL for the channel you wish to publish below.") );
params.addElement(new ParameterField("Height", "height", "3", "4", "The channel width will be determined by its layout but you must specify the height in pixels. " +
"Please enter the height below.") );
params.addElement(new ParameterField("Name", "name", "30", "40", "Please enter a decriptive name below.") );
}
public void init (ChannelConfig chConfig) {this.chConfig = chConfig;}
public String getName () {return (String) chConfig.get ("name");}
public boolean isMinimizable () {return true;}
public boolean isDetachable () {return true;}
public boolean isRemovable () {return true;}
public boolean isEditable () {return false;}
public boolean hasHelp () {return false;}
public int getDefaultDetachWidth () {return 0;}
public int getDefaultDetachHeight () {return 0;}
public Vector getParameters()
{
return params;
}
public void render (HttpServletRequest req, HttpServletResponse res, JspWriter out)
{
try
{
String sBrowser = req.getHeader("User-Agent");
String sHeight = (String) chConfig.get ("height");
m_sUrl = (String) chConfig.get ("url");
String sLine = null;
URL url = new URL (m_sUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
BufferedReader theHTML = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
StringBuffer sbHTML = new StringBuffer (1024);
while ((sLine = theHTML.readLine()) != null)
sbHTML.append (sLine);
String sHTML = sbHTML.toString ();
if (sHTML != null)
{
// This test gets IE 4 and 5 and Netscape 6 into the Iframe world
// all others get just a link. This could undoubtedly get refined.
// IE3 also handled Iframes but I'm not sure of the string it returns.
if ((sBrowser.indexOf("MSIE 3")>=0)||
(sBrowser.indexOf(" MSIE 4")>=0) ||
(sBrowser.indexOf("MSIE 5")>=0) ||
(sBrowser.indexOf("Mozilla/5")>=0) )
sHTML = "<IFRAME height=" + sHeight + " width=100% frameborder='no' src='" +
m_sUrl + "'></IFRAME>";
else
sHTML = "<p>This browser does not support inline frames.</p>" +
"<A href="+ m_sUrl +
" target='IFrame_Window'>Click this link to view content</A> in a separate window.";
out.println (sHTML);
}
else
{
out.println ("<p>The page you chose cannot be rendered within a channel. Please choose another. <p><i>Note: Pages containing framesets are not allowed.</i>");
}
}
catch (Exception e)
{
try
{
out.println ("<b>" + m_sUrl + "</b> is currently unreachable.");
out.println ("Please choose another.");
}
catch (Exception ex)
{
Logger.log (Logger.ERROR, e);
}
Logger.log (Logger.ERROR, e);
}
}
public void edit (HttpServletRequest req, HttpServletResponse res, JspWriter out)
{
// This channel is not editable
}
public void help (HttpServletRequest req, HttpServletResponse res, JspWriter out)
{
// This channel has no help
}
} | add author and version tags
git-svn-id: 477788cc2a8229a747c5b8073e47c1d0f6ec0604@3373 f5dbab47-78f9-eb45-b975-e544023573eb
| source/org/jasig/portal/channels/CInlineFrame.java | add author and version tags | <ide><path>ource/org/jasig/portal/channels/CInlineFrame.java
<ide> * For Browsers without support for Inline Frames the channel just presents
<ide> * a link to open in a separate window.
<ide> *
<add> * @author Susan Bramhall
<add> * @version $Revision$
<ide> */
<ide> public class CInlineFrame implements org.jasig.portal.IChannel
<ide> { |
|
Java | apache-2.0 | 20b6076b303e59d4163e53249239c45c4fa99587 | 0 | tagbangers/wallride,tagbangers/wallride,tagbangers/wallride | /*
* Copyright 2014 Tagbangers, 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.wallride.web.support;
import org.springframework.data.domain.Page;
import org.thymeleaf.context.IProcessingContext;
import org.wallride.domain.Article;
import org.wallride.domain.Post;
import org.wallride.model.ArticleSearchRequest;
import org.wallride.support.ArticleUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Articles {
private IProcessingContext processingContext;
private ArticleUtils articleUtils;
public Articles(IProcessingContext processingContext, ArticleUtils articleUtils) {
this.processingContext = processingContext;
this.articleUtils = articleUtils;
}
public List<Article> search(Condition condition) {
Page<Article> result = articleUtils.search(condition.buildArticleSearchRequest(), condition.size);
return new ArrayList<>(result.getContent());
}
public Condition condition() {
return new Condition();
}
class Condition {
private int size = 1;
private String keyword;
private Collection<Long> categoryIds;
private Collection<String> categoryCodes;
private Collection<String> tagNames;
private Long authorId;
private Post.Status status = Post.Status.PUBLISHED;
// private LocalDateTime dateFrom;
// private LocalDateTime dateTo;
public Condition size(int size) {
this.size = size;
return this;
}
public Condition keyword(String keyword) {
this.keyword = keyword;
return this;
}
public Condition category(Long... ids) {
List<Long> categoryIds = new ArrayList<>();
for (Long value : ids) {
categoryIds.add(value);
}
this.categoryIds = categoryIds;
return this;
}
public Condition category(String... codes) {
List<String> categoryCodes = new ArrayList<>();
for (String value : codes) {
categoryCodes.add(value);
}
this.categoryCodes = categoryCodes;
return this;
}
public Condition tag(String... names) {
List<String> tagNames = new ArrayList<>();
for (String value : names) {
tagNames.add(value);
}
this.tagNames = tagNames;
return this;
}
public Condition author(Long id) {
this.authorId = id;
return this;
}
private ArticleSearchRequest buildArticleSearchRequest() {
ArticleSearchRequest request = new ArticleSearchRequest(processingContext.getContext().getLocale().getLanguage())
.withStatus(this.status)
.withKeyword(this.keyword)
.withCategoryIds(this.categoryIds)
.withCategoryCodes(this.categoryCodes)
.withTagNames(this.tagNames)
.withAuthorId(this.authorId);
return request;
}
}
} | wallride-core/src/main/java/org/wallride/web/support/Articles.java | /*
* Copyright 2014 Tagbangers, 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.wallride.web.support;
import org.springframework.data.domain.Page;
import org.thymeleaf.context.IProcessingContext;
import org.wallride.domain.Article;
import org.wallride.model.ArticleSearchRequest;
import org.wallride.support.ArticleUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Articles {
private IProcessingContext processingContext;
private ArticleUtils articleUtils;
public Articles(IProcessingContext processingContext, ArticleUtils articleUtils) {
this.processingContext = processingContext;
this.articleUtils = articleUtils;
}
public List<Article> search(Condition condition) {
Page<Article> result = articleUtils.search(condition.buildArticleSearchRequest(), condition.size);
return new ArrayList<>(result.getContent());
}
public Condition condition() {
return new Condition();
}
class Condition {
private int size = 1;
private String keyword;
private Collection<Long> categoryIds;
private Collection<String> categoryCodes;
private Collection<String> tagNames;
private Long authorId;
// private Post.Status status;
// private LocalDateTime dateFrom;
// private LocalDateTime dateTo;
public Condition size(int size) {
this.size = size;
return this;
}
public Condition keyword(String keyword) {
this.keyword = keyword;
return this;
}
public Condition category(Long... ids) {
List<Long> categoryIds = new ArrayList<>();
for (Long value : ids) {
categoryIds.add(value);
}
this.categoryIds = categoryIds;
return this;
}
public Condition category(String... codes) {
List<String> categoryCodes = new ArrayList<>();
for (String value : codes) {
categoryCodes.add(value);
}
this.categoryCodes = categoryCodes;
return this;
}
public Condition tag(String... names) {
List<String> tagNames = new ArrayList<>();
for (String value : names) {
tagNames.add(value);
}
this.tagNames = tagNames;
return this;
}
public Condition author(Long id) {
this.authorId = id;
return this;
}
private ArticleSearchRequest buildArticleSearchRequest() {
ArticleSearchRequest request = new ArticleSearchRequest(processingContext.getContext().getLocale().getLanguage())
.withKeyword(this.keyword)
.withCategoryIds(this.categoryIds)
.withCategoryCodes(this.categoryCodes)
.withTagNames(this.tagNames)
.withAuthorId(this.authorId);
return request;
}
}
} | bug fix to Articles.
Modified to search request status set "Post.Status.PUBLISHED".
| wallride-core/src/main/java/org/wallride/web/support/Articles.java | bug fix to Articles. | <ide><path>allride-core/src/main/java/org/wallride/web/support/Articles.java
<ide> import org.springframework.data.domain.Page;
<ide> import org.thymeleaf.context.IProcessingContext;
<ide> import org.wallride.domain.Article;
<add>import org.wallride.domain.Post;
<ide> import org.wallride.model.ArticleSearchRequest;
<ide> import org.wallride.support.ArticleUtils;
<ide>
<ide> private Collection<String> categoryCodes;
<ide> private Collection<String> tagNames;
<ide> private Long authorId;
<del>// private Post.Status status;
<add> private Post.Status status = Post.Status.PUBLISHED;
<ide> // private LocalDateTime dateFrom;
<ide> // private LocalDateTime dateTo;
<ide>
<ide>
<ide> private ArticleSearchRequest buildArticleSearchRequest() {
<ide> ArticleSearchRequest request = new ArticleSearchRequest(processingContext.getContext().getLocale().getLanguage())
<add> .withStatus(this.status)
<ide> .withKeyword(this.keyword)
<ide> .withCategoryIds(this.categoryIds)
<ide> .withCategoryCodes(this.categoryCodes) |
|
Java | bsd-3-clause | f6bf6049f6f808bf748cf1cce4e2d8084090cc5e | 0 | knime-mpicbg/HCS-Tools,knime-mpicbg/HCS-Tools,knime-mpicbg/HCS-Tools,knime-mpicbg/HCS-Tools | package de.mpicbg.tds.knime.hcstools.visualization.heatmapviewer;
import de.mpicbg.tds.core.TdsUtils;
import de.mpicbg.tds.core.model.Plate;
import de.mpicbg.tds.core.model.Well;
import de.mpicbg.tds.knime.hcstools.visualization.PlateComparators;
import de.mpicbg.tds.knime.hcstools.visualization.heatmapviewer.color.GlobalMinMaxStrategy;
import de.mpicbg.tds.knime.hcstools.visualization.heatmapviewer.color.LinearGradientTools;
import de.mpicbg.tds.knime.hcstools.visualization.heatmapviewer.color.ReadoutRescaleStrategy;
import de.mpicbg.tds.knime.hcstools.visualization.heatmapviewer.color.ScreenColorScheme;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.math.stat.Frequency;
import java.awt.*;
import java.lang.reflect.Field;
import java.util.*;
import java.util.List;
/**
* Document me!
*
* @author Holger Brandl
*/
public class HeatMapModel2 { //TODO remove the 2 once the transition from the old to the new HeatMapModel is completed
// Reference populations
//TODO: This will be set by the Configuration dialog of the node at some point. This here is just a testing hack.
public static HashMap<String, String[]> referencePopulations = new HashMap<String, String[]>();
static {
referencePopulations.put("transfection",new String[]{"Mock", "Tox3", "Neg5"});
}
// Coloring attributes
ReadoutRescaleStrategy readoutRescaleStrategy = new GlobalMinMaxStrategy();
ScreenColorScheme colorScheme = ScreenColorScheme.getInstance();
LinearGradientPaint colorGradient = LinearGradientTools.getStandardGradient("GBR");
// contains all plates
private List<Plate> screen;
private String currentReadout;
HashMap<Plate, Boolean> plateFiltered = new HashMap<Plate, Boolean>();
// Well selection
Collection<Well> selection = new ArrayList<Well>();
private boolean markSelection = true;
// View flags
private boolean doShowConcentration = false;
private boolean doShowLayout = false;
// Trellis settings
private boolean automaticTrellisConfiguration = true;
private int numberOfTrellisRows;
private int numberOfTrellisColumns;
private boolean fixPlateProportions = true;
// Overlay attributes
private boolean hideMostFrequentOverlay = false;
private Map<String, String> maxFreqOverlay;
private String overlay = "";
//Plate Filtering
private String plateFilterString = "";
private PlateComparators.PlateAttribute plateFilterAttribute = PlateComparators.PlateAttribute.BARCODE;
// public static final String OVERLAY_COLOR_CACHE = "overlay_col_cache";
// Plate sorting;
private List<PlateComparators.PlateAttribute> sortAttributeSelection;
List<HeatMapModelChangeListener> changeListeners = new ArrayList<HeatMapModelChangeListener>();
public void setScreen(List<Plate> screen) {
this.screen = screen;
// just to test sorting mechanism
Collections.sort(screen, PlateComparators.getDateComparator());
for(Plate p : screen) {
plateFiltered.put(p, true);
}
// sort all wells according to readout
readoutRescaleStrategy.configure(screen);
updateMaxOverlayFreqs(screen);
}
public void filterPlates(String pfs) {
setPlateFilterString(pfs);
// no filter selected or no filter string defined.
if(plateFilterString.isEmpty() || StringUtils.isBlank(pfs) ) {
for(Plate p : plateFiltered.keySet()) {
plateFiltered.put(p,true);
}
// fireModelChanged();
return;
}
for(Plate p : plateFiltered.keySet()) {
boolean keep = false;
switch (plateFilterAttribute) {
case BARCODE:
if(p.getBarcode().contains(plateFilterString)) { keep = true; } break;
case SCREENED_AT:
if(p.getScreenedAt().equals(new Date(plateFilterString))) { keep = true; } break;
case BATCH_NAME:
if(p.getBatchName().contains(plateFilterString)) { keep = true; } break;
case LIBRARY_CODE:
if(p.getLibraryCode().contains(plateFilterString)) { keep = true; } break;
case LIBRARY_PLATE_NUMBER:
if(p.getLibraryPlateNumber().equals(Integer.parseInt(plateFilterString))) { keep = true; } break;
case ASSAY:
if(p.getAssay().contains(plateFilterString)) { keep = true; } break;
case REPLICATE:
if(p.getReplicate().contains(plateFilterString)) { keep = true; } break;
}
plateFiltered.put(p,keep);
}
// fireModelChanged();
}
public void filterPlates(String pfs, PlateComparators.PlateAttribute pfa) {
setPlateFilterAttribute(pfa);
filterPlates(pfs);
}
public boolean isFiltered(Plate p){
return plateFiltered.get(p);
}
// public void setSortAttributeSelection(HashMap<Integer,PlateComparators.PlateAttribute> sortAttributeSelection) {
// this.sortAttributeSelection = sortAttributeSelection;
// }
//
// public HashMap<Integer,PlateComparators.PlateAttribute> getSortAttributeSelection() {
// return sortAttributeSelection;
// }
public void setSortAttributeSelectionByTiles(String[] titles) {
sortAttributeSelection = new ArrayList<PlateComparators.PlateAttribute>();
for (String title : titles) {
sortAttributeSelection.add(PlateComparators.getPlateAttributeByTitle(title));
}
// fireModelChanged();
}
public String[] getSortAttributesSelectionTitles() {
if (sortAttributeSelection == null) {
return null;
} else {
return PlateComparators.getPlateAttributeTitles(sortAttributeSelection);
}
}
public void sortPlates(PlateComparators.PlateAttribute attribute) {
sortPlates(attribute, false);
}
public void sortPlates(PlateComparators.PlateAttribute attribute, boolean descending) {
Collections.sort(screen, PlateComparators.getComparator(attribute));
if (!descending) { Collections.reverse(screen); }
}
private void updateMaxOverlayFreqs(List<Plate> screen) {
Collection<Well> wellCollection = new ArrayList<Well>(TdsUtils.flattenWells(screen));
List<String> overlayNames = TdsUtils.flattenAnnotationTypes(screen);
Map<String, Frequency> annotStats = new HashMap<String, Frequency>();
for (String overlayName : overlayNames) {
annotStats.put(overlayName, new Frequency());
}
for (Well well : wellCollection) {
for (String overlayName : overlayNames) {
String annotation = well.getAnnotation(overlayName);
if (annotation != null)
annotStats.get(overlayName).addValue(annotation);
}
}
// rebuild the map
maxFreqOverlay = new HashMap<String, String>();
for (String overlayName : overlayNames) {
final Frequency frequency = annotStats.get(overlayName);
List<String> overlays = new ArrayList<String>();
Iterator<Comparable<?>> valIt = frequency.valuesIterator();
while (valIt.hasNext()) {
overlays.add((String) valIt.next());
}
if (!overlays.isEmpty()) {
Object maxOverlay = Collections.max(overlays, new Comparator<String>() {
public int compare(String o, String o1) {
return frequency.getCount(o) - frequency.getCount(o1) < 0 ? -1 : 1;
}
});
maxFreqOverlay.put(overlayName, (String) maxOverlay);
}
}
}
public ReadoutRescaleStrategy getRescaleStrategy() {
return readoutRescaleStrategy;
}
public void setReadoutRescaleStrategy(ReadoutRescaleStrategy readoutRescaleStrategy) {
readoutRescaleStrategy.configure(screen);
this.readoutRescaleStrategy = readoutRescaleStrategy;
// fireModelChanged();
}
// public void setColorScale(ColorScale colorScale) {
// this.colorScale = colorScale;
// fireModelChanged();
// }
//
//
// public ColorScale getColorScale() {
// return colorScale;
// }
public List<Plate> getScreen() {
return screen;
}
public String getSelectedReadOut() {
return currentReadout;
}
public void setCurrentReadout(String currentReadout) {
this.currentReadout = currentReadout;
// fireModelChanged();
}
public ScreenColorScheme getColorScheme() {
return colorScheme;
}
public LinearGradientPaint getColorGradient() {
return colorGradient;
}
public void setColorGradient(LinearGradientPaint gradient) {
colorGradient = gradient;
// fireModelChanged();
}
public Color getOverlayColor(Well well) {
String overlayType = getOverlay();
if (overlayType == null || overlayType.isEmpty()) {
return null;
}
String overlay = well.getAnnotation(overlayType);
if (overlay == null || (doHideMostFreqOverlay() && isMostFrequent(overlayType, overlay))) {
return null;
}
return getColorScheme().getColorFromCache(overlayType, overlay);
}
private boolean isMostFrequent(String overlayType, String overlay) {
return maxFreqOverlay.containsKey(overlayType) && maxFreqOverlay.get(overlayType).equals(overlay);
}
public Color getReadoutColor(Well well) {
if (!well.isReadoutSuccess()) {
return colorScheme.errorReadOut;
}
String selectedReadOut = getSelectedReadOut();
assert selectedReadOut != null;
Double wellReadout = well.getReadout(selectedReadOut);
return getReadOutColor(selectedReadOut, wellReadout);
}
public Color getReadOutColor(String selectedReadOut, Double wellReadout) {
// also show the fallback color in cases when a single readout is not available
if (wellReadout == null) {
return colorScheme.emptyReadOut;
}
// check if we can normalize the value (this maybe impossible if there's just a single well
Double displayNormReadOut = readoutRescaleStrategy.normalize(wellReadout, selectedReadOut);
if (displayNormReadOut == null) {
return colorScheme.errorReadOut;
}
return LinearGradientTools.getColorAt(colorGradient, displayNormReadOut.floatValue());
// return colorScale.mapReadout2Color(displayNormReadOut);
}
public boolean doShowLayout() {
return doShowLayout;
}
public void setDoShowLayout(boolean showLayout) {
this.doShowLayout = showLayout;
// fireModelChanged();
}
public boolean doShowConcentration() {
return doShowConcentration;
}
/**
* This is a convenience method to update the GUI. It should not be called from this class but rather from other
* classes using the HeatMapModel as a information carrier.
*/
void fireModelChanged() {
for (HeatMapModelChangeListener changeListener : changeListeners) {
changeListener.modelChanged();
}
}
public void setDoShowConcentration(boolean doShowConcentration) {
this.doShowConcentration = doShowConcentration;
// fireModelChanged();
}
public Collection<Well> getWellSelection() {
return selection;
}
public void setWellSelection(Collection<Well> selection) {
this.selection = selection;
}
public void clearWellSelection() {
this.selection.clear();
}
public boolean isPlateSelected(Plate plate) {
for (Well well : plate.getWells()) {
if ( isWellSelected(well) ) { return true; }
}
return false;
}
public boolean isWellSelected(Well well) {
if ( selection.isEmpty() )
return false;
for (Well w : selection) {
if (well.getPlateColumn().equals(w.getPlateColumn()) &&
well.getPlateRow().equals(w.getPlateRow()) &&
well.getPlate().getBarcode().equals(w.getPlate().getBarcode()))
return true;
}
// return selection.contains(well);
return false;
}
public boolean doHideMostFreqOverlay() {
return hideMostFrequentOverlay;
}
public void setHideMostFreqOverlay(boolean useBckndForLibraryWells) {
this.hideMostFrequentOverlay = useBckndForLibraryWells;
// fireModelChanged();
}
public void setMarkSelection(boolean markSelection) {
this.markSelection = markSelection;
// fireModelChanged();
}
public boolean doMarkSelection() {
return markSelection;
}
public String getOverlay() {
return overlay;
}
public void setOverlay(String overlay) {
this.overlay = overlay;
// fireModelChanged();
}
public String getOverlayValue(Well well) {
return well.getAnnotation(getOverlay());
}
public void setPlateFilterString(String fs) {
this.plateFilterString = fs;
}
public void setPlateFilterAttribute(PlateComparators.PlateAttribute fa) {
this.plateFilterAttribute = fa;
}
public void addChangeListener(HeatMapModelChangeListener changeListener) {
if (!changeListeners.contains(changeListener)) {
changeListeners.add(changeListener);
}
}
public void setColorScheme(ScreenColorScheme colorScheme) {
this.colorScheme = colorScheme;
}
// TODO: This should be solved via the configuration dialog of the node eventually
public Collection<PlateComparators.PlateAttribute> getPlateAttributes() {
Collection<PlateComparators.PlateAttribute> availableAttributes = new HashSet<PlateComparators.PlateAttribute>();
PlateComparators.PlateAttribute[] attributes = PlateComparators.PlateAttribute.values();
for (Plate plate : screen) {
for (PlateComparators.PlateAttribute attribute : attributes) {
try {
Field field = plate.getClass().getDeclaredField(attribute.getName());
field.setAccessible(true);
Object object = field.get(plate);
if (!(object == null)) {
availableAttributes.add(attribute);
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return availableAttributes;
}
public void revertScreen() {
Collections.reverse(screen);
}
public boolean getAutomaticTrellisConfiguration() {
return automaticTrellisConfiguration;
}
public void setAutomaticTrellisConfiguration(boolean flag) {
this.automaticTrellisConfiguration = flag;
}
public Integer getNumberOfTrellisRows() {
return numberOfTrellisRows;
}
public void setNumberOfTrellisRows(int numberOfTrellisRows) {
this.numberOfTrellisRows = numberOfTrellisRows;
}
public Integer getNumberOfTrellisColumns() {
return numberOfTrellisColumns;
}
public void setNumberOfTrellisColumns(int numberOfTrellisColumns) {
this.numberOfTrellisColumns = numberOfTrellisColumns;
}
public void updateTrellisConfiguration(int rows, int columns, boolean flag) {
this.setAutomaticTrellisConfiguration(flag);
updateTrellisConfiguration(rows, columns);
}
public void updateTrellisConfiguration(int rows, int columns) {
this.setNumberOfTrellisRows(rows);
this.setNumberOfTrellisColumns(columns);
}
public int getCurrentNumberOfPlates() {
int number = 0;
for (boolean state: plateFiltered.values()) {
if (state) {
number++;
}
}
return number;
}
public boolean isFixedPlateProportion() {
return fixPlateProportions;
}
public void setPlateProportionMode(boolean plateDimensionMode) {
this.fixPlateProportions = plateDimensionMode;
}
public String[] getReferencePopulations() {
String attribute = (String) referencePopulations.keySet().toArray()[0];
return referencePopulations.get(attribute);
}
}
| src/de/mpicbg/tds/knime/hcstools/visualization/heatmapviewer/HeatMapModel2.java | package de.mpicbg.tds.knime.hcstools.visualization.heatmapviewer;
import de.mpicbg.tds.core.TdsUtils;
import de.mpicbg.tds.core.model.Plate;
import de.mpicbg.tds.core.model.Well;
import de.mpicbg.tds.knime.hcstools.visualization.PlateComparators;
import de.mpicbg.tds.knime.hcstools.visualization.heatmapviewer.color.GlobalMinMaxStrategy;
import de.mpicbg.tds.knime.hcstools.visualization.heatmapviewer.color.LinearGradientTools;
import de.mpicbg.tds.knime.hcstools.visualization.heatmapviewer.color.ReadoutRescaleStrategy;
import de.mpicbg.tds.knime.hcstools.visualization.heatmapviewer.color.ScreenColorScheme;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.math.stat.Frequency;
import java.awt.*;
import java.lang.reflect.Field;
import java.util.*;
import java.util.List;
/**
* Document me!
*
* @author Holger Brandl
*/
public class HeatMapModel2 { //TODO remove the 2 once the transition from the old to the new HeatMapModel is completed
// Reference populations
//TODO: This will be set by the Configuration dialog of the node at some point. This here is just a testing hack.
public static HashMap<String, String[]> referencePopulations = new HashMap<String, String[]>();
static {
referencePopulations.put("transfection",new String[]{"Mock", "Tox3", "Neg5"});
}
// Coloring attributes
ReadoutRescaleStrategy readoutRescaleStrategy = new GlobalMinMaxStrategy();
ScreenColorScheme colorScheme = ScreenColorScheme.getInstance();
LinearGradientPaint colorGradient = LinearGradientTools.getStandardGradient("GBR");
// contains all plates
private List<Plate> screen;
private String currentReadout;
HashMap<Plate, Boolean> plateFiltered = new HashMap<Plate, Boolean>();
// Well selection
Collection<Well> selection = new ArrayList<Well>();
private boolean markSelection = true;
// View flags
private boolean doShowConcentration = false;
private boolean doShowLayout = false;
// Trellis settings
private boolean automaticTrellisConfiguration = true;
private int numberOfTrellisRows;
private int numberOfTrellisColumns;
private boolean fixPlateProportions = true;
// Overlay attributes
private boolean hideMostFrequentOverlay = false;
private Map<String, String> maxFreqOverlay;
private String overlay = "";
//Plate Filtering
private String plateFilterString = "";
private PlateComparators.PlateAttribute plateFilterAttribute = PlateComparators.PlateAttribute.BARCODE;
// public static final String OVERLAY_COLOR_CACHE = "overlay_col_cache";
// Plate sorting;
private List<PlateComparators.PlateAttribute> sortAttributeSelection;
List<HeatMapModelChangeListener> changeListeners = new ArrayList<HeatMapModelChangeListener>();
public void setScreen(List<Plate> screen) {
this.screen = screen;
// just to test sorting mechanism
Collections.sort(screen, PlateComparators.getDateComparator());
for(Plate p : screen) {
plateFiltered.put(p, true);
}
// sort all wells according to readout
readoutRescaleStrategy.configure(screen);
updateMaxOverlayFreqs(screen);
}
public void filterPlates(String pfs) {
setPlateFilterString(pfs);
// no filter selected or no filter string defined.
if(plateFilterString.isEmpty() || StringUtils.isBlank(pfs) ) {
for(Plate p : plateFiltered.keySet()) {
plateFiltered.put(p,true);
}
// fireModelChanged();
return;
}
for(Plate p : plateFiltered.keySet()) {
boolean keep = false;
switch (plateFilterAttribute) {
case BARCODE:
if(p.getBarcode().contains(plateFilterString)) { keep = true; } break;
case SCREENED_AT:
if(p.getScreenedAt().equals(new Date(plateFilterString))) { keep = true; } break;
case BATCH_NAME:
if(p.getBatchName().contains(plateFilterString)) { keep = true; } break;
case LIBRARY_CODE:
if(p.getLibraryCode().contains(plateFilterString)) { keep = true; } break;
case LIBRARY_PLATE_NUMBER:
if(p.getLibraryPlateNumber().equals(Integer.parseInt(plateFilterString))) { keep = true; } break;
case ASSAY:
if(p.getAssay().contains(plateFilterString)) { keep = true; } break;
case REPLICATE:
if(p.getReplicate().contains(plateFilterString)) { keep = true; } break;
}
plateFiltered.put(p,keep);
}
// fireModelChanged();
}
public void filterPlates(String pfs, PlateComparators.PlateAttribute pfa) {
setPlateFilterAttribute(pfa);
filterPlates(pfs);
}
public boolean isFiltered(Plate p){
return plateFiltered.get(p);
}
// public void setSortAttributeSelection(HashMap<Integer,PlateComparators.PlateAttribute> sortAttributeSelection) {
// this.sortAttributeSelection = sortAttributeSelection;
// }
//
// public HashMap<Integer,PlateComparators.PlateAttribute> getSortAttributeSelection() {
// return sortAttributeSelection;
// }
public void setSortAttributeSelectionByTiles(String[] titles) {
sortAttributeSelection = new ArrayList<PlateComparators.PlateAttribute>();
for (String title : titles) {
sortAttributeSelection.add(PlateComparators.getPlateAttributeByTitle(title));
}
// fireModelChanged();
}
public String[] getSortAttributesSelectionTitles() {
if (sortAttributeSelection == null) {
return null;
} else {
return PlateComparators.getPlateAttributeTitles(sortAttributeSelection);
}
}
public void sortPlates(PlateComparators.PlateAttribute attribute) {
sortPlates(attribute, false);
}
public void sortPlates(PlateComparators.PlateAttribute attribute, boolean descending) {
Collections.sort(screen, PlateComparators.getComparator(attribute));
if (!descending) { Collections.reverse(screen); }
}
private void updateMaxOverlayFreqs(List<Plate> screen) {
Collection<Well> wellCollection = new ArrayList<Well>(TdsUtils.flattenWells(screen));
List<String> overlayNames = TdsUtils.flattenAnnotationTypes(screen);
Map<String, Frequency> annotStats = new HashMap<String, Frequency>();
for (String overlayName : overlayNames) {
annotStats.put(overlayName, new Frequency());
}
for (Well well : wellCollection) {
for (String overlayName : overlayNames) {
String annotation = well.getAnnotation(overlayName);
if (annotation != null)
annotStats.get(overlayName).addValue(annotation);
}
}
// rebuild the map
maxFreqOverlay = new HashMap<String, String>();
for (String overlayName : overlayNames) {
final Frequency frequency = annotStats.get(overlayName);
List<String> overlays = new ArrayList<String>();
Iterator<Comparable<?>> valIt = frequency.valuesIterator();
while (valIt.hasNext()) {
overlays.add((String) valIt.next());
}
if (!overlays.isEmpty()) {
Object maxOverlay = Collections.max(overlays, new Comparator<String>() {
public int compare(String o, String o1) {
return frequency.getCount(o) - frequency.getCount(o1) < 0 ? -1 : 1;
}
});
maxFreqOverlay.put(overlayName, (String) maxOverlay);
}
}
}
public ReadoutRescaleStrategy getRescaleStrategy() {
return readoutRescaleStrategy;
}
public void setReadoutRescaleStrategy(ReadoutRescaleStrategy readoutRescaleStrategy) {
readoutRescaleStrategy.configure(screen);
this.readoutRescaleStrategy = readoutRescaleStrategy;
// fireModelChanged();
}
// public void setColorScale(ColorScale colorScale) {
// this.colorScale = colorScale;
// fireModelChanged();
// }
//
//
// public ColorScale getColorScale() {
// return colorScale;
// }
public List<Plate> getScreen() {
return screen;
}
public String getSelectedReadOut() {
return currentReadout;
}
public void setCurrentReadout(String currentReadout) {
this.currentReadout = currentReadout;
// fireModelChanged();
}
public ScreenColorScheme getColorScheme() {
return colorScheme;
}
public LinearGradientPaint getColorGradient() {
return colorGradient;
}
public void setColorGradient(LinearGradientPaint gradient) {
colorGradient = gradient;
// fireModelChanged();
}
public Color getOverlayColor(Well well) {
String overlayType = getOverlay();
if (overlayType == null || overlayType.isEmpty()) {
return null;
}
String overlay = well.getAnnotation(overlayType);
if (overlay == null || (doHideMostFreqOverlay() && isMostFrequent(overlayType, overlay))) {
return null;
}
return getColorScheme().getColorFromCache(overlayType, overlay);
}
private boolean isMostFrequent(String overlayType, String overlay) {
return maxFreqOverlay.containsKey(overlayType) && maxFreqOverlay.get(overlayType).equals(overlay);
}
public Color getReadoutColor(Well well) {
if (!well.isReadoutSuccess()) {
return colorScheme.errorReadOut;
}
String selectedReadOut = getSelectedReadOut();
assert selectedReadOut != null;
Double wellReadout = well.getReadout(selectedReadOut);
return getReadOutColor(selectedReadOut, wellReadout);
}
public Color getReadOutColor(String selectedReadOut, Double wellReadout) {
// also show the fallback color in cases when a single readout is not available
if (wellReadout == null) {
return colorScheme.emptyReadOut;
}
// check if we can normalize the value (this maybe impossible if there's just a single well
Double displayNormReadOut = readoutRescaleStrategy.normalize(wellReadout, selectedReadOut);
if (displayNormReadOut == null) {
return colorScheme.errorReadOut;
}
return LinearGradientTools.getColorAt(colorGradient, displayNormReadOut.floatValue());
// return colorScale.mapReadout2Color(displayNormReadOut);
}
public boolean doShowLayout() {
return doShowLayout;
}
public void setDoShowLayout(boolean showLayout) {
this.doShowLayout = showLayout;
// fireModelChanged();
}
public boolean doShowConcentration() {
return doShowConcentration;
}
/**
* This is a convenience method to update the GUI. It should not be called from this class but rather from other
* classes using the HeatMapModel as a information carrier.
*/
void fireModelChanged() {
for (HeatMapModelChangeListener changeListener : changeListeners) {
changeListener.modelChanged();
}
}
public void setDoShowConcentration(boolean doShowConcentration) {
this.doShowConcentration = doShowConcentration;
// fireModelChanged();
}
public Collection<Well> getWellSelection() {
return selection;
}
public void setWellSelection(Collection<Well> selection) {
this.selection = selection;
}
public void clearWellSelection() {
this.selection.clear();
}
public boolean isPlateSelected(Plate plate) {
for (Well well : plate.getWells()) {
if ( isWellSelected(well) ) { return true; }
}
return false;
}
public boolean isWellSelected(Well well) {
for (Well w : selection) {
if (well.getPlateColumn().equals(w.getPlateColumn()) &&
well.getPlateRow().equals(w.getPlateRow()) &&
well.getPlate().getBarcode().equals(w.getPlate().getBarcode()))
return true;
}
// return selection.contains(well);
return false;
}
public boolean doHideMostFreqOverlay() {
return hideMostFrequentOverlay;
}
public void setHideMostFreqOverlay(boolean useBckndForLibraryWells) {
this.hideMostFrequentOverlay = useBckndForLibraryWells;
// fireModelChanged();
}
public void setMarkSelection(boolean markSelection) {
this.markSelection = markSelection;
// fireModelChanged();
}
public boolean doMarkSelection() {
return markSelection;
}
public String getOverlay() {
return overlay;
}
public void setOverlay(String overlay) {
this.overlay = overlay;
// fireModelChanged();
}
public String getOverlayValue(Well well) {
return well.getAnnotation(getOverlay());
}
public void setPlateFilterString(String fs) {
this.plateFilterString = fs;
}
public void setPlateFilterAttribute(PlateComparators.PlateAttribute fa) {
this.plateFilterAttribute = fa;
}
public void addChangeListener(HeatMapModelChangeListener changeListener) {
if (!changeListeners.contains(changeListener)) {
changeListeners.add(changeListener);
}
}
public void setColorScheme(ScreenColorScheme colorScheme) {
this.colorScheme = colorScheme;
}
// TODO: This should be solved via the configuration dialog of the node eventually
public Collection<PlateComparators.PlateAttribute> getPlateAttributes() {
Collection<PlateComparators.PlateAttribute> availableAttributes = new HashSet<PlateComparators.PlateAttribute>();
PlateComparators.PlateAttribute[] attributes = PlateComparators.PlateAttribute.values();
for (Plate plate : screen) {
for (PlateComparators.PlateAttribute attribute : attributes) {
try {
Field field = plate.getClass().getDeclaredField(attribute.getName());
field.setAccessible(true);
Object object = field.get(plate);
if (!(object == null)) {
availableAttributes.add(attribute);
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return availableAttributes;
}
public void revertScreen() {
Collections.reverse(screen);
}
public boolean getAutomaticTrellisConfiguration() {
return automaticTrellisConfiguration;
}
public void setAutomaticTrellisConfiguration(boolean flag) {
this.automaticTrellisConfiguration = flag;
}
public Integer getNumberOfTrellisRows() {
return numberOfTrellisRows;
}
public void setNumberOfTrellisRows(int numberOfTrellisRows) {
this.numberOfTrellisRows = numberOfTrellisRows;
}
public Integer getNumberOfTrellisColumns() {
return numberOfTrellisColumns;
}
public void setNumberOfTrellisColumns(int numberOfTrellisColumns) {
this.numberOfTrellisColumns = numberOfTrellisColumns;
}
public void updateTrellisConfiguration(int rows, int columns, boolean flag) {
this.setAutomaticTrellisConfiguration(flag);
updateTrellisConfiguration(rows, columns);
}
public void updateTrellisConfiguration(int rows, int columns) {
this.setNumberOfTrellisRows(rows);
this.setNumberOfTrellisColumns(columns);
}
public int getCurrentNumberOfPlates() {
int number = 0;
for (boolean state: plateFiltered.values()) {
if (state) {
number++;
}
}
return number;
}
public boolean isFixedPlateProportion() {
return fixPlateProportions;
}
public void setPlateProportionMode(boolean plateDimensionMode) {
this.fixPlateProportions = plateDimensionMode;
}
public String[] getReferencePopulations() {
String attribute = (String) referencePopulations.keySet().toArray()[0];
return referencePopulations.get(attribute);
}
}
| fixed small bug in the well selection
if nothing was selected it was possible to have a nullpointerexception before.
| src/de/mpicbg/tds/knime/hcstools/visualization/heatmapviewer/HeatMapModel2.java | fixed small bug in the well selection | <ide><path>rc/de/mpicbg/tds/knime/hcstools/visualization/heatmapviewer/HeatMapModel2.java
<ide> }
<ide>
<ide> public boolean isWellSelected(Well well) {
<add> if ( selection.isEmpty() )
<add> return false;
<ide>
<ide> for (Well w : selection) {
<ide> if (well.getPlateColumn().equals(w.getPlateColumn()) && |
|
Java | agpl-3.0 | 2fd791f45052184dca5b189f434264e8dfdb9294 | 0 | VietOpenCPS/opencps,VietOpenCPS/opencps,VietOpenCPS/opencps | /**
* OpenCPS is the open source Core Public Services software
* Copyright (C) 2016-present OpenCPS community
*
* 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
* 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 org.opencps.backend.engine;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.opencps.accountmgt.model.Business;
import org.opencps.accountmgt.model.Citizen;
import org.opencps.backend.message.SendToBackOfficeMsg;
import org.opencps.backend.message.SendToEngineMsg;
import org.opencps.backend.util.BackendUtils;
import org.opencps.backend.util.DossierNoGenerator;
import org.opencps.backend.util.KeypayUrlGenerator;
import org.opencps.backend.util.PaymentRequestGenerator;
import org.opencps.dossiermgt.bean.AccountBean;
import org.opencps.dossiermgt.model.Dossier;
import org.opencps.dossiermgt.model.DossierLog;
import org.opencps.dossiermgt.model.ServiceConfig;
import org.opencps.dossiermgt.service.DossierLogLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceConfigLocalServiceUtil;
import org.opencps.dossiermgt.util.ActorBean;
import org.opencps.notificationmgt.message.SendNotificationMessage;
import org.opencps.notificationmgt.utils.NotificationEventKeys;
import org.opencps.paymentmgt.model.PaymentFile;
import org.opencps.paymentmgt.model.impl.PaymentFileImpl;
import org.opencps.paymentmgt.service.PaymentFileLocalServiceUtil;
import org.opencps.processmgt.model.ProcessOrder;
import org.opencps.processmgt.model.ProcessStep;
import org.opencps.processmgt.model.ProcessWorkflow;
import org.opencps.processmgt.model.impl.ProcessStepImpl;
import org.opencps.processmgt.service.ProcessOrderLocalServiceUtil;
import org.opencps.processmgt.service.ProcessStepLocalServiceUtil;
import org.opencps.processmgt.service.ProcessWorkflowLocalServiceUtil;
import org.opencps.processmgt.util.ProcessMgtUtil;
import org.opencps.processmgt.util.ProcessUtils;
import org.opencps.usermgt.model.Employee;
import org.opencps.util.AccountUtil;
import org.opencps.util.PortletConstants;
import org.opencps.util.WebKeys;
import com.liferay.portal.kernel.language.LanguageUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBusUtil;
import com.liferay.portal.kernel.messaging.MessageListener;
import com.liferay.portal.kernel.messaging.MessageListenerException;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.User;
/**
* @author khoavd
*/
public class BackOfficeProcessEngine implements MessageListener {
@Override
public void receive(Message message)
throws MessageListenerException {
_doRecevie(message);
}
private void _doRecevie(Message message) {
SendToEngineMsg toEngineMsg =
(SendToEngineMsg) message.get("msgToEngine");
List<SendNotificationMessage> lsNotification = new ArrayList<SendNotificationMessage>();
List<String> employEvents = new ArrayList<String>();
List<String> citizenEvents = new ArrayList<String>();
String actionName = StringPool.BLANK;
String stepName = StringPool.BLANK;
ProcessOrder processOrder = null;
long curStepId = 0;
long processStepId = 0;
long ownerUserId = 0;
long ownerOrganizationId = 0;
Dossier dossier = BackendUtils.getDossier(toEngineMsg.getDossierId());
long serviceInfoId = 0;
long dossierTemplateId = 0;
String govAgencyCode = StringPool.BLANK;
String govAgencyName = StringPool.BLANK;
long govAgencyOrganizationId = 0;
long serviceProcessId = 0;
long actionUserId = toEngineMsg.getActionUserId();
ActorBean actorBean = new ActorBean(toEngineMsg.getActorType(), actionUserId);
if (Validator.isNotNull(dossier)) {
serviceInfoId = dossier.getServiceInfoId();
dossierTemplateId = dossier.getDossierTemplateId();
govAgencyCode = dossier.getGovAgencyCode();
govAgencyName = dossier.getGovAgencyName();
govAgencyOrganizationId = dossier.getGovAgencyOrganizationId();
try {
ServiceConfig serviceConfig =
ServiceConfigLocalServiceUtil.getServiceConfigByG_S_G(
toEngineMsg.getGroupId(), serviceInfoId, govAgencyCode);
serviceProcessId = serviceConfig.getServiceProcessId();
}
catch (Exception e) {
_log.error(e);
}
}
SendToBackOfficeMsg toBackOffice = new SendToBackOfficeMsg();
toBackOffice.setSubmitDateTime(toEngineMsg.getActionDatetime());
toBackOffice.setActor(actorBean.getActor());
toBackOffice.setActorId(actorBean.getActorId());
toBackOffice.setActorName(actorBean.getActorName());
long processWorkflowId = toEngineMsg.getProcessWorkflowId();
long processOrderId = toEngineMsg.getProcessOrderId();
try {
if (Validator.isNull(processOrderId)) {
// Check processOrder
processOrder =
BackendUtils.getProcessOrder(
toEngineMsg.getDossierId(),
toEngineMsg.getFileGroupId());
if (Validator.isNull(processOrder)) {
// Init process order
processOrder =
ProcessOrderLocalServiceUtil.initProcessOrder(
toEngineMsg.getUserId(),
toEngineMsg.getCompanyId(),
toEngineMsg.getGroupId(), serviceInfoId,
dossierTemplateId, govAgencyCode, govAgencyName,
govAgencyOrganizationId, serviceProcessId,
toEngineMsg.getDossierId(),
toEngineMsg.getFileGroupId(),
toEngineMsg.getProcessWorkflowId(),
toEngineMsg.getActionDatetime(), StringPool.BLANK,
StringPool.BLANK, StringPool.BLANK, 0, 0, 0,
PortletConstants.DOSSIER_STATUS_SYSTEM);
// Add DossierLog for create ProcessOrder
ActorBean actorBeanSys = new ActorBean(0, 0);
DossierLog dossierLog =
DossierLogLocalServiceUtil.addDossierLog(
toEngineMsg.getUserId(),
toEngineMsg.getGroupId(),
toEngineMsg.getCompanyId(),
toEngineMsg.getDossierId(),
toEngineMsg.getFileGroupId(),
PortletConstants.DOSSIER_STATUS_SYSTEM,
PortletConstants.DOSSIER_ACTION_CREATE_PROCESS_ORDER,
PortletConstants.DOSSIER_ACTION_CREATE_PROCESS_ORDER,
new Date(), 0, 0, actorBeanSys.getActor(),
actorBeanSys.getActorId(), actorBeanSys.getActorName(),
BackOfficeProcessEngine.class.getName() +
".createProcessOrder()");
toBackOffice.setDossierLogOId(dossierLog.getOId());
}
processOrderId = processOrder.getProcessOrderId();
}
else {
// Find process order by processOrderId
processOrder =
ProcessOrderLocalServiceUtil.fetchProcessOrder(processOrderId);
processOrderId = processOrder.getProcessOrderId();
curStepId = processOrder.getProcessStepId();
}
long assignToUserId = toEngineMsg.getAssignToUserId();
ProcessWorkflow processWorkflow = null;
// Find workflow
if (Validator.isNull(processWorkflowId)) {
processWorkflow =
ProcessWorkflowLocalServiceUtil.getProcessWorkflowByEvent(
serviceProcessId, toEngineMsg.getEvent(), curStepId);
}
else {
processWorkflow =
ProcessWorkflowLocalServiceUtil.fetchProcessWorkflow(processWorkflowId);
}
if (Validator.isNull(assignToUserId)) {
assignToUserId =
ProcessMgtUtil.getAssignUser(
processWorkflow.getProcessWorkflowId(), processOrderId,
processWorkflow.getPostProcessStepId());
}
// Do Workflow
if (Validator.isNotNull(processWorkflow)) {
actionName = processWorkflow.getActionName();
processStepId = processWorkflow.getPostProcessStepId();
long changeStepId = processWorkflow.getPostProcessStepId();
ProcessStep changeStep =
ProcessStepLocalServiceUtil.getProcessStep(changeStepId);
ProcessStep currStep = new ProcessStepImpl();
if (curStepId != 0) {
stepName =
ProcessStepLocalServiceUtil.fetchProcessStep(curStepId).getStepName();
}
// Add noti's events
if(changeStep.getDossierStatus().contains(PortletConstants.DOSSIER_STATUS_RECEIVING)) {
// dossier receiving
employEvents.add(NotificationEventKeys.OFFICIALS.EVENT1);
citizenEvents.add(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT1);
}
if (currStep.getDossierStatus().contains(PortletConstants.DOSSIER_STATUS_WAITING)) {
// Dossier add new documents
employEvents.add(NotificationEventKeys.OFFICIALS.EVENT2);
}
if ((Validator.isNotNull(currStep.getDossierStatus()) ||
!currStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_WAITING) || !currStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_RECEIVING)) &&
changeStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_PROCESSING)) {
employEvents.add(NotificationEventKeys.OFFICIALS.EVENT6);
}
if (currStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_RECEIVING) &&
changeStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_PROCESSING)) {
citizenEvents.add(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT2);
}
if (currStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_RECEIVING) &&
!changeStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_PROCESSING)) {
citizenEvents.add(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT3);
}
if (changeStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_WAITING)) {
citizenEvents.add(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT4);
}
if (changeStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_DONE)) {
citizenEvents.add(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT6);
}
String changeStatus = StringPool.BLANK;
boolean isResubmit = false;
if (changeStepId != 0) {
//Set Receive Date
if (currStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_RECEIVING) &&
changeStep.getDossierStatus().contains("processing")) {
toBackOffice.setReceiveDatetime(new Date());
}
if (Validator.isNotNull(changeStep)) {
changeStatus = changeStep.getDossierStatus();
if (Validator.equals(
changeStep.getDossierStatus(),
PortletConstants.DOSSIER_STATUS_WAITING)) {
isResubmit = true;
}
}
}
else {
changeStatus = PortletConstants.DOSSIER_STATUS_DONE;
}
int syncStatus = 0;
if (!changeStatus.contentEquals(toEngineMsg.getDossierStatus())) {
syncStatus = 2;
}
// Update process order to SYSTEM
ProcessOrderLocalServiceUtil.updateProcessOrderStatus(
processOrderId, PortletConstants.DOSSIER_STATUS_SYSTEM);
// Update process order
ProcessOrderLocalServiceUtil.updateProcessOrder(
processOrderId, processStepId,
processWorkflow.getProcessWorkflowId(),
toEngineMsg.getActionUserId(),
toEngineMsg.getActionDatetime(),
toEngineMsg.getActionNote(), assignToUserId, stepName,
actionName, 0, 0, PortletConstants.DOSSIER_STATUS_SYSTEM);
toBackOffice.setStepName(stepName);
toBackOffice.setProcessWorkflowId(processWorkflow.getProcessWorkflowId());
toBackOffice.setProcessOrderId(processOrderId);
toBackOffice.setDossierId(toEngineMsg.getDossierId());
toBackOffice.setFileGroupId(toEngineMsg.getFileGroupId());
toBackOffice.setDossierStatus(changeStatus);
toBackOffice.setSyncStatus(syncStatus);
if (changeStatus.equals(PortletConstants.DOSSIER_STATUS_WAITING)) {
toBackOffice.setRequestCommand(WebKeys.DOSSIER_LOG_RESUBMIT_REQUEST);
}
toBackOffice.setActionInfo(processWorkflow.getActionName());
toBackOffice.setSendResult(0);
if (changeStatus.equals(PortletConstants.DOSSIER_STATUS_PAYING)) {
toBackOffice.setRequestPayment(1);
}
else {
toBackOffice.setRequestPayment(0);
}
toBackOffice.setUpdateDatetime(new Date());
if (Validator.isNull(toEngineMsg.getReceptionNo())) {
String pattern = processWorkflow.getReceptionNoPattern();
if (Validator.isNotNull(pattern) &&
StringUtil.trim(pattern).length() != 0) {
toBackOffice.setReceptionNo(DossierNoGenerator.genaratorNoReception(
pattern, toEngineMsg.getDossierId()));
// Add log create dossier
}
else {
toBackOffice.setReceptionNo(dossier.getReceptionNo());
}
}
else {
toBackOffice.setReceptionNo(toEngineMsg.getReceptionNo());
}
if (processWorkflow.getIsFinishStep()) {
toBackOffice.setFinishDatetime(new Date());
}
toBackOffice.setCompanyId(toEngineMsg.getCompanyId());
toBackOffice.setGovAgencyCode(govAgencyCode);
toBackOffice.setUserActorAction(toEngineMsg.getActionUserId());
if (dossier.getOwnerOrganizationId() != 0) {
ownerUserId = 0;
ownerOrganizationId = dossier.getOwnerOrganizationId();
}
else {
ownerUserId = dossier.getUserId();
}
boolean isPayment = false;
PaymentFile paymentFile = new PaymentFileImpl();
// Update Paying
if (processWorkflow.getRequestPayment()) {
int totalPayment =
PaymentRequestGenerator.getTotalPayment(
processWorkflow.getPaymentFee(),
dossier.getDossierId());
List<String> paymentMethods =
PaymentRequestGenerator.getPaymentMethod(processWorkflow.getPaymentFee());
String paymentOptions = StringUtil.merge(paymentMethods);
List<String> paymentMessages =
PaymentRequestGenerator.getMessagePayment(processWorkflow.getPaymentFee());
String paymentName =
(paymentMessages.size() != 0)
? paymentMessages.get(0) : StringPool.BLANK;
paymentFile =
PaymentFileLocalServiceUtil.addPaymentFile(
toEngineMsg.getDossierId(),
toEngineMsg.getFileGroupId(), ownerUserId,
ownerOrganizationId, govAgencyOrganizationId,
paymentName, new Date(), (double) totalPayment,
paymentName, StringPool.BLANK, paymentOptions);
if (paymentMethods.contains(PaymentRequestGenerator.PAY_METHOD_KEYPAY)) {
paymentFile =
KeypayUrlGenerator.generatorKeypayURL(
processWorkflow.getGroupId(),
govAgencyOrganizationId,
paymentFile.getPaymentFileId(),
processWorkflow.getPaymentFee(),
toEngineMsg.getDossierId());
}
citizenEvents.add(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT5);
isPayment = true;
toBackOffice.setRequestCommand(WebKeys.DOSSIER_LOG_PAYMENT_REQUEST);
toBackOffice.setPaymentFile(paymentFile);
Locale vnLocale = new Locale("vi", "VN");
NumberFormat vnFormat =
NumberFormat.getCurrencyInstance(vnLocale);
// setPayment message in pattern in message Info
StringBuffer sb = new StringBuffer();
sb.append(paymentMessages.get(0));
sb.append(StringPool.OPEN_PARENTHESIS);
sb.append(vnFormat.format(totalPayment));
sb.append(StringPool.CLOSE_PARENTHESIS);
sb.append(StringPool.SEMICOLON);
sb.append(toEngineMsg.getActionNote());
toBackOffice.setMessageInfo(sb.toString());
}
else {
toBackOffice.setRequestPayment(0);
toBackOffice.setMessageInfo(toEngineMsg.getActionNote());
}
toBackOffice.setPayment(isPayment);
toBackOffice.setResubmit(isResubmit);
toBackOffice.setEstimateDatetime(toEngineMsg.getEstimateDatetime());
toBackOffice.setReceiveDatetime(toEngineMsg.getReceiveDate());
lsNotification =
getListNoties(
citizenEvents, employEvents, dossier.getUserId(), dossier.getUserId(),
assignToUserId, processWorkflow, dossier.getDossierId(), paymentFile.getPaymentFileId() ,
processOrderId);
_log.info("%%%%%%%%%%%%% LIST :::::: FUCKKKKKKKING" + lsNotification.size());
toBackOffice.setListNotifications(lsNotification);
Message sendToBackOffice = new Message();
sendToBackOffice.put("toBackOffice", toBackOffice);
MessageBusUtil.sendMessage(
"opencps/backoffice/out/destination", sendToBackOffice);
}
else {
// Send message to backoffice/out/destination
toBackOffice.setProcessOrderId(processOrderId);
toBackOffice.setDossierId(toEngineMsg.getDossierId());
toBackOffice.setFileGroupId(toEngineMsg.getFileGroupId());
toBackOffice.setDossierStatus(PortletConstants.DOSSIER_STATUS_ERROR);
toBackOffice.setCompanyId(toEngineMsg.getCompanyId());
toBackOffice.setGovAgencyCode(govAgencyCode);
toBackOffice.setReceptionNo(toEngineMsg.getReceptionNo());
toBackOffice.setUserActorAction(toEngineMsg.getActionUserId());
toBackOffice.setStepName(stepName);
citizenEvents.add(NotificationEventKeys.ADMINTRATOR.EVENT1);
lsNotification =
getListNoties(
citizenEvents, employEvents, dossier.getUserId(), dossier.getUserId(),
assignToUserId, processWorkflow, dossier.getDossierId(), 0 ,
processOrderId);
toBackOffice.setListNotifications(lsNotification);
Message sendToBackOffice = new Message();
sendToBackOffice.put("toBackOffice", toBackOffice);
MessageBusUtil.sendMessage(
"opencps/backoffice/out/destination", sendToBackOffice);
}
}
catch (Exception e) {
_log.error(e);
}
}
private List<SendNotificationMessage> getListNoties(
List<String> citizenEvents, List<String> employEvents,
long citizenUserId, long groupId, long assignToUserId,
ProcessWorkflow processWorkflow, long dossierId, long paymentFileId,
long processOrderId) {
List<SendNotificationMessage> ls =
new ArrayList<SendNotificationMessage>();
AccountBean accountBean =
AccountUtil.getAccountBean(citizenUserId, groupId, null);
Citizen citizen = null;
Business bussines = null;
if (accountBean.isCitizen()) {
citizen = (Citizen) accountBean.getAccountInstance();
}
if (accountBean.isBusiness()) {
bussines = (Business) accountBean.getAccountInstance();
}
for (String event : citizenEvents) {
_log.info("INFORRRRRRRRRRRRRRR + " + event);
SendNotificationMessage notiMsg = new SendNotificationMessage();
notiMsg.setDossierId(dossierId);
notiMsg.setNotificationEventName(event);
notiMsg.setProcessOrderId(processOrderId);
notiMsg.setType("SMS, INBOX, EMAIL");
SendNotificationMessage.InfoList info =
new SendNotificationMessage.InfoList();
info.setGroupId(groupId);
List<SendNotificationMessage.InfoList> infoList =
new ArrayList<SendNotificationMessage.InfoList>();
infoList.add(info);
notiMsg.setInfoList(infoList);
if (Validator.isNotNull(citizen)) {
info.setUserId(citizen.getUserId());
info.setUserMail(citizen.getEmail());
info.setUserPhone(citizen.getTelNo());
}
if (Validator.isNotNull(bussines)) {
info.setUserId(bussines.getUserId());
info.setUserMail(bussines.getEmail());
info.setUserPhone(bussines.getTelNo());
}
if (event.contains(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT5)) {
info.setGroup(NotificationEventKeys.GROUP3);
Locale vnLocale = new Locale("vi", "VN");
notiMsg.setNotificationContent(LanguageUtil.get(
vnLocale, "phieu-yeu-cau-thanh-toan"));
}
else {
info.setGroup(NotificationEventKeys.GROUP2);
notiMsg.setNotificationContent(processWorkflow.getActionName());
}
ls.add(notiMsg);
}
for (String employEvent : employEvents) {
SendNotificationMessage notiMsg = new SendNotificationMessage();
notiMsg.setDossierId(dossierId);
notiMsg.setNotificationEventName(employEvent);
notiMsg.setProcessOrderId(processOrderId);
notiMsg.setType("SMS, INBOX, EMAIL");
if (assignToUserId != 0) {
SendNotificationMessage.InfoList infoEmploy =
new SendNotificationMessage.InfoList();
List<SendNotificationMessage.InfoList> infoListEmploy =
new ArrayList<SendNotificationMessage.InfoList>();
AccountBean accountEmploy =
AccountUtil.getAccountBean(assignToUserId, groupId, null);
Employee employee = null;
if (accountEmploy.isEmployee()) {
employee = (Employee) accountEmploy.getAccountInstance();
infoEmploy.setUserId(employee.getUserId());
infoEmploy.setUserMail(employee.getEmail());
infoEmploy.setUserPhone(employee.getTelNo());
}
infoListEmploy.add(infoEmploy);
if (employEvent.contains(NotificationEventKeys.OFFICIALS.EVENT3)) {
infoEmploy.setGroup(NotificationEventKeys.GROUP4);
Locale vnLocale = new Locale("vi", "VN");
notiMsg.setNotificationContent(LanguageUtil.get(
vnLocale, "phieu-yeu-cau-thanh-toan-moi-thuc-hien"));
}
else {
infoEmploy.setGroup(NotificationEventKeys.GROUP1);
notiMsg.setNotificationContent(processWorkflow.getActionName());
}
ls.add(notiMsg);
} else {
List<SendNotificationMessage.InfoList> infoListEmploy =
new ArrayList<SendNotificationMessage.InfoList>();
List<Employee> employees = getListEmploy(processWorkflow);
for (Employee employee : employees) {
SendNotificationMessage.InfoList infoEmploy =
new SendNotificationMessage.InfoList();
infoEmploy.setUserId(employee.getUserId());
infoEmploy.setUserMail(employee.getEmail());
infoEmploy.setUserPhone(employee.getTelNo());
infoEmploy.setGroupId(groupId);
if (employEvent.contains(NotificationEventKeys.OFFICIALS.EVENT3)) {
infoEmploy.setGroup(NotificationEventKeys.GROUP4);
}
else {
infoEmploy.setGroup(NotificationEventKeys.GROUP1);
}
infoListEmploy.add(infoEmploy);
}
if (employEvent.contains(NotificationEventKeys.OFFICIALS.EVENT3)) {
Locale vnLocale = new Locale("vi", "VN");
notiMsg.setNotificationContent(LanguageUtil.get(
vnLocale, "phieu-yeu-cau-thanh-toan-moi-thuc-hien"));
}
else {
notiMsg.setNotificationContent(processWorkflow.getActionName());
}
ls.add(notiMsg);
}
}
return ls;
}
/**
* @param processWorkflow
* @param assignToUserId
* @return
*/
private List<Employee> getListEmploy(
ProcessWorkflow processWorkflow) {
List<Employee> ls = new ArrayList<>();
try {
List<User> users = ProcessUtils.getAssignUsers(processWorkflow.getPostProcessStepId(), 3);
for (User user : users) {
AccountBean accountEmploy =
AccountUtil.getAccountBean(user.getUserId(), user.getGroupId(), null);
Employee employee = (Employee) accountEmploy.getAccountInstance();
ls.add(employee);
}
}
catch (Exception e) {
}
return ls;
}
private Log _log = LogFactoryUtil.getLog(BackOfficeProcessEngine.class);
}
| portlets/opencps-portlet/docroot/WEB-INF/src/org/opencps/backend/engine/BackOfficeProcessEngine.java | /**
* OpenCPS is the open source Core Public Services software
* Copyright (C) 2016-present OpenCPS community
*
* 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
* 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 org.opencps.backend.engine;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.opencps.accountmgt.model.Business;
import org.opencps.accountmgt.model.Citizen;
import org.opencps.backend.message.SendToBackOfficeMsg;
import org.opencps.backend.message.SendToEngineMsg;
import org.opencps.backend.util.BackendUtils;
import org.opencps.backend.util.DossierNoGenerator;
import org.opencps.backend.util.KeypayUrlGenerator;
import org.opencps.backend.util.PaymentRequestGenerator;
import org.opencps.dossiermgt.bean.AccountBean;
import org.opencps.dossiermgt.model.Dossier;
import org.opencps.dossiermgt.model.DossierLog;
import org.opencps.dossiermgt.model.ServiceConfig;
import org.opencps.dossiermgt.service.DossierLogLocalServiceUtil;
import org.opencps.dossiermgt.service.ServiceConfigLocalServiceUtil;
import org.opencps.dossiermgt.util.ActorBean;
import org.opencps.notificationmgt.message.SendNotificationMessage;
import org.opencps.notificationmgt.utils.NotificationEventKeys;
import org.opencps.paymentmgt.model.PaymentFile;
import org.opencps.paymentmgt.model.impl.PaymentFileImpl;
import org.opencps.paymentmgt.service.PaymentFileLocalServiceUtil;
import org.opencps.processmgt.model.ProcessOrder;
import org.opencps.processmgt.model.ProcessStep;
import org.opencps.processmgt.model.ProcessWorkflow;
import org.opencps.processmgt.model.impl.ProcessStepImpl;
import org.opencps.processmgt.service.ProcessOrderLocalServiceUtil;
import org.opencps.processmgt.service.ProcessStepLocalServiceUtil;
import org.opencps.processmgt.service.ProcessWorkflowLocalServiceUtil;
import org.opencps.processmgt.util.ProcessMgtUtil;
import org.opencps.util.AccountUtil;
import org.opencps.util.PortletConstants;
import org.opencps.util.WebKeys;
import com.liferay.portal.kernel.language.LanguageUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.Message;
import com.liferay.portal.kernel.messaging.MessageBusUtil;
import com.liferay.portal.kernel.messaging.MessageListener;
import com.liferay.portal.kernel.messaging.MessageListenerException;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
/**
* @author khoavd
*/
public class BackOfficeProcessEngine implements MessageListener {
@Override
public void receive(Message message)
throws MessageListenerException {
_doRecevie(message);
}
private void _doRecevie(Message message) {
SendToEngineMsg toEngineMsg =
(SendToEngineMsg) message.get("msgToEngine");
List<SendNotificationMessage> lsNotification = new ArrayList<SendNotificationMessage>();
List<String> employEvents = new ArrayList<String>();
List<String> citizenEvents = new ArrayList<String>();
String actionName = StringPool.BLANK;
String stepName = StringPool.BLANK;
ProcessOrder processOrder = null;
long curStepId = 0;
long processStepId = 0;
long ownerUserId = 0;
long ownerOrganizationId = 0;
Dossier dossier = BackendUtils.getDossier(toEngineMsg.getDossierId());
long serviceInfoId = 0;
long dossierTemplateId = 0;
String govAgencyCode = StringPool.BLANK;
String govAgencyName = StringPool.BLANK;
long govAgencyOrganizationId = 0;
long serviceProcessId = 0;
long actionUserId = toEngineMsg.getActionUserId();
ActorBean actorBean = new ActorBean(toEngineMsg.getActorType(), actionUserId);
if (Validator.isNotNull(dossier)) {
serviceInfoId = dossier.getServiceInfoId();
dossierTemplateId = dossier.getDossierTemplateId();
govAgencyCode = dossier.getGovAgencyCode();
govAgencyName = dossier.getGovAgencyName();
govAgencyOrganizationId = dossier.getGovAgencyOrganizationId();
try {
ServiceConfig serviceConfig =
ServiceConfigLocalServiceUtil.getServiceConfigByG_S_G(
toEngineMsg.getGroupId(), serviceInfoId, govAgencyCode);
serviceProcessId = serviceConfig.getServiceProcessId();
}
catch (Exception e) {
_log.error(e);
}
}
SendToBackOfficeMsg toBackOffice = new SendToBackOfficeMsg();
toBackOffice.setSubmitDateTime(toEngineMsg.getActionDatetime());
toBackOffice.setActor(actorBean.getActor());
toBackOffice.setActorId(actorBean.getActorId());
toBackOffice.setActorName(actorBean.getActorName());
long processWorkflowId = toEngineMsg.getProcessWorkflowId();
long processOrderId = toEngineMsg.getProcessOrderId();
try {
if (Validator.isNull(processOrderId)) {
// Check processOrder
processOrder =
BackendUtils.getProcessOrder(
toEngineMsg.getDossierId(),
toEngineMsg.getFileGroupId());
if (Validator.isNull(processOrder)) {
// Init process order
processOrder =
ProcessOrderLocalServiceUtil.initProcessOrder(
toEngineMsg.getUserId(),
toEngineMsg.getCompanyId(),
toEngineMsg.getGroupId(), serviceInfoId,
dossierTemplateId, govAgencyCode, govAgencyName,
govAgencyOrganizationId, serviceProcessId,
toEngineMsg.getDossierId(),
toEngineMsg.getFileGroupId(),
toEngineMsg.getProcessWorkflowId(),
toEngineMsg.getActionDatetime(), StringPool.BLANK,
StringPool.BLANK, StringPool.BLANK, 0, 0, 0,
PortletConstants.DOSSIER_STATUS_SYSTEM);
// Add DossierLog for create ProcessOrder
ActorBean actorBeanSys = new ActorBean(0, 0);
DossierLog dossierLog =
DossierLogLocalServiceUtil.addDossierLog(
toEngineMsg.getUserId(),
toEngineMsg.getGroupId(),
toEngineMsg.getCompanyId(),
toEngineMsg.getDossierId(),
toEngineMsg.getFileGroupId(),
PortletConstants.DOSSIER_STATUS_SYSTEM,
PortletConstants.DOSSIER_ACTION_CREATE_PROCESS_ORDER,
PortletConstants.DOSSIER_ACTION_CREATE_PROCESS_ORDER,
new Date(), 0, 0, actorBeanSys.getActor(),
actorBeanSys.getActorId(), actorBeanSys.getActorName(),
BackOfficeProcessEngine.class.getName() +
".createProcessOrder()");
toBackOffice.setDossierLogOId(dossierLog.getOId());
}
processOrderId = processOrder.getProcessOrderId();
}
else {
// Find process order by processOrderId
processOrder =
ProcessOrderLocalServiceUtil.fetchProcessOrder(processOrderId);
processOrderId = processOrder.getProcessOrderId();
curStepId = processOrder.getProcessStepId();
}
long assignToUserId = toEngineMsg.getAssignToUserId();
ProcessWorkflow processWorkflow = null;
// Find workflow
if (Validator.isNull(processWorkflowId)) {
processWorkflow =
ProcessWorkflowLocalServiceUtil.getProcessWorkflowByEvent(
serviceProcessId, toEngineMsg.getEvent(), curStepId);
}
else {
processWorkflow =
ProcessWorkflowLocalServiceUtil.fetchProcessWorkflow(processWorkflowId);
}
if (Validator.isNull(assignToUserId)) {
assignToUserId =
ProcessMgtUtil.getAssignUser(
processWorkflow.getProcessWorkflowId(), processOrderId,
processWorkflow.getPostProcessStepId());
}
// Do Workflow
if (Validator.isNotNull(processWorkflow)) {
actionName = processWorkflow.getActionName();
processStepId = processWorkflow.getPostProcessStepId();
long changeStepId = processWorkflow.getPostProcessStepId();
ProcessStep changeStep =
ProcessStepLocalServiceUtil.getProcessStep(changeStepId);
ProcessStep currStep = new ProcessStepImpl();
if (curStepId != 0) {
stepName =
ProcessStepLocalServiceUtil.fetchProcessStep(curStepId).getStepName();
}
// Add noti's events
if(changeStep.getDossierStatus().contains(PortletConstants.DOSSIER_STATUS_RECEIVING)) {
// dossier receiving
employEvents.add(NotificationEventKeys.OFFICIALS.EVENT1);
citizenEvents.add(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT1);
}
if (currStep.getDossierStatus().contains(PortletConstants.DOSSIER_STATUS_WAITING)) {
// Dossier add new documents
employEvents.add(NotificationEventKeys.OFFICIALS.EVENT2);
}
if ((Validator.isNotNull(currStep.getDossierStatus()) ||
!currStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_WAITING) || !currStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_RECEIVING)) &&
changeStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_PROCESSING)) {
employEvents.add(NotificationEventKeys.OFFICIALS.EVENT6);
}
if (currStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_RECEIVING) &&
changeStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_PROCESSING)) {
citizenEvents.add(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT2);
}
if (currStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_RECEIVING) &&
!changeStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_PROCESSING)) {
citizenEvents.add(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT3);
}
if (changeStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_WAITING)) {
citizenEvents.add(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT4);
}
if (changeStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_DONE)) {
citizenEvents.add(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT6);
}
String changeStatus = StringPool.BLANK;
boolean isResubmit = false;
if (changeStepId != 0) {
//Set Receive Date
if (currStep.getDossierStatus().contains(
PortletConstants.DOSSIER_STATUS_RECEIVING) &&
changeStep.getDossierStatus().contains("processing")) {
toBackOffice.setReceiveDatetime(new Date());
}
if (Validator.isNotNull(changeStep)) {
changeStatus = changeStep.getDossierStatus();
if (Validator.equals(
changeStep.getDossierStatus(),
PortletConstants.DOSSIER_STATUS_WAITING)) {
isResubmit = true;
}
}
}
else {
changeStatus = PortletConstants.DOSSIER_STATUS_DONE;
}
int syncStatus = 0;
if (!changeStatus.contentEquals(toEngineMsg.getDossierStatus())) {
syncStatus = 2;
}
// Update process order to SYSTEM
ProcessOrderLocalServiceUtil.updateProcessOrderStatus(
processOrderId, PortletConstants.DOSSIER_STATUS_SYSTEM);
// Update process order
ProcessOrderLocalServiceUtil.updateProcessOrder(
processOrderId, processStepId,
processWorkflow.getProcessWorkflowId(),
toEngineMsg.getActionUserId(),
toEngineMsg.getActionDatetime(),
toEngineMsg.getActionNote(), assignToUserId, stepName,
actionName, 0, 0, PortletConstants.DOSSIER_STATUS_SYSTEM);
toBackOffice.setStepName(stepName);
toBackOffice.setProcessWorkflowId(processWorkflow.getProcessWorkflowId());
toBackOffice.setProcessOrderId(processOrderId);
toBackOffice.setDossierId(toEngineMsg.getDossierId());
toBackOffice.setFileGroupId(toEngineMsg.getFileGroupId());
toBackOffice.setDossierStatus(changeStatus);
toBackOffice.setSyncStatus(syncStatus);
if (changeStatus.equals(PortletConstants.DOSSIER_STATUS_WAITING)) {
toBackOffice.setRequestCommand(WebKeys.DOSSIER_LOG_RESUBMIT_REQUEST);
}
toBackOffice.setActionInfo(processWorkflow.getActionName());
toBackOffice.setSendResult(0);
if (changeStatus.equals(PortletConstants.DOSSIER_STATUS_PAYING)) {
toBackOffice.setRequestPayment(1);
}
else {
toBackOffice.setRequestPayment(0);
}
toBackOffice.setUpdateDatetime(new Date());
if (Validator.isNull(toEngineMsg.getReceptionNo())) {
String pattern = processWorkflow.getReceptionNoPattern();
if (Validator.isNotNull(pattern) &&
StringUtil.trim(pattern).length() != 0) {
toBackOffice.setReceptionNo(DossierNoGenerator.genaratorNoReception(
pattern, toEngineMsg.getDossierId()));
// Add log create dossier
}
else {
toBackOffice.setReceptionNo(dossier.getReceptionNo());
}
}
else {
toBackOffice.setReceptionNo(toEngineMsg.getReceptionNo());
}
if (processWorkflow.getIsFinishStep()) {
toBackOffice.setFinishDatetime(new Date());
}
toBackOffice.setCompanyId(toEngineMsg.getCompanyId());
toBackOffice.setGovAgencyCode(govAgencyCode);
toBackOffice.setUserActorAction(toEngineMsg.getActionUserId());
if (dossier.getOwnerOrganizationId() != 0) {
ownerUserId = 0;
ownerOrganizationId = dossier.getOwnerOrganizationId();
}
else {
ownerUserId = dossier.getUserId();
}
boolean isPayment = false;
PaymentFile paymentFile = new PaymentFileImpl();
// Update Paying
if (processWorkflow.getRequestPayment()) {
int totalPayment =
PaymentRequestGenerator.getTotalPayment(
processWorkflow.getPaymentFee(),
dossier.getDossierId());
List<String> paymentMethods =
PaymentRequestGenerator.getPaymentMethod(processWorkflow.getPaymentFee());
String paymentOptions = StringUtil.merge(paymentMethods);
List<String> paymentMessages =
PaymentRequestGenerator.getMessagePayment(processWorkflow.getPaymentFee());
String paymentName =
(paymentMessages.size() != 0)
? paymentMessages.get(0) : StringPool.BLANK;
paymentFile =
PaymentFileLocalServiceUtil.addPaymentFile(
toEngineMsg.getDossierId(),
toEngineMsg.getFileGroupId(), ownerUserId,
ownerOrganizationId, govAgencyOrganizationId,
paymentName, new Date(), (double) totalPayment,
paymentName, StringPool.BLANK, paymentOptions);
if (paymentMethods.contains(PaymentRequestGenerator.PAY_METHOD_KEYPAY)) {
paymentFile =
KeypayUrlGenerator.generatorKeypayURL(
processWorkflow.getGroupId(),
govAgencyOrganizationId,
paymentFile.getPaymentFileId(),
processWorkflow.getPaymentFee(),
toEngineMsg.getDossierId());
}
citizenEvents.add(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT5);
isPayment = true;
toBackOffice.setRequestCommand(WebKeys.DOSSIER_LOG_PAYMENT_REQUEST);
toBackOffice.setPaymentFile(paymentFile);
Locale vnLocale = new Locale("vi", "VN");
NumberFormat vnFormat =
NumberFormat.getCurrencyInstance(vnLocale);
// setPayment message in pattern in message Info
StringBuffer sb = new StringBuffer();
sb.append(paymentMessages.get(0));
sb.append(StringPool.OPEN_PARENTHESIS);
sb.append(vnFormat.format(totalPayment));
sb.append(StringPool.CLOSE_PARENTHESIS);
sb.append(StringPool.SEMICOLON);
sb.append(toEngineMsg.getActionNote());
toBackOffice.setMessageInfo(sb.toString());
}
else {
toBackOffice.setRequestPayment(0);
toBackOffice.setMessageInfo(toEngineMsg.getActionNote());
}
toBackOffice.setPayment(isPayment);
toBackOffice.setResubmit(isResubmit);
toBackOffice.setEstimateDatetime(toEngineMsg.getEstimateDatetime());
toBackOffice.setReceiveDatetime(toEngineMsg.getReceiveDate());
lsNotification =
getListNoties(
citizenEvents, employEvents, dossier.getUserId(), dossier.getUserId(),
assignToUserId, processWorkflow, dossier.getDossierId(), paymentFile.getPaymentFileId() ,
processOrderId);
_log.info("%%%%%%%%%%%%% LIST ::::::" + lsNotification.size());
toBackOffice.setListNotifications(lsNotification);
Message sendToBackOffice = new Message();
sendToBackOffice.put("toBackOffice", toBackOffice);
MessageBusUtil.sendMessage(
"opencps/backoffice/out/destination", sendToBackOffice);
}
else {
// Send message to backoffice/out/destination
toBackOffice.setProcessOrderId(processOrderId);
toBackOffice.setDossierId(toEngineMsg.getDossierId());
toBackOffice.setFileGroupId(toEngineMsg.getFileGroupId());
toBackOffice.setDossierStatus(PortletConstants.DOSSIER_STATUS_ERROR);
toBackOffice.setCompanyId(toEngineMsg.getCompanyId());
toBackOffice.setGovAgencyCode(govAgencyCode);
toBackOffice.setReceptionNo(toEngineMsg.getReceptionNo());
toBackOffice.setUserActorAction(toEngineMsg.getActionUserId());
toBackOffice.setStepName(stepName);
citizenEvents.add(NotificationEventKeys.ADMINTRATOR.EVENT1);
lsNotification =
getListNoties(
citizenEvents, employEvents, dossier.getUserId(), dossier.getUserId(),
assignToUserId, processWorkflow, dossier.getDossierId(), 0 ,
processOrderId);
toBackOffice.setListNotifications(lsNotification);
Message sendToBackOffice = new Message();
sendToBackOffice.put("toBackOffice", toBackOffice);
MessageBusUtil.sendMessage(
"opencps/backoffice/out/destination", sendToBackOffice);
}
}
catch (Exception e) {
_log.error(e);
}
}
public List<SendNotificationMessage> getListNoties(
List<String> citizenEvents, List<String> employEvents,
long citizenUserId, long groupId, long assignToUserId,
ProcessWorkflow processWorkflow, long dossierId, long paymentFileId,
long processOrderId) {
List<SendNotificationMessage> ls =
new ArrayList<SendNotificationMessage>();
List<SendNotificationMessage.InfoList> infoCitizens =
new ArrayList<SendNotificationMessage.InfoList>();
List<SendNotificationMessage.InfoList> infoEmploys =
new ArrayList<SendNotificationMessage.InfoList>();
List<SendNotificationMessage.InfoList> employInfoList =
new ArrayList<SendNotificationMessage.InfoList>();
AccountBean accountBean =
AccountUtil.getAccountBean(citizenUserId, groupId, null);
Citizen citizen = null;
Business bussines = null;
if (accountBean.isCitizen()) {
citizen = (Citizen) accountBean.getAccountInstance();
}
if (accountBean.isBusiness()) {
bussines = (Business) accountBean.getAccountInstance();
}
for (String event : citizenEvents) {
_log.info("INFORRRRRRRRRRRRRRR + " + event);
SendNotificationMessage notiMsg = new SendNotificationMessage();
notiMsg.setDossierId(dossierId);
notiMsg.setNotificationEventName(event);
notiMsg.setProcessOrderId(processOrderId);
notiMsg.setType("SMS, INBOX, EMAIL");
SendNotificationMessage.InfoList info =
new SendNotificationMessage.InfoList();
List<SendNotificationMessage.InfoList> infoList =
new ArrayList<SendNotificationMessage.InfoList>();
infoList.add(info);
notiMsg.setInfoList(infoList);
if (Validator.isNotNull(citizen)) {
info.setUserId(citizen.getUserId());
info.setUserMail(citizen.getEmail());
info.setUserPhone(citizen.getTelNo());
}
if (Validator.isNotNull(bussines)) {
info.setUserId(bussines.getUserId());
info.setUserMail(bussines.getEmail());
info.setUserPhone(bussines.getTelNo());
}
if (event.contains(NotificationEventKeys.USERS_AND_ENTERPRISE.EVENT5)) {
info.setGroup(NotificationEventKeys.GROUP3);
Locale vnLocale = new Locale("vi", "VN");
notiMsg.setNotificationContent(LanguageUtil.get(
vnLocale, "phieu-yeu-cau-thanh-toan"));
}
else {
info.setGroup(NotificationEventKeys.GROUP2);
notiMsg.setNotificationContent(processWorkflow.getActionName());
}
ls.add(notiMsg);
}
for (String employEvent : employEvents) {
}
return ls;
}
private Log _log = LogFactoryUtil.getLog(BackOfficeProcessEngine.class);
}
| Update BackProcessEngine | portlets/opencps-portlet/docroot/WEB-INF/src/org/opencps/backend/engine/BackOfficeProcessEngine.java | Update BackProcessEngine | <ide><path>ortlets/opencps-portlet/docroot/WEB-INF/src/org/opencps/backend/engine/BackOfficeProcessEngine.java
<ide> import org.opencps.processmgt.service.ProcessStepLocalServiceUtil;
<ide> import org.opencps.processmgt.service.ProcessWorkflowLocalServiceUtil;
<ide> import org.opencps.processmgt.util.ProcessMgtUtil;
<add>import org.opencps.processmgt.util.ProcessUtils;
<add>import org.opencps.usermgt.model.Employee;
<ide> import org.opencps.util.AccountUtil;
<ide> import org.opencps.util.PortletConstants;
<ide> import org.opencps.util.WebKeys;
<ide> import com.liferay.portal.kernel.util.StringPool;
<ide> import com.liferay.portal.kernel.util.StringUtil;
<ide> import com.liferay.portal.kernel.util.Validator;
<add>import com.liferay.portal.model.User;
<ide>
<ide> /**
<ide> * @author khoavd
<ide> assignToUserId, processWorkflow, dossier.getDossierId(), paymentFile.getPaymentFileId() ,
<ide> processOrderId);
<ide>
<del> _log.info("%%%%%%%%%%%%% LIST ::::::" + lsNotification.size());
<add> _log.info("%%%%%%%%%%%%% LIST :::::: FUCKKKKKKKING" + lsNotification.size());
<ide>
<ide> toBackOffice.setListNotifications(lsNotification);
<ide>
<ide> assignToUserId, processWorkflow, dossier.getDossierId(), 0 ,
<ide> processOrderId);
<ide>
<del>
<del>
<ide> toBackOffice.setListNotifications(lsNotification);
<ide>
<ide> Message sendToBackOffice = new Message();
<ide> }
<ide>
<ide>
<del> public List<SendNotificationMessage> getListNoties(
<add> private List<SendNotificationMessage> getListNoties(
<ide> List<String> citizenEvents, List<String> employEvents,
<ide> long citizenUserId, long groupId, long assignToUserId,
<ide> ProcessWorkflow processWorkflow, long dossierId, long paymentFileId,
<ide>
<ide> List<SendNotificationMessage> ls =
<ide> new ArrayList<SendNotificationMessage>();
<del>
<del> List<SendNotificationMessage.InfoList> infoCitizens =
<del> new ArrayList<SendNotificationMessage.InfoList>();
<del> List<SendNotificationMessage.InfoList> infoEmploys =
<del> new ArrayList<SendNotificationMessage.InfoList>();
<del>
<del> List<SendNotificationMessage.InfoList> employInfoList =
<del> new ArrayList<SendNotificationMessage.InfoList>();
<ide>
<ide> AccountBean accountBean =
<ide> AccountUtil.getAccountBean(citizenUserId, groupId, null);
<ide> _log.info("INFORRRRRRRRRRRRRRR + " + event);
<ide>
<ide> SendNotificationMessage notiMsg = new SendNotificationMessage();
<add>
<ide>
<ide> notiMsg.setDossierId(dossierId);
<ide> notiMsg.setNotificationEventName(event);
<ide>
<ide> SendNotificationMessage.InfoList info =
<ide> new SendNotificationMessage.InfoList();
<del>
<add>
<add> info.setGroupId(groupId);
<add>
<ide> List<SendNotificationMessage.InfoList> infoList =
<ide> new ArrayList<SendNotificationMessage.InfoList>();
<ide>
<ide> }
<ide>
<ide> for (String employEvent : employEvents) {
<del>
<add>
<add> SendNotificationMessage notiMsg = new SendNotificationMessage();
<add>
<add> notiMsg.setDossierId(dossierId);
<add> notiMsg.setNotificationEventName(employEvent);
<add> notiMsg.setProcessOrderId(processOrderId);
<add> notiMsg.setType("SMS, INBOX, EMAIL");
<add>
<add>
<add> if (assignToUserId != 0) {
<add>
<add> SendNotificationMessage.InfoList infoEmploy =
<add> new SendNotificationMessage.InfoList();
<add>
<add> List<SendNotificationMessage.InfoList> infoListEmploy =
<add> new ArrayList<SendNotificationMessage.InfoList>();
<add>
<add> AccountBean accountEmploy =
<add> AccountUtil.getAccountBean(assignToUserId, groupId, null);
<add>
<add> Employee employee = null;
<add>
<add> if (accountEmploy.isEmployee()) {
<add> employee = (Employee) accountEmploy.getAccountInstance();
<add>
<add> infoEmploy.setUserId(employee.getUserId());
<add> infoEmploy.setUserMail(employee.getEmail());
<add> infoEmploy.setUserPhone(employee.getTelNo());
<add>
<add> }
<add>
<add> infoListEmploy.add(infoEmploy);
<add>
<add> if (employEvent.contains(NotificationEventKeys.OFFICIALS.EVENT3)) {
<add> infoEmploy.setGroup(NotificationEventKeys.GROUP4);
<add>
<add> Locale vnLocale = new Locale("vi", "VN");
<add> notiMsg.setNotificationContent(LanguageUtil.get(
<add> vnLocale, "phieu-yeu-cau-thanh-toan-moi-thuc-hien"));
<add>
<add> }
<add> else {
<add> infoEmploy.setGroup(NotificationEventKeys.GROUP1);
<add> notiMsg.setNotificationContent(processWorkflow.getActionName());
<add> }
<add>
<add> ls.add(notiMsg);
<add>
<add> } else {
<add> List<SendNotificationMessage.InfoList> infoListEmploy =
<add> new ArrayList<SendNotificationMessage.InfoList>();
<add>
<add> List<Employee> employees = getListEmploy(processWorkflow);
<add>
<add> for (Employee employee : employees) {
<add>
<add> SendNotificationMessage.InfoList infoEmploy =
<add> new SendNotificationMessage.InfoList();
<add>
<add> infoEmploy.setUserId(employee.getUserId());
<add> infoEmploy.setUserMail(employee.getEmail());
<add> infoEmploy.setUserPhone(employee.getTelNo());
<add> infoEmploy.setGroupId(groupId);
<add>
<add> if (employEvent.contains(NotificationEventKeys.OFFICIALS.EVENT3)) {
<add> infoEmploy.setGroup(NotificationEventKeys.GROUP4);
<add> }
<add> else {
<add> infoEmploy.setGroup(NotificationEventKeys.GROUP1);
<add> }
<add>
<add> infoListEmploy.add(infoEmploy);
<add> }
<add>
<add> if (employEvent.contains(NotificationEventKeys.OFFICIALS.EVENT3)) {
<add>
<add> Locale vnLocale = new Locale("vi", "VN");
<add>
<add> notiMsg.setNotificationContent(LanguageUtil.get(
<add> vnLocale, "phieu-yeu-cau-thanh-toan-moi-thuc-hien"));
<add> }
<add> else {
<add> notiMsg.setNotificationContent(processWorkflow.getActionName());
<add> }
<add>
<add> ls.add(notiMsg);
<add>
<add> }
<ide> }
<del>
<ide> return ls;
<ide> }
<ide>
<add> /**
<add> * @param processWorkflow
<add> * @param assignToUserId
<add> * @return
<add> */
<add> private List<Employee> getListEmploy(
<add> ProcessWorkflow processWorkflow) {
<add>
<add> List<Employee> ls = new ArrayList<>();
<add>
<add> try {
<add> List<User> users = ProcessUtils.getAssignUsers(processWorkflow.getPostProcessStepId(), 3);
<add>
<add> for (User user : users) {
<add> AccountBean accountEmploy =
<add> AccountUtil.getAccountBean(user.getUserId(), user.getGroupId(), null);
<add>
<add> Employee employee = (Employee) accountEmploy.getAccountInstance();
<add>
<add> ls.add(employee);
<add>
<add> }
<add>
<add> }
<add> catch (Exception e) {
<add>
<add> }
<add>
<add> return ls;
<add>
<add> }
<add>
<ide> private Log _log = LogFactoryUtil.getLog(BackOfficeProcessEngine.class);
<ide>
<ide> } |
|
Java | agpl-3.0 | 8a4c3501ae94279cba00c6952487da1c6ebd7d55 | 0 | quikkian-ua-devops/kfs,kkronenb/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,smith750/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,kuali/kfs,UniversityOfHawaii/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,ua-eas/kfs,quikkian-ua-devops/kfs,kuali/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,bhutchinson/kfs,ua-eas/kfs,ua-eas/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,bhutchinson/kfs,kuali/kfs,kuali/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,smith750/kfs,ua-eas/kfs-devops-automation-fork | /*
* Copyright 2011 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.ar.report.service.impl;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.coa.businessobject.IndirectCostRecoveryRateDetail;
import org.kuali.kfs.coa.businessobject.Organization;
import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAgency;
import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAward;
import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAwardAccount;
import org.kuali.kfs.module.ar.ArConstants;
import org.kuali.kfs.module.ar.ArKeyConstants;
import org.kuali.kfs.module.ar.ArPropertyConstants;
import org.kuali.kfs.module.ar.businessobject.ContractsGrantsLetterOfCreditReviewDetail;
import org.kuali.kfs.module.ar.businessobject.CustomerAddress;
import org.kuali.kfs.module.ar.businessobject.InvoiceAddressDetail;
import org.kuali.kfs.module.ar.businessobject.InvoicePaidApplied;
import org.kuali.kfs.module.ar.businessobject.SystemInformation;
import org.kuali.kfs.module.ar.document.ContractsGrantsInvoiceDocument;
import org.kuali.kfs.module.ar.document.ContractsGrantsLetterOfCreditReviewDocument;
import org.kuali.kfs.module.ar.document.service.ContractsGrantsInvoiceDocumentService;
import org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService;
import org.kuali.kfs.module.ar.service.ContractsGrantsBillingUtilityService;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.PdfFormFillerUtil;
import org.kuali.kfs.sys.report.ReportInfo;
import org.kuali.kfs.sys.service.NonTransactional;
import org.kuali.kfs.sys.service.ReportGenerationService;
import org.kuali.rice.core.api.config.property.ConfigurationService;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kim.api.identity.Person;
import org.kuali.rice.kim.api.identity.PersonService;
import org.kuali.rice.kns.service.DataDictionaryService;
import org.kuali.rice.krad.bo.Note;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.service.DocumentService;
import org.kuali.rice.krad.service.KualiModuleService;
import org.kuali.rice.krad.service.NoteService;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.ObjectUtils;
import au.com.bytecode.opencsv.CSVWriter;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfCopyFields;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;
/**
* This class implements the methods for report generation services for Contracts and Grants.
*/
public class ContractsGrantsInvoiceReportServiceImpl implements ContractsGrantsInvoiceReportService {
private final static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ContractsGrantsInvoiceReportServiceImpl.class);
protected DateTimeService dateTimeService;
protected DataDictionaryService dataDictionaryService;
protected PersonService personService;
protected BusinessObjectService businessObjectService;
protected ParameterService parameterService;
protected ConfigurationService configService;
protected KualiModuleService kualiModuleService;
protected DocumentService documentService;
protected NoteService noteService;
protected ReportInfo reportInfo;
protected ReportGenerationService reportGenerationService;
protected ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService;
protected ContractsGrantsBillingUtilityService contractsGrantsBillingUtilityService;
/**
* @see org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService#generateInvoice(org.kuali.kfs.module.ar.document.ContractsGrantsLOCReviewDocument)
*/
@Override
public byte[] generateLOCReviewAsPdf(ContractsGrantsLetterOfCreditReviewDocument document) {
Date runDate = new Date(new java.util.Date().getTime());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
this.generateLOCReviewInPdf(baos, document);
return baos.toByteArray();
}
/**
* this method generated the actual pdf for the Contracts and Grants LOC Review Document.
*
* @param os
* @param LOCDocument
*/
protected void generateLOCReviewInPdf(OutputStream os, ContractsGrantsLetterOfCreditReviewDocument locDocument) {
try {
Document document = new Document(new Rectangle(ArConstants.LOCReviewPdf.LENGTH, ArConstants.LOCReviewPdf.WIDTH));
PdfWriter.getInstance(document, os);
document.open();
Paragraph header = new Paragraph();
Paragraph text = new Paragraph();
Paragraph title = new Paragraph();
// Lets write the header
header.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_TITLE), ArConstants.PdfReportFonts.LOC_REVIEW_TITLE_FONT));
if (StringUtils.isNotEmpty(locDocument.getLetterOfCreditFundGroupCode())) {
header.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_HEADER_FUND_GROUP_CODE) + locDocument.getLetterOfCreditFundGroupCode(), ArConstants.PdfReportFonts.LOC_REVIEW_TITLE_FONT));
}
if (StringUtils.isNotEmpty(locDocument.getLetterOfCreditFundCode())) {
header.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_HEADER_FUND_CODE) + locDocument.getLetterOfCreditFundCode(), ArConstants.PdfReportFonts.LOC_REVIEW_TITLE_FONT));
}
header.add(new Paragraph(KFSConstants.BLANK_SPACE));
header.setAlignment(Element.ALIGN_CENTER);
title.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_HEADER_DOCUMENT_NUMBER) + locDocument.getDocumentNumber(), ArConstants.PdfReportFonts.LOC_REVIEW_HEADER_FONT));
Person person = getPersonService().getPerson(locDocument.getFinancialSystemDocumentHeader().getInitiatorPrincipalId());
// writing the Document details
title.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_HEADER_APP_DOC_STATUS) + locDocument.getFinancialSystemDocumentHeader().getApplicationDocumentStatus(), ArConstants.PdfReportFonts.LOC_REVIEW_HEADER_FONT));
title.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_HEADER_DOCUMENT_INITIATOR) + person.getName(), ArConstants.PdfReportFonts.LOC_REVIEW_HEADER_FONT));
title.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_HEADER_DOCUMENT_CREATE_DATE) + getDateTimeService().toDateString(locDocument.getFinancialSystemDocumentHeader().getWorkflowCreateDate()), ArConstants.PdfReportFonts.LOC_REVIEW_HEADER_FONT));
title.add(new Paragraph(KFSConstants.BLANK_SPACE));
title.setAlignment(Element.ALIGN_RIGHT);
text.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_SUBHEADER_AWARDS), ArConstants.PdfReportFonts.LOC_REVIEW_SMALL_BOLD));
text.add(new Paragraph(KFSConstants.BLANK_SPACE));
document.add(header);
document.add(title);
document.add(text);
PdfPTable table = new PdfPTable(11);
table.setTotalWidth(ArConstants.LOCReviewPdf.RESULTS_TABLE_WIDTH);
// fix the absolute width of the table
table.setLockedWidth(true);
// relative col widths in proportions - 1/11
float[] widths = new float[] { 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f };
table.setWidths(widths);
table.setHorizontalAlignment(0);
addAwardHeaders(table);
if (CollectionUtils.isNotEmpty(locDocument.getHeaderReviewDetails()) && CollectionUtils.isNotEmpty(locDocument.getAccountReviewDetails())) {
for (ContractsGrantsLetterOfCreditReviewDetail item : locDocument.getHeaderReviewDetails()) {
table.addCell(Long.toString(item.getProposalNumber()));
table.addCell(item.getAwardDocumentNumber());
table.addCell(item.getAgencyNumber());
table.addCell(item.getCustomerNumber());
table.addCell(getDateTimeService().toDateString(item.getAwardBeginningDate()));
table.addCell(getDateTimeService().toDateString(item.getAwardEndingDate()));
table.addCell(contractsGrantsBillingUtilityService.formatForCurrency(item.getAwardBudgetAmount()));
table.addCell(contractsGrantsBillingUtilityService.formatForCurrency(item.getLetterOfCreditAmount()));
table.addCell(contractsGrantsBillingUtilityService.formatForCurrency(item.getClaimOnCashBalance()));
table.addCell(contractsGrantsBillingUtilityService.formatForCurrency(item.getAmountToDraw()));
table.addCell(contractsGrantsBillingUtilityService.formatForCurrency(item.getAmountAvailableToDraw()));
PdfPCell cell = new PdfPCell();
cell.setPadding(ArConstants.LOCReviewPdf.RESULTS_TABLE_CELL_PADDING);
cell.setColspan(ArConstants.LOCReviewPdf.RESULTS_TABLE_COLSPAN);
PdfPTable newTable = new PdfPTable(ArConstants.LOCReviewPdf.INNER_TABLE_COLUMNS);
newTable.setTotalWidth(ArConstants.LOCReviewPdf.INNER_TABLE_WIDTH);
// fix the absolute width of the newTable
newTable.setLockedWidth(true);
// relative col widths in proportions - 1/8
float[] newWidths = new float[] { 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f };
newTable.setWidths(newWidths);
newTable.setHorizontalAlignment(0);
addAccountsHeaders(newTable);
for (ContractsGrantsLetterOfCreditReviewDetail newItem : locDocument.getAccountReviewDetails()) {
if (item.getProposalNumber().equals(newItem.getProposalNumber())) {
newTable.addCell(newItem.getAccountDescription());
newTable.addCell(newItem.getChartOfAccountsCode());
newTable.addCell(newItem.getAccountNumber());
newTable.addCell(getDateTimeService().toDateString(newItem.getAccountExpirationDate()));
newTable.addCell(contractsGrantsBillingUtilityService.formatForCurrency(newItem.getAwardBudgetAmount()));
newTable.addCell(contractsGrantsBillingUtilityService.formatForCurrency(newItem.getClaimOnCashBalance()));
newTable.addCell(contractsGrantsBillingUtilityService.formatForCurrency(newItem.getAmountToDraw()));
newTable.addCell(contractsGrantsBillingUtilityService.formatForCurrency(newItem.getFundsNotDrawn()));
}
}
cell.addElement(newTable);
table.addCell(cell);
}
document.add(table);
}
document.close();
}
catch (DocumentException e) {
LOG.error("problem during ContractsGrantsInvoiceReportServiceImpl.generateInvoiceInPdf()", e);
}
}
/**
* This method is used to set the headers for the CG LOC review Document
*
* @param table
*/
protected void addAccountsHeaders(PdfPTable table) {
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_DESCRIPTION));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_NUMBER));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_EXPIRATION_DATE));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AWARD_BUDGET_AMOUNT));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.CLAIM_ON_CASH_BALANCE));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AMOUNT_TO_DRAW));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.FUNDS_NOT_DRAWN));
}
/**
* This method is used to set the headers for the CG LOC review Document
*
* @param table
*/
protected void addAwardHeaders(PdfPTable table) {
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.PROPOSAL_NUMBER));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AWARD_DOCUMENT_NUMBER));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AGENCY_NUMBER));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.CUSTOMER_NUMBER));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AWARD_BEGINNING_DATE));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AWARD_ENDING_DATE));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AWARD_BUDGET_AMOUNT));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.LETTER_OF_CREDIT_AMOUNT));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.CLAIM_ON_CASH_BALANCE));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AMOUNT_TO_DRAW));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.FUNDS_NOT_DRAWN));
}
/**
* @see org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService#generateFederalFinancialForm(org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAward,
* java.lang.String, java.lang.String, java.lang.String, org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAgency)
*/
@Override
public File generateFederalFinancialForm(ContractsAndGrantsBillingAward award, String period, String year, String formType, ContractsAndGrantsBillingAgency agency) {
Map<String, String> replacementList = new HashMap<String, String>();
Date runDate = new Date(new java.util.Date().getTime());
String reportFileName = getReportInfo().getReportFileName();
String reportDirectory = getReportInfo().getReportsDirectory();
try {
if (formType.equals(ArConstants.FEDERAL_FORM_425) && ObjectUtils.isNotNull(award)) {
String fullReportFileName = reportGenerationService.buildFullFileName(runDate, reportDirectory, reportFileName, ArConstants.FEDERAL_FUND_425_REPORT_ABBREVIATION) + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION;
File file = new File(fullReportFileName);
FileOutputStream fos = new FileOutputStream(file);
stampPdfFormValues425(award, period, year, fos, replacementList);
return file;
}
else if (formType.equals(ArConstants.FEDERAL_FORM_425A) && ObjectUtils.isNotNull(agency)) {
String fullReportFileName = reportGenerationService.buildFullFileName(runDate, reportDirectory, reportFileName, ArConstants.FEDERAL_FUND_425A_REPORT_ABBREVIATION) + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION;
File file = new File(fullReportFileName);
FileOutputStream fos = new FileOutputStream(file);
stampPdfFormValues425A(agency, period, year, fos, replacementList);
return file;
}
}
catch (FileNotFoundException ex) {
throw new RuntimeException("Cannot find pdf to stamp for federal financial form", ex);
}
return null;
}
/**
* @param award
* @return
*/
protected KualiDecimal getCashReceipts(ContractsAndGrantsBillingAward award) {
KualiDecimal cashReceipt = KualiDecimal.ZERO;
Map<String,String> fieldValues = new HashMap<String,String>();
if (ObjectUtils.isNotNull(award) && ObjectUtils.isNotNull(award.getProposalNumber())){
fieldValues.put(KFSPropertyConstants.PROPOSAL_NUMBER, award.getProposalNumber().toString());
}
List<ContractsGrantsInvoiceDocument> list = (List<ContractsGrantsInvoiceDocument>) contractsGrantsInvoiceDocumentService.retrieveAllCGInvoicesByCriteria(fieldValues);
if (!CollectionUtils.isEmpty(list)) {
for(ContractsGrantsInvoiceDocument invoice: list){
Map primaryKeys = new HashMap<String, Object>();
primaryKeys.put(ArPropertyConstants.CustomerInvoiceDocumentFields.FINANCIAL_DOCUMENT_REF_INVOICE_NUMBER, invoice.getDocumentNumber());
List<InvoicePaidApplied> ipas = (List<InvoicePaidApplied>)businessObjectService.findMatching(InvoicePaidApplied.class, primaryKeys);
if(ObjectUtils.isNotNull(ipas)) {
for(InvoicePaidApplied ipa : ipas) {
cashReceipt = cashReceipt.add(ipa.getInvoiceItemAppliedAmount());
}
}
}
}
return cashReceipt;
}
/**
* This method is used to populate the replacement list to replace values from pdf template to actual values for Federal Form
* 425
*
* @param award
* @param reportingPeriod
* @param year
*/
protected void populateListByAward(ContractsAndGrantsBillingAward award, String reportingPeriod, String year, Map<String, String> replacementList) {
KualiDecimal cashDisbursement = KualiDecimal.ZERO;
for (ContractsAndGrantsBillingAwardAccount awardAccount : award.getActiveAwardAccounts()) {
int index = 0;
KualiDecimal baseSum = KualiDecimal.ZERO;
KualiDecimal amountSum = KualiDecimal.ZERO;
cashDisbursement = cashDisbursement.add(contractsGrantsInvoiceDocumentService.getBudgetAndActualsForAwardAccount(awardAccount, ArPropertyConstants.ACTUAL_BALANCE_TYPE, award.getAwardBeginningDate()));
if (ObjectUtils.isNotNull(awardAccount.getAccount().getFinancialIcrSeriesIdentifier()) && ObjectUtils.isNotNull(awardAccount.getAccount().getAcctIndirectCostRcvyTypeCd())) {
index++;
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_TYPE + " " + index, awardAccount.getAccount().getAcctIndirectCostRcvyTypeCd());
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_RATE + " " + index, awardAccount.getAccount().getFinancialIcrSeriesIdentifier());
if (ObjectUtils.isNotNull(awardAccount.getAccount().getAccountEffectiveDate())) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_PERIOD_FROM + " " + index, getDateTimeService().toDateString(awardAccount.getAccount().getAccountEffectiveDate()));
}
if (ObjectUtils.isNotNull(awardAccount.getAccount().getAccountExpirationDate())) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_PERIOD_TO + " " + index, getDateTimeService().toDateString(awardAccount.getAccount().getAccountExpirationDate()));
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_BASE + " " + index, contractsGrantsBillingUtilityService.formatForCurrency(award.getAwardTotalAmount()));
Map<String, Object> key = new HashMap<String, Object>();
key.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, year);
key.put(KFSPropertyConstants.FINANCIAL_ICR_SERIES_IDENTIFIER, awardAccount.getAccount().getFinancialIcrSeriesIdentifier());
key.put(KFSPropertyConstants.ACTIVE, true);
key.put(KFSPropertyConstants.TRANSACTION_DEBIT_INDICATOR, KFSConstants.GL_DEBIT_CODE);
List<IndirectCostRecoveryRateDetail> icrDetail = (List<IndirectCostRecoveryRateDetail>) businessObjectService.findMatchingOrderBy(IndirectCostRecoveryRateDetail.class, key, KFSPropertyConstants.AWARD_INDR_COST_RCVY_ENTRY_NBR, false);
if (CollectionUtils.isNotEmpty(icrDetail)) {
KualiDecimal rate = new KualiDecimal(icrDetail.get(0).getAwardIndrCostRcvyRatePct());
if (ObjectUtils.isNotNull(rate)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_AMOUNT + " " + index, contractsGrantsBillingUtilityService.formatForCurrency(award.getAwardTotalAmount().multiply(rate)));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_FEDERAL + " " + index, contractsGrantsBillingUtilityService.formatForCurrency(award.getAwardTotalAmount().multiply(rate)));
amountSum = amountSum.add(award.getAwardTotalAmount().multiply(rate));
}
}
baseSum = baseSum.add(award.getAwardTotalAmount());
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_BASE_SUM, contractsGrantsBillingUtilityService.formatForCurrency(baseSum));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_AMOUNT_SUM, contractsGrantsBillingUtilityService.formatForCurrency(amountSum));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_FEDERAL_SUM, contractsGrantsBillingUtilityService.formatForCurrency(amountSum));
}
final SystemInformation sysInfo = retrieveSystemInformationForAward(award, year);
if (ObjectUtils.isNotNull(sysInfo)) {
final String address = concatenateAddressFromSystemInformation(sysInfo);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.RECIPIENT_ORGANIZATION, address);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.ZWEI, sysInfo.getUniversityFederalEmployerIdentificationNumber());
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_AGENCY, award.getAgency().getFullName());
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_GRANT_NUMBER, award.getAwardDocumentNumber());
if(CollectionUtils.isNotEmpty(award.getActiveAwardAccounts())){
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.RECIPIENT_ACCOUNT_NUMBER, award.getActiveAwardAccounts().get(0).getAccountNumber());
}
if (ObjectUtils.isNotNull(award.getAwardBeginningDate())) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.GRANT_PERIOD_FROM, getDateTimeService().toDateString(award.getAwardBeginningDate()));
}
if (ObjectUtils.isNotNull(award.getAwardClosingDate())) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.GRANT_PERIOD_TO, getDateTimeService().toDateString(award.getAwardClosingDate()));
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH_RECEIPTS, contractsGrantsBillingUtilityService.formatForCurrency(this.getCashReceipts(award)));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.TOTAL_FEDERAL_FUNDS_AUTHORIZED, contractsGrantsBillingUtilityService.formatForCurrency(award.getAwardTotalAmount()));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.REPORTING_PERIOD_END_DATE, getReportingPeriodEndDate(reportingPeriod, year));
if (ObjectUtils.isNotNull(cashDisbursement)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH_DISBURSEMENTS, contractsGrantsBillingUtilityService.formatForCurrency(cashDisbursement));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH_ON_HAND, contractsGrantsBillingUtilityService.formatForCurrency(getCashReceipts(award).subtract(cashDisbursement)));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_SHARE_OF_EXPENDITURES, contractsGrantsBillingUtilityService.formatForCurrency(cashDisbursement));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.TOTAL_FEDERAL_SHARE, contractsGrantsBillingUtilityService.formatForCurrency(cashDisbursement));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.UNOBLIGATED_BALANCE_OF_FEDERAL_FUNDS, contractsGrantsBillingUtilityService.formatForCurrency(award.getAwardTotalAmount().subtract(cashDisbursement)));
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_SHARE_OF_UNLIQUIDATED_OBLIGATION, contractsGrantsBillingUtilityService.formatForCurrency(KualiDecimal.ZERO));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.TOTAL_FEDERAL_INCOME_EARNED, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INCOME_EXPENDED_DEDUCATION_ALTERNATIVE, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INCOME_EXPENDED_ADDITION_ALTERNATIVE, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.UNEXPECTED_PROGRAM_INCOME, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.NAME, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.TELEPHONE, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.EMAIL_ADDRESS, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.DATE_REPORT_SUBMITTED, getDateTimeService().toDateString(getDateTimeService().getCurrentDate()));
if (ArConstants.QUARTER1.equals(reportingPeriod) || ArConstants.QUARTER2.equals(reportingPeriod) || ArConstants.QUARTER3.equals(reportingPeriod) || ArConstants.QUARTER4.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.QUARTERLY, KFSConstants.OptionLabels.YES);
}
if (ArConstants.SEMI_ANNUAL.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.SEMI_ANNUAL, KFSConstants.OptionLabels.YES);
}
if (ArConstants.ANNUAL.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.ANNUAL, KFSConstants.OptionLabels.YES);
}
if (ArConstants.FINAL.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FINAL, KFSConstants.OptionLabels.YES);
}
String accountingBasis = parameterService.getParameterValueAsString(ArConstants.AR_NAMESPACE_CODE, KRADConstants.DetailTypes.ALL_DETAIL_TYPE, ArConstants.BASIS_OF_ACCOUNTING);
if (ArConstants.BASIS_OF_ACCOUNTING_CASH.equals(accountingBasis)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH, KFSConstants.OptionLabels.YES);
}
if (ArConstants.BASIS_OF_ACCOUNTING_ACCRUAL.equals(accountingBasis)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.ACCRUAL, KFSConstants.OptionLabels.YES);
}
}
/**
* Concatenates the address from an AR System Information object into a single String
* @param sysInfo the System Information business object to concatenate the address of
* @return the concatenated address
*/
protected String concatenateAddressFromSystemInformation(final SystemInformation sysInfo) {
String address = sysInfo.getOrganizationRemitToAddressName();
if(!StringUtils.isBlank(sysInfo.getOrganizationRemitToLine1StreetAddress())) {
address += ", " + sysInfo.getOrganizationRemitToLine1StreetAddress();
}
if(!StringUtils.isBlank(sysInfo.getOrganizationRemitToLine2StreetAddress())) {
address += ", " + sysInfo.getOrganizationRemitToLine2StreetAddress();
}
if(!StringUtils.isBlank(sysInfo.getOrganizationRemitToCityName())) {
address += ", " + sysInfo.getOrganizationRemitToCityName();
}
if(!StringUtils.isBlank(sysInfo.getOrganizationRemitToStateCode())) {
address += " " + sysInfo.getOrganizationRemitToStateCode();
}
if(!StringUtils.isBlank(sysInfo.getOrganizationRemitToZipCode())) {
address += "-" + sysInfo.getOrganizationRemitToZipCode();
}
return address;
}
/**
* Retrieves an AR System Information object for an award
* @param award the award to retrieve an associated System Information for
* @param year the year of the System Information object to retrieve
* @return the System Information object, or null if nothing is found
*/
protected SystemInformation retrieveSystemInformationForAward(ContractsAndGrantsBillingAward award, String year) {
Map primaryKeys = new HashMap<String, Object>();
primaryKeys.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, year);
primaryKeys.put(ArPropertyConstants.SystemInformationFields.PROCESSING_CHART_OF_ACCOUNTS_CODE, award.getPrimaryAwardOrganization().getChartOfAccountsCode());
primaryKeys.put(ArPropertyConstants.SystemInformationFields.PROCESSING_ORGANIZATION_CODE, award.getPrimaryAwardOrganization().getOrganizationCode());
SystemInformation sysInfo = businessObjectService.findByPrimaryKey(SystemInformation.class, primaryKeys);
return sysInfo;
}
/**
* This method is used to populate the replacement list to replace values from pdf template to actual values for Federal Form
* 425A
*
* @param awards
* @param reportingPeriod
* @param year
* @param agency
* @return total amount
*/
protected List<KualiDecimal> populateListByAgency(List<ContractsAndGrantsBillingAward> awards, String reportingPeriod, String year, ContractsAndGrantsBillingAgency agency) {
Map<String, String> replacementList = new HashMap<String, String>();
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.REPORTING_PERIOD_END_DATE, getReportingPeriodEndDate(reportingPeriod, year));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_AGENCY, agency.getFullName());
Map primaryKeys = new HashMap<String, Object>();
primaryKeys.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, year);
if (CollectionUtils.isNotEmpty(awards)){
primaryKeys.put(ArPropertyConstants.SystemInformationFields.PROCESSING_CHART_OF_ACCOUNTS_CODE, awards.get(0).getPrimaryAwardOrganization().getChartOfAccountsCode());
primaryKeys.put(ArPropertyConstants.SystemInformationFields.PROCESSING_ORGANIZATION_CODE, awards.get(0).getPrimaryAwardOrganization().getOrganizationCode());
}
SystemInformation sysInfo = businessObjectService.findByPrimaryKey(SystemInformation.class, primaryKeys);
if (ObjectUtils.isNotNull(sysInfo)) {
String address = concatenateAddressFromSystemInformation(sysInfo);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.RECIPIENT_ORGANIZATION, address);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.ZWEI, sysInfo.getUniversityFederalEmployerIdentificationNumber());
}
if (ArConstants.QUARTER1.equals(reportingPeriod) || ArConstants.QUARTER2.equals(reportingPeriod) || ArConstants.QUARTER3.equals(reportingPeriod) || ArConstants.QUARTER4.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.QUARTERLY, KFSConstants.OptionLabels.YES);
}
if (ArConstants.SEMI_ANNUAL.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.SEMI_ANNUAL, KFSConstants.OptionLabels.YES);
}
if (ArConstants.ANNUAL.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.ANNUAL, KFSConstants.OptionLabels.YES);
}
if (ArConstants.FINAL.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FINAL, KFSConstants.OptionLabels.YES);
}
String accountingBasis = parameterService.getParameterValueAsString(ArConstants.AR_NAMESPACE_CODE, KRADConstants.DetailTypes.ALL_DETAIL_TYPE, ArConstants.BASIS_OF_ACCOUNTING);
if (ArConstants.BASIS_OF_ACCOUNTING_CASH.equals(accountingBasis)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH, KFSConstants.OptionLabels.YES);
}
if (ArConstants.BASIS_OF_ACCOUNTING_ACCRUAL.equals(accountingBasis)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.ACCRUAL,KFSConstants.OptionLabels.YES);
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.DATE_REPORT_SUBMITTED, getDateTimeService().toDateString(new Date(new java.util.Date().getTime())));
KualiDecimal totalCashControl = KualiDecimal.ZERO;
KualiDecimal totalCashDisbursement = KualiDecimal.ZERO;
for (int i = 0; i < 30; i++) {
if (i < awards.size()) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_GRANT_NUMBER + " " + (i + 1), awards.get(i).getAwardDocumentNumber());
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.RECIPIENT_ACCOUNT_NUMBER + " " + (i + 1), awards.get(i).getActiveAwardAccounts().get(0).getAccountNumber());
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_CASH_DISBURSEMENT + " " + (i + 1), contractsGrantsBillingUtilityService.formatForCurrency(getCashReceipts(awards.get(i))));
totalCashControl = totalCashControl.add(this.getCashReceipts(awards.get(i)));
for (ContractsAndGrantsBillingAwardAccount awardAccount : awards.get(i).getActiveAwardAccounts()) {
totalCashDisbursement = totalCashDisbursement.add(contractsGrantsInvoiceDocumentService.getBudgetAndActualsForAwardAccount(awardAccount, ArPropertyConstants.ACTUAL_BALANCE_TYPE, awards.get(i).getAwardBeginningDate()));
}
}
}
ArrayList<KualiDecimal> list = new ArrayList<KualiDecimal>();
list.add(totalCashControl);
list.add(totalCashDisbursement);
return list;
}
/**
* This method returns the last day of the given reporting period.
*
* @param reportingPeriod
* @param year
* @return
*/
protected String getReportingPeriodEndDate(String reportingPeriod, String year) {
Integer yearAsInt = Integer.parseInt(year);
java.util.Date endDate = null;
if (ArConstants.QUARTER1.equals(reportingPeriod)) {
endDate = ArConstants.BillingQuarterLastDays.FIRST_QUARTER.getDateForYear(yearAsInt);
}
else if (ArConstants.QUARTER2.equals(reportingPeriod) || ArConstants.SEMI_ANNUAL.equals(reportingPeriod)) {
endDate = ArConstants.BillingQuarterLastDays.SECOND_QUARTER.getDateForYear(yearAsInt);
}
else if (ArConstants.QUARTER3.equals(reportingPeriod)) {
endDate = ArConstants.BillingQuarterLastDays.THIRD_QUARTER.getDateForYear(yearAsInt);
}
else {
endDate = ArConstants.BillingQuarterLastDays.FOURTH_QUARTER.getDateForYear(yearAsInt);
}
return getDateTimeService().toDateString(endDate);
}
/**
* Use iText <code>{@link PdfStamper}</code> to stamp information into field values on a PDF Form Template.
*
* @param award The award the values will be pulled from.
* @param reportingPeriod
* @param year
* @param returnStream The output stream the federal form will be written to.
*/
protected void stampPdfFormValues425(ContractsAndGrantsBillingAward award, String reportingPeriod, String year, OutputStream returnStream, Map<String, String> replacementList) {
String reportTemplateName = ArConstants.FF_425_TEMPLATE_NM + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION;
try {
String federalReportTemplatePath = configService.getPropertyValueAsString(KFSConstants.EXTERNALIZABLE_HELP_URL_KEY);
populateListByAward(award, reportingPeriod, year, replacementList);
//final byte[] pdfBytes = renameFieldsIn(federalReportTemplatePath + reportTemplateName, replacementList);
URL template = new URL(federalReportTemplatePath + reportTemplateName);
final byte[] pdfBytes = PdfFormFillerUtil.populateTemplate(template.openStream(), replacementList);
returnStream.write(pdfBytes);
}
catch (IOException | DocumentException ex) {
throw new RuntimeException("Troubles stamping the old 425!", ex);
}
}
/**
* Use iText <code>{@link PdfStamper}</code> to stamp information into field values on a PDF Form Template.
*
* @param agency The award the values will be pulled from.
* @param reportingPeriod
* @param year
* @param returnStream The output stream the federal form will be written to.
*/
protected void stampPdfFormValues425A(ContractsAndGrantsBillingAgency agency, String reportingPeriod, String year, OutputStream returnStream, Map<String, String> replacementList) {
String federalReportTemplatePath = configService.getPropertyValueAsString(KFSConstants.EXTERNALIZABLE_HELP_URL_KEY);
try {
final String federal425ATemplateUrl = federalReportTemplatePath + ArConstants.FF_425A_TEMPLATE_NM + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION;
final String federal425TemplateUrl = federalReportTemplatePath + ArConstants.FF_425_TEMPLATE_NM + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION;
Map<String, Object> fieldValues = new HashMap<>();
fieldValues.put(KFSPropertyConstants.AGENCY_NUMBER, agency.getAgencyNumber());
fieldValues.put(KFSPropertyConstants.ACTIVE, Boolean.TRUE);
List<ContractsAndGrantsBillingAward> awards = kualiModuleService.getResponsibleModuleService(ContractsAndGrantsBillingAward.class).getExternalizableBusinessObjectsList(ContractsAndGrantsBillingAward.class, fieldValues);
Integer pageNumber = 1, totalPages;
totalPages = (awards.size() / ArConstants.Federal425APdf.NUMBER_OF_SUMMARIES_PER_PAGE) + 1;
PdfCopyFields copy = new PdfCopyFields(returnStream);
// generate replacement list for FF425
populateListByAgency(awards, reportingPeriod, year, agency);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.TOTAL_PAGES, org.apache.commons.lang.ObjectUtils.toString(totalPages + 1));
KualiDecimal sumCashControl = KualiDecimal.ZERO;
KualiDecimal sumCumExp = KualiDecimal.ZERO;
while (pageNumber <= totalPages) {
List<ContractsAndGrantsBillingAward> awardsList = new ArrayList<ContractsAndGrantsBillingAward>();
for (int i = ((pageNumber - 1) * ArConstants.Federal425APdf.NUMBER_OF_SUMMARIES_PER_PAGE); i < (pageNumber * ArConstants.Federal425APdf.NUMBER_OF_SUMMARIES_PER_PAGE); i++) {
if (i < awards.size()) {
awardsList.add(awards.get(i));
}
}
// generate replacement list for FF425
List<KualiDecimal> list = populateListByAgency(awardsList, reportingPeriod, year, agency);
if (CollectionUtils.isNotEmpty(list)){
sumCashControl = sumCashControl.add(list.get(0));
if (list.size() > 1){
sumCumExp = sumCumExp.add(list.get(1));
}
}
// populate form with document values
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.PAGE_NUMBER, org.apache.commons.lang.ObjectUtils.toString(pageNumber + 1));
if (pageNumber == totalPages){
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.TOTAL, contractsGrantsBillingUtilityService.formatForCurrency(sumCashControl));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH_RECEIPTS, contractsGrantsBillingUtilityService.formatForCurrency(sumCashControl));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH_DISBURSEMENTS, contractsGrantsBillingUtilityService.formatForCurrency(sumCumExp));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH_ON_HAND, contractsGrantsBillingUtilityService.formatForCurrency(sumCashControl.subtract(sumCumExp)));
}
// add a document
copy.addDocument(new PdfReader(renameFieldsIn(federal425ATemplateUrl, replacementList)));
pageNumber++;
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.PAGE_NUMBER, "1");
// add the FF425 form.
copy.addDocument(new PdfReader(renameFieldsIn(federal425TemplateUrl, replacementList)));
// Close the PdfCopyFields object
copy.close();
}
catch (DocumentException | IOException ex) {
throw new RuntimeException("Tried to stamp the 425A, but couldn't do it. Just...just couldn't do it.", ex);
}
}
/**
*
* @param template the path to the original form
* @param list the replacement list
* @return
* @throws IOException
* @throws DocumentException
*/
protected byte[] renameFieldsIn(String template, Map<String, String> list) throws IOException, DocumentException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Create the stamper
PdfStamper stamper = new PdfStamper(new PdfReader(template), baos);
// Get the fields
AcroFields fields = stamper.getAcroFields();
// Loop over the fields
for (String field : list.keySet()) {
fields.setField(field, list.get(field));
}
// close the stamper
stamper.close();
return baos.toByteArray();
}
/**
* @see org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService#generateListOfInvoicesPdfToPrint(java.util.Collection)
*/
@Override
public byte[] combineInvoicePdfs(Collection<ContractsGrantsInvoiceDocument> list) throws DocumentException, IOException {
Date runDate = new Date(new java.util.Date().getTime());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
generateCombinedPdfForInvoices(list, baos);
return baos.toByteArray();
}
/**
* @see org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService#generateListOfInvoicesEnvelopesPdfToPrint(java.util.Collection)
*/
@Override
public byte[] combineInvoicePdfEnvelopes(Collection<ContractsGrantsInvoiceDocument> list) throws DocumentException, IOException {
Date runDate = new Date(new java.util.Date().getTime());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
generateCombinedPdfForEnvelopes(list, baos);
return baos.toByteArray();
}
/**
* Generates the pdf file for printing the invoices.
*
* @param list
* @param outputStream
* @throws DocumentException
* @throws IOException
*/
protected void generateCombinedPdfForInvoices(Collection<ContractsGrantsInvoiceDocument> list, OutputStream outputStream) throws DocumentException, IOException {
PdfCopyFields copy = new PdfCopyFields(outputStream);
boolean pageAdded = false;
for (ContractsGrantsInvoiceDocument invoice : list) {
// add a document
List<InvoiceAddressDetail> invoiceAddressDetails = invoice.getInvoiceAddressDetails();
for (InvoiceAddressDetail invoiceAddressDetail : invoiceAddressDetails) {
if (ArConstants.InvoiceTransmissionMethod.MAIL.equals(invoiceAddressDetail.getInvoiceTransmissionMethodCode())) {
Note note = noteService.getNoteByNoteId(invoiceAddressDetail.getNoteId());
Integer numberOfCopiesToPrint = invoiceAddressDetail.getCustomerAddress().getCustomerCopiesToPrint();
if (ObjectUtils.isNull(numberOfCopiesToPrint)) {
numberOfCopiesToPrint = 1;
}
if (!ObjectUtils.isNull(note)) {
for (int i = 0; i < numberOfCopiesToPrint; i++) {
if (!pageAdded) {
copy.open();
}
pageAdded = true;
copy.addDocument(new PdfReader(note.getAttachment().getAttachmentContents()));
}
}
}
}
invoice.setDateReportProcessed(new Date(new java.util.Date().getTime()));
documentService.updateDocument(invoice);
}
if (pageAdded) {
copy.close();
}
}
/**
* Generates the pdf file for printing the envelopes.
*
* @param list
* @param outputStream
* @throws DocumentException
* @throws IOException
*/
protected void generateCombinedPdfForEnvelopes(Collection<ContractsGrantsInvoiceDocument> list, OutputStream outputStream) throws DocumentException, IOException {
Document document = new Document(new Rectangle(ArConstants.InvoiceEnvelopePdf.LENGTH, ArConstants.InvoiceEnvelopePdf.WIDTH));
PdfWriter.getInstance(document, outputStream);
boolean pageAdded = false;
for (ContractsGrantsInvoiceDocument invoice : list) {
// add a document
for (InvoiceAddressDetail invoiceAddressDetail : invoice.getInvoiceAddressDetails()) {
if (ArConstants.InvoiceTransmissionMethod.MAIL.equals(invoiceAddressDetail.getInvoiceTransmissionMethodCode())) {
CustomerAddress address = invoiceAddressDetail.getCustomerAddress();
Integer numberOfEnvelopesToPrint = address.getCustomerPrintEnvelopesNumber();
if (ObjectUtils.isNull(numberOfEnvelopesToPrint)) {
numberOfEnvelopesToPrint = 1;
}
for (int i = 0; i < numberOfEnvelopesToPrint; i++) {
// if a page has not already been added then open the document.
if (!pageAdded) {
document.open();
}
pageAdded = true;
document.newPage();
// adding the sent From address
Organization org = invoice.getAward().getPrimaryAwardOrganization().getOrganization();
Paragraph sentBy = generateAddressParagraph(org.getOrganizationName(), org.getOrganizationLine1Address(), org.getOrganizationLine2Address(), org.getOrganizationCityName(), org.getOrganizationStateCode(), org.getOrganizationZipCode(), ArConstants.PdfReportFonts.ENVELOPE_SMALL_FONT);
sentBy.setIndentationLeft(ArConstants.InvoiceEnvelopePdf.INDENTATION_LEFT);
sentBy.setAlignment(Element.ALIGN_LEFT);
// adding the send To address
String string;
Paragraph sendTo = generateAddressParagraph(address.getCustomerAddressName(), address.getCustomerLine1StreetAddress(), address.getCustomerLine2StreetAddress(), address.getCustomerCityName(), address.getCustomerStateCode(), address.getCustomerZipCode(), ArConstants.PdfReportFonts.ENVELOPE_TITLE_FONT);
sendTo.setAlignment(Element.ALIGN_CENTER);
sendTo.add(new Paragraph(KFSConstants.BLANK_SPACE));
document.add(sentBy);
document.add(sendTo);
}
}
}
}
if (pageAdded) {
document.close();
}
}
/**
* Generates a PDF paragraph for a given Address
* @param name the name that this envelope is being sent to
* @param line1Address the first line of the address
* @param line2Address the second line of the address
* @param cityName the name of the city to send this to
* @param stateCode the code of the state or presumably province to send this to
* @param postalCode the postal code/zip code to send the enveleope to
* @param font the font to write in
* @return a PDF Paragraph for the address
*/
protected Paragraph generateAddressParagraph(String name, String line1Address, String line2Address, String cityName, String stateCode, String postalCode, Font font) {
Paragraph addressParagraph = new Paragraph();
addressParagraph.add(new Paragraph(name, font));
if (!StringUtils.isBlank(line1Address)) {
addressParagraph.add(new Paragraph(line1Address, font));
}
if (!StringUtils.isBlank(line2Address)) {
addressParagraph.add(new Paragraph(line2Address, font));
}
String string = "";
if (!StringUtils.isBlank(cityName)) {
string += cityName;
}
if (!StringUtils.isBlank(stateCode)) {
string += ", " + stateCode;
}
if (!StringUtils.isBlank(postalCode)) {
string += "-" + postalCode;
}
if (!StringUtils.isBlank(string)) {
addressParagraph.add(new Paragraph(string, font));
}
return addressParagraph;
}
/**
* @see org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService#generateCSVToExport(org.kuali.kfs.module.ar.document.ContractsGrantsLOCReviewDocument)
*/
@Override
public byte[] convertLetterOfCreditReviewToCSV(ContractsGrantsLetterOfCreditReviewDocument LOCDocument) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(baos);
CSVWriter csvWriter = new CSVWriter(writer);
try {
csvWriter.writeNext(new String[] {getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.PROPOSAL_NUMBER),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.ReferralToCollectionsFields.AWARD_DOCUMENT_NUMBER),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_DESCRIPTION),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_NUMBER),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_EXPIRATION_DATE),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AWARD_BUDGET_AMOUNT),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.CLAIM_ON_CASH_BALANCE),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AMOUNT_TO_DRAW),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.FUNDS_NOT_DRAWN)});
if (CollectionUtils.isNotEmpty(LOCDocument.getHeaderReviewDetails()) && CollectionUtils.isNotEmpty(LOCDocument.getAccountReviewDetails())) {
for (ContractsGrantsLetterOfCreditReviewDetail item : LOCDocument.getHeaderReviewDetails()) {
String proposalNumber = org.apache.commons.lang.ObjectUtils.toString(item.getProposalNumber());
String awardDocumentNumber = org.apache.commons.lang.ObjectUtils.toString(item.getAwardDocumentNumber());
for (ContractsGrantsLetterOfCreditReviewDetail newItem : LOCDocument.getAccountReviewDetails()) {
if (org.apache.commons.lang.ObjectUtils.equals(item.getProposalNumber(), newItem.getProposalNumber())) {
csvWriter.writeNext(new String[] { proposalNumber,
awardDocumentNumber,
newItem.getAccountDescription(),
newItem.getChartOfAccountsCode(),
newItem.getAccountNumber(),
getDateTimeService().toDateString(newItem.getAccountExpirationDate()),
contractsGrantsBillingUtilityService.formatForCurrency(newItem.getAwardBudgetAmount()),
contractsGrantsBillingUtilityService.formatForCurrency(newItem.getClaimOnCashBalance()),
contractsGrantsBillingUtilityService.formatForCurrency(newItem.getAmountToDraw()),
contractsGrantsBillingUtilityService.formatForCurrency(newItem.getFundsNotDrawn()) });
}
}
}
}
}
finally {
if (csvWriter != null) {
try {
csvWriter.close();
}
catch (IOException ex) {
csvWriter = null;
throw new RuntimeException("problem during ContractsGrantsInvoiceReportServiceImpl.generateCSVToExport()", ex);
}
}
if (writer != null) {
try {
writer.flush();
writer.close();
}
catch (IOException ex) {
writer = null;
throw new RuntimeException("problem during ContractsGrantsInvoiceReportServiceImpl.generateCSVToExport()", ex);
}
}
}
return baos.toByteArray();
}
public PersonService getPersonService() {
return personService;
}
public void setPersonService(PersonService personService) {
this.personService = personService;
}
/**
* Gets the businessObjectService attribute.
*
* @return Returns the businessObjectService.
*/
public BusinessObjectService getBusinessObjectService() {
return businessObjectService;
}
/**
* Sets the businessObjectService attribute value.
*
* @param businessObjectService The businessObjectService to set.
*/
public void setBusinessObjectService(BusinessObjectService businessObjectService) {
this.businessObjectService = businessObjectService;
}
public ParameterService getParameterService() {
return parameterService;
}
public void setParameterService(ParameterService parameterService) {
this.parameterService = parameterService;
}
public void setConfigService(ConfigurationService configService) {
this.configService = configService;
}
/**
* Sets the kualiModuleService attribute value.
*
* @param kualiModuleService The kualiModuleService to set.
*/
@NonTransactional
public void setKualiModuleService(KualiModuleService kualiModuleService) {
this.kualiModuleService = kualiModuleService;
}
/**
* @return the documentService
*/
public DocumentService getDocumentService() {
return documentService;
}
/**
* @param documentService the documentService to set
*/
public void setDocumentService(DocumentService documentService) {
this.documentService = documentService;
}
public NoteService getNoteService() {
return noteService;
}
public void setNoteService(NoteService noteService) {
this.noteService = noteService;
}
public ReportInfo getReportInfo() {
return reportInfo;
}
public void setReportInfo(ReportInfo reportInfo) {
this.reportInfo = reportInfo;
}
public ReportGenerationService getReportGenerationService() {
return reportGenerationService;
}
public void setReportGenerationService(ReportGenerationService reportGenerationService) {
this.reportGenerationService = reportGenerationService;
}
public ContractsGrantsInvoiceDocumentService getContractsGrantsInvoiceDocumentService() {
return contractsGrantsInvoiceDocumentService;
}
public void setContractsGrantsInvoiceDocumentService(ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService) {
this.contractsGrantsInvoiceDocumentService = contractsGrantsInvoiceDocumentService;
}
public DateTimeService getDateTimeService() {
return dateTimeService;
}
public void setDateTimeService(DateTimeService dateTimeService) {
this.dateTimeService = dateTimeService;
}
public DataDictionaryService getDataDictionaryService() {
return dataDictionaryService;
}
public void setDataDictionaryService(DataDictionaryService dataDictionaryService) {
this.dataDictionaryService = dataDictionaryService;
}
public ContractsGrantsBillingUtilityService getContractsGrantsBillingUtilityService() {
return contractsGrantsBillingUtilityService;
}
public void setContractsGrantsBillingUtilityService(ContractsGrantsBillingUtilityService contractsGrantsBillingUtilityService) {
this.contractsGrantsBillingUtilityService = contractsGrantsBillingUtilityService;
}
} | work/src/org/kuali/kfs/module/ar/report/service/impl/ContractsGrantsInvoiceReportServiceImpl.java | /*
* Copyright 2011 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.ar.report.service.impl;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.coa.businessobject.IndirectCostRecoveryRateDetail;
import org.kuali.kfs.coa.businessobject.Organization;
import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAgency;
import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAward;
import org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAwardAccount;
import org.kuali.kfs.module.ar.ArConstants;
import org.kuali.kfs.module.ar.ArKeyConstants;
import org.kuali.kfs.module.ar.ArPropertyConstants;
import org.kuali.kfs.module.ar.businessobject.ContractsGrantsLetterOfCreditReviewDetail;
import org.kuali.kfs.module.ar.businessobject.CustomerAddress;
import org.kuali.kfs.module.ar.businessobject.InvoiceAddressDetail;
import org.kuali.kfs.module.ar.businessobject.InvoicePaidApplied;
import org.kuali.kfs.module.ar.businessobject.SystemInformation;
import org.kuali.kfs.module.ar.document.ContractsGrantsInvoiceDocument;
import org.kuali.kfs.module.ar.document.ContractsGrantsLetterOfCreditReviewDocument;
import org.kuali.kfs.module.ar.document.service.ContractsGrantsInvoiceDocumentService;
import org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService;
import org.kuali.kfs.module.ar.service.ContractsGrantsBillingUtilityService;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.PdfFormFillerUtil;
import org.kuali.kfs.sys.report.ReportInfo;
import org.kuali.kfs.sys.service.NonTransactional;
import org.kuali.kfs.sys.service.ReportGenerationService;
import org.kuali.rice.core.api.config.property.ConfigurationService;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kim.api.identity.Person;
import org.kuali.rice.kim.api.identity.PersonService;
import org.kuali.rice.kns.service.DataDictionaryService;
import org.kuali.rice.krad.bo.Note;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.service.DocumentService;
import org.kuali.rice.krad.service.KualiModuleService;
import org.kuali.rice.krad.service.NoteService;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.util.ObjectUtils;
import au.com.bytecode.opencsv.CSVWriter;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfCopyFields;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;
/**
* This class implements the methods for report generation services for Contracts and Grants.
*/
public class ContractsGrantsInvoiceReportServiceImpl implements ContractsGrantsInvoiceReportService {
private final static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ContractsGrantsInvoiceReportServiceImpl.class);
protected DateTimeService dateTimeService;
protected DataDictionaryService dataDictionaryService;
protected PersonService personService;
protected BusinessObjectService businessObjectService;
protected ParameterService parameterService;
protected ConfigurationService configService;
protected KualiModuleService kualiModuleService;
protected DocumentService documentService;
protected NoteService noteService;
protected ReportInfo reportInfo;
protected ReportGenerationService reportGenerationService;
protected ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService;
protected ContractsGrantsBillingUtilityService contractsGrantsBillingUtilityService;
/**
* @see org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService#generateInvoice(org.kuali.kfs.module.ar.document.ContractsGrantsLOCReviewDocument)
*/
@Override
public byte[] generateLOCReviewAsPdf(ContractsGrantsLetterOfCreditReviewDocument document) {
Date runDate = new Date(new java.util.Date().getTime());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
this.generateLOCReviewInPdf(baos, document);
return baos.toByteArray();
}
/**
* this method generated the actual pdf for the Contracts and Grants LOC Review Document.
*
* @param os
* @param LOCDocument
*/
protected void generateLOCReviewInPdf(OutputStream os, ContractsGrantsLetterOfCreditReviewDocument locDocument) {
try {
Document document = new Document(new Rectangle(ArConstants.LOCReviewPdf.LENGTH, ArConstants.LOCReviewPdf.WIDTH));
PdfWriter.getInstance(document, os);
document.open();
Paragraph header = new Paragraph();
Paragraph text = new Paragraph();
Paragraph title = new Paragraph();
// Lets write the header
header.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_TITLE), ArConstants.PdfReportFonts.LOC_REVIEW_TITLE_FONT));
if (StringUtils.isNotEmpty(locDocument.getLetterOfCreditFundGroupCode())) {
header.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_HEADER_FUND_GROUP_CODE) + locDocument.getLetterOfCreditFundGroupCode(), ArConstants.PdfReportFonts.LOC_REVIEW_TITLE_FONT));
}
if (StringUtils.isNotEmpty(locDocument.getLetterOfCreditFundCode())) {
header.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_HEADER_FUND_CODE) + locDocument.getLetterOfCreditFundCode(), ArConstants.PdfReportFonts.LOC_REVIEW_TITLE_FONT));
}
header.add(new Paragraph(KFSConstants.BLANK_SPACE));
header.setAlignment(Element.ALIGN_CENTER);
title.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_HEADER_DOCUMENT_NUMBER) + locDocument.getDocumentNumber(), ArConstants.PdfReportFonts.LOC_REVIEW_HEADER_FONT));
Person person = getPersonService().getPerson(locDocument.getFinancialSystemDocumentHeader().getInitiatorPrincipalId());
// writing the Document details
title.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_HEADER_APP_DOC_STATUS) + locDocument.getFinancialSystemDocumentHeader().getApplicationDocumentStatus(), ArConstants.PdfReportFonts.LOC_REVIEW_HEADER_FONT));
title.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_HEADER_DOCUMENT_INITIATOR) + person.getName(), ArConstants.PdfReportFonts.LOC_REVIEW_HEADER_FONT));
title.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_HEADER_DOCUMENT_CREATE_DATE) + getDateTimeService().toDateString(locDocument.getFinancialSystemDocumentHeader().getWorkflowCreateDate()), ArConstants.PdfReportFonts.LOC_REVIEW_HEADER_FONT));
title.add(new Paragraph(KFSConstants.BLANK_SPACE));
title.setAlignment(Element.ALIGN_RIGHT);
text.add(new Paragraph(configService.getPropertyValueAsString(ArKeyConstants.LOC_REVIEW_PDF_SUBHEADER_AWARDS), ArConstants.PdfReportFonts.LOC_REVIEW_SMALL_BOLD));
text.add(new Paragraph(KFSConstants.BLANK_SPACE));
document.add(header);
document.add(title);
document.add(text);
PdfPTable table = new PdfPTable(11);
table.setTotalWidth(ArConstants.LOCReviewPdf.RESULTS_TABLE_WIDTH);
// fix the absolute width of the table
table.setLockedWidth(true);
// relative col widths in proportions - 1/11
float[] widths = new float[] { 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f };
table.setWidths(widths);
table.setHorizontalAlignment(0);
addAwardHeaders(table);
if (CollectionUtils.isNotEmpty(locDocument.getHeaderReviewDetails()) && CollectionUtils.isNotEmpty(locDocument.getAccountReviewDetails())) {
for (ContractsGrantsLetterOfCreditReviewDetail item : locDocument.getHeaderReviewDetails()) {
table.addCell(Long.toString(item.getProposalNumber()));
table.addCell(item.getAwardDocumentNumber());
table.addCell(item.getAgencyNumber());
table.addCell(item.getCustomerNumber());
table.addCell(getDateTimeService().toDateString(item.getAwardBeginningDate()));
table.addCell(getDateTimeService().toDateString(item.getAwardEndingDate()));
table.addCell(contractsGrantsBillingUtilityService.formatForCurrency(item.getAwardBudgetAmount()));
table.addCell(contractsGrantsBillingUtilityService.formatForCurrency(item.getLetterOfCreditAmount()));
table.addCell(contractsGrantsBillingUtilityService.formatForCurrency(item.getClaimOnCashBalance()));
table.addCell(contractsGrantsBillingUtilityService.formatForCurrency(item.getAmountToDraw()));
table.addCell(contractsGrantsBillingUtilityService.formatForCurrency(item.getAmountAvailableToDraw()));
PdfPCell cell = new PdfPCell();
cell.setPadding(ArConstants.LOCReviewPdf.RESULTS_TABLE_CELL_PADDING);
cell.setColspan(ArConstants.LOCReviewPdf.RESULTS_TABLE_COLSPAN);
PdfPTable newTable = new PdfPTable(ArConstants.LOCReviewPdf.INNER_TABLE_COLUMNS);
newTable.setTotalWidth(ArConstants.LOCReviewPdf.INNER_TABLE_WIDTH);
// fix the absolute width of the newTable
newTable.setLockedWidth(true);
// relative col widths in proportions - 1/8
float[] newWidths = new float[] { 1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f };
newTable.setWidths(newWidths);
newTable.setHorizontalAlignment(0);
addAccountsHeaders(newTable);
for (ContractsGrantsLetterOfCreditReviewDetail newItem : locDocument.getAccountReviewDetails()) {
if (item.getProposalNumber().equals(newItem.getProposalNumber())) {
newTable.addCell(newItem.getAccountDescription());
newTable.addCell(newItem.getChartOfAccountsCode());
newTable.addCell(newItem.getAccountNumber());
newTable.addCell(getDateTimeService().toDateString(newItem.getAccountExpirationDate()));
newTable.addCell(contractsGrantsBillingUtilityService.formatForCurrency(newItem.getAwardBudgetAmount()));
newTable.addCell(contractsGrantsBillingUtilityService.formatForCurrency(newItem.getClaimOnCashBalance()));
newTable.addCell(contractsGrantsBillingUtilityService.formatForCurrency(newItem.getAmountToDraw()));
newTable.addCell(contractsGrantsBillingUtilityService.formatForCurrency(newItem.getFundsNotDrawn()));
}
}
cell.addElement(newTable);
table.addCell(cell);
}
document.add(table);
}
document.close();
}
catch (DocumentException e) {
LOG.error("problem during ContractsGrantsInvoiceReportServiceImpl.generateInvoiceInPdf()", e);
}
}
/**
* This method is used to set the headers for the CG LOC review Document
*
* @param table
*/
protected void addAccountsHeaders(PdfPTable table) {
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_DESCRIPTION));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_NUMBER));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_EXPIRATION_DATE));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AWARD_BUDGET_AMOUNT));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.CLAIM_ON_CASH_BALANCE));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AMOUNT_TO_DRAW));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.FUNDS_NOT_DRAWN));
}
/**
* This method is used to set the headers for the CG LOC review Document
*
* @param table
*/
protected void addAwardHeaders(PdfPTable table) {
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.PROPOSAL_NUMBER));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AWARD_DOCUMENT_NUMBER));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AGENCY_NUMBER));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.CUSTOMER_NUMBER));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AWARD_BEGINNING_DATE));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AWARD_ENDING_DATE));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AWARD_BUDGET_AMOUNT));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.LETTER_OF_CREDIT_AMOUNT));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.CLAIM_ON_CASH_BALANCE));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AMOUNT_TO_DRAW));
table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.FUNDS_NOT_DRAWN));
}
/**
* @see org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService#generateFederalFinancialForm(org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAward,
* java.lang.String, java.lang.String, java.lang.String, org.kuali.kfs.integration.cg.ContractsAndGrantsBillingAgency)
*/
@Override
public File generateFederalFinancialForm(ContractsAndGrantsBillingAward award, String period, String year, String formType, ContractsAndGrantsBillingAgency agency) {
Map<String, String> replacementList = new HashMap<String, String>();
Date runDate = new Date(new java.util.Date().getTime());
String reportFileName = getReportInfo().getReportFileName();
String reportDirectory = getReportInfo().getReportsDirectory();
try {
if (formType.equals(ArConstants.FEDERAL_FORM_425) && ObjectUtils.isNotNull(award)) {
String fullReportFileName = reportGenerationService.buildFullFileName(runDate, reportDirectory, reportFileName, ArConstants.FEDERAL_FUND_425_REPORT_ABBREVIATION) + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION;
File file = new File(fullReportFileName);
FileOutputStream fos = new FileOutputStream(file);
stampPdfFormValues425(award, period, year, fos, replacementList);
return file;
}
else if (formType.equals(ArConstants.FEDERAL_FORM_425A) && ObjectUtils.isNotNull(agency)) {
String fullReportFileName = reportGenerationService.buildFullFileName(runDate, reportDirectory, reportFileName, ArConstants.FEDERAL_FUND_425A_REPORT_ABBREVIATION) + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION;
File file = new File(fullReportFileName);
FileOutputStream fos = new FileOutputStream(file);
stampPdfFormValues425A(agency, period, year, fos, replacementList);
return file;
}
}
catch (FileNotFoundException ex) {
throw new RuntimeException("Cannot find pdf to stamp for federal financial form", ex);
}
return null;
}
/**
* @param award
* @return
*/
protected KualiDecimal getCashReceipts(ContractsAndGrantsBillingAward award) {
KualiDecimal cashReceipt = KualiDecimal.ZERO;
Map<String,String> fieldValues = new HashMap<String,String>();
if (ObjectUtils.isNotNull(award) && ObjectUtils.isNotNull(award.getProposalNumber())){
fieldValues.put(KFSPropertyConstants.PROPOSAL_NUMBER, award.getProposalNumber().toString());
}
List<ContractsGrantsInvoiceDocument> list = (List<ContractsGrantsInvoiceDocument>) contractsGrantsInvoiceDocumentService.retrieveAllCGInvoicesByCriteria(fieldValues);
if (!CollectionUtils.isEmpty(list)) {
for(ContractsGrantsInvoiceDocument invoice: list){
Map primaryKeys = new HashMap<String, Object>();
primaryKeys.put(ArPropertyConstants.CustomerInvoiceDocumentFields.FINANCIAL_DOCUMENT_REF_INVOICE_NUMBER, invoice.getDocumentNumber());
List<InvoicePaidApplied> ipas = (List<InvoicePaidApplied>)businessObjectService.findMatching(InvoicePaidApplied.class, primaryKeys);
if(ObjectUtils.isNotNull(ipas)) {
for(InvoicePaidApplied ipa : ipas) {
cashReceipt = cashReceipt.add(ipa.getInvoiceItemAppliedAmount());
}
}
}
}
return cashReceipt;
}
/**
* This method is used to populate the replacement list to replace values from pdf template to actual values for Federal Form
* 425
*
* @param award
* @param reportingPeriod
* @param year
*/
protected void populateListByAward(ContractsAndGrantsBillingAward award, String reportingPeriod, String year, Map<String, String> replacementList) {
KualiDecimal cashDisbursement = KualiDecimal.ZERO;
for (ContractsAndGrantsBillingAwardAccount awardAccount : award.getActiveAwardAccounts()) {
int index = 0;
KualiDecimal baseSum = KualiDecimal.ZERO;
KualiDecimal amountSum = KualiDecimal.ZERO;
cashDisbursement = cashDisbursement.add(contractsGrantsInvoiceDocumentService.getBudgetAndActualsForAwardAccount(awardAccount, ArPropertyConstants.ACTUAL_BALANCE_TYPE, award.getAwardBeginningDate()));
if (ObjectUtils.isNotNull(awardAccount.getAccount().getFinancialIcrSeriesIdentifier()) && ObjectUtils.isNotNull(awardAccount.getAccount().getAcctIndirectCostRcvyTypeCd())) {
index++;
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_TYPE + " " + index, awardAccount.getAccount().getAcctIndirectCostRcvyTypeCd());
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_RATE + " " + index, awardAccount.getAccount().getFinancialIcrSeriesIdentifier());
if (ObjectUtils.isNotNull(awardAccount.getAccount().getAccountEffectiveDate())) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_PERIOD_FROM + " " + index, getDateTimeService().toDateString(awardAccount.getAccount().getAccountEffectiveDate()));
}
if (ObjectUtils.isNotNull(awardAccount.getAccount().getAccountExpirationDate())) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_PERIOD_TO + " " + index, getDateTimeService().toDateString(awardAccount.getAccount().getAccountExpirationDate()));
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_BASE + " " + index, contractsGrantsBillingUtilityService.formatForCurrency(award.getAwardTotalAmount()));
Map<String, Object> key = new HashMap<String, Object>();
key.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, year);
key.put(KFSPropertyConstants.FINANCIAL_ICR_SERIES_IDENTIFIER, awardAccount.getAccount().getFinancialIcrSeriesIdentifier());
key.put(KFSPropertyConstants.ACTIVE, true);
key.put(KFSPropertyConstants.TRANSACTION_DEBIT_INDICATOR, KFSConstants.GL_DEBIT_CODE);
List<IndirectCostRecoveryRateDetail> icrDetail = (List<IndirectCostRecoveryRateDetail>) businessObjectService.findMatchingOrderBy(IndirectCostRecoveryRateDetail.class, key, KFSPropertyConstants.AWARD_INDR_COST_RCVY_ENTRY_NBR, false);
if (CollectionUtils.isNotEmpty(icrDetail)) {
KualiDecimal rate = new KualiDecimal(icrDetail.get(0).getAwardIndrCostRcvyRatePct());
if (ObjectUtils.isNotNull(rate)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_AMOUNT + " " + index, contractsGrantsBillingUtilityService.formatForCurrency(award.getAwardTotalAmount().multiply(rate)));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_FEDERAL + " " + index, contractsGrantsBillingUtilityService.formatForCurrency(award.getAwardTotalAmount().multiply(rate)));
amountSum = amountSum.add(award.getAwardTotalAmount().multiply(rate));
}
}
baseSum = baseSum.add(award.getAwardTotalAmount());
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_BASE_SUM, contractsGrantsBillingUtilityService.formatForCurrency(baseSum));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_AMOUNT_SUM, contractsGrantsBillingUtilityService.formatForCurrency(amountSum));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INDIRECT_EXPENSE_FEDERAL_SUM, contractsGrantsBillingUtilityService.formatForCurrency(amountSum));
}
final SystemInformation sysInfo = retrieveSystemInformationForAward(award, year);
if (ObjectUtils.isNotNull(sysInfo)) {
final String address = concatenateAddressFromSystemInformation(sysInfo);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.RECIPIENT_ORGANIZATION, address);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.ZWEI, sysInfo.getUniversityFederalEmployerIdentificationNumber());
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_AGENCY, award.getAgency().getFullName());
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_GRANT_NUMBER, award.getAwardDocumentNumber());
if(CollectionUtils.isNotEmpty(award.getActiveAwardAccounts())){
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.RECIPIENT_ACCOUNT_NUMBER, award.getActiveAwardAccounts().get(0).getAccountNumber());
}
if (ObjectUtils.isNotNull(award.getAwardBeginningDate())) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.GRANT_PERIOD_FROM, getDateTimeService().toDateString(award.getAwardBeginningDate()));
}
if (ObjectUtils.isNotNull(award.getAwardClosingDate())) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.GRANT_PERIOD_TO, getDateTimeService().toDateString(award.getAwardClosingDate()));
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH_RECEIPTS, contractsGrantsBillingUtilityService.formatForCurrency(this.getCashReceipts(award)));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.TOTAL_FEDERAL_FUNDS_AUTHORIZED, contractsGrantsBillingUtilityService.formatForCurrency(award.getAwardTotalAmount()));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.REPORTING_PERIOD_END_DATE, getReportingPeriodEndDate(reportingPeriod, year));
if (ObjectUtils.isNotNull(cashDisbursement)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH_DISBURSEMENTS, contractsGrantsBillingUtilityService.formatForCurrency(cashDisbursement));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH_ON_HAND, contractsGrantsBillingUtilityService.formatForCurrency(getCashReceipts(award).subtract(cashDisbursement)));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_SHARE_OF_EXPENDITURES, contractsGrantsBillingUtilityService.formatForCurrency(cashDisbursement));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.TOTAL_FEDERAL_SHARE, contractsGrantsBillingUtilityService.formatForCurrency(cashDisbursement));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.UNOBLIGATED_BALANCE_OF_FEDERAL_FUNDS, contractsGrantsBillingUtilityService.formatForCurrency(award.getAwardTotalAmount().subtract(cashDisbursement)));
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_SHARE_OF_UNLIQUIDATED_OBLIGATION, contractsGrantsBillingUtilityService.formatForCurrency(KualiDecimal.ZERO));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.TOTAL_FEDERAL_INCOME_EARNED, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INCOME_EXPENDED_DEDUCATION_ALTERNATIVE, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.INCOME_EXPENDED_ADDITION_ALTERNATIVE, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.UNEXPECTED_PROGRAM_INCOME, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.NAME, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.TELEPHONE, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.EMAIL_ADDRESS, KFSConstants.EMPTY_STRING);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.DATE_REPORT_SUBMITTED, getDateTimeService().toDateString(getDateTimeService().getCurrentDate()));
if (ArConstants.QUARTER1.equals(reportingPeriod) || ArConstants.QUARTER2.equals(reportingPeriod) || ArConstants.QUARTER3.equals(reportingPeriod) || ArConstants.QUARTER4.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.QUARTERLY, KFSConstants.OptionLabels.YES);
}
if (ArConstants.SEMI_ANNUAL.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.SEMI_ANNUAL, KFSConstants.OptionLabels.YES);
}
if (ArConstants.ANNUAL.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.ANNUAL, KFSConstants.OptionLabels.YES);
}
if (ArConstants.FINAL.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FINAL, KFSConstants.OptionLabels.YES);
}
String accountingBasis = parameterService.getParameterValueAsString(ArConstants.AR_NAMESPACE_CODE, KRADConstants.DetailTypes.ALL_DETAIL_TYPE, ArConstants.BASIS_OF_ACCOUNTING);
if (ArConstants.BASIS_OF_ACCOUNTING_CASH.equals(accountingBasis)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH, KFSConstants.OptionLabels.YES);
}
if (ArConstants.BASIS_OF_ACCOUNTING_ACCRUAL.equals(accountingBasis)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.ACCRUAL, KFSConstants.OptionLabels.YES);
}
}
/**
* Concatenates the address from an AR System Information object into a single String
* @param sysInfo the System Information business object to concatenate the address of
* @return the concatenated address
*/
protected String concatenateAddressFromSystemInformation(final SystemInformation sysInfo) {
String address = sysInfo.getOrganizationRemitToAddressName();
if(!StringUtils.isBlank(sysInfo.getOrganizationRemitToLine1StreetAddress())) {
address += ", " + sysInfo.getOrganizationRemitToLine1StreetAddress();
}
if(!StringUtils.isBlank(sysInfo.getOrganizationRemitToLine2StreetAddress())) {
address += ", " + sysInfo.getOrganizationRemitToLine2StreetAddress();
}
if(!StringUtils.isBlank(sysInfo.getOrganizationRemitToCityName())) {
address += ", " + sysInfo.getOrganizationRemitToCityName();
}
if(!StringUtils.isBlank(sysInfo.getOrganizationRemitToStateCode())) {
address += " " + sysInfo.getOrganizationRemitToStateCode();
}
if(!StringUtils.isBlank(sysInfo.getOrganizationRemitToZipCode())) {
address += "-" + sysInfo.getOrganizationRemitToZipCode();
}
return address;
}
/**
* Retrieves an AR System Information object for an award
* @param award the award to retrieve an associated System Information for
* @param year the year of the System Information object to retrieve
* @return the System Information object, or null if nothing is found
*/
protected SystemInformation retrieveSystemInformationForAward(ContractsAndGrantsBillingAward award, String year) {
Map primaryKeys = new HashMap<String, Object>();
primaryKeys.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, year);
primaryKeys.put(ArPropertyConstants.SystemInformationFields.PROCESSING_CHART_OF_ACCOUNTS_CODE, award.getPrimaryAwardOrganization().getChartOfAccountsCode());
primaryKeys.put(ArPropertyConstants.SystemInformationFields.PROCESSING_ORGANIZATION_CODE, award.getPrimaryAwardOrganization().getOrganizationCode());
SystemInformation sysInfo = businessObjectService.findByPrimaryKey(SystemInformation.class, primaryKeys);
return sysInfo;
}
/**
* This method is used to populate the replacement list to replace values from pdf template to actual values for Federal Form
* 425A
*
* @param awards
* @param reportingPeriod
* @param year
* @param agency
* @return total amount
*/
protected List<KualiDecimal> populateListByAgency(List<ContractsAndGrantsBillingAward> awards, String reportingPeriod, String year, ContractsAndGrantsBillingAgency agency) {
Map<String, String> replacementList = new HashMap<String, String>();
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.REPORTING_PERIOD_END_DATE, getReportingPeriodEndDate(reportingPeriod, year));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_AGENCY, agency.getFullName());
Map primaryKeys = new HashMap<String, Object>();
primaryKeys.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, year);
if (CollectionUtils.isNotEmpty(awards)){
primaryKeys.put(ArPropertyConstants.SystemInformationFields.PROCESSING_CHART_OF_ACCOUNTS_CODE, awards.get(0).getPrimaryAwardOrganization().getChartOfAccountsCode());
primaryKeys.put(ArPropertyConstants.SystemInformationFields.PROCESSING_ORGANIZATION_CODE, awards.get(0).getPrimaryAwardOrganization().getOrganizationCode());
}
SystemInformation sysInfo = businessObjectService.findByPrimaryKey(SystemInformation.class, primaryKeys);
if (ObjectUtils.isNotNull(sysInfo)) {
String address = concatenateAddressFromSystemInformation(sysInfo);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.RECIPIENT_ORGANIZATION, address);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.ZWEI, sysInfo.getUniversityFederalEmployerIdentificationNumber());
}
if (ArConstants.QUARTER1.equals(reportingPeriod) || ArConstants.QUARTER2.equals(reportingPeriod) || ArConstants.QUARTER3.equals(reportingPeriod) || ArConstants.QUARTER4.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.QUARTERLY, KFSConstants.OptionLabels.YES);
}
if (ArConstants.SEMI_ANNUAL.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.SEMI_ANNUAL, KFSConstants.OptionLabels.YES);
}
if (ArConstants.ANNUAL.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.ANNUAL, KFSConstants.OptionLabels.YES);
}
if (ArConstants.FINAL.equals(reportingPeriod)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FINAL, KFSConstants.OptionLabels.YES);
}
String accountingBasis = parameterService.getParameterValueAsString(ArConstants.AR_NAMESPACE_CODE, KRADConstants.DetailTypes.ALL_DETAIL_TYPE, ArConstants.BASIS_OF_ACCOUNTING);
if (ArConstants.BASIS_OF_ACCOUNTING_CASH.equals(accountingBasis)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH, KFSConstants.OptionLabels.YES);
}
if (ArConstants.BASIS_OF_ACCOUNTING_ACCRUAL.equals(accountingBasis)) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.ACCRUAL,KFSConstants.OptionLabels.YES);
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.DATE_REPORT_SUBMITTED, getDateTimeService().toDateString(new Date(new java.util.Date().getTime())));
KualiDecimal totalCashControl = KualiDecimal.ZERO;
KualiDecimal totalCashDisbursement = KualiDecimal.ZERO;
for (int i = 0; i < 30; i++) {
if (i < awards.size()) {
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_GRANT_NUMBER + " " + (i + 1), awards.get(i).getAwardDocumentNumber());
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.RECIPIENT_ACCOUNT_NUMBER + " " + (i + 1), awards.get(i).getActiveAwardAccounts().get(0).getAccountNumber());
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.FEDERAL_CASH_DISBURSEMENT + " " + (i + 1), contractsGrantsBillingUtilityService.formatForCurrency(getCashReceipts(awards.get(i))));
totalCashControl = totalCashControl.add(this.getCashReceipts(awards.get(i)));
for (ContractsAndGrantsBillingAwardAccount awardAccount : awards.get(i).getActiveAwardAccounts()) {
totalCashDisbursement = totalCashDisbursement.add(contractsGrantsInvoiceDocumentService.getBudgetAndActualsForAwardAccount(awardAccount, ArPropertyConstants.ACTUAL_BALANCE_TYPE, awards.get(i).getAwardBeginningDate()));
}
}
}
ArrayList<KualiDecimal> list = new ArrayList<KualiDecimal>();
list.add(totalCashControl);
list.add(totalCashDisbursement);
return list;
}
/**
* This method returns the last day of the given reporting period.
*
* @param reportingPeriod
* @param year
* @return
*/
protected String getReportingPeriodEndDate(String reportingPeriod, String year) {
Integer yearAsInt = Integer.parseInt(year);
java.util.Date endDate = null;
if (ArConstants.QUARTER1.equals(reportingPeriod)) {
endDate = ArConstants.BillingQuarterLastDays.FIRST_QUARTER.getDateForYear(yearAsInt);
}
else if (ArConstants.QUARTER2.equals(reportingPeriod) || ArConstants.SEMI_ANNUAL.equals(reportingPeriod)) {
endDate = ArConstants.BillingQuarterLastDays.SECOND_QUARTER.getDateForYear(yearAsInt);
}
else if (ArConstants.QUARTER3.equals(reportingPeriod)) {
endDate = ArConstants.BillingQuarterLastDays.THIRD_QUARTER.getDateForYear(yearAsInt);
}
else {
endDate = ArConstants.BillingQuarterLastDays.FOURTH_QUARTER.getDateForYear(yearAsInt);
}
return getDateTimeService().toDateString(endDate);
}
/**
* Use iText <code>{@link PdfStamper}</code> to stamp information into field values on a PDF Form Template.
*
* @param award The award the values will be pulled from.
* @param reportingPeriod
* @param year
* @param returnStream The output stream the federal form will be written to.
*/
protected void stampPdfFormValues425(ContractsAndGrantsBillingAward award, String reportingPeriod, String year, OutputStream returnStream, Map<String, String> replacementList) {
String reportTemplateName = ArConstants.FF_425_TEMPLATE_NM + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION;
try {
String federalReportTemplatePath = configService.getPropertyValueAsString(KFSConstants.EXTERNALIZABLE_HELP_URL_KEY);
populateListByAward(award, reportingPeriod, year, replacementList);
//final byte[] pdfBytes = renameFieldsIn(federalReportTemplatePath + reportTemplateName, replacementList);
URL template = new URL(federalReportTemplatePath + reportTemplateName);
final byte[] pdfBytes = PdfFormFillerUtil.populateTemplate(template.openStream(), replacementList);
returnStream.write(pdfBytes);
}
catch (IOException | DocumentException ex) {
throw new RuntimeException("Troubles stamping the old 425!", ex);
}
}
/**
* Use iText <code>{@link PdfStamper}</code> to stamp information into field values on a PDF Form Template.
*
* @param agency The award the values will be pulled from.
* @param reportingPeriod
* @param year
* @param returnStream The output stream the federal form will be written to.
*/
protected void stampPdfFormValues425A(ContractsAndGrantsBillingAgency agency, String reportingPeriod, String year, OutputStream returnStream, Map<String, String> replacementList) {
String federalReportTemplatePath = configService.getPropertyValueAsString(KFSConstants.EXTERNALIZABLE_HELP_URL_KEY);
try {
final String federal425ATemplateUrl = federalReportTemplatePath + ArConstants.FF_425A_TEMPLATE_NM + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION;
final String federal425TemplateUrl = federalReportTemplatePath + ArConstants.FF_425_TEMPLATE_NM + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION;
Map<String, Object> fieldValues = new HashMap<>();
fieldValues.put(KFSPropertyConstants.AGENCY_NUMBER, agency.getAgencyNumber());
fieldValues.put(KFSPropertyConstants.ACTIVE, Boolean.TRUE);
List<ContractsAndGrantsBillingAward> awards = kualiModuleService.getResponsibleModuleService(ContractsAndGrantsBillingAward.class).getExternalizableBusinessObjectsList(ContractsAndGrantsBillingAward.class, fieldValues);
Integer pageNumber = 1, totalPages;
totalPages = (awards.size() / ArConstants.Federal425APdf.NUMBER_OF_SUMMARIES_PER_PAGE) + 1;
PdfCopyFields copy = new PdfCopyFields(returnStream);
// generate replacement list for FF425
populateListByAgency(awards, reportingPeriod, year, agency);
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.TOTAL_PAGES, org.apache.commons.lang.ObjectUtils.toString(totalPages + 1));
KualiDecimal sumCashControl = KualiDecimal.ZERO;
KualiDecimal sumCumExp = KualiDecimal.ZERO;
while (pageNumber <= totalPages) {
List<ContractsAndGrantsBillingAward> awardsList = new ArrayList<ContractsAndGrantsBillingAward>();
for (int i = ((pageNumber - 1) * ArConstants.Federal425APdf.NUMBER_OF_SUMMARIES_PER_PAGE); i < (pageNumber * ArConstants.Federal425APdf.NUMBER_OF_SUMMARIES_PER_PAGE); i++) {
if (i < awards.size()) {
awardsList.add(awards.get(i));
}
}
// generate replacement list for FF425
List<KualiDecimal> list = populateListByAgency(awardsList, reportingPeriod, year, agency);
if (CollectionUtils.isNotEmpty(list)){
sumCashControl = sumCashControl.add(list.get(0));
if (list.size() > 1){
sumCumExp = sumCumExp.add(list.get(1));
}
}
// populate form with document values
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.PAGE_NUMBER, org.apache.commons.lang.ObjectUtils.toString(pageNumber + 1));
if (pageNumber == totalPages){
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.TOTAL, contractsGrantsBillingUtilityService.formatForCurrency(sumCashControl));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH_RECEIPTS, contractsGrantsBillingUtilityService.formatForCurrency(sumCashControl));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH_DISBURSEMENTS, contractsGrantsBillingUtilityService.formatForCurrency(sumCumExp));
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.CASH_ON_HAND, contractsGrantsBillingUtilityService.formatForCurrency(sumCashControl.subtract(sumCumExp)));
}
// add a document
copy.addDocument(new PdfReader(renameFieldsIn(federal425ATemplateUrl, replacementList)));
pageNumber++;
}
contractsGrantsBillingUtilityService.putValueOrEmptyString(replacementList, ArPropertyConstants.FederalFormReportFields.PAGE_NUMBER, "1");
// add the FF425 form.
copy.addDocument(new PdfReader(renameFieldsIn(federal425TemplateUrl, replacementList)));
// Close the PdfCopyFields object
copy.close();
}
catch (DocumentException | IOException ex) {
throw new RuntimeException("Tried to stamp the 425A, but couldn't do it. Just...just couldn't do it.", ex);
}
}
/**
*
* @param template the path to the original form
* @param list the replacement list
* @return
* @throws IOException
* @throws DocumentException
*/
protected byte[] renameFieldsIn(String template, Map<String, String> list) throws IOException, DocumentException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Create the stamper
PdfStamper stamper = new PdfStamper(new PdfReader(template), baos);
// Get the fields
AcroFields fields = stamper.getAcroFields();
// Loop over the fields
for (String field : list.keySet()) {
fields.setField(field, list.get(field));
}
// close the stamper
stamper.close();
return baos.toByteArray();
}
/**
* @see org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService#generateListOfInvoicesPdfToPrint(java.util.Collection)
*/
@Override
public byte[] combineInvoicePdfs(Collection<ContractsGrantsInvoiceDocument> list) throws DocumentException, IOException {
Date runDate = new Date(new java.util.Date().getTime());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
generateCombinedPdfForInvoices(list, baos);
return baos.toByteArray();
}
/**
* @see org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService#generateListOfInvoicesEnvelopesPdfToPrint(java.util.Collection)
*/
@Override
public byte[] combineInvoicePdfEnvelopes(Collection<ContractsGrantsInvoiceDocument> list) throws DocumentException, IOException {
Date runDate = new Date(new java.util.Date().getTime());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
generateCombinedPdfForEnvelopes(list, baos);
return baos.toByteArray();
}
/**
* Generates the pdf file for printing the invoices.
*
* @param list
* @param outputStream
* @throws DocumentException
* @throws IOException
*/
protected void generateCombinedPdfForInvoices(Collection<ContractsGrantsInvoiceDocument> list, OutputStream outputStream) throws DocumentException, IOException {
PdfCopyFields copy = new PdfCopyFields(outputStream);
boolean pageAdded = false;
for (ContractsGrantsInvoiceDocument invoice : list) {
// add a document
List<InvoiceAddressDetail> invoiceAddressDetails = invoice.getInvoiceAddressDetails();
for (InvoiceAddressDetail invoiceAddressDetail : invoiceAddressDetails) {
if (ArConstants.InvoiceTransmissionMethod.MAIL.equals(invoiceAddressDetail.getInvoiceTransmissionMethodCode())) {
CustomerAddress address = invoiceAddressDetail.getCustomerAddress();
Note note = noteService.getNoteByNoteId(invoiceAddressDetail.getNoteId());
Integer numberOfCopiesToPrint = address.getCustomerCopiesToPrint();
if (ObjectUtils.isNull(numberOfCopiesToPrint)) {
numberOfCopiesToPrint = 1;
}
if (!ObjectUtils.isNull(note)) {
for (int i = 0; i < numberOfCopiesToPrint; i++) {
if (!pageAdded) {
copy.open();
}
pageAdded = true;
copy.addDocument(new PdfReader(note.getAttachment().getAttachmentContents()));
}
}
}
}
invoice.setDateReportProcessed(new Date(new java.util.Date().getTime()));
documentService.updateDocument(invoice);
}
if (pageAdded) {
copy.close();
}
}
/**
* Generates the pdf file for printing the envelopes.
*
* @param list
* @param outputStream
* @throws DocumentException
* @throws IOException
*/
protected void generateCombinedPdfForEnvelopes(Collection<ContractsGrantsInvoiceDocument> list, OutputStream outputStream) throws DocumentException, IOException {
Document document = new Document(new Rectangle(ArConstants.InvoiceEnvelopePdf.LENGTH, ArConstants.InvoiceEnvelopePdf.WIDTH));
PdfWriter.getInstance(document, outputStream);
boolean pageAdded = false;
for (ContractsGrantsInvoiceDocument invoice : list) {
// add a document
List<InvoiceAddressDetail> agencyAddresses = invoice.getInvoiceAddressDetails();
for (InvoiceAddressDetail agencyAddress : agencyAddresses) {
if (ArConstants.InvoiceTransmissionMethod.MAIL.equals(agencyAddress.getInvoiceTransmissionMethodCode())) {
CustomerAddress address = agencyAddress.getCustomerAddress();
Integer numberOfEnvelopesToPrint = address.getCustomerPrintEnvelopesNumber();
if (ObjectUtils.isNull(numberOfEnvelopesToPrint)) {
numberOfEnvelopesToPrint = 1;
}
for (int i = 0; i < numberOfEnvelopesToPrint; i++) {
// if a page has not already been added then open the document.
if (!pageAdded) {
document.open();
}
pageAdded = true;
document.newPage();
Paragraph sendTo = new Paragraph();
Paragraph sentBy = new Paragraph();
sentBy.setIndentationLeft(ArConstants.InvoiceEnvelopePdf.INDENTATION_LEFT);
// adding the send To address
sendTo.add(new Paragraph(address.getCustomerAddressName(), ArConstants.PdfReportFonts.ENVELOPE_TITLE_FONT));
if (StringUtils.isNotEmpty(address.getCustomerLine1StreetAddress())) {
sendTo.add(new Paragraph(address.getCustomerLine1StreetAddress(), ArConstants.PdfReportFonts.ENVELOPE_TITLE_FONT));
}
if (StringUtils.isNotEmpty(address.getCustomerLine2StreetAddress())) {
sendTo.add(new Paragraph(address.getCustomerLine2StreetAddress(), ArConstants.PdfReportFonts.ENVELOPE_TITLE_FONT));
}
String string = "";
if (StringUtils.isNotEmpty(address.getCustomerCityName())) {
string += address.getCustomerCityName();
}
if (StringUtils.isNotEmpty(address.getCustomerStateCode())) {
string += ", " + address.getCustomerStateCode();
}
if (StringUtils.isNotEmpty(address.getCustomerZipCode())) {
string += "-" + address.getCustomerZipCode();
}
if (StringUtils.isNotEmpty(string)) {
sendTo.add(new Paragraph(string, ArConstants.PdfReportFonts.ENVELOPE_TITLE_FONT));
}
sendTo.setAlignment(Element.ALIGN_CENTER);
sendTo.add(new Paragraph(KFSConstants.BLANK_SPACE));
// adding the sent From address
Organization org = invoice.getAward().getPrimaryAwardOrganization().getOrganization();
sentBy.add(new Paragraph(org.getOrganizationName(), ArConstants.PdfReportFonts.ENVELOPE_SMALL_FONT));
if (StringUtils.isNotEmpty(org.getOrganizationLine1Address())) {
sentBy.add(new Paragraph(org.getOrganizationLine1Address(), ArConstants.PdfReportFonts.ENVELOPE_SMALL_FONT));
}
if (StringUtils.isNotEmpty(org.getOrganizationLine2Address())) {
sentBy.add(new Paragraph(org.getOrganizationLine2Address(), ArConstants.PdfReportFonts.ENVELOPE_SMALL_FONT));
}
string = "";
if (StringUtils.isNotEmpty(address.getCustomerCityName())) {
string += org.getOrganizationCityName();
}
if (StringUtils.isNotEmpty(address.getCustomerStateCode())) {
string += ", " + org.getOrganizationStateCode();
}
if (StringUtils.isNotEmpty(address.getCustomerZipCode())) {
string += "-" + org.getOrganizationZipCode();
}
if (StringUtils.isNotEmpty(string)) {
sentBy.add(new Paragraph(string, ArConstants.PdfReportFonts.ENVELOPE_SMALL_FONT));
}
sentBy.setAlignment(Element.ALIGN_LEFT);
document.add(sentBy);
document.add(sendTo);
}
}
}
}
if (pageAdded) {
document.close();
}
}
/**
* @see org.kuali.kfs.module.ar.report.service.ContractsGrantsInvoiceReportService#generateCSVToExport(org.kuali.kfs.module.ar.document.ContractsGrantsLOCReviewDocument)
*/
@Override
public byte[] convertLetterOfCreditReviewToCSV(ContractsGrantsLetterOfCreditReviewDocument LOCDocument) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(baos);
CSVWriter csvWriter = new CSVWriter(writer);
try {
csvWriter.writeNext(new String[] {getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.PROPOSAL_NUMBER),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.ReferralToCollectionsFields.AWARD_DOCUMENT_NUMBER),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_DESCRIPTION),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_NUMBER),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.ACCOUNT_EXPIRATION_DATE),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AWARD_BUDGET_AMOUNT),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.CLAIM_ON_CASH_BALANCE),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AMOUNT_TO_DRAW),
getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.FUNDS_NOT_DRAWN)});
if (CollectionUtils.isNotEmpty(LOCDocument.getHeaderReviewDetails()) && CollectionUtils.isNotEmpty(LOCDocument.getAccountReviewDetails())) {
for (ContractsGrantsLetterOfCreditReviewDetail item : LOCDocument.getHeaderReviewDetails()) {
String proposalNumber = org.apache.commons.lang.ObjectUtils.toString(item.getProposalNumber());
String awardDocumentNumber = org.apache.commons.lang.ObjectUtils.toString(item.getAwardDocumentNumber());
for (ContractsGrantsLetterOfCreditReviewDetail newItem : LOCDocument.getAccountReviewDetails()) {
if (org.apache.commons.lang.ObjectUtils.equals(item.getProposalNumber(), newItem.getProposalNumber())) {
csvWriter.writeNext(new String[] { proposalNumber,
awardDocumentNumber,
newItem.getAccountDescription(),
newItem.getChartOfAccountsCode(),
newItem.getAccountNumber(),
getDateTimeService().toDateString(newItem.getAccountExpirationDate()),
contractsGrantsBillingUtilityService.formatForCurrency(newItem.getAwardBudgetAmount()),
contractsGrantsBillingUtilityService.formatForCurrency(newItem.getClaimOnCashBalance()),
contractsGrantsBillingUtilityService.formatForCurrency(newItem.getAmountToDraw()),
contractsGrantsBillingUtilityService.formatForCurrency(newItem.getFundsNotDrawn()) });
}
}
}
}
}
finally {
if (csvWriter != null) {
try {
csvWriter.close();
}
catch (IOException ex) {
csvWriter = null;
throw new RuntimeException("problem during ContractsGrantsInvoiceReportServiceImpl.generateCSVToExport()", ex);
}
}
if (writer != null) {
try {
writer.flush();
writer.close();
}
catch (IOException ex) {
writer = null;
throw new RuntimeException("problem during ContractsGrantsInvoiceReportServiceImpl.generateCSVToExport()", ex);
}
}
}
return baos.toByteArray();
}
public PersonService getPersonService() {
return personService;
}
public void setPersonService(PersonService personService) {
this.personService = personService;
}
/**
* Gets the businessObjectService attribute.
*
* @return Returns the businessObjectService.
*/
public BusinessObjectService getBusinessObjectService() {
return businessObjectService;
}
/**
* Sets the businessObjectService attribute value.
*
* @param businessObjectService The businessObjectService to set.
*/
public void setBusinessObjectService(BusinessObjectService businessObjectService) {
this.businessObjectService = businessObjectService;
}
public ParameterService getParameterService() {
return parameterService;
}
public void setParameterService(ParameterService parameterService) {
this.parameterService = parameterService;
}
public void setConfigService(ConfigurationService configService) {
this.configService = configService;
}
/**
* Sets the kualiModuleService attribute value.
*
* @param kualiModuleService The kualiModuleService to set.
*/
@NonTransactional
public void setKualiModuleService(KualiModuleService kualiModuleService) {
this.kualiModuleService = kualiModuleService;
}
/**
* @return the documentService
*/
public DocumentService getDocumentService() {
return documentService;
}
/**
* @param documentService the documentService to set
*/
public void setDocumentService(DocumentService documentService) {
this.documentService = documentService;
}
public NoteService getNoteService() {
return noteService;
}
public void setNoteService(NoteService noteService) {
this.noteService = noteService;
}
public ReportInfo getReportInfo() {
return reportInfo;
}
public void setReportInfo(ReportInfo reportInfo) {
this.reportInfo = reportInfo;
}
public ReportGenerationService getReportGenerationService() {
return reportGenerationService;
}
public void setReportGenerationService(ReportGenerationService reportGenerationService) {
this.reportGenerationService = reportGenerationService;
}
public ContractsGrantsInvoiceDocumentService getContractsGrantsInvoiceDocumentService() {
return contractsGrantsInvoiceDocumentService;
}
public void setContractsGrantsInvoiceDocumentService(ContractsGrantsInvoiceDocumentService contractsGrantsInvoiceDocumentService) {
this.contractsGrantsInvoiceDocumentService = contractsGrantsInvoiceDocumentService;
}
public DateTimeService getDateTimeService() {
return dateTimeService;
}
public void setDateTimeService(DateTimeService dateTimeService) {
this.dateTimeService = dateTimeService;
}
public DataDictionaryService getDataDictionaryService() {
return dataDictionaryService;
}
public void setDataDictionaryService(DataDictionaryService dataDictionaryService) {
this.dataDictionaryService = dataDictionaryService;
}
public ContractsGrantsBillingUtilityService getContractsGrantsBillingUtilityService() {
return contractsGrantsBillingUtilityService;
}
public void setContractsGrantsBillingUtilityService(ContractsGrantsBillingUtilityService contractsGrantsBillingUtilityService) {
this.contractsGrantsBillingUtilityService = contractsGrantsBillingUtilityService;
}
} | KFSTI-364: refactor out address method, clarify naming of variables
| work/src/org/kuali/kfs/module/ar/report/service/impl/ContractsGrantsInvoiceReportServiceImpl.java | KFSTI-364: refactor out address method, clarify naming of variables | <ide><path>ork/src/org/kuali/kfs/module/ar/report/service/impl/ContractsGrantsInvoiceReportServiceImpl.java
<ide> import com.lowagie.text.Document;
<ide> import com.lowagie.text.DocumentException;
<ide> import com.lowagie.text.Element;
<add>import com.lowagie.text.Font;
<ide> import com.lowagie.text.Paragraph;
<ide> import com.lowagie.text.Rectangle;
<ide> import com.lowagie.text.pdf.AcroFields;
<ide>
<ide> for (InvoiceAddressDetail invoiceAddressDetail : invoiceAddressDetails) {
<ide> if (ArConstants.InvoiceTransmissionMethod.MAIL.equals(invoiceAddressDetail.getInvoiceTransmissionMethodCode())) {
<del> CustomerAddress address = invoiceAddressDetail.getCustomerAddress();
<del>
<ide> Note note = noteService.getNoteByNoteId(invoiceAddressDetail.getNoteId());
<del> Integer numberOfCopiesToPrint = address.getCustomerCopiesToPrint();
<add> Integer numberOfCopiesToPrint = invoiceAddressDetail.getCustomerAddress().getCustomerCopiesToPrint();
<ide> if (ObjectUtils.isNull(numberOfCopiesToPrint)) {
<ide> numberOfCopiesToPrint = 1;
<ide> }
<ide>
<ide> for (ContractsGrantsInvoiceDocument invoice : list) {
<ide> // add a document
<del> List<InvoiceAddressDetail> agencyAddresses = invoice.getInvoiceAddressDetails();
<del>
<del> for (InvoiceAddressDetail agencyAddress : agencyAddresses) {
<del> if (ArConstants.InvoiceTransmissionMethod.MAIL.equals(agencyAddress.getInvoiceTransmissionMethodCode())) {
<del> CustomerAddress address = agencyAddress.getCustomerAddress();
<add> for (InvoiceAddressDetail invoiceAddressDetail : invoice.getInvoiceAddressDetails()) {
<add> if (ArConstants.InvoiceTransmissionMethod.MAIL.equals(invoiceAddressDetail.getInvoiceTransmissionMethodCode())) {
<add> CustomerAddress address = invoiceAddressDetail.getCustomerAddress();
<ide>
<ide> Integer numberOfEnvelopesToPrint = address.getCustomerPrintEnvelopesNumber();
<ide> if (ObjectUtils.isNull(numberOfEnvelopesToPrint)) {
<ide> }
<ide> pageAdded = true;
<ide> document.newPage();
<del> Paragraph sendTo = new Paragraph();
<del> Paragraph sentBy = new Paragraph();
<add> // adding the sent From address
<add> Organization org = invoice.getAward().getPrimaryAwardOrganization().getOrganization();
<add> Paragraph sentBy = generateAddressParagraph(org.getOrganizationName(), org.getOrganizationLine1Address(), org.getOrganizationLine2Address(), org.getOrganizationCityName(), org.getOrganizationStateCode(), org.getOrganizationZipCode(), ArConstants.PdfReportFonts.ENVELOPE_SMALL_FONT);
<ide> sentBy.setIndentationLeft(ArConstants.InvoiceEnvelopePdf.INDENTATION_LEFT);
<add> sentBy.setAlignment(Element.ALIGN_LEFT);
<add>
<ide> // adding the send To address
<del> sendTo.add(new Paragraph(address.getCustomerAddressName(), ArConstants.PdfReportFonts.ENVELOPE_TITLE_FONT));
<del> if (StringUtils.isNotEmpty(address.getCustomerLine1StreetAddress())) {
<del> sendTo.add(new Paragraph(address.getCustomerLine1StreetAddress(), ArConstants.PdfReportFonts.ENVELOPE_TITLE_FONT));
<del> }
<del> if (StringUtils.isNotEmpty(address.getCustomerLine2StreetAddress())) {
<del> sendTo.add(new Paragraph(address.getCustomerLine2StreetAddress(), ArConstants.PdfReportFonts.ENVELOPE_TITLE_FONT));
<del> }
<del> String string = "";
<del> if (StringUtils.isNotEmpty(address.getCustomerCityName())) {
<del> string += address.getCustomerCityName();
<del> }
<del> if (StringUtils.isNotEmpty(address.getCustomerStateCode())) {
<del> string += ", " + address.getCustomerStateCode();
<del> }
<del> if (StringUtils.isNotEmpty(address.getCustomerZipCode())) {
<del> string += "-" + address.getCustomerZipCode();
<del> }
<del> if (StringUtils.isNotEmpty(string)) {
<del> sendTo.add(new Paragraph(string, ArConstants.PdfReportFonts.ENVELOPE_TITLE_FONT));
<del> }
<add> String string;
<add> Paragraph sendTo = generateAddressParagraph(address.getCustomerAddressName(), address.getCustomerLine1StreetAddress(), address.getCustomerLine2StreetAddress(), address.getCustomerCityName(), address.getCustomerStateCode(), address.getCustomerZipCode(), ArConstants.PdfReportFonts.ENVELOPE_TITLE_FONT);
<ide> sendTo.setAlignment(Element.ALIGN_CENTER);
<ide> sendTo.add(new Paragraph(KFSConstants.BLANK_SPACE));
<del>
<del> // adding the sent From address
<del> Organization org = invoice.getAward().getPrimaryAwardOrganization().getOrganization();
<del> sentBy.add(new Paragraph(org.getOrganizationName(), ArConstants.PdfReportFonts.ENVELOPE_SMALL_FONT));
<del> if (StringUtils.isNotEmpty(org.getOrganizationLine1Address())) {
<del> sentBy.add(new Paragraph(org.getOrganizationLine1Address(), ArConstants.PdfReportFonts.ENVELOPE_SMALL_FONT));
<del> }
<del> if (StringUtils.isNotEmpty(org.getOrganizationLine2Address())) {
<del> sentBy.add(new Paragraph(org.getOrganizationLine2Address(), ArConstants.PdfReportFonts.ENVELOPE_SMALL_FONT));
<del> }
<del> string = "";
<del> if (StringUtils.isNotEmpty(address.getCustomerCityName())) {
<del> string += org.getOrganizationCityName();
<del> }
<del> if (StringUtils.isNotEmpty(address.getCustomerStateCode())) {
<del> string += ", " + org.getOrganizationStateCode();
<del> }
<del> if (StringUtils.isNotEmpty(address.getCustomerZipCode())) {
<del> string += "-" + org.getOrganizationZipCode();
<del> }
<del> if (StringUtils.isNotEmpty(string)) {
<del> sentBy.add(new Paragraph(string, ArConstants.PdfReportFonts.ENVELOPE_SMALL_FONT));
<del> }
<del> sentBy.setAlignment(Element.ALIGN_LEFT);
<ide>
<ide> document.add(sentBy);
<ide> document.add(sendTo);
<ide> if (pageAdded) {
<ide> document.close();
<ide> }
<add> }
<add>
<add> /**
<add> * Generates a PDF paragraph for a given Address
<add> * @param name the name that this envelope is being sent to
<add> * @param line1Address the first line of the address
<add> * @param line2Address the second line of the address
<add> * @param cityName the name of the city to send this to
<add> * @param stateCode the code of the state or presumably province to send this to
<add> * @param postalCode the postal code/zip code to send the enveleope to
<add> * @param font the font to write in
<add> * @return a PDF Paragraph for the address
<add> */
<add> protected Paragraph generateAddressParagraph(String name, String line1Address, String line2Address, String cityName, String stateCode, String postalCode, Font font) {
<add> Paragraph addressParagraph = new Paragraph();
<add> addressParagraph.add(new Paragraph(name, font));
<add> if (!StringUtils.isBlank(line1Address)) {
<add> addressParagraph.add(new Paragraph(line1Address, font));
<add> }
<add> if (!StringUtils.isBlank(line2Address)) {
<add> addressParagraph.add(new Paragraph(line2Address, font));
<add> }
<add> String string = "";
<add> if (!StringUtils.isBlank(cityName)) {
<add> string += cityName;
<add> }
<add> if (!StringUtils.isBlank(stateCode)) {
<add> string += ", " + stateCode;
<add> }
<add> if (!StringUtils.isBlank(postalCode)) {
<add> string += "-" + postalCode;
<add> }
<add> if (!StringUtils.isBlank(string)) {
<add> addressParagraph.add(new Paragraph(string, font));
<add> }
<add> return addressParagraph;
<ide> }
<ide>
<ide> /** |
|
Java | mit | fbde00771e68a834f074c03324131dee5cf8d240 | 0 | Vlatombe/git-plugin,ialbors/git-plugin,MarkEWaite/git-plugin,martinda/git-plugin,ndeloof/git-plugin,mklein0/git-plugin,martinda/git-plugin,nordstrand/git-plugin,Talend/git-plugin,recena/git-plugin,jenkinsci/git-plugin,nordstrand/git-plugin,bjacklyn/git-plugin,v1v/git-plugin,recena/git-plugin,ldtkms/git-plugin,mlgiroux/git-plugin,Jellyvision/git-plugin,kzantow/git-plugin,kzantow/git-plugin,mlgiroux/git-plugin,nKey/git-plugin,jenkinsci/git-plugin,nKey/git-plugin,avdv/git-plugin,ndeloof/git-plugin,loomchild/git-plugin,bjacklyn/git-plugin,mlgiroux/git-plugin,MarkEWaite/git-plugin,ndeloof/git-plugin,avdv/git-plugin,ivan-fedorov/git-plugin,Nonymus/git-plugin,sgargan/git-plugin,v1v/git-plugin,loomchild/git-plugin,Vlatombe/git-plugin,KostyaSha/git-plugin,pauxus/git-plugin,kzantow/git-plugin,ydubreuil/git-plugin,jenkinsci/git-plugin,Talend/git-plugin,MarkEWaite/git-plugin,Nonymus/git-plugin,nKey/git-plugin,ivan-fedorov/git-plugin,jacob-keller/git-plugin,Vlatombe/git-plugin,Talend/git-plugin,recena/git-plugin,abaditsegay/git-plugin,bjacklyn/git-plugin,jacob-keller/git-plugin,ldtkms/git-plugin,ivan-fedorov/git-plugin,v1v/git-plugin,jenkinsci/git-plugin,Nonymus/git-plugin,jacob-keller/git-plugin,Deveo/git-plugin,mklein0/git-plugin,Jellyvision/git-plugin,pauxus/git-plugin,pauxus/git-plugin,nordstrand/git-plugin,ydubreuil/git-plugin,loomchild/git-plugin,abaditsegay/git-plugin,MarkEWaite/git-plugin,ldtkms/git-plugin,avdv/git-plugin,sgargan/git-plugin,abaditsegay/git-plugin,martinda/git-plugin,mklein0/git-plugin,sgargan/git-plugin,Jellyvision/git-plugin,Deveo/git-plugin,ialbors/git-plugin,KostyaSha/git-plugin,Deveo/git-plugin,ydubreuil/git-plugin | package hudson.plugins.git;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.Extension;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.model.AbstractModelObject;
import hudson.model.AbstractProject;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Item;
import hudson.model.UnprotectedRootAction;
import hudson.plugins.git.extensions.impl.IgnoreNotifyCommit;
import hudson.scm.SCM;
import hudson.security.ACL;
import hudson.triggers.SCMTrigger;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import jenkins.model.Jenkins;
import jenkins.triggers.SCMTriggerItem;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.apache.commons.lang.StringUtils;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.URIish;
import org.kohsuke.stapler.*;
/**
* Information screen for the use of Git in Hudson.
*/
@Extension
public class GitStatus extends AbstractModelObject implements UnprotectedRootAction {
public String getDisplayName() {
return "Git";
}
public String getSearchUrl() {
return getUrlName();
}
public String getIconFileName() {
// TODO
return null;
}
public String getUrlName() {
return "git";
}
public HttpResponse doNotifyCommit(@QueryParameter(required=true) String url,
@QueryParameter(required=false) String branches,
@QueryParameter(required=false) String sha1) throws ServletException, IOException {
URIish uri;
try {
uri = new URIish(url);
} catch (URISyntaxException e) {
return HttpResponses.error(SC_BAD_REQUEST, new Exception("Illegal URL: " + url, e));
}
branches = Util.fixEmptyAndTrim(branches);
String[] branchesArray;
if (branches == null) {
branchesArray = new String[0];
} else {
branchesArray = branches.split(",");
}
final List<ResponseContributor> contributors = new ArrayList<ResponseContributor>();
for (Listener listener : Jenkins.getInstance().getExtensionList(Listener.class)) {
contributors.addAll(listener.onNotifyCommit(uri, sha1, branchesArray));
}
return new HttpResponse() {
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node)
throws IOException, ServletException {
rsp.setStatus(SC_OK);
rsp.setContentType("text/plain");
for (ResponseContributor c : contributors) {
c.addHeaders(req, rsp);
}
PrintWriter w = rsp.getWriter();
for (ResponseContributor c : contributors) {
c.writeBody(req, rsp, w);
}
}
};
}
/**
* Used to test if what we have in the job configuration matches what was submitted to the notification endpoint.
* It is better to match loosely and wastes a few polling calls than to be pedantic and miss the push notification,
* especially given that Git tends to support multiple access protocols.
*/
public static boolean looselyMatches(URIish lhs, URIish rhs) {
return StringUtils.equals(lhs.getHost(),rhs.getHost())
&& StringUtils.equals(normalizePath(lhs.getPath()), normalizePath(rhs.getPath()));
}
private static String normalizePath(String path) {
if (path.startsWith("/")) path=path.substring(1);
if (path.endsWith("/")) path=path.substring(0,path.length()-1);
if (path.endsWith(".git")) path=path.substring(0,path.length()-4);
return path;
}
/**
* Contributes to a {@link #doNotifyCommit(String, String, String)} response.
*
* @since 1.4.1
*/
public static class ResponseContributor {
/**
* Add headers to the response.
*
* @param req the request.
* @param rsp the response.
* @since 1.4.1
*/
public void addHeaders(StaplerRequest req, StaplerResponse rsp) {
}
/**
* Write the contributed body.
*
* @param req the request.
* @param rsp the response.
* @param w the writer.
* @since 1.4.1
*/
public void writeBody(StaplerRequest req, StaplerResponse rsp, PrintWriter w) {
writeBody(w);
}
/**
* Write the contributed body.
*
* @param w the writer.
* @since 1.4.1
*/
public void writeBody(PrintWriter w) {
}
}
/**
* Other plugins may be interested in listening for these updates.
*
* @since 1.4.1
*/
public static abstract class Listener implements ExtensionPoint {
/**
* Called when there is a change notification on a specific repository url.
*
* @param uri the repository uri.
* @param branches the (optional) branch information.
* @return any response contributors for the response to the push request.
* @since 1.4.1
* @deprecated implement #onNotifyCommit(org.eclipse.jgit.transport.URIish, String, String...)
*/
public List<ResponseContributor> onNotifyCommit(URIish uri, String[] branches) {
return onNotifyCommit(uri, null, branches);
}
public List<ResponseContributor> onNotifyCommit(URIish uri, @Nullable String sha1, String... branches) {
return Collections.EMPTY_LIST;
}
}
/**
* Handle standard {@link SCMTriggerItem} instances with a standard {@link SCMTrigger}.
*
* @since 1.4.1
*/
@Extension
@SuppressWarnings("unused") // Jenkins extension
public static class JenkinsAbstractProjectListener extends Listener {
/**
* {@inheritDoc}
*/
@Override
public List<ResponseContributor> onNotifyCommit(URIish uri, String sha1, String... branches) {
List<ResponseContributor> result = new ArrayList<ResponseContributor>();
// run in high privilege to see all the projects anonymous users don't see.
// this is safe because when we actually schedule a build, it's a build that can
// happen at some random time anyway.
SecurityContext old = ACL.impersonate(ACL.SYSTEM);
try {
boolean scmFound = false,
urlFound = false;
for (final Item project : Jenkins.getInstance().getAllItems()) {
SCMTriggerItem scmTriggerItem = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(project);
if (project == null) {
continue;
}
SCMS: for (SCM scm : scmTriggerItem.getSCMs()) {
if (!(scm instanceof GitSCM)) {
continue;
}
GitSCM git = (GitSCM) scm;
scmFound = true;
for (RemoteConfig repository : git.getRepositories()) {
boolean repositoryMatches = false,
branchMatches = false;
for (URIish remoteURL : repository.getURIs()) {
if (looselyMatches(uri, remoteURL)) {
repositoryMatches = true;
break;
}
}
if (!repositoryMatches || git.getExtensions().get(IgnoreNotifyCommit.class)!=null) {
continue;
}
SCMTrigger trigger = scmTriggerItem.getSCMTrigger();
if (trigger != null && trigger.isIgnorePostCommitHooks()) {
LOGGER.info("PostCommitHooks are disabled on " + project.getFullDisplayName());
continue;
}
Boolean branchFound = false;
if (branches.length == 0) {
branchFound = true;
} else {
OUT: for (BranchSpec branchSpec : git.getBranches()) {
for (String branch : branches) {
if (branchSpec.matches(repository.getName() + "/" + branch)) {
branchFound = true;
break OUT;
}
}
}
}
if (!branchFound) continue;
urlFound = true;
if (!(project instanceof AbstractProject && ((AbstractProject) project).isDisabled())) {
if (isNotEmpty(sha1)) {
LOGGER.info("Scheduling " + project.getFullDisplayName() + " to build commit " + sha1);
scmTriggerItem.scheduleBuild2(scmTriggerItem.getQuietPeriod(),
new CauseAction(new CommitHookCause(sha1)),
new RevisionParameterAction(sha1));
result.add(new ScheduledResponseContributor(project));
} else if (trigger != null) {
LOGGER.info("Triggering the polling of " + project.getFullDisplayName());
trigger.run();
result.add(new PollingScheduledResponseContributor(project));
break SCMS; // no need to trigger the same project twice, so do not consider other GitSCMs in it
}
}
break;
}
}
}
if (!scmFound) {
result.add(new MessageResponseContributor("No git jobs found"));
} else if (!urlFound) {
result.add(new MessageResponseContributor(
"No git jobs using repository: " + uri.toString() + " and branches: " + StringUtils
.join(branches, ",")));
}
return result;
} finally {
SecurityContextHolder.setContext(old);
}
}
/**
* A response contributor for triggering polling of a project.
*
* @since 1.4.1
*/
private static class PollingScheduledResponseContributor extends ResponseContributor {
/**
* The project
*/
private final Item project;
/**
* Constructor.
*
* @param project the project.
*/
public PollingScheduledResponseContributor(Item project) {
this.project = project;
}
/**
* {@inheritDoc}
*/
@Override
public void addHeaders(StaplerRequest req, StaplerResponse rsp) {
rsp.addHeader("Triggered", project.getAbsoluteUrl());
}
/**
* {@inheritDoc}
*/
@Override
public void writeBody(PrintWriter w) {
w.println("Scheduled polling of " + project.getFullDisplayName());
}
}
private static class ScheduledResponseContributor extends ResponseContributor {
/**
* The project
*/
private final Item project;
/**
* Constructor.
*
* @param project the project.
*/
public ScheduledResponseContributor(Item project) {
this.project = project;
}
/**
* {@inheritDoc}
*/
@Override
public void addHeaders(StaplerRequest req, StaplerResponse rsp) {
rsp.addHeader("Triggered", project.getAbsoluteUrl());
}
/**
* {@inheritDoc}
*/
@Override
public void writeBody(PrintWriter w) {
w.println("Scheduled " + project.getFullDisplayName());
}
}
}
/**
* A response contributor that just adds a simple message to the body.
*
* @since 1.4.1
*/
public static class MessageResponseContributor extends ResponseContributor {
/**
* The message.
*/
private final String msg;
/**
* Constructor.
*
* @param msg the message.
*/
public MessageResponseContributor(String msg) {
this.msg = msg;
}
/**
* {@inheritDoc}
*/
@Override
public void writeBody(PrintWriter w) {
w.println(msg);
}
}
public static class CommitHookCause extends Cause {
public final String sha1;
public CommitHookCause(String sha1) {
this.sha1 = sha1;
}
@Override
public String getShortDescription() {
return "commit notification " + sha1;
}
}
private static final Logger LOGGER = Logger.getLogger(GitStatus.class.getName());
}
| src/main/java/hudson/plugins/git/GitStatus.java | package hudson.plugins.git;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.Extension;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.model.AbstractModelObject;
import hudson.model.AbstractProject;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Item;
import hudson.model.UnprotectedRootAction;
import hudson.plugins.git.extensions.impl.IgnoreNotifyCommit;
import hudson.scm.SCM;
import hudson.security.ACL;
import hudson.triggers.SCMTrigger;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import jenkins.model.Jenkins;
import jenkins.triggers.SCMTriggerItem;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.apache.commons.lang.StringUtils;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.URIish;
import org.kohsuke.stapler.*;
/**
* Information screen for the use of Git in Hudson.
*/
@Extension
public class GitStatus extends AbstractModelObject implements UnprotectedRootAction {
public String getDisplayName() {
return "Git";
}
public String getSearchUrl() {
return getUrlName();
}
public String getIconFileName() {
// TODO
return null;
}
public String getUrlName() {
return "git";
}
public HttpResponse doNotifyCommit(@QueryParameter(required=true) String url,
@QueryParameter(required=false) String branches,
@QueryParameter(required=false) String sha1) throws ServletException, IOException {
URIish uri;
try {
uri = new URIish(url);
} catch (URISyntaxException e) {
return HttpResponses.error(SC_BAD_REQUEST, new Exception("Illegal URL: " + url, e));
}
branches = Util.fixEmptyAndTrim(branches);
String[] branchesArray;
if (branches == null) {
branchesArray = new String[0];
} else {
branchesArray = branches.split(",");
}
final List<ResponseContributor> contributors = new ArrayList<ResponseContributor>();
for (Listener listener : Jenkins.getInstance().getExtensionList(Listener.class)) {
contributors.addAll(listener.onNotifyCommit(uri, sha1, branchesArray));
}
return new HttpResponse() {
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node)
throws IOException, ServletException {
rsp.setStatus(SC_OK);
rsp.setContentType("text/plain");
for (ResponseContributor c : contributors) {
c.addHeaders(req, rsp);
}
PrintWriter w = rsp.getWriter();
for (ResponseContributor c : contributors) {
c.writeBody(req, rsp, w);
}
}
};
}
/**
* Used to test if what we have in the job configuration matches what was submitted to the notification endpoint.
* It is better to match loosely and wastes a few polling calls than to be pedantic and miss the push notification,
* especially given that Git tends to support multiple access protocols.
*/
public static boolean looselyMatches(URIish lhs, URIish rhs) {
return StringUtils.equals(lhs.getHost(),rhs.getHost())
&& StringUtils.equals(normalizePath(lhs.getPath()), normalizePath(rhs.getPath()));
}
private static String normalizePath(String path) {
if (path.startsWith("/")) path=path.substring(1);
if (path.endsWith("/")) path=path.substring(0,path.length()-1);
if (path.endsWith(".git")) path=path.substring(0,path.length()-4);
return path;
}
/**
* Contributes to a {@link #doNotifyCommit(String, String, String)} response.
*
* @since 1.4.1
*/
public static class ResponseContributor {
/**
* Add headers to the response.
*
* @param req the request.
* @param rsp the response.
* @since 1.4.1
*/
public void addHeaders(StaplerRequest req, StaplerResponse rsp) {
}
/**
* Write the contributed body.
*
* @param req the request.
* @param rsp the response.
* @param w the writer.
* @since 1.4.1
*/
public void writeBody(StaplerRequest req, StaplerResponse rsp, PrintWriter w) {
writeBody(w);
}
/**
* Write the contributed body.
*
* @param w the writer.
* @since 1.4.1
*/
public void writeBody(PrintWriter w) {
}
}
/**
* Other plugins may be interested in listening for these updates.
*
* @since 1.4.1
*/
public static abstract class Listener implements ExtensionPoint {
/**
* Called when there is a change notification on a specific repository url.
*
* @param uri the repository uri.
* @param branches the (optional) branch information.
* @return any response contributors for the response to the push request.
* @since 1.4.1
* @deprecated implement #onNotifyCommit(org.eclipse.jgit.transport.URIish, String, String...)
*/
public List<ResponseContributor> onNotifyCommit(URIish uri, String[] branches) {
return onNotifyCommit(uri, null, branches);
}
public List<ResponseContributor> onNotifyCommit(URIish uri, @Nullable String sha1, String... branches) {
return Collections.EMPTY_LIST;
}
}
/**
* Handle standard {@link AbstractProject} instances with a standard {@link SCMTrigger}.
*
* @since 1.4.1
*/
@Extension
@SuppressWarnings("unused") // Jenkins extension
public static class JenkinsAbstractProjectListener extends Listener {
/**
* {@inheritDoc}
*/
@Override
public List<ResponseContributor> onNotifyCommit(URIish uri, String sha1, String... branches) {
List<ResponseContributor> result = new ArrayList<ResponseContributor>();
// run in high privilege to see all the projects anonymous users don't see.
// this is safe because when we actually schedule a build, it's a build that can
// happen at some random time anyway.
SecurityContext old = ACL.impersonate(ACL.SYSTEM);
try {
boolean scmFound = false,
urlFound = false;
for (final Item project : Jenkins.getInstance().getAllItems()) {
SCMTriggerItem scmTriggerItem = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(project);
if (project == null) {
continue;
}
for (SCM scm : scmTriggerItem.getSCMs()) {
if (!(scm instanceof GitSCM)) {
continue;
}
GitSCM git = (GitSCM) scm;
scmFound = true;
for (RemoteConfig repository : git.getRepositories()) {
boolean repositoryMatches = false,
branchMatches = false;
for (URIish remoteURL : repository.getURIs()) {
if (looselyMatches(uri, remoteURL)) {
repositoryMatches = true;
break;
}
}
if (!repositoryMatches || git.getExtensions().get(IgnoreNotifyCommit.class)!=null) {
continue;
}
SCMTrigger trigger = scmTriggerItem.getSCMTrigger();
if (trigger != null && trigger.isIgnorePostCommitHooks()) {
LOGGER.info("PostCommitHooks are disabled on " + project.getFullDisplayName());
continue;
}
Boolean branchFound = false;
if (branches.length == 0) {
branchFound = true;
} else {
OUT: for (BranchSpec branchSpec : git.getBranches()) {
for (String branch : branches) {
if (branchSpec.matches(repository.getName() + "/" + branch)) {
branchFound = true;
break OUT;
}
}
}
}
if (!branchFound) continue;
urlFound = true;
if (!(project instanceof AbstractProject && ((AbstractProject) project).isDisabled())) {
if (isNotEmpty(sha1)) {
LOGGER.info("Scheduling " + project.getFullDisplayName() + " to build commit " + sha1);
scmTriggerItem.scheduleBuild2(scmTriggerItem.getQuietPeriod(),
new CauseAction(new CommitHookCause(sha1)),
new RevisionParameterAction(sha1));
result.add(new ScheduledResponseContributor(project));
} else if (trigger != null) {
LOGGER.info("Triggering the polling of " + project.getFullDisplayName());
trigger.run();
result.add(new PollingScheduledResponseContributor(project));
}
}
break;
}
}
}
if (!scmFound) {
result.add(new MessageResponseContributor("No git jobs found"));
} else if (!urlFound) {
result.add(new MessageResponseContributor(
"No git jobs using repository: " + uri.toString() + " and branches: " + StringUtils
.join(branches, ",")));
}
return result;
} finally {
SecurityContextHolder.setContext(old);
}
}
/**
* A response contributor for triggering polling of a project.
*
* @since 1.4.1
*/
private static class PollingScheduledResponseContributor extends ResponseContributor {
/**
* The project
*/
private final Item project;
/**
* Constructor.
*
* @param project the project.
*/
public PollingScheduledResponseContributor(Item project) {
this.project = project;
}
/**
* {@inheritDoc}
*/
@Override
public void addHeaders(StaplerRequest req, StaplerResponse rsp) {
rsp.addHeader("Triggered", project.getAbsoluteUrl());
}
/**
* {@inheritDoc}
*/
@Override
public void writeBody(PrintWriter w) {
w.println("Scheduled polling of " + project.getFullDisplayName());
}
}
private static class ScheduledResponseContributor extends ResponseContributor {
/**
* The project
*/
private final Item project;
/**
* Constructor.
*
* @param project the project.
*/
public ScheduledResponseContributor(Item project) {
this.project = project;
}
/**
* {@inheritDoc}
*/
@Override
public void addHeaders(StaplerRequest req, StaplerResponse rsp) {
rsp.addHeader("Triggered", project.getAbsoluteUrl());
}
/**
* {@inheritDoc}
*/
@Override
public void writeBody(PrintWriter w) {
w.println("Scheduled " + project.getFullDisplayName());
}
}
}
/**
* A response contributor that just adds a simple message to the body.
*
* @since 1.4.1
*/
public static class MessageResponseContributor extends ResponseContributor {
/**
* The message.
*/
private final String msg;
/**
* Constructor.
*
* @param msg the message.
*/
public MessageResponseContributor(String msg) {
this.msg = msg;
}
/**
* {@inheritDoc}
*/
@Override
public void writeBody(PrintWriter w) {
w.println(msg);
}
}
public static class CommitHookCause extends Cause {
public final String sha1;
public CommitHookCause(String sha1) {
this.sha1 = sha1;
}
@Override
public String getShortDescription() {
return "commit notification " + sha1;
}
}
private static final Logger LOGGER = Logger.getLogger(GitStatus.class.getName());
}
| Should trigger polling at most once per project. | src/main/java/hudson/plugins/git/GitStatus.java | Should trigger polling at most once per project. | <ide><path>rc/main/java/hudson/plugins/git/GitStatus.java
<ide> }
<ide>
<ide> /**
<del> * Handle standard {@link AbstractProject} instances with a standard {@link SCMTrigger}.
<add> * Handle standard {@link SCMTriggerItem} instances with a standard {@link SCMTrigger}.
<ide> *
<ide> * @since 1.4.1
<ide> */
<ide> if (project == null) {
<ide> continue;
<ide> }
<del> for (SCM scm : scmTriggerItem.getSCMs()) {
<add> SCMS: for (SCM scm : scmTriggerItem.getSCMs()) {
<ide> if (!(scm instanceof GitSCM)) {
<ide> continue;
<ide> }
<ide> LOGGER.info("Triggering the polling of " + project.getFullDisplayName());
<ide> trigger.run();
<ide> result.add(new PollingScheduledResponseContributor(project));
<add> break SCMS; // no need to trigger the same project twice, so do not consider other GitSCMs in it
<ide> }
<ide> }
<ide> break; |
|
Java | bsd-3-clause | 6d7d1b0845da1ec27c95f4db394bdc65165a2a8f | 0 | eugen-eugen/eugensjbehave,kops/jbehave-core,donsenior/jbehave-core,valfirst/jbehave-core,gmandnepr/jbehave-core,sischnei/jbehave-core,irfanah/jbehave-core,pocamin/jbehave-core,valfirst/jbehave-core,bsaylor/jbehave-core,sischnei/jbehave-core,mestihudson/jbehave-core,jbehave/jbehave-core,eugen-eugen/eugensjbehave,valfirst/jbehave-core,eugen-eugen/eugensjbehave,irfanah/jbehave-core,jbehave/jbehave-core,mestihudson/jbehave-core,codehaus/jbehave-core,mhariri/jbehave-core,sischnei/jbehave-core,sischnei/jbehave-core,bsaylor/jbehave-core,gmandnepr/jbehave-core,pocamin/jbehave-core,jeremiehuchet/jbehave-core,pocamin/jbehave-core,kops/jbehave-core,mhariri/jbehave-core,skundrik/jbehave-core,jbehave/jbehave-core,irfanah/jbehave-core,eugen-eugen/eugensjbehave,eugen-eugen/eugensjbehave,codehaus/jbehave-core,jeremiehuchet/jbehave-core,mestihudson/jbehave-core,gmandnepr/jbehave-core,skundrik/jbehave-core,skundrik/jbehave-core,valfirst/jbehave-core,jeremiehuchet/jbehave-core,codehaus/jbehave-core,mestihudson/jbehave-core,donsenior/jbehave-core,eugen-eugen/eugensjbehave,mhariri/jbehave-core,codehaus/jbehave-core,irfanah/jbehave-core,irfanah/jbehave-core,mestihudson/jbehave-core,sischnei/jbehave-core,codehaus/jbehave-core,bsaylor/jbehave-core,jbehave/jbehave-core,kops/jbehave-core,donsenior/jbehave-core | package org.jbehave.core.failures;
import java.util.HashMap;
@SuppressWarnings("serial")
public class BatchFailures extends HashMap<String,Throwable> {
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
for (String name : keySet()) {
Throwable cause = get(name);
sb.append("\n");
sb.append(name);
sb.append(": ");
sb.append((cause != null && cause.getMessage() != null) ? cause.getMessage() : "N/A");
}
return sb.toString();
}
} | jbehave-core/src/main/java/org/jbehave/core/failures/BatchFailures.java | package org.jbehave.core.failures;
import java.util.HashMap;
@SuppressWarnings("serial")
public class BatchFailures extends HashMap<String,Throwable> {
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
for (String name : keySet()) {
Throwable cause = get(name);
sb.append("\n");
sb.append(name);
sb.append(": ");
sb.append(cause.getMessage() != null ? cause.getMessage() : "N/A");
}
return sb.toString();
}
} | JBEHAVE-580: fix NPE in BatchFailures
| jbehave-core/src/main/java/org/jbehave/core/failures/BatchFailures.java | JBEHAVE-580: fix NPE in BatchFailures | <ide><path>behave-core/src/main/java/org/jbehave/core/failures/BatchFailures.java
<ide> sb.append("\n");
<ide> sb.append(name);
<ide> sb.append(": ");
<del> sb.append(cause.getMessage() != null ? cause.getMessage() : "N/A");
<add> sb.append((cause != null && cause.getMessage() != null) ? cause.getMessage() : "N/A");
<ide> }
<ide> return sb.toString();
<ide> } |
|
Java | apache-2.0 | dcdd8c9b4daf085fd5eb01da6f85d1cdd2afae29 | 0 | evanchooly/morphia,evanchooly/morphia | package com.google.code.morphia.query;
import org.bson.types.CodeWScope;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.ReadPreference;
/**
* @author Scott Hernandez
*/
public interface Query<T> extends QueryResults<T>, Cloneable {
/**
* <p>Create a filter based on the specified condition and value. </p>
* <p><b>Note</b>: Property is in the form of "name op" ("age >").</p>
* <p>Valid operators are ["=", "==","!=", "<>", ">", "<", ">=", "<=", "in", "nin", "all", "size", "exists"] </p>
* <p>Examples:</p>
* <p/>
* <ul>
* <li>{@code filter("yearsOfOperation >", 5)}</li>
* <li>{@code filter("rooms.maxBeds >=", 2)}</li>
* <li>{@code filter("rooms.bathrooms exists", 1)}</li>
* <li>{@code filter("stars in", new Long[]{3, 4}) //3 and 4 stars (midrange?)}</li>
* <li>{@code filter("quantity mod", new Long[]{4, 0}) // customers ordered in packs of 4)}</li>
* <li>{@code filter("age >=", age)}</li>
* <li>{@code filter("age =", age)}</li>
* <li>{@code filter("age", age)} (if no operator, = is assumed)</li>
* <li>{@code filter("age !=", age)}</li>
* <li>{@code filter("age in", ageList)}</li>
* <li>{@code filter("customers.loyaltyYears in", yearsList)}</li>
* </ul>
* <p/>
* <p>You can filter on id properties <strong>if</strong> this query is restricted to a Class<T>.
*/
Query<T> filter(String condition, Object value);
/**
* Fluent query interface: {@code createQuery(Ent.class).field("count").greaterThan(7)...}
*/
FieldEnd<? extends Query<T>> field(String field);
/**
* Criteria builder interface
*/
FieldEnd<? extends CriteriaContainerImpl> criteria(String field);
CriteriaContainer and(Criteria... criteria);
CriteriaContainer or(Criteria... criteria);
/**
* Limit the query using this javascript block; only one per query
*/
Query<T> where(String js);
/**
* Limit the query using this javascript block; only one per query
*/
Query<T> where(CodeWScope js);
/**
* <p>Sorts based on a property (defines return order). Examples:</p>
* <p/>
* <ul> <li>{@code order("age")}</li> <li>{@code order("-age")} (descending order)</li> <li>{@code order("age, date")}</li> <li>{@code
* order("age,-date")} (age ascending, date descending)</li> </ul>
*/
Query<T> order(String condition);
/**
* Limit the fetched result set to a certain number of values.
*
* @param value must be >= 0. A value of 0 indicates no limit.
*/
Query<T> limit(int value);
/**
* Batch-size of the fetched result (cursor).
*
* @param value must be >= 0. A value of 0 indicates the server default.
*/
Query<T> batchSize(int value);
/**
* Starts the query results at a particular zero-based offset.
*
* @param value must be >= 0
*/
Query<T> offset(int value);
/**
*
* @param value
* @return
* @deprecated use @{link #offset(int)} instead
*/
Query<T> skip(int value);
/**
* Turns on validation (for all calls made after); by default validation is on
*/
Query<T> enableValidation();
/**
* Turns off validation (for all calls made after)
*/
Query<T> disableValidation();
/**
* Hints as to which index should be used.
*/
Query<T> hintIndex(String idxName);
/**
* Limits the fields retrieved
*/
Query<T> retrievedFields(boolean include, String... fields);
/**
* Limits the fields retrieved to those of the query type -- dangerous with interfaces and abstract classes
*/
Query<T> retrieveKnownFields();
/**
* Enabled snapshotted mode where duplicate results (which may be updated during the lifetime of the cursor) will not be returned. Not
* compatible with order/sort and hint. *
*/
Query<T> enableSnapshotMode();
/**
* Disable snapshotted mode (default mode). This will be faster but changes made during the cursor may cause duplicates. *
*/
Query<T> disableSnapshotMode();
/**
* Route query to non-primary node
*/
Query<T> queryNonPrimary();
/**
* Route query to primary node
*/
Query<T> queryPrimaryOnly();
/**
* Route query ReadPreference
*/
Query<T> useReadPreference(ReadPreference readPref);
/**
* Disables cursor timeout on server.
*/
Query<T> disableCursorTimeout();
/**
* Enables cursor timeout on server.
*/
Query<T> enableCursorTimeout();
/**
* <p>Generates a string that consistently and uniquely specifies this query. There is no way to convert this string back into a query
* and there is no guarantee that the string will be consistent across versions.</p> <p/> <p>In particular, this value is useful as a key
* for a simple memcache query cache.</p>
*/
String toString();
/**
* Returns the entity {@link Class}.
*/
Class<T> getEntityClass();
/**
* Returns the offset.
*
* @see #offset(int)
*/
int getOffset();
/**
* Returns the limit
*
* @see #limit(int)
*/
int getLimit();
/**
* Returns the batch size
*
* @see #batchSize(int)
*/
int getBatchSize();
/**
* Returns the Mongo query {@link DBObject}.
*/
DBObject getQueryObject();
/**
* Returns the Mongo sort {@link DBObject}.
*/
DBObject getSortObject();
/**
* Returns the Mongo fields {@link DBObject}.
*/
DBObject getFieldsObject();
/**
* Returns the {@link DBCollection} of the {@link Query}.
*/
DBCollection getCollection();
/**
* Creates and returns a copy of this {@link Query}.
*/
Query<T> clone();
} | morphia/src/main/java/com/google/code/morphia/query/Query.java | package com.google.code.morphia.query;
import org.bson.types.CodeWScope;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.ReadPreference;
/**
* @author Scott Hernandez
*/
public interface Query<T> extends QueryResults<T>, Cloneable {
/**
* <p>Create a filter based on the specified condition and value. </p>
* <p><b>Note</b>: Property is in the form of "name op" ("age >").</p>
* <p>Valid operators are ["=", "==","!=", "<>", ">", "<", ">=", "<=", "in", "nin", "all", "size", "exists"] </p>
* <p>Examples:</p>
* <p/>
* <ul>
* <li>{@code filter("yearsOfOperation >", 5)}</li>
* <li>{@code filter("rooms.maxBeds >=", 2)}</li>
* <li>{@code filter("rooms.bathrooms exists", 1)}</li>
* <li>{@code filter("stars in", new Long[]{3, 4}) //3 and 4 stars (midrange?)}</li>
* <li>{@code filter("age >=", age)}</li>
* <li>{@code filter("age =", age)}</li>
* <li>{@code filter("age", age)} (if no operator, = is assumed)</li>
* <li>{@code filter("age !=", age)}</li>
* <li>{@code filter("age in", ageList)}</li>
* <li>{@code filter("customers.loyaltyYears in", yearsList)}</li>
* </ul>
* <p/>
* <p>You can filter on id properties <strong>if</strong> this query is restricted to a Class<T>.
*/
Query<T> filter(String condition, Object value);
/**
* Fluent query interface: {@code createQuery(Ent.class).field("count").greaterThan(7)...}
*/
FieldEnd<? extends Query<T>> field(String field);
/**
* Criteria builder interface
*/
FieldEnd<? extends CriteriaContainerImpl> criteria(String field);
CriteriaContainer and(Criteria... criteria);
CriteriaContainer or(Criteria... criteria);
/**
* Limit the query using this javascript block; only one per query
*/
Query<T> where(String js);
/**
* Limit the query using this javascript block; only one per query
*/
Query<T> where(CodeWScope js);
/**
* <p>Sorts based on a property (defines return order). Examples:</p>
* <p/>
* <ul> <li>{@code order("age")}</li> <li>{@code order("-age")} (descending order)</li> <li>{@code order("age, date")}</li> <li>{@code
* order("age,-date")} (age ascending, date descending)</li> </ul>
*/
Query<T> order(String condition);
/**
* Limit the fetched result set to a certain number of values.
*
* @param value must be >= 0. A value of 0 indicates no limit.
*/
Query<T> limit(int value);
/**
* Batch-size of the fetched result (cursor).
*
* @param value must be >= 0. A value of 0 indicates the server default.
*/
Query<T> batchSize(int value);
/**
* Starts the query results at a particular zero-based offset.
*
* @param value must be >= 0
*/
Query<T> offset(int value);
/**
*
* @param value
* @return
* @deprecated use @{link #offset(int)} instead
*/
Query<T> skip(int value);
/**
* Turns on validation (for all calls made after); by default validation is on
*/
Query<T> enableValidation();
/**
* Turns off validation (for all calls made after)
*/
Query<T> disableValidation();
/**
* Hints as to which index should be used.
*/
Query<T> hintIndex(String idxName);
/**
* Limits the fields retrieved
*/
Query<T> retrievedFields(boolean include, String... fields);
/**
* Limits the fields retrieved to those of the query type -- dangerous with interfaces and abstract classes
*/
Query<T> retrieveKnownFields();
/**
* Enabled snapshotted mode where duplicate results (which may be updated during the lifetime of the cursor) will not be returned. Not
* compatible with order/sort and hint. *
*/
Query<T> enableSnapshotMode();
/**
* Disable snapshotted mode (default mode). This will be faster but changes made during the cursor may cause duplicates. *
*/
Query<T> disableSnapshotMode();
/**
* Route query to non-primary node
*/
Query<T> queryNonPrimary();
/**
* Route query to primary node
*/
Query<T> queryPrimaryOnly();
/**
* Route query ReadPreference
*/
Query<T> useReadPreference(ReadPreference readPref);
/**
* Disables cursor timeout on server.
*/
Query<T> disableCursorTimeout();
/**
* Enables cursor timeout on server.
*/
Query<T> enableCursorTimeout();
/**
* <p>Generates a string that consistently and uniquely specifies this query. There is no way to convert this string back into a query
* and there is no guarantee that the string will be consistent across versions.</p> <p/> <p>In particular, this value is useful as a key
* for a simple memcache query cache.</p>
*/
String toString();
/**
* Returns the entity {@link Class}.
*/
Class<T> getEntityClass();
/**
* Returns the offset.
*
* @see #offset(int)
*/
int getOffset();
/**
* Returns the limit
*
* @see #limit(int)
*/
int getLimit();
/**
* Returns the batch size
*
* @see #batchSize(int)
*/
int getBatchSize();
/**
* Returns the Mongo query {@link DBObject}.
*/
DBObject getQueryObject();
/**
* Returns the Mongo sort {@link DBObject}.
*/
DBObject getSortObject();
/**
* Returns the Mongo fields {@link DBObject}.
*/
DBObject getFieldsObject();
/**
* Returns the {@link DBCollection} of the {@link Query}.
*/
DBCollection getCollection();
/**
* Creates and returns a copy of this {@link Query}.
*/
Query<T> clone();
} | add mod to list of filters
| morphia/src/main/java/com/google/code/morphia/query/Query.java | add mod to list of filters | <ide><path>orphia/src/main/java/com/google/code/morphia/query/Query.java
<ide> * <li>{@code filter("rooms.maxBeds >=", 2)}</li>
<ide> * <li>{@code filter("rooms.bathrooms exists", 1)}</li>
<ide> * <li>{@code filter("stars in", new Long[]{3, 4}) //3 and 4 stars (midrange?)}</li>
<add> * <li>{@code filter("quantity mod", new Long[]{4, 0}) // customers ordered in packs of 4)}</li>
<ide> * <li>{@code filter("age >=", age)}</li>
<ide> * <li>{@code filter("age =", age)}</li>
<ide> * <li>{@code filter("age", age)} (if no operator, = is assumed)</li> |
|
Java | bsd-3-clause | 096763fcec2e92b6b122df386528355bb699fa66 | 0 | NCIP/cagrid,NCIP/cagrid,NCIP/cagrid,NCIP/cagrid | package gov.nih.nci.cagrid.introduce.security.service;
import gov.nih.nci.cagrid.common.FaultHelper;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.metadata.security.ServiceSecurityMetadata;
import java.io.File;
import java.rmi.RemoteException;
import javax.naming.InitialContext;
import javax.xml.namespace.QName;
import org.apache.axis.MessageContext;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.globus.wsrf.Constants;
import org.globus.wsrf.config.ContainerConfig;
import org.globus.wsrf.utils.AddressingUtils;
/**
* gov.nih.nci.cagrid.introduce.securityI TODO:DOCUMENT ME
*
* @created by Introduce Toolkit version 1.0
*/
public class ServiceSecurityImpl {
private ServiceConfiguration configuration;
private ServiceSecurityMetadata metadata;
public ServiceSecurityImpl() throws RemoteException {
try {
EndpointReferenceType type = AddressingUtils.createEndpointReference(null);
String configFileEnd = (String)MessageContext.getCurrentContext().getProperty("securityMetadata");
String configFile = ContainerConfig.getBaseDirectory() + File.separator+configFileEnd;
File f = new File(configFile);
if(!f.exists()){
throw new RemoteException("The security metadata file ("+configFile+") could not be found!!!");
}
metadata = (ServiceSecurityMetadata) Utils.deserializeDocument(configFile, ServiceSecurityMetadata.class);
} catch (Exception e) {
FaultHelper.printStackTrace(e);
throw new RemoteException(Utils.getExceptionMessage(e));
}
}
public ServiceConfiguration getConfiguration() throws Exception {
if (this.configuration != null) {
return this.configuration;
}
MessageContext ctx = MessageContext.getCurrentContext();
String servicePath = ctx.getTargetService();
String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/serviceconfiguration";
try {
javax.naming.Context initialContext = new InitialContext();
this.configuration = (ServiceConfiguration) initialContext.lookup(jndiName);
} catch (Exception e) {
throw new Exception("Unable to instantiate service configuration.", e);
}
return this.configuration;
}
public gov.nih.nci.cagrid.metadata.security.ServiceSecurityMetadata getServiceSecurityMetadata()
throws RemoteException {
return metadata;
}
}
| cagrid-1-0/caGrid/projects/introduce/operationProviders/ServiceSecurity/src/gov/nih/nci/cagrid/introduce/security/service/ServiceSecurityImpl.java | package gov.nih.nci.cagrid.introduce.security.service;
import gov.nih.nci.cagrid.common.FaultHelper;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.dorian.service.Dorian;
import gov.nih.nci.cagrid.metadata.security.ServiceSecurityMetadata;
import gov.nih.nci.cagrid.syncgts.bean.SyncReport;
import java.io.File;
import java.rmi.RemoteException;
import javax.naming.InitialContext;
import javax.xml.namespace.QName;
import org.apache.axis.MessageContext;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.globus.wsrf.Constants;
import org.globus.wsrf.config.ContainerConfig;
import org.globus.wsrf.utils.AddressingUtils;
/**
* gov.nih.nci.cagrid.introduce.securityI TODO:DOCUMENT ME
*
* @created by Introduce Toolkit version 1.0
*/
public class ServiceSecurityImpl {
private ServiceConfiguration configuration;
private ServiceSecurityMetadata metadata;
public ServiceSecurityImpl() throws RemoteException {
try {
EndpointReferenceType type = AddressingUtils.createEndpointReference(null);
String configFileEnd = (String)MessageContext.getCurrentContext().getProperty("securityMetadata");
String configFile = ContainerConfig.getBaseDirectory() + File.separator+configFileEnd;
File f = new File(configFile);
if(!f.exists()){
throw new RemoteException("The security metadata file ("+configFile+") could not be found!!!");
}
metadata = (ServiceSecurityMetadata) Utils.deserializeDocument(configFile, ServiceSecurityMetadata.class);
} catch (Exception e) {
FaultHelper.printStackTrace(e);
throw new RemoteException(Utils.getExceptionMessage(e));
}
}
public ServiceConfiguration getConfiguration() throws Exception {
if (this.configuration != null) {
return this.configuration;
}
MessageContext ctx = MessageContext.getCurrentContext();
String servicePath = ctx.getTargetService();
String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/serviceconfiguration";
try {
javax.naming.Context initialContext = new InitialContext();
this.configuration = (ServiceConfiguration) initialContext.lookup(jndiName);
} catch (Exception e) {
throw new Exception("Unable to instantiate service configuration.", e);
}
return this.configuration;
}
public gov.nih.nci.cagrid.metadata.security.ServiceSecurityMetadata getServiceSecurityMetadata()
throws RemoteException {
return metadata;
}
}
| *** empty log message ***
| cagrid-1-0/caGrid/projects/introduce/operationProviders/ServiceSecurity/src/gov/nih/nci/cagrid/introduce/security/service/ServiceSecurityImpl.java | *** empty log message *** | <ide><path>agrid-1-0/caGrid/projects/introduce/operationProviders/ServiceSecurity/src/gov/nih/nci/cagrid/introduce/security/service/ServiceSecurityImpl.java
<ide>
<ide> import gov.nih.nci.cagrid.common.FaultHelper;
<ide> import gov.nih.nci.cagrid.common.Utils;
<del>import gov.nih.nci.cagrid.dorian.service.Dorian;
<ide> import gov.nih.nci.cagrid.metadata.security.ServiceSecurityMetadata;
<del>import gov.nih.nci.cagrid.syncgts.bean.SyncReport;
<del>
<ide>
<ide> import java.io.File;
<ide> import java.rmi.RemoteException; |
|
Java | apache-2.0 | 26a5f5cb09d08e184f6105f70e3987158384e3b8 | 0 | ahb0327/intellij-community,adedayo/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,hurricup/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,jexp/idea2,youdonghai/intellij-community,petteyg/intellij-community,allotria/intellij-community,semonte/intellij-community,robovm/robovm-studio,ibinti/intellij-community,izonder/intellij-community,allotria/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,asedunov/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,supersven/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,supersven/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,adedayo/intellij-community,samthor/intellij-community,apixandru/intellij-community,jexp/idea2,adedayo/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,consulo/consulo,wreckJ/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,izonder/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,holmes/intellij-community,diorcety/intellij-community,samthor/intellij-community,supersven/intellij-community,wreckJ/intellij-community,izonder/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,signed/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,blademainer/intellij-community,vladmm/intellij-community,ernestp/consulo,kdwink/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,caot/intellij-community,gnuhub/intellij-community,semonte/intellij-community,kool79/intellij-community,suncycheng/intellij-community,ryano144/intellij-community,caot/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,ernestp/consulo,caot/intellij-community,robovm/robovm-studio,jagguli/intellij-community,retomerz/intellij-community,kdwink/intellij-community,vladmm/intellij-community,ernestp/consulo,suncycheng/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,lucafavatella/intellij-community,petteyg/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,retomerz/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,joewalnes/idea-community,gnuhub/intellij-community,asedunov/intellij-community,asedunov/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,slisson/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,semonte/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,slisson/intellij-community,adedayo/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,kool79/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,fnouama/intellij-community,retomerz/intellij-community,joewalnes/idea-community,robovm/robovm-studio,da1z/intellij-community,blademainer/intellij-community,allotria/intellij-community,jagguli/intellij-community,caot/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,robovm/robovm-studio,fitermay/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,blademainer/intellij-community,allotria/intellij-community,slisson/intellij-community,samthor/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,supersven/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,jexp/idea2,supersven/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,dslomov/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,allotria/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,hurricup/intellij-community,holmes/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,signed/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,apixandru/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,da1z/intellij-community,vladmm/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,adedayo/intellij-community,amith01994/intellij-community,hurricup/intellij-community,xfournet/intellij-community,samthor/intellij-community,amith01994/intellij-community,semonte/intellij-community,xfournet/intellij-community,clumsy/intellij-community,da1z/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,FHannes/intellij-community,izonder/intellij-community,Lekanich/intellij-community,kool79/intellij-community,holmes/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,da1z/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,fitermay/intellij-community,semonte/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,ibinti/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,adedayo/intellij-community,jexp/idea2,vladmm/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,apixandru/intellij-community,apixandru/intellij-community,fnouama/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,petteyg/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,consulo/consulo,samthor/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,kool79/intellij-community,supersven/intellij-community,holmes/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,kdwink/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,retomerz/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,caot/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,apixandru/intellij-community,caot/intellij-community,diorcety/intellij-community,holmes/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,caot/intellij-community,da1z/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,semonte/intellij-community,retomerz/intellij-community,petteyg/intellij-community,caot/intellij-community,semonte/intellij-community,adedayo/intellij-community,signed/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,consulo/consulo,kool79/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,diorcety/intellij-community,kdwink/intellij-community,petteyg/intellij-community,robovm/robovm-studio,kool79/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,holmes/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,jexp/idea2,ahb0327/intellij-community,wreckJ/intellij-community,da1z/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,fnouama/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,signed/intellij-community,izonder/intellij-community,semonte/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,amith01994/intellij-community,consulo/consulo,nicolargo/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,caot/intellij-community,clumsy/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,semonte/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,ibinti/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,da1z/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,ernestp/consulo,tmpgit/intellij-community,semonte/intellij-community,tmpgit/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,ernestp/consulo,izonder/intellij-community,kool79/intellij-community,retomerz/intellij-community,ryano144/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,jexp/idea2,signed/intellij-community,dslomov/intellij-community,hurricup/intellij-community,hurricup/intellij-community,FHannes/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,jexp/idea2,orekyuu/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,signed/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,joewalnes/idea-community,robovm/robovm-studio,allotria/intellij-community,youdonghai/intellij-community,slisson/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,izonder/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,samthor/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,ahb0327/intellij-community,samthor/intellij-community,jagguli/intellij-community,fnouama/intellij-community,signed/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,caot/intellij-community,ernestp/consulo,FHannes/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,allotria/intellij-community,Lekanich/intellij-community,jexp/idea2,apixandru/intellij-community,slisson/intellij-community,signed/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,holmes/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,amith01994/intellij-community,dslomov/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,youdonghai/intellij-community,semonte/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,adedayo/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,ibinti/intellij-community,caot/intellij-community,wreckJ/intellij-community,signed/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,semonte/intellij-community,xfournet/intellij-community,adedayo/intellij-community,fitermay/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,semonte/intellij-community,dslomov/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,hurricup/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,samthor/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,ryano144/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,holmes/intellij-community,fnouama/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,consulo/consulo,joewalnes/idea-community | /*
* Copyright (c) 2000-2004 by JetBrains s.r.o. All Rights Reserved.
* Use is subject to license terms.
*/
package com.intellij.psi;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.psi.search.GlobalSearchScope;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* @author ven
*/
public class GenericsUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.GenericsUtil");
public static PsiType getGreatestLowerBound(PsiType type1, PsiType type2) {
return PsiIntersectionType.createIntersection(new PsiType[] {type1, type2});
}
public static PsiType getLeastUpperBound(PsiType type1, PsiType type2, PsiManager manager) {
if (type1 instanceof PsiPrimitiveType || type2 instanceof PsiPrimitiveType) return null;
return getLeastUpperBound(type1, type2, new LinkedHashSet<Pair<PsiType, PsiType>>(), manager);
}
private static PsiType getLeastUpperBound(PsiType type1, PsiType type2, Set<Pair<PsiType, PsiType>> compared, PsiManager manager) {
if (type1 instanceof PsiCapturedWildcardType) {
return getLeastUpperBound(((PsiCapturedWildcardType)type1).getUpperBound(), type2, compared, manager);
} else if (type2 instanceof PsiCapturedWildcardType) {
return getLeastUpperBound(type1, ((PsiCapturedWildcardType)type2).getUpperBound(), compared, manager);
}
if (type1 instanceof PsiArrayType && type2 instanceof PsiArrayType) {
final PsiType componentType = getLeastUpperBound(((PsiArrayType)type1).getComponentType(),
((PsiArrayType)type2).getComponentType(), manager);
if (componentType != null) {
return componentType.createArrayType();
}
}
else if (type1 instanceof PsiClassType && type2 instanceof PsiClassType) {
PsiClassType.ClassResolveResult classResolveResult1 = ((PsiClassType)type1).resolveGenerics();
PsiClassType.ClassResolveResult classResolveResult2 = ((PsiClassType)type2).resolveGenerics();
PsiClass aClass = classResolveResult1.getElement();
PsiClass bClass = classResolveResult2.getElement();
if (aClass == null || bClass == null) {
return manager.getElementFactory().createTypeByFQClassName("java.lang.Object", GlobalSearchScope.allScope(manager.getProject()));
}
PsiClass[] supers = getLeastUpperClasses(aClass, bClass);
if (supers.length == 0) {
return manager.getElementFactory().createTypeByFQClassName("java.lang.Object", aClass.getResolveScope());
}
PsiClassType[] conjuncts = new PsiClassType[supers.length];
for (int i = 0; i < supers.length; i++) {
PsiClass aSuper = supers[i];
PsiSubstitutor subst1 = TypeConversionUtil.getSuperClassSubstitutor(aSuper, aClass,
classResolveResult1.getSubstitutor());
PsiSubstitutor subst2 = TypeConversionUtil.getSuperClassSubstitutor(aSuper, bClass,
classResolveResult2.getSubstitutor());
LOG.assertTrue(subst1 != null && subst2 != null);
Iterator<PsiTypeParameter> iterator = PsiUtil.typeParametersIterator(aSuper);
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
while (iterator.hasNext()) {
PsiTypeParameter parameter = iterator.next();
PsiType mapping1 = subst1.substitute(parameter);
PsiType mapping2 = subst2.substitute(parameter);
if (mapping1 != null && mapping2 != null) {
substitutor = substitutor.put(parameter, getLeastContainingTypeArgument(mapping1, mapping2, compared, manager));
}
else {
substitutor = substitutor.put(parameter, null);
}
}
conjuncts[i] = manager.getElementFactory().createType(aSuper, substitutor);
}
return PsiIntersectionType.createIntersection(conjuncts);
}
return manager.getElementFactory().createTypeByFQClassName("java.lang.Object", GlobalSearchScope.allScope(manager.getProject()));
}
private static PsiType getLeastContainingTypeArgument(PsiType type1,
PsiType type2,
Set<Pair<PsiType, PsiType>> compared,
PsiManager manager) {
Pair<PsiType, PsiType> p = new Pair<PsiType, PsiType>(type1, type2);
if (compared.contains(p)) return PsiWildcardType.createUnbounded(manager);
compared.add(p);
if (type1 instanceof PsiWildcardType) {
PsiWildcardType wild1 = (PsiWildcardType)type1;
if (type2 instanceof PsiWildcardType) {
PsiWildcardType wild2 = (PsiWildcardType)type2;
if (wild1.isExtends() == wild2.isExtends()) {
return wild1.isExtends() ? PsiWildcardType.createExtends(manager, getLeastUpperBound(wild1.getBound(), wild2.getBound(), compared, manager)) :
wild1.isSuper() ? PsiWildcardType.createSuper(manager, getGreatestLowerBound(wild1.getBound(), wild2.getBound())) :
wild1;
} else {
return wild1.getBound().equals(wild2.getBound()) ? wild1.getBound() : PsiWildcardType.createUnbounded(manager);
}
} else {
return wild1.isExtends() ? PsiWildcardType.createExtends(manager, getLeastUpperBound(wild1.getBound(), type2, compared, manager)) :
wild1.isSuper() ? PsiWildcardType.createSuper(manager, getGreatestLowerBound(wild1.getBound(), type2)) :
wild1;
}
} else if (type2 instanceof PsiWildcardType) {
return getLeastContainingTypeArgument(type2, type1, compared, manager);
}
//Done with wildcards
if (type1.equals(type2)) return type1;
return PsiWildcardType.createExtends(manager, getLeastUpperBound(type1, type2, compared, manager));
}
public static PsiClass[] getLeastUpperClasses(PsiClass aClass, PsiClass bClass) {
if (InheritanceUtil.isInheritorOrSelf(aClass, bClass, true)) return new PsiClass[]{bClass};
Set<PsiClass> supers = new LinkedHashSet<PsiClass>();
getLeastUpperClassesInner(aClass, bClass, supers);
return supers.toArray(new PsiClass[supers.size()]);
}
private static void getLeastUpperClassesInner(PsiClass aClass, PsiClass bClass, Set<PsiClass> supers) {
if (bClass.isInheritor(aClass, true)) {
supers.add(aClass);
} else {
final PsiClass[] aSupers = aClass.getSupers();
for (int i = 0; i < aSupers.length; i++) {
PsiClass aSuper = aSupers[i];
getLeastUpperClassesInner(aSuper, bClass, supers);
}
}
}
public static boolean isTypeArgumentsApplicable(PsiTypeParameter[] typeParams, PsiSubstitutor substitutor) {
for (int i = 0; i < typeParams.length; i++) {
PsiTypeParameter typeParameter = typeParams[i];
PsiType substituted = substitutor.substitute(typeParameter);
if (substituted == null) return true;
PsiClassType[] extendsTypes = typeParameter.getExtendsListTypes();
for (int j = 0; j < extendsTypes.length; j++) {
PsiType extendsType = substitutor.substitute(extendsTypes[j]);
if (!extendsType.isAssignableFrom(substituted)) {
return false;
}
}
}
return true;
}
}
| openapi/src/com/intellij/psi/GenericsUtil.java | /*
* Copyright (c) 2000-2004 by JetBrains s.r.o. All Rights Reserved.
* Use is subject to license terms.
*/
package com.intellij.psi;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.psi.search.GlobalSearchScope;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* @author ven
*/
public class GenericsUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.GenericsUtil");
public static PsiType getGreatestLowerBound(PsiType type1, PsiType type2) {
return PsiIntersectionType.createIntersection(new PsiType[] {type1, type2});
}
public static PsiType getLeastUpperBound(PsiType type1, PsiType type2, PsiManager manager) {
if (type1 instanceof PsiPrimitiveType || type2 instanceof PsiPrimitiveType) return null;
return getLeastUpperBound(type1, type2, new LinkedHashSet<Pair<PsiType, PsiType>>(), manager);
}
private static PsiType getLeastUpperBound(PsiType type1, PsiType type2, Set<Pair<PsiType, PsiType>> compared, PsiManager manager) {
if (type1 instanceof PsiCapturedWildcardType) {
return getLeastUpperBound(((PsiCapturedWildcardType)type1).getUpperBound(), type2, compared, manager);
} else if (type2 instanceof PsiCapturedWildcardType) {
return getLeastUpperBound(type1, ((PsiCapturedWildcardType)type2).getUpperBound(), compared, manager);
}
if (type1 instanceof PsiArrayType && type2 instanceof PsiArrayType) {
final PsiType componentType = getLeastUpperBound(((PsiArrayType)type1).getComponentType(),
((PsiArrayType)type2).getComponentType(), manager);
if (componentType != null) {
return componentType.createArrayType();
}
}
else if (type1 instanceof PsiClassType && type2 instanceof PsiClassType) {
PsiClassType.ClassResolveResult classResolveResult1 = ((PsiClassType)type1).resolveGenerics();
PsiClassType.ClassResolveResult classResolveResult2 = ((PsiClassType)type2).resolveGenerics();
PsiClass aClass = classResolveResult1.getElement();
PsiClass bClass = classResolveResult2.getElement();
if (aClass == null || bClass == null) {
return manager.getElementFactory().createTypeByFQClassName("java.lang.Object", GlobalSearchScope.allScope(manager.getProject()));
}
PsiClass[] supers = getLeastUpperClasses(aClass, bClass);
if (supers.length == 0) {
return manager.getElementFactory().createTypeByFQClassName("java.lang.Object", aClass.getResolveScope());
}
PsiClassType[] conjuncts = new PsiClassType[supers.length];
for (int i = 0; i < supers.length; i++) {
PsiClass aSuper = supers[i];
PsiSubstitutor subst1 = TypeConversionUtil.getSuperClassSubstitutor(aSuper, aClass,
classResolveResult1.getSubstitutor());
PsiSubstitutor subst2 = TypeConversionUtil.getSuperClassSubstitutor(aSuper, bClass,
classResolveResult2.getSubstitutor());
LOG.assertTrue(subst1 != null && subst2 != null);
Iterator<PsiTypeParameter> iterator = PsiUtil.typeParametersIterator(aSuper);
PsiSubstitutor substitutor = PsiSubstitutor.EMPTY;
while (iterator.hasNext()) {
PsiTypeParameter parameter = iterator.next();
PsiType mapping1 = subst1.substitute(parameter);
PsiType mapping2 = subst2.substitute(parameter);
if (mapping1 != null && mapping2 != null) {
substitutor = substitutor.put(parameter, getLeastContainingTypeArgument(mapping1, mapping2, compared, manager));
}
else {
substitutor = substitutor.put(parameter, null);
}
}
conjuncts[i] = manager.getElementFactory().createType(aSuper, substitutor);
}
return PsiIntersectionType.createIntersection(conjuncts);
}
return manager.getElementFactory().createTypeByFQClassName("java.lang.Object", GlobalSearchScope.allScope(manager.getProject()));
}
private static PsiType getLeastContainingTypeArgument(PsiType type1,
PsiType type2,
Set<Pair<PsiType, PsiType>> compared,
PsiManager manager) {
Pair<PsiType, PsiType> p = new Pair<PsiType, PsiType>(type1, type2);
if (compared.contains(p)) return PsiWildcardType.createUnbounded(manager);
compared.add(p);
if (type1 instanceof PsiWildcardType) {
PsiWildcardType wild1 = (PsiWildcardType)type1;
if (type2 instanceof PsiWildcardType) {
PsiWildcardType wild2 = (PsiWildcardType)type2;
if (wild1.isExtends() == wild2.isExtends()) {
return wild1.isExtends() ? PsiWildcardType.createExtends(manager, getLeastUpperBound(wild1.getBound(), wild2.getBound(), compared, manager)) :
wild1.isSuper() ? PsiWildcardType.createSuper(manager, getGreatestLowerBound(wild1.getBound(), wild2.getBound())) :
wild1;
} else {
return wild1.getBound().equals(wild2.getBound()) ? wild1.getBound() : PsiWildcardType.createUnbounded(manager);
}
} else {
return wild1.isExtends() ? PsiWildcardType.createExtends(manager, getLeastUpperBound(wild1.getBound(), type2, compared, manager)) :
wild1.isSuper() ? PsiWildcardType.createSuper(manager, getGreatestLowerBound(wild1.getBound(), type2)) :
wild1;
}
} else if (type2 instanceof PsiWildcardType) {
return getLeastContainingTypeArgument(type2, type1, compared, manager);
}
//Done with wildcards
if (type1.equals(type2)) return type1;
return PsiWildcardType.createExtends(manager, getLeastUpperBound(type1, type2, compared, manager));
}
private static PsiClass[] getLeastUpperClasses(PsiClass aClass, PsiClass bClass) {
if (InheritanceUtil.isInheritorOrSelf(aClass, bClass, true)) return new PsiClass[]{bClass};
Set<PsiClass> supers = new LinkedHashSet<PsiClass>();
getLeastUpperClassesInner(aClass, bClass, supers);
return supers.toArray(new PsiClass[supers.size()]);
}
private static void getLeastUpperClassesInner(PsiClass aClass, PsiClass bClass, Set<PsiClass> supers) {
if (bClass.isInheritor(aClass, true)) {
supers.add(aClass);
} else {
final PsiClass[] aSupers = aClass.getSupers();
for (int i = 0; i < aSupers.length; i++) {
PsiClass aSuper = aSupers[i];
getLeastUpperClassesInner(aSuper, bClass, supers);
}
}
}
public static boolean isTypeArgumentsApplicable(PsiTypeParameter[] typeParams, PsiSubstitutor substitutor) {
for (int i = 0; i < typeParams.length; i++) {
PsiTypeParameter typeParameter = typeParams[i];
PsiType substituted = substitutor.substitute(typeParameter);
if (substituted == null) return true;
PsiClassType[] extendsTypes = typeParameter.getExtendsListTypes();
for (int j = 0; j < extendsTypes.length; j++) {
PsiType extendsType = substitutor.substitute(extendsTypes[j]);
if (!extendsType.isAssignableFrom(substituted)) {
return false;
}
}
}
return true;
}
}
| (no message) | openapi/src/com/intellij/psi/GenericsUtil.java | (no message) | <ide><path>penapi/src/com/intellij/psi/GenericsUtil.java
<ide> return PsiWildcardType.createExtends(manager, getLeastUpperBound(type1, type2, compared, manager));
<ide> }
<ide>
<del> private static PsiClass[] getLeastUpperClasses(PsiClass aClass, PsiClass bClass) {
<add> public static PsiClass[] getLeastUpperClasses(PsiClass aClass, PsiClass bClass) {
<ide> if (InheritanceUtil.isInheritorOrSelf(aClass, bClass, true)) return new PsiClass[]{bClass};
<ide> Set<PsiClass> supers = new LinkedHashSet<PsiClass>();
<ide> getLeastUpperClassesInner(aClass, bClass, supers); |
|
JavaScript | agpl-3.0 | 17fedcd96e9aed52edf5dbd557422e9139f76f1c | 0 | schul-cloud/schulcloud-server,schul-cloud/schulcloud-server,schul-cloud/schulcloud-server | // Global hooks that run for every service
const sanitizeHtml = require('sanitize-html');
const sanitize = (data, options) => {
// https://www.npmjs.com/package/sanitize-html
if ((options||{}).html === true) {
// editor-content data
data = sanitizeHtml(data, {
allowedTags: [ 'h1', 'h2', 'h3', 'blockquote', 'p', 'a', 'ul', 'ol', 's', 'u', 'span', 'del',
'li', 'b', 'i', 'img', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'rechnen',
'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'audio', 'video' ],
allowedAttributes: false, // allow all attributes of allowed tags
allowedSchemes: [ 'http', 'https', 'ftp', 'mailto' ],
parser: {
decodeEntities: true
}
});
data = data.replace(/(<script>).*?(<\/script>)/gim, ''); // force remove script tags
data = data.replace(/(<script>).*?(<\/script>)/gim, ''); // force remove script tags
} else {
// non editor-content data
data = sanitizeHtml(data, {
allowedTags: [], // disallow all tags
allowedAttributes: [], // disallow all attributes
allowedSchemes: [], // disallow url schemes
parser: {
decodeEntities: true
}
});
}
return data;
};
/**
* Strips JS/HTML Code from data and returns clean version of it
* @param data {object/array/string}
* @returns data - clean without JS
*/
const sanitizeDeep = (data, path) => {
if (typeof data === "object" && data !== null) {
Object.entries(data).forEach(([key, value]) => {
if(typeof value === "string") {
// ignore values completely
if (["password"].includes(key))
return data;
// enable html for all current editors
if (["content", "text", "comment", "gradeComment", "description"].includes(key) && ["lessons", "news", "homework"].includes(path))
data[key] = sanitize(value, {html: true});
else
data[key] = sanitize(value, {html: false});
} else
sanitizeDeep(value, path);
});
} else if (typeof data === "string")
data = sanitize(data, {html:false});
else if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
if (typeof data[i] === "string")
data[i] = sanitize(data[i], {html:false});
else
sanitizeDeep(data[i], path);
}
}
return data;
};
const sanitizeData = (hook) => {
if (hook.data && hook.path && hook.path !== "authentication") {
sanitizeDeep(hook.data, hook.path);
}
return hook;
};
module.exports = {
before: {
all: [],
find: [],
get: [],
create: [sanitizeData],
update: [sanitizeData],
patch: [sanitizeData],
remove: []
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
| src/app.hooks.js | // Global hooks that run for every service
const sanitizeHtml = require('sanitize-html');
const sanitize = (data, options) => {
// https://www.npmjs.com/package/sanitize-html
if ((options||{}).html === true) {
// editor-content data
data = sanitizeHtml(data, {
allowedTags: [ 'h1', 'h2', 'h3', 'blockquote', 'p', 'a', 'ul', 'ol', 's', 'u', 'span', 'del',
'li', 'b', 'i', 'img', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'rechnen',
'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'audio', 'video' ],
allowedAttributes: false, // allow all attributes of allowed tags
allowedSchemes: [ 'http', 'https', 'ftp', 'mailto' ],
parser: {
decodeEntities: true
}
});
data = data.replace(/(<script>).*?(<\/script>)/gim, ''); // force remove script tags
data = data.replace(/(<script>).*?(<\/script>)/gim, ''); // force remove script tags
} else {
// non editor-content data
data = sanitizeHtml(data, {
allowedTags: [], // disallow all tags
allowedAttributes: [], // disallow all attributes
allowedSchemes: [], // disallow url schemes
parser: {
decodeEntities: true
}
});
}
return data;
};
/**
* Strips JS/HTML Code from data and returns clean version of it
* @param data {object/array/string}
* @returns data - clean without JS
*/
const sanitizeDeep = (data, path) => {
if (typeof data === "object" && data !== null) {
Object.entries(data).forEach(([key, value]) => {
if(typeof value === "string")
// enable html for all current editors
if (["content", "text", "comment", "gradeComment", "description"].includes(key) && ["lessons", "news", "homework"].includes(path))
data[key] = sanitize(value, {html: true});
else
data[key] = sanitize(value, {html: false});
else
sanitizeDeep(value, path);
});
} else if (typeof data === "string")
data = sanitize(data, {html:false});
else if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
if (typeof data[i] === "string")
data[i] = sanitize(data[i], {html:false});
else
sanitizeDeep(data[i], path);
}
}
return data;
};
const sanitizeData = (hook) => {
if (hook.data && hook.path && hook.path !== "authentication") {
sanitizeDeep(hook.data, hook.path);
}
return hook;
};
module.exports = {
before: {
all: [],
find: [],
get: [],
create: [sanitizeData],
update: [sanitizeData],
patch: [sanitizeData],
remove: []
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};
| ignore specific values entirely
| src/app.hooks.js | ignore specific values entirely | <ide><path>rc/app.hooks.js
<ide> const sanitizeDeep = (data, path) => {
<ide> if (typeof data === "object" && data !== null) {
<ide> Object.entries(data).forEach(([key, value]) => {
<del> if(typeof value === "string")
<add> if(typeof value === "string") {
<add> // ignore values completely
<add> if (["password"].includes(key))
<add> return data;
<ide> // enable html for all current editors
<ide> if (["content", "text", "comment", "gradeComment", "description"].includes(key) && ["lessons", "news", "homework"].includes(path))
<ide> data[key] = sanitize(value, {html: true});
<ide> else
<ide> data[key] = sanitize(value, {html: false});
<del> else
<add> } else
<ide> sanitizeDeep(value, path);
<ide> });
<ide> } else if (typeof data === "string") |
|
Java | apache-2.0 | 25b6bc7f65e91b8100ea156f49682228f9da3d16 | 0 | Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services | package org.sagebionetworks.repo.model.dbo.persistence;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_CLAIMS;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_CLIENT_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_CREATED_ON;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_ETAG;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_HASH;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_LAST_USED;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_MODIFIED_ON;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_NAME;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_PRINCIPAL_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_SCOPES;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.DDL_OAUTH_REFRESH_TOKEN;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_OAUTH_REFRESH_TOKEN;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import org.sagebionetworks.repo.model.dbo.FieldColumn;
import org.sagebionetworks.repo.model.dbo.MigratableDatabaseObject;
import org.sagebionetworks.repo.model.dbo.TableMapping;
import org.sagebionetworks.repo.model.dbo.migration.BasicMigratableTableTranslation;
import org.sagebionetworks.repo.model.dbo.migration.MigratableTableTranslation;
import org.sagebionetworks.repo.model.migration.MigrationType;
/**
* Database object representing an OAuth 2.0 refresh token
*/
public class DBOOAuthRefreshToken implements MigratableDatabaseObject<DBOOAuthRefreshToken, DBOOAuthRefreshToken> {
private Long id;
private String tokenHash;
private String name;
private Long principalId;
private Long clientId;
private byte[] scopes;
private byte[] claims;
private Timestamp createdOn;
private Timestamp modifiedOn;
private Timestamp lastUsed;
private String etag;
private static FieldColumn[] FIELDS = new FieldColumn[] {
new FieldColumn("id", COL_OAUTH_REFRESH_TOKEN_ID, true).withIsBackupId(true),
new FieldColumn("tokenHash", COL_OAUTH_REFRESH_TOKEN_HASH),
new FieldColumn("name", COL_OAUTH_REFRESH_TOKEN_NAME),
new FieldColumn("principalId", COL_OAUTH_REFRESH_TOKEN_PRINCIPAL_ID),
new FieldColumn("clientId", COL_OAUTH_REFRESH_TOKEN_CLIENT_ID),
new FieldColumn("scopes", COL_OAUTH_REFRESH_TOKEN_SCOPES),
new FieldColumn("claims", COL_OAUTH_REFRESH_TOKEN_CLAIMS),
new FieldColumn("createdOn", COL_OAUTH_REFRESH_TOKEN_CREATED_ON),
new FieldColumn("modifiedOn", COL_OAUTH_REFRESH_TOKEN_MODIFIED_ON),
new FieldColumn("lastUsed", COL_OAUTH_REFRESH_TOKEN_LAST_USED),
new FieldColumn("etag", COL_OAUTH_REFRESH_TOKEN_ETAG).withIsEtag(true),
};
private static DBOOAuthRefreshToken mapRow(ResultSet rs, int rowNum) throws SQLException {
DBOOAuthRefreshToken token = new DBOOAuthRefreshToken();
token.setId(rs.getLong(COL_OAUTH_REFRESH_TOKEN_ID));
token.setTokenHash(rs.getString(COL_OAUTH_REFRESH_TOKEN_HASH));
token.setName(rs.getString(COL_OAUTH_REFRESH_TOKEN_NAME));
token.setPrincipalId(rs.getLong(COL_OAUTH_REFRESH_TOKEN_PRINCIPAL_ID));
token.setClientId(rs.getLong(COL_OAUTH_REFRESH_TOKEN_CLIENT_ID));
token.setScopes(rs.getBytes(COL_OAUTH_REFRESH_TOKEN_SCOPES));
token.setClaims(rs.getBytes(COL_OAUTH_REFRESH_TOKEN_CLAIMS));
token.setCreatedOn(rs.getTimestamp(COL_OAUTH_REFRESH_TOKEN_CREATED_ON));
token.setModifiedOn(rs.getTimestamp(COL_OAUTH_REFRESH_TOKEN_MODIFIED_ON));
token.setLastUsed(rs.getTimestamp(COL_OAUTH_REFRESH_TOKEN_LAST_USED));
token.setEtag(rs.getString(COL_OAUTH_REFRESH_TOKEN_ETAG));
return token;
}
@Override
public TableMapping<DBOOAuthRefreshToken> getTableMapping() {
return new TableMapping<DBOOAuthRefreshToken>() {
// Map a result set to this object
@Override
public DBOOAuthRefreshToken mapRow(ResultSet rs, int rowNum) throws SQLException {
// Use static method to avoid unintentionally referencing `this`
return DBOOAuthRefreshToken.mapRow(rs, rowNum);
}
@Override
public String getTableName() {
return TABLE_OAUTH_REFRESH_TOKEN;
}
@Override
public String getDDLFileName() {
return DDL_OAUTH_REFRESH_TOKEN;
}
@Override
public FieldColumn[] getFieldColumns() {
return FIELDS;
}
@Override
public Class<? extends DBOOAuthRefreshToken> getDBOClass() {
return DBOOAuthRefreshToken.class;
}
};
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public String getTokenHash() {
return tokenHash;
}
public void setTokenHash(String tokenHash) {
this.tokenHash = tokenHash;
}
public Long getPrincipalId() {
return principalId;
}
public void setPrincipalId(Long principalId) {
this.principalId = principalId;
}
public Long getClientId() {
return clientId;
}
public void setClientId(Long clientId) {
this.clientId = clientId;
}
public byte[] getScopes() {
return this.scopes;
}
public void setScopes(byte[] scopes) {
this.scopes = scopes;
}
public byte[] getClaims() {
return claims;
}
public void setClaims(byte[] claims) {
this.claims = claims;
}
public Timestamp getLastUsed() {
return lastUsed;
}
public void setLastUsed(Timestamp lastUsed) {
this.lastUsed = lastUsed;
}
public void setName(String name) {
this.name = name;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
public Timestamp getModifiedOn() {
return modifiedOn;
}
public void setModifiedOn(Timestamp modifiedOn) {
this.modifiedOn = modifiedOn;
}
public String getEtag() {
return etag;
}
public void setEtag(String eTag) {
this.etag = eTag;
}
@Override
public String toString() {
return "DBOOAuthClient [id=" + id + ", tokenHash=" + tokenHash +", name=" + name +
", principalId=" + principalId + ", clientId=" + clientId + ", scopes=" + Arrays.toString(scopes) +
", claims=" + Arrays.toString(claims) + ", createdOn=" + createdOn + ", modifiedOn=" + modifiedOn
+ ", lastUsed=" + lastUsed + ", eTag=" + etag + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((tokenHash == null) ? 0 : tokenHash.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((principalId == null) ? 0 : principalId.hashCode());
result = prime * result + ((clientId == null) ? 0 : clientId.hashCode());
result = prime * result + ((scopes == null) ? 0 : Arrays.hashCode(scopes));
result = prime * result + ((scopes == null) ? 0 : Arrays.hashCode(claims));
result = prime * result + ((createdOn == null) ? 0 : createdOn.hashCode());
result = prime * result + ((modifiedOn == null) ? 0 : modifiedOn.hashCode());
result = prime * result + ((lastUsed == null) ? 0 : lastUsed.hashCode());
result = prime * result + ((etag == null) ? 0 : etag.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DBOOAuthRefreshToken other = (DBOOAuthRefreshToken) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (tokenHash == null) {
if (other.tokenHash != null)
return false;
} else if (!tokenHash.equals(other.tokenHash))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (principalId == null) {
if (other.principalId != null)
return false;
} else if (!principalId.equals(other.principalId))
return false;
if (clientId == null) {
if (other.clientId != null)
return false;
} else if (!clientId.equals(other.clientId))
return false;
if (scopes == null) {
if (other.scopes != null)
return false;
} else if (!Arrays.equals(scopes, other.scopes))
return false;
if (claims == null) {
if (other.claims != null)
return false;
} else if (!Arrays.equals(claims, other.claims))
return false;
if (createdOn == null) {
if (other.createdOn != null) {
return false;
}
} else if (!createdOn.equals(other.createdOn)) {
return false;
}
if (modifiedOn == null) {
if (other.modifiedOn != null) {
return false;
}
} else if (!modifiedOn.equals(other.modifiedOn)) {
return false;
}
if (lastUsed == null) {
if (other.lastUsed != null) {
return false;
}
} else if (!lastUsed.equals(other.lastUsed)) {
return false;
}
if (etag == null) {
if (other.etag != null) {
return false;
}
} else if (!etag.equals(other.etag)) {
return false;
}
return true;
}
@Override
public MigrationType getMigratableTableType() {
return MigrationType.OAUTH_REFRESH_TOKEN;
}
@Override
public MigratableTableTranslation<DBOOAuthRefreshToken, DBOOAuthRefreshToken> getTranslator() {
return new BasicMigratableTableTranslation<DBOOAuthRefreshToken>();
}
@Override
public Class<? extends DBOOAuthRefreshToken> getBackupClass() {
return DBOOAuthRefreshToken.class;
}
@Override
public Class<? extends DBOOAuthRefreshToken> getDatabaseObjectClass() {
return DBOOAuthRefreshToken.class;
}
@Override
public List<MigratableDatabaseObject<?,?>> getSecondaryTypes() {
return null;
}
}
| lib/jdomodels/src/main/java/org/sagebionetworks/repo/model/dbo/persistence/DBOOAuthRefreshToken.java | package org.sagebionetworks.repo.model.dbo.persistence;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_CLIENT_NAME;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_CLAIMS;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_CLIENT_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_CREATED_ON;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_ETAG;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_HASH;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_LAST_USED;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_MODIFIED_ON;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_NAME;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_PRINCIPAL_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_SCOPES;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.DDL_OAUTH_REFRESH_TOKEN;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_OAUTH_REFRESH_TOKEN;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import org.sagebionetworks.repo.model.dbo.FieldColumn;
import org.sagebionetworks.repo.model.dbo.MigratableDatabaseObject;
import org.sagebionetworks.repo.model.dbo.TableMapping;
import org.sagebionetworks.repo.model.dbo.migration.BasicMigratableTableTranslation;
import org.sagebionetworks.repo.model.dbo.migration.MigratableTableTranslation;
import org.sagebionetworks.repo.model.migration.MigrationType;
/**
* Database object representing an OAuth 2.0 refresh token
*/
public class DBOOAuthRefreshToken implements MigratableDatabaseObject<DBOOAuthRefreshToken, DBOOAuthRefreshToken> {
private Long id;
private String tokenHash;
private String name;
private Long principalId;
private Long clientId;
private byte[] scopes;
private byte[] claims;
private Timestamp createdOn;
private Timestamp modifiedOn;
private Timestamp lastUsed;
private String etag;
private static FieldColumn[] FIELDS = new FieldColumn[] {
new FieldColumn("id", COL_OAUTH_REFRESH_TOKEN_ID, true).withIsBackupId(true),
new FieldColumn("tokenHash", COL_OAUTH_REFRESH_TOKEN_HASH),
new FieldColumn("name", COL_OAUTH_REFRESH_TOKEN_NAME),
new FieldColumn("principalId", COL_OAUTH_REFRESH_TOKEN_PRINCIPAL_ID),
new FieldColumn("clientId", COL_OAUTH_REFRESH_TOKEN_CLIENT_ID),
new FieldColumn("scopes", COL_OAUTH_REFRESH_TOKEN_SCOPES),
new FieldColumn("claims", COL_OAUTH_REFRESH_TOKEN_CLAIMS),
new FieldColumn("createdOn", COL_OAUTH_REFRESH_TOKEN_CREATED_ON),
new FieldColumn("modifiedOn", COL_OAUTH_REFRESH_TOKEN_MODIFIED_ON),
new FieldColumn("lastUsed", COL_OAUTH_REFRESH_TOKEN_LAST_USED),
new FieldColumn("etag", COL_OAUTH_REFRESH_TOKEN_ETAG).withIsEtag(true),
};
private static DBOOAuthRefreshToken mapRow(ResultSet rs, int rowNum) throws SQLException {
DBOOAuthRefreshToken token = new DBOOAuthRefreshToken();
token.setId(rs.getLong(COL_OAUTH_REFRESH_TOKEN_ID));
token.setTokenHash(rs.getString(COL_OAUTH_REFRESH_TOKEN_HASH));
token.setName(rs.getString(COL_OAUTH_CLIENT_NAME));
token.setPrincipalId(rs.getLong(COL_OAUTH_REFRESH_TOKEN_PRINCIPAL_ID));
token.setClientId(rs.getLong(COL_OAUTH_REFRESH_TOKEN_CLIENT_ID));
token.setScopes(rs.getBytes(COL_OAUTH_REFRESH_TOKEN_SCOPES));
token.setClaims(rs.getBytes(COL_OAUTH_REFRESH_TOKEN_CLAIMS));
token.setCreatedOn(rs.getTimestamp(COL_OAUTH_REFRESH_TOKEN_CREATED_ON));
token.setModifiedOn(rs.getTimestamp(COL_OAUTH_REFRESH_TOKEN_MODIFIED_ON));
token.setLastUsed(rs.getTimestamp(COL_OAUTH_REFRESH_TOKEN_LAST_USED));
token.setEtag(rs.getString(COL_OAUTH_REFRESH_TOKEN_ETAG));
return token;
}
@Override
public TableMapping<DBOOAuthRefreshToken> getTableMapping() {
return new TableMapping<DBOOAuthRefreshToken>() {
// Map a result set to this object
@Override
public DBOOAuthRefreshToken mapRow(ResultSet rs, int rowNum) throws SQLException {
// Use static method to avoid unintentionally referencing `this`
return DBOOAuthRefreshToken.mapRow(rs, rowNum);
}
@Override
public String getTableName() {
return TABLE_OAUTH_REFRESH_TOKEN;
}
@Override
public String getDDLFileName() {
return DDL_OAUTH_REFRESH_TOKEN;
}
@Override
public FieldColumn[] getFieldColumns() {
return FIELDS;
}
@Override
public Class<? extends DBOOAuthRefreshToken> getDBOClass() {
return DBOOAuthRefreshToken.class;
}
};
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public String getTokenHash() {
return tokenHash;
}
public void setTokenHash(String tokenHash) {
this.tokenHash = tokenHash;
}
public Long getPrincipalId() {
return principalId;
}
public void setPrincipalId(Long principalId) {
this.principalId = principalId;
}
public Long getClientId() {
return clientId;
}
public void setClientId(Long clientId) {
this.clientId = clientId;
}
public byte[] getScopes() {
return this.scopes;
}
public void setScopes(byte[] scopes) {
this.scopes = scopes;
}
public byte[] getClaims() {
return claims;
}
public void setClaims(byte[] claims) {
this.claims = claims;
}
public Timestamp getLastUsed() {
return lastUsed;
}
public void setLastUsed(Timestamp lastUsed) {
this.lastUsed = lastUsed;
}
public void setName(String name) {
this.name = name;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}
public Timestamp getModifiedOn() {
return modifiedOn;
}
public void setModifiedOn(Timestamp modifiedOn) {
this.modifiedOn = modifiedOn;
}
public String getEtag() {
return etag;
}
public void setEtag(String eTag) {
this.etag = eTag;
}
@Override
public String toString() {
return "DBOOAuthClient [id=" + id + ", tokenHash=" + tokenHash +", name=" + name +
", principalId=" + principalId + ", clientId=" + clientId + ", scopes=" + Arrays.toString(scopes) +
", claims=" + Arrays.toString(claims) + ", createdOn=" + createdOn + ", modifiedOn=" + modifiedOn
+ ", lastUsed=" + lastUsed + ", eTag=" + etag + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((tokenHash == null) ? 0 : tokenHash.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((principalId == null) ? 0 : principalId.hashCode());
result = prime * result + ((clientId == null) ? 0 : clientId.hashCode());
result = prime * result + ((scopes == null) ? 0 : Arrays.hashCode(scopes));
result = prime * result + ((scopes == null) ? 0 : Arrays.hashCode(claims));
result = prime * result + ((createdOn == null) ? 0 : createdOn.hashCode());
result = prime * result + ((modifiedOn == null) ? 0 : modifiedOn.hashCode());
result = prime * result + ((lastUsed == null) ? 0 : lastUsed.hashCode());
result = prime * result + ((etag == null) ? 0 : etag.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DBOOAuthRefreshToken other = (DBOOAuthRefreshToken) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (tokenHash == null) {
if (other.tokenHash != null)
return false;
} else if (!tokenHash.equals(other.tokenHash))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (principalId == null) {
if (other.principalId != null)
return false;
} else if (!principalId.equals(other.principalId))
return false;
if (clientId == null) {
if (other.clientId != null)
return false;
} else if (!clientId.equals(other.clientId))
return false;
if (scopes == null) {
if (other.scopes != null)
return false;
} else if (!Arrays.equals(scopes, other.scopes))
return false;
if (claims == null) {
if (other.claims != null)
return false;
} else if (!Arrays.equals(claims, other.claims))
return false;
if (createdOn == null) {
if (other.createdOn != null) {
return false;
}
} else if (!createdOn.equals(other.createdOn)) {
return false;
}
if (modifiedOn == null) {
if (other.modifiedOn != null) {
return false;
}
} else if (!modifiedOn.equals(other.modifiedOn)) {
return false;
}
if (lastUsed == null) {
if (other.lastUsed != null) {
return false;
}
} else if (!lastUsed.equals(other.lastUsed)) {
return false;
}
if (etag == null) {
if (other.etag != null) {
return false;
}
} else if (!etag.equals(other.etag)) {
return false;
}
return true;
}
@Override
public MigrationType getMigratableTableType() {
return MigrationType.OAUTH_REFRESH_TOKEN;
}
@Override
public MigratableTableTranslation<DBOOAuthRefreshToken, DBOOAuthRefreshToken> getTranslator() {
return new BasicMigratableTableTranslation<DBOOAuthRefreshToken>();
}
@Override
public Class<? extends DBOOAuthRefreshToken> getBackupClass() {
return DBOOAuthRefreshToken.class;
}
@Override
public Class<? extends DBOOAuthRefreshToken> getDatabaseObjectClass() {
return DBOOAuthRefreshToken.class;
}
@Override
public List<MigratableDatabaseObject<?,?>> getSecondaryTypes() {
return null;
}
}
| Fix column reference on incorrect table
| lib/jdomodels/src/main/java/org/sagebionetworks/repo/model/dbo/persistence/DBOOAuthRefreshToken.java | Fix column reference on incorrect table | <ide><path>ib/jdomodels/src/main/java/org/sagebionetworks/repo/model/dbo/persistence/DBOOAuthRefreshToken.java
<ide> package org.sagebionetworks.repo.model.dbo.persistence;
<ide>
<del>import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_CLIENT_NAME;
<ide> import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_CLAIMS;
<ide> import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_CLIENT_ID;
<ide> import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_OAUTH_REFRESH_TOKEN_CREATED_ON;
<ide> DBOOAuthRefreshToken token = new DBOOAuthRefreshToken();
<ide> token.setId(rs.getLong(COL_OAUTH_REFRESH_TOKEN_ID));
<ide> token.setTokenHash(rs.getString(COL_OAUTH_REFRESH_TOKEN_HASH));
<del> token.setName(rs.getString(COL_OAUTH_CLIENT_NAME));
<add> token.setName(rs.getString(COL_OAUTH_REFRESH_TOKEN_NAME));
<ide> token.setPrincipalId(rs.getLong(COL_OAUTH_REFRESH_TOKEN_PRINCIPAL_ID));
<ide> token.setClientId(rs.getLong(COL_OAUTH_REFRESH_TOKEN_CLIENT_ID));
<ide> token.setScopes(rs.getBytes(COL_OAUTH_REFRESH_TOKEN_SCOPES)); |
|
JavaScript | mit | e6f1c102dd3eb944078847bc8e21f7497d09f386 | 0 | sivertsenstian/visualclojure | const vscode = require('vscode');
const nreplClient = require('./nrepl/client');
const SESSION_TYPE = require('./nrepl/session_type');
const nreplMsg = require('./nrepl/message');
var state = require('./state'); //initial state
var statusbar_connection = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
var statusbar_type = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
var outputChannel = vscode.window.createOutputChannel("VisualClojure");
let diagnosticCollection = vscode.languages.createDiagnosticCollection('VisualClojure: Evaluation errors');
const CLOJURE_MODE = { language: 'clojure', scheme: 'file'};
let evaluateFile;
function updateStatusbar(state) {
if (state.hostname) {
statusbar_connection.text = "nrepl://" + state.hostname + ":" + state.port;
} else {
statusbar_connection.text = "nrepl - no connection";
}
statusbar_type.text = state.session_type.statusbar;
switch (state.session_type.id) {
case SESSION_TYPE.CLJ.id:
statusbar_type.color = "rgb(144,180,254)";
break;
case SESSION_TYPE.CLJS.id:
statusbar_type.color = "rgb(145,220,71)";
break;
default:
statusbar_type.color = "rgb(192,192,192)";
break;
}
statusbar_connection.show();
statusbar_type.show();
};
function findSession(state, current, sessions) {
let tmpClient = nreplClient.create({
host: state.hostname,
port: state.port
})
.once('connect', function () {
let msg = nreplMsg.testSession(sessions[current]);
tmpClient.send(msg, function (results) {
for (var i = 0; i < results.length; i++) {
let result = results[i];
if (result.value && result.value === "3.14") {
state.session = sessions[current];
state.session_type = SESSION_TYPE.CLJS;
state.cljs_session = sessions[current];
state.clj_session = sessions[current + 1];
} else if (result.ex) {
console.log("EXCEPTION!! HANDLE IT");
console.log(JSON.stringify(result));
}
}
tmpClient.end();
});
})
.once('end', function () {
//If last session, check if found
if (current === (sessions.length - 1) && state.session === null) {
//Default to first session if no cljs-session is found, and treat it as a clj-session
if (sessions.length > 0) {
state.session = sessions[0];
state.session_type = SESSION_TYPE.CLJ;
}
} else if (state.session === null) {
findSession(state, (current + 1), sessions);
} else {
evaluateFile();
}
updateStatusbar(state);
});
};
function getNamespace(text) {
let match = text.match(/^[\s\t]*\((?:[\s\t\n]*(?:in-){0,1}ns)[\s\t\n]+'?([\w.\-\/]+)[\s\S]*\)[\s\S]*/);
return match ? match[1] : 'user';
};
//using algorithm from: http://stackoverflow.com/questions/15717436/js-regex-to-match-everything-inside-braces-including-nested-braces-i-want/27088184#27088184
function getContentToNextBracket(block) {
var currPos = 0,
openBrackets = 0,
stillSearching = true,
waitForChar = false;
while (stillSearching && currPos <= block.length) {
var currChar = block.charAt(currPos);
if (!waitForChar) {
switch (currChar) {
case '(':
openBrackets++;
break;
case ')':
openBrackets--;
break;
case '"':
case "'":
waitForChar = currChar;
break;
case '/':
var nextChar = block.charAt(currPos + 1);
if (nextChar === '/') {
waitForChar = '\n';
} else if (nextChar === '*') {
waitForChar = '*/';
}
break;
}
} else {
if (currChar === waitForChar) {
if (waitForChar === '"' || waitForChar === "'") {
block.charAt(currPos - 1) !== '\\' && (waitForChar = false);
} else {
waitForChar = false;
}
} else if (currChar === '*') {
block.charAt(currPos + 1) === '/' && (waitForChar = false);
}
}
currPos++
if (openBrackets === 0) {
stillSearching = false;
}
}
return block.substr(0, currPos);
};
function getContentToPreviousBracket(block) {
var currPos = (block.length - 1),
openBrackets = 0,
stillSearching = true,
waitForChar = false;
while (stillSearching && currPos >= 0) {
var currChar = block.charAt(currPos);
if (!waitForChar) {
switch (currChar) {
case '(':
openBrackets--;
break;
case ')':
openBrackets++;
break;
case '"':
case "'":
waitForChar = currChar;
break;
case '/':
var nextChar = block.charAt(currPos + 1);
if (nextChar === '/') {
waitForChar = '\n';
} else if (nextChar === '*') {
waitForChar = '*/';
}
break;
}
} else {
if (currChar === waitForChar) {
if (waitForChar === '"' || waitForChar === "'") {
block.charAt(currPos - 1) !== '\\' && (waitForChar = false);
} else {
waitForChar = false;
}
} else if (currChar === '*') {
block.charAt(currPos + 1) === '/' && (waitForChar = false);
}
}
currPos--
if (openBrackets === 0) {
stillSearching = false;
}
}
return block.substr(currPos + 1, block.length);
};
function handleException(exceptions, isSelection = false) {
let errorHasBeenMarked = false;
diagnosticCollection.clear();
let exClient = nreplClient.create({
host: state.hostname,
port: state.port
}).once('connect', function () {
let msg = nreplMsg.stacktrace(state),
editor = vscode.window.activeTextEditor,
errLine = null,
errChar = null,
errFileUri = editor.document.uri;
exClient.send(msg, (results) => {
if (results.length === 2 && results[0].status[0] === "no-error" && results[1].status[0] === "done") {
let errorMsg = "Error when evaluating this expression..";
for(let r = 0; r < exceptions.length; r++) {
let result = exceptions[r];
if(result.hasOwnProperty('err')
&& result.err.indexOf("line") !== -1
&& result.err.indexOf("column") !== -1) {
errorHasBeenMarked = true;
let errorParts = result.err;
if (errorParts.indexOf("starting at line") !== -1 && errorParts.indexOf("and column") !== -1) {
errorParts = result.err.split(' ');
errorMsg = result.err.substring(result.err.indexOf("clojure.lang.ExceptionInfo:") + 27, result.err.indexOf("starting"));
} else if (errorParts.indexOf("at line") !== -1 && errorParts.indexOf("and column") === -1) {
errorParts = result.err.substring(result.err.indexOf('{'), result.err.indexOf('}')).replace(/:/g, '').replace(/,/g, '').replace(/\r\n/, '').replace(/}/, '').split(' ');
errorMsg = result.err.substring(result.err.indexOf("clojure.lang.ExceptionInfo:") + 27, result.err.indexOf("at line"));
} else if (errorParts.indexOf(":line") !== -1 && errorParts.indexOf(":column") !== -1) {
errorParts = result.err.substring(result.err.indexOf('{'), result.err.indexOf('}')).replace(/:/g, '').replace(/,/g, '').replace(/\r\n/, '').replace(/}/, '').split(' ');
errorMsg = result.err.substring(result.err.indexOf("clojure.lang.ExceptionInfo:") + 27, result.err.indexOf("{"));
}
errLine = parseInt(errorParts[errorParts.indexOf("line") + 1], 10) - 1;
errChar = parseInt(errorParts[errorParts.indexOf("column") + 1], 10) - 1;
}
if (result.hasOwnProperty('err') && result.err.indexOf("WARNING:") !== -1) {
errorMsg += "\n" + result.err.substring(result.err.indexOf("WARNING:"), result.err.indexOf("at line"));
}
if (result.hasOwnProperty('err') && result.err.indexOf("TypeError:") !== -1) {
errorMsg += "\n" + result.err;
}
}
if(!errorHasBeenMarked) {
diagnosticCollection.set(editor.document.uri,
[new vscode.Diagnostic(new vscode.Range(editor.selection.start.line,
editor.selection.start.character,
editor.selection.start.line,
editor.document.lineAt(editor.selection.start.line).text.length),
errorMsg, vscode.DiagnosticSeverity.Error)]);
} else if(errLine >= 0 && errChar >= 0) {
if(isSelection) {
errLine = errLine + editor.selection.start.line;
errChar = errChar + editor.selection.start.character;
}
let errPos = new vscode.Position(errLine, errChar),
errLineLength = editor.document.lineAt(errLine).text.length;
editor.selection = new vscode.Selection(errPos, errPos);
diagnosticCollection.set(errFileUri, [new vscode.Diagnostic(new vscode.Range(errLine, errChar, errLine, errLineLength),
errorMsg, vscode.DiagnosticSeverity.Error)]);
}
} else {
for(let r = 0; r < results.length; r++) {
let result = results[r],
errLine = result.line - 1,
errChar = result.column - 1,
errFile = result.file,
errFileUri = null,
errMsg = result.message,
editor = vscode.window.activeTextEditor;
if (errFile) {
errFileUri = vscode.Uri.file(errFile);
} else {
errFileUri = editor.document.uri;
}
if(errLine >= 0 && errChar >= 0) {
if(!editor.selection.isEmpty) {
errLine = errLine + editor.selection.start.line;
errChar = errChar + editor.selection.start.character;
}
let errPos = new vscode.Position(errLine, errChar);
editor.selection = new vscode.Selection(errPos, errPos);
let errLineLength = editor.document.lineAt(errLine).text.length;
diagnosticCollection.set(errFileUri, [new vscode.Diagnostic(new vscode.Range(errLine, errChar, errLine, errLineLength),
errMsg, vscode.DiagnosticSeverity.Error)]);
}
}
}
exClient.end();
});
});
};
function activate(context) {
context.subscriptions.push(vscode.languages.setLanguageConfiguration('clojure', {}));
updateStatusbar(state);
let connectToREPL = vscode.commands.registerCommand('visualclojure.connectToREPL', function () {
vscode.window.showInputBox({
placeHolder: "Enter existing nREPL hostname:port here...",
prompt: "Add port to nREPL if localhost, otherwise 'hostname:port'",
value: "localhost:",
ignoreFocusOut: true
})
.then(function (url) {
let [hostname, port] = url.split(':');
state.hostname = hostname;
state.port = port;
let lsSessionClient = nreplClient.create({
host: state.hostname,
port: state.port
}).once('connect', function () {
state.connected = true;
let msg = nreplMsg.listSessions();
lsSessionClient.send(msg, function (results) {
findSession(state, 0, results[0].sessions);
lsSessionClient.end();
});
});
});
});
context.subscriptions.push(connectToREPL);
let evaluateExpression = vscode.commands.registerCommand('visualclojure.evaluateExpression', function () {
if (state.connected) {
let editor = vscode.window.activeTextEditor;
if (editor !== undefined) {
let filetypeIndex = (editor.document.fileName.lastIndexOf('.') + 1),
filetype = editor.document.fileName.substr(filetypeIndex,
editor.document.fileName.length);
if (state.session_type.supports.indexOf(filetype) >= 0) {
let documentText = editor.document.getText(),
selection = editor.selection,
isSelection = !selection.isEmpty,
code = '';
if (isSelection) { //text selected by user, try to evaluate it
code = editor.document.getText(selection);
//If a '(' or ')' is selected, evaluate the expression within
if (code === '(') {
let currentPosition = selection.active,
previousPosition = currentPosition.with(currentPosition.line, Math.max((currentPosition.character - 1), 0)),
lastLine = editor.document.lineCount,
endPosition = currentPosition.with(lastLine, editor.document.lineAt(Math.max(lastLine - 1, 0)).text.length),
textSelection = new vscode.Selection(previousPosition, endPosition);
code = getContentToNextBracket(editor.document.getText(textSelection));
} else if (code === ')') {
let currentPosition = selection.active,
startPosition = currentPosition.with(0, 0),
textSelection = new vscode.Selection(startPosition, currentPosition);
code = getContentToPreviousBracket(editor.document.getText(textSelection));
}
} else { //no text selected, check if cursor at a start '(' or end ')' and evaluate the expression within
let currentPosition = selection.active,
nextPosition = currentPosition.with(currentPosition.line, (currentPosition.character + 1)),
previousPosition = currentPosition.with(currentPosition.line, Math.max((currentPosition.character - 1), 0)),
nextSelection = new vscode.Selection(currentPosition, nextPosition),
previousSelection = new vscode.Selection(previousPosition, currentPosition),
nextChar = editor.document.getText(nextSelection),
prevChar = editor.document.getText(previousSelection);
if (nextChar === '(' || prevChar === '(') {
let lastLine = editor.document.lineCount,
endPosition = currentPosition.with(lastLine, editor.document.lineAt(Math.max(lastLine - 1, 0)).text.length),
startPosition = (nextChar === '(') ? currentPosition : previousPosition,
textSelection = new vscode.Selection(startPosition, endPosition);
code = getContentToNextBracket(editor.document.getText(textSelection));
} else if (nextChar === ')' || prevChar === ')') {
let startPosition = currentPosition.with(0, 0),
endPosition = (prevChar === ')') ? currentPosition : nextPosition,
textSelection = new vscode.Selection(startPosition, endPosition);
code = getContentToPreviousBracket(editor.document.getText(textSelection));
}
}
if (code.length > 0) {
outputChannel.clear();
outputChannel.appendLine("Evaluating \n" + code);
outputChannel.appendLine("----------------------------");
let evalClient = nreplClient.create({
host: state.hostname,
port: state.port
}).once('connect', function () {
let msg = nreplMsg.evaluate(state, getNamespace(documentText), code);
evalClient.send(msg, function (results) {
for (var i = 0; i < results.length; i++) {
let result = results[i];
if (result.hasOwnProperty('out')) {
outputChannel.appendLine("side effects:");
outputChannel.append(result.out);
} else if (result.hasOwnProperty('value')) {
outputChannel.appendLine("Evaluation: success");
outputChannel.appendLine("=>")
outputChannel.appendLine((result.value.length > 0 ? result.value : "no result.."));
} else if (result.ex) {
outputChannel.appendLine("Evaluation: failure");
outputChannel.appendLine("=>");
outputChannel.appendLine(result.ex);
handleException(results, true);
}
}
outputChannel.appendLine("----------- done -----------\n");
outputChannel.show(true);
evalClient.end();
});
});
}
} else {
vscode.window.showErrorMessage("Filetype " + filetype + " not supported by current nREPL => " + state.session_type.statusbar);
}
}
}
});
context.subscriptions.push(evaluateExpression);
evaluateFile = function (document = null) {
if (state.connected) {
let editor = vscode.window.activeTextEditor;
document = document === null ? editor.document : document;
if (editor !== undefined) {
let filetypeIndex = (document.fileName.lastIndexOf('.') + 1);
let filetype = document.fileName.substr(filetypeIndex,
document.fileName.length);
if (state.session_type.supports.indexOf(filetype) >= 0) {
let documentText = document.getText();
let hasText = documentText.length > 0;
if (hasText) {
let fileNameIndex = (document.fileName.lastIndexOf('\\') + 1),
fileName = document.fileName.substr(fileNameIndex, document.fileName.length),
filePath = document.fileName;
outputChannel.clear();
outputChannel.appendLine("Evaluating " + fileName);
outputChannel.appendLine("----------------------------");
diagnosticCollection.clear();
let evalClient = nreplClient.create({
host: state.hostname,
port: state.port
}).once('connect', function () {
let msg = nreplMsg.loadFile(state, documentText, fileName, filePath);
evalClient.send(msg, function (results) {
for (var r = 0; r < results.length; r++) {
let result = results[r];
if (result.hasOwnProperty('out')) {
outputChannel.appendLine("side effects:");
outputChannel.append(result.out);
} else if (result.hasOwnProperty('value')) {
outputChannel.appendLine("Evaluation: success");
outputChannel.appendLine("=>")
outputChannel.appendLine((result.value.length > 0 ? result.value : "no result.."));
} else if (result.ex) {
outputChannel.appendLine("Evaluation: failure");
outputChannel.appendLine("=>");
outputChannel.appendLine(result.ex);
handleException(results);
}
}
outputChannel.appendLine("----------- done -----------\n");
outputChannel.show(true);
evalClient.end();
});
});
}
} else {
vscode.window.showErrorMessage("Filetype " + filetype + " not supported by current repl => " + state.session_type.statusbar);
}
}
}
};
context.subscriptions.push(vscode.commands.registerCommand('visualclojure.evaluateFile', evaluateFile));
context.subscriptions.push(vscode.workspace.onDidOpenTextDocument((document) => {
evaluateFile(document);
}));
context.subscriptions.push(vscode.workspace.onDidOpenTextDocument((document) => {
evaluateFile(document);
}));
context.subscriptions.push(vscode.workspace.onDidSaveTextDocument((document) => {
evaluateFile(document);
}));
class HoverProviderTest {
constructor() {
this.wordBinders = ['/', '-'];
this.specialWords = ['-', '+', '/', '*']; //TODO: Add more here, '*' not supported by bencoder
}
formatDocString (arglist, doc) {
let result = '';
if(arglist !== 'undefined'){
result += '**signature:**\n\n'
result += arglist.substring(1, arglist.length - 1)
.replace(/\]\ \[/g, ']\n\n[');
}
if(doc !== 'undefined'){
result += '\n\n**description:**\n\n'
result += '```clojure\n' + doc.replace(/\s\s+/g, ' ') + '\n```';
}
result += '';
return result.length > 0 ? result : "";
}
getActualWord(document, position, selected, word) {
if(selected !== undefined) {
let preChar = document.lineAt(position.line).text.slice(selected.start.character - 1, selected.start.character),
postChar = document.lineAt(position.line).text.slice(selected.end.character, selected.end.character + 1);
if (this.wordBinders.indexOf(preChar) !== -1) {
let prePosition = new vscode.Position(selected.start.line, selected.start.character - 1),
preSelected = document.getWordRangeAtPosition(prePosition),
preText = document.getText(new vscode.Range(preSelected.start, preSelected.end));
return this.getActualWord(document, prePosition, new vscode.Range(preSelected.start, selected.end), preText + preChar + word);
} else if (this.wordBinders.indexOf(postChar) !== -1) {
let postPosition = new vscode.Position(selected.end.line, selected.end.character + 1),
postSelected = document.getWordRangeAtPosition(postPosition),
postText = document.getText(new vscode.Range(postSelected.start, postSelected.end));
return this.getActualWord(document, postPosition, new vscode.Range(selected.start, postSelected.end), word + postChar + postText);
} else {
return word
}
} else {
let selectedChar = document.lineAt(position.line).text.slice(position.character, position.character + 1),
isFn = document.lineAt(position.line).text.slice(position.character - 1, position.character) === "(";
if(this.specialWords.indexOf(selectedChar) !== -1 && isFn) {
return selectedChar;
} else {
console.error("Unsupported selectedChar '" + selectedChar + "'");
return word;
}
}
}
provideHover (document, position, token) {
let selected = document.getWordRangeAtPosition(position),
selectedText = selected !== undefined ? document.getText(new vscode.Range(selected.start, selected.end)) : "",
text = this.getActualWord(document, position, selected, selectedText),
arglist = "",
docstring = "",
scope = this;
if(state.connected) {
return new Promise((resolve, reject) => {
let infoClient = nreplClient.create({
host: state.hostname,
port: state.port
}).once('connect', () => {
let msg = nreplMsg.info(state, getNamespace(document.getText()), text);
infoClient.send(msg, function (results) {
for (var r = 0; r < results.length; r++) {
let result = results[r];
arglist += result['arglists-str'];
docstring += result.doc;
}
infoClient.end();
if (docstring.length === 0) {
reject("Docstring not found for " + text);
} else {
let result = scope.formatDocString(arglist, docstring);
if(result.length === 0) {
reject("Docstring not found for " + text);
} else {
resolve(new vscode.Hover(result));
}
}
});
});
});
} else {
return new vscode.Hover("Not connected to nREPL..");
}
}
}
context.subscriptions.push(vscode.languages.registerHoverProvider(CLOJURE_MODE, new HoverProviderTest()));
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {}
exports.deactivate = deactivate;
| src/extension.js | const vscode = require('vscode');
const nreplClient = require('./nrepl/client');
const SESSION_TYPE = require('./nrepl/session_type');
const nreplMsg = require('./nrepl/message');
var state = require('./state'); //initial state
var statusbar_connection = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
var statusbar_type = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
var outputChannel = vscode.window.createOutputChannel("VisualClojure");
let diagnosticCollection = vscode.languages.createDiagnosticCollection('VisualClojure: Evaluation errors');
let evaluateFile;
function updateStatusbar(state) {
if (state.hostname) {
statusbar_connection.text = "nrepl://" + state.hostname + ":" + state.port;
} else {
statusbar_connection.text = "nrepl - no connection";
}
statusbar_type.text = state.session_type.statusbar;
switch (state.session_type.id) {
case SESSION_TYPE.CLJ.id:
statusbar_type.color = "rgb(144,180,254)";
break;
case SESSION_TYPE.CLJS.id:
statusbar_type.color = "rgb(145,220,71)";
break;
default:
statusbar_type.color = "rgb(192,192,192)";
break;
}
statusbar_connection.show();
statusbar_type.show();
};
function findSession(state, current, sessions) {
let tmpClient = nreplClient.create({
host: state.hostname,
port: state.port
})
.once('connect', function () {
let msg = nreplMsg.testSession(sessions[current]);
tmpClient.send(msg, function (results) {
for (var i = 0; i < results.length; i++) {
let result = results[i];
if (result.value && result.value === "3.14") {
state.session = sessions[current];
state.session_type = SESSION_TYPE.CLJS;
state.cljs_session = sessions[current];
state.clj_session = sessions[current + 1];
} else if (result.ex) {
console.log("EXCEPTION!! HANDLE IT");
console.log(JSON.stringify(result));
}
}
tmpClient.end();
});
})
.once('end', function () {
//If last session, check if found
if (current === (sessions.length - 1) && state.session === null) {
//Default to first session if no cljs-session is found, and treat it as a clj-session
if (sessions.length > 0) {
state.session = sessions[0];
state.session_type = SESSION_TYPE.CLJ;
}
} else if (state.session === null) {
findSession(state, (current + 1), sessions);
} else {
evaluateFile();
}
updateStatusbar(state);
});
};
function getNamespace(text) {
let match = text.match(/^[\s\t]*\((?:[\s\t\n]*(?:in-){0,1}ns)[\s\t\n]+'?([\w.\-\/]+)[\s\S]*\)[\s\S]*/);
return match ? match[1] : 'user';
};
//using algorithm from: http://stackoverflow.com/questions/15717436/js-regex-to-match-everything-inside-braces-including-nested-braces-i-want/27088184#27088184
function getContentToNextBracket(block) {
var currPos = 0,
openBrackets = 0,
stillSearching = true,
waitForChar = false;
while (stillSearching && currPos <= block.length) {
var currChar = block.charAt(currPos);
if (!waitForChar) {
switch (currChar) {
case '(':
openBrackets++;
break;
case ')':
openBrackets--;
break;
case '"':
case "'":
waitForChar = currChar;
break;
case '/':
var nextChar = block.charAt(currPos + 1);
if (nextChar === '/') {
waitForChar = '\n';
} else if (nextChar === '*') {
waitForChar = '*/';
}
break;
}
} else {
if (currChar === waitForChar) {
if (waitForChar === '"' || waitForChar === "'") {
block.charAt(currPos - 1) !== '\\' && (waitForChar = false);
} else {
waitForChar = false;
}
} else if (currChar === '*') {
block.charAt(currPos + 1) === '/' && (waitForChar = false);
}
}
currPos++
if (openBrackets === 0) {
stillSearching = false;
}
}
return block.substr(0, currPos);
};
function getContentToPreviousBracket(block) {
var currPos = (block.length - 1),
openBrackets = 0,
stillSearching = true,
waitForChar = false;
while (stillSearching && currPos >= 0) {
var currChar = block.charAt(currPos);
if (!waitForChar) {
switch (currChar) {
case '(':
openBrackets--;
break;
case ')':
openBrackets++;
break;
case '"':
case "'":
waitForChar = currChar;
break;
case '/':
var nextChar = block.charAt(currPos + 1);
if (nextChar === '/') {
waitForChar = '\n';
} else if (nextChar === '*') {
waitForChar = '*/';
}
break;
}
} else {
if (currChar === waitForChar) {
if (waitForChar === '"' || waitForChar === "'") {
block.charAt(currPos - 1) !== '\\' && (waitForChar = false);
} else {
waitForChar = false;
}
} else if (currChar === '*') {
block.charAt(currPos + 1) === '/' && (waitForChar = false);
}
}
currPos--
if (openBrackets === 0) {
stillSearching = false;
}
}
return block.substr(currPos + 1, block.length);
};
function handleException(exceptions, isSelection = false) {
let errorHasBeenMarked = false;
diagnosticCollection.clear();
let exClient = nreplClient.create({
host: state.hostname,
port: state.port
}).once('connect', function () {
let msg = nreplMsg.stacktrace(state),
editor = vscode.window.activeTextEditor,
errLine = null,
errChar = null,
errFileUri = editor.document.uri;
exClient.send(msg, (results) => {
if (results.length === 2 && results[0].status[0] === "no-error" && results[1].status[0] === "done") {
let errorMsg = "Error when evaluating this expression..";
for(let r = 0; r < exceptions.length; r++) {
let result = exceptions[r];
if(result.hasOwnProperty('err')
&& result.err.indexOf("line") !== -1
&& result.err.indexOf("column") !== -1) {
errorHasBeenMarked = true;
let errorParts = result.err;
if (errorParts.indexOf("starting at line") !== -1 && errorParts.indexOf("and column") !== -1) {
errorParts = result.err.split(' ');
errorMsg = result.err.substring(result.err.indexOf("clojure.lang.ExceptionInfo:") + 27, result.err.indexOf("starting"));
} else if (errorParts.indexOf("at line") !== -1 && errorParts.indexOf("and column") === -1) {
errorParts = result.err.substring(result.err.indexOf('{'), result.err.indexOf('}')).replace(/:/g, '').replace(/,/g, '').replace(/\r\n/, '').replace(/}/, '').split(' ');
errorMsg = result.err.substring(result.err.indexOf("clojure.lang.ExceptionInfo:") + 27, result.err.indexOf("at line"));
} else if (errorParts.indexOf(":line") !== -1 && errorParts.indexOf(":column") !== -1) {
errorParts = result.err.substring(result.err.indexOf('{'), result.err.indexOf('}')).replace(/:/g, '').replace(/,/g, '').replace(/\r\n/, '').replace(/}/, '').split(' ');
errorMsg = result.err.substring(result.err.indexOf("clojure.lang.ExceptionInfo:") + 27, result.err.indexOf("{"));
}
errLine = parseInt(errorParts[errorParts.indexOf("line") + 1], 10) - 1;
errChar = parseInt(errorParts[errorParts.indexOf("column") + 1], 10) - 1;
}
if (result.hasOwnProperty('err') && result.err.indexOf("WARNING:") !== -1) {
errorMsg += "\n" + result.err.substring(result.err.indexOf("WARNING:"), result.err.indexOf("at line"));
}
if (result.hasOwnProperty('err') && result.err.indexOf("TypeError:") !== -1) {
errorMsg += "\n" + result.err;
}
}
if(!errorHasBeenMarked) {
diagnosticCollection.set(editor.document.uri,
[new vscode.Diagnostic(new vscode.Range(editor.selection.start.line,
editor.selection.start.character,
editor.selection.start.line,
editor.document.lineAt(editor.selection.start.line).text.length),
errorMsg, vscode.DiagnosticSeverity.Error)]);
} else if(errLine >= 0 && errChar >= 0) {
if(isSelection) {
errLine = errLine + editor.selection.start.line;
errChar = errChar + editor.selection.start.character;
}
let errPos = new vscode.Position(errLine, errChar),
errLineLength = editor.document.lineAt(errLine).text.length;
editor.selection = new vscode.Selection(errPos, errPos);
diagnosticCollection.set(errFileUri, [new vscode.Diagnostic(new vscode.Range(errLine, errChar, errLine, errLineLength),
errorMsg, vscode.DiagnosticSeverity.Error)]);
}
} else {
for(let r = 0; r < results.length; r++) {
let result = results[r],
errLine = result.line - 1,
errChar = result.column - 1,
errFile = result.file,
errFileUri = null,
errMsg = result.message,
editor = vscode.window.activeTextEditor;
if (errFile) {
errFileUri = vscode.Uri.file(errFile);
} else {
errFileUri = editor.document.uri;
}
if(errLine >= 0 && errChar >= 0) {
if(!editor.selection.isEmpty) {
errLine = errLine + editor.selection.start.line;
errChar = errChar + editor.selection.start.character;
}
let errPos = new vscode.Position(errLine, errChar);
editor.selection = new vscode.Selection(errPos, errPos);
let errLineLength = editor.document.lineAt(errLine).text.length;
diagnosticCollection.set(errFileUri, [new vscode.Diagnostic(new vscode.Range(errLine, errChar, errLine, errLineLength),
errMsg, vscode.DiagnosticSeverity.Error)]);
}
}
}
exClient.end();
});
});
};
function activate(context) {
updateStatusbar(state);
let connectToREPL = vscode.commands.registerCommand('visualclojure.connectToREPL', function () {
vscode.window.showInputBox({
placeHolder: "Enter existing nREPL hostname:port here...",
prompt: "Add port to nREPL if localhost, otherwise 'hostname:port'",
value: "localhost:",
ignoreFocusOut: true
})
.then(function (url) {
let [hostname, port] = url.split(':');
state.hostname = hostname;
state.port = port;
let lsSessionClient = nreplClient.create({
host: state.hostname,
port: state.port
}).once('connect', function () {
state.connected = true;
let msg = nreplMsg.listSessions();
lsSessionClient.send(msg, function (results) {
findSession(state, 0, results[0].sessions);
lsSessionClient.end();
});
});
});
});
context.subscriptions.push(connectToREPL);
let evaluateExpression = vscode.commands.registerCommand('visualclojure.evaluateExpression', function () {
if (state.connected) {
let editor = vscode.window.activeTextEditor;
if (editor !== undefined) {
let filetypeIndex = (editor.document.fileName.lastIndexOf('.') + 1),
filetype = editor.document.fileName.substr(filetypeIndex,
editor.document.fileName.length);
if (state.session_type.supports.indexOf(filetype) >= 0) {
let documentText = editor.document.getText(),
selection = editor.selection,
isSelection = !selection.isEmpty,
code = '';
if (isSelection) { //text selected by user, try to evaluate it
code = editor.document.getText(selection);
//If a '(' or ')' is selected, evaluate the expression within
if (code === '(') {
let currentPosition = selection.active,
previousPosition = currentPosition.with(currentPosition.line, Math.max((currentPosition.character - 1), 0)),
lastLine = editor.document.lineCount,
endPosition = currentPosition.with(lastLine, editor.document.lineAt(Math.max(lastLine - 1, 0)).text.length),
textSelection = new vscode.Selection(previousPosition, endPosition);
code = getContentToNextBracket(editor.document.getText(textSelection));
} else if (code === ')') {
let currentPosition = selection.active,
startPosition = currentPosition.with(0, 0),
textSelection = new vscode.Selection(startPosition, currentPosition);
code = getContentToPreviousBracket(editor.document.getText(textSelection));
}
} else { //no text selected, check if cursor at a start '(' or end ')' and evaluate the expression within
let currentPosition = selection.active,
nextPosition = currentPosition.with(currentPosition.line, (currentPosition.character + 1)),
previousPosition = currentPosition.with(currentPosition.line, Math.max((currentPosition.character - 1), 0)),
nextSelection = new vscode.Selection(currentPosition, nextPosition),
previousSelection = new vscode.Selection(previousPosition, currentPosition),
nextChar = editor.document.getText(nextSelection),
prevChar = editor.document.getText(previousSelection);
if (nextChar === '(' || prevChar === '(') {
let lastLine = editor.document.lineCount,
endPosition = currentPosition.with(lastLine, editor.document.lineAt(Math.max(lastLine - 1, 0)).text.length),
startPosition = (nextChar === '(') ? currentPosition : previousPosition,
textSelection = new vscode.Selection(startPosition, endPosition);
code = getContentToNextBracket(editor.document.getText(textSelection));
} else if (nextChar === ')' || prevChar === ')') {
let startPosition = currentPosition.with(0, 0),
endPosition = (prevChar === ')') ? currentPosition : nextPosition,
textSelection = new vscode.Selection(startPosition, endPosition);
code = getContentToPreviousBracket(editor.document.getText(textSelection));
}
}
if (code.length > 0) {
outputChannel.clear();
outputChannel.appendLine("Evaluating \n" + code);
outputChannel.appendLine("----------------------------");
let evalClient = nreplClient.create({
host: state.hostname,
port: state.port
}).once('connect', function () {
let msg = nreplMsg.evaluate(state, getNamespace(documentText), code);
evalClient.send(msg, function (results) {
for (var i = 0; i < results.length; i++) {
let result = results[i];
if (result.hasOwnProperty('out')) {
outputChannel.appendLine("side effects:");
outputChannel.append(result.out);
} else if (result.hasOwnProperty('value')) {
outputChannel.appendLine("Evaluation: success");
outputChannel.appendLine("=>")
outputChannel.appendLine((result.value.length > 0 ? result.value : "no result.."));
} else if (result.ex) {
outputChannel.appendLine("Evaluation: failure");
outputChannel.appendLine("=>");
outputChannel.appendLine(result.ex);
handleException(results, true);
}
}
outputChannel.appendLine("----------- done -----------\n");
outputChannel.show(true);
evalClient.end();
});
});
}
} else {
vscode.window.showErrorMessage("Filetype " + filetype + " not supported by current nREPL => " + state.session_type.statusbar);
}
}
}
});
context.subscriptions.push(evaluateExpression);
evaluateFile = function (document = null) {
if (state.connected) {
let editor = vscode.window.activeTextEditor;
document = document === null ? editor.document : document;
if (editor !== undefined) {
let filetypeIndex = (document.fileName.lastIndexOf('.') + 1);
let filetype = document.fileName.substr(filetypeIndex,
document.fileName.length);
if (state.session_type.supports.indexOf(filetype) >= 0) {
let documentText = document.getText();
let hasText = documentText.length > 0;
if (hasText) {
let fileNameIndex = (document.fileName.lastIndexOf('\\') + 1),
fileName = document.fileName.substr(fileNameIndex, document.fileName.length),
filePath = document.fileName;
outputChannel.clear();
outputChannel.appendLine("Evaluating " + fileName);
outputChannel.appendLine("----------------------------");
diagnosticCollection.clear();
let evalClient = nreplClient.create({
host: state.hostname,
port: state.port
}).once('connect', function () {
let msg = nreplMsg.loadFile(state, documentText, fileName, filePath);
evalClient.send(msg, function (results) {
for (var r = 0; r < results.length; r++) {
let result = results[r];
if (result.hasOwnProperty('out')) {
outputChannel.appendLine("side effects:");
outputChannel.append(result.out);
} else if (result.hasOwnProperty('value')) {
outputChannel.appendLine("Evaluation: success");
outputChannel.appendLine("=>")
outputChannel.appendLine((result.value.length > 0 ? result.value : "no result.."));
} else if (result.ex) {
outputChannel.appendLine("Evaluation: failure");
outputChannel.appendLine("=>");
outputChannel.appendLine(result.ex);
handleException(results);
}
}
outputChannel.appendLine("----------- done -----------\n");
outputChannel.show(true);
evalClient.end();
});
});
}
} else {
vscode.window.showErrorMessage("Filetype " + filetype + " not supported by current repl => " + state.session_type.statusbar);
}
}
}
};
context.subscriptions.push(vscode.commands.registerCommand('visualclojure.evaluateFile', evaluateFile));
context.subscriptions.push(vscode.workspace.onDidOpenTextDocument((document) => {
evaluateFile(document);
}));
context.subscriptions.push(vscode.workspace.onDidOpenTextDocument((document) => {
evaluateFile(document);
}));
context.subscriptions.push(vscode.workspace.onDidSaveTextDocument((document) => {
evaluateFile(document);
}));
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {}
exports.deactivate = deactivate;
| Implemented hoverprovider to show arguments and docstring on hover for both clj and cljs.
| src/extension.js | Implemented hoverprovider to show arguments and docstring on hover for both clj and cljs. | <ide><path>rc/extension.js
<ide> var outputChannel = vscode.window.createOutputChannel("VisualClojure");
<ide> let diagnosticCollection = vscode.languages.createDiagnosticCollection('VisualClojure: Evaluation errors');
<ide>
<add>const CLOJURE_MODE = { language: 'clojure', scheme: 'file'};
<ide> let evaluateFile;
<ide>
<ide> function updateStatusbar(state) {
<ide> };
<ide>
<ide> function activate(context) {
<add> context.subscriptions.push(vscode.languages.setLanguageConfiguration('clojure', {}));
<ide> updateStatusbar(state);
<ide>
<ide> let connectToREPL = vscode.commands.registerCommand('visualclojure.connectToREPL', function () {
<ide> context.subscriptions.push(vscode.workspace.onDidSaveTextDocument((document) => {
<ide> evaluateFile(document);
<ide> }));
<add>
<add> class HoverProviderTest {
<add> constructor() {
<add> this.wordBinders = ['/', '-'];
<add> this.specialWords = ['-', '+', '/', '*']; //TODO: Add more here, '*' not supported by bencoder
<add> }
<add>
<add> formatDocString (arglist, doc) {
<add> let result = '';
<add> if(arglist !== 'undefined'){
<add> result += '**signature:**\n\n'
<add> result += arglist.substring(1, arglist.length - 1)
<add> .replace(/\]\ \[/g, ']\n\n[');
<add> }
<add> if(doc !== 'undefined'){
<add> result += '\n\n**description:**\n\n'
<add> result += '```clojure\n' + doc.replace(/\s\s+/g, ' ') + '\n```';
<add> }
<add> result += '';
<add> return result.length > 0 ? result : "";
<add> }
<add>
<add> getActualWord(document, position, selected, word) {
<add> if(selected !== undefined) {
<add> let preChar = document.lineAt(position.line).text.slice(selected.start.character - 1, selected.start.character),
<add> postChar = document.lineAt(position.line).text.slice(selected.end.character, selected.end.character + 1);
<add>
<add> if (this.wordBinders.indexOf(preChar) !== -1) {
<add> let prePosition = new vscode.Position(selected.start.line, selected.start.character - 1),
<add> preSelected = document.getWordRangeAtPosition(prePosition),
<add> preText = document.getText(new vscode.Range(preSelected.start, preSelected.end));
<add>
<add> return this.getActualWord(document, prePosition, new vscode.Range(preSelected.start, selected.end), preText + preChar + word);
<add> } else if (this.wordBinders.indexOf(postChar) !== -1) {
<add> let postPosition = new vscode.Position(selected.end.line, selected.end.character + 1),
<add> postSelected = document.getWordRangeAtPosition(postPosition),
<add> postText = document.getText(new vscode.Range(postSelected.start, postSelected.end));
<add>
<add> return this.getActualWord(document, postPosition, new vscode.Range(selected.start, postSelected.end), word + postChar + postText);
<add> } else {
<add> return word
<add> }
<add>
<add> } else {
<add> let selectedChar = document.lineAt(position.line).text.slice(position.character, position.character + 1),
<add> isFn = document.lineAt(position.line).text.slice(position.character - 1, position.character) === "(";
<add> if(this.specialWords.indexOf(selectedChar) !== -1 && isFn) {
<add> return selectedChar;
<add> } else {
<add> console.error("Unsupported selectedChar '" + selectedChar + "'");
<add> return word;
<add> }
<add> }
<add> }
<add>
<add> provideHover (document, position, token) {
<add> let selected = document.getWordRangeAtPosition(position),
<add> selectedText = selected !== undefined ? document.getText(new vscode.Range(selected.start, selected.end)) : "",
<add> text = this.getActualWord(document, position, selected, selectedText),
<add> arglist = "",
<add> docstring = "",
<add> scope = this;
<add> if(state.connected) {
<add> return new Promise((resolve, reject) => {
<add> let infoClient = nreplClient.create({
<add> host: state.hostname,
<add> port: state.port
<add> }).once('connect', () => {
<add> let msg = nreplMsg.info(state, getNamespace(document.getText()), text);
<add> infoClient.send(msg, function (results) {
<add> for (var r = 0; r < results.length; r++) {
<add> let result = results[r];
<add>
<add> arglist += result['arglists-str'];
<add> docstring += result.doc;
<add> }
<add> infoClient.end();
<add> if (docstring.length === 0) {
<add> reject("Docstring not found for " + text);
<add> } else {
<add> let result = scope.formatDocString(arglist, docstring);
<add> if(result.length === 0) {
<add> reject("Docstring not found for " + text);
<add> } else {
<add> resolve(new vscode.Hover(result));
<add> }
<add> }
<add> });
<add> });
<add> });
<add> } else {
<add> return new vscode.Hover("Not connected to nREPL..");
<add> }
<add> }
<add> }
<add> context.subscriptions.push(vscode.languages.registerHoverProvider(CLOJURE_MODE, new HoverProviderTest()));
<ide> }
<ide> exports.activate = activate;
<ide> |
|
Java | apache-2.0 | cfc8941f41eeb1628e4f4665efb9a887549f845c | 0 | jsmadja/shmuphiscores,jsmadja/shmuphiscores,jsmadja/shmuphiscores | package controllers;
import actions.User;
import com.avaje.ebean.Ebean;
import com.google.common.base.Predicate;
import models.Difficulty;
import models.Game;
import models.Mode;
import models.Platform;
import models.Player;
import models.Score;
import models.Ship;
import models.Stage;
import play.Logger;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.score_create;
import views.html.score_import;
import views.html.score_update;
import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import static com.avaje.ebean.Ebean.find;
import static com.google.common.collect.Collections2.filter;
import static java.lang.Long.parseLong;
import static java.math.RoundingMode.HALF_UP;
import static org.apache.commons.lang3.StringUtils.isNumeric;
import static play.data.Form.form;
public class ScoreController extends Controller {
public static Result selectGame() {
return ok(views.html.select_game.render(Game.findAll()));
}
public static Result fillForm() {
models.Game game = Game.finder.byId(Long.parseLong(request().body().asFormUrlEncoded().get("game")[0]));
return ok(score_create.render(game, form(Score.class)));
}
public static Result fillFormWithGame(Game game) {
return ok(score_create.render(game, form(Score.class)));
}
public static Result importScores(Game game) {
return ok(score_import.render(game, form(Score.class)));
}
public static Result read(models.Score score) {
if (score == null) {
return notFound();
}
return ok(score_update.render(score));
}
public static Result save() {
if (!User.current().isAuthenticated()) {
return unauthorized();
}
Form<models.Score> scoreForm = new Form<models.Score>(models.Score.class).bindFromRequest();
Map<String, String> data = scoreForm.data();
Logger.info("Nouveau score envoyé par " + User.current().name + ", " + data.toString());
models.Score score = createScore(data);
if (score.isWorstThanOlders()) {
scoreForm.reject("Score inférieur à un score déjà présent dans la base.");
return badRequest(views.html.score_create.render(score.game, scoreForm));
}
score.save();
RankingController.getRankingCache().remove(score.game);
score.game.recomputeRankings();
return shmup(score);
}
public static Result update() {
Form<models.Score> scoreForm = new Form<models.Score>(models.Score.class).bindFromRequest();
Map<String, String> data = scoreForm.data();
Logger.info("Mise a jour du score envoyé par " + User.current().name + ", " + data.toString());
models.Score score = Ebean.find(models.Score.class, Long.valueOf(data.get("scoreId")));
if (!score.isPlayedBy(User.current())) {
return unauthorized();
}
updateScore(score, data);
score.update();
RankingController.getRankingCache().remove(score.game);
score.game.recomputeRankings();
return redirect("/");
}
public static Result shmup(models.Score score) {
return ok(views.html.post_to_shmup.render(score));
}
private static models.Score createScore(Map<String, String> data) {
String login = User.current().name;
return createScore(data, login);
}
private static Score createScore(Map<String, String> data, String login) {
Difficulty difficulty = difficulty(data);
Stage stage = find(Stage.class, parseLong(data.get("stage")));
Ship ship = ship(data);
Mode mode = mode(data);
Platform platform = find(Platform.class, parseLong(data.get("platform")));
Player player = Player.findOrCreatePlayer(login);
Game game = find(Game.class, parseLong(data.get("gameId")));
BigDecimal value = value(data);
String comment = data.get("comment");
String replay = data.get("replay");
String photo = data.get("photo");
return new Score(game, player, stage, ship, mode, difficulty, comment, platform, value, photo, replay);
}
private static void updateScore(models.Score score, Map<String, String> data) {
score.stage = find(Stage.class, parseLong(data.get("stage")));
score.mode = mode(data);
score.difficulty = difficulty(data);
score.comment = data.get("comment");
score.platform = find(Platform.class, parseLong(data.get("platform")));
score.value = value(data);
score.photo = data.get("photo");
score.replay = data.get("replay");
}
private static Difficulty difficulty(Map<String, String> data) {
Difficulty difficulty = null;
if (data.get("difficulty") != null) {
difficulty = find(Difficulty.class, parseLong(data.get("difficulty")));
}
return difficulty;
}
private static BigDecimal value(Map<String, String> data) {
String scoreValue = data.get("value");
StringBuilder strValue = new StringBuilder();
for (Character c : scoreValue.toCharArray()) {
if (isNumeric(c.toString())) {
strValue.append(c);
}
}
return new BigDecimal(strValue.toString());
}
private static Mode mode(Map<String, String> data) {
Mode mode = null;
if (data.get("mode") != null) {
mode = find(Mode.class, parseLong(data.get("mode")));
}
return mode;
}
private static Ship ship(Map<String, String> data) {
Ship ship = null;
if (data.get("ship") != null) {
ship = find(Ship.class, parseLong(data.get("ship")));
}
return ship;
}
public static Collection<Score> findProgressionOf(final Score score) {
List<Score> scores = score.player.allScores;
scores = new ArrayList<Score>(filter(scores, new Predicate<Score>() {
@Override
public boolean apply(@Nullable Score _score) {
return score.game.equals(_score.game) && score.mode == _score.mode && score.difficulty == _score.difficulty;
}
}));
if (scores.size() > 1) {
for (int i = 1; i < scores.size(); i++) {
Score previous = scores.get(i - 1);
Score current = scores.get(i);
BigDecimal gap = current.value.subtract(previous.value);
current.gapWithPreviousScore = gap.multiply(BigDecimal.valueOf(100)).divide(previous.value, HALF_UP).longValue();
}
}
return scores;
}
public static Result importScore(Game game) {
if (!User.current().isAuthenticated()) {
return unauthorized();
}
Form<models.Score> scoreForm = new Form<models.Score>(models.Score.class).bindFromRequest();
Map<String, String> data = scoreForm.data();
models.Score score = createScore(data, data.get("player"));
score.save();
RankingController.getRankingCache().remove(game);
game.recomputeRankings();
return ok(score_import.render(game, form(Score.class)));
}
public static Result delete() {
if (!User.current().isAuthenticated()) {
return unauthorized();
}
Form<models.Score> scoreForm = new Form<models.Score>(models.Score.class).bindFromRequest();
Map<String, String> data = scoreForm.data();
models.Score score = Score.finder.byId(Long.parseLong(data.get("score")));
score.delete();
Game game = score.game;
RankingController.getRankingCache().remove(game);
game.recomputeRankings();
return ok(score_import.render(game, form(Score.class)));
}
}
| app/controllers/ScoreController.java | package controllers;
import actions.User;
import com.avaje.ebean.Ebean;
import com.google.common.base.Predicate;
import models.Difficulty;
import models.Game;
import models.Mode;
import models.Platform;
import models.Player;
import models.Score;
import models.Ship;
import models.Stage;
import play.Logger;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.score_create;
import views.html.score_import;
import views.html.score_update;
import javax.annotation.Nullable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import static com.avaje.ebean.Ebean.find;
import static com.google.common.collect.Collections2.filter;
import static java.lang.Long.parseLong;
import static java.math.RoundingMode.HALF_UP;
import static org.apache.commons.lang3.StringUtils.isNumeric;
import static play.data.Form.form;
public class ScoreController extends Controller {
public static Result selectGame() {
return ok(views.html.select_game.render(Game.findAll()));
}
public static Result fillForm() {
models.Game game = Game.finder.byId(Long.parseLong(request().body().asFormUrlEncoded().get("game")[0]));
return ok(score_create.render(game, form(Score.class)));
}
public static Result fillFormWithGame(Game game) {
return ok(score_create.render(game, form(Score.class)));
}
public static Result importScores(Game game) {
return ok(score_import.render(game, form(Score.class)));
}
public static Result read(models.Score score) {
if (score == null) {
return notFound();
}
return ok(score_update.render(score));
}
public static Result save() {
if (!User.current().isAuthenticated()) {
return unauthorized();
}
Form<models.Score> scoreForm = new Form<models.Score>(models.Score.class).bindFromRequest();
Map<String, String> data = scoreForm.data();
Logger.info("Nouveau score envoyé par " + User.current().name + ", " + data.toString());
models.Score score = createScore(data);
if (score.isWorstThanOlders()) {
scoreForm.reject("Score inférieur à un score déjà présent dans la base.");
return badRequest(views.html.score_create.render(score.game, scoreForm));
}
score.save();
RankingController.getRankingCache().remove(score.game);
score.game.recomputeRankings();
return shmup(score);
}
public static Result update() {
Form<models.Score> scoreForm = new Form<models.Score>(models.Score.class).bindFromRequest();
Map<String, String> data = scoreForm.data();
Logger.info("Mise a jour du score envoyé par " + User.current().name + ", " + data.toString());
models.Score score = Ebean.find(models.Score.class, Long.valueOf(data.get("scoreId")));
if (!score.isPlayedBy(User.current())) {
return unauthorized();
}
updateScore(score, data);
score.update();
RankingController.getRankingCache().remove(score.game);
score.game.recomputeRankings();
return redirect("/");
}
public static Result shmup(models.Score score) {
return ok(views.html.post_to_shmup.render(score));
}
private static models.Score createScore(Map<String, String> data) {
String login = User.current().name;
return createScore(data, login);
}
private static Score createScore(Map<String, String> data, String login) {
Difficulty difficulty = difficulty(data);
Stage stage = find(Stage.class, parseLong(data.get("stage")));
Ship ship = ship(data);
Mode mode = mode(data);
Platform platform = find(Platform.class, parseLong(data.get("platform")));
Player player = Player.findOrCreatePlayer(login);
Game game = find(Game.class, parseLong(data.get("gameId")));
BigDecimal value = value(data);
String comment = data.get("comment");
String replay = data.get("replay");
String photo = data.get("photo");
return new Score(game, player, stage, ship, mode, difficulty, comment, platform, value, photo, replay);
}
private static void updateScore(models.Score score, Map<String, String> data) {
score.stage = find(Stage.class, parseLong(data.get("stage")));
score.mode = mode(data);
score.difficulty = difficulty(data);
score.comment = data.get("comment");
score.platform = find(Platform.class, parseLong(data.get("platform")));
score.value = value(data);
score.photo = data.get("photo");
score.replay = data.get("replay");
}
private static Difficulty difficulty(Map<String, String> data) {
Difficulty difficulty = null;
if (data.get("difficulty") != null) {
difficulty = find(Difficulty.class, parseLong(data.get("difficulty")));
}
return difficulty;
}
private static BigDecimal value(Map<String, String> data) {
String scoreValue = data.get("value");
StringBuilder strValue = new StringBuilder();
for (Character c : scoreValue.toCharArray()) {
if (isNumeric(c.toString())) {
strValue.append(c);
}
}
BigDecimal value = new BigDecimal(strValue.toString());
if (value.longValue() < 0) {
value = value.multiply(new BigDecimal("-1"));
}
return value;
}
private static Mode mode(Map<String, String> data) {
Mode mode = null;
if (data.get("mode") != null) {
mode = find(Mode.class, parseLong(data.get("mode")));
}
return mode;
}
private static Ship ship(Map<String, String> data) {
Ship ship = null;
if (data.get("ship") != null) {
ship = find(Ship.class, parseLong(data.get("ship")));
}
return ship;
}
public static Collection<Score> findProgressionOf(final Score score) {
List<Score> scores = score.player.allScores;
scores = new ArrayList<Score>(filter(scores, new Predicate<Score>() {
@Override
public boolean apply(@Nullable Score _score) {
return score.game.equals(_score.game) && score.mode == _score.mode && score.difficulty == _score.difficulty;
}
}));
if (scores.size() > 1) {
for (int i = 1; i < scores.size(); i++) {
Score previous = scores.get(i - 1);
Score current = scores.get(i);
BigDecimal gap = current.value.subtract(previous.value);
current.gapWithPreviousScore = gap.multiply(BigDecimal.valueOf(100)).divide(previous.value, HALF_UP).longValue();
}
}
return scores;
}
public static Result importScore(Game game) {
if (!User.current().isAuthenticated()) {
return unauthorized();
}
Form<models.Score> scoreForm = new Form<models.Score>(models.Score.class).bindFromRequest();
Map<String, String> data = scoreForm.data();
models.Score score = createScore(data, data.get("player"));
score.save();
RankingController.getRankingCache().remove(game);
game.recomputeRankings();
return ok(score_import.render(game, form(Score.class)));
}
public static Result delete() {
if (!User.current().isAuthenticated()) {
return unauthorized();
}
Form<models.Score> scoreForm = new Form<models.Score>(models.Score.class).bindFromRequest();
Map<String, String> data = scoreForm.data();
models.Score score = Score.finder.byId(Long.parseLong(data.get("score")));
score.delete();
Game game = score.game;
RankingController.getRankingCache().remove(game);
game.recomputeRankings();
return ok(score_import.render(game, form(Score.class)));
}
}
| Fix bug when entering a big score
| app/controllers/ScoreController.java | Fix bug when entering a big score | <ide><path>pp/controllers/ScoreController.java
<ide> strValue.append(c);
<ide> }
<ide> }
<del> BigDecimal value = new BigDecimal(strValue.toString());
<del> if (value.longValue() < 0) {
<del> value = value.multiply(new BigDecimal("-1"));
<del> }
<del> return value;
<add> return new BigDecimal(strValue.toString());
<ide> }
<ide>
<ide> private static Mode mode(Map<String, String> data) { |
|
JavaScript | mit | f875d3a4ede7ac69f4e8043f353bb40c65f0d3b6 | 0 | weacast/weacast,weacast/weacast,weacast/weacast | import _ from 'lodash'
import logger from 'winston'
// Create all element services
export default async function initializeElements (app, forecast, servicesPath) {
logger.info('Initializing ' + forecast.name + ' forecast')
const forecastsService = app.getService('forecasts')
// Register the forecast model if not already done
const result = await forecastsService.find({
query: {
name: forecast.name,
$select: ['_id'] // We only need object ID
}
})
if (result.data.length > 0) {
await forecastsService.patch(result.data[0]._id, forecast)
} else {
await forecastsService.create(forecast)
}
// Create download buckets
let elementBuckets = {}
forecast.elements.forEach(element => {
const bucket = element.bucket || 0
// Initialize bucket
if (!elementBuckets[bucket]) elementBuckets[bucket] = []
elementBuckets[bucket].push(element)
})
// Then generate services for each forecast element in buckets
// Retrieve generic elements options if any
const elementServiceOptions = app.getServiceOptions('elements')
elementBuckets = _.mapValues(elementBuckets, elements => {
return elements.map(element => app.createElementService(forecast, element, servicesPath,
Object.assign({}, element.serviceOptions, elementServiceOptions)))
})
async function update () {
// Iterate over buckets
const buckets = _.keys(elementBuckets)
for (let i = 0; i < buckets.length; i++) {
const bucket = buckets[i]
// For each bucket launch download tasks in parallel
await Promise.all(elementBuckets[bucket].map(service => {
return service.updateForecastData().catch(error => {
logger.error(error.message)
service.updateRunning = false
})
}))
}
}
if (forecast.updateInterval >= 0) {
// Trigger the initial harvesting, i.e. try data refresh for current time
// Add a small offset to wait for everything being initialized
setTimeout(update, 30 * 1000)
// Then plan next updates according to provided update interval if required
if (forecast.updateInterval > 0) {
logger.info('Installing forecast update on ' + forecast.name + ' with interval (s) ' + forecast.updateInterval)
setInterval(update, 1000 * forecast.updateInterval)
}
}
// Process elements with GridFS data store which requires manual cleanup
const elementsToClean = forecast.elements.filter(element => element.dataStore === 'gridfs')
async function clean () {
// Iterate over required elements
for (let i = 0; i < elementsToClean.length; i++) {
let service = app.getService(forecast.name + '/' + elementsToClean[i].name)
// Launch clean task
await service.cleanForecastData().catch(error => {
logger.error(error.message)
service.cleanupRunning = false
})
}
}
if (elementsToClean.length > 0) {
// Trigger the initial cleanup, i.e. try data cleanup for current time
// Add a small offset to wait for everything being initialized
setTimeout(clean, 10 * 1000)
// Then plan next cleanups according to provided clean interval if required, alternatively with data update
// Provide a default interval if no updates
const cleanInterval = (forecast.updateInterval >= 0 ? forecast.updateInterval : 30 * 60)
if (cleanInterval > 0) {
setTimeout(() => {
logger.info('Installing forecast cleanup on ' + forecast.name + ' with interval (s) ' + cleanInterval)
setInterval(clean, cleanInterval)
}, 0.5 * cleanInterval)
}
}
}
| packages/weacast-core/src/elements.js | import _ from 'lodash'
import logger from 'winston'
// Create all element services
export default async function initializeElements (app, forecast, servicesPath) {
logger.info('Initializing ' + forecast.name + ' forecast')
const forecastsService = app.getService('forecasts')
// Register the forecast model if not already done
const result = await forecastsService.find({
query: {
name: forecast.name,
$select: ['_id'] // We only need object ID
}
})
if (result.data.length > 0) {
await forecastsService.patch(result.data[0]._id, forecast)
} else {
await forecastsService.create(forecast)
}
// Create download buckets
let elementBuckets = {}
forecast.elements.forEach(element => {
const bucket = element.bucket || 0
// Initialize bucket
if (!elementBuckets[bucket]) elementBuckets[bucket] = []
elementBuckets[bucket].push(element)
})
// Then generate services for each forecast element in buckets
// Retrieve generic elements options if any
const elementServiceOptions = app.getServiceOptions('elements')
elementBuckets = _.mapValues(elementBuckets, elements => {
return elements.map(element => app.createElementService(forecast, element, servicesPath,
Object.assign({}, element.serviceOptions, elementServiceOptions)))
})
async function update () {
// Iterate over buckets
const buckets = _.keys(elementBuckets)
for (let i = 0; i < buckets.length; i++) {
const bucket = buckets[i]
// For each bucket launch download tasks in parallel
await Promise.all(elementBuckets[bucket].map(service => {
return service.updateForecastData().catch(error => {
logger.error(error.message)
service.updateRunning = false
})
}))
}
}
if (forecast.updateInterval >= 0) {
// Trigger the initial harvesting, i.e. try data refresh for current time
// Add a small offset to wait for everything being initialized
setTimeout(update, 30 * 1000)
// Then plan next updates according to provided update interval if required
if (forecast.updateInterval > 0) {
logger.info('Installing forecast update on ' + forecast.name + ' with interval (s) ' + forecast.updateInterval)
setInterval(update, 1000 * forecast.updateInterval)
}
}
// Process elements with GridFS data store which requires manual cleanup
const elementsToClean = forecast.elements.filter(element => element.dataStore === 'gridfs')
async function clean () {
// Iterate over required elements
for (let i = 0; i < elementsToClean.length; i++) {
let service = app.getService(forecast.name + '/' + elementsToClean[i].name)
// Launch clean task
await service.cleanForecastData().catch(error => {
logger.error(error.message)
service.cleanupRunning = false
})
}
}
if (elementsToClean.length > 0) {
// Trigger the initial cleanup, i.e. try data cleanup for current time
// Add a small offset to wait for everything being initialized
setTimeout(clean, 10 * 1000)
// Then plan next cleanups according to provided clean interval if required, alternatively with data update
// Provide a default interval if no updates
const cleanInterval = (forecast.updateInterval >= 0 ? forecast.updateInterval : 30 * 60 * 1000)
if (cleanInterval > 0) {
setTimeout(() => {
logger.info('Installing forecast cleanup on ' + forecast.name + ' with interval (s) ' + cleanInterval)
setInterval(clean, cleanInterval)
}, 0.5 * cleanInterval)
}
}
}
| Fixed default clean up interval
| packages/weacast-core/src/elements.js | Fixed default clean up interval | <ide><path>ackages/weacast-core/src/elements.js
<ide> setTimeout(clean, 10 * 1000)
<ide> // Then plan next cleanups according to provided clean interval if required, alternatively with data update
<ide> // Provide a default interval if no updates
<del> const cleanInterval = (forecast.updateInterval >= 0 ? forecast.updateInterval : 30 * 60 * 1000)
<add> const cleanInterval = (forecast.updateInterval >= 0 ? forecast.updateInterval : 30 * 60)
<ide> if (cleanInterval > 0) {
<ide> setTimeout(() => {
<ide> logger.info('Installing forecast cleanup on ' + forecast.name + ' with interval (s) ' + cleanInterval) |
|
Java | mit | 8460a8665b6f70c36f708274cb4f82877859567c | 0 | crispab/codekvast,crispab/codekvast,crispab/codekvast,crispab/codekvast,crispab/codekvast,crispab/codekvast | package se.crisp.codekvast.server.codekvast_server;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import se.crisp.codekvast.server.codekvast_server.controller.RegistrationController;
import se.crisp.codekvast.server.codekvast_server.model.RegistrationRequest;
import se.crisp.codekvast.server.codekvast_server.model.RegistrationResponse;
import java.net.URI;
import java.util.Random;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static se.crisp.codekvast.server.agent.model.v1.Constraints.*;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CodekvastServerApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port=0",
"management.port=0",
"spring.datasource.url=jdbc:h2:mem:integrationTest",
"codekvast.auto-register-customer=true",
})
public class RegistrationControllerTest {
@Value("${local.server.port}")
private int port;
private RestTemplate restTemplate = new RestTemplate();
private URI registrationUri;
private Random random = new Random();
@Before
public void before() throws Exception {
registrationUri = new URI(String.format("http://localhost:%d%s", port, RegistrationController.REGISTER_PATH));
}
@Test
public void testRegistration_success() {
String fullName = randomString(MAX_FULL_NAME_LENGTH);
// @formatter:off
RegistrationRequest request = RegistrationRequest.builder()
.fullName(fullName)
.username(randomString(MAX_USER_NAME_LENGTH))
.emailAddress(randomString(MAX_EMAIL_ADDRESS_LENGTH))
.password(randomString(100))
.customerName(randomString(MAX_CUSTOMER_NAME_LENGTH))
.build();
// @formatter:on
RegistrationResponse response = restTemplate.postForEntity(registrationUri, request, RegistrationResponse.class).getBody();
assertThat(response.getGreeting(), is("Welcome " + fullName + "!"));
}
@Test(expected = HttpClientErrorException.class)
public void testRegistration_too_long_full_name() {
// @formatter:off
RegistrationRequest request = RegistrationRequest.builder()
.fullName(randomString(MAX_FULL_NAME_LENGTH + 1))
.username(randomString(MAX_USER_NAME_LENGTH))
.emailAddress(randomString(MAX_EMAIL_ADDRESS_LENGTH))
.password(randomString(100))
.customerName(randomString(MAX_CUSTOMER_NAME_LENGTH))
.build();
// @formatter:on
restTemplate.postForEntity(registrationUri, request, RegistrationResponse.class).getBody();
}
@Test(expected = HttpClientErrorException.class)
public void testRegistration_duplicate_username() {
// @formatter:off
RegistrationRequest request = RegistrationRequest.builder()
.fullName(randomString(MAX_FULL_NAME_LENGTH))
.username("user")
.emailAddress(randomString(MAX_EMAIL_ADDRESS_LENGTH))
.password(randomString(100))
.customerName(randomString(MAX_CUSTOMER_NAME_LENGTH))
.build();
// @formatter:on
restTemplate.postForEntity(registrationUri, request, RegistrationResponse.class).getBody();
}
@Test(expected = HttpClientErrorException.class)
public void testRegistration_duplicate_emailAddress() {
// @formatter:off
RegistrationRequest request = RegistrationRequest.builder()
.fullName(randomString(MAX_FULL_NAME_LENGTH))
.username(randomString(MAX_USER_NAME_LENGTH))
.emailAddress("[email protected]")
.password(randomString(100))
.customerName(randomString(MAX_CUSTOMER_NAME_LENGTH))
.build();
// @formatter:on
restTemplate.postForEntity(registrationUri, request, RegistrationResponse.class).getBody();
}
private String randomString(int length) {
char s[] = new char[length];
char min = 'a';
int bound = 'z' - min;
for (int i = 0; i < length; i++) {
s[i] = (char) (random.nextInt(bound) + min);
}
String result = new String(s);
assertThat(result.length(), is(length));
return result;
}
}
| product/server/codekvast-server/src/test/java/se/crisp/codekvast/server/codekvast_server/RegistrationControllerTest.java | package se.crisp.codekvast.server.codekvast_server;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import se.crisp.codekvast.server.codekvast_server.controller.RegistrationController;
import se.crisp.codekvast.server.codekvast_server.model.RegistrationRequest;
import se.crisp.codekvast.server.codekvast_server.model.RegistrationResponse;
import java.net.URI;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CodekvastServerApplication.class)
@WebAppConfiguration
@IntegrationTest({"server.port=0",
"management.port=0",
"spring.datasource.url=jdbc:h2:mem:integrationTest",
"codekvast.auto-register-customer=true",
})
public class RegistrationControllerTest {
@Value("${local.server.port}")
private int port;
private RestTemplate restTemplate = new RestTemplate();
private URI registrationUri;
@Before
public void before() throws Exception {
registrationUri = new URI(String.format("http://localhost:%d%s", port, RegistrationController.REGISTER_PATH));
}
@Test
public void testRegistration_success() {
// @formatter:off
RegistrationRequest request = RegistrationRequest.builder()
.fullName("Full Name")
.username("username")
.emailAddress("foo@bar")
.password("pw")
.customerName("customerName")
.build();
// @formatter:on
RegistrationResponse response = restTemplate.postForEntity(registrationUri, request, RegistrationResponse.class).getBody();
assertThat(response.getGreeting(), is("Welcome Full Name!"));
}
@Test(expected = HttpClientErrorException.class)
public void testRegistration_duplicate_username() {
// @formatter:off
RegistrationRequest request = RegistrationRequest.builder()
.fullName("Full Name")
.username("user")
.emailAddress("foo@bar")
.password("pw")
.customerName("customerName2")
.build();
// @formatter:on
restTemplate.postForEntity(registrationUri, request, RegistrationResponse.class).getBody();
}
@Test(expected = HttpClientErrorException.class)
public void testRegistration_duplicate_emailAddress() {
// @formatter:off
RegistrationRequest request = RegistrationRequest.builder()
.fullName("Full Name")
.username("user" + System.currentTimeMillis())
.emailAddress("[email protected]")
.password("pw")
.customerName("customerName2")
.build();
// @formatter:on
restTemplate.postForEntity(registrationUri, request, RegistrationResponse.class).getBody();
}
}
| Improved RegistrationControllerTest.
| product/server/codekvast-server/src/test/java/se/crisp/codekvast/server/codekvast_server/RegistrationControllerTest.java | Improved RegistrationControllerTest. | <ide><path>roduct/server/codekvast-server/src/test/java/se/crisp/codekvast/server/codekvast_server/RegistrationControllerTest.java
<ide> import se.crisp.codekvast.server.codekvast_server.model.RegistrationResponse;
<ide>
<ide> import java.net.URI;
<add>import java.util.Random;
<ide>
<ide> import static org.hamcrest.Matchers.is;
<ide> import static org.junit.Assert.assertThat;
<add>import static se.crisp.codekvast.server.agent.model.v1.Constraints.*;
<ide>
<ide> @RunWith(SpringJUnit4ClassRunner.class)
<ide> @SpringApplicationConfiguration(classes = CodekvastServerApplication.class)
<ide>
<ide> private RestTemplate restTemplate = new RestTemplate();
<ide> private URI registrationUri;
<add> private Random random = new Random();
<ide>
<ide> @Before
<ide> public void before() throws Exception {
<ide>
<ide> @Test
<ide> public void testRegistration_success() {
<add> String fullName = randomString(MAX_FULL_NAME_LENGTH);
<ide> // @formatter:off
<ide> RegistrationRequest request = RegistrationRequest.builder()
<del> .fullName("Full Name")
<del> .username("username")
<del> .emailAddress("foo@bar")
<del> .password("pw")
<del> .customerName("customerName")
<add> .fullName(fullName)
<add> .username(randomString(MAX_USER_NAME_LENGTH))
<add> .emailAddress(randomString(MAX_EMAIL_ADDRESS_LENGTH))
<add> .password(randomString(100))
<add> .customerName(randomString(MAX_CUSTOMER_NAME_LENGTH))
<ide> .build();
<ide> // @formatter:on
<ide> RegistrationResponse response = restTemplate.postForEntity(registrationUri, request, RegistrationResponse.class).getBody();
<del> assertThat(response.getGreeting(), is("Welcome Full Name!"));
<add> assertThat(response.getGreeting(), is("Welcome " + fullName + "!"));
<add> }
<add>
<add> @Test(expected = HttpClientErrorException.class)
<add> public void testRegistration_too_long_full_name() {
<add> // @formatter:off
<add> RegistrationRequest request = RegistrationRequest.builder()
<add> .fullName(randomString(MAX_FULL_NAME_LENGTH + 1))
<add> .username(randomString(MAX_USER_NAME_LENGTH))
<add> .emailAddress(randomString(MAX_EMAIL_ADDRESS_LENGTH))
<add> .password(randomString(100))
<add> .customerName(randomString(MAX_CUSTOMER_NAME_LENGTH))
<add> .build();
<add> // @formatter:on
<add> restTemplate.postForEntity(registrationUri, request, RegistrationResponse.class).getBody();
<ide> }
<ide>
<ide> @Test(expected = HttpClientErrorException.class)
<ide> public void testRegistration_duplicate_username() {
<ide> // @formatter:off
<ide> RegistrationRequest request = RegistrationRequest.builder()
<del> .fullName("Full Name")
<add> .fullName(randomString(MAX_FULL_NAME_LENGTH))
<ide> .username("user")
<del> .emailAddress("foo@bar")
<del> .password("pw")
<del> .customerName("customerName2")
<add> .emailAddress(randomString(MAX_EMAIL_ADDRESS_LENGTH))
<add> .password(randomString(100))
<add> .customerName(randomString(MAX_CUSTOMER_NAME_LENGTH))
<ide> .build();
<ide> // @formatter:on
<ide> restTemplate.postForEntity(registrationUri, request, RegistrationResponse.class).getBody();
<ide> public void testRegistration_duplicate_emailAddress() {
<ide> // @formatter:off
<ide> RegistrationRequest request = RegistrationRequest.builder()
<del> .fullName("Full Name")
<del> .username("user" + System.currentTimeMillis())
<add> .fullName(randomString(MAX_FULL_NAME_LENGTH))
<add> .username(randomString(MAX_USER_NAME_LENGTH))
<ide> .emailAddress("[email protected]")
<del> .password("pw")
<del> .customerName("customerName2")
<add> .password(randomString(100))
<add> .customerName(randomString(MAX_CUSTOMER_NAME_LENGTH))
<ide> .build();
<ide> // @formatter:on
<ide> restTemplate.postForEntity(registrationUri, request, RegistrationResponse.class).getBody();
<ide> }
<ide>
<add> private String randomString(int length) {
<add> char s[] = new char[length];
<add> char min = 'a';
<add> int bound = 'z' - min;
<add> for (int i = 0; i < length; i++) {
<add> s[i] = (char) (random.nextInt(bound) + min);
<add> }
<add> String result = new String(s);
<add> assertThat(result.length(), is(length));
<add> return result;
<add> }
<add>
<ide> } |
|
JavaScript | mit | 1e8ce0145e6cc6d27dc944804919c23f4ec293e4 | 0 | christianbueschi/teambuddy_meanjs,christianbueschi/teambuddy_meanjs,christianbueschi/teambuddy_meanjs,christianbueschi/teambuddy_meanjs | 'use strict';
module.exports = {
app: {
title: 'Team Buddy',
description: 'Organisieren leicht gemacht',
keywords: 'Verein, Organisation, Administration, Eventorganisation'
},
port: process.env.PORT || 8080,
templateEngine: 'swig',
// The secret should be set to a non-guessable string that
// is used to compute a session hash
sessionSecret: 'TEAMBUDDY',
// The name of the MongoDB collection to store sessions in
sessionCollection: 'sessions',
// The session cookie settings
sessionCookie: {
path: '/',
httpOnly: true,
// If secure is set to true then it will cause the cookie to be set
// only when SSL-enabled (HTTPS) is used, and otherwise it won't
// set a cookie. 'true' is recommended yet it requires the above
// mentioned pre-requisite.
secure: false,
// Only set the maxAge to null if the cookie shouldn't be expired
// at all. The cookie will expunge when the browser is closed.
maxAge: null,
// To set the cookie in a specific domain uncomment the following
// setting:
// domain: 'yourdomain.com'
},
// The session cookie name
sessionName: 'connect.sid',
log: {
// Can specify one of 'combined', 'common', 'dev', 'short', 'tiny'
format: 'combined',
// Stream defaults to process.stdout
// Uncomment to enable logging to a log on the file system
options: {
stream: 'access.log'
}
},
assets: {
lib: {
css: [],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
// for datetimepicker
'public/lib/jquery/dist/jquery.js',
'public/lib/bootstrap/dist/js/bootstrap.js',
'public/lib/moment/moment.js',
'public/lib/angular-bootstrap-datetimepicker/src/js/datetimepicker.js',
]
},
css: [
'public/dist/application.css',
// for datetimepicker
'public/lib/angular-bootstrap-datetimepicker/src/css/datetimepicker.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
}; | config/env/all.js | 'use strict';
module.exports = {
app: {
title: 'Team Buddy',
description: 'Organisieren leicht gemacht',
keywords: 'Verein, Organisation, Administration, Eventorganisation'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
// The secret should be set to a non-guessable string that
// is used to compute a session hash
sessionSecret: 'TEAMBUDDY',
// The name of the MongoDB collection to store sessions in
sessionCollection: 'sessions',
// The session cookie settings
sessionCookie: {
path: '/',
httpOnly: true,
// If secure is set to true then it will cause the cookie to be set
// only when SSL-enabled (HTTPS) is used, and otherwise it won't
// set a cookie. 'true' is recommended yet it requires the above
// mentioned pre-requisite.
secure: false,
// Only set the maxAge to null if the cookie shouldn't be expired
// at all. The cookie will expunge when the browser is closed.
maxAge: null,
// To set the cookie in a specific domain uncomment the following
// setting:
// domain: 'yourdomain.com'
},
// The session cookie name
sessionName: 'connect.sid',
log: {
// Can specify one of 'combined', 'common', 'dev', 'short', 'tiny'
format: 'combined',
// Stream defaults to process.stdout
// Uncomment to enable logging to a log on the file system
options: {
stream: 'access.log'
}
},
assets: {
lib: {
css: [],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
// for datetimepicker
'public/lib/jquery/dist/jquery.js',
'public/lib/bootstrap/dist/js/bootstrap.js',
'public/lib/moment/moment.js',
'public/lib/angular-bootstrap-datetimepicker/src/js/datetimepicker.js',
]
},
css: [
'public/dist/application.css',
// for datetimepicker
'public/lib/angular-bootstrap-datetimepicker/src/css/datetimepicker.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
}; | change port
| config/env/all.js | change port | <ide><path>onfig/env/all.js
<ide> description: 'Organisieren leicht gemacht',
<ide> keywords: 'Verein, Organisation, Administration, Eventorganisation'
<ide> },
<del> port: process.env.PORT || 3000,
<add> port: process.env.PORT || 8080,
<ide> templateEngine: 'swig',
<ide> // The secret should be set to a non-guessable string that
<ide> // is used to compute a session hash |
|
Java | mit | b6a9e8ae0cec3e30731dc753dae024950ff2bd2f | 0 | markovandooren/jlo | package subobjectjava.translate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import jnome.core.expression.invocation.ConstructorInvocation;
import jnome.core.expression.invocation.JavaMethodInvocation;
import jnome.core.expression.invocation.NonLocalJavaTypeReference;
import jnome.core.expression.invocation.SuperConstructorDelegation;
import jnome.core.language.Java;
import jnome.core.modifier.Implements;
import jnome.core.type.BasicJavaTypeReference;
import jnome.core.type.JavaTypeReference;
import org.rejuse.association.Association;
import org.rejuse.association.SingleAssociation;
import org.rejuse.java.collections.TypeFilter;
import org.rejuse.logic.ternary.Ternary;
import org.rejuse.predicate.SafePredicate;
import org.rejuse.predicate.UnsafePredicate;
import org.rejuse.property.Property;
import subobjectjava.model.component.AbstractClause;
import subobjectjava.model.component.ActualComponentArgument;
import subobjectjava.model.component.ComponentNameActualArgument;
import subobjectjava.model.component.ComponentParameter;
import subobjectjava.model.component.ComponentParameterTypeReference;
import subobjectjava.model.component.ComponentRelation;
import subobjectjava.model.component.ComponentRelationSet;
import subobjectjava.model.component.ComponentType;
import subobjectjava.model.component.ConfigurationBlock;
import subobjectjava.model.component.ConfigurationClause;
import subobjectjava.model.component.FormalComponentParameter;
import subobjectjava.model.component.InstantiatedComponentParameter;
import subobjectjava.model.component.MultiActualComponentArgument;
import subobjectjava.model.component.MultiFormalComponentParameter;
import subobjectjava.model.component.ParameterReferenceActualArgument;
import subobjectjava.model.component.RenamingClause;
import subobjectjava.model.expression.AbstractTarget;
import subobjectjava.model.expression.ComponentParameterCall;
import subobjectjava.model.expression.OuterTarget;
import subobjectjava.model.expression.SubobjectConstructorCall;
import subobjectjava.model.language.JLo;
import subobjectjava.model.type.RegularJLoType;
import chameleon.core.compilationunit.CompilationUnit;
import chameleon.core.declaration.CompositeQualifiedName;
import chameleon.core.declaration.Declaration;
import chameleon.core.declaration.QualifiedName;
import chameleon.core.declaration.Signature;
import chameleon.core.declaration.SimpleNameDeclarationWithParametersHeader;
import chameleon.core.declaration.SimpleNameDeclarationWithParametersSignature;
import chameleon.core.declaration.SimpleNameSignature;
import chameleon.core.declaration.TargetDeclaration;
import chameleon.core.element.Element;
import chameleon.core.expression.Expression;
import chameleon.core.expression.InvocationTarget;
import chameleon.core.expression.MethodInvocation;
import chameleon.core.expression.NamedTarget;
import chameleon.core.expression.NamedTargetExpression;
import chameleon.core.lookup.DeclarationSelector;
import chameleon.core.lookup.LookupException;
import chameleon.core.lookup.SelectorWithoutOrder;
import chameleon.core.member.Member;
import chameleon.core.method.Implementation;
import chameleon.core.method.Method;
import chameleon.core.method.RegularImplementation;
import chameleon.core.method.RegularMethod;
import chameleon.core.method.exception.ExceptionClause;
import chameleon.core.modifier.ElementWithModifiers;
import chameleon.core.modifier.Modifier;
import chameleon.core.namespace.Namespace;
import chameleon.core.namespace.NamespaceElement;
import chameleon.core.namespacepart.Import;
import chameleon.core.namespacepart.NamespacePart;
import chameleon.core.namespacepart.TypeImport;
import chameleon.core.reference.CrossReference;
import chameleon.core.reference.CrossReferenceWithArguments;
import chameleon.core.reference.CrossReferenceWithName;
import chameleon.core.reference.CrossReferenceWithTarget;
import chameleon.core.reference.SimpleReference;
import chameleon.core.reference.SpecificReference;
import chameleon.core.statement.Block;
import chameleon.core.variable.FormalParameter;
import chameleon.core.variable.VariableDeclaration;
import chameleon.core.variable.VariableDeclarator;
import chameleon.exception.ChameleonProgrammerException;
import chameleon.exception.ModelException;
import chameleon.oo.language.ObjectOrientedLanguage;
import chameleon.oo.type.BasicTypeReference;
import chameleon.oo.type.DeclarationWithType;
import chameleon.oo.type.ParameterBlock;
import chameleon.oo.type.RegularType;
import chameleon.oo.type.Type;
import chameleon.oo.type.TypeElement;
import chameleon.oo.type.TypeReference;
import chameleon.oo.type.TypeWithBody;
import chameleon.oo.type.generics.ActualType;
import chameleon.oo.type.generics.BasicTypeArgument;
import chameleon.oo.type.generics.InstantiatedTypeParameter;
import chameleon.oo.type.generics.TypeParameter;
import chameleon.oo.type.generics.TypeParameterBlock;
import chameleon.oo.type.inheritance.AbstractInheritanceRelation;
import chameleon.oo.type.inheritance.SubtypeRelation;
import chameleon.support.expression.AssignmentExpression;
import chameleon.support.expression.SuperTarget;
import chameleon.support.expression.ThisLiteral;
import chameleon.support.member.simplename.SimpleNameMethodInvocation;
import chameleon.support.member.simplename.method.NormalMethod;
import chameleon.support.member.simplename.method.RegularMethodInvocation;
import chameleon.support.member.simplename.variable.MemberVariableDeclarator;
import chameleon.support.modifier.Interface;
import chameleon.support.modifier.Public;
import chameleon.support.statement.ReturnStatement;
import chameleon.support.statement.StatementExpression;
import chameleon.support.statement.ThrowStatement;
import chameleon.support.variable.LocalVariableDeclarator;
import chameleon.util.Util;
public class JavaTranslator {
public List<CompilationUnit> translate(CompilationUnit source, CompilationUnit implementationCompilationUnit) throws LookupException, ModelException {
List<CompilationUnit> result = new ArrayList<CompilationUnit>();
// Remove a possible old translation of the given compilation unit
// from the target model.
NamespacePart originalNamespacePart = source.namespaceParts().get(0);
NamespacePart newNamespacePart = implementationCompilationUnit.namespaceParts().get(0);
Iterator<Type> originalTypes = originalNamespacePart.children(Type.class).iterator();
Iterator<Type> newTypes = newNamespacePart.children(Type.class).iterator();
while(originalTypes.hasNext()) {
SingleAssociation<Type, Element> newParentLink = newTypes.next().parentLink();
Type translated = translatedImplementation(originalTypes.next());
newParentLink.getOtherRelation().replace(newParentLink, translated.parentLink());
}
newNamespacePart.clearImports();
for(Import imp: originalNamespacePart.imports()) {
newNamespacePart.addImport(imp.clone());
}
implementationCompilationUnit.flushCache();
result.add(implementationCompilationUnit);
implementationCompilationUnit.namespacePart(1).getNamespaceLink().lock();
CompilationUnit interfaceCompilationUnit = interfaceCompilationUnit(source, implementationCompilationUnit);
for(NamespacePart part: implementationCompilationUnit.descendants(NamespacePart.class)) {
part.removeDuplicateImports();
}
for(NamespacePart part: interfaceCompilationUnit.descendants(NamespacePart.class)) {
part.removeDuplicateImports();
}
result.add(interfaceCompilationUnit);
return result;
}
private boolean isJLo(NamespaceElement element) {
Namespace ns = element.getNamespace();
return ! ns.getFullyQualifiedName().startsWith("java.");
}
private CompilationUnit interfaceCompilationUnit(CompilationUnit original, CompilationUnit implementation) throws ModelException {
original.flushCache();
implementation.flushCache();
CompilationUnit interfaceCompilationUnit = implementation.cloneTo(implementation.language());
NamespacePart interfaceNamespacePart = interfaceCompilationUnit.namespacePart(1);
Type interfaceType = interfaceNamespacePart.declarations(Type.class).get(0);
interfaceType.addModifier(new Interface());
transformToInterfaceDeep(interfaceType);
for(BasicJavaTypeReference tref: interfaceType.descendants(BasicJavaTypeReference.class)) {
String name = tref.signature().name();
if(name.endsWith(IMPL)) {
tref.setSignature(new SimpleNameSignature(interfaceName(name)));
}
}
interfaceCompilationUnit.flushCache();
return interfaceCompilationUnit;
}
private void rewriteConstructorCalls(Element<?> type) throws LookupException {
Java language = type.language(Java.class);
List<ConstructorInvocation> invocations = type.descendants(ConstructorInvocation.class);
for(ConstructorInvocation invocation: invocations) {
try {
Type constructedType = invocation.getType();
if(isJLo(constructedType) && (! constructedType.isTrue(language.PRIVATE))) {
transformToImplReference((CrossReferenceWithName) invocation.getTypeReference());
}
} catch(LookupException exc) {
transformToImplReference((CrossReferenceWithName) invocation.getTypeReference());
}
}
}
private void rewriteThisLiterals(Element<?> type) throws LookupException {
List<ThisLiteral> literals = type.descendants(ThisLiteral.class);
for(ThisLiteral literal: literals) {
TypeReference typeReference = literal.getTypeReference();
if(typeReference != null) {
transformToImplReference((CrossReferenceWithName) typeReference);
}
}
}
private void rewriteComponentAccess(Element<?> type) throws LookupException {
List<CrossReference> literals = type.descendants(CrossReference.class);
for(CrossReference literal: literals) {
if((literal instanceof CrossReferenceWithTarget)) {
transformComponentAccessors((CrossReferenceWithTarget) literal);
}
}
}
private void transformComponentAccessors(CrossReferenceWithTarget cwt) {
Element target = cwt.getTarget();
if(target instanceof CrossReferenceWithTarget) {
transformComponentAccessors((CrossReferenceWithTarget) target);
}
boolean rewrite = false;
String name = null;
if((! (cwt instanceof MethodInvocation)) && (! (cwt instanceof TypeReference))) {
name = ((CrossReferenceWithName)cwt).name();
try {
Declaration decl = cwt.getElement();
if(decl instanceof ComponentRelation) {
rewrite = true;
}
}catch(LookupException exc) {
// rewrite = true;
}
}
if(rewrite) {
String getterName = getterName(name);
MethodInvocation inv = new JavaMethodInvocation(getterName,(InvocationTarget) target);
SingleAssociation parentLink = cwt.parentLink();
parentLink.getOtherRelation().replace(parentLink, inv.parentLink());
}
}
private void transformToInterfaceDeep(Type type) throws ModelException {
List<Type> types = type.descendants(Type.class);
types.add(type);
for(Type t: types) {
transformToInterface(t);
}
}
private void transformToInterface(Type type) throws ModelException {
String name = type.getName();
Java language = type.language(Java.class);
if(name.endsWith(IMPL)) {
copyTypeParametersIfNecessary(type);
makePublic(type);
List<SubtypeRelation> inheritanceRelations = type.nonMemberInheritanceRelations(SubtypeRelation.class);
int last = inheritanceRelations.size() - 1;
inheritanceRelations.get(last).disconnect();
for(TypeElement decl: type.directlyDeclaredElements()) {
if(decl instanceof Method) {
((Method) decl).setImplementation(null);
if(decl.is(language.CLASS) == Ternary.TRUE) {
decl.disconnect();
}
}
if((decl.is(language.CONSTRUCTOR) == Ternary.TRUE) ||
(decl.is(language.PRIVATE) == Ternary.TRUE) ||
(decl instanceof VariableDeclarator && (! (decl.is(language.CLASS) == Ternary.TRUE)))) {
decl.disconnect();
}
if(decl instanceof ElementWithModifiers) {
makePublic(decl);
}
}
type.signature().setName(interfaceName(name));
if(! (type.is(language.INTERFACE) == Ternary.TRUE)) {
type.addModifier(new Interface());
}
}
}
private void copyTypeParametersIfNecessary(Type type) {
Type outmost = type.farthestAncestor(Type.class);
if(outmost != null) {
List<TypeParameter> typeParameters = outmost.parameters(TypeParameter.class);
ParameterBlock tpars = type.parameterBlock(TypeParameter.class);
if(tpars == null) {
type.addParameterBlock(new TypeParameterBlock());
}
for(TypeParameter<?> typeParameter:typeParameters) {
type.addParameter(TypeParameter.class, typeParameter.clone());
}
}
}
private void makePublic(ElementWithModifiers<?> element) throws ModelException {
Java language = element.language(Java.class);
Property access = element.property(language.SCOPE_MUTEX);
if(access != language.PRIVATE) {
for(Modifier mod: element.modifiers(language.SCOPE_MUTEX)) {
mod.disconnect();
}
element.addModifier(new Public());
}
}
private void transformToImplReference(CrossReferenceWithName ref) {
if(ref instanceof CrossReferenceWithTarget) {
CrossReferenceWithName target = (CrossReferenceWithName) ((CrossReferenceWithTarget)ref).getTarget();
if(target != null) {
transformToImplReference(target);
}
}
boolean change;
try {
Declaration referencedElement = ref.getElement();
if(referencedElement instanceof Type) {
change = true;
} else {
change = false;
}
} catch(LookupException exc) {
change = true;
}
if(change) {
String name = ref.name();
if(! name.endsWith(IMPL)) {
ref.setName(name+IMPL);
}
}
}
private void transformToInterfaceReference(SpecificReference ref) {
SpecificReference target = (SpecificReference) ref.getTarget();
if(target != null) {
transformToInterfaceReference(target);
}
String name = ref.signature().name();
if(name.endsWith(IMPL)) {
ref.setSignature(new SimpleNameSignature(interfaceName(name)));
}
}
private String interfaceName(String name) {
if(! name.endsWith(IMPL)) {
throw new IllegalArgumentException();
}
return name.substring(0, name.length()-IMPL.length());
}
/**
* Return a type that represents the translation of the given JLow class to a Java class.
* @throws ModelException
*/
private Type translatedImplementation(Type original) throws ChameleonProgrammerException, ModelException {
Type result = original.clone();
result.setUniParent(original.parent());
List<ComponentRelation> relations = original.directlyDeclaredMembers(ComponentRelation.class);
for(ComponentRelation relation : relations) {
// Add a getter for subobject
Method getterForComponent = getterForComponent(relation,result);
if(getterForComponent != null) {
result.add(getterForComponent);
}
// Add a setter for subobject
Method setterForComponent = setterForComponent(relation,result);
if(setterForComponent != null) {
result.add(setterForComponent);
}
// Create the inner classes for the components
inner(result, relation, result,original);
result.flushCache();
addOutwardDelegations(relation, result);
result.flushCache();
}
replaceSuperCalls(result);
for(ComponentRelation relation: result.directlyDeclaredMembers(ComponentRelation.class)) {
replaceConstructorCalls(relation);
MemberVariableDeclarator fieldForComponent = fieldForComponent(relation,result);
if(fieldForComponent != null) {
result.add(fieldForComponent);
}
relation.disconnect();
}
List<Method> decls = selectorsFor(result);
for(Method decl:decls) {
result.add(decl);
}
List<ComponentParameterCall> calls = result.descendants(ComponentParameterCall.class);
for(ComponentParameterCall call: calls) {
FormalComponentParameter parameter = call.getElement();
MethodInvocation expr = new JavaMethodInvocation(selectorName(parameter),null);
expr.addArgument((Expression) call.target());
SingleAssociation pl = call.parentLink();
pl.getOtherRelation().replace(pl, expr.parentLink());
}
for(SubtypeRelation rel: result.nonMemberInheritanceRelations(SubtypeRelation.class)) {
processSuperComponentParameters(rel);
}
if(result.getFullyQualifiedName().equals("example.meta.Klass")) {
System.out.println("debug");
}
rebindOverriddenMethods(result,original);//TODO
rewriteConstructorCalls(result);
rewriteThisLiterals(result);
rewriteComponentAccess(result);
expandReferences(result);
removeNonLocalReferences(result);
// The result is still temporarily attached to the original model.
transformToImplRecursive(result);
result.setUniParent(null);
return result;
}
private void rebindOverriddenMethods(Type result, Type original) throws LookupException {
for(final Method method: original.descendants(Method.class)) {
rebindOverriddenMethodsOf(result, original, method);
}
}
private void rebindOverriddenMethodsOf(Type result, Type original, Method method) throws LookupException, Error {
if(method.name().equals("setFrequency")) {
System.out.println("debug");
}
Set<? extends Member> overridden = method.overriddenMembers();
if(! overridden.isEmpty()) {
final Method tmp = method.clone();
// Type containerOfNewDefinition = createOrGetInnerTypeForMethod(result, original, method);
Type containerOfNewDefinition = containerOfDefinition(result,original, method);
if(containerOfNewDefinition != null) {
tmp.setUniParent(containerOfNewDefinition);
// substituteTypeParameters(method);
DeclarationSelector<Method> selector = new SelectorWithoutOrder<Method>(Method.class) {
@Override
public Signature signature() {
return tmp.signature();
}
};
Method newDefinitionInResult = null;
try {
newDefinitionInResult = containerOfNewDefinition.members(selector).get(0);
} catch (IndexOutOfBoundsException e) {
containerOfNewDefinition = containerOfDefinition(result, original, method);
newDefinitionInResult = containerOfNewDefinition.members(selector).get(0);
}
Method<?,?,?,?> stat = newDefinitionInResult.clone();
String name = toImplName(containerOfNewDefinition.getFullyQualifiedName().replace('.', '_'))+"_"+method.name();
stat.setName(name);
containerOfNewDefinition.add(stat);
if(!stat.descendants(ComponentParameterCall.class).isEmpty()) {
throw new Error();
}
}
}
for(Member toBeRebound: overridden) {
rebind(result, original, method, (Method) toBeRebound);
}
}
private void rebind(Type container, Type original, Method<?,?,?,?> newDefinition, Method toBeRebound) throws LookupException {
Type containerOfNewDefinition = containerOfDefinition(container,original, newDefinition);
Type rootOfNewDefinitionInOriginal = levelOfDefinition(newDefinition);
List<Element> trailOfRootInOriginal = filterAncestors(rootOfNewDefinitionInOriginal);
trailOfRootInOriginal.add(0, rootOfNewDefinitionInOriginal);
trailOfRootInOriginal.remove(trailOfRootInOriginal.size()-1);
Type containerToAdd = createOrGetInnerTypeAux(container, original, trailOfRootInOriginal,1);
List<Element> trailtoBeReboundInOriginal = filterAncestors(toBeRebound);
Type rootOfToBeRebound = levelOfDefinition(toBeRebound);
while(! (trailtoBeReboundInOriginal.get(trailtoBeReboundInOriginal.size()-1) == rootOfToBeRebound)) {
trailtoBeReboundInOriginal.remove(trailtoBeReboundInOriginal.size()-1);
}
trailtoBeReboundInOriginal.remove(trailtoBeReboundInOriginal.size()-1);
Type x = containerToAdd;
if(! trailtoBeReboundInOriginal.isEmpty()) {
x = createOrGetInnerTypeAux(containerToAdd, original, trailtoBeReboundInOriginal,1);
}
// Type containerOfToBebound = containerOfDefinition(containerOfNewDefinition, original, toBeRebound);
Type containerOfToBebound = x;
// containerOfToBebound = x;
if((containerOfToBebound != null) && ! containerOfToBebound.sameAs(containerOfNewDefinition)) {
if(newDefinition.name().equals("isValid")) {
System.out.println("debug");
}
System.out.println("----------------------");
System.out.println("Source: "+containerOfNewDefinition.getFullyQualifiedName()+"."+newDefinition.name());
System.out.println("Target: "+containerOfToBebound.getFullyQualifiedName()+"."+toBeRebound.name());
System.out.println("----------------------");
String thisName = containerOfNewDefinition.getFullyQualifiedName();
Method clone = createOutward(toBeRebound, newDefinition.name(),thisName);
String newName = containerOfToBebound.getFullyQualifiedName().replace('.', '_')+"_"+clone.name();
//FIXME this is tricky.
clone.setUniParent(toBeRebound);
Implementation<Implementation> impl = clone.implementation();
clone.setImplementation(null);
substituteTypeParameters(clone);
clone.setImplementation(impl);
clone.setUniParent(null);
containerOfToBebound.add(clone);
Method<?,?,?,?> stat = clone.clone();
stat.setName(newName);
String name = containerOfNewDefinition.getFullyQualifiedName().replace('.', '_');
for(SimpleNameMethodInvocation inv:stat.descendants(SimpleNameMethodInvocation.class)) {
name = toImplName(name);
inv.setName(name+"_"+newDefinition.name());
}
containerOfToBebound.add(stat);
containerOfToBebound.flushCache();
}
}
private Type containerOfDefinition(Type container, Type original,
Method<?, ?, ?, ?> newDefinition) throws LookupException {
Type containerOfNewDefinition = container;
Type rootOfNewDefinitionInOriginal = levelOfDefinition(newDefinition);
List<Element> trailOfRootInOriginal = filterAncestors(rootOfNewDefinitionInOriginal);
trailOfRootInOriginal.add(0, rootOfNewDefinitionInOriginal);
trailOfRootInOriginal.remove(trailOfRootInOriginal.size()-1);
containerOfNewDefinition = createOrGetInnerTypeAux(container, original, trailOfRootInOriginal,1);
List<Element> trailNewDefinitionInOriginal = filterAncestors(newDefinition);
// Remove everything up to the container.
while(! (trailNewDefinitionInOriginal.get(trailNewDefinitionInOriginal.size()-1) == rootOfNewDefinitionInOriginal)) {
trailNewDefinitionInOriginal.remove(trailNewDefinitionInOriginal.size()-1);
}
// Remove the container.
trailNewDefinitionInOriginal.remove(trailNewDefinitionInOriginal.size()-1);
if(! trailNewDefinitionInOriginal.isEmpty()) {
// trailOfRootInOriginal.add(0, rootOfNewDefinitionInOriginal);
containerOfNewDefinition = createOrGetInnerTypeAux(containerOfNewDefinition, original, trailNewDefinitionInOriginal,1);
}
return containerOfNewDefinition;
}
private Type levelOfDefinition(Element<?> element) {
Type result = element.nearestAncestor(Type.class, new SafePredicate<Type>(){
@Override
public boolean eval(Type object) {
return ! (object instanceof ComponentType);
}});
return result;
}
private String toImplName(String name) {
if(! name.endsWith(IMPL)) {
name = name + IMPL;
}
return name;
}
private Type createOrGetInnerTypeForType(Type container, Type original, Type current, List<Element> elements, int baseOneIndex) throws LookupException {
// Signature innerName = (new SimpleNameSignature(innerClassName(relationBeingTranslated, original)));
Signature innerName = current.signature().clone();
SimpleReference<Type> tref = new SimpleReference<Type>(innerName, Type.class);
tref.setUniParent(container);
Type result;
try {
result= tref.getElement();
} catch(LookupException exc) {
// We add the imports to the original. They are copied later on to 'container'.
ComponentRelation relation = ((ComponentType)current).nearestAncestor(ComponentRelation.class);
result = emptyInnerClassFor(relation, container);
NamespacePart namespacePart = container.farthestAncestor(NamespacePart.class);
incorporateImports(relation, namespacePart);
// Since we are adding inner classes that were not written in the current namespacepart, their type
// may not have been imported yet. Therefore, we add an import of the referenced component type.
namespacePart.addImport(new TypeImport(container.language(Java.class).createTypeReference(relation.referencedComponentType().getFullyQualifiedName())));
container.add(result);
container.flushCache();
}
return createOrGetInnerTypeAux(result, original, elements, baseOneIndex + 1);
}
private Type createOrGetInnerTypeForComponent(Type container, Type original, ComponentRelation relationBeingTranslated, List<Element> elements, int baseOneIndex) throws LookupException {
Signature innerName = null;
innerName = (new SimpleNameSignature(innerClassName(relationBeingTranslated, container)));
SimpleReference<Type> tref = new SimpleReference<Type>(innerName, Type.class);
tref.setUniParent(container);
Type result;
try {
result= tref.getElement();
} catch(LookupException exc) {
// We add the imports to the original. They are copied later on to 'container'.
result = emptyInnerClassFor(relationBeingTranslated, container);
NamespacePart namespacePart = container.farthestAncestor(NamespacePart.class);
incorporateImports(relationBeingTranslated, namespacePart);
// Since we are adding inner classes that were not written in the current namespacepart, their type
// may not have been imported yet. Therefore, we add an import of the referenced component type.
namespacePart.addImport(new TypeImport(container.language(Java.class).createTypeReference(relationBeingTranslated.referencedComponentType().getFullyQualifiedName())));
container.add(result);
container.flushCache();
}
return createOrGetInnerTypeAux(result, original, elements, baseOneIndex + 1);
}
private List<Element> filterAncestors(Element<?> element) {
SafePredicate<Element> predicate = componentRelationOrNonComponentTypePredicate();
return element.ancestors(Element.class, predicate);
}
private SafePredicate<Element> componentRelationOrNonComponentTypePredicate() {
return new SafePredicate<Element>(){
@Override
public boolean eval(Element object) {
return (object instanceof ComponentRelation) || (object instanceof Type && !(object instanceof ComponentType));
}};
}
private SafePredicate<Type> nonComponentTypePredicate() {
return new SafePredicate<Type>(){
@Override
public boolean eval(Type object) {
return !(object instanceof ComponentType);
}};
}
private Type createOrGetInnerTypeAux(Type container, Type original, List<Element> elements, int baseOneIndex) throws LookupException {
int index = elements.size()-baseOneIndex;
if(index >= 0) {
Element element = elements.get(index);
if(element instanceof ComponentRelation) {
return createOrGetInnerTypeForComponent(container,original, (ComponentRelation) element, elements,baseOneIndex);
} else {
return createOrGetInnerTypeForType(container,original, (Type) element, elements,baseOneIndex);
}
} else {
return container;
}
}
private void transformToImplRecursive(Type type) throws ModelException {
transformToImpl(type);
for(Type nested: type.directlyDeclaredMembers(Type.class)) {
transformToImplRecursive(nested);
}
}
private void transformToImpl(Type type) throws ModelException {
JLo lang = type.language(JLo.class);
if(! type.isTrue(lang.PRIVATE)) {
// Change the name of the outer type.
// What a crappy code. I would probably be easier to not add IMPL
// to the generated subobject class in the first place, but add
// it afterwards.
String oldName = type.getName();
String name = oldName;
if(! name.endsWith(IMPL)) {
name = name +IMPL;
type.signature().setName(name);
}
for(SubtypeRelation relation: type.nonMemberInheritanceRelations(SubtypeRelation.class)) {
BasicJavaTypeReference tref = (BasicJavaTypeReference) relation.superClassReference();
try {
if((! relation.isTrue(lang.IMPLEMENTS_RELATION)) && isJLo(tref.getElement())) {
tref.setSignature(new SimpleNameSignature(tref.signature().name()+IMPL));
}
}
catch(LookupException exc) {
tref.getElement();
throw exc;
}
}
implementOwnInterface(type);
for(TypeElement decl: type.directlyDeclaredElements()) {
if((decl instanceof Method) && (decl.is(lang.CONSTRUCTOR) == Ternary.TRUE)) {
((Method)decl).setName(name);
}
if(decl instanceof ElementWithModifiers) {
makePublic(decl);
}
}
}
}
private void implementOwnInterface(Type type) {
JLo language = type.language(JLo.class);
if(!type.isTrue(language.PRIVATE)) {
String oldFQN = type.getFullyQualifiedName();
BasicJavaTypeReference createTypeReference = language.createTypeReference(oldFQN);
transformToInterfaceReference(createTypeReference);
copyTypeParametersIfNecessary(type, createTypeReference);
SubtypeRelation relation = new SubtypeRelation(createTypeReference);
relation.addModifier(new Implements());
type.addInheritanceRelation(relation);
}
}
private void copyTypeParametersIfNecessary(Type type, BasicJavaTypeReference createTypeReference) {
Java language = type.language(Java.class);
if(! (type.is(language.CLASS) == Ternary.TRUE)) {
copyTypeParametersFromFarthestAncestor(type, createTypeReference);
}
}
private void copyTypeParametersFromFarthestAncestor(Element<?> type, BasicJavaTypeReference createTypeReference) {
Type farthestAncestor = type.farthestAncestorOrSelf(Type.class);
Java language = type.language(Java.class);
List<TypeParameter> tpars = farthestAncestor.parameters(TypeParameter.class);
for(TypeParameter parameter:tpars) {
createTypeReference.addArgument(language.createBasicTypeArgument(language.createTypeReference(parameter.signature().name())));
}
}
private void processSuperComponentParameters(AbstractInheritanceRelation<?> relation) throws LookupException {
TypeReference tref = relation.superClassReference();
Type type = relation.nearestAncestor(Type.class);
if(tref instanceof ComponentParameterTypeReference) {
ComponentParameterTypeReference ctref = (ComponentParameterTypeReference) tref;
Type ctype = tref.getType();
type.addAll(selectorsForComponent(ctype));
relation.setSuperClassReference(ctref.componentTypeReference());
}
}
private void removeNonLocalReferences(Type type) throws LookupException {
for(NonLocalJavaTypeReference tref: type.descendants(NonLocalJavaTypeReference.class)) {
SingleAssociation<NonLocalJavaTypeReference, Element> parentLink = tref.parentLink();
parentLink.getOtherRelation().replace(parentLink, tref.actualReference().parentLink());
}
}
private void expandReferences(Element<?> type) throws LookupException {
Java language = type.language(Java.class);
for(BasicJavaTypeReference tref: type.descendants(BasicJavaTypeReference.class)) {
if(tref.getTarget() == null) {
try {
// Filthy hack, should add meta information to such references, and use that instead.
if(! tref.signature().name().contains(SHADOW)) {
Type element = tref.getElement();
if(! element.isTrue(language.PRIVATE)) {
String fullyQualifiedName = element.getFullyQualifiedName();
String predecessor = Util.getAllButLastPart(fullyQualifiedName);
if(predecessor != null) {
NamedTarget nt = new NamedTarget(predecessor);
tref.setTarget(nt);
}
}
}
} catch(LookupException exc) {
// This occurs because a generated element cannot be resolved in the original model. E.g.
// an inner class of another class than the one that has been generated.
}
}
}
}
private List<Method> selectorsFor(ComponentRelation rel) throws LookupException {
Type t = rel.referencedComponentType();
return selectorsForComponent(t);
}
private List<Method> selectorsForComponent(Type t) throws LookupException {
List<Method> result = new ArrayList<Method>();
for(ComponentParameter par: t.parameters(ComponentParameter.class)) {
Method realSelector= realSelectorFor((InstantiatedComponentParameter) par);
realSelector.setUniParent(t);
substituteTypeParameters(realSelector);
realSelector.setUniParent(null);
result.add(realSelector);
}
return result;
}
private Method realSelectorFor(InstantiatedComponentParameter<?> par) throws LookupException {
SimpleNameDeclarationWithParametersHeader header = new SimpleNameDeclarationWithParametersHeader(selectorName(par));
FormalComponentParameter formal = par.formalParameter();
Java language = par.language(Java.class);
// Method result = new NormalMethod(header,formal.componentTypeReference().clone());
Type declarationType = formal.declarationType();
JavaTypeReference reference = language.reference(declarationType);
reference.setUniParent(null);
Method result = par.language(Java.class).createNormalMethod(header,reference);
result.addModifier(new Public());
// result.addModifier(new Abstract());
header.addFormalParameter(new FormalParameter("argument", formal.containerTypeReference().clone()));
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
ActualComponentArgument arg = par.argument();
Expression expr;
if(arg instanceof ComponentNameActualArgument) {
ComponentNameActualArgument singarg = (ComponentNameActualArgument) arg;
expr = new JavaMethodInvocation(getterName(singarg.declaration()),new NamedTargetExpression("argument", null));
body.addStatement(new ReturnStatement(expr));
} else if(arg instanceof ParameterReferenceActualArgument) {
ParameterReferenceActualArgument ref = (ParameterReferenceActualArgument) arg;
ComponentParameter p = ref.declaration();
expr = new JavaMethodInvocation(selectorName(p), null);
((JavaMethodInvocation)expr).addArgument(new NamedTargetExpression("argument",null));
body.addStatement(new ReturnStatement(expr));
}
else {
// result variable declaration
VariableDeclaration declaration = new VariableDeclaration("result");
BasicJavaTypeReference arrayList = language.createTypeReference("java.util.ArrayList");
JavaTypeReference componentType = language.reference(formal.componentTypeReference().getElement());
componentType.setUniParent(null);
BasicTypeArgument targ = language.createBasicTypeArgument(componentType);
arrayList.addArgument(targ);
// LocalVariableDeclarator varDecl = new LocalVariableDeclarator(reference.clone());
LocalVariableDeclarator varDecl = new LocalVariableDeclarator(arrayList.clone());
Expression init = new ConstructorInvocation(arrayList, null);
declaration.setInitialization(init);
varDecl.add(declaration);
body.addStatement(varDecl);
// add all components
ComponentRelationSet componentRelations = ((MultiActualComponentArgument)arg).declaration();
for(DeclarationWithType rel: componentRelations.relations()) {
Expression t = new NamedTargetExpression("result", null);
SimpleNameMethodInvocation inv = new JavaMethodInvocation("add", t);
Expression componentSelector;
if(rel instanceof ComponentParameter) {
if(rel instanceof MultiFormalComponentParameter) {
inv.setName("addAll");
}
componentSelector = new JavaMethodInvocation(selectorName((ComponentParameter)rel), null);
((JavaMethodInvocation)componentSelector).addArgument(new NamedTargetExpression("argument",null));
} else {
componentSelector = new NamedTargetExpression(rel.signature().name(), new NamedTargetExpression("argument",null));
}
inv.addArgument(componentSelector);
body.addStatement(new StatementExpression(inv));
}
// return statement
expr = new NamedTargetExpression("result",null);
body.addStatement(new ReturnStatement(expr));
}
return result;
}
private List<Method> selectorsFor(Type type) throws LookupException {
ParameterBlock<?,ComponentParameter> block = type.parameterBlock(ComponentParameter.class);
List<Method> result = new ArrayList<Method>();
if(block != null) {
for(ComponentParameter par: block.parameters()) {
result.add(selectorFor((FormalComponentParameter<?>) par));
}
}
return result;
}
private String selectorName(ComponentParameter<?> par) {
return "__select$"+ toUnderScore(par.nearestAncestor(Type.class).getFullyQualifiedName())+"$"+par.signature().name();
}
private String toUnderScore(String string) {
return string.replace('.', '_');
}
private Method selectorFor(FormalComponentParameter<?> par) throws LookupException {
SimpleNameDeclarationWithParametersHeader header = new SimpleNameDeclarationWithParametersHeader(selectorName(par));
Java language = par.language(Java.class);
// Method result = new NormalMethod(header,par.componentTypeReference().clone());
JavaTypeReference reference = language.reference(par.declarationType());
reference.setUniParent(null);
Method result = par.language(Java.class).createNormalMethod(header,reference);
result.addModifier(new Public());
// result.addModifier(new Abstract());
header.addFormalParameter(new FormalParameter("argument", par.containerTypeReference().clone()));
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
ConstructorInvocation cons = new ConstructorInvocation((BasicJavaTypeReference) par.language(Java.class).createTypeReference("java.lang.Error"), null);
body.addStatement(new ThrowStatement(cons));
return result;
}
private void replaceConstructorCalls(final ComponentRelation relation) throws LookupException {
Type type = relation.nearestAncestor(Type.class);
List<SubobjectConstructorCall> constructorCalls = type.descendants(SubobjectConstructorCall.class, new UnsafePredicate<SubobjectConstructorCall,LookupException>() {
@Override
public boolean eval(SubobjectConstructorCall constructorCall) throws LookupException {
return constructorCall.getTarget().getElement().equals(relation);
}
}
);
for(SubobjectConstructorCall call: constructorCalls) {
MethodInvocation inv = new ConstructorInvocation((BasicJavaTypeReference) innerClassTypeReference(relation, type), null);
// move actual arguments from subobject constructor call to new constructor call.
inv.addAllArguments(call.getActualParameters());
MethodInvocation setterCall = new JavaMethodInvocation(setterName(relation), null);
setterCall.addArgument(inv);
SingleAssociation<SubobjectConstructorCall, Element> parentLink = call.parentLink();
parentLink.getOtherRelation().replace(parentLink, setterCall.parentLink());
}
}
private void inner(Type type, ComponentRelation relation, Type outer, Type outerTypeBeingTranslated) throws LookupException {
Type innerClass = createInnerClassFor(relation,type,outerTypeBeingTranslated);
type.add(innerClass);
Type componentType = relation.componentType();
for(ComponentRelation nestedRelation: componentType.directlyDeclaredElements(ComponentRelation.class)) {
// subst parameters
ComponentRelation clonedNestedRelation = nestedRelation.clone();
clonedNestedRelation.setUniParent(nestedRelation.parent());
substituteTypeParameters(clonedNestedRelation);
inner(innerClass, clonedNestedRelation, outer,outerTypeBeingTranslated);
}
}
private void addOutwardDelegations(ComponentRelation relation, Type outer) throws LookupException {
ConfigurationBlock block = relation.configurationBlock();
if(block != null) {
TypeWithBody componentTypeDeclaration = relation.componentTypeDeclaration();
List<Method> elements = methodsOfComponentBody(componentTypeDeclaration);
for(ConfigurationClause clause: block.clauses()) {
if(clause instanceof AbstractClause) {
AbstractClause ov = (AbstractClause)clause;
final QualifiedName poppedName = ov.oldFqn().popped();
// Type targetInnerClass = searchInnerClass(outer, relation, poppedName);
Declaration decl = ov.oldDeclaration();
if(decl instanceof Method) {
final Method<?,?,?,?> method = (Method<?, ?, ?, ?>) decl;
if(ov instanceof RenamingClause) {
outer.add(createAlias(relation, method, ((SimpleNameDeclarationWithParametersSignature)ov.newSignature()).name()));
}
}
}
}
}
}
private List<Method> methodsOfComponentBody(TypeWithBody componentTypeDeclaration) {
List<Method> elements;
if(componentTypeDeclaration != null) {
elements = componentTypeDeclaration.body().children(Method.class);
} else {
elements = new ArrayList<Method>();
}
return elements;
}
// private boolean containsMethodWithSameSignature(List<Method> elements, final Method<?, ?, ?, ?> method) throws LookupException {
// boolean overriddenInSubobject = new UnsafePredicate<Method, LookupException>() {
// public boolean eval(Method subobjectMethod) throws LookupException {
// return subobjectMethod.signature().sameAs(method.signature());
// }
// }.exists(elements);
// return overriddenInSubobject;
// }
private Method createAlias(ComponentRelation relation, Method<?,?,?,?> method, String newName) throws LookupException {
NormalMethod<?,?,?> result;
result = innerMethod(method, newName);
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
MethodInvocation invocation = invocation(result, method.name());
// We now bind to the regular method name in case the method has not been overridden
// and there is no 'original' method.
// If it is overridden, then this adds 1 extra delegation, so we should optimize it later on.
// Invocation invocation = invocation(result, original(method.name()));
Expression target = new JavaMethodInvocation(getterName(relation), null);
invocation.setTarget(target);
substituteTypeParameters(method, result);
addImplementation(method, body, invocation);
return result;
}
/**
*
* @param relationBeingTranslated A component relation from either the original class, or one of its nested components.
* @param outer The outer class being generated.
*/
private Type createInnerClassFor(ComponentRelation relationBeingTranslated, Type outer, Type outerTypeBeingTranslated) throws ChameleonProgrammerException, LookupException {
Type result = emptyInnerClassFor(relationBeingTranslated, outer);
List<? extends TypeElement> elements = relationBeingTranslated.componentType().directlyDeclaredElements();
processComponentRelationBody(relationBeingTranslated, outer, outerTypeBeingTranslated, result);
return result;
}
private Type emptyInnerClassFor(ComponentRelation relationBeingTranslated, Type outer) throws LookupException {
incorporateImports(relationBeingTranslated);
String className = innerClassName(relationBeingTranslated, outer);
Type result = new RegularJLoType(className);
for(Modifier mod: relationBeingTranslated.modifiers()) {
result.addModifier(mod.clone());
}
TypeReference superReference = superClassReference(relationBeingTranslated);
superReference.setUniParent(relationBeingTranslated);
substituteTypeParameters(superReference);
superReference.setUniParent(null);
result.addInheritanceRelation(new SubtypeRelation(superReference));
List<Method> selectors = selectorsFor(relationBeingTranslated);
for(Method selector:selectors) {
result.add(selector);
}
processInnerClassMethod(relationBeingTranslated, relationBeingTranslated.referencedComponentType(), result);
return result;
}
/**
* Incorporate the imports of the namespace part of the declared type of the component relation to
* the namespace part of the component relation.
* @param relationBeingTranslated
* @throws LookupException
*/
private void incorporateImports(ComponentRelation relationBeingTranslated)
throws LookupException {
incorporateImports(relationBeingTranslated, relationBeingTranslated.farthestAncestor(NamespacePart.class));
}
/**
* Incorporate the imports of the namespace part of the declared type of the component relation to
* the given namespace part.
* @param relationBeingTranslated
* @throws LookupException
*/
private void incorporateImports(ComponentRelation relationBeingTranslated, NamespacePart target)
throws LookupException {
Type baseT = relationBeingTranslated.referencedComponentType().baseType();
NamespacePart originalNsp = baseT.farthestAncestor(NamespacePart.class);
for(Import imp: originalNsp.imports()) {
target.addImport(imp.clone());
}
}
private void processComponentRelationBody(ComponentRelation relation, Type outer, Type outerTypeBeingTranslated, Type result)
throws LookupException {
ComponentType ctype = relation.componentTypeDeclaration();
if(ctype != null) {
if(ctype.ancestors().contains(outerTypeBeingTranslated)) {
ComponentType clonedType = ctype.clone();
clonedType.setUniParent(relation);
replaceOuterAndRootTargets(relation,clonedType);
for(TypeElement typeElement:clonedType.body().elements()) {
if(! (typeElement instanceof ComponentRelation)) {
result.add(typeElement);
}
}
}
}
}
private void processInnerClassMethod(ComponentRelation relation, Type componentType, Type result) throws LookupException {
List<Method> localMethods = componentType.directlyDeclaredMembers(Method.class);
for(Method<?,?,?,?> method: localMethods) {
if(method.is(method.language(ObjectOrientedLanguage.class).CONSTRUCTOR) == Ternary.TRUE) {
NormalMethod<?,?,?> clone = (NormalMethod) method.clone();
clone.setUniParent(method.parent());
for(BasicTypeReference<?> tref: clone.descendants(BasicTypeReference.class)) {
if(tref.getTarget() == null) {
Type element = tref.getElement();
Type base = element.baseType();
if((! (element instanceof ActualType)) && base instanceof RegularType) {
String fqn = base.getFullyQualifiedName();
String qn = Util.getAllButLastPart(fqn);
if(qn != null && (! qn.isEmpty())) {
tref.setTarget(new SimpleReference<TargetDeclaration>(qn, TargetDeclaration.class));
}
}
}
}
clone.setUniParent(null);
String name = result.signature().name();
RegularImplementation impl = (RegularImplementation) clone.implementation();
Block block = new Block();
impl.setBody(block);
// substitute parameters before replace the return type, method name, and the body.
// the types are not known in the component type, and the super class of the component type
// may not have a constructor with the same signature as the current constructor.
substituteTypeParameters(method, clone);
MethodInvocation inv = new SuperConstructorDelegation();
useParametersInInvocation(clone, inv);
block.addStatement(new StatementExpression(inv));
clone.setReturnTypeReference(relation.language(Java.class).createTypeReference(name));
((SimpleNameDeclarationWithParametersHeader)clone.header()).setName(name);
result.add(clone);
}
}
}
private TypeReference superClassReference(ComponentRelation relation) throws LookupException {
TypeReference superReference = relation.componentTypeReference().clone();
if(superReference instanceof ComponentParameterTypeReference) {
superReference = ((ComponentParameterTypeReference) superReference).componentTypeReference();
}
return superReference;
}
private void replaceOuterAndRootTargets(ComponentRelation rel, TypeElement<?> clone) {
List<AbstractTarget> outers = clone.descendants(AbstractTarget.class);
for(AbstractTarget o: outers) {
String name = o.getTargetDeclaration().getName();
SingleAssociation parentLink = o.parentLink();
ThisLiteral e = new ThisLiteral();
e.setTypeReference(new BasicJavaTypeReference(name));
parentLink.getOtherRelation().replace(parentLink, e.parentLink());
}
}
public final static String SHADOW = "_subobject_";
public final static String IMPL = "_implementation";
private Method createOutward(Method<?,?,?,?> method, String newName, String className) throws LookupException {
NormalMethod<?,?,?> result;
if(//(method.is(method.language(ObjectOrientedLanguage.class).DEFINED) == Ternary.TRUE) &&
(method.is(method.language(ObjectOrientedLanguage.class).OVERRIDABLE) == Ternary.TRUE)) {
result = innerMethod(method, method.name());
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
MethodInvocation invocation = invocation(result, newName);
TypeReference ref = method.language(Java.class).createTypeReference(className);
ThisLiteral target = new ThisLiteral(ref);
invocation.setTarget(target);
substituteTypeParameters(method, result);
addImplementation(method, body, invocation);
} else {
result = null;
}
return result;
}
private Method createDispathToOriginal(Method<?,?,?,?> method, ComponentRelation relation) throws LookupException {
NormalMethod<?,?,?> result = null;
result = innerMethod(method, method.name());
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
MethodInvocation invocation = invocation(result, original(method.name()));
substituteTypeParameters(method, result);
addImplementation(method, body, invocation);
return result;
}
private TypeReference getRelativeClassReference(ComponentRelation relation) {
return relation.language(Java.class).createTypeReference(getRelativeClassName(relation));
}
private String getRelativeClassName(ComponentRelation relation) {
return relation.nearestAncestor(Type.class).signature().name();
}
private void substituteTypeParameters(Method<?, ?, ?, ?> methodInTypeWhoseParametersMustBeSubstituted, NormalMethod<?, ?, ?> methodWhereActualTypeParametersMustBeFilledIn) throws LookupException {
methodWhereActualTypeParametersMustBeFilledIn.setUniParent(methodInTypeWhoseParametersMustBeSubstituted);
substituteTypeParameters(methodWhereActualTypeParametersMustBeFilledIn);
methodWhereActualTypeParametersMustBeFilledIn.setUniParent(null);
}
private void addImplementation(Method<?, ?, ?, ?> method, Block body, MethodInvocation invocation) throws LookupException {
if(method.returnType().equals(method.language(Java.class).voidType())) {
body.addStatement(new StatementExpression(invocation));
} else {
body.addStatement(new ReturnStatement(invocation));
}
}
private NormalMethod<?, ?, ?> innerMethod(Method<?, ?, ?, ?> method, String original) throws LookupException {
NormalMethod<?, ?, ?> result;
TypeReference tref = method.returnTypeReference().clone();
result = method.language(Java.class).createNormalMethod(method.header().clone(), tref);
((SimpleNameDeclarationWithParametersHeader)result.header()).setName(original);
ExceptionClause exceptionClause = method.getExceptionClause();
ExceptionClause clone = (exceptionClause != null ? exceptionClause.clone(): null);
result.setExceptionClause(clone);
result.addModifier(new Public());
return result;
}
/**
* Replace all references to type parameters
* @param element
* @throws LookupException
*/
private void substituteTypeParameters(Element<?> element) throws LookupException {
List<TypeReference> crossReferences =
element.descendants(TypeReference.class,
new UnsafePredicate<TypeReference,LookupException>() {
public boolean eval(TypeReference object) throws LookupException {
try {
return object.getDeclarator() instanceof InstantiatedTypeParameter;
} catch (LookupException e) {
e.printStackTrace();
throw e;
}
}
});
for(TypeReference cref: crossReferences) {
SingleAssociation parentLink = cref.parentLink();
Association childLink = parentLink.getOtherRelation();
InstantiatedTypeParameter declarator = (InstantiatedTypeParameter) cref.getDeclarator();
Type type = cref.getElement();
while(type instanceof ActualType) {
type = ((ActualType)type).aliasedType();
}
TypeReference namedTargetExpression = element.language(ObjectOrientedLanguage.class).createTypeReference(type.getFullyQualifiedName());
childLink.replace(parentLink, namedTargetExpression.parentLink());
}
}
private String innerClassName(Type outer, QualifiedName qn) {
StringBuffer result = new StringBuffer();
result.append(outer.signature().name());
result.append(SHADOW);
List<Signature> sigs = qn.signatures();
int size = sigs.size();
for(int i = 0; i < size; i++) {
result.append(((SimpleNameSignature)sigs.get(i)).name());
if(i < size - 1) {
result.append(SHADOW);
}
}
result.append(IMPL);
return result.toString();
}
private String innerClassName(ComponentRelation relation, Type outer) throws LookupException {
return innerClassName(outer, relation.signature());
}
private void replaceSuperCalls(Type type) throws LookupException {
List<SuperTarget> superTargets = type.descendants(SuperTarget.class, new UnsafePredicate<SuperTarget,LookupException>() {
@Override
public boolean eval(SuperTarget superTarget) throws LookupException {
return superTarget.getTargetDeclaration() instanceof ComponentRelation;
}
}
);
for(SuperTarget superTarget: superTargets) {
Element<?> cr = superTarget.parent();
if(cr instanceof CrossReferenceWithArguments) {
Element<?> inv = cr.parent();
if(inv instanceof RegularMethodInvocation) {
RegularMethodInvocation call = (RegularMethodInvocation) inv;
MethodInvocation subObjectSelection = new JavaMethodInvocation(getterName((ComponentRelation) superTarget.getTargetDeclaration()), null);
call.setTarget(subObjectSelection);
call.setName(original(call.name()));
}
}
}
}
private String original(String name) {
return "original__"+name;
}
private MemberVariableDeclarator fieldForComponent(ComponentRelation relation, Type outer) throws LookupException {
if(relation.overriddenMembers().isEmpty()) {
MemberVariableDeclarator result = new MemberVariableDeclarator(componentTypeReference(relation, outer));
result.add(new VariableDeclaration(fieldName(relation)));
return result;
} else {
return null;
}
}
private BasicJavaTypeReference innerClassTypeReference(ComponentRelation relation, Type outer) throws LookupException {
return relation.language(Java.class).createTypeReference(innerClassName(relation, outer));
}
private String getterName(ComponentRelation relation) {
return getterName(relation.signature().name());
}
private String getterName(String componentName) {
return componentName+COMPONENT;
}
public final static String COMPONENT = "__component__lkjkberfuncye__";
private Method getterForComponent(ComponentRelation relation, Type outer) throws LookupException {
if(relation.overriddenMembers().isEmpty()) {
JavaTypeReference returnTypeReference = componentTypeReference(relation, outer);
RegularMethod result = relation.language(Java.class).createNormalMethod(new SimpleNameDeclarationWithParametersHeader(getterName(relation)), returnTypeReference);
result.addModifier(new Public());
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
body.addStatement(new ReturnStatement(new NamedTargetExpression(fieldName(relation), null)));
return result;
} else {
return null;
}
}
private String setterName(ComponentRelation relation) {
return "set"+COMPONENT+"__"+relation.signature().name();
}
private Method setterForComponent(ComponentRelation relation, Type outer) throws LookupException {
if(relation.overriddenMembers().isEmpty()) {
String name = relation.signature().name();
RegularMethod result = relation.language(Java.class).createNormalMethod(new SimpleNameDeclarationWithParametersHeader(setterName(relation)), relation.language(Java.class).createTypeReference("void"));
BasicJavaTypeReference tref = componentTypeReference(relation, outer);
result.header().addFormalParameter(new FormalParameter(name, tref));
result.addModifier(new Public());
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
NamedTargetExpression componentFieldRef = new NamedTargetExpression(fieldName(relation), null);
componentFieldRef.setTarget(new ThisLiteral());
body.addStatement(new StatementExpression(new AssignmentExpression(componentFieldRef, new NamedTargetExpression(name, null))));
return result;
} else {
return null;
}
}
private BasicJavaTypeReference componentTypeReference(ComponentRelation relation, Type outer) throws LookupException {
BasicJavaTypeReference tref = innerClassTypeReference(relation,outer);
copyTypeParametersFromFarthestAncestor(outer,tref);
transformToInterfaceReference(tref);
return tref;
}
private MethodInvocation invocation(Method<?, ?, ?, ?> method, String origin) {
MethodInvocation invocation = new JavaMethodInvocation(origin, null);
// pass parameters.
useParametersInInvocation(method, invocation);
return invocation;
}
private void useParametersInInvocation(Method<?, ?, ?, ?> method, MethodInvocation invocation) {
for(FormalParameter param: method.formalParameters()) {
invocation.addArgument(new NamedTargetExpression(param.signature().name(), null));
}
}
private String fieldName(ComponentRelation relation) {
return relation.signature().name();
}
}
| src/subobjectjava/translate/JavaTranslator.java | package subobjectjava.translate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import jnome.core.expression.invocation.ConstructorInvocation;
import jnome.core.expression.invocation.JavaMethodInvocation;
import jnome.core.expression.invocation.NonLocalJavaTypeReference;
import jnome.core.expression.invocation.SuperConstructorDelegation;
import jnome.core.language.Java;
import jnome.core.modifier.Implements;
import jnome.core.type.BasicJavaTypeReference;
import jnome.core.type.JavaTypeReference;
import org.rejuse.association.Association;
import org.rejuse.association.SingleAssociation;
import org.rejuse.java.collections.TypeFilter;
import org.rejuse.logic.ternary.Ternary;
import org.rejuse.predicate.SafePredicate;
import org.rejuse.predicate.UnsafePredicate;
import org.rejuse.property.Property;
import subobjectjava.model.component.AbstractClause;
import subobjectjava.model.component.ActualComponentArgument;
import subobjectjava.model.component.ComponentNameActualArgument;
import subobjectjava.model.component.ComponentParameter;
import subobjectjava.model.component.ComponentParameterTypeReference;
import subobjectjava.model.component.ComponentRelation;
import subobjectjava.model.component.ComponentRelationSet;
import subobjectjava.model.component.ComponentType;
import subobjectjava.model.component.ConfigurationBlock;
import subobjectjava.model.component.ConfigurationClause;
import subobjectjava.model.component.FormalComponentParameter;
import subobjectjava.model.component.InstantiatedComponentParameter;
import subobjectjava.model.component.MultiActualComponentArgument;
import subobjectjava.model.component.MultiFormalComponentParameter;
import subobjectjava.model.component.ParameterReferenceActualArgument;
import subobjectjava.model.component.RenamingClause;
import subobjectjava.model.expression.AbstractTarget;
import subobjectjava.model.expression.ComponentParameterCall;
import subobjectjava.model.expression.OuterTarget;
import subobjectjava.model.expression.SubobjectConstructorCall;
import subobjectjava.model.language.JLo;
import subobjectjava.model.type.RegularJLoType;
import chameleon.core.compilationunit.CompilationUnit;
import chameleon.core.declaration.CompositeQualifiedName;
import chameleon.core.declaration.Declaration;
import chameleon.core.declaration.QualifiedName;
import chameleon.core.declaration.Signature;
import chameleon.core.declaration.SimpleNameDeclarationWithParametersHeader;
import chameleon.core.declaration.SimpleNameDeclarationWithParametersSignature;
import chameleon.core.declaration.SimpleNameSignature;
import chameleon.core.declaration.TargetDeclaration;
import chameleon.core.element.Element;
import chameleon.core.expression.Expression;
import chameleon.core.expression.InvocationTarget;
import chameleon.core.expression.MethodInvocation;
import chameleon.core.expression.NamedTarget;
import chameleon.core.expression.NamedTargetExpression;
import chameleon.core.lookup.DeclarationSelector;
import chameleon.core.lookup.LookupException;
import chameleon.core.lookup.SelectorWithoutOrder;
import chameleon.core.member.Member;
import chameleon.core.method.Implementation;
import chameleon.core.method.Method;
import chameleon.core.method.RegularImplementation;
import chameleon.core.method.RegularMethod;
import chameleon.core.method.exception.ExceptionClause;
import chameleon.core.modifier.ElementWithModifiers;
import chameleon.core.modifier.Modifier;
import chameleon.core.namespace.Namespace;
import chameleon.core.namespace.NamespaceElement;
import chameleon.core.namespacepart.Import;
import chameleon.core.namespacepart.NamespacePart;
import chameleon.core.namespacepart.TypeImport;
import chameleon.core.reference.CrossReference;
import chameleon.core.reference.CrossReferenceWithArguments;
import chameleon.core.reference.CrossReferenceWithName;
import chameleon.core.reference.CrossReferenceWithTarget;
import chameleon.core.reference.SimpleReference;
import chameleon.core.reference.SpecificReference;
import chameleon.core.statement.Block;
import chameleon.core.variable.FormalParameter;
import chameleon.core.variable.VariableDeclaration;
import chameleon.core.variable.VariableDeclarator;
import chameleon.exception.ChameleonProgrammerException;
import chameleon.exception.ModelException;
import chameleon.oo.language.ObjectOrientedLanguage;
import chameleon.oo.type.BasicTypeReference;
import chameleon.oo.type.DeclarationWithType;
import chameleon.oo.type.ParameterBlock;
import chameleon.oo.type.RegularType;
import chameleon.oo.type.Type;
import chameleon.oo.type.TypeElement;
import chameleon.oo.type.TypeReference;
import chameleon.oo.type.TypeWithBody;
import chameleon.oo.type.generics.ActualType;
import chameleon.oo.type.generics.BasicTypeArgument;
import chameleon.oo.type.generics.InstantiatedTypeParameter;
import chameleon.oo.type.generics.TypeParameter;
import chameleon.oo.type.generics.TypeParameterBlock;
import chameleon.oo.type.inheritance.AbstractInheritanceRelation;
import chameleon.oo.type.inheritance.SubtypeRelation;
import chameleon.support.expression.AssignmentExpression;
import chameleon.support.expression.SuperTarget;
import chameleon.support.expression.ThisLiteral;
import chameleon.support.member.simplename.SimpleNameMethodInvocation;
import chameleon.support.member.simplename.method.NormalMethod;
import chameleon.support.member.simplename.method.RegularMethodInvocation;
import chameleon.support.member.simplename.variable.MemberVariableDeclarator;
import chameleon.support.modifier.Interface;
import chameleon.support.modifier.Public;
import chameleon.support.statement.ReturnStatement;
import chameleon.support.statement.StatementExpression;
import chameleon.support.statement.ThrowStatement;
import chameleon.support.variable.LocalVariableDeclarator;
import chameleon.util.Util;
public class JavaTranslator {
public List<CompilationUnit> translate(CompilationUnit source, CompilationUnit implementationCompilationUnit) throws LookupException, ModelException {
List<CompilationUnit> result = new ArrayList<CompilationUnit>();
// Remove a possible old translation of the given compilation unit
// from the target model.
NamespacePart originalNamespacePart = source.namespaceParts().get(0);
NamespacePart newNamespacePart = implementationCompilationUnit.namespaceParts().get(0);
Iterator<Type> originalTypes = originalNamespacePart.children(Type.class).iterator();
Iterator<Type> newTypes = newNamespacePart.children(Type.class).iterator();
while(originalTypes.hasNext()) {
SingleAssociation<Type, Element> newParentLink = newTypes.next().parentLink();
Type translated = translatedImplementation(originalTypes.next());
newParentLink.getOtherRelation().replace(newParentLink, translated.parentLink());
}
newNamespacePart.clearImports();
for(Import imp: originalNamespacePart.imports()) {
newNamespacePart.addImport(imp.clone());
}
implementationCompilationUnit.flushCache();
result.add(implementationCompilationUnit);
implementationCompilationUnit.namespacePart(1).getNamespaceLink().lock();
CompilationUnit interfaceCompilationUnit = interfaceCompilationUnit(source, implementationCompilationUnit);
for(NamespacePart part: implementationCompilationUnit.descendants(NamespacePart.class)) {
part.removeDuplicateImports();
}
for(NamespacePart part: interfaceCompilationUnit.descendants(NamespacePart.class)) {
part.removeDuplicateImports();
}
result.add(interfaceCompilationUnit);
return result;
}
private boolean isJLo(NamespaceElement element) {
Namespace ns = element.getNamespace();
return ! ns.getFullyQualifiedName().startsWith("java.");
}
private CompilationUnit interfaceCompilationUnit(CompilationUnit original, CompilationUnit implementation) throws ModelException {
original.flushCache();
implementation.flushCache();
CompilationUnit interfaceCompilationUnit = implementation.cloneTo(implementation.language());
NamespacePart interfaceNamespacePart = interfaceCompilationUnit.namespacePart(1);
Type interfaceType = interfaceNamespacePart.declarations(Type.class).get(0);
interfaceType.addModifier(new Interface());
transformToInterfaceDeep(interfaceType);
for(BasicJavaTypeReference tref: interfaceType.descendants(BasicJavaTypeReference.class)) {
String name = tref.signature().name();
if(name.endsWith(IMPL)) {
tref.setSignature(new SimpleNameSignature(interfaceName(name)));
}
}
interfaceCompilationUnit.flushCache();
return interfaceCompilationUnit;
}
private void rewriteConstructorCalls(Element<?> type) throws LookupException {
Java language = type.language(Java.class);
List<ConstructorInvocation> invocations = type.descendants(ConstructorInvocation.class);
for(ConstructorInvocation invocation: invocations) {
try {
Type constructedType = invocation.getType();
if(isJLo(constructedType) && (! constructedType.isTrue(language.PRIVATE))) {
transformToImplReference((CrossReferenceWithName) invocation.getTypeReference());
}
} catch(LookupException exc) {
transformToImplReference((CrossReferenceWithName) invocation.getTypeReference());
}
}
}
private void rewriteThisLiterals(Element<?> type) throws LookupException {
List<ThisLiteral> literals = type.descendants(ThisLiteral.class);
for(ThisLiteral literal: literals) {
TypeReference typeReference = literal.getTypeReference();
if(typeReference != null) {
transformToImplReference((CrossReferenceWithName) typeReference);
}
}
}
private void rewriteComponentAccess(Element<?> type) throws LookupException {
List<CrossReference> literals = type.descendants(CrossReference.class);
for(CrossReference literal: literals) {
if((literal instanceof CrossReferenceWithTarget)) {
transformComponentAccessors((CrossReferenceWithTarget) literal);
}
}
}
private void transformComponentAccessors(CrossReferenceWithTarget cwt) {
Element target = cwt.getTarget();
if(target instanceof CrossReferenceWithTarget) {
transformComponentAccessors((CrossReferenceWithTarget) target);
}
boolean rewrite = false;
String name = null;
if((! (cwt instanceof MethodInvocation)) && (! (cwt instanceof TypeReference))) {
name = ((CrossReferenceWithName)cwt).name();
try {
Declaration decl = cwt.getElement();
if(decl instanceof ComponentRelation) {
rewrite = true;
}
}catch(LookupException exc) {
// rewrite = true;
}
}
if(rewrite) {
String getterName = getterName(name);
MethodInvocation inv = new JavaMethodInvocation(getterName,(InvocationTarget) target);
SingleAssociation parentLink = cwt.parentLink();
parentLink.getOtherRelation().replace(parentLink, inv.parentLink());
}
}
private void transformToInterfaceDeep(Type type) throws ModelException {
List<Type> types = type.descendants(Type.class);
types.add(type);
for(Type t: types) {
transformToInterface(t);
}
}
private void transformToInterface(Type type) throws ModelException {
String name = type.getName();
Java language = type.language(Java.class);
if(name.endsWith(IMPL)) {
copyTypeParametersIfNecessary(type);
makePublic(type);
List<SubtypeRelation> inheritanceRelations = type.nonMemberInheritanceRelations(SubtypeRelation.class);
int last = inheritanceRelations.size() - 1;
inheritanceRelations.get(last).disconnect();
for(TypeElement decl: type.directlyDeclaredElements()) {
if(decl instanceof Method) {
((Method) decl).setImplementation(null);
if(decl.is(language.CLASS) == Ternary.TRUE) {
decl.disconnect();
}
}
if((decl.is(language.CONSTRUCTOR) == Ternary.TRUE) ||
(decl.is(language.PRIVATE) == Ternary.TRUE) ||
(decl instanceof VariableDeclarator && (! (decl.is(language.CLASS) == Ternary.TRUE)))) {
decl.disconnect();
}
if(decl instanceof ElementWithModifiers) {
makePublic(decl);
}
}
type.signature().setName(interfaceName(name));
if(! (type.is(language.INTERFACE) == Ternary.TRUE)) {
type.addModifier(new Interface());
}
}
}
private void copyTypeParametersIfNecessary(Type type) {
Type outmost = type.farthestAncestor(Type.class);
if(outmost != null) {
List<TypeParameter> typeParameters = outmost.parameters(TypeParameter.class);
ParameterBlock tpars = type.parameterBlock(TypeParameter.class);
if(tpars == null) {
type.addParameterBlock(new TypeParameterBlock());
}
for(TypeParameter<?> typeParameter:typeParameters) {
type.addParameter(TypeParameter.class, typeParameter.clone());
}
}
}
private void makePublic(ElementWithModifiers<?> element) throws ModelException {
Java language = element.language(Java.class);
Property access = element.property(language.SCOPE_MUTEX);
if(access != language.PRIVATE) {
for(Modifier mod: element.modifiers(language.SCOPE_MUTEX)) {
mod.disconnect();
}
element.addModifier(new Public());
}
}
private void transformToImplReference(CrossReferenceWithName ref) {
if(ref instanceof CrossReferenceWithTarget) {
CrossReferenceWithName target = (CrossReferenceWithName) ((CrossReferenceWithTarget)ref).getTarget();
if(target != null) {
transformToImplReference(target);
}
}
boolean change;
try {
Declaration referencedElement = ref.getElement();
if(referencedElement instanceof Type) {
change = true;
} else {
change = false;
}
} catch(LookupException exc) {
change = true;
}
if(change) {
String name = ref.name();
if(! name.endsWith(IMPL)) {
ref.setName(name+IMPL);
}
}
}
private void transformToInterfaceReference(SpecificReference ref) {
SpecificReference target = (SpecificReference) ref.getTarget();
if(target != null) {
transformToInterfaceReference(target);
}
String name = ref.signature().name();
if(name.endsWith(IMPL)) {
ref.setSignature(new SimpleNameSignature(interfaceName(name)));
}
}
private String interfaceName(String name) {
if(! name.endsWith(IMPL)) {
throw new IllegalArgumentException();
}
return name.substring(0, name.length()-IMPL.length());
}
/**
* Return a type that represents the translation of the given JLow class to a Java class.
* @throws ModelException
*/
private Type translatedImplementation(Type original) throws ChameleonProgrammerException, ModelException {
Type result = original.clone();
result.setUniParent(original.parent());
List<ComponentRelation> relations = original.directlyDeclaredMembers(ComponentRelation.class);
for(ComponentRelation relation : relations) {
// Add a getter for subobject
Method getterForComponent = getterForComponent(relation,result);
if(getterForComponent != null) {
result.add(getterForComponent);
}
// Add a setter for subobject
Method setterForComponent = setterForComponent(relation,result);
if(setterForComponent != null) {
result.add(setterForComponent);
}
// Create the inner classes for the components
inner(result, relation, result,original);
result.flushCache();
addOutwardDelegations(relation, result);
result.flushCache();
}
replaceSuperCalls(result);
for(ComponentRelation relation: result.directlyDeclaredMembers(ComponentRelation.class)) {
replaceConstructorCalls(relation);
MemberVariableDeclarator fieldForComponent = fieldForComponent(relation,result);
if(fieldForComponent != null) {
result.add(fieldForComponent);
}
relation.disconnect();
}
List<Method> decls = selectorsFor(result);
for(Method decl:decls) {
result.add(decl);
}
List<ComponentParameterCall> calls = result.descendants(ComponentParameterCall.class);
for(ComponentParameterCall call: calls) {
FormalComponentParameter parameter = call.getElement();
MethodInvocation expr = new JavaMethodInvocation(selectorName(parameter),null);
expr.addArgument((Expression) call.target());
SingleAssociation pl = call.parentLink();
pl.getOtherRelation().replace(pl, expr.parentLink());
}
for(SubtypeRelation rel: result.nonMemberInheritanceRelations(SubtypeRelation.class)) {
processSuperComponentParameters(rel);
}
if(result.getFullyQualifiedName().equals("example.meta.Klass")) {
System.out.println("debug");
}
rebindOverriddenMethods(result,original);//TODO
rewriteConstructorCalls(result);
rewriteThisLiterals(result);
rewriteComponentAccess(result);
expandReferences(result);
removeNonLocalReferences(result);
// The result is still temporarily attached to the original model.
transformToImplRecursive(result);
result.setUniParent(null);
return result;
}
private void rebindOverriddenMethods(Type result, Type original) throws LookupException {
for(final Method method: original.descendants(Method.class)) {
rebindOverriddenMethodsOf(result, original, method);
}
}
private void rebindOverriddenMethodsOf(Type result, Type original, Method method) throws LookupException, Error {
if(method.name().equals("isValid")) {
System.out.println("debug");
}
Set<? extends Member> overridden = method.overriddenMembers();
if(! overridden.isEmpty()) {
final Method tmp = method.clone();
// Type containerOfNewDefinition = createOrGetInnerTypeForMethod(result, original, method);
Type containerOfNewDefinition = containerOfDefinition(result,original, method);
if(containerOfNewDefinition != null) {
tmp.setUniParent(containerOfNewDefinition);
// substituteTypeParameters(method);
DeclarationSelector<Method> selector = new SelectorWithoutOrder<Method>(Method.class) {
@Override
public Signature signature() {
return tmp.signature();
}
};
Method newDefinitionInResult = null;
try {
newDefinitionInResult = containerOfNewDefinition.members(selector).get(0);
} catch (IndexOutOfBoundsException e) {
containerOfNewDefinition = containerOfDefinition(result, original, method);
newDefinitionInResult = containerOfNewDefinition.members(selector).get(0);
}
Method<?,?,?,?> stat = newDefinitionInResult.clone();
String name = toImplName(containerOfNewDefinition.getFullyQualifiedName().replace('.', '_'))+"_"+method.name();
stat.setName(name);
containerOfNewDefinition.add(stat);
if(!stat.descendants(ComponentParameterCall.class).isEmpty()) {
throw new Error();
}
}
}
for(Member toBeRebound: overridden) {
rebind(result, original, method, (Method) toBeRebound);
}
}
private void rebind(Type container, Type original, Method<?,?,?,?> newDefinition, Method toBeRebound) throws LookupException {
Type containerOfNewDefinition = containerOfDefinition(container,original, newDefinition);
Type rootOfNewDefinitionInOriginal = levelOfDefinition(newDefinition);
List<Element> trailOfRootInOriginal = filterAncestors(rootOfNewDefinitionInOriginal);
trailOfRootInOriginal.add(0, rootOfNewDefinitionInOriginal);
trailOfRootInOriginal.remove(trailOfRootInOriginal.size()-1);
Type containerToAdd = createOrGetInnerTypeAux(container, original, trailOfRootInOriginal,1);
List<Element> trailtoBeReboundInOriginal = filterAncestors(toBeRebound);
Type rootOfToBeRebound = levelOfDefinition(toBeRebound);
if(! trailtoBeReboundInOriginal.contains(rootOfToBeRebound)) {
System.out.println("debug");
}
while(! (trailtoBeReboundInOriginal.get(trailtoBeReboundInOriginal.size()-1) == rootOfToBeRebound)) {
trailtoBeReboundInOriginal.remove(trailtoBeReboundInOriginal.size()-1);
}
trailtoBeReboundInOriginal.remove(trailtoBeReboundInOriginal.size()-1);
Type x = containerToAdd;
if(! trailtoBeReboundInOriginal.isEmpty()) {
x = createOrGetInnerTypeAux(containerToAdd, original, trailtoBeReboundInOriginal,1);
}
// Type containerOfToBebound = containerOfDefinition(containerOfNewDefinition, original, toBeRebound);
Type containerOfToBebound = x;
if(x != containerOfToBebound) {
System.out.println("debug");
}
// containerOfToBebound = x;
if((containerOfToBebound != null) && ! containerOfToBebound.sameAs(containerOfNewDefinition)) {
if(newDefinition.name().equals("isValid")) {
System.out.println("debug");
}
System.out.println("----------------------");
System.out.println("Source: "+containerOfNewDefinition.getFullyQualifiedName()+"."+newDefinition.name());
System.out.println("Target: "+containerOfToBebound.getFullyQualifiedName()+"."+toBeRebound.name());
System.out.println("----------------------");
String thisName = containerOfNewDefinition.getFullyQualifiedName();
Method clone = createOutward(toBeRebound, newDefinition.name(),thisName);
String newName = containerOfToBebound.getFullyQualifiedName().replace('.', '_')+"_"+clone.name();
if(newName.equals("radio_Radio_Radio_subobject_frequency_implementation_Radio_subobject_frequency_implementation_subobject_value_implementation_Radio_subobject_frequency_implementation_subobject_value_implementation_subobject_frequency_implementation_Radio_subobject_frequency_implementation_subobject_value_implementation_subobject_frequency_implementation_subobject_value_implementation_getValue")) {
System.out.println("debug");
}
//FIXME this is tricky.
clone.setUniParent(toBeRebound);
Implementation<Implementation> impl = clone.implementation();
clone.setImplementation(null);
substituteTypeParameters(clone);
clone.setImplementation(impl);
clone.setUniParent(null);
containerOfToBebound.add(clone);
Method<?,?,?,?> stat = clone.clone();
stat.setName(newName);
String name = containerOfNewDefinition.getFullyQualifiedName().replace('.', '_');
for(SimpleNameMethodInvocation inv:stat.descendants(SimpleNameMethodInvocation.class)) {
name = toImplName(name);
inv.setName(name+"_"+newDefinition.name());
}
containerOfToBebound.add(stat);
containerOfToBebound.flushCache();
}
}
private Type containerOfDefinition(Type container, Type original,
Method<?, ?, ?, ?> newDefinition) throws LookupException {
Type containerOfNewDefinition = container;
Type rootOfNewDefinitionInOriginal = levelOfDefinition(newDefinition);
List<Element> trailOfRootInOriginal = filterAncestors(rootOfNewDefinitionInOriginal);
trailOfRootInOriginal.add(0, rootOfNewDefinitionInOriginal);
trailOfRootInOriginal.remove(trailOfRootInOriginal.size()-1);
containerOfNewDefinition = createOrGetInnerTypeAux(container, original, trailOfRootInOriginal,1);
List<Element> trailNewDefinitionInOriginal = filterAncestors(newDefinition);
// Remove everything up to the container.
while(! (trailNewDefinitionInOriginal.get(trailNewDefinitionInOriginal.size()-1) == rootOfNewDefinitionInOriginal)) {
trailNewDefinitionInOriginal.remove(trailNewDefinitionInOriginal.size()-1);
}
// Remove the container.
trailNewDefinitionInOriginal.remove(trailNewDefinitionInOriginal.size()-1);
if(! trailNewDefinitionInOriginal.isEmpty()) {
// trailOfRootInOriginal.add(0, rootOfNewDefinitionInOriginal);
containerOfNewDefinition = createOrGetInnerTypeAux(containerOfNewDefinition, original, trailNewDefinitionInOriginal,1);
}
return containerOfNewDefinition;
}
private Type levelOfDefinition(Element<?> element) {
Type result = element.nearestAncestor(Type.class, new SafePredicate<Type>(){
@Override
public boolean eval(Type object) {
return ! (object instanceof ComponentType);
}});
return result;
}
private String toImplName(String name) {
if(! name.endsWith(IMPL)) {
name = name + IMPL;
}
return name;
}
private Type createOrGetInnerTypeForType(Type container, Type original, Type current, List<Element> elements, int baseOneIndex) throws LookupException {
// Signature innerName = (new SimpleNameSignature(innerClassName(relationBeingTranslated, original)));
Signature innerName = current.signature().clone();
SimpleReference<Type> tref = new SimpleReference<Type>(innerName, Type.class);
tref.setUniParent(container);
Type result;
try {
result= tref.getElement();
} catch(LookupException exc) {
// We add the imports to the original. They are copied later on to 'container'.
ComponentRelation relation = ((ComponentType)current).nearestAncestor(ComponentRelation.class);
result = innerClassFor(relation, container);
NamespacePart namespacePart = container.farthestAncestor(NamespacePart.class);
incorporateImports(relation, namespacePart);
// Since we are adding inner classes that were not written in the current namespacepart, their type
// may not have been imported yet. Therefore, we add an import of the referenced component type.
namespacePart.addImport(new TypeImport(container.language(Java.class).createTypeReference(relation.referencedComponentType().getFullyQualifiedName())));
container.add(result);
container.flushCache();
}
return createOrGetInnerTypeAux(result, original, elements, baseOneIndex + 1);
}
private Type createOrGetInnerTypeForComponent(Type container, Type original, ComponentRelation relationBeingTranslated, List<Element> elements, int baseOneIndex) throws LookupException {
Signature innerName = null;
innerName = (new SimpleNameSignature(innerClassName(relationBeingTranslated, container)));
SimpleReference<Type> tref = new SimpleReference<Type>(innerName, Type.class);
tref.setUniParent(container);
Type result;
try {
result= tref.getElement();
} catch(LookupException exc) {
// We add the imports to the original. They are copied later on to 'container'.
result = innerClassFor(relationBeingTranslated, container);
NamespacePart namespacePart = container.farthestAncestor(NamespacePart.class);
incorporateImports(relationBeingTranslated, namespacePart);
// Since we are adding inner classes that were not written in the current namespacepart, their type
// may not have been imported yet. Therefore, we add an import of the referenced component type.
namespacePart.addImport(new TypeImport(container.language(Java.class).createTypeReference(relationBeingTranslated.referencedComponentType().getFullyQualifiedName())));
container.add(result);
container.flushCache();
}
return createOrGetInnerTypeAux(result, original, elements, baseOneIndex + 1);
}
private List<Element> filterAncestors(Element<?> element) {
SafePredicate<Element> predicate = componentRelationOrNonComponentTypePredicate();
return element.ancestors(Element.class, predicate);
}
private SafePredicate<Element> componentRelationOrNonComponentTypePredicate() {
return new SafePredicate<Element>(){
@Override
public boolean eval(Element object) {
return (object instanceof ComponentRelation) || (object instanceof Type && !(object instanceof ComponentType));
}};
}
private SafePredicate<Type> nonComponentTypePredicate() {
return new SafePredicate<Type>(){
@Override
public boolean eval(Type object) {
return !(object instanceof ComponentType);
}};
}
private Type createOrGetInnerTypeAux(Type container, Type original, List<Element> elements, int baseOneIndex) throws LookupException {
int index = elements.size()-baseOneIndex;
if(index >= 0) {
Element element = elements.get(index);
if(element instanceof ComponentRelation) {
return createOrGetInnerTypeForComponent(container,original, (ComponentRelation) element, elements,baseOneIndex);
} else {
return createOrGetInnerTypeForType(container,original, (Type) element, elements,baseOneIndex);
}
} else {
return container;
}
}
private void transformToImplRecursive(Type type) throws ModelException {
transformToImpl(type);
for(Type nested: type.directlyDeclaredMembers(Type.class)) {
transformToImplRecursive(nested);
}
}
private void transformToImpl(Type type) throws ModelException {
JLo lang = type.language(JLo.class);
if(! type.isTrue(lang.PRIVATE)) {
// Change the name of the outer type.
// What a crappy code. I would probably be easier to not add IMPL
// to the generated subobject class in the first place, but add
// it afterwards.
String oldName = type.getName();
String name = oldName;
if(! name.endsWith(IMPL)) {
name = name +IMPL;
type.signature().setName(name);
}
for(SubtypeRelation relation: type.nonMemberInheritanceRelations(SubtypeRelation.class)) {
BasicJavaTypeReference tref = (BasicJavaTypeReference) relation.superClassReference();
try {
if((! relation.isTrue(lang.IMPLEMENTS_RELATION)) && isJLo(tref.getElement())) {
tref.setSignature(new SimpleNameSignature(tref.signature().name()+IMPL));
}
}
catch(LookupException exc) {
tref.getElement();
throw exc;
}
}
implementOwnInterface(type);
for(TypeElement decl: type.directlyDeclaredElements()) {
if((decl instanceof Method) && (decl.is(lang.CONSTRUCTOR) == Ternary.TRUE)) {
((Method)decl).setName(name);
}
if(decl instanceof ElementWithModifiers) {
makePublic(decl);
}
}
}
}
private void implementOwnInterface(Type type) {
JLo language = type.language(JLo.class);
if(!type.isTrue(language.PRIVATE)) {
String oldFQN = type.getFullyQualifiedName();
BasicJavaTypeReference createTypeReference = language.createTypeReference(oldFQN);
transformToInterfaceReference(createTypeReference);
copyTypeParametersIfNecessary(type, createTypeReference);
SubtypeRelation relation = new SubtypeRelation(createTypeReference);
relation.addModifier(new Implements());
type.addInheritanceRelation(relation);
}
}
private void copyTypeParametersIfNecessary(Type type, BasicJavaTypeReference createTypeReference) {
Java language = type.language(Java.class);
if(! (type.is(language.CLASS) == Ternary.TRUE)) {
copyTypeParametersFromFarthestAncestor(type, createTypeReference);
}
}
private void copyTypeParametersFromFarthestAncestor(Element<?> type, BasicJavaTypeReference createTypeReference) {
Type farthestAncestor = type.farthestAncestorOrSelf(Type.class);
Java language = type.language(Java.class);
List<TypeParameter> tpars = farthestAncestor.parameters(TypeParameter.class);
for(TypeParameter parameter:tpars) {
createTypeReference.addArgument(language.createBasicTypeArgument(language.createTypeReference(parameter.signature().name())));
}
}
private void processSuperComponentParameters(AbstractInheritanceRelation<?> relation) throws LookupException {
TypeReference tref = relation.superClassReference();
Type type = relation.nearestAncestor(Type.class);
if(tref instanceof ComponentParameterTypeReference) {
ComponentParameterTypeReference ctref = (ComponentParameterTypeReference) tref;
Type ctype = tref.getType();
type.addAll(selectorsForComponent(ctype));
relation.setSuperClassReference(ctref.componentTypeReference());
}
}
private void removeNonLocalReferences(Type type) throws LookupException {
for(NonLocalJavaTypeReference tref: type.descendants(NonLocalJavaTypeReference.class)) {
SingleAssociation<NonLocalJavaTypeReference, Element> parentLink = tref.parentLink();
parentLink.getOtherRelation().replace(parentLink, tref.actualReference().parentLink());
}
}
private void expandReferences(Element<?> type) throws LookupException {
Java language = type.language(Java.class);
for(BasicJavaTypeReference tref: type.descendants(BasicJavaTypeReference.class)) {
if(tref.getTarget() == null) {
try {
// Filthy hack, should add meta information to such references, and use that instead.
if(! tref.signature().name().contains(SHADOW)) {
Type element = tref.getElement();
if(! element.isTrue(language.PRIVATE)) {
String fullyQualifiedName = element.getFullyQualifiedName();
String predecessor = Util.getAllButLastPart(fullyQualifiedName);
if(predecessor != null) {
NamedTarget nt = new NamedTarget(predecessor);
tref.setTarget(nt);
}
}
}
} catch(LookupException exc) {
// This occurs because a generated element cannot be resolved in the original model. E.g.
// an inner class of another class than the one that has been generated.
}
}
}
}
private List<Method> selectorsFor(ComponentRelation rel) throws LookupException {
Type t = rel.referencedComponentType();
return selectorsForComponent(t);
}
private List<Method> selectorsForComponent(Type t) throws LookupException {
List<Method> result = new ArrayList<Method>();
for(ComponentParameter par: t.parameters(ComponentParameter.class)) {
Method realSelector= realSelectorFor((InstantiatedComponentParameter) par);
realSelector.setUniParent(t);
substituteTypeParameters(realSelector);
realSelector.setUniParent(null);
result.add(realSelector);
}
return result;
}
private Method realSelectorFor(InstantiatedComponentParameter<?> par) throws LookupException {
SimpleNameDeclarationWithParametersHeader header = new SimpleNameDeclarationWithParametersHeader(selectorName(par));
FormalComponentParameter formal = par.formalParameter();
Java language = par.language(Java.class);
// Method result = new NormalMethod(header,formal.componentTypeReference().clone());
Type declarationType = formal.declarationType();
JavaTypeReference reference = language.reference(declarationType);
reference.setUniParent(null);
Method result = par.language(Java.class).createNormalMethod(header,reference);
result.addModifier(new Public());
// result.addModifier(new Abstract());
header.addFormalParameter(new FormalParameter("argument", formal.containerTypeReference().clone()));
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
ActualComponentArgument arg = par.argument();
Expression expr;
if(arg instanceof ComponentNameActualArgument) {
ComponentNameActualArgument singarg = (ComponentNameActualArgument) arg;
expr = new JavaMethodInvocation(getterName(singarg.declaration()),new NamedTargetExpression("argument", null));
body.addStatement(new ReturnStatement(expr));
} else if(arg instanceof ParameterReferenceActualArgument) {
ParameterReferenceActualArgument ref = (ParameterReferenceActualArgument) arg;
ComponentParameter p = ref.declaration();
expr = new JavaMethodInvocation(selectorName(p), null);
((JavaMethodInvocation)expr).addArgument(new NamedTargetExpression("argument",null));
body.addStatement(new ReturnStatement(expr));
}
else {
// result variable declaration
VariableDeclaration declaration = new VariableDeclaration("result");
BasicJavaTypeReference arrayList = language.createTypeReference("java.util.ArrayList");
JavaTypeReference componentType = language.reference(formal.componentTypeReference().getElement());
componentType.setUniParent(null);
BasicTypeArgument targ = language.createBasicTypeArgument(componentType);
arrayList.addArgument(targ);
// LocalVariableDeclarator varDecl = new LocalVariableDeclarator(reference.clone());
LocalVariableDeclarator varDecl = new LocalVariableDeclarator(arrayList.clone());
Expression init = new ConstructorInvocation(arrayList, null);
declaration.setInitialization(init);
varDecl.add(declaration);
body.addStatement(varDecl);
// add all components
ComponentRelationSet componentRelations = ((MultiActualComponentArgument)arg).declaration();
for(DeclarationWithType rel: componentRelations.relations()) {
Expression t = new NamedTargetExpression("result", null);
SimpleNameMethodInvocation inv = new JavaMethodInvocation("add", t);
Expression componentSelector;
if(rel instanceof ComponentParameter) {
if(rel instanceof MultiFormalComponentParameter) {
inv.setName("addAll");
}
componentSelector = new JavaMethodInvocation(selectorName((ComponentParameter)rel), null);
((JavaMethodInvocation)componentSelector).addArgument(new NamedTargetExpression("argument",null));
} else {
componentSelector = new NamedTargetExpression(rel.signature().name(), new NamedTargetExpression("argument",null));
}
inv.addArgument(componentSelector);
body.addStatement(new StatementExpression(inv));
}
// return statement
expr = new NamedTargetExpression("result",null);
body.addStatement(new ReturnStatement(expr));
}
return result;
}
private List<Method> selectorsFor(Type type) throws LookupException {
ParameterBlock<?,ComponentParameter> block = type.parameterBlock(ComponentParameter.class);
List<Method> result = new ArrayList<Method>();
if(block != null) {
for(ComponentParameter par: block.parameters()) {
result.add(selectorFor((FormalComponentParameter<?>) par));
}
}
return result;
}
private String selectorName(ComponentParameter<?> par) {
return "__select$"+ toUnderScore(par.nearestAncestor(Type.class).getFullyQualifiedName())+"$"+par.signature().name();
}
private String toUnderScore(String string) {
return string.replace('.', '_');
}
private Method selectorFor(FormalComponentParameter<?> par) throws LookupException {
SimpleNameDeclarationWithParametersHeader header = new SimpleNameDeclarationWithParametersHeader(selectorName(par));
Java language = par.language(Java.class);
// Method result = new NormalMethod(header,par.componentTypeReference().clone());
JavaTypeReference reference = language.reference(par.declarationType());
reference.setUniParent(null);
Method result = par.language(Java.class).createNormalMethod(header,reference);
result.addModifier(new Public());
// result.addModifier(new Abstract());
header.addFormalParameter(new FormalParameter("argument", par.containerTypeReference().clone()));
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
ConstructorInvocation cons = new ConstructorInvocation((BasicJavaTypeReference) par.language(Java.class).createTypeReference("java.lang.Error"), null);
body.addStatement(new ThrowStatement(cons));
return result;
}
private void replaceConstructorCalls(final ComponentRelation relation) throws LookupException {
Type type = relation.nearestAncestor(Type.class);
List<SubobjectConstructorCall> constructorCalls = type.descendants(SubobjectConstructorCall.class, new UnsafePredicate<SubobjectConstructorCall,LookupException>() {
@Override
public boolean eval(SubobjectConstructorCall constructorCall) throws LookupException {
return constructorCall.getTarget().getElement().equals(relation);
}
}
);
for(SubobjectConstructorCall call: constructorCalls) {
MethodInvocation inv = new ConstructorInvocation((BasicJavaTypeReference) innerClassTypeReference(relation, type), null);
// move actual arguments from subobject constructor call to new constructor call.
inv.addAllArguments(call.getActualParameters());
MethodInvocation setterCall = new JavaMethodInvocation(setterName(relation), null);
setterCall.addArgument(inv);
SingleAssociation<SubobjectConstructorCall, Element> parentLink = call.parentLink();
parentLink.getOtherRelation().replace(parentLink, setterCall.parentLink());
}
}
private void inner(Type type, ComponentRelation relation, Type outer, Type outerTypeBeingTranslated) throws LookupException {
Type innerClass = createInnerClassFor(relation,type,outerTypeBeingTranslated);
type.add(innerClass);
Type componentType = relation.componentType();
for(ComponentRelation nestedRelation: componentType.directlyDeclaredElements(ComponentRelation.class)) {
// subst parameters
ComponentRelation clonedNestedRelation = nestedRelation.clone();
clonedNestedRelation.setUniParent(nestedRelation.parent());
substituteTypeParameters(clonedNestedRelation);
inner(innerClass, clonedNestedRelation, outer,outerTypeBeingTranslated);
}
}
private void addOutwardDelegations(ComponentRelation relation, Type outer) throws LookupException {
ConfigurationBlock block = relation.configurationBlock();
if(block != null) {
TypeWithBody componentTypeDeclaration = relation.componentTypeDeclaration();
List<Method> elements = methodsOfComponentBody(componentTypeDeclaration);
for(ConfigurationClause clause: block.clauses()) {
if(clause instanceof AbstractClause) {
AbstractClause ov = (AbstractClause)clause;
final QualifiedName poppedName = ov.oldFqn().popped();
// Type targetInnerClass = searchInnerClass(outer, relation, poppedName);
Declaration decl = ov.oldDeclaration();
if(decl instanceof Method) {
final Method<?,?,?,?> method = (Method<?, ?, ?, ?>) decl;
if(ov instanceof RenamingClause) {
outer.add(createAlias(relation, method, ((SimpleNameDeclarationWithParametersSignature)ov.newSignature()).name()));
}
}
}
}
}
}
private List<Method> methodsOfComponentBody(TypeWithBody componentTypeDeclaration) {
List<Method> elements;
if(componentTypeDeclaration != null) {
elements = componentTypeDeclaration.body().children(Method.class);
} else {
elements = new ArrayList<Method>();
}
return elements;
}
// private boolean containsMethodWithSameSignature(List<Method> elements, final Method<?, ?, ?, ?> method) throws LookupException {
// boolean overriddenInSubobject = new UnsafePredicate<Method, LookupException>() {
// public boolean eval(Method subobjectMethod) throws LookupException {
// return subobjectMethod.signature().sameAs(method.signature());
// }
// }.exists(elements);
// return overriddenInSubobject;
// }
private Method createAlias(ComponentRelation relation, Method<?,?,?,?> method, String newName) throws LookupException {
NormalMethod<?,?,?> result;
result = innerMethod(method, newName);
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
MethodInvocation invocation = invocation(result, method.name());
// We now bind to the regular method name in case the method has not been overridden
// and there is no 'original' method.
// If it is overridden, then this adds 1 extra delegation, so we should optimize it later on.
// Invocation invocation = invocation(result, original(method.name()));
TypeReference ref = getRelativeClassReference(relation);
Expression target = new JavaMethodInvocation(getterName(relation), null);
invocation.setTarget(target);
substituteTypeParameters(method, result);
addImplementation(method, body, invocation);
return result;
}
/**
* Retrieve an (inner) type that is reached when resolving the given qualified name with the given
* component relation as target in the context of the given type. First an element is resolved in the
* container type that has the same signature as the given component relation. This yields a declaration 'd'.
* Then, the given qualified name is resolved with 'd' as its target.
*
* @param containerType The type in which the actually lookup is done.
* @param relation The component relation that is resolved within the container type.
* @param qualifiedName The qualified name that must be resolved relative to the relation.
* @return
* @throws LookupException
*/
private Type searchInnerClass(Type containerType, ComponentRelation relation, QualifiedName qualifiedName) throws LookupException {
List<Signature> sigs = new ArrayList<Signature>();
sigs.add(relation.signature());
sigs.addAll(qualifiedName.signatures());
CompositeQualifiedName innerName = new CompositeQualifiedName();
CompositeQualifiedName acc = new CompositeQualifiedName();
for(Signature signature: sigs) {
acc.append(signature.clone());
innerName.append(new SimpleNameSignature(innerClassName(containerType, acc)));
}
SimpleReference<Type> tref = new SimpleReference<Type>(innerName, Type.class);
tref.setUniParent(containerType);
Type result = tref.getElement();
return result;
}
/**
*
* @param relationBeingTranslated A component relation from either the original class, or one of its nested components.
* @param outer The outer class being generated.
*/
private Type createInnerClassFor(ComponentRelation relationBeingTranslated, Type outer, Type outerTypeBeingTranslated) throws ChameleonProgrammerException, LookupException {
Type result = innerClassFor(relationBeingTranslated, outer);
List<? extends TypeElement> elements = relationBeingTranslated.componentType().directlyDeclaredElements();
processComponentRelationBody(relationBeingTranslated, outer, outerTypeBeingTranslated, result);
return result;
}
private Type innerClassFor(ComponentRelation relationBeingTranslated, Type outer) throws LookupException {
incorporateImports(relationBeingTranslated);
String className = innerClassName(relationBeingTranslated, outer);
Type result = new RegularJLoType(className);
for(Modifier mod: relationBeingTranslated.modifiers()) {
result.addModifier(mod.clone());
}
TypeReference superReference = superClassReference(relationBeingTranslated);
superReference.setUniParent(relationBeingTranslated);
substituteTypeParameters(superReference);
superReference.setUniParent(null);
result.addInheritanceRelation(new SubtypeRelation(superReference));
List<Method> selectors = selectorsFor(relationBeingTranslated);
for(Method selector:selectors) {
result.add(selector);
}
processInnerClassMethod(relationBeingTranslated, relationBeingTranslated.referencedComponentType(), result);
return result;
}
/**
* Incorporate the imports of the namespace part of the declared type of the component relation to
* the namespace part of the component relation.
* @param relationBeingTranslated
* @throws LookupException
*/
private void incorporateImports(ComponentRelation relationBeingTranslated)
throws LookupException {
incorporateImports(relationBeingTranslated, relationBeingTranslated.farthestAncestor(NamespacePart.class));
}
/**
* Incorporate the imports of the namespace part of the declared type of the component relation to
* the given namespace part.
* @param relationBeingTranslated
* @throws LookupException
*/
private void incorporateImports(ComponentRelation relationBeingTranslated, NamespacePart target)
throws LookupException {
Type baseT = relationBeingTranslated.referencedComponentType().baseType();
NamespacePart originalNsp = baseT.farthestAncestor(NamespacePart.class);
for(Import imp: originalNsp.imports()) {
target.addImport(imp.clone());
}
}
private void processComponentRelationBody(ComponentRelation relation, Type outer, Type outerTypeBeingTranslated, Type result)
throws LookupException {
ComponentType ctype = relation.componentTypeDeclaration();
if(ctype != null) {
if(ctype.ancestors().contains(outerTypeBeingTranslated)) {
ComponentType clonedType = ctype.clone();
clonedType.setUniParent(relation);
replaceOuterAndRootTargets(relation,clonedType);
for(TypeElement typeElement:clonedType.body().elements()) {
if(! (typeElement instanceof ComponentRelation)) {
result.add(typeElement);
}
}
}
}
}
private void processInnerClassMethod(ComponentRelation relation, Type componentType, Type result) throws LookupException {
List<Method> localMethods = componentType.directlyDeclaredMembers(Method.class);
for(Method<?,?,?,?> method: localMethods) {
if(method.is(method.language(ObjectOrientedLanguage.class).CONSTRUCTOR) == Ternary.TRUE) {
NormalMethod<?,?,?> clone = (NormalMethod) method.clone();
clone.setUniParent(method.parent());
for(BasicTypeReference<?> tref: clone.descendants(BasicTypeReference.class)) {
if(tref.getTarget() == null) {
Type element = tref.getElement();
Type base = element.baseType();
if((! (element instanceof ActualType)) && base instanceof RegularType) {
String fqn = base.getFullyQualifiedName();
String qn = Util.getAllButLastPart(fqn);
if(qn != null && (! qn.isEmpty())) {
tref.setTarget(new SimpleReference<TargetDeclaration>(qn, TargetDeclaration.class));
}
}
}
}
clone.setUniParent(null);
String name = result.signature().name();
RegularImplementation impl = (RegularImplementation) clone.implementation();
Block block = new Block();
impl.setBody(block);
// substitute parameters before replace the return type, method name, and the body.
// the types are not known in the component type, and the super class of the component type
// may not have a constructor with the same signature as the current constructor.
substituteTypeParameters(method, clone);
MethodInvocation inv = new SuperConstructorDelegation();
useParametersInInvocation(clone, inv);
block.addStatement(new StatementExpression(inv));
clone.setReturnTypeReference(relation.language(Java.class).createTypeReference(name));
((SimpleNameDeclarationWithParametersHeader)clone.header()).setName(name);
result.add(clone);
}
}
}
private TypeReference superClassReference(ComponentRelation relation) throws LookupException {
TypeReference superReference = relation.componentTypeReference().clone();
if(superReference instanceof ComponentParameterTypeReference) {
superReference = ((ComponentParameterTypeReference) superReference).componentTypeReference();
}
return superReference;
}
private void replaceOuterAndRootTargets(ComponentRelation rel, TypeElement<?> clone) {
List<AbstractTarget> outers = clone.descendants(AbstractTarget.class);
for(AbstractTarget o: outers) {
String name = o.getTargetDeclaration().getName();
SingleAssociation parentLink = o.parentLink();
ThisLiteral e = new ThisLiteral();
e.setTypeReference(new BasicJavaTypeReference(name));
parentLink.getOtherRelation().replace(parentLink, e.parentLink());
}
}
public final static String SHADOW = "_subobject_";
public final static String IMPL = "_implementation";
private Method createOutward(Method<?,?,?,?> method, String newName, String className) throws LookupException {
NormalMethod<?,?,?> result;
if(//(method.is(method.language(ObjectOrientedLanguage.class).DEFINED) == Ternary.TRUE) &&
(method.is(method.language(ObjectOrientedLanguage.class).OVERRIDABLE) == Ternary.TRUE)) {
result = innerMethod(method, method.name());
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
MethodInvocation invocation = invocation(result, newName);
TypeReference ref = method.language(Java.class).createTypeReference(className);
ThisLiteral target = new ThisLiteral(ref);
invocation.setTarget(target);
substituteTypeParameters(method, result);
addImplementation(method, body, invocation);
} else {
result = null;
}
return result;
}
private Method createDispathToOriginal(Method<?,?,?,?> method, ComponentRelation relation) throws LookupException {
NormalMethod<?,?,?> result = null;
result = innerMethod(method, method.name());
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
MethodInvocation invocation = invocation(result, original(method.name()));
substituteTypeParameters(method, result);
addImplementation(method, body, invocation);
return result;
}
private TypeReference getRelativeClassReference(ComponentRelation relation) {
return relation.language(Java.class).createTypeReference(getRelativeClassName(relation));
}
private String getRelativeClassName(ComponentRelation relation) {
return relation.nearestAncestor(Type.class).signature().name();
}
private void substituteTypeParameters(Method<?, ?, ?, ?> methodInTypeWhoseParametersMustBeSubstituted, NormalMethod<?, ?, ?> methodWhereActualTypeParametersMustBeFilledIn) throws LookupException {
methodWhereActualTypeParametersMustBeFilledIn.setUniParent(methodInTypeWhoseParametersMustBeSubstituted);
substituteTypeParameters(methodWhereActualTypeParametersMustBeFilledIn);
methodWhereActualTypeParametersMustBeFilledIn.setUniParent(null);
}
private void addImplementation(Method<?, ?, ?, ?> method, Block body, MethodInvocation invocation) throws LookupException {
if(method.returnType().equals(method.language(Java.class).voidType())) {
body.addStatement(new StatementExpression(invocation));
} else {
body.addStatement(new ReturnStatement(invocation));
}
}
private NormalMethod<?, ?, ?> innerMethod(Method<?, ?, ?, ?> method, String original) throws LookupException {
NormalMethod<?, ?, ?> result;
TypeReference tref = method.returnTypeReference().clone();
result = method.language(Java.class).createNormalMethod(method.header().clone(), tref);
((SimpleNameDeclarationWithParametersHeader)result.header()).setName(original);
ExceptionClause exceptionClause = method.getExceptionClause();
ExceptionClause clone = (exceptionClause != null ? exceptionClause.clone(): null);
result.setExceptionClause(clone);
result.addModifier(new Public());
return result;
}
/**
* Replace all references to type parameters
* @param element
* @throws LookupException
*/
private void substituteTypeParameters(Element<?> element) throws LookupException {
List<TypeReference> crossReferences =
element.descendants(TypeReference.class,
new UnsafePredicate<TypeReference,LookupException>() {
public boolean eval(TypeReference object) throws LookupException {
try {
return object.getDeclarator() instanceof InstantiatedTypeParameter;
} catch (LookupException e) {
e.printStackTrace();
throw e;
}
}
});
for(TypeReference cref: crossReferences) {
SingleAssociation parentLink = cref.parentLink();
Association childLink = parentLink.getOtherRelation();
InstantiatedTypeParameter declarator = (InstantiatedTypeParameter) cref.getDeclarator();
Type type = cref.getElement();
while(type instanceof ActualType) {
type = ((ActualType)type).aliasedType();
}
TypeReference namedTargetExpression = element.language(ObjectOrientedLanguage.class).createTypeReference(type.getFullyQualifiedName());
childLink.replace(parentLink, namedTargetExpression.parentLink());
}
}
private String innerClassName(Type outer, QualifiedName qn) {
StringBuffer result = new StringBuffer();
result.append(outer.signature().name());
result.append(SHADOW);
List<Signature> sigs = qn.signatures();
int size = sigs.size();
for(int i = 0; i < size; i++) {
result.append(((SimpleNameSignature)sigs.get(i)).name());
if(i < size - 1) {
result.append(SHADOW);
}
}
result.append(IMPL);
return result.toString();
}
private String innerClassName(ComponentRelation relation, Type outer) throws LookupException {
return innerClassName(outer, relation.signature());
}
private void replaceSuperCalls(Type type) throws LookupException {
List<SuperTarget> superTargets = type.descendants(SuperTarget.class, new UnsafePredicate<SuperTarget,LookupException>() {
@Override
public boolean eval(SuperTarget superTarget) throws LookupException {
return superTarget.getTargetDeclaration() instanceof ComponentRelation;
}
}
);
for(SuperTarget superTarget: superTargets) {
Element<?> cr = superTarget.parent();
if(cr instanceof CrossReferenceWithArguments) {
Element<?> inv = cr.parent();
if(inv instanceof RegularMethodInvocation) {
RegularMethodInvocation call = (RegularMethodInvocation) inv;
MethodInvocation subObjectSelection = new JavaMethodInvocation(getterName((ComponentRelation) superTarget.getTargetDeclaration()), null);
call.setTarget(subObjectSelection);
call.setName(original(call.name()));
}
}
}
}
private String original(String name) {
return "original__"+name;
}
private MemberVariableDeclarator fieldForComponent(ComponentRelation relation, Type outer) throws LookupException {
if(relation.overriddenMembers().isEmpty()) {
MemberVariableDeclarator result = new MemberVariableDeclarator(componentTypeReference(relation, outer));
result.add(new VariableDeclaration(fieldName(relation)));
return result;
} else {
return null;
}
}
private BasicJavaTypeReference innerClassTypeReference(ComponentRelation relation, Type outer) throws LookupException {
return relation.language(Java.class).createTypeReference(innerClassName(relation, outer));
}
private String getterName(ComponentRelation relation) {
return getterName(relation.signature().name());
}
private String getterName(String componentName) {
return componentName+COMPONENT;
}
public final static String COMPONENT = "__component__lkjkberfuncye__";
private Method getterForComponent(ComponentRelation relation, Type outer) throws LookupException {
if(relation.overriddenMembers().isEmpty()) {
JavaTypeReference returnTypeReference = componentTypeReference(relation, outer);
RegularMethod result = relation.language(Java.class).createNormalMethod(new SimpleNameDeclarationWithParametersHeader(getterName(relation)), returnTypeReference);
result.addModifier(new Public());
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
body.addStatement(new ReturnStatement(new NamedTargetExpression(fieldName(relation), null)));
return result;
} else {
return null;
}
}
private String setterName(ComponentRelation relation) {
return "set"+COMPONENT+"__"+relation.signature().name();
}
private Method setterForComponent(ComponentRelation relation, Type outer) throws LookupException {
if(relation.overriddenMembers().isEmpty()) {
String name = relation.signature().name();
RegularMethod result = relation.language(Java.class).createNormalMethod(new SimpleNameDeclarationWithParametersHeader(setterName(relation)), relation.language(Java.class).createTypeReference("void"));
BasicJavaTypeReference tref = componentTypeReference(relation, outer);
result.header().addFormalParameter(new FormalParameter(name, tref));
result.addModifier(new Public());
Block body = new Block();
result.setImplementation(new RegularImplementation(body));
NamedTargetExpression componentFieldRef = new NamedTargetExpression(fieldName(relation), null);
componentFieldRef.setTarget(new ThisLiteral());
body.addStatement(new StatementExpression(new AssignmentExpression(componentFieldRef, new NamedTargetExpression(name, null))));
return result;
} else {
return null;
}
}
private BasicJavaTypeReference componentTypeReference(ComponentRelation relation, Type outer) throws LookupException {
BasicJavaTypeReference tref = innerClassTypeReference(relation,outer);
copyTypeParametersFromFarthestAncestor(outer,tref);
transformToInterfaceReference(tref);
return tref;
}
private MethodInvocation invocation(Method<?, ?, ?, ?> method, String origin) {
MethodInvocation invocation = new JavaMethodInvocation(origin, null);
// pass parameters.
useParametersInInvocation(method, invocation);
return invocation;
}
private void useParametersInInvocation(Method<?, ?, ?, ?> method, MethodInvocation invocation) {
for(FormalParameter param: method.formalParameters()) {
invocation.addArgument(new NamedTargetExpression(param.signature().name(), null));
}
}
private String fieldName(ComponentRelation relation) {
return relation.signature().name();
}
}
| added exceptions test
| src/subobjectjava/translate/JavaTranslator.java | added exceptions test | <ide><path>rc/subobjectjava/translate/JavaTranslator.java
<ide> }
<ide>
<ide> private void rebindOverriddenMethodsOf(Type result, Type original, Method method) throws LookupException, Error {
<del> if(method.name().equals("isValid")) {
<add> if(method.name().equals("setFrequency")) {
<ide> System.out.println("debug");
<ide> }
<ide> Set<? extends Member> overridden = method.overriddenMembers();
<ide>
<ide> List<Element> trailtoBeReboundInOriginal = filterAncestors(toBeRebound);
<ide> Type rootOfToBeRebound = levelOfDefinition(toBeRebound);
<del> if(! trailtoBeReboundInOriginal.contains(rootOfToBeRebound)) {
<del> System.out.println("debug");
<del> }
<ide> while(! (trailtoBeReboundInOriginal.get(trailtoBeReboundInOriginal.size()-1) == rootOfToBeRebound)) {
<ide> trailtoBeReboundInOriginal.remove(trailtoBeReboundInOriginal.size()-1);
<ide> }
<ide>
<ide> // Type containerOfToBebound = containerOfDefinition(containerOfNewDefinition, original, toBeRebound);
<ide> Type containerOfToBebound = x;
<del> if(x != containerOfToBebound) {
<del> System.out.println("debug");
<del> }
<ide> // containerOfToBebound = x;
<ide> if((containerOfToBebound != null) && ! containerOfToBebound.sameAs(containerOfNewDefinition)) {
<ide> if(newDefinition.name().equals("isValid")) {
<ide> String thisName = containerOfNewDefinition.getFullyQualifiedName();
<ide> Method clone = createOutward(toBeRebound, newDefinition.name(),thisName);
<ide> String newName = containerOfToBebound.getFullyQualifiedName().replace('.', '_')+"_"+clone.name();
<del> if(newName.equals("radio_Radio_Radio_subobject_frequency_implementation_Radio_subobject_frequency_implementation_subobject_value_implementation_Radio_subobject_frequency_implementation_subobject_value_implementation_subobject_frequency_implementation_Radio_subobject_frequency_implementation_subobject_value_implementation_subobject_frequency_implementation_subobject_value_implementation_getValue")) {
<del> System.out.println("debug");
<del> }
<ide> //FIXME this is tricky.
<ide> clone.setUniParent(toBeRebound);
<ide> Implementation<Implementation> impl = clone.implementation();
<ide> } catch(LookupException exc) {
<ide> // We add the imports to the original. They are copied later on to 'container'.
<ide> ComponentRelation relation = ((ComponentType)current).nearestAncestor(ComponentRelation.class);
<del> result = innerClassFor(relation, container);
<add> result = emptyInnerClassFor(relation, container);
<ide> NamespacePart namespacePart = container.farthestAncestor(NamespacePart.class);
<ide> incorporateImports(relation, namespacePart);
<ide> // Since we are adding inner classes that were not written in the current namespacepart, their type
<ide> result= tref.getElement();
<ide> } catch(LookupException exc) {
<ide> // We add the imports to the original. They are copied later on to 'container'.
<del> result = innerClassFor(relationBeingTranslated, container);
<add> result = emptyInnerClassFor(relationBeingTranslated, container);
<ide> NamespacePart namespacePart = container.farthestAncestor(NamespacePart.class);
<ide> incorporateImports(relationBeingTranslated, namespacePart);
<ide> // Since we are adding inner classes that were not written in the current namespacepart, their type
<ide> // If it is overridden, then this adds 1 extra delegation, so we should optimize it later on.
<ide> // Invocation invocation = invocation(result, original(method.name()));
<ide>
<del> TypeReference ref = getRelativeClassReference(relation);
<ide> Expression target = new JavaMethodInvocation(getterName(relation), null);
<ide> invocation.setTarget(target);
<ide> substituteTypeParameters(method, result);
<ide> }
<ide>
<ide>
<del> /**
<del> * Retrieve an (inner) type that is reached when resolving the given qualified name with the given
<del> * component relation as target in the context of the given type. First an element is resolved in the
<del> * container type that has the same signature as the given component relation. This yields a declaration 'd'.
<del> * Then, the given qualified name is resolved with 'd' as its target.
<del> *
<del> * @param containerType The type in which the actually lookup is done.
<del> * @param relation The component relation that is resolved within the container type.
<del> * @param qualifiedName The qualified name that must be resolved relative to the relation.
<del> * @return
<del> * @throws LookupException
<del> */
<del> private Type searchInnerClass(Type containerType, ComponentRelation relation, QualifiedName qualifiedName) throws LookupException {
<del> List<Signature> sigs = new ArrayList<Signature>();
<del> sigs.add(relation.signature());
<del> sigs.addAll(qualifiedName.signatures());
<del> CompositeQualifiedName innerName = new CompositeQualifiedName();
<del> CompositeQualifiedName acc = new CompositeQualifiedName();
<del> for(Signature signature: sigs) {
<del> acc.append(signature.clone());
<del> innerName.append(new SimpleNameSignature(innerClassName(containerType, acc)));
<del> }
<del> SimpleReference<Type> tref = new SimpleReference<Type>(innerName, Type.class);
<del> tref.setUniParent(containerType);
<del> Type result = tref.getElement();
<del> return result;
<del> }
<del>
<ide> /**
<ide> *
<ide> * @param relationBeingTranslated A component relation from either the original class, or one of its nested components.
<ide> * @param outer The outer class being generated.
<ide> */
<ide> private Type createInnerClassFor(ComponentRelation relationBeingTranslated, Type outer, Type outerTypeBeingTranslated) throws ChameleonProgrammerException, LookupException {
<del> Type result = innerClassFor(relationBeingTranslated, outer);
<add> Type result = emptyInnerClassFor(relationBeingTranslated, outer);
<ide> List<? extends TypeElement> elements = relationBeingTranslated.componentType().directlyDeclaredElements();
<ide> processComponentRelationBody(relationBeingTranslated, outer, outerTypeBeingTranslated, result);
<ide> return result;
<ide> }
<ide>
<del> private Type innerClassFor(ComponentRelation relationBeingTranslated, Type outer) throws LookupException {
<add> private Type emptyInnerClassFor(ComponentRelation relationBeingTranslated, Type outer) throws LookupException {
<ide> incorporateImports(relationBeingTranslated);
<ide> String className = innerClassName(relationBeingTranslated, outer);
<ide> Type result = new RegularJLoType(className); |
|
Java | bsd-3-clause | 4207e6f5199471ac1f9c797d645a8c5aadafe04c | 0 | subgraph/Orchid,mohsenuss91/Orchid | package com.subgraph.orchid.circuits;
import java.math.BigInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.subgraph.orchid.Cell;
import com.subgraph.orchid.CircuitNode;
import com.subgraph.orchid.Connection;
import com.subgraph.orchid.ConnectionCache;
import com.subgraph.orchid.ConnectionFailedException;
import com.subgraph.orchid.ConnectionHandshakeException;
import com.subgraph.orchid.ConnectionTimeoutException;
import com.subgraph.orchid.RelayCell;
import com.subgraph.orchid.Router;
import com.subgraph.orchid.Tor;
import com.subgraph.orchid.TorException;
import com.subgraph.orchid.circuits.cells.CellImpl;
import com.subgraph.orchid.circuits.cells.RelayCellImpl;
import com.subgraph.orchid.circuits.path.PathSelectionFailedException;
import com.subgraph.orchid.crypto.TorKeyAgreement;
import com.subgraph.orchid.crypto.TorMessageDigest;
import com.subgraph.orchid.data.HexDigest;
public class CircuitBuildTask implements Runnable {
private final static Logger logger = Logger.getLogger(CircuitBuildTask.class.getName());
private final CircuitCreationRequest creationRequest;
private final ConnectionCache connectionCache;
private final TorInitializationTracker initializationTracker;
private final CircuitBase circuit;
private Connection connection = null;
CircuitBuildTask(CircuitCreationRequest request, ConnectionCache connectionCache, TorInitializationTracker initializationTracker) {
this.creationRequest = request;
this.connectionCache = connectionCache;
this.initializationTracker = initializationTracker;
this.circuit = request.getCircuit();
}
public void run() {
Router firstRouter = null;
try {
circuit.notifyCircuitBuildStart();
creationRequest.choosePath();
circuit.notifyCircuitPathChosen(creationRequest.getPath());
if(logger.isLoggable(Level.FINE)) {
logger.fine("Opening a new circuit to "+ pathToString(creationRequest));
}
firstRouter = creationRequest.getPathElement(0);
openEntryNodeConnection(firstRouter);
buildCircuit(firstRouter);
circuit.notifyCircuitBuildCompleted();
} catch (ConnectionTimeoutException e) {
connectionFailed("Timeout connecting to "+ firstRouter);
} catch (ConnectionFailedException e) {
connectionFailed("Connection failed to "+ firstRouter + " : " + e.getMessage());
} catch (ConnectionHandshakeException e) {
connectionFailed("Handshake error connecting to "+ firstRouter + " : " + e.getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
circuitBuildFailed("Circuit building thread interrupted");
} catch(PathSelectionFailedException e) {
circuitBuildFailed(e.getMessage());
} catch (TorException e) {
circuitBuildFailed(e.getMessage());
} catch(Exception e) {
circuitBuildFailed("Unexpected exception: "+ e);
logger.log(Level.WARNING, "Unexpected exception while building circuit: "+ e, e);
}
}
private String pathToString(CircuitCreationRequest ccr) {
final StringBuilder sb = new StringBuilder();
sb.append("[");
for(Router r: ccr.getPath()) {
if(sb.length() > 1)
sb.append(",");
sb.append(r.getNickname());
}
sb.append("]");
return sb.toString();
}
private void connectionFailed(String message) {
creationRequest.connectionFailed(message);
circuit.notifyCircuitBuildFailed();
}
private void circuitBuildFailed(String message) {
creationRequest.circuitBuildFailed(message);
circuit.notifyCircuitBuildFailed();
if(connection != null) {
connection.removeCircuit(circuit);
}
}
private void openEntryNodeConnection(Router firstRouter) throws ConnectionTimeoutException, ConnectionFailedException, ConnectionHandshakeException, InterruptedException {
connection = connectionCache.getConnectionTo(firstRouter, creationRequest.isDirectoryCircuit());
circuit.bindToConnection(connection);
creationRequest.connectionCompleted(connection);
}
private void buildCircuit(Router firstRouter) throws TorException {
final CircuitNode firstNode = createFastTo(firstRouter);
creationRequest.nodeAdded(firstNode);
for(int i = 1; i < creationRequest.getPathLength(); i++) {
final CircuitNode extendedNode = extendTo(creationRequest.getPathElement(i));
creationRequest.nodeAdded(extendedNode);
}
creationRequest.circuitBuildCompleted(circuit);
notifyDone();
}
private CircuitNode createFastTo(Router targetRouter) {
notifyInitialization();
final CircuitNodeImpl newNode = new CircuitNodeImpl(targetRouter, null);
sendCreateFastCell(newNode);
receiveAndProcessCreateFastResponse(newNode);
return newNode;
}
private void notifyInitialization() {
if(initializationTracker != null) {
final int event = creationRequest.isDirectoryCircuit() ?
Tor.BOOTSTRAP_STATUS_ONEHOP_CREATE : Tor.BOOTSTRAP_STATUS_CIRCUIT_CREATE;
initializationTracker.notifyEvent(event);
}
}
private void notifyDone() {
if(initializationTracker != null && !creationRequest.isDirectoryCircuit()) {
initializationTracker.notifyEvent(Tor.BOOTSTRAP_STATUS_DONE);
}
}
private void sendCreateFastCell(CircuitNodeImpl node) {
final Cell cell = CellImpl.createCell(circuit.getCircuitId(), Cell.CREATE_FAST);
cell.putByteArray(node.getCreateFastPublicValue());
circuit.sendCell(cell);
}
private void receiveAndProcessCreateFastResponse(CircuitNodeImpl node) {
final Cell cell = circuit.receiveControlCellResponse();
if(cell == null) {
throw new TorException("Timeout building circuit");
}
processCreatedFastCell(node, cell);
circuit.appendNode(node);
}
private void processCreatedFastCell(CircuitNodeImpl node, Cell cell) {
final byte[] cellBytes = cell.getCellBytes();
final byte[] yValue = new byte[TorMessageDigest.TOR_DIGEST_SIZE];
final byte[] hash = new byte[TorMessageDigest.TOR_DIGEST_SIZE];
int offset = Cell.CELL_HEADER_LEN;
System.arraycopy(cellBytes, offset, yValue, 0, TorMessageDigest.TOR_DIGEST_SIZE);
offset += TorMessageDigest.TOR_DIGEST_SIZE;
System.arraycopy(cellBytes, offset, hash, 0, TorMessageDigest.TOR_DIGEST_SIZE);
node.setCreatedFastValue(yValue, HexDigest.createFromDigestBytes(hash));
}
CircuitNode extendTo(Router targetRouter) {
if(circuit.getCircuitLength() == 0)
throw new TorException("Cannot EXTEND an empty circuit");
final CircuitNodeImpl newNode = createExtendNode(targetRouter);
final RelayCell cell = createRelayExtendCell(newNode);
circuit.sendRelayCellToFinalNode(cell);
receiveExtendResponse(newNode);
circuit.appendNode(newNode);
return newNode;
}
private CircuitNodeImpl createExtendNode(Router router) {
return new CircuitNodeImpl(router, circuit.getFinalCircuitNode());
}
private RelayCell createRelayExtendCell(CircuitNodeImpl newNode) {
final RelayCell cell = new RelayCellImpl(circuit.getFinalCircuitNode(), circuit.getCircuitId(), 0, RelayCell.RELAY_EXTEND, true);
final Router router = newNode.getRouter();
cell.putByteArray(router.getAddress().getAddressDataBytes());
cell.putShort(router.getOnionPort());
cell.putByteArray( newNode.createOnionSkin());
cell.putByteArray(router.getIdentityKey().getFingerprint().getRawBytes());
return cell;
}
private void receiveExtendResponse(CircuitNodeImpl newNode) {
final RelayCell cell = circuit.receiveRelayCell();
if(cell == null)
throw new TorException("Timeout building circuit");
final int command = cell.getRelayCommand();
if(command == RelayCell.RELAY_TRUNCATED) {
final int code = cell.getByte() & 0xFF;
final String msg = CellImpl.errorToDescription(code);
final String source = nodeToName(cell.getCircuitNode());
final String extendTarget = nodeToName(newNode);
if(code == Cell.ERROR_PROTOCOL) {
logProtocolViolation(source, extendTarget, newNode.getRouter());
}
throw new TorException("Error from ("+ source + ") while extending to ("+ extendTarget +"): "+ msg);
} else if (command != RelayCell.RELAY_EXTENDED) {
throw new TorException("Unexpected response to RELAY_EXTEND. Command = "+ command);
}
byte[] dhPublic = new byte[TorKeyAgreement.DH_LEN];
cell.getByteArray(dhPublic);
byte[] keyHash = new byte[TorMessageDigest.TOR_DIGEST_SIZE];
cell.getByteArray(keyHash);
HexDigest packetDigest = HexDigest.createFromDigestBytes(keyHash);
BigInteger peerPublic = new BigInteger(1, dhPublic);
newNode.setSharedSecret(peerPublic, packetDigest);
}
private void logProtocolViolation(String sourceName, String targetName, Router targetRouter) {
final String version = (targetRouter == null) ? "(none)" : targetRouter.getVersion();
logger.warning("Protocol error extending circuit from ("+ sourceName +") to ("+ targetName +") [version: "+ version +"]");
}
private String nodeToName(CircuitNode node) {
if(node == null || node.getRouter() == null) {
return "(null)";
}
final Router router = node.getRouter();
return router.getNickname();
}
}
| src/com/subgraph/orchid/circuits/CircuitBuildTask.java | package com.subgraph.orchid.circuits;
import java.math.BigInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.subgraph.orchid.Cell;
import com.subgraph.orchid.CircuitNode;
import com.subgraph.orchid.Connection;
import com.subgraph.orchid.ConnectionCache;
import com.subgraph.orchid.ConnectionFailedException;
import com.subgraph.orchid.ConnectionHandshakeException;
import com.subgraph.orchid.ConnectionTimeoutException;
import com.subgraph.orchid.RelayCell;
import com.subgraph.orchid.Router;
import com.subgraph.orchid.Tor;
import com.subgraph.orchid.TorException;
import com.subgraph.orchid.circuits.cells.CellImpl;
import com.subgraph.orchid.circuits.cells.RelayCellImpl;
import com.subgraph.orchid.circuits.path.PathSelectionFailedException;
import com.subgraph.orchid.crypto.TorKeyAgreement;
import com.subgraph.orchid.crypto.TorMessageDigest;
import com.subgraph.orchid.data.HexDigest;
public class CircuitBuildTask implements Runnable {
private final static Logger logger = Logger.getLogger(CircuitBuildTask.class.getName());
private final CircuitCreationRequest creationRequest;
private final ConnectionCache connectionCache;
private final TorInitializationTracker initializationTracker;
private final CircuitBase circuit;
private Connection connection = null;
CircuitBuildTask(CircuitCreationRequest request, ConnectionCache connectionCache, TorInitializationTracker initializationTracker) {
this.creationRequest = request;
this.connectionCache = connectionCache;
this.initializationTracker = initializationTracker;
this.circuit = request.getCircuit();
}
public void run() {
Router firstRouter = null;
try {
circuit.notifyCircuitBuildStart();
creationRequest.choosePath();
circuit.notifyCircuitPathChosen(creationRequest.getPath());
if(logger.isLoggable(Level.FINE)) {
logger.fine("Opening a new circuit to "+ pathToString(creationRequest));
}
firstRouter = creationRequest.getPathElement(0);
openEntryNodeConnection(firstRouter);
buildCircuit(firstRouter);
circuit.notifyCircuitBuildCompleted();
} catch (ConnectionTimeoutException e) {
connectionFailed("Timeout connecting to "+ firstRouter);
} catch (ConnectionFailedException e) {
connectionFailed("Connection failed to "+ firstRouter + " : " + e.getMessage());
} catch (ConnectionHandshakeException e) {
connectionFailed("Handshake error connecting to "+ firstRouter + " : " + e.getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
circuitBuildFailed("Circuit building thread interrupted");
} catch(PathSelectionFailedException e) {
circuitBuildFailed(e.getMessage());
} catch (TorException e) {
circuitBuildFailed(e.getMessage());
} catch(Exception e) {
circuitBuildFailed("Unexpected exception: "+ e);
logger.log(Level.WARNING, "Unexpected exception while building circuit: "+ e, e);
}
}
private String pathToString(CircuitCreationRequest ccr) {
final StringBuilder sb = new StringBuilder();
sb.append("[");
for(Router r: ccr.getPath()) {
if(sb.length() > 1)
sb.append(",");
sb.append(r.getNickname());
}
sb.append("]");
return sb.toString();
}
private void connectionFailed(String message) {
creationRequest.connectionFailed(message);
circuit.notifyCircuitBuildFailed();
}
private void circuitBuildFailed(String message) {
creationRequest.circuitBuildFailed(message);
circuit.notifyCircuitBuildFailed();
if(connection != null) {
connection.removeCircuit(circuit);
}
}
private void openEntryNodeConnection(Router firstRouter) throws ConnectionTimeoutException, ConnectionFailedException, ConnectionHandshakeException, InterruptedException {
connection = connectionCache.getConnectionTo(firstRouter, creationRequest.isDirectoryCircuit());
circuit.bindToConnection(connection);
creationRequest.connectionCompleted(connection);
}
private void buildCircuit(Router firstRouter) throws TorException {
final CircuitNode firstNode = createFastTo(firstRouter);
creationRequest.nodeAdded(firstNode);
for(int i = 1; i < creationRequest.getPathLength(); i++) {
final CircuitNode extendedNode = extendTo(creationRequest.getPathElement(i));
creationRequest.nodeAdded(extendedNode);
}
creationRequest.circuitBuildCompleted(circuit);
notifyDone();
}
private CircuitNode createFastTo(Router targetRouter) {
notifyInitialization();
final CircuitNodeImpl newNode = new CircuitNodeImpl(targetRouter, null);
sendCreateFastCell(newNode);
receiveAndProcessCreateFastResponse(newNode);
return newNode;
}
private void notifyInitialization() {
if(initializationTracker != null) {
final int event = creationRequest.isDirectoryCircuit() ?
Tor.BOOTSTRAP_STATUS_ONEHOP_CREATE : Tor.BOOTSTRAP_STATUS_CIRCUIT_CREATE;
initializationTracker.notifyEvent(event);
}
}
private void notifyDone() {
if(initializationTracker != null && !creationRequest.isDirectoryCircuit()) {
initializationTracker.notifyEvent(Tor.BOOTSTRAP_STATUS_DONE);
}
}
private void sendCreateFastCell(CircuitNodeImpl node) {
final Cell cell = CellImpl.createCell(circuit.getCircuitId(), Cell.CREATE_FAST);
cell.putByteArray(node.getCreateFastPublicValue());
circuit.sendCell(cell);
}
private void receiveAndProcessCreateFastResponse(CircuitNodeImpl node) {
final Cell cell = circuit.receiveControlCellResponse();
if(cell == null) {
throw new TorException("Timeout building circuit");
}
processCreatedFastCell(node, cell);
circuit.appendNode(node);
}
private void processCreatedFastCell(CircuitNodeImpl node, Cell cell) {
final byte[] cellBytes = cell.getCellBytes();
final byte[] yValue = new byte[TorMessageDigest.TOR_DIGEST_SIZE];
final byte[] hash = new byte[TorMessageDigest.TOR_DIGEST_SIZE];
int offset = Cell.CELL_HEADER_LEN;
System.arraycopy(cellBytes, offset, yValue, 0, TorMessageDigest.TOR_DIGEST_SIZE);
offset += TorMessageDigest.TOR_DIGEST_SIZE;
System.arraycopy(cellBytes, offset, hash, 0, TorMessageDigest.TOR_DIGEST_SIZE);
node.setCreatedFastValue(yValue, HexDigest.createFromDigestBytes(hash));
}
CircuitNode extendTo(Router targetRouter) {
if(circuit.getCircuitLength() == 0)
throw new TorException("Cannot EXTEND an empty circuit");
final CircuitNodeImpl newNode = createExtendNode(targetRouter);
final RelayCell cell = createRelayExtendCell(newNode);
circuit.sendRelayCellToFinalNode(cell);
receiveExtendResponse(newNode);
circuit.appendNode(newNode);
return newNode;
}
private CircuitNodeImpl createExtendNode(Router router) {
return new CircuitNodeImpl(router, circuit.getFinalCircuitNode());
}
private RelayCell createRelayExtendCell(CircuitNodeImpl newNode) {
final RelayCell cell = new RelayCellImpl(circuit.getFinalCircuitNode(), circuit.getCircuitId(), 0, RelayCell.RELAY_EXTEND, true);
final Router router = newNode.getRouter();
cell.putByteArray(router.getAddress().getAddressDataBytes());
cell.putShort(router.getOnionPort());
cell.putByteArray( newNode.createOnionSkin());
cell.putByteArray(router.getIdentityKey().getFingerprint().getRawBytes());
return cell;
}
private void receiveExtendResponse(CircuitNodeImpl newNode) {
final RelayCell cell = circuit.receiveRelayCell();
if(cell == null)
throw new TorException("Timeout building circuit");
final int command = cell.getRelayCommand();
if(command == RelayCell.RELAY_TRUNCATED) {
final int code = cell.getByte() & 0xFF;
final String msg = CellImpl.errorToDescription(code);
final String source = nodeToName(cell.getCircuitNode());
final String extendTarget = nodeToName(newNode);
throw new TorException("Error from ("+ source + ") while extending to ("+ extendTarget +"): "+ msg);
} else if (command != RelayCell.RELAY_EXTENDED) {
throw new TorException("Unexpected response to RELAY_EXTEND. Command = "+ command);
}
byte[] dhPublic = new byte[TorKeyAgreement.DH_LEN];
cell.getByteArray(dhPublic);
byte[] keyHash = new byte[TorMessageDigest.TOR_DIGEST_SIZE];
cell.getByteArray(keyHash);
HexDigest packetDigest = HexDigest.createFromDigestBytes(keyHash);
BigInteger peerPublic = new BigInteger(1, dhPublic);
newNode.setSharedSecret(peerPublic, packetDigest);
}
private String nodeToName(CircuitNode node) {
if(node == null || node.getRouter() == null) {
return "(null)";
}
final Router router = node.getRouter();
return router.getNickname();
}
}
| Log a warning if Tor network returns protocol violation error during circuit construction
| src/com/subgraph/orchid/circuits/CircuitBuildTask.java | Log a warning if Tor network returns protocol violation error during circuit construction | <ide><path>rc/com/subgraph/orchid/circuits/CircuitBuildTask.java
<ide> final String msg = CellImpl.errorToDescription(code);
<ide> final String source = nodeToName(cell.getCircuitNode());
<ide> final String extendTarget = nodeToName(newNode);
<add> if(code == Cell.ERROR_PROTOCOL) {
<add> logProtocolViolation(source, extendTarget, newNode.getRouter());
<add> }
<ide> throw new TorException("Error from ("+ source + ") while extending to ("+ extendTarget +"): "+ msg);
<ide> } else if (command != RelayCell.RELAY_EXTENDED) {
<ide> throw new TorException("Unexpected response to RELAY_EXTEND. Command = "+ command);
<ide> newNode.setSharedSecret(peerPublic, packetDigest);
<ide> }
<ide>
<add> private void logProtocolViolation(String sourceName, String targetName, Router targetRouter) {
<add> final String version = (targetRouter == null) ? "(none)" : targetRouter.getVersion();
<add> logger.warning("Protocol error extending circuit from ("+ sourceName +") to ("+ targetName +") [version: "+ version +"]");
<add> }
<add>
<ide> private String nodeToName(CircuitNode node) {
<ide> if(node == null || node.getRouter() == null) {
<ide> return "(null)"; |
|
Java | apache-2.0 | 69fab1bf1711099ec6ffd4182b6ecba4d0791375 | 0 | danielferber/git-to-clearcase | package br.com.danielferber.gittocc2.config.git;
import java.io.File;
import java.util.Properties;
import br.com.danielferber.gittocc2.config.ConfigProperties;
/**
*
* @author Daniel Felix Ferber
*/
public class GitConfigProperties implements GitConfig {
private final ConfigProperties properties;
private final String prefix;
public GitConfigProperties(final GitConfigSource other) {
this(other, "");
}
public GitConfigProperties(final GitConfigSource other, final String prefix) {
this.properties = new ConfigProperties();
this.prefix = prefix;
this.setGitExec(other.getGitExec());
this.setRepositoryDir(other.getRepositoryDir());
this.setCleanLocalGitRepository(other.getCleanLocalGitRepository());
this.setFastForwardLocalGitRepository(other.getFastForwardLocalGitRepository());
this.setFetchRemoteGitRepository(other.getFetchRemoteGitRepository());
this.setResetLocalGitRepository(other.getResetLocalGitRepository());
this.setApplyDefaultGitConfig(other.getApplyDefaultGitConfig());
}
public GitConfigProperties(final Properties properties) {
this(properties, "");
}
public GitConfigProperties(final Properties properties, final String prefix) {
this.properties = new ConfigProperties(properties);
this.prefix = prefix;
}
@Override
public Boolean getCleanLocalGitRepository() {
return properties.getBoolean(prefix + "cleanLocalGitRepository");
}
@Override
public Boolean getFastForwardLocalGitRepository() {
return properties.getBoolean(prefix + "fastForwardLocalGitRepository");
}
@Override
public Boolean getFetchRemoteGitRepository() {
return properties.getBoolean(prefix + "fetchRemoteGitRepository");
}
@Override
public File getGitExec() {
return properties.getFile(prefix + "exec");
}
@Override
public File getRepositoryDir() {
return properties.getFile(prefix + "repository.dir");
}
@Override
public Boolean getResetLocalGitRepository() {
return properties.getBoolean(prefix + "resetLocalGitRepository");
}
@Override
public Boolean getApplyDefaultGitConfig() {
return properties.getBoolean(prefix + "applyDefaultGitConfig");
}
@Override
public GitConfig setCleanLocalGitRepository(final Boolean value) {
properties.setBoolean(prefix + "cleanLocalGitRepository", value);
return this;
}
@Override
public GitConfig setFastForwardLocalGitRepository(final Boolean value) {
properties.setBoolean(prefix + "fastForwardLocalGitRepository", value);
return this;
}
@Override
public GitConfig setFetchRemoteGitRepository(final Boolean value) {
properties.setBoolean(prefix + "fetchRemoteGitRepository", value);
return this;
}
@Override
public GitConfig setGitExec(final File file) {
properties.setFile(prefix + "exec", file);
return this;
}
@Override
public GitConfig setRepositoryDir(final File dir) {
properties.setFile(prefix + "repository.dir", dir);
return this;
}
@Override
public GitConfig setResetLocalGitRepository(final Boolean value) {
properties.setBoolean(prefix + "resetLocalGitRepository", value);
return this;
}
@Override
public GitConfig setApplyDefaultGitConfig(final Boolean value) {
properties.setBoolean(prefix + "applyDefaultGitConfig", value);
return this;
}
@Override
public String toString() {
return properties.toString();
}
}
| GitToClearCase/src/br/com/danielferber/gittocc2/config/git/GitConfigProperties.java | package br.com.danielferber.gittocc2.config.git;
import java.io.File;
import java.util.Properties;
import br.com.danielferber.gittocc2.config.ConfigProperties;
/**
*
* @author Daniel Felix Ferber
*/
public class GitConfigProperties implements GitConfig {
private final ConfigProperties properties;
private final String prefix;
public GitConfigProperties(final GitConfigSource other) {
this(other, "");
}
public GitConfigProperties(final GitConfigSource other, final String prefix) {
this.properties = new ConfigProperties();
this.prefix = prefix;
this.setGitExec(other.getGitExec());
this.setRepositoryDir(other.getRepositoryDir());
this.setCleanLocalGitRepository(other.getCleanLocalGitRepository());
this.setFastForwardLocalGitRepository(other.getFastForwardLocalGitRepository());
this.setFetchRemoteGitRepository(other.getFetchRemoteGitRepository());
this.setResetLocalGitRepository(other.getResetLocalGitRepository());
this.setApplyDefaultGitConfig(other.getApplyDefaultGitConfig());
}
public GitConfigProperties(final Properties properties) {
this(properties, "");
}
public GitConfigProperties(final Properties properties, final String prefix) {
this.properties = new ConfigProperties(properties);
this.prefix = prefix;
}
@Override
public Boolean getCleanLocalGitRepository() {
return properties.getBoolean(prefix + "git.cleanLocalGitRepository");
}
@Override
public Boolean getFastForwardLocalGitRepository() {
return properties.getBoolean(prefix + "git.fastForwardLocalGitRepository");
}
@Override
public Boolean getFetchRemoteGitRepository() {
return properties.getBoolean(prefix + "git.fetchRemoteGitRepository");
}
@Override
public File getGitExec() {
return properties.getFile(prefix + "git.exec");
}
@Override
public File getRepositoryDir() {
return properties.getFile(prefix + "repository.dir");
}
@Override
public Boolean getResetLocalGitRepository() {
return properties.getBoolean(prefix + "git.resetLocalGitRepository");
}
@Override
public Boolean getApplyDefaultGitConfig() {
return properties.getBoolean(prefix + "git.applyDefaultGitConfig");
}
@Override
public GitConfig setCleanLocalGitRepository(final Boolean value) {
properties.setBoolean(prefix + "git.cleanLocalGitRepository", value);
return this;
}
@Override
public GitConfig setFastForwardLocalGitRepository(final Boolean value) {
properties.setBoolean(prefix + "git.fastForwardLocalGitRepository", value);
return this;
}
@Override
public GitConfig setFetchRemoteGitRepository(final Boolean value) {
properties.setBoolean(prefix + "git.fetchRemoteGitRepository", value);
return this;
}
@Override
public GitConfig setGitExec(final File file) {
properties.setFile(prefix + "git.exec", file);
return this;
}
@Override
public GitConfig setRepositoryDir(final File dir) {
properties.setFile(prefix + "repository.dir", dir);
return this;
}
@Override
public GitConfig setResetLocalGitRepository(final Boolean value) {
properties.setBoolean(prefix + "git.resetLocalGitRepository", value);
return this;
}
@Override
public GitConfig setApplyDefaultGitConfig(final Boolean value) {
properties.setBoolean(prefix + "git.applyDefaultGitConfig", value);
return this;
}
@Override
public String toString() {
return properties.toString();
}
}
| [dev] No prefix for git properties configuration. | GitToClearCase/src/br/com/danielferber/gittocc2/config/git/GitConfigProperties.java | [dev] No prefix for git properties configuration. | <ide><path>itToClearCase/src/br/com/danielferber/gittocc2/config/git/GitConfigProperties.java
<ide>
<ide> @Override
<ide> public Boolean getCleanLocalGitRepository() {
<del> return properties.getBoolean(prefix + "git.cleanLocalGitRepository");
<add> return properties.getBoolean(prefix + "cleanLocalGitRepository");
<ide> }
<ide>
<ide> @Override
<ide> public Boolean getFastForwardLocalGitRepository() {
<del> return properties.getBoolean(prefix + "git.fastForwardLocalGitRepository");
<add> return properties.getBoolean(prefix + "fastForwardLocalGitRepository");
<ide> }
<ide>
<ide> @Override
<ide> public Boolean getFetchRemoteGitRepository() {
<del> return properties.getBoolean(prefix + "git.fetchRemoteGitRepository");
<add> return properties.getBoolean(prefix + "fetchRemoteGitRepository");
<ide> }
<ide>
<ide> @Override
<ide> public File getGitExec() {
<del> return properties.getFile(prefix + "git.exec");
<add> return properties.getFile(prefix + "exec");
<ide> }
<ide>
<ide> @Override
<ide>
<ide> @Override
<ide> public Boolean getResetLocalGitRepository() {
<del> return properties.getBoolean(prefix + "git.resetLocalGitRepository");
<add> return properties.getBoolean(prefix + "resetLocalGitRepository");
<ide> }
<ide>
<ide> @Override
<ide> public Boolean getApplyDefaultGitConfig() {
<del> return properties.getBoolean(prefix + "git.applyDefaultGitConfig");
<add> return properties.getBoolean(prefix + "applyDefaultGitConfig");
<ide> }
<ide>
<ide> @Override
<ide> public GitConfig setCleanLocalGitRepository(final Boolean value) {
<del> properties.setBoolean(prefix + "git.cleanLocalGitRepository", value);
<add> properties.setBoolean(prefix + "cleanLocalGitRepository", value);
<ide> return this;
<ide> }
<ide>
<ide> @Override
<ide> public GitConfig setFastForwardLocalGitRepository(final Boolean value) {
<del> properties.setBoolean(prefix + "git.fastForwardLocalGitRepository", value);
<add> properties.setBoolean(prefix + "fastForwardLocalGitRepository", value);
<ide> return this;
<ide> }
<ide>
<ide> @Override
<ide> public GitConfig setFetchRemoteGitRepository(final Boolean value) {
<del> properties.setBoolean(prefix + "git.fetchRemoteGitRepository", value);
<add> properties.setBoolean(prefix + "fetchRemoteGitRepository", value);
<ide> return this;
<ide> }
<ide>
<ide> @Override
<ide> public GitConfig setGitExec(final File file) {
<del> properties.setFile(prefix + "git.exec", file);
<add> properties.setFile(prefix + "exec", file);
<ide> return this;
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public GitConfig setResetLocalGitRepository(final Boolean value) {
<del> properties.setBoolean(prefix + "git.resetLocalGitRepository", value);
<add> properties.setBoolean(prefix + "resetLocalGitRepository", value);
<ide> return this;
<ide> }
<ide>
<ide> @Override
<ide> public GitConfig setApplyDefaultGitConfig(final Boolean value) {
<del> properties.setBoolean(prefix + "git.applyDefaultGitConfig", value);
<add> properties.setBoolean(prefix + "applyDefaultGitConfig", value);
<ide> return this;
<ide> }
<ide> |
|
Java | apache-2.0 | 007d88c855bd70cf913de6c208fc484c32e5c635 | 0 | Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces | /*******************************************************************************
*
* Copyright (c) 2012 GigaSpaces Technologies Ltd. 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 org.openspaces.grid.gsm.machines;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openspaces.admin.Admin;
import org.openspaces.admin.gsa.GSAReservationId;
import org.openspaces.admin.gsa.GridServiceAgent;
import org.openspaces.admin.gsa.GridServiceAgents;
import org.openspaces.admin.gsc.GridServiceContainer;
import org.openspaces.admin.internal.gsa.InternalGridServiceAgent;
import org.openspaces.admin.pu.ProcessingUnit;
import org.openspaces.admin.pu.ProcessingUnitInstance;
import org.openspaces.admin.zone.config.ExactZonesConfig;
import org.openspaces.admin.zone.config.ExactZonesConfigurer;
import org.openspaces.admin.zone.config.ZonesConfig;
import org.openspaces.grid.gsm.LogPerProcessingUnit;
import org.openspaces.grid.gsm.SingleThreadedPollingLog;
import org.openspaces.grid.gsm.capacity.CapacityRequirement;
import org.openspaces.grid.gsm.capacity.CapacityRequirements;
import org.openspaces.grid.gsm.capacity.CapacityRequirementsPerAgent;
import org.openspaces.grid.gsm.capacity.MemoryCapacityRequirement;
import org.openspaces.grid.gsm.capacity.NumberOfMachinesCapacityRequirement;
import org.openspaces.grid.gsm.containers.ContainersSlaUtils;
import org.openspaces.grid.gsm.machines.MachinesSlaEnforcementState.RecoveryState;
import org.openspaces.grid.gsm.machines.MachinesSlaEnforcementState.StateKey;
import org.openspaces.grid.gsm.machines.exceptions.CannotDetermineIfNeedToStartMoreMachinesException;
import org.openspaces.grid.gsm.machines.exceptions.DelayingScaleInUntilAllMachinesHaveStartedException;
import org.openspaces.grid.gsm.machines.exceptions.FailedToDiscoverMachinesException;
import org.openspaces.grid.gsm.machines.exceptions.FailedToStartNewGridServiceAgentException;
import org.openspaces.grid.gsm.machines.exceptions.FailedToStartNewMachineException;
import org.openspaces.grid.gsm.machines.exceptions.FailedToStopGridServiceAgentException;
import org.openspaces.grid.gsm.machines.exceptions.FailedToStopMachineException;
import org.openspaces.grid.gsm.machines.exceptions.GridServiceAgentSlaEnforcementInProgressException;
import org.openspaces.grid.gsm.machines.exceptions.GridServiceAgentSlaEnforcementPendingContainerDeallocationException;
import org.openspaces.grid.gsm.machines.exceptions.InconsistentMachineProvisioningException;
import org.openspaces.grid.gsm.machines.exceptions.MachinesSlaEnforcementInProgressException;
import org.openspaces.grid.gsm.machines.exceptions.NeedToStartMoreGridServiceAgentsException;
import org.openspaces.grid.gsm.machines.exceptions.NeedToWaitUntilAllGridServiceAgentsDiscoveredException;
import org.openspaces.grid.gsm.machines.exceptions.SomeProcessingUnitsHaveNotCompletedStateRecoveryException;
import org.openspaces.grid.gsm.machines.exceptions.StartedTooManyMachinesException;
import org.openspaces.grid.gsm.machines.exceptions.UndeployInProgressException;
import org.openspaces.grid.gsm.machines.exceptions.UnexpectedShutdownOfNewGridServiceAgentException;
import org.openspaces.grid.gsm.machines.exceptions.WaitingForDiscoveredMachinesException;
import org.openspaces.grid.gsm.machines.plugins.NonBlockingElasticMachineProvisioning;
import org.openspaces.grid.gsm.machines.plugins.exceptions.ElasticGridServiceAgentProvisioningException;
import org.openspaces.grid.gsm.machines.plugins.exceptions.ElasticMachineProvisioningException;
/**
* This class tracks started and shutdown machines while the operating is in progress.
* It uses internal logic and the bin packing solver to allocated and deallocate capacity (cpu/memory) on these machines.
* When there is excess capacity, machines are marked for deallocation.
* When there is capacity shortage, new machines are started.
*
* @author itaif
* @see MachinesSlaEnforcement - creates this endpoint
* @see MachinesSlaPolicy - defines the sla policy for this endpoint
*/
class DefaultMachinesSlaEnforcementEndpoint implements MachinesSlaEnforcementEndpoint {
private static final long START_AGENT_TIMEOUT_SECONDS = Long.getLong("org.openspaces.grid.start-agent-timeout-seconds", 30*60L);
private static final long STOP_AGENT_TIMEOUT_SECONDS = Long.getLong("org.openspaces.grid.stop-agent-timeout-seconds", 10*60L);
private final ProcessingUnit pu;
private final Log logger;
private final MachinesSlaEnforcementState state;
public DefaultMachinesSlaEnforcementEndpoint(ProcessingUnit pu, MachinesSlaEnforcementState state) {
if (pu == null) {
throw new IllegalArgumentException("pu cannot be null.");
}
this.state = state;
this.pu = pu;
this.logger =
new LogPerProcessingUnit(
new SingleThreadedPollingLog(
LogFactory.getLog(DefaultMachinesSlaEnforcementEndpoint.class)),
pu);
}
@Override
public CapacityRequirementsPerAgent getAllocatedCapacity(AbstractMachinesSlaPolicy sla) {
CapacityRequirementsPerAgent allocatedCapacity = getAllocatedCapacityUnfiltered(sla);
// validate all agents have been discovered
for (String agentUid : allocatedCapacity.getAgentUids()) {
GridServiceAgent agent = pu.getAdmin().getGridServiceAgents().getAgentByUID(agentUid);
if (agent == null) {
throw new IllegalStateException(
"agent " + agentUid +" is not discovered. "+
"sla.agentZones="+sla.getGridServiceAgentZones());
}
}
return allocatedCapacity;
}
public CapacityRequirementsPerAgent getAllocatedCapacityUnfiltered(AbstractMachinesSlaPolicy sla) {
return state.getAllocatedCapacity(getKey(sla));
}
@Override
public CapacityRequirementsPerAgent getAllocatedCapacityFilterUndiscoveredAgents(AbstractMachinesSlaPolicy sla) {
CapacityRequirementsPerAgent checkedAllocatedCapacity = new CapacityRequirementsPerAgent();
CapacityRequirementsPerAgent allocatedCapacity = getAllocatedCapacityUnfiltered(sla);
// validate all agents have been discovered
for (String agentUid : allocatedCapacity.getAgentUids()) {
GridServiceAgent agent = pu.getAdmin().getGridServiceAgents().getAgentByUID(agentUid);
if (agent != null) {
CapacityRequirements capacity = allocatedCapacity.getAgentCapacity(agentUid);
checkedAllocatedCapacity = checkedAllocatedCapacity.add(agentUid,capacity);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Found llocated capacity on agent that is no longer discovered " + agentUid);
}
}
}
return checkedAllocatedCapacity;
}
public void enforceSla(CapacityMachinesSlaPolicy sla) throws MachinesSlaEnforcementInProgressException, GridServiceAgentSlaEnforcementInProgressException {
validateSla(sla);
long memoryInMB = MachinesSlaUtils.getMemoryInMB(sla.getCapacityRequirements());
if (memoryInMB <
sla.getMinimumNumberOfMachines()*sla.getContainerMemoryCapacityInMB()) {
throw new IllegalArgumentException(
"Memory capacity " + memoryInMB + "MB "+
"is less than the minimum of " + sla.getMinimumNumberOfMachines() + " "+
"containers with " + sla.getContainerMemoryCapacityInMB() + "MB each. "+
"sla.agentZone="+sla.getGridServiceAgentZones());
}
if (memoryInMB > getMaximumNumberOfMachines(sla)*sla.getContainerMemoryCapacityInMB()) {
throw new IllegalArgumentException(
"Memory capacity " + memoryInMB + "MB "+
"is more than the maximum of " + getMaximumNumberOfMachines(sla) + " "+
"containers with " + sla.getContainerMemoryCapacityInMB() + "MB each. "+
"sla.agentZone="+sla.getGridServiceAgentZones());
}
validateProvisionedMachines(sla);
setMachineIsolation(sla);
enforceSlaInternal(sla);
}
/**
* This method calculates the upper bound (suprimum) for the number of machines to be started in this zone.
* It is not intended to be an exact upper bound.
*/
private int getMaximumNumberOfMachines(AbstractMachinesSlaPolicy sla) {
int numberOfMachinesFromSamePu = state.getAllocatedCapacityOfOtherKeysFromSamePu(getKey(sla)).getAgentUids().size();
int maxNumberOfMachines = sla.getMaximumNumberOfMachines() - numberOfMachinesFromSamePu;
if (maxNumberOfMachines < 0 && logger.isWarnEnabled()) {
logger.warn(
"number of allocated machines (" + state.getAllocatedCapacity(pu).getAgentUids().size() + ") "+
"is above maximum " + sla.getMaximumNumberOfMachines() + ":" +
state.getAllocatedCapacity(pu));
}
return Math.max(sla.getMinimumNumberOfMachines(),maxNumberOfMachines);
}
private StateKey getKey(AbstractMachinesSlaPolicy sla) {
return new MachinesSlaEnforcementState.StateKey(pu, sla.getGridServiceAgentZones());
}
@Override
public void recoverStateOnEsmStart(AbstractMachinesSlaPolicy sla) throws SomeProcessingUnitsHaveNotCompletedStateRecoveryException, NeedToWaitUntilAllGridServiceAgentsDiscoveredException, UndeployInProgressException {
if (!isCompletedStateRecovery(sla)) {
if (!sla.isUndeploying()) {
state.validateUndeployNotInProgress(pu);
}
setMachineIsolation(sla);
Set<String> puZones = pu.getRequiredContainerZones().getZones();
// check pu zone matches container zones.
if (puZones.size() != 1) {
throw new IllegalStateException("PU has to have exactly 1 zone defined");
}
String containerZone = puZones.iterator().next();
Admin admin = pu.getAdmin();
// Validate all Agents have been discovered.
for (ProcessingUnitInstance instance : pu.getInstances()) {
GridServiceContainer container = instance.getGridServiceContainer();
if (container.getAgentId() != -1 && container.getGridServiceAgent() == null) {
throw new NeedToWaitUntilAllGridServiceAgentsDiscoveredException(pu, container);
}
}
// Recover the endpoint state based on running containers.
CapacityRequirementsPerAgent allocatedCapacityForPu = state.getAllocatedCapacity(pu);
for (GridServiceAgent agent: admin.getGridServiceAgents()) {
if (!sla.getGridServiceAgentZones().isSatisfiedBy(agent.getExactZones())) {
continue;
}
String agentUid = agent.getUid();
// state maps [agentUid,PU] into memory capacity
// we cannot assume allocatedMemoryOnAgent == 0 since this method
// must be idempotent.
long allocatedMemoryOnAgentInMB = MachinesSlaUtils.getMemoryInMB(
allocatedCapacityForPu.getAgentCapacityOrZero(agentUid));
int numberOfContainersForPuOnAgent =
ContainersSlaUtils.getContainersByZoneOnAgentUid(admin,containerZone,agentUid).size();
long memoryToAllocateOnAgentInMB =
numberOfContainersForPuOnAgent * sla.getContainerMemoryCapacityInMB() - allocatedMemoryOnAgentInMB;
if (memoryToAllocateOnAgentInMB > 0) {
logger.info("Recovering " + memoryToAllocateOnAgentInMB + "MB allocated for PU" + pu.getName() + " on machine " + MachinesSlaUtils.machineToString(agent.getMachine()));
CapacityRequirements capacityToAllocateOnAgent =
new CapacityRequirements(new MemoryCapacityRequirement(memoryToAllocateOnAgentInMB));
allocateManualCapacity(
sla,
capacityToAllocateOnAgent,
new CapacityRequirementsPerAgent().add(
agentUid,
capacityToAllocateOnAgent));
}
}
completedStateRecovery(sla);
}
}
/**
* Validates that the cloud has not "forgot about" machines without killing the agent on them.
* This can happen when the connection with the cloud is lost and we cannot determine which machines are allocated for this pu by the cloud.
*
* We added this method since in such condition the code behaves unexpectedly (all machines are unallocated automatically, and then some other pu tries to allocate them once the cloud is back online).
* @param sla
* @throws InconsistentMachineProvisioningException
* @throws FailedToDiscoverMachinesException
* @throws WaitingForDiscoveredMachinesException
*/
private void validateProvisionedMachines(AbstractMachinesSlaPolicy sla) throws GridServiceAgentSlaEnforcementInProgressException, MachinesSlaEnforcementInProgressException {
Collection<GridServiceAgent> discoveredAgents =sla.getDiscoveredMachinesCache().getDiscoveredAgents();
Collection<GridServiceAgent> undiscoveredAgents = new HashSet<GridServiceAgent>();
for(GridServiceAgent agent : MachinesSlaUtils.convertAgentUidsToAgentsIfDiscovered(getAllocatedCapacityUnfiltered(sla).getAgentUids(),pu.getAdmin())) {
if (!discoveredAgents.contains(agent)) {
undiscoveredAgents.add(agent);
}
}
if (undiscoveredAgents.size() > 0) {
throw new InconsistentMachineProvisioningException(getProcessingUnit(), undiscoveredAgents);
}
}
private void validateSla(AbstractMachinesSlaPolicy sla) {
if (sla == null) {
throw new IllegalArgumentException("SLA cannot be null");
}
sla.validate();
}
@Override
public void enforceSla(EagerMachinesSlaPolicy sla)
throws GridServiceAgentSlaEnforcementInProgressException {
validateSla(sla);
try {
validateProvisionedMachines(sla);
} catch (MachinesSlaEnforcementInProgressException e) {
logger.warn("Ignoring failure to related to new machines, since now in eager mode", e);
}
setMachineIsolation(sla);
enforceSlaInternal(sla);
}
private void enforceSlaInternal(EagerMachinesSlaPolicy sla)
throws GridServiceAgentSlaEnforcementInProgressException {
try {
updateFailedMachinesState(sla);
updateFutureAgentsState(sla);
updateRestrictedMachinesState(sla);
updateAgentsMarkedForDeallocationState(sla);
unmarkAgentsMarkedForDeallocationToSatisfyMinimumNumberOfMachines(sla);
//Eager scale out: allocate as many machines and as many CPU as possible
allocateEagerCapacity(sla);
} catch (MachinesSlaEnforcementInProgressException e) {
logger.warn("Ignoring failure to related to new machines, since now in eager mode", e);
}
int machineShortage = getMachineShortageInOrderToReachMinimumNumberOfMachines(sla);
if (machineShortage > 0) {
CapacityRequirements capacityRequirements = new CapacityRequirements(
new NumberOfMachinesCapacityRequirement(machineShortage));
throw new NeedToStartMoreGridServiceAgentsException(sla, state, capacityRequirements, pu);
}
if (!getCapacityMarkedForDeallocation(sla).equalsZero()) {
// containers need to be removed (required when number of containers per machine changes)
throw new GridServiceAgentSlaEnforcementPendingContainerDeallocationException(getProcessingUnit(), getCapacityMarkedForDeallocation(sla));
}
}
public ProcessingUnit getProcessingUnit() {
return pu;
}
private void enforceSlaInternal(CapacityMachinesSlaPolicy sla)
throws MachinesSlaEnforcementInProgressException, GridServiceAgentSlaEnforcementInProgressException {
updateFailedMachinesState(sla);
updateFutureAgentsState(sla);
updateRestrictedMachinesState(sla);
updateAgentsMarkedForDeallocationState(sla);
CapacityRequirementsPerAgent capacityMarkedForDeallocation = getCapacityMarkedForDeallocation(sla);
CapacityRequirementsPerAgent capacityAllocated = getAllocatedCapacity(sla);
if (getNumberOfFutureAgents(sla) > 0 &&
!capacityMarkedForDeallocation.equalsZero()) {
throw new IllegalStateException(
"Cannot have both agents pending to be started and agents pending deallocation. "+
"capacityMarkedForDeallocation="+capacityMarkedForDeallocation + " " +
"getNumberOfFutureAgents(sla)="+getNumberOfFutureAgents(sla) + " " +
"sla.agentZones=" + sla.getGridServiceAgentZones());
}
CapacityRequirements target = sla.getCapacityRequirements();
CapacityRequirementsPerAgent capacityAllocatedAndMarked =
capacityMarkedForDeallocation.add(capacityAllocated);
int machineShortage = getMachineShortageInOrderToReachMinimumNumberOfMachines(sla);
if (!capacityAllocatedAndMarked.getTotalAllocatedCapacity().equals(target) &&
capacityAllocatedAndMarked.getTotalAllocatedCapacity().greaterOrEquals(target) &&
machineShortage == 0) {
if (getNumberOfFutureAgents(sla) > 0) {
throw new DelayingScaleInUntilAllMachinesHaveStartedException(getProcessingUnit());
}
logger.debug("Considering scale in: "+
"target is "+ target + " " +
"minimum #machines is " + sla.getMinimumNumberOfMachines() + ", " +
"machines started " + getAllocatedCapacity(sla) + ", " +
"machines pending deallocation " + getCapacityMarkedForDeallocation(sla));
// scale in
CapacityRequirements surplusCapacity =
capacityAllocatedAndMarked.getTotalAllocatedCapacity().subtract(target);
int surplusMachines = capacityAllocatedAndMarked.getAgentUids().size() - sla.getMinimumNumberOfMachines();
// adjust surplusMemory based on agents marked for deallocation
// remove mark if it would cause surplus to be below zero
// remove mark if it would reduce the number of machines below the sla minimum.
for (String agentUid : capacityMarkedForDeallocation.getAgentUids()) {
CapacityRequirements agentCapacity = capacityMarkedForDeallocation.getAgentCapacity(agentUid);
if (surplusCapacity.greaterOrEquals(agentCapacity) &&
surplusMachines > 0) {
// this machine is already marked for deallocation, so surplus
// is adjusted to reflect that
surplusCapacity = surplusCapacity.subtract(agentCapacity);
surplusMachines--;
} else {
// cancel scale in
unmarkCapacityForDeallocation(sla, agentUid, agentCapacity);
if (logger.isInfoEnabled()) {
GridServiceAgent agent = pu.getAdmin().getGridServiceAgents().getAgentByUID(agentUid);
if (agent != null) {
logger.info(
"machine agent " + agent.getMachine().getHostAddress() + " " +
"is no longer marked for deallocation in order to maintain capacity. "+
"Allocated machine agents are: " + getAllocatedCapacity(sla));
}
}
}
}
if (!surplusCapacity.equalsZero()) {
// scale in now
deallocateManualCapacity(sla,surplusCapacity);
}
}
else if (!capacityAllocatedAndMarked.getTotalAllocatedCapacity().greaterOrEquals(target)) {
// scale out
if (logger.isInfoEnabled()) {
logger.info("Considering to start more machines inorder to reach target capacity of " + target +". "+
"Current capacity is " + getAllocatedCapacity(sla).getTotalAllocatedCapacity());
}
CapacityRequirements shortageCapacity = getCapacityShortage(sla, target);
// unmark all machines pending deallocation
for (String agentUid : capacityMarkedForDeallocation.getAgentUids()) {
if (MachinesSlaUtils.getMemoryInMB(shortageCapacity) == 0L) {
break;
}
CapacityRequirements agentCapacity = capacityMarkedForDeallocation.getAgentCapacity(agentUid);
CapacityRequirements requiredCapacity = agentCapacity.min(shortageCapacity);
if (logger.isInfoEnabled()) {
GridServiceAgent agent = pu.getAdmin().getGridServiceAgents().getAgentByUID(agentUid);
if (agent != null) {
logger.info("machine agent " + agent.getMachine().getHostAddress() + " is no longer marked for deallocation in order to maintain capacity.");
}
}
unmarkCapacityForDeallocation(sla, agentUid, requiredCapacity);
shortageCapacity = shortageCapacity.subtract(requiredCapacity);
}
if (!shortageCapacity.equalsZero()) {
allocateManualCapacity(sla, shortageCapacity);
shortageCapacity = getCapacityShortage(sla, target);
}
if (!shortageCapacity.equalsZero()) {
if (!sla.getMachineProvisioning().isStartMachineSupported()) {
throw new NeedToStartMoreGridServiceAgentsException(sla, state,shortageCapacity,pu);
}
ExactZonesConfig exactZones = new ExactZonesConfigurer().addZones(sla.getGridServiceAgentZones().getZones()).create();
FutureGridServiceAgent[] futureAgents = sla.getMachineProvisioning().startMachinesAsync(
shortageCapacity,
exactZones,
START_AGENT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
addFutureAgents(sla, futureAgents, shortageCapacity);
logger.info(
"One or more new machine(s) is started in order to "+
"fill capacity shortage " + shortageCapacity + " " +
"for zones " + exactZones +" "+
"Allocated machine agents are: " + getAllocatedCapacity(sla) +" "+
"Pending future machine(s) requests " + getNumberOfFutureAgents(sla));
}
}
// we check minimum number of machines last since it was likely dealt with
// by enforcing the capacity requirements.
else if (machineShortage > 0) {
logger.info("Considering to start more machines to reach required minimum number of machines: " +
capacityAllocated + " started, " +
capacityMarkedForDeallocation + " marked for deallocation, " +
sla.getMinimumNumberOfMachines() + " is the required minimum number of machines."
);
machineShortage = unmarkAgentsMarkedForDeallocationToSatisfyMinimumNumberOfMachines(sla);
if (machineShortage > 0) {
//try allocate on new machines, that have other PUs on it.
allocateNumberOfMachines(sla, machineShortage);
machineShortage = getMachineShortageInOrderToReachMinimumNumberOfMachines(sla);
}
if (machineShortage > 0) {
// scale out to get to the minimum number of agents
CapacityRequirements capacityRequirements = new CapacityRequirements(
new NumberOfMachinesCapacityRequirement(machineShortage));
if (!sla.getMachineProvisioning().isStartMachineSupported()) {
throw new NeedToStartMoreGridServiceAgentsException(sla, state, capacityRequirements, pu);
}
ExactZonesConfig exactZones = new ExactZonesConfigurer().addZones(sla.getGridServiceAgentZones().getZones()).create();
FutureGridServiceAgent[] futureAgents = sla.getMachineProvisioning().startMachinesAsync(
capacityRequirements,
exactZones,
START_AGENT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
addFutureAgents(sla, futureAgents, capacityRequirements);
logger.info(
machineShortage+ " new machine(s) is scheduled to be started in order to reach the minimum of " +
sla.getMinimumNumberOfMachines() + " machines, for zones " + exactZones + ". " +
"Allocated machine agents are: " + getAllocatedCapacity(sla));
}
// even if machineShortage is 0, we still need to come back to this method
// to check the capacity is satisfied (scale out)
throw new MachinesSlaEnforcementInProgressException(getProcessingUnit());
}
else {
logger.debug("No action required in order to enforce machines sla. "+
"target="+target + "| " +
"allocated="+capacityAllocated.toDetailedString() + "| " +
"marked for deallocation="+capacityMarkedForDeallocation.toDetailedString() + "| " +
"#futures="+getNumberOfFutureAgents(sla) + " |" +
"#minimumMachines="+sla.getMinimumNumberOfMachines());
}
if (!getCapacityMarkedForDeallocation(sla).equalsZero()) {
// containers need to move to another machine
throw new GridServiceAgentSlaEnforcementPendingContainerDeallocationException(getProcessingUnit(), getCapacityMarkedForDeallocation(sla));
}
if (getNumberOfFutureAgents(sla) > 0) {
// new machines need to be started
throw new MachinesSlaEnforcementInProgressException(getProcessingUnit());
}
if (!getFutureStoppedMachines(sla).isEmpty()) {
// old machines need to complete shutdown
throw new MachinesSlaEnforcementInProgressException(getProcessingUnit());
}
}
/**
* @param sla
* @return
*/
private Collection<FutureStoppedMachine> getFutureStoppedMachines(CapacityMachinesSlaPolicy sla) {
return state.getMachinesGoingDown(getKey(sla));
}
private CapacityRequirements getCapacityShortage(CapacityMachinesSlaPolicy sla, CapacityRequirements target) throws MachinesSlaEnforcementInProgressException {
CapacityRequirements shortageCapacity =
target.subtractOrZero(getAllocatedCapacity(sla).getTotalAllocatedCapacity());
// take into account expected machines into shortage calculate
for (GridServiceAgentFutures futureAgents : getFutureAgents(sla)) {
CapacityRequirements expectedCapacityRequirements = futureAgents.getExpectedCapacity();
for (CapacityRequirement shortageCapacityRequirement : shortageCapacity.getRequirements()) {
CapacityRequirement expectedCapacityRequirement = expectedCapacityRequirements.getRequirement(shortageCapacityRequirement.getType());
if (!shortageCapacityRequirement.equalsZero() && expectedCapacityRequirement.equalsZero()) {
throw new MachinesSlaEnforcementInProgressException(getProcessingUnit(),
"Cannot determine if more machines need to be started, waiting for relevant " + getProcessingUnit() + " machines to start first to offset machine shortage.");
}
}
shortageCapacity =
shortageCapacity.subtractOrZero(expectedCapacityRequirements);
}
if (!shortageCapacity.equalsZero() && isFutureAgentsOfOtherSharedServices(sla)) {
throw new MachinesSlaEnforcementInProgressException(getProcessingUnit(),
"Cannot determine if more machines need to be started, waiting for other machines from same tenant to start first, to offset machine shortage.");
}
return shortageCapacity;
}
/**
* if minimum number of machines is breached then
* unmark machines that have only containers that are pending for deallocation
* @throws CannotDetermineIfNeedToStartMoreMachinesException
*/
private int unmarkAgentsMarkedForDeallocationToSatisfyMinimumNumberOfMachines(AbstractMachinesSlaPolicy sla) throws CannotDetermineIfNeedToStartMoreMachinesException {
int machineShortage = getMachineShortageInOrderToReachMinimumNumberOfMachines(sla);
final CapacityRequirementsPerAgent capacityAllocated = getAllocatedCapacity(sla);
CapacityRequirementsPerAgent capacityMarkedForDeallocation = getCapacityMarkedForDeallocation(sla);
if (!capacityMarkedForDeallocation.equalsZero()) {
// unmark machines that have only containers that are pending deallocation
for (String agentUid : capacityMarkedForDeallocation.getAgentUids()) {
if (machineShortage > 0 && !capacityAllocated.getAgentUids().contains(agentUid)) {
CapacityRequirements agentCapacity = capacityMarkedForDeallocation.getAgentCapacity(agentUid);
unmarkCapacityForDeallocation(sla, agentUid, agentCapacity);
machineShortage--;
if (logger.isInfoEnabled()) {
GridServiceAgent agent = pu.getAdmin().getGridServiceAgents().getAgentByUID(agentUid);
if (agent != null) {
logger.info(
"machine " + MachinesSlaUtils.machineToString(agent.getMachine()) + " "+
"is no longer marked for deallocation in order to reach the minimum of " +
sla.getMinimumNumberOfMachines() + " machines.");
}
}
}
}
}
return machineShortage;
}
/**
* @return minimumNumberOfMachines - allocatedMachines - futureMachines
* @throws CannotDetermineIfNeedToStartMoreMachinesException
*/
private int getMachineShortageInOrderToReachMinimumNumberOfMachines(AbstractMachinesSlaPolicy sla) throws CannotDetermineIfNeedToStartMoreMachinesException
{
boolean cannotDetermineExpectedNumberOfMachines = false;
final CapacityRequirementsPerAgent capacityAllocated = getAllocatedCapacity(sla);
int machineShortage = sla.getMinimumNumberOfMachines() - capacityAllocated.getAgentUids().size();
if (getNumberOfFutureAgents(sla) > 0) {
// take into account expected machines into shortage calculate
for (final GridServiceAgentFutures future : getFutureAgents(sla)) {
final int expectedNumberOfMachines = numberOfMachines(future.getExpectedCapacity());
if (expectedNumberOfMachines == 0) {
cannotDetermineExpectedNumberOfMachines = true;
}
else {
machineShortage -= expectedNumberOfMachines;
}
}
}
if (machineShortage > 0 && cannotDetermineExpectedNumberOfMachines) {
throw new CannotDetermineIfNeedToStartMoreMachinesException(getProcessingUnit(), machineShortage);
}
if (machineShortage < 0) {
machineShortage = 0;
}
return machineShortage;
}
/**
* Kill agents marked for deallocation that no longer manage containers.
* @param sla
* @param machineProvisioning
* @return
* @throws FailedToStopMachineException
* @throws FailedToStopGridServiceAgentException
*/
private void updateAgentsMarkedForDeallocationState(AbstractMachinesSlaPolicy sla) throws FailedToStopMachineException, FailedToStopGridServiceAgentException {
CapacityRequirementsPerAgent capacityMarkedForDeallocation = getCapacityMarkedForDeallocation(sla);
for (String agentUid : capacityMarkedForDeallocation.getAgentUids()) {
GridServiceAgent agent = pu.getAdmin().getGridServiceAgents().getAgentByUID(agentUid);
if (agent == null) {
deallocateAgentCapacity(sla, agentUid);
logger.info("pu " + pu.getName() + " agent " + agentUid + " has shutdown.");
}
else if (MachinesSlaUtils.getMemoryInMB(getAllocatedCapacity(sla).getAgentCapacityOrZero(agentUid))>=sla.getContainerMemoryCapacityInMB()) {
deallocateAgentCapacity(sla, agentUid);
logger.info("pu " + pu.getName() +" is still allocated on agent " + agentUid);
}
else if (MachinesSlaUtils.getNumberOfChildContainersForProcessingUnit(agent,pu) == 0) {
if (!sla.isStopMachineSupported()) {
logger.info("Agent running on machine " + agent.getMachine().getHostAddress()
+ " is not stopped since scale strategy " + sla.getScaleStrategyName()
+ " does not support automatic start/stop of machines");
deallocateAgentCapacity(sla, agentUid);
continue;
}
if (!MachinesSlaUtils.isAgentAutoShutdownEnabled(agent)) {
logger.info("Agent running on machine " + agent.getMachine().getHostAddress()
+ " is not stopped since it does not have the auto-shutdown flag");
deallocateAgentCapacity(sla, agentUid);
continue;
}
if (MachinesSlaUtils.isManagementRunningOnMachine(agent.getMachine())) {
logger.info("Agent running on machine " + agent.getMachine().getHostAddress()
+ " is not stopped since it is running management processes.");
deallocateAgentCapacity(sla, agentUid);
continue;
}
if (state.isAgentSharedWithOtherProcessingUnits(pu,agent.getUid())) {
// This is a bit like reference counting, the last pu to leave stops the machine
logger.info("Agent running on machine " + agent.getMachine().getHostAddress()
+ " is not stopped since it is shared with other processing units.");
deallocateAgentCapacity(sla, agentUid);
continue;
}
// double check that agent is not used
Set<Long> childProcessesIds = MachinesSlaUtils.getChildProcessesIds(agent);
if (!childProcessesIds.isEmpty()) {
// this is unexpected. We already checked for management processes and other PU processes.
logger.warn("Agent " + agent.getUid() + " on machine " + MachinesSlaUtils.machineToString(agent.getMachine())+ " cannot be shutdown due to the following child processes: " + childProcessesIds);
continue;
}
stopMachine(sla, agent);
}
}
cleanMachinesGoingDown(sla);
}
private void stopMachine(AbstractMachinesSlaPolicy sla, GridServiceAgent agent) {
if (!isAgentExistsInStoppedMachinesFutures(agent)) {
logger.info("Agent " + agent.getUid() + " on machine " + MachinesSlaUtils.machineToString(agent.getMachine())
+ " is no longer in use by any processing unit. "+
"It is going down!");
final NonBlockingElasticMachineProvisioning machineProvisioning = sla.getMachineProvisioning();
// The machineProvisioning might not be the same one that started this agent,
// Nevertheless, we expect it to be able to stop this agent.
FutureStoppedMachine stopMachineFuture = machineProvisioning.stopMachineAsync(
agent,
STOP_AGENT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
addFutureStoppedMachine(sla, stopMachineFuture);
}
}
public boolean isAgentExistsInStoppedMachinesFutures(GridServiceAgent agent) {
/** {@link NonBlockingElasticMachineProvisioning#stopMachineAsync(GridServiceAgent, long, TimeUnit) may not be idempotent.
* Make sure stopAsync has not already been called on this agent.
*/
Collection<FutureStoppedMachine> machinesGoingDown = state.getMachinesGoingDown();
for (FutureStoppedMachine machineGoingDown : machinesGoingDown) {
if (machineGoingDown.getGridServiceAgent().getUid().equals(agent.getUid())) {
if (logger.isDebugEnabled()) {
logger.debug("Not calling stopMachine for agent with uid = " + agent.getUid()
+ " because a request was already sent to shut it down");
}
return true;
}
}
return false;
}
/**
* @param sla
* @param stopMachineFuture
*/
private void addFutureStoppedMachine(AbstractMachinesSlaPolicy sla, FutureStoppedMachine stopMachineFuture) {
state.addFutureStoppedMachine(getKey(sla), stopMachineFuture);
}
/**
* mark for deallocation machines that were not restricted but are now restricted for this PU
*/
private void updateRestrictedMachinesState(AbstractMachinesSlaPolicy sla) {
// mark for deallocation machines that are restricted for this PU
Map<String,List<String>> restrictedMachines = getRestrictedAgentUidsForPuWithReason(sla);
for(GridServiceAgent agent : MachinesSlaUtils.convertAgentUidsToAgents(getAllocatedCapacity(sla).getAgentUids(),pu.getAdmin())) {
String agentUid = agent.getUid();
if (restrictedMachines.containsKey(agentUid)) {
logger.info("Machine " + MachinesSlaUtils.machineToString(agent.getMachine())+ " is restricted for pu " + pu.getName() + " reason:" + restrictedMachines.get(agentUid));
markAgentCapacityForDeallocation(sla, agentUid);
}
}
}
/**
* mark for deallocation machines that were undiscovered by the lookup service
*/
private void updateFailedMachinesState(AbstractMachinesSlaPolicy sla) {
final GridServiceAgents agents = pu.getAdmin().getGridServiceAgents();
// mark for deallocation all failed machines
for(final String agentUid: getAllocatedCapacityUnfiltered(sla).getAgentUids()) {
if (agents.getAgentByUID(agentUid) == null) {
logger.warn("Agent " + agentUid + " was killed unexpectedly.");
markAgentCapacityForDeallocation(sla, agentUid);
}
}
}
private void cleanMachinesGoingDown(AbstractMachinesSlaPolicy sla) throws FailedToStopMachineException, FailedToStopGridServiceAgentException {
for (FutureStoppedMachine futureStoppedMachine : state.getMachinesGoingDown(getKey(sla))) {
GridServiceAgent agent = futureStoppedMachine.getGridServiceAgent();
Exception exception = null;
try {
if (futureStoppedMachine.isDone()) {
futureStoppedMachine.get();
if (agent.isDiscovered()) {
throw new IllegalStateException("Agent [" + agent.getUid() + "] should not be discovered at this point.");
}
removeFutureStoppedMachine(sla, futureStoppedMachine);
}
} catch (ExecutionException e) {
// if runtime or error propagate exception "as-is"
Throwable cause = e.getCause();
if (cause instanceof TimeoutException ||
cause instanceof ElasticMachineProvisioningException ||
cause instanceof ElasticGridServiceAgentProvisioningException ||
cause instanceof InterruptedException) {
// expected exception
exception = e;
}
else {
throw new IllegalStateException("Unexpected Exception from machine provisioning.",e);
}
} catch (TimeoutException e) {
// expected exception
exception = e;
}
if (exception != null) {
if (logger.isDebugEnabled()) {
if (agent.isDiscovered()) {
logger.debug("Agent [" + agent.getUid() + "] is still discovered. Another processing unit may use it if needed."
+ "if not, another attempt to shut it down will be executed.");
} else {
logger.debug("agent [" + agent.getUid() + "] is not discovered. but an error happened while terminating the machine");
}
}
removeFutureStoppedMachine(sla, futureStoppedMachine);
if (exception instanceof ElasticGridServiceAgentProvisioningException) {
throw new FailedToStopGridServiceAgentException(pu, agent,exception);
}
throw new FailedToStopMachineException(pu, agent, exception);
}
}
}
/**
* @param sla
* @param futureStoppedMachine
*/
private void removeFutureStoppedMachine(AbstractMachinesSlaPolicy sla, FutureStoppedMachine futureStoppedMachine) {
state.removeFutureStoppedMachine(getKey(sla), futureStoppedMachine);
}
/**
* Move future agents that completed startup, from the future state to allocated state.
*
* This is done by removing the future state, and adding pu allocation state on these machines.
* @throws InconsistentMachineProvisioningException
* @throws UnexpectedShutdownOfNewGridServiceAgentException
* @throws FailedToStartNewMachineException
* @throws StartedTooManyMachinesException
* @throws FailedToDiscoverMachinesException
* @throws WaitingForDiscoveredMachinesException
*/
private void updateFutureAgentsState(AbstractMachinesSlaPolicy sla) throws GridServiceAgentSlaEnforcementInProgressException, MachinesSlaEnforcementInProgressException {
// each futureAgents object contains an array of FutureGridServiceAgent
// only when all future in the array is done, the futureAgents object is done.
Collection<GridServiceAgentFutures> doneFutureAgentss = getAllDoneFutureAgents(sla);
Collection<GridServiceAgent> discoveredAgents = sla.getDiscoveredMachinesCache().getDiscoveredAgents();
for (GridServiceAgentFutures doneFutureAgents : doneFutureAgentss) {
for (FutureGridServiceAgent doneFutureAgent : doneFutureAgents.getFutureGridServiceAgents()) {
try {
validateHealthyAgent(
sla,
discoveredAgents,
doneFutureAgent);
}
catch (InconsistentMachineProvisioningException e) {
// should be fixed by next time we get here
// do not remove the future
throw e;
} catch (FailedToStartNewMachineException e) {
// we remove the future, next time we wont find it
doneFutureAgents.removeFutureAgent(doneFutureAgent);
if (sla.isUndeploying()) {
logger.info("Ignoring failure to start new machine, since undeploy is in progress",e);
}
else {
throw e;
}
} catch (UnexpectedShutdownOfNewGridServiceAgentException e) {
// we remove the future, next time we wont find it
doneFutureAgents.removeFutureAgent(doneFutureAgent);
if (sla.isUndeploying()) {
logger.info("Ignoring failure to start new grid service agent, since undeploy is in progress",e);
}
else {
throw e;
}
}
}
}
for (GridServiceAgentFutures doneFutureAgents : doneFutureAgentss) {
Collection<GridServiceAgent> healthyAgents = doneFutureAgents.getGridServiceAgents();
if (healthyAgents.size() > 0) {
if (logger.isInfoEnabled()) {
logger.info("Agents that were started by " +
"machineProvisioning class=" + sla.getMachineProvisioning().getClass() + " " +
"new agents: " + MachinesSlaUtils.machinesToString(healthyAgents) + " " +
"provisioned agents:" + MachinesSlaUtils.machinesToString(discoveredAgents));
}
CapacityRequirementsPerAgent unallocatedCapacity =
getUnallocatedCapacityIncludeNewMachines(sla, healthyAgents);
//update state 1: allocate capacity based on expectation (even if it was not met)
if (numberOfMachines(doneFutureAgents.getExpectedCapacity()) > 0) {
allocateNumberOfMachines(
sla,
numberOfMachines(doneFutureAgents.getExpectedCapacity()),
unallocatedCapacity);
}
else if (!doneFutureAgents.getExpectedCapacity().equalsZero()) {
allocateManualCapacity(
sla,
doneFutureAgents.getExpectedCapacity(),
unallocatedCapacity);
}
else {
throw new IllegalStateException(
"futureAgents expected capacity malformed. "+
"doneFutureAgents=" + doneFutureAgents.getExpectedCapacity());
}
}
//update state 2: remove futures from list
removeFutureAgents(sla, doneFutureAgents);
// update state 3:
// mark for shutdown new machines that are not marked by any processing unit
// these are all future agents that should have been used by the binpacking solver.
// The fact that they have not been used suggests that the number of started
// machines by machineProvisioning is more than we asked for.
Collection<GridServiceAgent> unallocatedAgents = new ArrayList<GridServiceAgent>();
for (GridServiceAgent newAgent : healthyAgents) {
String agentUid = newAgent.getUid();
CapacityRequirements agentCapacity = getAllocatedCapacity(sla).getAgentCapacityOrZero(agentUid);
if (agentCapacity.equalsZero()) {
unallocatedAgents.add(newAgent);
}
}
if (unallocatedAgents.size() > 0) {
if (!sla.getMachineProvisioning().isStartMachineSupported()) {
logger.info(
"Agents " + MachinesSlaUtils.machinesToString(unallocatedAgents) +
" are not needed for pu " + pu.getName());
}
else {
StartedTooManyMachinesException tooManyMachinesExceptions = new StartedTooManyMachinesException(pu,unallocatedAgents);
logger.warn(
"Stopping machines " + MachinesSlaUtils.machinesToString(unallocatedAgents) + " "+
"Agents provisioned by cloud: " + discoveredAgents,
tooManyMachinesExceptions);
for (GridServiceAgent unallocatedAgent : unallocatedAgents) {
stopMachine(sla,unallocatedAgent);
}
throw tooManyMachinesExceptions;
}
}
}
}
private CapacityRequirementsPerAgent getUnallocatedCapacityIncludeNewMachines(
AbstractMachinesSlaPolicy sla,
Collection<GridServiceAgent> newMachines ) throws MachinesSlaEnforcementInProgressException {
// unallocated capacity = unallocated capacity + new machines
CapacityRequirementsPerAgent unallocatedCapacity = getUnallocatedCapacity(sla);
for (GridServiceAgent newAgent : newMachines) {
if (unallocatedCapacity.getAgentUids().contains(newAgent.getUid())) {
throw new IllegalStateException(
"unallocated capacity cannot contain future agents. "+
"unallocatedCapacity="+unallocatedCapacity+
"newAgent.getUid()="+newAgent.getUid()+
"sla.agentZones="+sla.getGridServiceAgentZones());
}
CapacityRequirements newAgentCapacity = MachinesSlaUtils.getMachineTotalCapacity(newAgent,sla);
if (logger.isInfoEnabled()) {
logger.info("Agent started and provisioned succesfully on a new machine " + MachinesSlaUtils.machineToString(newAgent.getMachine())+ " has "+ newAgentCapacity);
}
if (MachinesSlaUtils.getMemoryInMB(newAgentCapacity) < sla.getContainerMemoryCapacityInMB()) {
logger.warn("New agent " + MachinesSlaUtils.machineToString(newAgent.getMachine()) + " has only "
+ newAgentCapacity
+ " unreserved free resources, which is not enough for even one container that requires "
+ sla.getContainerMemoryCapacityInMB() + "MB");
}
unallocatedCapacity =
unallocatedCapacity.add(
newAgent.getUid(),
newAgentCapacity);
}
return unallocatedCapacity;
}
/**
* @param sla
* @param discoveredAgents
* @return true - if removed future agent from the state
* @throws InconsistentMachineProvisioningException
* @throws UnexpectedShutdownOfNewGridServiceAgentException
* @throws MachinesSlaEnforcementInProgressException
* @throws FailedToStartNewGridServiceAgentException
* @throws FailedMachineProvisioningException
*/
private void validateHealthyAgent(
AbstractMachinesSlaPolicy sla,
Collection<GridServiceAgent> discoveredAgents,
FutureGridServiceAgent futureAgent)
throws UnexpectedShutdownOfNewGridServiceAgentException, InconsistentMachineProvisioningException, MachinesSlaEnforcementInProgressException, FailedToStartNewGridServiceAgentException {
final NonBlockingElasticMachineProvisioning machineProvisioning = sla.getMachineProvisioning();
final Collection<String> usedAgentUids = state.getAllUsedAgentUids();
final Collection<String> usedAgentUidsForPu = state.getUsedAgentUids(getKey(sla));
GridServiceAgent newAgent = null;
{
Exception exception = null;
try {
newAgent = futureAgent.get();
} catch (ExecutionException e) {
// if runtime or error propagate exception "as-is"
Throwable cause = e.getCause();
if (cause instanceof TimeoutException || cause instanceof ElasticMachineProvisioningException || cause instanceof ElasticGridServiceAgentProvisioningException || cause instanceof InterruptedException) {
// expected exception
exception = e;
}
else {
throw new IllegalStateException("Unexpected Exception from machine provisioning.",e);
}
} catch (TimeoutException e) {
// expected exception
exception = e;
}
if (exception != null) {
if (exception instanceof ElasticGridServiceAgentProvisioningException) {
throw new FailedToStartNewGridServiceAgentException(pu, exception);
}
throw new FailedToStartNewMachineException(pu, exception);
}
}
if (newAgent == null) {
throw new IllegalStateException("Machine provisioning future is done without exception, but returned a null agent");
}
GSAReservationId actualReservationId = ((InternalGridServiceAgent)newAgent).getReservationId();
if (actualReservationId == null) {
throw new IllegalStateException("Machine provisioning future is done without exception, but returned a null reservationId from the agent");
}
GSAReservationId expectedReservationId = futureAgent.getReservationId();
if (!actualReservationId.equals(expectedReservationId)) {
final String ipAddress = newAgent.getMachine().getHostAddress();
throw new IllegalStateException(
"Machine provisioning future is done without exception, but returned an agent(ip="+ipAddress+") "+
"with the wrong reservationId: expected="+expectedReservationId+ " actual="+actualReservationId);
}
if (!newAgent.isDiscovered()) {
UnexpectedShutdownOfNewGridServiceAgentException unexpectedShutdownException = new UnexpectedShutdownOfNewGridServiceAgentException(newAgent.getMachine(), pu);
if (logger.isWarnEnabled()) {
logger.warn("Failed to start agent on new machine.", unexpectedShutdownException);
}
throw unexpectedShutdownException;
}
if (usedAgentUidsForPu.contains(newAgent.getUid())) {
//some nasty bug in machine provisioning implementation
throw new IllegalStateException(
"Machine provisioning for " + pu.getName() + " "+
"has provided the machine " + MachinesSlaUtils.machineToString(newAgent.getMachine()) +
" which is already in use by this PU."+
"The machine is ignored");
}
if (usedAgentUids.contains(newAgent.getUid())) {
//some nasty bug in machine provisioning implementation
throw new IllegalStateException(
"Machine provisioning for " + pu.getName() + " "+
"has provided the machine " + MachinesSlaUtils.machineToString(newAgent.getMachine()) +
" which is already in use by another PU."+
"This machine is ignored");
}
if (!discoveredAgents.contains(newAgent)) {
//Handle the case of a new machine that was started with @{link {@link NonBlockingElasticMachineProvisioning#startMachinesAsync(CapacityRequirements, long, TimeUnit)}
//but still not in the list returned by {@link NonBlockingElasticMachineProvisioning#getDiscoveredMachinesAsync(long, TimeUnit)}
final NonBlockingElasticMachineProvisioning oldMachineProvisioning = futureAgent.getMachineProvisioning();
if (
// checking for a bug in the implementation of machineProvisioning
oldMachineProvisioning != null &&
!MachinesSlaUtils.isAgentConformsToMachineProvisioningConfig(newAgent, oldMachineProvisioning.getConfig()) &&
// ignore error if machine provisioning was modified
oldMachineProvisioning == machineProvisioning) {
throw new IllegalStateException(
MachinesSlaUtils.machineToString(newAgent.getMachine()) + " has been started but with the wrong zone or management settings. "+
"newagent.zones="+newAgent.getExactZones() + " "+
"oldMachineProvisioning.config.zones="+oldMachineProvisioning.getConfig().getGridServiceAgentZones());
}
// providing a grace period for provisionedAgents to update.
throw new InconsistentMachineProvisioningException(getProcessingUnit(), newAgent);
}
}
/**
* Eagerly allocates all unallocated capacity that match the specified SLA
* @throws FailedToDiscoverMachinesException
* @throws WaitingForDiscoveredMachinesException
*/
private void allocateEagerCapacity(AbstractMachinesSlaPolicy sla) throws MachinesSlaEnforcementInProgressException {
CapacityRequirementsPerAgent unallocatedCapacity = getUnallocatedCapacity(sla);
// limit the memory to the maximum possible by this PU
long maxAllocatedMemoryForPu = getMaximumNumberOfMachines(sla)*sla.getContainerMemoryCapacityInMB();
long allocatedMemoryForPu = MachinesSlaUtils.getMemoryInMB(getAllocatedCapacity(sla).getTotalAllocatedCapacity());
// validate not breached max eager capacity
if (allocatedMemoryForPu > maxAllocatedMemoryForPu) {
throw new IllegalStateException(
"maxAllocatedMemoryForPu="+getMaximumNumberOfMachines(sla)+"*"+sla.getContainerMemoryCapacityInMB()+"="+
maxAllocatedMemoryForPu+" "+
"cannot be smaller than allocatedMemoryForPu="+getAllocatedCapacity(sla).toDetailedString());
}
long unallocatedMemory = MachinesSlaUtils.getMemoryInMB(unallocatedCapacity.getTotalAllocatedCapacity());
long memoryToAllocate = Math.min(maxAllocatedMemoryForPu - allocatedMemoryForPu, unallocatedMemory);
CapacityRequirements capacityToAllocate =
unallocatedCapacity.getTotalAllocatedCapacity()
.set(new MemoryCapacityRequirement(memoryToAllocate));
if (logger.isDebugEnabled()) {
logger.debug(
"capacityToAllocate=" + capacityToAllocate + " "+
"maxAllocatedMemoryForPu="+maxAllocatedMemoryForPu + " "+
"unallocatedCapacity="+unallocatedCapacity.toDetailedString() );
}
// allocate memory and CPU eagerly
if (!capacityToAllocate.equalsZero()) {
allocateManualCapacity(sla, capacityToAllocate, unallocatedCapacity);
}
//validate not breached max eager capacity
long allocatedMemoryForPuAfter = MachinesSlaUtils.getMemoryInMB(getAllocatedCapacity(sla).getTotalAllocatedCapacity());
if ( allocatedMemoryForPuAfter > maxAllocatedMemoryForPu) {
throw new IllegalStateException("allocatedMemoryForPuAfter="+allocatedMemoryForPuAfter+" greater than "+
"maxAllocatedMemoryForPu="+getMaximumNumberOfMachines(sla)+"*"+sla.getContainerMemoryCapacityInMB()+"="+maxAllocatedMemoryForPu+
"allocatedMemoryForPu="+allocatedMemoryForPu+"="+getAllocatedCapacity(sla).toDetailedString()+ " "+
"capacityToAllocate=" + capacityToAllocate + " "+
"maxAllocatedMemoryForPu="+maxAllocatedMemoryForPu + " "+
"unallocatedCapacity="+unallocatedCapacity.toDetailedString() );
}
}
/**
* Allocates the specified capacity on unallocated capacity that match the specified SLA
* @throws MachinesSlaEnforcementInProgressException
*/
private void allocateManualCapacity(AbstractMachinesSlaPolicy sla, CapacityRequirements capacityToAllocate) throws MachinesSlaEnforcementInProgressException {
CapacityRequirementsPerAgent unallocatedCapacity = getUnallocatedCapacity(sla);
allocateManualCapacity(sla, capacityToAllocate, unallocatedCapacity);
}
/**
* Finds an agent that matches the SLA, and can satisfy the specified capacity to allocate.
*
* The algorithm goes over all such machines and chooses the machine that after the allocation would have
* the least amount of memory. So continuous unallocated blocks is left for the next allocation, which could be bigger.
*
* @param capacityToAllocate - the missing capacity that requires allocation on shared machines.
* @return the remaining capacity left for allocation(the rest has been allocated already)
*/
private void allocateManualCapacity(AbstractMachinesSlaPolicy sla, CapacityRequirements capacityToAllocate, CapacityRequirementsPerAgent unallocatedCapacity) {
final BinPackingSolver solver = createBinPackingSolver(sla , unallocatedCapacity);
solver.solveManualCapacityScaleOut(capacityToAllocate);
allocateCapacity(sla, solver.getAllocatedCapacityResult());
markCapacityForDeallocation(sla, solver.getDeallocatedCapacityResult());
}
private void deallocateManualCapacity(AbstractMachinesSlaPolicy sla, CapacityRequirements capacityToDeallocate) throws MachinesSlaEnforcementInProgressException {
CapacityRequirementsPerAgent unallocatedCapacity = getUnallocatedCapacity(sla);
final BinPackingSolver solver = createBinPackingSolver(sla , unallocatedCapacity);
solver.solveManualCapacityScaleIn(capacityToDeallocate);
allocateCapacity(sla, solver.getAllocatedCapacityResult());
markCapacityForDeallocation(sla, solver.getDeallocatedCapacityResult());
}
private void allocateNumberOfMachines(AbstractMachinesSlaPolicy sla, int numberOfFreeAgents) throws MachinesSlaEnforcementInProgressException {
CapacityRequirementsPerAgent unallocatedCapacity = getUnallocatedCapacity(sla);
allocateNumberOfMachines(sla, numberOfFreeAgents, unallocatedCapacity);
}
/**
* Finds an agent that matches the SLA, and can satisfy the specified capacity to allocate.
*
* The algorithm goes over all such machines and chooses the machine that after the allocation would have
* the least amount of memory. So continuous unallocated blocks is left for the next allocation, which could be bigger.
*
* @param numberOfMachines - the missing number of machines that are required.
* @return the remaining number of machines (the rest has been allocated already)
*/
private void allocateNumberOfMachines(AbstractMachinesSlaPolicy sla, int numberOfMachines, CapacityRequirementsPerAgent unallocatedCapacity) {
final BinPackingSolver solver = createBinPackingSolver(sla, unallocatedCapacity);
solver.solveNumberOfMachines(numberOfMachines);
allocateCapacity(sla, solver.getAllocatedCapacityResult());
markCapacityForDeallocation(sla, solver.getDeallocatedCapacityResult());
}
private BinPackingSolver createBinPackingSolver(AbstractMachinesSlaPolicy sla, CapacityRequirementsPerAgent unallocatedCapacity) {
final BinPackingSolver solver = new BinPackingSolver();
solver.setLogger(logger);
solver.setContainerMemoryCapacityInMB(sla.getContainerMemoryCapacityInMB());
solver.setUnallocatedCapacity(unallocatedCapacity);
solver.setAllocatedCapacityForPu(getAllocatedCapacity(sla));
solver.setMaxAllocatedMemoryCapacityOfPuInMB(getMaximumNumberOfMachines(sla)*sla.getContainerMemoryCapacityInMB());
solver.setMaxAllocatedMemoryCapacityOfPuPerMachineInMB(sla.getMaximumNumberOfContainersPerMachine()*sla.getContainerMemoryCapacityInMB());
solver.setMinimumNumberOfMachines(sla.getMinimumNumberOfMachines());
// the higher the priority the less likely the machine to be scaled in.
Map<String,Long> scaleInPriorityPerAgentUid = new HashMap<String,Long>();
GridServiceAgents agents = pu.getAdmin().getGridServiceAgents();
final long FIRST_PRIORITY = Long.MAX_VALUE;
final long SECOND_PRIORITY = FIRST_PRIORITY - 1;
final long THIRD_PRIORITY = SECOND_PRIORITY - 1;
final long FOURTH_PRIORITY = THIRD_PRIORITY - 1;
final long now = System.currentTimeMillis();
for (String agentUid : getAllocatedCapacity(sla).getAgentUids()) {
long agentOrderToDeallocateContainers = 0;
GridServiceAgent agent = agents.getAgentByUID(agentUid);
if (agent != null) {
if (MachinesSlaUtils.isManagementRunningOnMachine(agent.getMachine())) {
// machine has management on it. It will not shutdown anyway, so try to scale in other
// machines first.
agentOrderToDeallocateContainers = FIRST_PRIORITY;
}
else if (state.isAgentSharedWithOtherProcessingUnits(pu, agentUid)) {
// machine has other PUs on it.
// try to scale in other machines first.
agentOrderToDeallocateContainers = SECOND_PRIORITY;
}
else if (!MachinesSlaUtils.isAgentAutoShutdownEnabled(agent)) {
// machine cannot be shutdown by ESM
// try scaling in machines that we can shutdown first.
agentOrderToDeallocateContainers = THIRD_PRIORITY;
}
else {
long startTime = agent.getVirtualMachine().getDetails().getStartTime();
long runDuration = now - startTime;
if (runDuration > FOURTH_PRIORITY) {
runDuration = FOURTH_PRIORITY;
}
//The more time the agent is running the higher the priority the less it should be shutdown
agentOrderToDeallocateContainers = runDuration;
}
}
scaleInPriorityPerAgentUid.put(agentUid, agentOrderToDeallocateContainers);
}
solver.setAgentAllocationPriority(scaleInPriorityPerAgentUid);
return solver;
}
/**
* Calculates the total unused capacity (memory / CPU) on machines (that some of its capacity is already allocated by some PU).
* Returns only machines that match the specified SLA.
* @throws MachinesSlaEnforcementInProgressException
*/
private CapacityRequirementsPerAgent getUnallocatedCapacity(AbstractMachinesSlaPolicy sla) throws MachinesSlaEnforcementInProgressException {
CapacityRequirementsPerAgent physicalCapacity = getPhysicalProvisionedCapacity(sla);
CapacityRequirementsPerAgent usedCapacity = state.getAllUsedCapacity();
Map<String,List<String>> restrictedAgentUids = getRestrictedAgentUidsForPuWithReason(sla);
CapacityRequirementsPerAgent unallocatedCapacity = new CapacityRequirementsPerAgent();
for (String agentUid : physicalCapacity.getAgentUids()) {
if (!restrictedAgentUids.containsKey(agentUid)) {
// machine matches isolation and zone SLA
CapacityRequirements unallocatedCapacityOnAgent =
physicalCapacity.getAgentCapacity(agentUid)
.subtract(usedCapacity.getAgentCapacityOrZero(agentUid));
unallocatedCapacity =
unallocatedCapacity.add(agentUid, unallocatedCapacityOnAgent);
}
}
if (logger.isDebugEnabled()) {
logger.debug("physicalCapacity="+physicalCapacity.toDetailedString()+" usedCapacity="+usedCapacity.toDetailedString()+" restrictedAgentUids="+restrictedAgentUids+" unallocatedCapacity="+unallocatedCapacity.toDetailedString());
}
return unallocatedCapacity;
}
/**
* Calculates the total maximum capacity (memory/CPU) on all sla.getDiscoveredMachinesCache().getDiscoveredAgents()
* @throws MachinesSlaEnforcementInProgressException
*/
private CapacityRequirementsPerAgent getPhysicalProvisionedCapacity(AbstractMachinesSlaPolicy sla) throws MachinesSlaEnforcementInProgressException {
CapacityRequirementsPerAgent totalCapacity = new CapacityRequirementsPerAgent();
for (final GridServiceAgent agent: sla.getDiscoveredMachinesCache().getDiscoveredAgents()) {
if (agent.isDiscovered()) {
totalCapacity = totalCapacity.add(
agent.getUid(),
MachinesSlaUtils.getMachineTotalCapacity(agent, sla));
}
}
return totalCapacity;
}
private static int numberOfMachines(CapacityRequirements capacityRequirements) {
return capacityRequirements.getRequirement(new NumberOfMachinesCapacityRequirement().getType()).getNumberOfMachines();
}
private CapacityRequirementsPerAgent getCapacityMarkedForDeallocation(AbstractMachinesSlaPolicy sla) {
return state.getCapacityMarkedForDeallocation(getKey(sla));
}
private Map<String,List<String>> getRestrictedAgentUidsForPuWithReason(AbstractMachinesSlaPolicy sla) {
return state.getRestrictedAgentUids(getKey(sla));
}
private void setMachineIsolation(AbstractMachinesSlaPolicy sla) {
state.setMachineIsolation(getKey(sla), sla.getMachineIsolation());
}
private int getNumberOfFutureAgents(AbstractMachinesSlaPolicy sla) {
return state.getNumberOfFutureAgents(getKey(sla));
}
private void unmarkCapacityForDeallocation(CapacityMachinesSlaPolicy sla, String agentUid, CapacityRequirements agentCapacity) {
state.unmarkCapacityForDeallocation(getKey(sla), agentUid, agentCapacity);
}
private void addFutureAgents(CapacityMachinesSlaPolicy sla,
FutureGridServiceAgent[] futureAgents, CapacityRequirements shortageCapacity) {
state.addFutureAgents(getKey(sla), futureAgents, shortageCapacity);
}
private Collection<GridServiceAgentFutures> getFutureAgents(AbstractMachinesSlaPolicy sla) {
return state.getFutureAgents(getKey(sla));
}
private boolean isFutureAgentsOfOtherSharedServices(AbstractMachinesSlaPolicy sla) {
return state.isFutureAgentsOfOtherSharedServices(getKey(sla));
}
private void unmarkCapacityForDeallocation(AbstractMachinesSlaPolicy sla, String agentUid, CapacityRequirements agentCapacity) {
state.unmarkCapacityForDeallocation(getKey(sla), agentUid, agentCapacity);
}
private void deallocateAgentCapacity(AbstractMachinesSlaPolicy sla, String agentUid) {
state.deallocateAgentCapacity(getKey(sla), agentUid);
}
private void markAgentCapacityForDeallocation(AbstractMachinesSlaPolicy sla, String agentUid) {
state.markAgentCapacityForDeallocation(getKey(sla), agentUid);
}
private Collection<GridServiceAgentFutures> getAllDoneFutureAgents(AbstractMachinesSlaPolicy sla) {
return state.getAllDoneFutureAgents(getKey(sla));
}
private void removeFutureAgents(AbstractMachinesSlaPolicy sla, GridServiceAgentFutures doneFutureAgents) {
state.removeFutureAgents(getKey(sla), doneFutureAgents);
}
private void allocateCapacity(AbstractMachinesSlaPolicy sla, CapacityRequirementsPerAgent capacityToAllocate) {
GridServiceAgents gridServiceAgents = pu.getAdmin().getGridServiceAgents();
for (String agentUid : capacityToAllocate.getAgentUids()) {
if (gridServiceAgents.getAgentByUID(agentUid) == null) {
throw new IllegalArgumentException("Cannot allocate capacity on a removed agent " + agentUid);
}
state.allocateCapacity(getKey(sla), agentUid, capacityToAllocate.getAgentCapacity(agentUid));
if (logger.isInfoEnabled()) {
logger.info("allocating capacity "+capacityToAllocate.getAgentCapacity(agentUid) + " "+
"on " + MachinesSlaUtils.agentToString(pu.getAdmin(), agentUid) + " "+
"for " + pu.getName() + " "+sla.getGridServiceAgentZones());
}
}
}
private void markCapacityForDeallocation(AbstractMachinesSlaPolicy sla, CapacityRequirementsPerAgent capacityToMarkForDeallocation) {
for (String agentUid : capacityToMarkForDeallocation.getAgentUids()) {
state.markCapacityForDeallocation(getKey(sla), agentUid, capacityToMarkForDeallocation.getAgentCapacity(agentUid));
if (logger.isInfoEnabled()) {
logger.info("marking capacity for deallocation "+capacityToMarkForDeallocation.getAgentCapacity(agentUid) + " on " + MachinesSlaUtils.agentToString(pu.getAdmin(), agentUid));
}
}
}
private void completedStateRecovery(AbstractMachinesSlaPolicy sla) {
state.completedStateRecovery(getKey(sla));
}
private boolean isCompletedStateRecovery(AbstractMachinesSlaPolicy sla) {
return state.isCompletedStateRecovery(getKey(sla));
}
@Override
public void recoveredStateOnEsmStart(ProcessingUnit otherPu) {
state.recoveredStateOnEsmStart(otherPu);
}
@Override
public RecoveryState getRecoveredStateOnEsmStart(ProcessingUnit otherPu) {
return state.getRecoveredStateOnEsmStart(otherPu);
}
@Override
public Set<ZonesConfig> getGridServiceAgentsZones() {
return state.getGridServiceAgentsZones(pu);
}
@Override
public Set<ZonesConfig> getUndeployedGridServiceAgentsZones() {
return state.getUndeployedGridServiceAgentsZones(pu);
}
@Override
public boolean replaceAllocatedCapacity(AbstractMachinesSlaPolicy sla) {
return state.replaceAllocatedCapacity(getKey(sla), pu.getAdmin());
}
@Override
public void beforeUndeployedProcessingUnit(ProcessingUnit pu) {
state.beforeUndeployProcessingUnit(pu);
}
@Override
public void afterUndeployedProcessingUnit(ProcessingUnit pu) {
state.afterUndeployProcessingUnit(pu);
}
} | src/main/java/org/openspaces/grid/gsm/machines/DefaultMachinesSlaEnforcementEndpoint.java | /*******************************************************************************
*
* Copyright (c) 2012 GigaSpaces Technologies Ltd. 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 org.openspaces.grid.gsm.machines;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openspaces.admin.Admin;
import org.openspaces.admin.gsa.GSAReservationId;
import org.openspaces.admin.gsa.GridServiceAgent;
import org.openspaces.admin.gsa.GridServiceAgents;
import org.openspaces.admin.gsc.GridServiceContainer;
import org.openspaces.admin.internal.gsa.InternalGridServiceAgent;
import org.openspaces.admin.pu.ProcessingUnit;
import org.openspaces.admin.pu.ProcessingUnitInstance;
import org.openspaces.admin.zone.config.ExactZonesConfig;
import org.openspaces.admin.zone.config.ExactZonesConfigurer;
import org.openspaces.admin.zone.config.ZonesConfig;
import org.openspaces.grid.gsm.LogPerProcessingUnit;
import org.openspaces.grid.gsm.SingleThreadedPollingLog;
import org.openspaces.grid.gsm.capacity.CapacityRequirement;
import org.openspaces.grid.gsm.capacity.CapacityRequirements;
import org.openspaces.grid.gsm.capacity.CapacityRequirementsPerAgent;
import org.openspaces.grid.gsm.capacity.MemoryCapacityRequirement;
import org.openspaces.grid.gsm.capacity.NumberOfMachinesCapacityRequirement;
import org.openspaces.grid.gsm.containers.ContainersSlaUtils;
import org.openspaces.grid.gsm.machines.MachinesSlaEnforcementState.RecoveryState;
import org.openspaces.grid.gsm.machines.MachinesSlaEnforcementState.StateKey;
import org.openspaces.grid.gsm.machines.exceptions.CannotDetermineIfNeedToStartMoreMachinesException;
import org.openspaces.grid.gsm.machines.exceptions.DelayingScaleInUntilAllMachinesHaveStartedException;
import org.openspaces.grid.gsm.machines.exceptions.FailedToDiscoverMachinesException;
import org.openspaces.grid.gsm.machines.exceptions.FailedToStartNewGridServiceAgentException;
import org.openspaces.grid.gsm.machines.exceptions.FailedToStartNewMachineException;
import org.openspaces.grid.gsm.machines.exceptions.FailedToStopGridServiceAgentException;
import org.openspaces.grid.gsm.machines.exceptions.FailedToStopMachineException;
import org.openspaces.grid.gsm.machines.exceptions.GridServiceAgentSlaEnforcementInProgressException;
import org.openspaces.grid.gsm.machines.exceptions.GridServiceAgentSlaEnforcementPendingContainerDeallocationException;
import org.openspaces.grid.gsm.machines.exceptions.InconsistentMachineProvisioningException;
import org.openspaces.grid.gsm.machines.exceptions.MachinesSlaEnforcementInProgressException;
import org.openspaces.grid.gsm.machines.exceptions.NeedToStartMoreGridServiceAgentsException;
import org.openspaces.grid.gsm.machines.exceptions.NeedToWaitUntilAllGridServiceAgentsDiscoveredException;
import org.openspaces.grid.gsm.machines.exceptions.SomeProcessingUnitsHaveNotCompletedStateRecoveryException;
import org.openspaces.grid.gsm.machines.exceptions.StartedTooManyMachinesException;
import org.openspaces.grid.gsm.machines.exceptions.UndeployInProgressException;
import org.openspaces.grid.gsm.machines.exceptions.UnexpectedShutdownOfNewGridServiceAgentException;
import org.openspaces.grid.gsm.machines.exceptions.WaitingForDiscoveredMachinesException;
import org.openspaces.grid.gsm.machines.plugins.NonBlockingElasticMachineProvisioning;
import org.openspaces.grid.gsm.machines.plugins.exceptions.ElasticGridServiceAgentProvisioningException;
import org.openspaces.grid.gsm.machines.plugins.exceptions.ElasticMachineProvisioningException;
/**
* This class tracks started and shutdown machines while the operating is in progress.
* It uses internal logic and the bin packing solver to allocated and deallocate capacity (cpu/memory) on these machines.
* When there is excess capacity, machines are marked for deallocation.
* When there is capacity shortage, new machines are started.
*
* @author itaif
* @see MachinesSlaEnforcement - creates this endpoint
* @see MachinesSlaPolicy - defines the sla policy for this endpoint
*/
class DefaultMachinesSlaEnforcementEndpoint implements MachinesSlaEnforcementEndpoint {
private static final long START_AGENT_TIMEOUT_SECONDS = Long.getLong("org.openspaces.grid.start-agent-timeout-seconds", 30*60L);
private static final long STOP_AGENT_TIMEOUT_SECONDS = Long.getLong("org.openspaces.grid.stop-agent-timeout-seconds", 10*60L);
private final ProcessingUnit pu;
private final Log logger;
private final MachinesSlaEnforcementState state;
public DefaultMachinesSlaEnforcementEndpoint(ProcessingUnit pu, MachinesSlaEnforcementState state) {
if (pu == null) {
throw new IllegalArgumentException("pu cannot be null.");
}
this.state = state;
this.pu = pu;
this.logger =
new LogPerProcessingUnit(
new SingleThreadedPollingLog(
LogFactory.getLog(DefaultMachinesSlaEnforcementEndpoint.class)),
pu);
}
@Override
public CapacityRequirementsPerAgent getAllocatedCapacity(AbstractMachinesSlaPolicy sla) {
CapacityRequirementsPerAgent allocatedCapacity = getAllocatedCapacityUnfiltered(sla);
// validate all agents have been discovered
for (String agentUid : allocatedCapacity.getAgentUids()) {
GridServiceAgent agent = pu.getAdmin().getGridServiceAgents().getAgentByUID(agentUid);
if (agent == null) {
throw new IllegalStateException(
"agent " + agentUid +" is not discovered. "+
"sla.agentZones="+sla.getGridServiceAgentZones());
}
}
return allocatedCapacity;
}
public CapacityRequirementsPerAgent getAllocatedCapacityUnfiltered(AbstractMachinesSlaPolicy sla) {
return state.getAllocatedCapacity(getKey(sla));
}
@Override
public CapacityRequirementsPerAgent getAllocatedCapacityFilterUndiscoveredAgents(AbstractMachinesSlaPolicy sla) {
CapacityRequirementsPerAgent checkedAllocatedCapacity = new CapacityRequirementsPerAgent();
CapacityRequirementsPerAgent allocatedCapacity = getAllocatedCapacityUnfiltered(sla);
// validate all agents have been discovered
for (String agentUid : allocatedCapacity.getAgentUids()) {
GridServiceAgent agent = pu.getAdmin().getGridServiceAgents().getAgentByUID(agentUid);
if (agent != null) {
CapacityRequirements capacity = allocatedCapacity.getAgentCapacity(agentUid);
checkedAllocatedCapacity = checkedAllocatedCapacity.add(agentUid,capacity);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Found llocated capacity on agent that is no longer discovered " + agentUid);
}
}
}
return checkedAllocatedCapacity;
}
public void enforceSla(CapacityMachinesSlaPolicy sla) throws MachinesSlaEnforcementInProgressException, GridServiceAgentSlaEnforcementInProgressException {
validateSla(sla);
long memoryInMB = MachinesSlaUtils.getMemoryInMB(sla.getCapacityRequirements());
if (memoryInMB <
sla.getMinimumNumberOfMachines()*sla.getContainerMemoryCapacityInMB()) {
throw new IllegalArgumentException(
"Memory capacity " + memoryInMB + "MB "+
"is less than the minimum of " + sla.getMinimumNumberOfMachines() + " "+
"containers with " + sla.getContainerMemoryCapacityInMB() + "MB each. "+
"sla.agentZone="+sla.getGridServiceAgentZones());
}
if (memoryInMB > getMaximumNumberOfMachines(sla)*sla.getContainerMemoryCapacityInMB()) {
throw new IllegalArgumentException(
"Memory capacity " + memoryInMB + "MB "+
"is more than the maximum of " + getMaximumNumberOfMachines(sla) + " "+
"containers with " + sla.getContainerMemoryCapacityInMB() + "MB each. "+
"sla.agentZone="+sla.getGridServiceAgentZones());
}
validateProvisionedMachines(sla);
setMachineIsolation(sla);
enforceSlaInternal(sla);
}
/**
* This method calculates the upper bound (suprimum) for the number of machines to be started in this zone.
* It is not intended to be an exact upper bound.
*/
private int getMaximumNumberOfMachines(AbstractMachinesSlaPolicy sla) {
int numberOfMachinesFromSamePu = state.getAllocatedCapacityOfOtherKeysFromSamePu(getKey(sla)).getAgentUids().size();
int maxNumberOfMachines = sla.getMaximumNumberOfMachines() - numberOfMachinesFromSamePu;
if (maxNumberOfMachines < 0 && logger.isWarnEnabled()) {
logger.warn(
"number of allocated machines (" + state.getAllocatedCapacity(pu).getAgentUids().size() + ") "+
"is above maximum " + sla.getMaximumNumberOfMachines() + ":" +
state.getAllocatedCapacity(pu));
}
return Math.max(sla.getMinimumNumberOfMachines(),maxNumberOfMachines);
}
private StateKey getKey(AbstractMachinesSlaPolicy sla) {
return new MachinesSlaEnforcementState.StateKey(pu, sla.getGridServiceAgentZones());
}
@Override
public void recoverStateOnEsmStart(AbstractMachinesSlaPolicy sla) throws SomeProcessingUnitsHaveNotCompletedStateRecoveryException, NeedToWaitUntilAllGridServiceAgentsDiscoveredException, UndeployInProgressException {
if (!isCompletedStateRecovery(sla)) {
if (!sla.isUndeploying()) {
state.validateUndeployNotInProgress(pu);
}
setMachineIsolation(sla);
Set<String> puZones = pu.getRequiredContainerZones().getZones();
// check pu zone matches container zones.
if (puZones.size() != 1) {
throw new IllegalStateException("PU has to have exactly 1 zone defined");
}
String containerZone = puZones.iterator().next();
Admin admin = pu.getAdmin();
// Validate all Agents have been discovered.
for (ProcessingUnitInstance instance : pu.getInstances()) {
GridServiceContainer container = instance.getGridServiceContainer();
if (container.getAgentId() != -1 && container.getGridServiceAgent() == null) {
throw new NeedToWaitUntilAllGridServiceAgentsDiscoveredException(pu, container);
}
}
// Recover the endpoint state based on running containers.
CapacityRequirementsPerAgent allocatedCapacityForPu = state.getAllocatedCapacity(pu);
for (GridServiceAgent agent: admin.getGridServiceAgents()) {
if (!sla.getGridServiceAgentZones().isSatisfiedBy(agent.getExactZones())) {
continue;
}
String agentUid = agent.getUid();
// state maps [agentUid,PU] into memory capacity
// we cannot assume allocatedMemoryOnAgent == 0 since this method
// must be idempotent.
long allocatedMemoryOnAgentInMB = MachinesSlaUtils.getMemoryInMB(
allocatedCapacityForPu.getAgentCapacityOrZero(agentUid));
int numberOfContainersForPuOnAgent =
ContainersSlaUtils.getContainersByZoneOnAgentUid(admin,containerZone,agentUid).size();
long memoryToAllocateOnAgentInMB =
numberOfContainersForPuOnAgent * sla.getContainerMemoryCapacityInMB() - allocatedMemoryOnAgentInMB;
if (memoryToAllocateOnAgentInMB > 0) {
logger.info("Recovering " + memoryToAllocateOnAgentInMB + "MB allocated for PU" + pu.getName() + " on machine " + MachinesSlaUtils.machineToString(agent.getMachine()));
CapacityRequirements capacityToAllocateOnAgent =
new CapacityRequirements(new MemoryCapacityRequirement(memoryToAllocateOnAgentInMB));
allocateManualCapacity(
sla,
capacityToAllocateOnAgent,
new CapacityRequirementsPerAgent().add(
agentUid,
capacityToAllocateOnAgent));
}
}
completedStateRecovery(sla);
}
}
/**
* Validates that the cloud has not "forgot about" machines without killing the agent on them.
* This can happen when the connection with the cloud is lost and we cannot determine which machines are allocated for this pu by the cloud.
*
* We added this method since in such condition the code behaves unexpectedly (all machines are unallocated automatically, and then some other pu tries to allocate them once the cloud is back online).
* @param sla
* @throws InconsistentMachineProvisioningException
* @throws FailedToDiscoverMachinesException
* @throws WaitingForDiscoveredMachinesException
*/
private void validateProvisionedMachines(AbstractMachinesSlaPolicy sla) throws GridServiceAgentSlaEnforcementInProgressException, MachinesSlaEnforcementInProgressException {
Collection<GridServiceAgent> discoveredAgents =sla.getDiscoveredMachinesCache().getDiscoveredAgents();
Collection<GridServiceAgent> undiscoveredAgents = new HashSet<GridServiceAgent>();
for(GridServiceAgent agent : MachinesSlaUtils.convertAgentUidsToAgentsIfDiscovered(getAllocatedCapacityUnfiltered(sla).getAgentUids(),pu.getAdmin())) {
if (!discoveredAgents.contains(agent)) {
undiscoveredAgents.add(agent);
}
}
if (undiscoveredAgents.size() > 0) {
throw new InconsistentMachineProvisioningException(getProcessingUnit(), undiscoveredAgents);
}
}
private void validateSla(AbstractMachinesSlaPolicy sla) {
if (sla == null) {
throw new IllegalArgumentException("SLA cannot be null");
}
sla.validate();
}
@Override
public void enforceSla(EagerMachinesSlaPolicy sla)
throws GridServiceAgentSlaEnforcementInProgressException {
validateSla(sla);
try {
validateProvisionedMachines(sla);
} catch (MachinesSlaEnforcementInProgressException e) {
logger.warn("Ignoring failure to related to new machines, since now in eager mode", e);
}
setMachineIsolation(sla);
enforceSlaInternal(sla);
}
private void enforceSlaInternal(EagerMachinesSlaPolicy sla)
throws GridServiceAgentSlaEnforcementInProgressException {
try {
updateFailedMachinesState(sla);
updateFutureAgentsState(sla);
updateRestrictedMachinesState(sla);
updateAgentsMarkedForDeallocationState(sla);
unmarkAgentsMarkedForDeallocationToSatisfyMinimumNumberOfMachines(sla);
//Eager scale out: allocate as many machines and as many CPU as possible
allocateEagerCapacity(sla);
} catch (MachinesSlaEnforcementInProgressException e) {
logger.warn("Ignoring failure to related to new machines, since now in eager mode", e);
}
int machineShortage = getMachineShortageInOrderToReachMinimumNumberOfMachines(sla);
if (machineShortage > 0) {
CapacityRequirements capacityRequirements = new CapacityRequirements(
new NumberOfMachinesCapacityRequirement(machineShortage));
throw new NeedToStartMoreGridServiceAgentsException(sla, state, capacityRequirements, pu);
}
if (!getCapacityMarkedForDeallocation(sla).equalsZero()) {
// containers need to be removed (required when number of containers per machine changes)
throw new GridServiceAgentSlaEnforcementPendingContainerDeallocationException(getProcessingUnit(), getCapacityMarkedForDeallocation(sla));
}
}
public ProcessingUnit getProcessingUnit() {
return pu;
}
private void enforceSlaInternal(CapacityMachinesSlaPolicy sla)
throws MachinesSlaEnforcementInProgressException, GridServiceAgentSlaEnforcementInProgressException {
updateFailedMachinesState(sla);
updateFutureAgentsState(sla);
updateRestrictedMachinesState(sla);
updateAgentsMarkedForDeallocationState(sla);
CapacityRequirementsPerAgent capacityMarkedForDeallocation = getCapacityMarkedForDeallocation(sla);
CapacityRequirementsPerAgent capacityAllocated = getAllocatedCapacity(sla);
if (getNumberOfFutureAgents(sla) > 0 &&
!capacityMarkedForDeallocation.equalsZero()) {
throw new IllegalStateException(
"Cannot have both agents pending to be started and agents pending deallocation. "+
"capacityMarkedForDeallocation="+capacityMarkedForDeallocation + " " +
"getNumberOfFutureAgents(sla)="+getNumberOfFutureAgents(sla) + " " +
"sla.agentZones=" + sla.getGridServiceAgentZones());
}
CapacityRequirements target = sla.getCapacityRequirements();
CapacityRequirementsPerAgent capacityAllocatedAndMarked =
capacityMarkedForDeallocation.add(capacityAllocated);
int machineShortage = getMachineShortageInOrderToReachMinimumNumberOfMachines(sla);
if (!capacityAllocatedAndMarked.getTotalAllocatedCapacity().equals(target) &&
capacityAllocatedAndMarked.getTotalAllocatedCapacity().greaterOrEquals(target) &&
machineShortage == 0) {
if (getNumberOfFutureAgents(sla) > 0) {
throw new DelayingScaleInUntilAllMachinesHaveStartedException(getProcessingUnit());
}
logger.debug("Considering scale in: "+
"target is "+ target + " " +
"minimum #machines is " + sla.getMinimumNumberOfMachines() + ", " +
"machines started " + getAllocatedCapacity(sla) + ", " +
"machines pending deallocation " + getCapacityMarkedForDeallocation(sla));
// scale in
CapacityRequirements surplusCapacity =
capacityAllocatedAndMarked.getTotalAllocatedCapacity().subtract(target);
int surplusMachines = capacityAllocatedAndMarked.getAgentUids().size() - sla.getMinimumNumberOfMachines();
// adjust surplusMemory based on agents marked for deallocation
// remove mark if it would cause surplus to be below zero
// remove mark if it would reduce the number of machines below the sla minimum.
for (String agentUid : capacityMarkedForDeallocation.getAgentUids()) {
CapacityRequirements agentCapacity = capacityMarkedForDeallocation.getAgentCapacity(agentUid);
if (surplusCapacity.greaterOrEquals(agentCapacity) &&
surplusMachines > 0) {
// this machine is already marked for deallocation, so surplus
// is adjusted to reflect that
surplusCapacity = surplusCapacity.subtract(agentCapacity);
surplusMachines--;
} else {
// cancel scale in
unmarkCapacityForDeallocation(sla, agentUid, agentCapacity);
if (logger.isInfoEnabled()) {
GridServiceAgent agent = pu.getAdmin().getGridServiceAgents().getAgentByUID(agentUid);
if (agent != null) {
logger.info(
"machine agent " + agent.getMachine().getHostAddress() + " " +
"is no longer marked for deallocation in order to maintain capacity. "+
"Allocated machine agents are: " + getAllocatedCapacity(sla));
}
}
}
}
if (!surplusCapacity.equalsZero()) {
// scale in now
deallocateManualCapacity(sla,surplusCapacity);
}
}
else if (!capacityAllocatedAndMarked.getTotalAllocatedCapacity().greaterOrEquals(target)) {
// scale out
if (logger.isInfoEnabled()) {
logger.info("Considering to start more machines inorder to reach target capacity of " + target +". "+
"Current capacity is " + getAllocatedCapacity(sla).getTotalAllocatedCapacity());
}
CapacityRequirements shortageCapacity = getCapacityShortage(sla, target);
// unmark all machines pending deallocation
for (String agentUid : capacityMarkedForDeallocation.getAgentUids()) {
if (MachinesSlaUtils.getMemoryInMB(shortageCapacity) == 0L) {
break;
}
CapacityRequirements agentCapacity = capacityMarkedForDeallocation.getAgentCapacity(agentUid);
CapacityRequirements requiredCapacity = agentCapacity.min(shortageCapacity);
if (logger.isInfoEnabled()) {
GridServiceAgent agent = pu.getAdmin().getGridServiceAgents().getAgentByUID(agentUid);
if (agent != null) {
logger.info("machine agent " + agent.getMachine().getHostAddress() + " is no longer marked for deallocation in order to maintain capacity.");
}
}
unmarkCapacityForDeallocation(sla, agentUid, requiredCapacity);
shortageCapacity = shortageCapacity.subtract(requiredCapacity);
}
if (!shortageCapacity.equalsZero()) {
allocateManualCapacity(sla, shortageCapacity);
shortageCapacity = getCapacityShortage(sla, target);
}
if (!shortageCapacity.equalsZero()) {
if (!sla.getMachineProvisioning().isStartMachineSupported()) {
throw new NeedToStartMoreGridServiceAgentsException(sla, state,shortageCapacity,pu);
}
ExactZonesConfig exactZones = new ExactZonesConfigurer().addZones(sla.getGridServiceAgentZones().getZones()).create();
FutureGridServiceAgent[] futureAgents = sla.getMachineProvisioning().startMachinesAsync(
shortageCapacity,
exactZones,
START_AGENT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
addFutureAgents(sla, futureAgents, shortageCapacity);
logger.info(
"One or more new machine(s) is started in order to "+
"fill capacity shortage " + shortageCapacity + " " +
"for zones " + exactZones +" "+
"Allocated machine agents are: " + getAllocatedCapacity(sla) +" "+
"Pending future machine(s) requests " + getNumberOfFutureAgents(sla));
}
}
// we check minimum number of machines last since it was likely dealt with
// by enforcing the capacity requirements.
else if (machineShortage > 0) {
logger.info("Considering to start more machines to reach required minimum number of machines: " +
capacityAllocated + " started, " +
capacityMarkedForDeallocation + " marked for deallocation, " +
sla.getMinimumNumberOfMachines() + " is the required minimum number of machines."
);
machineShortage = unmarkAgentsMarkedForDeallocationToSatisfyMinimumNumberOfMachines(sla);
if (machineShortage > 0) {
//try allocate on new machines, that have other PUs on it.
allocateNumberOfMachines(sla, machineShortage);
machineShortage = getMachineShortageInOrderToReachMinimumNumberOfMachines(sla);
}
if (machineShortage > 0) {
// scale out to get to the minimum number of agents
CapacityRequirements capacityRequirements = new CapacityRequirements(
new NumberOfMachinesCapacityRequirement(machineShortage));
if (!sla.getMachineProvisioning().isStartMachineSupported()) {
throw new NeedToStartMoreGridServiceAgentsException(sla, state, capacityRequirements, pu);
}
ExactZonesConfig exactZones = new ExactZonesConfigurer().addZones(sla.getGridServiceAgentZones().getZones()).create();
FutureGridServiceAgent[] futureAgents = sla.getMachineProvisioning().startMachinesAsync(
capacityRequirements,
exactZones,
START_AGENT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
addFutureAgents(sla, futureAgents, capacityRequirements);
logger.info(
machineShortage+ " new machine(s) is scheduled to be started in order to reach the minimum of " +
sla.getMinimumNumberOfMachines() + " machines, for zones " + exactZones + ". " +
"Allocated machine agents are: " + getAllocatedCapacity(sla));
}
// even if machineShortage is 0, we still need to come back to this method
// to check the capacity is satisfied (scale out)
throw new MachinesSlaEnforcementInProgressException(getProcessingUnit());
}
else {
logger.debug("No action required in order to enforce machines sla. "+
"target="+target + "| " +
"allocated="+capacityAllocated.toDetailedString() + "| " +
"marked for deallocation="+capacityMarkedForDeallocation.toDetailedString() + "| " +
"#futures="+getNumberOfFutureAgents(sla) + " |" +
"#minimumMachines="+sla.getMinimumNumberOfMachines());
}
if (!getCapacityMarkedForDeallocation(sla).equalsZero()) {
// containers need to move to another machine
throw new GridServiceAgentSlaEnforcementPendingContainerDeallocationException(getProcessingUnit(), getCapacityMarkedForDeallocation(sla));
}
if (getNumberOfFutureAgents(sla) > 0) {
// new machines need to be started
throw new MachinesSlaEnforcementInProgressException(getProcessingUnit());
}
if (!getFutureStoppedMachines(sla).isEmpty()) {
// old machines need to complete shutdown
throw new MachinesSlaEnforcementInProgressException(getProcessingUnit());
}
}
/**
* @param sla
* @return
*/
private Collection<FutureStoppedMachine> getFutureStoppedMachines(CapacityMachinesSlaPolicy sla) {
return state.getMachinesGoingDown(getKey(sla));
}
private CapacityRequirements getCapacityShortage(CapacityMachinesSlaPolicy sla, CapacityRequirements target) throws MachinesSlaEnforcementInProgressException {
CapacityRequirements shortageCapacity =
target.subtractOrZero(getAllocatedCapacity(sla).getTotalAllocatedCapacity());
// take into account expected machines into shortage calculate
for (GridServiceAgentFutures futureAgents : getFutureAgents(sla)) {
CapacityRequirements expectedCapacityRequirements = futureAgents.getExpectedCapacity();
for (CapacityRequirement shortageCapacityRequirement : shortageCapacity.getRequirements()) {
CapacityRequirement expectedCapacityRequirement = expectedCapacityRequirements.getRequirement(shortageCapacityRequirement.getType());
if (!shortageCapacityRequirement.equalsZero() && expectedCapacityRequirement.equalsZero()) {
throw new MachinesSlaEnforcementInProgressException(getProcessingUnit(),
"Cannot determine if more machines need to be started, waiting for relevant " + getProcessingUnit() + " machines to start first to offset machine shortage.");
}
}
shortageCapacity =
shortageCapacity.subtractOrZero(expectedCapacityRequirements);
}
if (!shortageCapacity.equalsZero() && isFutureAgentsOfOtherSharedServices(sla)) {
throw new MachinesSlaEnforcementInProgressException(getProcessingUnit(),
"Cannot determine if more machines need to be started, waiting for other machines from same tenant to start first, to offset machine shortage.");
}
return shortageCapacity;
}
/**
* if minimum number of machines is breached then
* unmark machines that have only containers that are pending for deallocation
* @throws CannotDetermineIfNeedToStartMoreMachinesException
*/
private int unmarkAgentsMarkedForDeallocationToSatisfyMinimumNumberOfMachines(AbstractMachinesSlaPolicy sla) throws CannotDetermineIfNeedToStartMoreMachinesException {
int machineShortage = getMachineShortageInOrderToReachMinimumNumberOfMachines(sla);
final CapacityRequirementsPerAgent capacityAllocated = getAllocatedCapacity(sla);
CapacityRequirementsPerAgent capacityMarkedForDeallocation = getCapacityMarkedForDeallocation(sla);
if (!capacityMarkedForDeallocation.equalsZero()) {
// unmark machines that have only containers that are pending deallocation
for (String agentUid : capacityMarkedForDeallocation.getAgentUids()) {
if (machineShortage > 0 && !capacityAllocated.getAgentUids().contains(agentUid)) {
CapacityRequirements agentCapacity = capacityMarkedForDeallocation.getAgentCapacity(agentUid);
unmarkCapacityForDeallocation(sla, agentUid, agentCapacity);
machineShortage--;
if (logger.isInfoEnabled()) {
GridServiceAgent agent = pu.getAdmin().getGridServiceAgents().getAgentByUID(agentUid);
if (agent != null) {
logger.info(
"machine " + MachinesSlaUtils.machineToString(agent.getMachine()) + " "+
"is no longer marked for deallocation in order to reach the minimum of " +
sla.getMinimumNumberOfMachines() + " machines.");
}
}
}
}
}
return machineShortage;
}
/**
* @return minimumNumberOfMachines - allocatedMachines - futureMachines
* @throws CannotDetermineIfNeedToStartMoreMachinesException
*/
private int getMachineShortageInOrderToReachMinimumNumberOfMachines(AbstractMachinesSlaPolicy sla) throws CannotDetermineIfNeedToStartMoreMachinesException
{
boolean cannotDetermineExpectedNumberOfMachines = false;
final CapacityRequirementsPerAgent capacityAllocated = getAllocatedCapacity(sla);
int machineShortage = sla.getMinimumNumberOfMachines() - capacityAllocated.getAgentUids().size();
if (getNumberOfFutureAgents(sla) > 0) {
// take into account expected machines into shortage calculate
for (final GridServiceAgentFutures future : getFutureAgents(sla)) {
final int expectedNumberOfMachines = numberOfMachines(future.getExpectedCapacity());
if (expectedNumberOfMachines == 0) {
cannotDetermineExpectedNumberOfMachines = true;
}
else {
machineShortage -= expectedNumberOfMachines;
}
}
}
if (machineShortage > 0 && cannotDetermineExpectedNumberOfMachines) {
throw new CannotDetermineIfNeedToStartMoreMachinesException(getProcessingUnit(), machineShortage);
}
if (machineShortage < 0) {
machineShortage = 0;
}
return machineShortage;
}
/**
* Kill agents marked for deallocation that no longer manage containers.
* @param sla
* @param machineProvisioning
* @return
* @throws FailedToStopMachineException
* @throws FailedToStopGridServiceAgentException
*/
private void updateAgentsMarkedForDeallocationState(AbstractMachinesSlaPolicy sla) throws FailedToStopMachineException, FailedToStopGridServiceAgentException {
CapacityRequirementsPerAgent capacityMarkedForDeallocation = getCapacityMarkedForDeallocation(sla);
for (String agentUid : capacityMarkedForDeallocation.getAgentUids()) {
GridServiceAgent agent = pu.getAdmin().getGridServiceAgents().getAgentByUID(agentUid);
if (agent == null) {
deallocateAgentCapacity(sla, agentUid);
logger.info("pu " + pu.getName() + " agent " + agentUid + " has shutdown.");
}
else if (MachinesSlaUtils.getMemoryInMB(getAllocatedCapacity(sla).getAgentCapacityOrZero(agentUid))>=sla.getContainerMemoryCapacityInMB()) {
deallocateAgentCapacity(sla, agentUid);
logger.info("pu " + pu.getName() +" is still allocated on agent " + agentUid);
}
else if (MachinesSlaUtils.getNumberOfChildContainersForProcessingUnit(agent,pu) == 0) {
if (!sla.isStopMachineSupported()) {
logger.info("Agent running on machine " + agent.getMachine().getHostAddress()
+ " is not stopped since scale strategy " + sla.getScaleStrategyName()
+ " does not support automatic start/stop of machines");
deallocateAgentCapacity(sla, agentUid);
continue;
}
if (!MachinesSlaUtils.isAgentAutoShutdownEnabled(agent)) {
logger.info("Agent running on machine " + agent.getMachine().getHostAddress()
+ " is not stopped since it does not have the auto-shutdown flag");
deallocateAgentCapacity(sla, agentUid);
continue;
}
if (MachinesSlaUtils.isManagementRunningOnMachine(agent.getMachine())) {
logger.info("Agent running on machine " + agent.getMachine().getHostAddress()
+ " is not stopped since it is running management processes.");
deallocateAgentCapacity(sla, agentUid);
continue;
}
if (state.isAgentSharedWithOtherProcessingUnits(pu,agent.getUid())) {
// This is a bit like reference counting, the last pu to leave stops the machine
logger.info("Agent running on machine " + agent.getMachine().getHostAddress()
+ " is not stopped since it is shared with other processing units.");
deallocateAgentCapacity(sla, agentUid);
continue;
}
// double check that agent is not used
Set<Long> childProcessesIds = MachinesSlaUtils.getChildProcessesIds(agent);
if (!childProcessesIds.isEmpty()) {
// this is unexpected. We already checked for management processes and other PU processes.
logger.warn("Agent " + agent.getUid() + " on machine " + MachinesSlaUtils.machineToString(agent.getMachine())+ " cannot be shutdown due to the following child processes: " + childProcessesIds);
continue;
}
stopMachine(sla, agent);
}
}
cleanMachinesGoingDown(sla);
}
private void stopMachine(AbstractMachinesSlaPolicy sla, GridServiceAgent agent) {
if (!isAgentExistsInStoppedMachinesFutures(agent)) {
logger.info("Agent " + agent.getUid() + " on machine " + MachinesSlaUtils.machineToString(agent.getMachine())
+ " is no longer in use by any processing unit. "+
"It is going down!");
final NonBlockingElasticMachineProvisioning machineProvisioning = sla.getMachineProvisioning();
// The machineProvisioning might not be the same one that started this agent,
// Nevertheless, we expect it to be able to stop this agent.
FutureStoppedMachine stopMachineFuture = machineProvisioning.stopMachineAsync(
agent,
STOP_AGENT_TIMEOUT_SECONDS, TimeUnit.SECONDS);
addFutureStoppedMachine(sla, stopMachineFuture);
}
}
public boolean isAgentExistsInStoppedMachinesFutures(GridServiceAgent agent) {
/** {@link NonBlockingElasticMachineProvisioning#stopMachineAsync(GridServiceAgent, long, TimeUnit) may not be idempotent.
* Make sure stopAsync has not already been called on this agent.
*/
Collection<FutureStoppedMachine> machinesGoingDown = state.getMachinesGoingDown();
for (FutureStoppedMachine machineGoingDown : machinesGoingDown) {
if (machineGoingDown.getGridServiceAgent().getUid().equals(agent.getUid())) {
if (logger.isDebugEnabled()) {
logger.debug("Not calling stopMachine for agent with uid = " + agent.getUid()
+ " because a request was already sent to shut it down");
}
return true;
}
}
return false;
}
/**
* @param sla
* @param stopMachineFuture
*/
private void addFutureStoppedMachine(AbstractMachinesSlaPolicy sla, FutureStoppedMachine stopMachineFuture) {
state.addFutureStoppedMachine(getKey(sla), stopMachineFuture);
}
/**
* mark for deallocation machines that were not restricted but are now restricted for this PU
*/
private void updateRestrictedMachinesState(AbstractMachinesSlaPolicy sla) {
// mark for deallocation machines that are restricted for this PU
Map<String,List<String>> restrictedMachines = getRestrictedAgentUidsForPuWithReason(sla);
for(GridServiceAgent agent : MachinesSlaUtils.convertAgentUidsToAgents(getAllocatedCapacity(sla).getAgentUids(),pu.getAdmin())) {
String agentUid = agent.getUid();
if (restrictedMachines.containsKey(agentUid)) {
logger.info("Machine " + MachinesSlaUtils.machineToString(agent.getMachine())+ " is restricted for pu " + pu.getName() + " reason:" + restrictedMachines.get(agentUid));
markAgentCapacityForDeallocation(sla, agentUid);
}
}
}
/**
* mark for deallocation machines that were undiscovered by the lookup service
*/
private void updateFailedMachinesState(AbstractMachinesSlaPolicy sla) {
final GridServiceAgents agents = pu.getAdmin().getGridServiceAgents();
// mark for deallocation all failed machines
for(final String agentUid: getAllocatedCapacityUnfiltered(sla).getAgentUids()) {
if (agents.getAgentByUID(agentUid) == null) {
logger.warn("Agent " + agentUid + " was killed unexpectedly.");
markAgentCapacityForDeallocation(sla, agentUid);
}
}
}
private void cleanMachinesGoingDown(AbstractMachinesSlaPolicy sla) throws FailedToStopMachineException, FailedToStopGridServiceAgentException {
for (FutureStoppedMachine futureStoppedMachine : state.getMachinesGoingDown(getKey(sla))) {
GridServiceAgent agent = futureStoppedMachine.getGridServiceAgent();
Exception exception = null;
try {
if (futureStoppedMachine.isDone()) {
futureStoppedMachine.get();
if (agent.isDiscovered()) {
throw new IllegalStateException("Agent [" + agent.getUid() + "] should not be discovered at this point.");
}
removeFutureStoppedMachine(sla, futureStoppedMachine);
}
} catch (ExecutionException e) {
// if runtime or error propagate exception "as-is"
Throwable cause = e.getCause();
if (cause instanceof TimeoutException ||
cause instanceof ElasticMachineProvisioningException ||
cause instanceof ElasticGridServiceAgentProvisioningException ||
cause instanceof InterruptedException) {
// expected exception
exception = e;
}
else {
throw new IllegalStateException("Unexpected Exception from machine provisioning.",e);
}
} catch (TimeoutException e) {
// expected exception
exception = e;
}
if (exception != null) {
if (logger.isDebugEnabled()) {
if (agent.isDiscovered()) {
logger.debug("Agent [" + agent.getUid() + "] is still discovered. Another processing unit may use it if needed."
+ "if not, another attempt to shut it down will be executed.");
} else {
logger.debug("agent [" + agent.getUid() + "] is not discovered. but an error happened while terminating the machine");
}
}
removeFutureStoppedMachine(sla, futureStoppedMachine);
if (exception instanceof ElasticGridServiceAgentProvisioningException) {
throw new FailedToStopGridServiceAgentException(pu, agent,exception);
}
throw new FailedToStopMachineException(pu, agent, exception);
}
}
}
/**
* @param sla
* @param futureStoppedMachine
*/
private void removeFutureStoppedMachine(AbstractMachinesSlaPolicy sla, FutureStoppedMachine futureStoppedMachine) {
state.removeFutureStoppedMachine(getKey(sla), futureStoppedMachine);
}
/**
* Move future agents that completed startup, from the future state to allocated state.
*
* This is done by removing the future state, and adding pu allocation state on these machines.
* @throws InconsistentMachineProvisioningException
* @throws UnexpectedShutdownOfNewGridServiceAgentException
* @throws FailedToStartNewMachineException
* @throws StartedTooManyMachinesException
* @throws FailedToDiscoverMachinesException
* @throws WaitingForDiscoveredMachinesException
*/
private void updateFutureAgentsState(AbstractMachinesSlaPolicy sla) throws GridServiceAgentSlaEnforcementInProgressException, MachinesSlaEnforcementInProgressException {
// each futureAgents object contains an array of FutureGridServiceAgent
// only when all future in the array is done, the futureAgents object is done.
Collection<GridServiceAgentFutures> doneFutureAgentss = getAllDoneFutureAgents(sla);
Collection<GridServiceAgent> discoveredAgents = sla.getDiscoveredMachinesCache().getDiscoveredAgents();
for (GridServiceAgentFutures doneFutureAgents : doneFutureAgentss) {
for (FutureGridServiceAgent doneFutureAgent : doneFutureAgents.getFutureGridServiceAgents()) {
try {
validateHealthyAgent(
sla,
discoveredAgents,
doneFutureAgent);
}
catch (InconsistentMachineProvisioningException e) {
// should be fixed by next time we get here
// do not remove the future
throw e;
} catch (FailedToStartNewMachineException e) {
// we remove the future, next time we wont find it
doneFutureAgents.removeFutureAgent(doneFutureAgent);
if (sla.isUndeploying()) {
logger.info("Ignoring failure to start new machine, since undeploy is in progress",e);
}
else {
throw e;
}
} catch (UnexpectedShutdownOfNewGridServiceAgentException e) {
// we remove the future, next time we wont find it
doneFutureAgents.removeFutureAgent(doneFutureAgent);
if (sla.isUndeploying()) {
logger.info("Ignoring failure to start new grid service agent, since undeploy is in progress",e);
}
else {
throw e;
}
}
}
}
for (GridServiceAgentFutures doneFutureAgents : doneFutureAgentss) {
Collection<GridServiceAgent> healthyAgents = doneFutureAgents.getGridServiceAgents();
if (healthyAgents.size() > 0) {
if (logger.isInfoEnabled()) {
logger.info("Agents that were started by " +
"machineProvisioning class=" + sla.getMachineProvisioning().getClass() + " " +
"new agents: " + MachinesSlaUtils.machinesToString(healthyAgents) + " " +
"provisioned agents:" + MachinesSlaUtils.machinesToString(discoveredAgents));
}
CapacityRequirementsPerAgent unallocatedCapacity =
getUnallocatedCapacityIncludeNewMachines(sla, healthyAgents);
//update state 1: allocate capacity based on expectation (even if it was not met)
if (numberOfMachines(doneFutureAgents.getExpectedCapacity()) > 0) {
allocateNumberOfMachines(
sla,
numberOfMachines(doneFutureAgents.getExpectedCapacity()),
unallocatedCapacity);
}
else if (!doneFutureAgents.getExpectedCapacity().equalsZero()) {
allocateManualCapacity(
sla,
doneFutureAgents.getExpectedCapacity(),
unallocatedCapacity);
}
else {
throw new IllegalStateException(
"futureAgents expected capacity malformed. "+
"doneFutureAgents=" + doneFutureAgents.getExpectedCapacity());
}
}
//update state 2: remove futures from list
removeFutureAgents(sla, doneFutureAgents);
// update state 3:
// mark for shutdown new machines that are not marked by any processing unit
// these are all future agents that should have been used by the binpacking solver.
// The fact that they have not been used suggests that the number of started
// machines by machineProvisioning is more than we asked for.
Collection<GridServiceAgent> unallocatedAgents = new ArrayList<GridServiceAgent>();
for (GridServiceAgent newAgent : healthyAgents) {
String agentUid = newAgent.getUid();
CapacityRequirements agentCapacity = getAllocatedCapacity(sla).getAgentCapacityOrZero(agentUid);
if (agentCapacity.equalsZero()) {
unallocatedAgents.add(newAgent);
}
}
if (unallocatedAgents.size() > 0) {
if (!sla.getMachineProvisioning().isStartMachineSupported()) {
logger.info(
"Agents " + MachinesSlaUtils.machinesToString(unallocatedAgents) +
" are not needed for pu " + pu.getName());
}
else {
StartedTooManyMachinesException tooManyMachinesExceptions = new StartedTooManyMachinesException(pu,unallocatedAgents);
logger.warn(
"Stopping machines " + MachinesSlaUtils.machinesToString(unallocatedAgents) + " "+
"Agents provisioned by cloud: " + discoveredAgents,
tooManyMachinesExceptions);
for (GridServiceAgent unallocatedAgent : unallocatedAgents) {
stopMachine(sla,unallocatedAgent);
}
throw tooManyMachinesExceptions;
}
}
}
}
private CapacityRequirementsPerAgent getUnallocatedCapacityIncludeNewMachines(
AbstractMachinesSlaPolicy sla,
Collection<GridServiceAgent> newMachines ) throws MachinesSlaEnforcementInProgressException {
// unallocated capacity = unallocated capacity + new machines
CapacityRequirementsPerAgent unallocatedCapacity = getUnallocatedCapacity(sla);
for (GridServiceAgent newAgent : newMachines) {
if (unallocatedCapacity.getAgentUids().contains(newAgent.getUid())) {
throw new IllegalStateException(
"unallocated capacity cannot contain future agents. "+
"unallocatedCapacity="+unallocatedCapacity+
"newAgent.getUid()="+newAgent.getUid()+
"sla.agentZones="+sla.getGridServiceAgentZones());
}
CapacityRequirements newAgentCapacity = MachinesSlaUtils.getMachineTotalCapacity(newAgent,sla);
if (logger.isInfoEnabled()) {
logger.info("Agent started and provisioned succesfully on a new machine " + MachinesSlaUtils.machineToString(newAgent.getMachine())+ " has "+ newAgentCapacity);
}
if (MachinesSlaUtils.getMemoryInMB(newAgentCapacity) < sla.getContainerMemoryCapacityInMB()) {
logger.warn("New agent " + MachinesSlaUtils.machineToString(newAgent.getMachine()) + " has only "
+ newAgentCapacity
+ " unreserved free resources, which is not enough for even one container that requires "
+ sla.getContainerMemoryCapacityInMB() + "MB");
}
unallocatedCapacity =
unallocatedCapacity.add(
newAgent.getUid(),
newAgentCapacity);
}
return unallocatedCapacity;
}
/**
* @param sla
* @param discoveredAgents
* @return true - if removed future agent from the state
* @throws InconsistentMachineProvisioningException
* @throws UnexpectedShutdownOfNewGridServiceAgentException
* @throws MachinesSlaEnforcementInProgressException
* @throws FailedToStartNewGridServiceAgentException
* @throws FailedMachineProvisioningException
*/
private void validateHealthyAgent(
AbstractMachinesSlaPolicy sla,
Collection<GridServiceAgent> discoveredAgents,
FutureGridServiceAgent futureAgent)
throws UnexpectedShutdownOfNewGridServiceAgentException, InconsistentMachineProvisioningException, MachinesSlaEnforcementInProgressException, FailedToStartNewGridServiceAgentException {
final NonBlockingElasticMachineProvisioning machineProvisioning = sla.getMachineProvisioning();
final Collection<String> usedAgentUids = state.getAllUsedAgentUids();
final Collection<String> usedAgentUidsForPu = state.getUsedAgentUids(getKey(sla));
GridServiceAgent newAgent = null;
{
Exception exception = null;
try {
newAgent = futureAgent.get();
} catch (ExecutionException e) {
// if runtime or error propagate exception "as-is"
Throwable cause = e.getCause();
if (cause instanceof TimeoutException || cause instanceof ElasticMachineProvisioningException || cause instanceof ElasticGridServiceAgentProvisioningException || cause instanceof InterruptedException) {
// expected exception
exception = e;
}
else {
throw new IllegalStateException("Unexpected Exception from machine provisioning.",e);
}
} catch (TimeoutException e) {
// expected exception
exception = e;
}
if (exception != null) {
if (exception instanceof ElasticGridServiceAgentProvisioningException) {
throw new FailedToStartNewGridServiceAgentException(pu, exception);
}
throw new FailedToStartNewMachineException(pu, exception);
}
}
if (newAgent == null) {
throw new IllegalStateException("Machine provisioning future is done without exception, but returned a null agent");
}
GSAReservationId reservationId = ((InternalGridServiceAgent)newAgent).getReservationId();
if (reservationId == null) {
throw new IllegalStateException("Machine provisioning future is done without exception, but returned a null reservationId from the agent");
}
if (!reservationId.equals(futureAgent.getReservationId())) {
throw new IllegalStateException("Machine provisioning future is done without exception, but returned an agent with the wrong reservationId");
}
if (!newAgent.isDiscovered()) {
UnexpectedShutdownOfNewGridServiceAgentException unexpectedShutdownException = new UnexpectedShutdownOfNewGridServiceAgentException(newAgent.getMachine(), pu);
if (logger.isWarnEnabled()) {
logger.warn("Failed to start agent on new machine.", unexpectedShutdownException);
}
throw unexpectedShutdownException;
}
if (usedAgentUidsForPu.contains(newAgent.getUid())) {
//some nasty bug in machine provisioning implementation
throw new IllegalStateException(
"Machine provisioning for " + pu.getName() + " "+
"has provided the machine " + MachinesSlaUtils.machineToString(newAgent.getMachine()) +
" which is already in use by this PU."+
"The machine is ignored");
}
if (usedAgentUids.contains(newAgent.getUid())) {
//some nasty bug in machine provisioning implementation
throw new IllegalStateException(
"Machine provisioning for " + pu.getName() + " "+
"has provided the machine " + MachinesSlaUtils.machineToString(newAgent.getMachine()) +
" which is already in use by another PU."+
"This machine is ignored");
}
if (!discoveredAgents.contains(newAgent)) {
//Handle the case of a new machine that was started with @{link {@link NonBlockingElasticMachineProvisioning#startMachinesAsync(CapacityRequirements, long, TimeUnit)}
//but still not in the list returned by {@link NonBlockingElasticMachineProvisioning#getDiscoveredMachinesAsync(long, TimeUnit)}
final NonBlockingElasticMachineProvisioning oldMachineProvisioning = futureAgent.getMachineProvisioning();
if (
// checking for a bug in the implementation of machineProvisioning
oldMachineProvisioning != null &&
!MachinesSlaUtils.isAgentConformsToMachineProvisioningConfig(newAgent, oldMachineProvisioning.getConfig()) &&
// ignore error if machine provisioning was modified
oldMachineProvisioning == machineProvisioning) {
throw new IllegalStateException(
MachinesSlaUtils.machineToString(newAgent.getMachine()) + " has been started but with the wrong zone or management settings. "+
"newagent.zones="+newAgent.getExactZones() + " "+
"oldMachineProvisioning.config.zones="+oldMachineProvisioning.getConfig().getGridServiceAgentZones());
}
// providing a grace period for provisionedAgents to update.
throw new InconsistentMachineProvisioningException(getProcessingUnit(), newAgent);
}
}
/**
* Eagerly allocates all unallocated capacity that match the specified SLA
* @throws FailedToDiscoverMachinesException
* @throws WaitingForDiscoveredMachinesException
*/
private void allocateEagerCapacity(AbstractMachinesSlaPolicy sla) throws MachinesSlaEnforcementInProgressException {
CapacityRequirementsPerAgent unallocatedCapacity = getUnallocatedCapacity(sla);
// limit the memory to the maximum possible by this PU
long maxAllocatedMemoryForPu = getMaximumNumberOfMachines(sla)*sla.getContainerMemoryCapacityInMB();
long allocatedMemoryForPu = MachinesSlaUtils.getMemoryInMB(getAllocatedCapacity(sla).getTotalAllocatedCapacity());
// validate not breached max eager capacity
if (allocatedMemoryForPu > maxAllocatedMemoryForPu) {
throw new IllegalStateException(
"maxAllocatedMemoryForPu="+getMaximumNumberOfMachines(sla)+"*"+sla.getContainerMemoryCapacityInMB()+"="+
maxAllocatedMemoryForPu+" "+
"cannot be smaller than allocatedMemoryForPu="+getAllocatedCapacity(sla).toDetailedString());
}
long unallocatedMemory = MachinesSlaUtils.getMemoryInMB(unallocatedCapacity.getTotalAllocatedCapacity());
long memoryToAllocate = Math.min(maxAllocatedMemoryForPu - allocatedMemoryForPu, unallocatedMemory);
CapacityRequirements capacityToAllocate =
unallocatedCapacity.getTotalAllocatedCapacity()
.set(new MemoryCapacityRequirement(memoryToAllocate));
if (logger.isDebugEnabled()) {
logger.debug(
"capacityToAllocate=" + capacityToAllocate + " "+
"maxAllocatedMemoryForPu="+maxAllocatedMemoryForPu + " "+
"unallocatedCapacity="+unallocatedCapacity.toDetailedString() );
}
// allocate memory and CPU eagerly
if (!capacityToAllocate.equalsZero()) {
allocateManualCapacity(sla, capacityToAllocate, unallocatedCapacity);
}
//validate not breached max eager capacity
long allocatedMemoryForPuAfter = MachinesSlaUtils.getMemoryInMB(getAllocatedCapacity(sla).getTotalAllocatedCapacity());
if ( allocatedMemoryForPuAfter > maxAllocatedMemoryForPu) {
throw new IllegalStateException("allocatedMemoryForPuAfter="+allocatedMemoryForPuAfter+" greater than "+
"maxAllocatedMemoryForPu="+getMaximumNumberOfMachines(sla)+"*"+sla.getContainerMemoryCapacityInMB()+"="+maxAllocatedMemoryForPu+
"allocatedMemoryForPu="+allocatedMemoryForPu+"="+getAllocatedCapacity(sla).toDetailedString()+ " "+
"capacityToAllocate=" + capacityToAllocate + " "+
"maxAllocatedMemoryForPu="+maxAllocatedMemoryForPu + " "+
"unallocatedCapacity="+unallocatedCapacity.toDetailedString() );
}
}
/**
* Allocates the specified capacity on unallocated capacity that match the specified SLA
* @throws MachinesSlaEnforcementInProgressException
*/
private void allocateManualCapacity(AbstractMachinesSlaPolicy sla, CapacityRequirements capacityToAllocate) throws MachinesSlaEnforcementInProgressException {
CapacityRequirementsPerAgent unallocatedCapacity = getUnallocatedCapacity(sla);
allocateManualCapacity(sla, capacityToAllocate, unallocatedCapacity);
}
/**
* Finds an agent that matches the SLA, and can satisfy the specified capacity to allocate.
*
* The algorithm goes over all such machines and chooses the machine that after the allocation would have
* the least amount of memory. So continuous unallocated blocks is left for the next allocation, which could be bigger.
*
* @param capacityToAllocate - the missing capacity that requires allocation on shared machines.
* @return the remaining capacity left for allocation(the rest has been allocated already)
*/
private void allocateManualCapacity(AbstractMachinesSlaPolicy sla, CapacityRequirements capacityToAllocate, CapacityRequirementsPerAgent unallocatedCapacity) {
final BinPackingSolver solver = createBinPackingSolver(sla , unallocatedCapacity);
solver.solveManualCapacityScaleOut(capacityToAllocate);
allocateCapacity(sla, solver.getAllocatedCapacityResult());
markCapacityForDeallocation(sla, solver.getDeallocatedCapacityResult());
}
private void deallocateManualCapacity(AbstractMachinesSlaPolicy sla, CapacityRequirements capacityToDeallocate) throws MachinesSlaEnforcementInProgressException {
CapacityRequirementsPerAgent unallocatedCapacity = getUnallocatedCapacity(sla);
final BinPackingSolver solver = createBinPackingSolver(sla , unallocatedCapacity);
solver.solveManualCapacityScaleIn(capacityToDeallocate);
allocateCapacity(sla, solver.getAllocatedCapacityResult());
markCapacityForDeallocation(sla, solver.getDeallocatedCapacityResult());
}
private void allocateNumberOfMachines(AbstractMachinesSlaPolicy sla, int numberOfFreeAgents) throws MachinesSlaEnforcementInProgressException {
CapacityRequirementsPerAgent unallocatedCapacity = getUnallocatedCapacity(sla);
allocateNumberOfMachines(sla, numberOfFreeAgents, unallocatedCapacity);
}
/**
* Finds an agent that matches the SLA, and can satisfy the specified capacity to allocate.
*
* The algorithm goes over all such machines and chooses the machine that after the allocation would have
* the least amount of memory. So continuous unallocated blocks is left for the next allocation, which could be bigger.
*
* @param numberOfMachines - the missing number of machines that are required.
* @return the remaining number of machines (the rest has been allocated already)
*/
private void allocateNumberOfMachines(AbstractMachinesSlaPolicy sla, int numberOfMachines, CapacityRequirementsPerAgent unallocatedCapacity) {
final BinPackingSolver solver = createBinPackingSolver(sla, unallocatedCapacity);
solver.solveNumberOfMachines(numberOfMachines);
allocateCapacity(sla, solver.getAllocatedCapacityResult());
markCapacityForDeallocation(sla, solver.getDeallocatedCapacityResult());
}
private BinPackingSolver createBinPackingSolver(AbstractMachinesSlaPolicy sla, CapacityRequirementsPerAgent unallocatedCapacity) {
final BinPackingSolver solver = new BinPackingSolver();
solver.setLogger(logger);
solver.setContainerMemoryCapacityInMB(sla.getContainerMemoryCapacityInMB());
solver.setUnallocatedCapacity(unallocatedCapacity);
solver.setAllocatedCapacityForPu(getAllocatedCapacity(sla));
solver.setMaxAllocatedMemoryCapacityOfPuInMB(getMaximumNumberOfMachines(sla)*sla.getContainerMemoryCapacityInMB());
solver.setMaxAllocatedMemoryCapacityOfPuPerMachineInMB(sla.getMaximumNumberOfContainersPerMachine()*sla.getContainerMemoryCapacityInMB());
solver.setMinimumNumberOfMachines(sla.getMinimumNumberOfMachines());
// the higher the priority the less likely the machine to be scaled in.
Map<String,Long> scaleInPriorityPerAgentUid = new HashMap<String,Long>();
GridServiceAgents agents = pu.getAdmin().getGridServiceAgents();
final long FIRST_PRIORITY = Long.MAX_VALUE;
final long SECOND_PRIORITY = FIRST_PRIORITY - 1;
final long THIRD_PRIORITY = SECOND_PRIORITY - 1;
final long FOURTH_PRIORITY = THIRD_PRIORITY - 1;
final long now = System.currentTimeMillis();
for (String agentUid : getAllocatedCapacity(sla).getAgentUids()) {
long agentOrderToDeallocateContainers = 0;
GridServiceAgent agent = agents.getAgentByUID(agentUid);
if (agent != null) {
if (MachinesSlaUtils.isManagementRunningOnMachine(agent.getMachine())) {
// machine has management on it. It will not shutdown anyway, so try to scale in other
// machines first.
agentOrderToDeallocateContainers = FIRST_PRIORITY;
}
else if (state.isAgentSharedWithOtherProcessingUnits(pu, agentUid)) {
// machine has other PUs on it.
// try to scale in other machines first.
agentOrderToDeallocateContainers = SECOND_PRIORITY;
}
else if (!MachinesSlaUtils.isAgentAutoShutdownEnabled(agent)) {
// machine cannot be shutdown by ESM
// try scaling in machines that we can shutdown first.
agentOrderToDeallocateContainers = THIRD_PRIORITY;
}
else {
long startTime = agent.getVirtualMachine().getDetails().getStartTime();
long runDuration = now - startTime;
if (runDuration > FOURTH_PRIORITY) {
runDuration = FOURTH_PRIORITY;
}
//The more time the agent is running the higher the priority the less it should be shutdown
agentOrderToDeallocateContainers = runDuration;
}
}
scaleInPriorityPerAgentUid.put(agentUid, agentOrderToDeallocateContainers);
}
solver.setAgentAllocationPriority(scaleInPriorityPerAgentUid);
return solver;
}
/**
* Calculates the total unused capacity (memory / CPU) on machines (that some of its capacity is already allocated by some PU).
* Returns only machines that match the specified SLA.
* @throws MachinesSlaEnforcementInProgressException
*/
private CapacityRequirementsPerAgent getUnallocatedCapacity(AbstractMachinesSlaPolicy sla) throws MachinesSlaEnforcementInProgressException {
CapacityRequirementsPerAgent physicalCapacity = getPhysicalProvisionedCapacity(sla);
CapacityRequirementsPerAgent usedCapacity = state.getAllUsedCapacity();
Map<String,List<String>> restrictedAgentUids = getRestrictedAgentUidsForPuWithReason(sla);
CapacityRequirementsPerAgent unallocatedCapacity = new CapacityRequirementsPerAgent();
for (String agentUid : physicalCapacity.getAgentUids()) {
if (!restrictedAgentUids.containsKey(agentUid)) {
// machine matches isolation and zone SLA
CapacityRequirements unallocatedCapacityOnAgent =
physicalCapacity.getAgentCapacity(agentUid)
.subtract(usedCapacity.getAgentCapacityOrZero(agentUid));
unallocatedCapacity =
unallocatedCapacity.add(agentUid, unallocatedCapacityOnAgent);
}
}
if (logger.isDebugEnabled()) {
logger.debug("physicalCapacity="+physicalCapacity.toDetailedString()+" usedCapacity="+usedCapacity.toDetailedString()+" restrictedAgentUids="+restrictedAgentUids+" unallocatedCapacity="+unallocatedCapacity.toDetailedString());
}
return unallocatedCapacity;
}
/**
* Calculates the total maximum capacity (memory/CPU) on all sla.getDiscoveredMachinesCache().getDiscoveredAgents()
* @throws MachinesSlaEnforcementInProgressException
*/
private CapacityRequirementsPerAgent getPhysicalProvisionedCapacity(AbstractMachinesSlaPolicy sla) throws MachinesSlaEnforcementInProgressException {
CapacityRequirementsPerAgent totalCapacity = new CapacityRequirementsPerAgent();
for (final GridServiceAgent agent: sla.getDiscoveredMachinesCache().getDiscoveredAgents()) {
if (agent.isDiscovered()) {
totalCapacity = totalCapacity.add(
agent.getUid(),
MachinesSlaUtils.getMachineTotalCapacity(agent, sla));
}
}
return totalCapacity;
}
private static int numberOfMachines(CapacityRequirements capacityRequirements) {
return capacityRequirements.getRequirement(new NumberOfMachinesCapacityRequirement().getType()).getNumberOfMachines();
}
private CapacityRequirementsPerAgent getCapacityMarkedForDeallocation(AbstractMachinesSlaPolicy sla) {
return state.getCapacityMarkedForDeallocation(getKey(sla));
}
private Map<String,List<String>> getRestrictedAgentUidsForPuWithReason(AbstractMachinesSlaPolicy sla) {
return state.getRestrictedAgentUids(getKey(sla));
}
private void setMachineIsolation(AbstractMachinesSlaPolicy sla) {
state.setMachineIsolation(getKey(sla), sla.getMachineIsolation());
}
private int getNumberOfFutureAgents(AbstractMachinesSlaPolicy sla) {
return state.getNumberOfFutureAgents(getKey(sla));
}
private void unmarkCapacityForDeallocation(CapacityMachinesSlaPolicy sla, String agentUid, CapacityRequirements agentCapacity) {
state.unmarkCapacityForDeallocation(getKey(sla), agentUid, agentCapacity);
}
private void addFutureAgents(CapacityMachinesSlaPolicy sla,
FutureGridServiceAgent[] futureAgents, CapacityRequirements shortageCapacity) {
state.addFutureAgents(getKey(sla), futureAgents, shortageCapacity);
}
private Collection<GridServiceAgentFutures> getFutureAgents(AbstractMachinesSlaPolicy sla) {
return state.getFutureAgents(getKey(sla));
}
private boolean isFutureAgentsOfOtherSharedServices(AbstractMachinesSlaPolicy sla) {
return state.isFutureAgentsOfOtherSharedServices(getKey(sla));
}
private void unmarkCapacityForDeallocation(AbstractMachinesSlaPolicy sla, String agentUid, CapacityRequirements agentCapacity) {
state.unmarkCapacityForDeallocation(getKey(sla), agentUid, agentCapacity);
}
private void deallocateAgentCapacity(AbstractMachinesSlaPolicy sla, String agentUid) {
state.deallocateAgentCapacity(getKey(sla), agentUid);
}
private void markAgentCapacityForDeallocation(AbstractMachinesSlaPolicy sla, String agentUid) {
state.markAgentCapacityForDeallocation(getKey(sla), agentUid);
}
private Collection<GridServiceAgentFutures> getAllDoneFutureAgents(AbstractMachinesSlaPolicy sla) {
return state.getAllDoneFutureAgents(getKey(sla));
}
private void removeFutureAgents(AbstractMachinesSlaPolicy sla, GridServiceAgentFutures doneFutureAgents) {
state.removeFutureAgents(getKey(sla), doneFutureAgents);
}
private void allocateCapacity(AbstractMachinesSlaPolicy sla, CapacityRequirementsPerAgent capacityToAllocate) {
GridServiceAgents gridServiceAgents = pu.getAdmin().getGridServiceAgents();
for (String agentUid : capacityToAllocate.getAgentUids()) {
if (gridServiceAgents.getAgentByUID(agentUid) == null) {
throw new IllegalArgumentException("Cannot allocate capacity on a removed agent " + agentUid);
}
state.allocateCapacity(getKey(sla), agentUid, capacityToAllocate.getAgentCapacity(agentUid));
if (logger.isInfoEnabled()) {
logger.info("allocating capacity "+capacityToAllocate.getAgentCapacity(agentUid) + " "+
"on " + MachinesSlaUtils.agentToString(pu.getAdmin(), agentUid) + " "+
"for " + pu.getName() + " "+sla.getGridServiceAgentZones());
}
}
}
private void markCapacityForDeallocation(AbstractMachinesSlaPolicy sla, CapacityRequirementsPerAgent capacityToMarkForDeallocation) {
for (String agentUid : capacityToMarkForDeallocation.getAgentUids()) {
state.markCapacityForDeallocation(getKey(sla), agentUid, capacityToMarkForDeallocation.getAgentCapacity(agentUid));
if (logger.isInfoEnabled()) {
logger.info("marking capacity for deallocation "+capacityToMarkForDeallocation.getAgentCapacity(agentUid) + " on " + MachinesSlaUtils.agentToString(pu.getAdmin(), agentUid));
}
}
}
private void completedStateRecovery(AbstractMachinesSlaPolicy sla) {
state.completedStateRecovery(getKey(sla));
}
private boolean isCompletedStateRecovery(AbstractMachinesSlaPolicy sla) {
return state.isCompletedStateRecovery(getKey(sla));
}
@Override
public void recoveredStateOnEsmStart(ProcessingUnit otherPu) {
state.recoveredStateOnEsmStart(otherPu);
}
@Override
public RecoveryState getRecoveredStateOnEsmStart(ProcessingUnit otherPu) {
return state.getRecoveredStateOnEsmStart(otherPu);
}
@Override
public Set<ZonesConfig> getGridServiceAgentsZones() {
return state.getGridServiceAgentsZones(pu);
}
@Override
public Set<ZonesConfig> getUndeployedGridServiceAgentsZones() {
return state.getUndeployedGridServiceAgentsZones(pu);
}
@Override
public boolean replaceAllocatedCapacity(AbstractMachinesSlaPolicy sla) {
return state.replaceAllocatedCapacity(getKey(sla), pu.getAdmin());
}
@Override
public void beforeUndeployedProcessingUnit(ProcessingUnit pu) {
state.beforeUndeployProcessingUnit(pu);
}
@Override
public void afterUndeployedProcessingUnit(ProcessingUnit pu) {
state.afterUndeployProcessingUnit(pu);
}
} | Added more logging for investigating wrong reservationId
svn path=/xap/trunk/openspaces/; revision=140082
Former-commit-id: 6def36c1ebff9e58caf698a5f69fbee0b521a0e5 | src/main/java/org/openspaces/grid/gsm/machines/DefaultMachinesSlaEnforcementEndpoint.java | Added more logging for investigating wrong reservationId | <ide><path>rc/main/java/org/openspaces/grid/gsm/machines/DefaultMachinesSlaEnforcementEndpoint.java
<ide> if (newAgent == null) {
<ide> throw new IllegalStateException("Machine provisioning future is done without exception, but returned a null agent");
<ide> }
<del> GSAReservationId reservationId = ((InternalGridServiceAgent)newAgent).getReservationId();
<del> if (reservationId == null) {
<add>
<add> GSAReservationId actualReservationId = ((InternalGridServiceAgent)newAgent).getReservationId();
<add> if (actualReservationId == null) {
<ide> throw new IllegalStateException("Machine provisioning future is done without exception, but returned a null reservationId from the agent");
<ide> }
<del> if (!reservationId.equals(futureAgent.getReservationId())) {
<del> throw new IllegalStateException("Machine provisioning future is done without exception, but returned an agent with the wrong reservationId");
<add> GSAReservationId expectedReservationId = futureAgent.getReservationId();
<add> if (!actualReservationId.equals(expectedReservationId)) {
<add> final String ipAddress = newAgent.getMachine().getHostAddress();
<add> throw new IllegalStateException(
<add> "Machine provisioning future is done without exception, but returned an agent(ip="+ipAddress+") "+
<add> "with the wrong reservationId: expected="+expectedReservationId+ " actual="+actualReservationId);
<ide> }
<ide>
<ide> if (!newAgent.isDiscovered()) { |
|
Java | epl-1.0 | 8012d2ddad26a49373aca9ce7174c158d11c7d23 | 0 | mondo-project/mondo-demo-wt | /**
*/
package WTSpec4M.presentation;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.ui.ViewerPane;
import org.eclipse.emf.common.ui.dialogs.ResourceDialog;
import org.eclipse.emf.common.ui.editor.ProblemEditorPart;
import org.eclipse.emf.common.ui.viewer.IViewerProvider;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EContentAdapter;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.edit.provider.AdapterFactoryItemDelegator;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory;
import org.eclipse.emf.edit.ui.action.EditingDomainActionBarContributor;
import org.eclipse.emf.edit.ui.celleditor.AdapterFactoryTreeEditor;
import org.eclipse.emf.edit.ui.dnd.EditingDomainViewerDropAdapter;
import org.eclipse.emf.edit.ui.dnd.LocalTransfer;
import org.eclipse.emf.edit.ui.dnd.ViewerDragAdapter;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.edit.ui.provider.UnwrappingSelectionProvider;
import org.eclipse.emf.edit.ui.util.EditUIUtil;
import org.eclipse.emf.edit.ui.view.ExtendedPropertySheetPage;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.rap.rwt.RWT;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheet;
import org.eclipse.ui.views.properties.PropertySheetPage;
import org.mondo.collaboration.online.core.LensActivator;
import org.mondo.collaboration.online.core.OnlineLeg;
import org.mondo.collaboration.online.core.OnlineLeg.LegCommand;
import org.mondo.collaboration.online.rap.widgets.ModelExplorer;
import org.mondo.collaboration.online.rap.widgets.ModelLogView;
import org.mondo.collaboration.online.rap.widgets.UISessionManager;
import org.mondo.collaboration.security.lens.bx.online.OnlineCollaborationSession;
import org.mondo.collaboration.security.lens.bx.online.OnlineCollaborationSession.Leg;
import com.google.common.util.concurrent.FutureCallback;
import WTSpec4M.provider.WTSpec4MItemProviderAdapterFactory;
/**
* This is an example of a WTSpec4M model editor. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
public class WTSpec4MEditor extends MultiPageEditorPart
implements IEditingDomainProvider, ISelectionProvider, IMenuListener, IViewerProvider {
/**
* The filters for file extensions supported by the editor. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public static final List<String> FILE_EXTENSION_FILTERS = prefixExtensions(WTSpec4MModelWizard.FILE_EXTENSIONS,
"*.");
/**
* Returns a new unmodifiable list containing prefixed versions of the
* extensions in the given list. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
private static List<String> prefixExtensions(List<String> extensions, String prefix) {
List<String> result = new ArrayList<String>();
for (String extension : extensions) {
result.add(prefix + extension);
}
return Collections.unmodifiableList(result);
}
/**
* This keeps track of the editing domain that is used to track all changes
* to the model. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected AdapterFactoryEditingDomain editingDomain;
/**
* This is the one adapter factory used for providing views of the model.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ComposedAdapterFactory adapterFactory;
/**
* This is the content outline page. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected IContentOutlinePage contentOutlinePage;
/**
* This is a kludge... <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected IStatusLineManager contentOutlineStatusLineManager;
/**
* This is the content outline page's viewer. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected TreeViewer contentOutlineViewer;
/**
* This is the property sheet page. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected List<PropertySheetPage> propertySheetPages = new ArrayList<PropertySheetPage>();
/**
* This is the viewer that shadows the selection in the content outline. The
* parent relation must be correctly defined for this to work. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected TreeViewer selectionViewer;
/**
* This inverts the roll of parent and child in the content provider and
* show parents as a tree. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected TreeViewer parentViewer;
/**
* This shows how a tree view works. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected TreeViewer treeViewer;
/**
* This shows how a list view works. A list viewer doesn't support icons.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ListViewer listViewer;
/**
* This shows how a table view works. A table can be used as a list with
* icons. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected TableViewer tableViewer;
/**
* This shows how a tree view with columns works. <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected TreeViewer treeViewerWithColumns;
/**
* This keeps track of the active viewer pane, in the book. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ViewerPane currentViewerPane;
/**
* This keeps track of the active content viewer, which may be either one of
* the viewers in the pages or the content outline viewer. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Viewer currentViewer;
/**
* This listens to which ever viewer is active. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected ISelectionChangedListener selectionChangedListener;
/**
* This keeps track of all the
* {@link org.eclipse.jface.viewers.ISelectionChangedListener}s that are
* listening to this editor. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Collection<ISelectionChangedListener> selectionChangedListeners = new ArrayList<ISelectionChangedListener>();
/**
* This keeps track of the selection of the editor as a whole. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ISelection editorSelection = StructuredSelection.EMPTY;
/**
* This listens for when the outline becomes active <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected IPartListener partListener = new IPartListener() {
public void partActivated(IWorkbenchPart p) {
if (p instanceof ContentOutline) {
if (((ContentOutline) p).getCurrentPage() == contentOutlinePage) {
getActionBarContributor().setActiveEditor(WTSpec4MEditor.this);
setCurrentViewer(contentOutlineViewer);
}
} else if (p instanceof PropertySheet) {
if (propertySheetPages.contains(((PropertySheet) p).getCurrentPage())) {
getActionBarContributor().setActiveEditor(WTSpec4MEditor.this);
handleActivate();
}
} else if (p == WTSpec4MEditor.this) {
handleActivate();
}
}
public void partBroughtToTop(IWorkbenchPart p) {
// Ignore.
}
public void partClosed(IWorkbenchPart p) {
// TODO dispose leg only when it was the last open front model editor for the current user
if(leg != null){
leg.dispose();
}
// Close the log view
IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page = workbenchWindow.getActivePage();
IViewReference[] viewReferences = page.getViewReferences();
for (IViewReference iViewReference : viewReferences) {
if(iViewReference.getId().equals(ModelLogView.ID)){
page.hideView(iViewReference);
}
}
}
public void partDeactivated(IWorkbenchPart p) {
// Ignore.
}
public void partOpened(IWorkbenchPart p) {
// Ignore.
}
};
/**
* Resources that have been removed since last activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Collection<Resource> removedResources = new ArrayList<Resource>();
/**
* Resources that have been changed since last activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Collection<Resource> changedResources = new ArrayList<Resource>();
/**
* Resources that have been saved. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
protected Collection<Resource> savedResources = new ArrayList<Resource>();
/**
* Map to store the diagnostic associated with a resource. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Map<Resource, Diagnostic> resourceToDiagnosticMap = new LinkedHashMap<Resource, Diagnostic>();
/**
* Controls whether the problem indication should be updated. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean updateProblemIndication = true;
/**
* Adapter used to update the problem indication when resources are demanded
* loaded. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected EContentAdapter problemIndicationAdapter = new EContentAdapter() {
@Override
public void notifyChanged(Notification notification) {
if (notification.getNotifier() instanceof Resource) {
switch (notification.getFeatureID(Resource.class)) {
case Resource.RESOURCE__IS_LOADED:
case Resource.RESOURCE__ERRORS:
case Resource.RESOURCE__WARNINGS: {
Resource resource = (Resource) notification.getNotifier();
Diagnostic diagnostic = analyzeResourceProblems(resource, null);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, diagnostic);
} else {
resourceToDiagnosticMap.remove(resource);
}
if (updateProblemIndication) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
break;
}
}
} else {
super.notifyChanged(notification);
}
}
@Override
protected void setTarget(Resource target) {
basicSetTarget(target);
}
@Override
protected void unsetTarget(Resource target) {
basicUnsetTarget(target);
resourceToDiagnosticMap.remove(target);
if (updateProblemIndication) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
}
};
private OnlineLeg leg;
private boolean isItMe;
/**
* Handles activation of the editor or it's associated views. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void handleActivate() {
// Recompute the read only state.
//
if (editingDomain.getResourceToReadOnlyMap() != null) {
editingDomain.getResourceToReadOnlyMap().clear();
// Refresh any actions that may become enabled or disabled.
//
setSelection(getSelection());
}
if (!removedResources.isEmpty()) {
if (handleDirtyConflict()) {
getSite().getPage().closeEditor(WTSpec4MEditor.this, false);
} else {
removedResources.clear();
changedResources.clear();
savedResources.clear();
}
} else if (!changedResources.isEmpty()) {
changedResources.removeAll(savedResources);
handleChangedResources();
changedResources.clear();
savedResources.clear();
}
}
/**
* Handles what to do with changed resources on activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void handleChangedResources() {
if (!changedResources.isEmpty() && (!isDirty() || handleDirtyConflict())) {
if (isDirty()) {
changedResources.addAll(editingDomain.getResourceSet().getResources());
}
editingDomain.getCommandStack().flush();
updateProblemIndication = false;
for (Resource resource : changedResources) {
if (resource.isLoaded()) {
resource.unload();
try {
resource.load(Collections.EMPTY_MAP);
} catch (IOException exception) {
if (!resourceToDiagnosticMap.containsKey(resource)) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
}
}
}
if (AdapterFactoryEditingDomain.isStale(editorSelection)) {
setSelection(StructuredSelection.EMPTY);
}
updateProblemIndication = true;
updateProblemIndication();
}
}
/**
* Updates the problems indication with the information described in the
* specified diagnostic. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void updateProblemIndication() {
if (updateProblemIndication) {
BasicDiagnostic diagnostic = new BasicDiagnostic(Diagnostic.OK, "org.mondo.wt.cstudy.metamodel.editor", 0,
null, new Object[] { editingDomain.getResourceSet() });
for (Diagnostic childDiagnostic : resourceToDiagnosticMap.values()) {
if (childDiagnostic.getSeverity() != Diagnostic.OK) {
diagnostic.add(childDiagnostic);
}
}
int lastEditorPage = getPageCount() - 1;
if (lastEditorPage >= 0 && getEditor(lastEditorPage) instanceof ProblemEditorPart) {
((ProblemEditorPart) getEditor(lastEditorPage)).setDiagnostic(diagnostic);
if (diagnostic.getSeverity() != Diagnostic.OK) {
setActivePage(lastEditorPage);
}
} else if (diagnostic.getSeverity() != Diagnostic.OK) {
ProblemEditorPart problemEditorPart = new ProblemEditorPart();
problemEditorPart.setDiagnostic(diagnostic);
try {
addPage(++lastEditorPage, problemEditorPart, getEditorInput());
setPageText(lastEditorPage, problemEditorPart.getPartName());
setActivePage(lastEditorPage);
showTabs();
} catch (PartInitException exception) {
WTSpec4MEditorPlugin.INSTANCE.log(exception);
}
}
}
}
/**
* Shows a dialog that asks if conflicting changes should be discarded. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean handleDirtyConflict() {
return MessageDialog.openQuestion(getSite().getShell(), getString("_UI_FileConflict_label"),
getString("_WARN_FileConflict"));
}
/**
* This creates a model editor. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
public WTSpec4MEditor() {
super();
initializeEditingDomain();
}
/**
* This sets up the editing domain for the model editor. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
protected void initializeEditingDomain() {
// Create an adapter factory that yields item providers.
//
adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
adapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new WTSpec4MItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory());
// Create the command stack that will notify this editor as commands are
// executed.
//
BasicCommandStack commandStack = new BasicCommandStack();
// Add a listener to set the most recent command's affected objects to
// be the selection of the viewer with focus.
//
commandStack.addCommandStackListener(new CommandStackListener() {
public void commandStackChanged(final EventObject event) {
getContainer().getDisplay().asyncExec(new Runnable() {
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
// Try to select the affected objects.
//
Command mostRecentCommand = ((CommandStack) event.getSource()).getMostRecentCommand();
if (mostRecentCommand != null) {
setSelectionToViewer(mostRecentCommand.getAffectedObjects());
}
for (Iterator<PropertySheetPage> i = propertySheetPages.iterator(); i.hasNext();) {
PropertySheetPage propertySheetPage = i.next();
if (propertySheetPage.getControl().isDisposed()) {
i.remove();
} else {
propertySheetPage.refresh();
}
}
}
});
}
});
// Create the editing domain with a special command stack.
//
editingDomain = new AdapterFactoryEditingDomain(adapterFactory, commandStack, new HashMap<Resource, Boolean>());
}
/**
* This is here for the listener to be able to call it. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
@Override
protected void firePropertyChange(int action) {
super.firePropertyChange(action);
}
/**
* This sets the selection into whichever viewer is active. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setSelectionToViewer(Collection<?> collection) {
final Collection<?> theSelection = collection;
// Make sure it's okay.
//
if (theSelection != null && !theSelection.isEmpty()) {
Runnable runnable = new Runnable() {
public void run() {
// Try to select the items in the current content viewer of
// the editor.
//
if (currentViewer != null) {
currentViewer.setSelection(new StructuredSelection(theSelection.toArray()), true);
}
}
};
getSite().getShell().getDisplay().asyncExec(runnable);
}
}
/**
* This returns the editing domain as required by the
* {@link IEditingDomainProvider} interface. This is important for
* implementing the static methods of {@link AdapterFactoryEditingDomain}
* and for supporting {@link org.eclipse.emf.edit.ui.action.CommandAction}.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public EditingDomain getEditingDomain() {
return editingDomain;
}
private final class UpdateOnModification implements FutureCallback<Object> {
@Override
public void onFailure(Throwable arg0) {
}
@Override
public void onSuccess(Object obj) {
if(!isItMe) {
System.out.println("other user");
selectionViewer.getControl().getDisplay().asyncExec( new Runnable() {
public void run() {
System.out.println("executing on ui thread");
if(selectionViewer != null)
selectionViewer.refresh();
System.out.println("finished");
}
});
}
}
}
private final class UpdateOnSave implements FutureCallback<Object> {
@Override
public void onFailure(Throwable arg0) {
}
@Override
public void onSuccess(Object obj) {
ModelExplorer.update((String) obj);
getContainer().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
}
});
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public class ReverseAdapterFactoryContentProvider extends AdapterFactoryContentProvider {
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public ReverseAdapterFactoryContentProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object[] getElements(Object object) {
Object parent = super.getParent(object);
return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object[] getChildren(Object object) {
Object parent = super.getParent(object);
return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean hasChildren(Object object) {
Object parent = super.getParent(object);
return parent != null;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object getParent(Object object) {
return null;
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setCurrentViewerPane(ViewerPane viewerPane) {
if (currentViewerPane != viewerPane) {
if (currentViewerPane != null) {
currentViewerPane.showFocus(false);
}
currentViewerPane = viewerPane;
}
setCurrentViewer(currentViewerPane.getViewer());
}
/**
* This makes sure that one content viewer, either for the current page or
* the outline view, if it has focus, is the current one. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setCurrentViewer(Viewer viewer) {
// If it is changing...
//
if (currentViewer != viewer) {
if (selectionChangedListener == null) {
// Create the listener on demand.
//
selectionChangedListener = new ISelectionChangedListener() {
// This just notifies those things that are affected by the
// section.
//
public void selectionChanged(SelectionChangedEvent selectionChangedEvent) {
setSelection(selectionChangedEvent.getSelection());
}
};
}
// Stop listening to the old one.
//
if (currentViewer != null) {
currentViewer.removeSelectionChangedListener(selectionChangedListener);
}
// Start listening to the new one.
//
if (viewer != null) {
viewer.addSelectionChangedListener(selectionChangedListener);
}
// Remember it.
//
currentViewer = viewer;
// Set the editors selection based on the current viewer's
// selection.
//
setSelection(currentViewer == null ? StructuredSelection.EMPTY : currentViewer.getSelection());
}
}
/**
* This returns the viewer as required by the {@link IViewerProvider}
* interface. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public Viewer getViewer() {
return currentViewer;
}
/**
* This creates a context menu for the viewer and adds a listener as well
* registering the menu for extension. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected void createContextMenuFor(StructuredViewer viewer) {
MenuManager contextMenu = new MenuManager("#PopUp");
contextMenu.add(new Separator("additions"));
contextMenu.setRemoveAllWhenShown(true);
contextMenu.addMenuListener(this);
Menu menu = contextMenu.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(contextMenu, new UnwrappingSelectionProvider(viewer));
int dndOperations = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers = new Transfer[] { LocalTransfer.getInstance(), LocalSelectionTransfer.getTransfer(),
FileTransfer.getInstance() };
viewer.addDragSupport(dndOperations, transfers, new ViewerDragAdapter(viewer));
viewer.addDropSupport(dndOperations, transfers, new EditingDomainViewerDropAdapter(editingDomain, viewer));
}
/**
* This is the method called to load a resource into the editing domain's
* resource set based on the editor's input. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated NOT
*/
public void createModel() {
URI resourceURI = EditUIUtil.getURI(getEditorInput());
Exception exception = null;
Resource resource = null;
// Initialize new Online Collaboration Session if needs
boolean needToInitialize = !LensActivator.getModelSessions().containsKey(resourceURI);
if (needToInitialize) {
LensActivator.initializeSession(resourceURI, ModelExplorer.getCurrentStorageAccess());
}
// Initialize new Online Collaboration Leg for the existing session
leg = LensActivator.getOrCreateResource(resourceURI, editingDomain, ModelExplorer.getCurrentStorageAccess());
UISessionManager.register(OnlineLeg.EVENT_UPDATE, RWT.getUISession(), new UpdateOnModification());
UISessionManager.register(OnlineLeg.EVENT_SAVE, RWT.getUISession(), new UpdateOnSave());
resource = leg.getFrontResourceSet().getResources().get(0);
Diagnostic diagnostic = analyzeResourceProblems(resource, exception);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter);
// Submit changes for lens
editingDomain.getCommandStack().addCommandStackListener(new CommandStackListener() {
@Override
public void commandStackChanged(EventObject event) {
Command mostRecentCommand = editingDomain.getCommandStack().getMostRecentCommand();
if(!(mostRecentCommand instanceof LegCommand)){
leg.trySubmitModification();
// Log the event
IViewReference[] viewReferences = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getViewReferences();
ModelLogView logView = ModelLogView.getCurrentLogView(viewReferences);
String username = ModelExplorer.getCurrentStorageAccess().getUsername();
Date now = new Date();
String strDate = ModelExplorer.DATE_FORMAT.format(now);
String commandLabel = mostRecentCommand.getLabel();
String logString = logView.getLogString();
Collection<?> affectedObjects = mostRecentCommand.getAffectedObjects();
String affectedObjectETypes = "";
for (Object object : affectedObjects) {
// TODO collect more details here about the executed command
affectedObjectETypes += (((EObject) object).eClass().getName()+ " ");
}
logString= strDate + " " + commandLabel + " by " + username + ". Affeted object type: " + affectedObjectETypes + logView.getLineDelimiter() + logString; //" (Details: " + commandDescription + ") " + logView.getLineDelimiter() + logString ;
logView.setLogString(logString);
logView.refresh();
}
}
});
}
/**
* Returns a diagnostic describing the errors and warnings listed in the
* resource and the specified exception (if any). <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public Diagnostic analyzeResourceProblems(Resource resource, Exception exception) {
boolean hasErrors = !resource.getErrors().isEmpty();
if (hasErrors || !resource.getWarnings().isEmpty()) {
BasicDiagnostic basicDiagnostic = new BasicDiagnostic(hasErrors ? Diagnostic.ERROR : Diagnostic.WARNING,
"org.mondo.wt.cstudy.metamodel.editor", 0,
getString("_UI_CreateModelError_message", resource.getURI()),
new Object[] { exception == null ? (Object) resource : exception });
basicDiagnostic.merge(EcoreUtil.computeDiagnostic(resource, true));
return basicDiagnostic;
} else if (exception != null) {
return new BasicDiagnostic(Diagnostic.ERROR, "org.mondo.wt.cstudy.metamodel.editor", 0,
getString("_UI_CreateModelError_message", resource.getURI()), new Object[] { exception });
} else {
return Diagnostic.OK_INSTANCE;
}
}
/**
* This is the method used by the framework to install your own controls.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void createPages() {
// Creates the model from the editor input
//
createModel();
// Only creates the other pages if there is something that can be edited
//
if (!getEditingDomain().getResourceSet().getResources().isEmpty()) {
// Create a page for the selection tree view.
//
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
Tree tree = new Tree(composite, SWT.MULTI);
TreeViewer newTreeViewer = new TreeViewer(tree);
return newTreeViewer;
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
selectionViewer = (TreeViewer) viewerPane.getViewer();
selectionViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
selectionViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
selectionViewer.setInput(editingDomain.getResourceSet());
selectionViewer.setSelection(
new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true);
viewerPane.setTitle(editingDomain.getResourceSet());
new AdapterFactoryTreeEditor(selectionViewer.getTree(), adapterFactory);
createContextMenuFor(selectionViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_SelectionPage_label"));
}
// Create a page for the parent tree view.
//
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
Tree tree = new Tree(composite, SWT.MULTI);
TreeViewer newTreeViewer = new TreeViewer(tree);
return newTreeViewer;
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
parentViewer = (TreeViewer) viewerPane.getViewer();
parentViewer.setAutoExpandLevel(30);
parentViewer.setContentProvider(new ReverseAdapterFactoryContentProvider(adapterFactory));
parentViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(parentViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_ParentPage_label"));
}
// This is the page for the list viewer
//
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new ListViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
listViewer = (ListViewer) viewerPane.getViewer();
listViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
listViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(listViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_ListPage_label"));
}
// This is the page for the tree viewer
//
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TreeViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
treeViewer = (TreeViewer) viewerPane.getViewer();
treeViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
treeViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
new AdapterFactoryTreeEditor(treeViewer.getTree(), adapterFactory);
createContextMenuFor(treeViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TreePage_label"));
}
// This is the page for the table viewer.
//
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TableViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
tableViewer = (TableViewer) viewerPane.getViewer();
Table table = tableViewer.getTable();
TableLayout layout = new TableLayout();
table.setLayout(layout);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn objectColumn = new TableColumn(table, SWT.NONE);
layout.addColumnData(new ColumnWeightData(3, 100, true));
objectColumn.setText(getString("_UI_ObjectColumn_label"));
objectColumn.setResizable(true);
TableColumn selfColumn = new TableColumn(table, SWT.NONE);
layout.addColumnData(new ColumnWeightData(2, 100, true));
selfColumn.setText(getString("_UI_SelfColumn_label"));
selfColumn.setResizable(true);
tableViewer.setColumnProperties(new String[] { "a", "b" });
tableViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
tableViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(tableViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TablePage_label"));
}
// This is the page for the table tree viewer.
//
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TreeViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
treeViewerWithColumns = (TreeViewer) viewerPane.getViewer();
Tree tree = treeViewerWithColumns.getTree();
tree.setLayoutData(new FillLayout());
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
TreeColumn objectColumn = new TreeColumn(tree, SWT.NONE);
objectColumn.setText(getString("_UI_ObjectColumn_label"));
objectColumn.setResizable(true);
objectColumn.setWidth(250);
TreeColumn selfColumn = new TreeColumn(tree, SWT.NONE);
selfColumn.setText(getString("_UI_SelfColumn_label"));
selfColumn.setResizable(true);
selfColumn.setWidth(200);
treeViewerWithColumns.setColumnProperties(new String[] { "a", "b" });
treeViewerWithColumns.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
treeViewerWithColumns.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(treeViewerWithColumns);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TreeWithColumnsPage_label"));
}
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
setActivePage(0);
}
});
}
// Ensures that this editor will only display the page's tab
// area if there are more than one page
//
getContainer().addControlListener(new ControlAdapter() {
boolean guard = false;
@Override
public void controlResized(ControlEvent event) {
if (!guard) {
guard = true;
hideTabs();
guard = false;
}
}
});
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
/**
* If there is just one page in the multi-page editor part, this hides the
* single tab at the bottom. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void hideTabs() {
if (getPageCount() <= 1) {
setPageText(0, "");
if (getContainer() instanceof CTabFolder) {
((CTabFolder) getContainer()).setTabHeight(1);
Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y + 6);
}
}
}
/**
* If there is more than one page in the multi-page editor part, this shows
* the tabs at the bottom. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void showTabs() {
if (getPageCount() > 1) {
setPageText(0, getString("_UI_SelectionPage_label"));
if (getContainer() instanceof CTabFolder) {
((CTabFolder) getContainer()).setTabHeight(SWT.DEFAULT);
Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y - 6);
}
}
}
/**
* This is used to track the active viewer. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
@Override
protected void pageChange(int pageIndex) {
super.pageChange(pageIndex);
if (contentOutlinePage != null) {
handleContentOutlineSelection(contentOutlinePage.getSelection());
}
}
/**
* This is how the framework determines which interfaces we implement. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class key) {
if (key.equals(IContentOutlinePage.class)) {
return showOutlineView() ? getContentOutlinePage() : null;
} else if (key.equals(IPropertySheetPage.class)) {
return getPropertySheetPage();
} else {
return super.getAdapter(key);
}
}
/**
* This accesses a cached version of the content outliner. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public IContentOutlinePage getContentOutlinePage() {
if (contentOutlinePage == null) {
// The content outline is just a tree.
//
class MyContentOutlinePage extends ContentOutlinePage {
@Override
public void createControl(Composite parent) {
super.createControl(parent);
contentOutlineViewer = getTreeViewer();
contentOutlineViewer.addSelectionChangedListener(this);
// Set up the tree viewer.
//
contentOutlineViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
contentOutlineViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
contentOutlineViewer.setInput(editingDomain.getResourceSet());
// Make sure our popups work.
//
createContextMenuFor(contentOutlineViewer);
if (!editingDomain.getResourceSet().getResources().isEmpty()) {
// Select the root object in the view.
//
contentOutlineViewer.setSelection(
new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true);
}
}
@Override
public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager,
IStatusLineManager statusLineManager) {
super.makeContributions(menuManager, toolBarManager, statusLineManager);
contentOutlineStatusLineManager = statusLineManager;
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
getActionBarContributor().shareGlobalActions(this, actionBars);
}
}
contentOutlinePage = new MyContentOutlinePage();
// Listen to selection so that we can handle it is a special way.
//
contentOutlinePage.addSelectionChangedListener(new ISelectionChangedListener() {
// This ensures that we handle selections correctly.
//
public void selectionChanged(SelectionChangedEvent event) {
handleContentOutlineSelection(event.getSelection());
}
});
}
return contentOutlinePage;
}
/**
* This accesses a cached version of the property sheet. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
public IPropertySheetPage getPropertySheetPage() {
PropertySheetPage propertySheetPage = new ExtendedPropertySheetPage(editingDomain) {
@Override
public void setSelectionToViewer(List<?> selection) {
WTSpec4MEditor.this.setSelectionToViewer(selection);
WTSpec4MEditor.this.setFocus();
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
getActionBarContributor().shareGlobalActions(this, actionBars);
}
};
propertySheetPage.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory));
propertySheetPages.add(propertySheetPage);
return propertySheetPage;
}
/**
* This deals with how we want selection in the outliner to affect the other
* views. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void handleContentOutlineSelection(ISelection selection) {
if (currentViewerPane != null && !selection.isEmpty() && selection instanceof IStructuredSelection) {
Iterator<?> selectedElements = ((IStructuredSelection) selection).iterator();
if (selectedElements.hasNext()) {
// Get the first selected element.
//
Object selectedElement = selectedElements.next();
// If it's the selection viewer, then we want it to select the
// same selection as this selection.
//
if (currentViewerPane.getViewer() == selectionViewer) {
ArrayList<Object> selectionList = new ArrayList<Object>();
selectionList.add(selectedElement);
while (selectedElements.hasNext()) {
selectionList.add(selectedElements.next());
}
// Set the selection to the widget.
//
selectionViewer.setSelection(new StructuredSelection(selectionList));
} else {
// Set the input to the widget.
//
if (currentViewerPane.getViewer().getInput() != selectedElement) {
currentViewerPane.getViewer().setInput(selectedElement);
currentViewerPane.setTitle(selectedElement);
}
}
}
}
}
/**
* This is for implementing {@link IEditorPart} and simply tests the command
* stack. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean isDirty() {
return ((BasicCommandStack) editingDomain.getCommandStack()).isSaveNeeded();
}
/**
* This is for implementing {@link IEditorPart} and simply saves the model
* file. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void doSave(IProgressMonitor progressMonitor) {
leg.trySubmitModification();
// Save only resources that have actually changed.
//
final Map<Object, Object> saveOptions = new HashMap<Object, Object>();
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
saveOptions.put(Resource.OPTION_LINE_DELIMITER, Resource.OPTION_LINE_DELIMITER_UNSPECIFIED);
// Do the work within an operation because this is a long running
// activity that modifies the workbench.
//
IRunnableWithProgress operation = new IRunnableWithProgress() {
// This is the method that gets invoked when the operation runs.
//
public void run(IProgressMonitor monitor) {
// Save the resources to the file system.
//
boolean first = true;
for (Resource resource : leg.getGoldResourceSet().getResources()) {
if ((first || !resource.getContents().isEmpty() || isPersisted(resource))) {
try {
long timeStamp = resource.getTimeStamp();
resource.save(saveOptions);
if (resource.getTimeStamp() != timeStamp) {
savedResources.add(resource);
}
} catch (Exception exception) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
first = false;
}
}
for (Leg l : leg.getOnlineCollaborationSession().getLegs()) {
if(l instanceof OnlineLeg) {
OnlineLeg onlineLeg = (OnlineLeg) l;
onlineLeg.saveExecuted();
}
}
}
};
updateProblemIndication = false;
try {
// This runs the options, and shows progress.
//
new ProgressMonitorDialog(getSite().getShell()).run(true, false, operation);
// Refresh the necessary state.
//
((BasicCommandStack) editingDomain.getCommandStack()).saveIsDone();
firePropertyChange(IEditorPart.PROP_DIRTY);
} catch (Exception exception) {
// Something went wrong that shouldn't.
//
WTSpec4MEditorPlugin.INSTANCE.log(exception);
}
updateProblemIndication = true;
updateProblemIndication();
}
/**
* This returns whether something has been persisted to the URI of the
* specified resource. The implementation uses the URI converter from the
* editor's resource set to try to open an input stream. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean isPersisted(Resource resource) {
boolean result = false;
try {
InputStream stream = editingDomain.getResourceSet().getURIConverter().createInputStream(resource.getURI());
if (stream != null) {
result = true;
stream.close();
}
} catch (IOException e) {
// Ignore
}
return result;
}
/**
* This always returns true because it is not currently supported. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean isSaveAsAllowed() {
return true;
}
/**
* This also changes the editor's input. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
@Override
public void doSaveAs() {
new ResourceDialog(getSite().getShell(), null, SWT.NONE) {
@Override
protected boolean isSave() {
return true;
}
@Override
protected boolean processResources() {
List<URI> uris = getURIs();
if (uris.size() > 0) {
URI uri = uris.get(0);
doSaveAs(uri, new URIEditorInput(uri));
return true;
} else {
return false;
}
}
}.open();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void doSaveAs(URI uri, IEditorInput editorInput) {
(editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
IProgressMonitor progressMonitor = getActionBars().getStatusLineManager() != null
? getActionBars().getStatusLineManager().getProgressMonitor() : new NullProgressMonitor();
doSave(progressMonitor);
}
/**
* This is called during startup. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
@Override
public void init(IEditorSite site, IEditorInput editorInput) {
setSite(site);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
site.setSelectionProvider(this);
site.getPage().addPartListener(partListener);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setFocus() {
if (currentViewerPane != null) {
currentViewerPane.setFocus();
} else {
getControl(getActivePage()).setFocus();
}
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to
* return this editor's overall selection. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
public ISelection getSelection() {
return editorSelection;
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to
* set this editor's overall selection. Calling this result will notify the
* listeners. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setSelection(ISelection selection) {
editorSelection = selection;
for (ISelectionChangedListener listener : selectionChangedListeners) {
listener.selectionChanged(new SelectionChangedEvent(this, selection));
}
setStatusLineManager(selection);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setStatusLineManager(ISelection selection) {
IStatusLineManager statusLineManager = currentViewer != null && currentViewer == contentOutlineViewer
? contentOutlineStatusLineManager : getActionBars().getStatusLineManager();
if (statusLineManager != null) {
if (selection instanceof IStructuredSelection) {
Collection<?> collection = ((IStructuredSelection) selection).toList();
switch (collection.size()) {
case 0: {
statusLineManager.setMessage(getString("_UI_NoObjectSelected"));
break;
}
case 1: {
String text = new AdapterFactoryItemDelegator(adapterFactory).getText(collection.iterator().next());
statusLineManager.setMessage(getString("_UI_SingleObjectSelected", text));
break;
}
default: {
statusLineManager
.setMessage(getString("_UI_MultiObjectSelected", Integer.toString(collection.size())));
break;
}
}
} else {
statusLineManager.setMessage("");
}
}
}
/**
* This looks up a string in the plugin's plugin.properties file. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
private static String getString(String key) {
return WTSpec4MEditorPlugin.INSTANCE.getString(key);
}
/**
* This looks up a string in plugin.properties, making a substitution. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
private static String getString(String key, Object s1) {
return WTSpec4MEditorPlugin.INSTANCE.getString(key, new Object[] { s1 });
}
/**
* This implements {@link org.eclipse.jface.action.IMenuListener} to help
* fill the context menus with contributions from the Edit menu. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void menuAboutToShow(IMenuManager menuManager) {
((IMenuListener) getEditorSite().getActionBarContributor()).menuAboutToShow(menuManager);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public EditingDomainActionBarContributor getActionBarContributor() {
return (EditingDomainActionBarContributor) getEditorSite().getActionBarContributor();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public IActionBars getActionBars() {
return getActionBarContributor().getActionBars();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public AdapterFactory getAdapterFactory() {
return adapterFactory;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void dispose() {
updateProblemIndication = false;
getSite().getPage().removePartListener(partListener);
adapterFactory.dispose();
if (getActionBarContributor().getActiveEditor() == this) {
getActionBarContributor().setActiveEditor(null);
}
for (PropertySheetPage propertySheetPage : propertySheetPages) {
propertySheetPage.dispose();
}
if (contentOutlinePage != null) {
contentOutlinePage.dispose();
}
super.dispose();
}
/**
* Returns whether the outline view should be presented to the user. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean showOutlineView() {
return true;
}
}
| MONDO-Collab/org.mondo.wt.cstudy.metamodel.editor/src/WTSpec4M/presentation/WTSpec4MEditor.java | /**
*/
package WTSpec4M.presentation;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.ui.ViewerPane;
import org.eclipse.emf.common.ui.dialogs.ResourceDialog;
import org.eclipse.emf.common.ui.editor.ProblemEditorPart;
import org.eclipse.emf.common.ui.viewer.IViewerProvider;
import org.eclipse.emf.common.util.BasicDiagnostic;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EContentAdapter;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.edit.provider.AdapterFactoryItemDelegator;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory;
import org.eclipse.emf.edit.ui.action.EditingDomainActionBarContributor;
import org.eclipse.emf.edit.ui.celleditor.AdapterFactoryTreeEditor;
import org.eclipse.emf.edit.ui.dnd.EditingDomainViewerDropAdapter;
import org.eclipse.emf.edit.ui.dnd.LocalTransfer;
import org.eclipse.emf.edit.ui.dnd.ViewerDragAdapter;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.edit.ui.provider.UnwrappingSelectionProvider;
import org.eclipse.emf.edit.ui.util.EditUIUtil;
import org.eclipse.emf.edit.ui.view.ExtendedPropertySheetPage;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.util.LocalSelectionTransfer;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.rap.rwt.RWT;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheet;
import org.eclipse.ui.views.properties.PropertySheetPage;
import org.mondo.collaboration.online.core.LensActivator;
import org.mondo.collaboration.online.core.OnlineLeg;
import org.mondo.collaboration.online.core.OnlineLeg.LegCommand;
import org.mondo.collaboration.online.rap.widgets.ModelExplorer;
import org.mondo.collaboration.online.rap.widgets.ModelLogView;
import org.mondo.collaboration.online.rap.widgets.UISessionManager;
import org.mondo.collaboration.security.lens.bx.online.OnlineCollaborationSession;
import org.mondo.collaboration.security.lens.bx.online.OnlineCollaborationSession.Leg;
import com.google.common.util.concurrent.FutureCallback;
import WTSpec4M.provider.WTSpec4MItemProviderAdapterFactory;
/**
* This is an example of a WTSpec4M model editor. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
public class WTSpec4MEditor extends MultiPageEditorPart
implements IEditingDomainProvider, ISelectionProvider, IMenuListener, IViewerProvider {
/**
* The filters for file extensions supported by the editor. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public static final List<String> FILE_EXTENSION_FILTERS = prefixExtensions(WTSpec4MModelWizard.FILE_EXTENSIONS,
"*.");
/**
* Returns a new unmodifiable list containing prefixed versions of the
* extensions in the given list. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
private static List<String> prefixExtensions(List<String> extensions, String prefix) {
List<String> result = new ArrayList<String>();
for (String extension : extensions) {
result.add(prefix + extension);
}
return Collections.unmodifiableList(result);
}
/**
* This keeps track of the editing domain that is used to track all changes
* to the model. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected AdapterFactoryEditingDomain editingDomain;
/**
* This is the one adapter factory used for providing views of the model.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ComposedAdapterFactory adapterFactory;
/**
* This is the content outline page. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected IContentOutlinePage contentOutlinePage;
/**
* This is a kludge... <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected IStatusLineManager contentOutlineStatusLineManager;
/**
* This is the content outline page's viewer. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected TreeViewer contentOutlineViewer;
/**
* This is the property sheet page. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected List<PropertySheetPage> propertySheetPages = new ArrayList<PropertySheetPage>();
/**
* This is the viewer that shadows the selection in the content outline. The
* parent relation must be correctly defined for this to work. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected TreeViewer selectionViewer;
/**
* This inverts the roll of parent and child in the content provider and
* show parents as a tree. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected TreeViewer parentViewer;
/**
* This shows how a tree view works. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected TreeViewer treeViewer;
/**
* This shows how a list view works. A list viewer doesn't support icons.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ListViewer listViewer;
/**
* This shows how a table view works. A table can be used as a list with
* icons. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected TableViewer tableViewer;
/**
* This shows how a tree view with columns works. <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected TreeViewer treeViewerWithColumns;
/**
* This keeps track of the active viewer pane, in the book. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ViewerPane currentViewerPane;
/**
* This keeps track of the active content viewer, which may be either one of
* the viewers in the pages or the content outline viewer. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Viewer currentViewer;
/**
* This listens to which ever viewer is active. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected ISelectionChangedListener selectionChangedListener;
/**
* This keeps track of all the
* {@link org.eclipse.jface.viewers.ISelectionChangedListener}s that are
* listening to this editor. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Collection<ISelectionChangedListener> selectionChangedListeners = new ArrayList<ISelectionChangedListener>();
/**
* This keeps track of the selection of the editor as a whole. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ISelection editorSelection = StructuredSelection.EMPTY;
/**
* This listens for when the outline becomes active <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected IPartListener partListener = new IPartListener() {
public void partActivated(IWorkbenchPart p) {
if (p instanceof ContentOutline) {
if (((ContentOutline) p).getCurrentPage() == contentOutlinePage) {
getActionBarContributor().setActiveEditor(WTSpec4MEditor.this);
setCurrentViewer(contentOutlineViewer);
}
} else if (p instanceof PropertySheet) {
if (propertySheetPages.contains(((PropertySheet) p).getCurrentPage())) {
getActionBarContributor().setActiveEditor(WTSpec4MEditor.this);
handleActivate();
}
} else if (p == WTSpec4MEditor.this) {
handleActivate();
}
}
public void partBroughtToTop(IWorkbenchPart p) {
// Ignore.
}
public void partClosed(IWorkbenchPart p) {
// TODO dispose leg only when it was the last open front model editor for the current user
if(leg != null){
leg.dispose();
}
// Close the log view
IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
IWorkbenchPage page = workbenchWindow.getActivePage();
IViewReference[] viewReferences = page.getViewReferences();
for (IViewReference iViewReference : viewReferences) {
if(iViewReference.getId().equals(ModelLogView.ID)){
page.hideView(iViewReference);
}
}
}
public void partDeactivated(IWorkbenchPart p) {
// Ignore.
}
public void partOpened(IWorkbenchPart p) {
// Ignore.
}
};
/**
* Resources that have been removed since last activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Collection<Resource> removedResources = new ArrayList<Resource>();
/**
* Resources that have been changed since last activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Collection<Resource> changedResources = new ArrayList<Resource>();
/**
* Resources that have been saved. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
protected Collection<Resource> savedResources = new ArrayList<Resource>();
/**
* Map to store the diagnostic associated with a resource. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected Map<Resource, Diagnostic> resourceToDiagnosticMap = new LinkedHashMap<Resource, Diagnostic>();
/**
* Controls whether the problem indication should be updated. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean updateProblemIndication = true;
/**
* Adapter used to update the problem indication when resources are demanded
* loaded. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected EContentAdapter problemIndicationAdapter = new EContentAdapter() {
@Override
public void notifyChanged(Notification notification) {
if (notification.getNotifier() instanceof Resource) {
switch (notification.getFeatureID(Resource.class)) {
case Resource.RESOURCE__IS_LOADED:
case Resource.RESOURCE__ERRORS:
case Resource.RESOURCE__WARNINGS: {
Resource resource = (Resource) notification.getNotifier();
Diagnostic diagnostic = analyzeResourceProblems(resource, null);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, diagnostic);
} else {
resourceToDiagnosticMap.remove(resource);
}
if (updateProblemIndication) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
break;
}
}
} else {
super.notifyChanged(notification);
}
}
@Override
protected void setTarget(Resource target) {
basicSetTarget(target);
}
@Override
protected void unsetTarget(Resource target) {
basicUnsetTarget(target);
resourceToDiagnosticMap.remove(target);
if (updateProblemIndication) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
}
};
private OnlineLeg leg;
private boolean isItMe;
/**
* Handles activation of the editor or it's associated views. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void handleActivate() {
// Recompute the read only state.
//
if (editingDomain.getResourceToReadOnlyMap() != null) {
editingDomain.getResourceToReadOnlyMap().clear();
// Refresh any actions that may become enabled or disabled.
//
setSelection(getSelection());
}
if (!removedResources.isEmpty()) {
if (handleDirtyConflict()) {
getSite().getPage().closeEditor(WTSpec4MEditor.this, false);
} else {
removedResources.clear();
changedResources.clear();
savedResources.clear();
}
} else if (!changedResources.isEmpty()) {
changedResources.removeAll(savedResources);
handleChangedResources();
changedResources.clear();
savedResources.clear();
}
}
/**
* Handles what to do with changed resources on activation. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void handleChangedResources() {
if (!changedResources.isEmpty() && (!isDirty() || handleDirtyConflict())) {
if (isDirty()) {
changedResources.addAll(editingDomain.getResourceSet().getResources());
}
editingDomain.getCommandStack().flush();
updateProblemIndication = false;
for (Resource resource : changedResources) {
if (resource.isLoaded()) {
resource.unload();
try {
resource.load(Collections.EMPTY_MAP);
} catch (IOException exception) {
if (!resourceToDiagnosticMap.containsKey(resource)) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
}
}
}
if (AdapterFactoryEditingDomain.isStale(editorSelection)) {
setSelection(StructuredSelection.EMPTY);
}
updateProblemIndication = true;
updateProblemIndication();
}
}
/**
* Updates the problems indication with the information described in the
* specified diagnostic. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void updateProblemIndication() {
if (updateProblemIndication) {
BasicDiagnostic diagnostic = new BasicDiagnostic(Diagnostic.OK, "org.mondo.wt.cstudy.metamodel.editor", 0,
null, new Object[] { editingDomain.getResourceSet() });
for (Diagnostic childDiagnostic : resourceToDiagnosticMap.values()) {
if (childDiagnostic.getSeverity() != Diagnostic.OK) {
diagnostic.add(childDiagnostic);
}
}
int lastEditorPage = getPageCount() - 1;
if (lastEditorPage >= 0 && getEditor(lastEditorPage) instanceof ProblemEditorPart) {
((ProblemEditorPart) getEditor(lastEditorPage)).setDiagnostic(diagnostic);
if (diagnostic.getSeverity() != Diagnostic.OK) {
setActivePage(lastEditorPage);
}
} else if (diagnostic.getSeverity() != Diagnostic.OK) {
ProblemEditorPart problemEditorPart = new ProblemEditorPart();
problemEditorPart.setDiagnostic(diagnostic);
try {
addPage(++lastEditorPage, problemEditorPart, getEditorInput());
setPageText(lastEditorPage, problemEditorPart.getPartName());
setActivePage(lastEditorPage);
showTabs();
} catch (PartInitException exception) {
WTSpec4MEditorPlugin.INSTANCE.log(exception);
}
}
}
}
/**
* Shows a dialog that asks if conflicting changes should be discarded. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean handleDirtyConflict() {
return MessageDialog.openQuestion(getSite().getShell(), getString("_UI_FileConflict_label"),
getString("_WARN_FileConflict"));
}
/**
* This creates a model editor. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
public WTSpec4MEditor() {
super();
initializeEditingDomain();
}
/**
* This sets up the editing domain for the model editor. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
protected void initializeEditingDomain() {
// Create an adapter factory that yields item providers.
//
adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
adapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new WTSpec4MItemProviderAdapterFactory());
adapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory());
// Create the command stack that will notify this editor as commands are
// executed.
//
BasicCommandStack commandStack = new BasicCommandStack();
// Add a listener to set the most recent command's affected objects to
// be the selection of the viewer with focus.
//
commandStack.addCommandStackListener(new CommandStackListener() {
public void commandStackChanged(final EventObject event) {
getContainer().getDisplay().asyncExec(new Runnable() {
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
// Try to select the affected objects.
//
Command mostRecentCommand = ((CommandStack) event.getSource()).getMostRecentCommand();
if (mostRecentCommand != null) {
setSelectionToViewer(mostRecentCommand.getAffectedObjects());
}
for (Iterator<PropertySheetPage> i = propertySheetPages.iterator(); i.hasNext();) {
PropertySheetPage propertySheetPage = i.next();
if (propertySheetPage.getControl().isDisposed()) {
i.remove();
} else {
propertySheetPage.refresh();
}
}
}
});
}
});
// Create the editing domain with a special command stack.
//
editingDomain = new AdapterFactoryEditingDomain(adapterFactory, commandStack, new HashMap<Resource, Boolean>());
}
/**
* This is here for the listener to be able to call it. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
@Override
protected void firePropertyChange(int action) {
super.firePropertyChange(action);
}
/**
* This sets the selection into whichever viewer is active. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setSelectionToViewer(Collection<?> collection) {
final Collection<?> theSelection = collection;
// Make sure it's okay.
//
if (theSelection != null && !theSelection.isEmpty()) {
Runnable runnable = new Runnable() {
public void run() {
// Try to select the items in the current content viewer of
// the editor.
//
if (currentViewer != null) {
currentViewer.setSelection(new StructuredSelection(theSelection.toArray()), true);
}
}
};
getSite().getShell().getDisplay().asyncExec(runnable);
}
}
/**
* This returns the editing domain as required by the
* {@link IEditingDomainProvider} interface. This is important for
* implementing the static methods of {@link AdapterFactoryEditingDomain}
* and for supporting {@link org.eclipse.emf.edit.ui.action.CommandAction}.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public EditingDomain getEditingDomain() {
return editingDomain;
}
private final class UpdateOnModification implements FutureCallback<Object> {
@Override
public void onFailure(Throwable arg0) {
}
@Override
public void onSuccess(Object obj) {
if(!isItMe) {
System.out.println("other user");
selectionViewer.getControl().getDisplay().asyncExec( new Runnable() {
public void run() {
System.out.println("executing on ui thread");
if(selectionViewer != null)
selectionViewer.refresh();
System.out.println("finished");
}
});
}
}
}
private final class UpdateOnSave implements FutureCallback<Object> {
@Override
public void onFailure(Throwable arg0) {
}
@Override
public void onSuccess(Object obj) {
ModelExplorer.update((String) obj);
getContainer().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
firePropertyChange(IEditorPart.PROP_DIRTY);
}
});
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public class ReverseAdapterFactoryContentProvider extends AdapterFactoryContentProvider {
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public ReverseAdapterFactoryContentProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object[] getElements(Object object) {
Object parent = super.getParent(object);
return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object[] getChildren(Object object) {
Object parent = super.getParent(object);
return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean hasChildren(Object object) {
Object parent = super.getParent(object);
return parent != null;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object getParent(Object object) {
return null;
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setCurrentViewerPane(ViewerPane viewerPane) {
if (currentViewerPane != viewerPane) {
if (currentViewerPane != null) {
currentViewerPane.showFocus(false);
}
currentViewerPane = viewerPane;
}
setCurrentViewer(currentViewerPane.getViewer());
}
/**
* This makes sure that one content viewer, either for the current page or
* the outline view, if it has focus, is the current one. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setCurrentViewer(Viewer viewer) {
// If it is changing...
//
if (currentViewer != viewer) {
if (selectionChangedListener == null) {
// Create the listener on demand.
//
selectionChangedListener = new ISelectionChangedListener() {
// This just notifies those things that are affected by the
// section.
//
public void selectionChanged(SelectionChangedEvent selectionChangedEvent) {
setSelection(selectionChangedEvent.getSelection());
}
};
}
// Stop listening to the old one.
//
if (currentViewer != null) {
currentViewer.removeSelectionChangedListener(selectionChangedListener);
}
// Start listening to the new one.
//
if (viewer != null) {
viewer.addSelectionChangedListener(selectionChangedListener);
}
// Remember it.
//
currentViewer = viewer;
// Set the editors selection based on the current viewer's
// selection.
//
setSelection(currentViewer == null ? StructuredSelection.EMPTY : currentViewer.getSelection());
}
}
/**
* This returns the viewer as required by the {@link IViewerProvider}
* interface. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public Viewer getViewer() {
return currentViewer;
}
/**
* This creates a context menu for the viewer and adds a listener as well
* registering the menu for extension. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
protected void createContextMenuFor(StructuredViewer viewer) {
MenuManager contextMenu = new MenuManager("#PopUp");
contextMenu.add(new Separator("additions"));
contextMenu.setRemoveAllWhenShown(true);
contextMenu.addMenuListener(this);
Menu menu = contextMenu.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
getSite().registerContextMenu(contextMenu, new UnwrappingSelectionProvider(viewer));
int dndOperations = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers = new Transfer[] { LocalTransfer.getInstance(), LocalSelectionTransfer.getTransfer(),
FileTransfer.getInstance() };
viewer.addDragSupport(dndOperations, transfers, new ViewerDragAdapter(viewer));
viewer.addDropSupport(dndOperations, transfers, new EditingDomainViewerDropAdapter(editingDomain, viewer));
}
/**
* This is the method called to load a resource into the editing domain's
* resource set based on the editor's input. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated NOT
*/
public void createModel() {
URI resourceURI = EditUIUtil.getURI(getEditorInput());
Exception exception = null;
Resource resource = null;
// Initialize new Online Collaboration Session if needs
boolean needToInitialize = !LensActivator.getModelSessions().containsKey(resourceURI);
if (needToInitialize) {
LensActivator.initializeSession(resourceURI, ModelExplorer.getCurrentStorageAccess());
}
// Initialize new Online Collaboration Leg for the existing session
leg = LensActivator.getOrCreateResource(resourceURI, editingDomain, ModelExplorer.getCurrentStorageAccess());
UISessionManager.register(OnlineLeg.EVENT_UPDATE, RWT.getUISession(), new UpdateOnModification());
UISessionManager.register(OnlineLeg.EVENT_SAVE, RWT.getUISession(), new UpdateOnSave());
resource = leg.getFrontResourceSet().getResources().get(0);
Diagnostic diagnostic = analyzeResourceProblems(resource, exception);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter);
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Submit changes for lens
editingDomain.getCommandStack().addCommandStackListener(new CommandStackListener() {
@Override
public void commandStackChanged(EventObject event) {
Command mostRecentCommand = editingDomain.getCommandStack().getMostRecentCommand();
if(!(mostRecentCommand instanceof LegCommand)){
leg.trySubmitModification();
// Log the event
IViewReference[] viewReferences = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getViewReferences();
ModelLogView logView = ModelLogView.getCurrentLogView(viewReferences);
String username = ModelExplorer.getCurrentStorageAccess().getUsername();
Date now = new Date();
String strDate = sdf.format(now);
String commandLabel = mostRecentCommand.getLabel();
String logString = logView.getLogString();
Collection<?> affectedObjects = mostRecentCommand.getAffectedObjects();
String affectedObjectETypes = "";
for (Object object : affectedObjects) {
// TODO collect more details here
affectedObjectETypes += (((EObject) object).eClass().getName()+ " ");
}
logString= strDate + " " + commandLabel + " by " + username + ". Affeted object type: " + affectedObjectETypes + logView.getLineDelimiter() + logString; //" (Details: " + commandDescription + ") " + logView.getLineDelimiter() + logString ;
logView.setLogString(logString);
logView.refresh();
}
}
});
}
/**
* Returns a diagnostic describing the errors and warnings listed in the
* resource and the specified exception (if any). <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public Diagnostic analyzeResourceProblems(Resource resource, Exception exception) {
boolean hasErrors = !resource.getErrors().isEmpty();
if (hasErrors || !resource.getWarnings().isEmpty()) {
BasicDiagnostic basicDiagnostic = new BasicDiagnostic(hasErrors ? Diagnostic.ERROR : Diagnostic.WARNING,
"org.mondo.wt.cstudy.metamodel.editor", 0,
getString("_UI_CreateModelError_message", resource.getURI()),
new Object[] { exception == null ? (Object) resource : exception });
basicDiagnostic.merge(EcoreUtil.computeDiagnostic(resource, true));
return basicDiagnostic;
} else if (exception != null) {
return new BasicDiagnostic(Diagnostic.ERROR, "org.mondo.wt.cstudy.metamodel.editor", 0,
getString("_UI_CreateModelError_message", resource.getURI()), new Object[] { exception });
} else {
return Diagnostic.OK_INSTANCE;
}
}
/**
* This is the method used by the framework to install your own controls.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void createPages() {
// Creates the model from the editor input
//
createModel();
// Only creates the other pages if there is something that can be edited
//
if (!getEditingDomain().getResourceSet().getResources().isEmpty()) {
// Create a page for the selection tree view.
//
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
Tree tree = new Tree(composite, SWT.MULTI);
TreeViewer newTreeViewer = new TreeViewer(tree);
return newTreeViewer;
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
selectionViewer = (TreeViewer) viewerPane.getViewer();
selectionViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
selectionViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
selectionViewer.setInput(editingDomain.getResourceSet());
selectionViewer.setSelection(
new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true);
viewerPane.setTitle(editingDomain.getResourceSet());
new AdapterFactoryTreeEditor(selectionViewer.getTree(), adapterFactory);
createContextMenuFor(selectionViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_SelectionPage_label"));
}
// Create a page for the parent tree view.
//
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
Tree tree = new Tree(composite, SWT.MULTI);
TreeViewer newTreeViewer = new TreeViewer(tree);
return newTreeViewer;
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
parentViewer = (TreeViewer) viewerPane.getViewer();
parentViewer.setAutoExpandLevel(30);
parentViewer.setContentProvider(new ReverseAdapterFactoryContentProvider(adapterFactory));
parentViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(parentViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_ParentPage_label"));
}
// This is the page for the list viewer
//
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new ListViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
listViewer = (ListViewer) viewerPane.getViewer();
listViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
listViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(listViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_ListPage_label"));
}
// This is the page for the tree viewer
//
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TreeViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
treeViewer = (TreeViewer) viewerPane.getViewer();
treeViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
treeViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
new AdapterFactoryTreeEditor(treeViewer.getTree(), adapterFactory);
createContextMenuFor(treeViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TreePage_label"));
}
// This is the page for the table viewer.
//
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TableViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
tableViewer = (TableViewer) viewerPane.getViewer();
Table table = tableViewer.getTable();
TableLayout layout = new TableLayout();
table.setLayout(layout);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn objectColumn = new TableColumn(table, SWT.NONE);
layout.addColumnData(new ColumnWeightData(3, 100, true));
objectColumn.setText(getString("_UI_ObjectColumn_label"));
objectColumn.setResizable(true);
TableColumn selfColumn = new TableColumn(table, SWT.NONE);
layout.addColumnData(new ColumnWeightData(2, 100, true));
selfColumn.setText(getString("_UI_SelfColumn_label"));
selfColumn.setResizable(true);
tableViewer.setColumnProperties(new String[] { "a", "b" });
tableViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
tableViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(tableViewer);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TablePage_label"));
}
// This is the page for the table tree viewer.
//
{
ViewerPane viewerPane = new ViewerPane(getSite().getPage(), WTSpec4MEditor.this) {
@Override
public Viewer createViewer(Composite composite) {
return new TreeViewer(composite);
}
@Override
public void requestActivation() {
super.requestActivation();
setCurrentViewerPane(this);
}
};
viewerPane.createControl(getContainer());
treeViewerWithColumns = (TreeViewer) viewerPane.getViewer();
Tree tree = treeViewerWithColumns.getTree();
tree.setLayoutData(new FillLayout());
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
TreeColumn objectColumn = new TreeColumn(tree, SWT.NONE);
objectColumn.setText(getString("_UI_ObjectColumn_label"));
objectColumn.setResizable(true);
objectColumn.setWidth(250);
TreeColumn selfColumn = new TreeColumn(tree, SWT.NONE);
selfColumn.setText(getString("_UI_SelfColumn_label"));
selfColumn.setResizable(true);
selfColumn.setWidth(200);
treeViewerWithColumns.setColumnProperties(new String[] { "a", "b" });
treeViewerWithColumns.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
treeViewerWithColumns.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
createContextMenuFor(treeViewerWithColumns);
int pageIndex = addPage(viewerPane.getControl());
setPageText(pageIndex, getString("_UI_TreeWithColumnsPage_label"));
}
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
setActivePage(0);
}
});
}
// Ensures that this editor will only display the page's tab
// area if there are more than one page
//
getContainer().addControlListener(new ControlAdapter() {
boolean guard = false;
@Override
public void controlResized(ControlEvent event) {
if (!guard) {
guard = true;
hideTabs();
guard = false;
}
}
});
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
updateProblemIndication();
}
});
}
/**
* If there is just one page in the multi-page editor part, this hides the
* single tab at the bottom. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void hideTabs() {
if (getPageCount() <= 1) {
setPageText(0, "");
if (getContainer() instanceof CTabFolder) {
((CTabFolder) getContainer()).setTabHeight(1);
Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y + 6);
}
}
}
/**
* If there is more than one page in the multi-page editor part, this shows
* the tabs at the bottom. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void showTabs() {
if (getPageCount() > 1) {
setPageText(0, getString("_UI_SelectionPage_label"));
if (getContainer() instanceof CTabFolder) {
((CTabFolder) getContainer()).setTabHeight(SWT.DEFAULT);
Point point = getContainer().getSize();
getContainer().setSize(point.x, point.y - 6);
}
}
}
/**
* This is used to track the active viewer. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
@Override
protected void pageChange(int pageIndex) {
super.pageChange(pageIndex);
if (contentOutlinePage != null) {
handleContentOutlineSelection(contentOutlinePage.getSelection());
}
}
/**
* This is how the framework determines which interfaces we implement. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class key) {
if (key.equals(IContentOutlinePage.class)) {
return showOutlineView() ? getContentOutlinePage() : null;
} else if (key.equals(IPropertySheetPage.class)) {
return getPropertySheetPage();
} else {
return super.getAdapter(key);
}
}
/**
* This accesses a cached version of the content outliner. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public IContentOutlinePage getContentOutlinePage() {
if (contentOutlinePage == null) {
// The content outline is just a tree.
//
class MyContentOutlinePage extends ContentOutlinePage {
@Override
public void createControl(Composite parent) {
super.createControl(parent);
contentOutlineViewer = getTreeViewer();
contentOutlineViewer.addSelectionChangedListener(this);
// Set up the tree viewer.
//
contentOutlineViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory));
contentOutlineViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory));
contentOutlineViewer.setInput(editingDomain.getResourceSet());
// Make sure our popups work.
//
createContextMenuFor(contentOutlineViewer);
if (!editingDomain.getResourceSet().getResources().isEmpty()) {
// Select the root object in the view.
//
contentOutlineViewer.setSelection(
new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true);
}
}
@Override
public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager,
IStatusLineManager statusLineManager) {
super.makeContributions(menuManager, toolBarManager, statusLineManager);
contentOutlineStatusLineManager = statusLineManager;
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
getActionBarContributor().shareGlobalActions(this, actionBars);
}
}
contentOutlinePage = new MyContentOutlinePage();
// Listen to selection so that we can handle it is a special way.
//
contentOutlinePage.addSelectionChangedListener(new ISelectionChangedListener() {
// This ensures that we handle selections correctly.
//
public void selectionChanged(SelectionChangedEvent event) {
handleContentOutlineSelection(event.getSelection());
}
});
}
return contentOutlinePage;
}
/**
* This accesses a cached version of the property sheet. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
public IPropertySheetPage getPropertySheetPage() {
PropertySheetPage propertySheetPage = new ExtendedPropertySheetPage(editingDomain) {
@Override
public void setSelectionToViewer(List<?> selection) {
WTSpec4MEditor.this.setSelectionToViewer(selection);
WTSpec4MEditor.this.setFocus();
}
@Override
public void setActionBars(IActionBars actionBars) {
super.setActionBars(actionBars);
getActionBarContributor().shareGlobalActions(this, actionBars);
}
};
propertySheetPage.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory));
propertySheetPages.add(propertySheetPage);
return propertySheetPage;
}
/**
* This deals with how we want selection in the outliner to affect the other
* views. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void handleContentOutlineSelection(ISelection selection) {
if (currentViewerPane != null && !selection.isEmpty() && selection instanceof IStructuredSelection) {
Iterator<?> selectedElements = ((IStructuredSelection) selection).iterator();
if (selectedElements.hasNext()) {
// Get the first selected element.
//
Object selectedElement = selectedElements.next();
// If it's the selection viewer, then we want it to select the
// same selection as this selection.
//
if (currentViewerPane.getViewer() == selectionViewer) {
ArrayList<Object> selectionList = new ArrayList<Object>();
selectionList.add(selectedElement);
while (selectedElements.hasNext()) {
selectionList.add(selectedElements.next());
}
// Set the selection to the widget.
//
selectionViewer.setSelection(new StructuredSelection(selectionList));
} else {
// Set the input to the widget.
//
if (currentViewerPane.getViewer().getInput() != selectedElement) {
currentViewerPane.getViewer().setInput(selectedElement);
currentViewerPane.setTitle(selectedElement);
}
}
}
}
}
/**
* This is for implementing {@link IEditorPart} and simply tests the command
* stack. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean isDirty() {
return ((BasicCommandStack) editingDomain.getCommandStack()).isSaveNeeded();
}
/**
* This is for implementing {@link IEditorPart} and simply saves the model
* file. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void doSave(IProgressMonitor progressMonitor) {
leg.trySubmitModification();
// Save only resources that have actually changed.
//
final Map<Object, Object> saveOptions = new HashMap<Object, Object>();
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
saveOptions.put(Resource.OPTION_LINE_DELIMITER, Resource.OPTION_LINE_DELIMITER_UNSPECIFIED);
// Do the work within an operation because this is a long running
// activity that modifies the workbench.
//
IRunnableWithProgress operation = new IRunnableWithProgress() {
// This is the method that gets invoked when the operation runs.
//
public void run(IProgressMonitor monitor) {
// Save the resources to the file system.
//
boolean first = true;
for (Resource resource : leg.getGoldResourceSet().getResources()) {
if ((first || !resource.getContents().isEmpty() || isPersisted(resource))) {
try {
long timeStamp = resource.getTimeStamp();
resource.save(saveOptions);
if (resource.getTimeStamp() != timeStamp) {
savedResources.add(resource);
}
} catch (Exception exception) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
first = false;
}
}
for (Leg l : leg.getOnlineCollaborationSession().getLegs()) {
if(l instanceof OnlineLeg) {
OnlineLeg onlineLeg = (OnlineLeg) l;
onlineLeg.saveExecuted();
}
}
}
};
updateProblemIndication = false;
try {
// This runs the options, and shows progress.
//
new ProgressMonitorDialog(getSite().getShell()).run(true, false, operation);
// Refresh the necessary state.
//
((BasicCommandStack) editingDomain.getCommandStack()).saveIsDone();
firePropertyChange(IEditorPart.PROP_DIRTY);
} catch (Exception exception) {
// Something went wrong that shouldn't.
//
WTSpec4MEditorPlugin.INSTANCE.log(exception);
}
updateProblemIndication = true;
updateProblemIndication();
}
/**
* This returns whether something has been persisted to the URI of the
* specified resource. The implementation uses the URI converter from the
* editor's resource set to try to open an input stream. <!-- begin-user-doc
* --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean isPersisted(Resource resource) {
boolean result = false;
try {
InputStream stream = editingDomain.getResourceSet().getURIConverter().createInputStream(resource.getURI());
if (stream != null) {
result = true;
stream.close();
}
} catch (IOException e) {
// Ignore
}
return result;
}
/**
* This always returns true because it is not currently supported. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean isSaveAsAllowed() {
return true;
}
/**
* This also changes the editor's input. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
@Override
public void doSaveAs() {
new ResourceDialog(getSite().getShell(), null, SWT.NONE) {
@Override
protected boolean isSave() {
return true;
}
@Override
protected boolean processResources() {
List<URI> uris = getURIs();
if (uris.size() > 0) {
URI uri = uris.get(0);
doSaveAs(uri, new URIEditorInput(uri));
return true;
} else {
return false;
}
}
}.open();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected void doSaveAs(URI uri, IEditorInput editorInput) {
(editingDomain.getResourceSet().getResources().get(0)).setURI(uri);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
IProgressMonitor progressMonitor = getActionBars().getStatusLineManager() != null
? getActionBars().getStatusLineManager().getProgressMonitor() : new NullProgressMonitor();
doSave(progressMonitor);
}
/**
* This is called during startup. <!-- begin-user-doc --> <!-- end-user-doc
* -->
*
* @generated
*/
@Override
public void init(IEditorSite site, IEditorInput editorInput) {
setSite(site);
setInputWithNotify(editorInput);
setPartName(editorInput.getName());
site.setSelectionProvider(this);
site.getPage().addPartListener(partListener);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setFocus() {
if (currentViewerPane != null) {
currentViewerPane.setFocus();
} else {
getControl(getActivePage()).setFocus();
}
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider}.
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to
* return this editor's overall selection. <!-- begin-user-doc --> <!--
* end-user-doc -->
*
* @generated
*/
public ISelection getSelection() {
return editorSelection;
}
/**
* This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to
* set this editor's overall selection. Calling this result will notify the
* listeners. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setSelection(ISelection selection) {
editorSelection = selection;
for (ISelectionChangedListener listener : selectionChangedListeners) {
listener.selectionChanged(new SelectionChangedEvent(this, selection));
}
setStatusLineManager(selection);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setStatusLineManager(ISelection selection) {
IStatusLineManager statusLineManager = currentViewer != null && currentViewer == contentOutlineViewer
? contentOutlineStatusLineManager : getActionBars().getStatusLineManager();
if (statusLineManager != null) {
if (selection instanceof IStructuredSelection) {
Collection<?> collection = ((IStructuredSelection) selection).toList();
switch (collection.size()) {
case 0: {
statusLineManager.setMessage(getString("_UI_NoObjectSelected"));
break;
}
case 1: {
String text = new AdapterFactoryItemDelegator(adapterFactory).getText(collection.iterator().next());
statusLineManager.setMessage(getString("_UI_SingleObjectSelected", text));
break;
}
default: {
statusLineManager
.setMessage(getString("_UI_MultiObjectSelected", Integer.toString(collection.size())));
break;
}
}
} else {
statusLineManager.setMessage("");
}
}
}
/**
* This looks up a string in the plugin's plugin.properties file. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
private static String getString(String key) {
return WTSpec4MEditorPlugin.INSTANCE.getString(key);
}
/**
* This looks up a string in plugin.properties, making a substitution. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
private static String getString(String key, Object s1) {
return WTSpec4MEditorPlugin.INSTANCE.getString(key, new Object[] { s1 });
}
/**
* This implements {@link org.eclipse.jface.action.IMenuListener} to help
* fill the context menus with contributions from the Edit menu. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void menuAboutToShow(IMenuManager menuManager) {
((IMenuListener) getEditorSite().getActionBarContributor()).menuAboutToShow(menuManager);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public EditingDomainActionBarContributor getActionBarContributor() {
return (EditingDomainActionBarContributor) getEditorSite().getActionBarContributor();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public IActionBars getActionBars() {
return getActionBarContributor().getActionBars();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public AdapterFactory getAdapterFactory() {
return adapterFactory;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void dispose() {
updateProblemIndication = false;
getSite().getPage().removePartListener(partListener);
adapterFactory.dispose();
if (getActionBarContributor().getActiveEditor() == this) {
getActionBarContributor().setActiveEditor(null);
}
for (PropertySheetPage propertySheetPage : propertySheetPages) {
propertySheetPage.dispose();
}
if (contentOutlinePage != null) {
contentOutlinePage.dispose();
}
super.dispose();
}
/**
* Returns whether the outline view should be presented to the user. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected boolean showOutlineView() {
return true;
}
}
| Uses the common date format for logging | MONDO-Collab/org.mondo.wt.cstudy.metamodel.editor/src/WTSpec4M/presentation/WTSpec4MEditor.java | Uses the common date format for logging | <ide><path>ONDO-Collab/org.mondo.wt.cstudy.metamodel.editor/src/WTSpec4M/presentation/WTSpec4MEditor.java
<ide> }
<ide> editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter);
<ide>
<del> final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
<del>
<ide> // Submit changes for lens
<ide> editingDomain.getCommandStack().addCommandStackListener(new CommandStackListener() {
<ide>
<ide> String username = ModelExplorer.getCurrentStorageAccess().getUsername();
<ide>
<ide> Date now = new Date();
<del> String strDate = sdf.format(now);
<add> String strDate = ModelExplorer.DATE_FORMAT.format(now);
<ide>
<ide> String commandLabel = mostRecentCommand.getLabel();
<ide> String logString = logView.getLogString();
<ide> Collection<?> affectedObjects = mostRecentCommand.getAffectedObjects();
<ide> String affectedObjectETypes = "";
<ide> for (Object object : affectedObjects) {
<del> // TODO collect more details here
<add> // TODO collect more details here about the executed command
<ide> affectedObjectETypes += (((EObject) object).eClass().getName()+ " ");
<ide> }
<ide> |
|
Java | epl-1.0 | 0e02f916d4e6b0f4c2921d0af9fa4998e72d30ef | 0 | kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder,kasemir/org.csstudio.display.builder,ESSICS/org.csstudio.display.builder | /*******************************************************************************
* Copyright (c) 2015-2016 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.csstudio.display.builder.runtime.test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import org.csstudio.display.builder.model.util.VTypeUtil;
import org.csstudio.display.builder.runtime.pv.PVFactory;
import org.csstudio.display.builder.runtime.pv.RuntimePV;
import org.csstudio.display.builder.runtime.pv.RuntimePVListener;
import org.csstudio.vtype.pv.PVPool;
import org.csstudio.vtype.pv.local.LocalPVFactory;
import org.diirt.vtype.VType;
import org.junit.BeforeClass;
import org.junit.Test;
/** JUnit demo of the {@link PVFactory}
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class PVFactoryTest
{
@BeforeClass
public static void setup()
{
PVPool.addPVFactory(new LocalPVFactory());
}
@Test
public void testPVFactory() throws Exception
{
final RuntimePV pv = PVFactory.getPV("loc://test(3.14)");
try
{ // vtype.pv uses the base name, without initializer
assertThat(pv.getName(), equalTo("loc://test"));
final CountDownLatch updates = new CountDownLatch(1);
final AtomicReference<Number> number = new AtomicReference<>();
RuntimePVListener listener = new RuntimePVListener()
{
@Override
public void valueChanged(RuntimePV pv, VType value)
{
System.out.println(pv.getName() + " = " + value);
number.set(VTypeUtil.getValueNumber(value));
updates.countDown();
}
};
pv.addListener(listener);
updates.await();
assertThat(number.get(), equalTo(3.14));
}
finally
{
PVFactory.releasePV(pv);
}
}
}
| org.csstudio.display.builder.runtime.test/src/org/csstudio/display/builder/runtime/test/PVFactoryTest.java | /*******************************************************************************
* Copyright (c) 2015-2016 Oak Ridge National Laboratory.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.csstudio.display.builder.runtime.test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import java.util.concurrent.CountDownLatch;
import org.csstudio.display.builder.runtime.pv.PVFactory;
import org.csstudio.display.builder.runtime.pv.RuntimePV;
import org.csstudio.display.builder.runtime.pv.RuntimePVListener;
import org.csstudio.vtype.pv.PVPool;
import org.csstudio.vtype.pv.local.LocalPVFactory;
import org.diirt.vtype.VType;
import org.junit.BeforeClass;
import org.junit.Test;
/** JUnit demo of the {@link PVFactory}
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class PVFactoryTest
{
@BeforeClass
public static void setup()
{
PVPool.addPVFactory(new LocalPVFactory());
}
@Test
public void testPVFactory() throws Exception
{
final RuntimePV pv = PVFactory.getPV("loc://test(3.14)");
try
{
assertThat(pv.getName(), equalTo("loc://test(3.14)"));
final CountDownLatch updates = new CountDownLatch(1);
RuntimePVListener listener = new RuntimePVListener()
{
@Override
public void valueChanged(RuntimePV pv, VType value)
{
System.out.println(pv.getName() + " = " + value);
updates.countDown();
}
};
pv.addListener(listener);
updates.await();
}
finally
{
PVFactory.releasePV(pv);
}
}
}
| PVFactoryTest: loc:// PV now uses the base, w/o initializer, as name | org.csstudio.display.builder.runtime.test/src/org/csstudio/display/builder/runtime/test/PVFactoryTest.java | PVFactoryTest: loc:// PV now uses the base, w/o initializer, as name | <ide><path>rg.csstudio.display.builder.runtime.test/src/org/csstudio/display/builder/runtime/test/PVFactoryTest.java
<ide> import static org.junit.Assert.assertThat;
<ide>
<ide> import java.util.concurrent.CountDownLatch;
<add>import java.util.concurrent.atomic.AtomicReference;
<ide>
<add>import org.csstudio.display.builder.model.util.VTypeUtil;
<ide> import org.csstudio.display.builder.runtime.pv.PVFactory;
<ide> import org.csstudio.display.builder.runtime.pv.RuntimePV;
<ide> import org.csstudio.display.builder.runtime.pv.RuntimePVListener;
<ide> {
<ide> final RuntimePV pv = PVFactory.getPV("loc://test(3.14)");
<ide> try
<del> {
<del> assertThat(pv.getName(), equalTo("loc://test(3.14)"));
<add> { // vtype.pv uses the base name, without initializer
<add> assertThat(pv.getName(), equalTo("loc://test"));
<ide>
<ide> final CountDownLatch updates = new CountDownLatch(1);
<add> final AtomicReference<Number> number = new AtomicReference<>();
<ide> RuntimePVListener listener = new RuntimePVListener()
<ide> {
<ide> @Override
<ide> public void valueChanged(RuntimePV pv, VType value)
<ide> {
<ide> System.out.println(pv.getName() + " = " + value);
<add> number.set(VTypeUtil.getValueNumber(value));
<ide> updates.countDown();
<ide> }
<ide> };
<ide> pv.addListener(listener);
<ide> updates.await();
<add> assertThat(number.get(), equalTo(3.14));
<ide> }
<ide> finally
<ide> { |
|
Java | apache-2.0 | 78357bd4f67a1546fca6798b6759657a8e84083b | 0 | apache/tomcat,Nickname0806/Test_Q4,Nickname0806/Test_Q4,apache/tomcat,Nickname0806/Test_Q4,apache/tomcat,apache/tomcat,apache/tomcat,Nickname0806/Test_Q4 | /*
* 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.catalina.connector;
import java.net.URLEncoder;
import java.util.HashMap;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.catalina.Container;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Service;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.util.LifecycleSupport;
import org.apache.tomcat.util.res.StringManager;
import org.apache.coyote.Adapter;
import org.apache.coyote.ProtocolHandler;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.http.mapper.Mapper;
import org.apache.tomcat.util.modeler.Registry;
/**
* Implementation of a Coyote connector for Tomcat 5.x.
*
* @author Craig R. McClanahan
* @author Remy Maucherat
* @version $Revision$ $Date$
*/
public class Connector
implements Lifecycle, MBeanRegistration
{
private static Log log = LogFactory.getLog(Connector.class);
/**
* Alternate flag to enable recycling of facades.
*/
public static final boolean RECYCLE_FACADES =
Boolean.valueOf(System.getProperty("org.apache.catalina.connector.RECYCLE_FACADES", "false")).booleanValue();
// ------------------------------------------------------------ Constructor
public Connector()
throws Exception {
this(null);
}
public Connector(String protocol) {
setProtocol(protocol);
// Instantiate protocol handler
try {
Class<?> clazz = Class.forName(protocolHandlerClassName);
this.protocolHandler = (ProtocolHandler) clazz.newInstance();
} catch (Exception e) {
log.error
(sm.getString
("coyoteConnector.protocolHandlerInstantiationFailed", e));
}
}
// ----------------------------------------------------- Instance Variables
/**
* The <code>Service</code> we are associated with (if any).
*/
protected Service service = null;
/**
* Do we allow TRACE ?
*/
protected boolean allowTrace = false;
/**
* The Container used for processing requests received by this Connector.
*/
protected Container container = null;
/**
* Use "/" as path for session cookies ?
*/
protected boolean emptySessionPath = false;
/**
* The "enable DNS lookups" flag for this Connector.
*/
protected boolean enableLookups = false;
/*
* Is generation of X-Powered-By response header enabled/disabled?
*/
protected boolean xpoweredBy = false;
/**
* Descriptive information about this Connector implementation.
*/
protected static final String info =
"org.apache.catalina.connector.Connector/2.1";
/**
* The lifecycle event support for this component.
*/
protected LifecycleSupport lifecycle = new LifecycleSupport(this);
/**
* The port number on which we listen for requests.
*/
protected int port = 0;
/**
* The server name to which we should pretend requests to this Connector
* were directed. This is useful when operating Tomcat behind a proxy
* server, so that redirects get constructed accurately. If not specified,
* the server name included in the <code>Host</code> header is used.
*/
protected String proxyName = null;
/**
* The server port to which we should pretent requests to this Connector
* were directed. This is useful when operating Tomcat behind a proxy
* server, so that redirects get constructed accurately. If not specified,
* the port number specified by the <code>port</code> property is used.
*/
protected int proxyPort = 0;
/**
* The redirect port for non-SSL to SSL redirects.
*/
protected int redirectPort = 443;
/**
* The request scheme that will be set on all requests received
* through this connector.
*/
protected String scheme = "http";
/**
* The secure connection flag that will be set on all requests received
* through this connector.
*/
protected boolean secure = false;
/**
* The string manager for this package.
*/
protected StringManager sm =
StringManager.getManager(Constants.Package);
/**
* Maximum size of a POST which will be automatically parsed by the
* container. 2MB by default.
*/
protected int maxPostSize = 2 * 1024 * 1024;
/**
* Maximum size of a POST which will be saved by the container
* during authentication. 4kB by default
*/
protected int maxSavePostSize = 4 * 1024;
/**
* Has this component been initialized yet?
*/
protected boolean initialized = false;
/**
* Has this component been started yet?
*/
protected boolean started = false;
/**
* The shutdown signal to our background thread
*/
protected boolean stopped = false;
/**
* Flag to use IP-based virtual hosting.
*/
protected boolean useIPVHosts = false;
/**
* The background thread.
*/
protected Thread thread = null;
/**
* Coyote Protocol handler class name.
* Defaults to the Coyote HTTP/1.1 protocolHandler.
*/
protected String protocolHandlerClassName =
"org.apache.coyote.http11.Http11Protocol";
/**
* Coyote protocol handler.
*/
protected ProtocolHandler protocolHandler = null;
/**
* Coyote adapter.
*/
protected Adapter adapter = null;
/**
* Mapper.
*/
protected Mapper mapper = new Mapper();
/**
* Mapper listener.
*/
protected MapperListener mapperListener = new MapperListener(mapper, this);
/**
* URI encoding.
*/
protected String URIEncoding = null;
/**
* URI encoding as body.
*/
protected boolean useBodyEncodingForURI = false;
protected static HashMap<String,String> replacements =
new HashMap<String,String>();
static {
replacements.put("acceptCount", "backlog");
replacements.put("connectionLinger", "soLinger");
replacements.put("connectionTimeout", "soTimeout");
replacements.put("connectionUploadTimeout", "timeout");
replacements.put("clientAuth", "clientauth");
replacements.put("keystoreFile", "keystore");
replacements.put("randomFile", "randomfile");
replacements.put("rootFile", "rootfile");
replacements.put("keystorePass", "keypass");
replacements.put("keystoreType", "keytype");
replacements.put("sslProtocol", "protocol");
replacements.put("sslProtocols", "protocols");
}
// ------------------------------------------------------------- Properties
/**
* Return a configured property.
*/
public Object getProperty(String name) {
String repl = name;
if (replacements.get(name) != null) {
repl = replacements.get(name);
}
return IntrospectionUtils.getProperty(protocolHandler, repl);
}
/**
* Set a configured property.
*/
public boolean setProperty(String name, String value) {
String repl = name;
if (replacements.get(name) != null) {
repl = replacements.get(name);
}
return IntrospectionUtils.setProperty(protocolHandler, repl, value);
}
/**
* Return a configured property.
*/
public Object getAttribute(String name) {
return getProperty(name);
}
/**
* Set a configured property.
*/
public void setAttribute(String name, Object value) {
setProperty(name, String.valueOf(value));
}
/**
* remove a configured property.
*/
public void removeProperty(String name) {
// FIXME !
//protocolHandler.removeAttribute(name);
}
/**
* Return the <code>Service</code> with which we are associated (if any).
*/
public Service getService() {
return (this.service);
}
/**
* Set the <code>Service</code> with which we are associated (if any).
*
* @param service The service that owns this Engine
*/
public void setService(Service service) {
this.service = service;
// FIXME: setProperty("service", service);
}
/**
* True if the TRACE method is allowed. Default value is "false".
*/
public boolean getAllowTrace() {
return (this.allowTrace);
}
/**
* Set the allowTrace flag, to disable or enable the TRACE HTTP method.
*
* @param allowTrace The new allowTrace flag
*/
public void setAllowTrace(boolean allowTrace) {
this.allowTrace = allowTrace;
setProperty("allowTrace", String.valueOf(allowTrace));
}
/**
* Is this connector available for processing requests?
*/
public boolean isAvailable() {
return (started);
}
/**
* Return the Container used for processing requests received by this
* Connector.
*/
public Container getContainer() {
if( container==null ) {
// Lazy - maybe it was added later
findContainer();
}
return (container);
}
/**
* Set the Container used for processing requests received by this
* Connector.
*
* @param container The new Container to use
*/
public void setContainer(Container container) {
this.container = container;
}
/**
* Return the "empty session path" flag.
*/
public boolean getEmptySessionPath() {
return (this.emptySessionPath);
}
/**
* Set the "empty session path" flag.
*
* @param emptySessionPath The new "empty session path" flag value
*/
public void setEmptySessionPath(boolean emptySessionPath) {
this.emptySessionPath = emptySessionPath;
setProperty("emptySessionPath", String.valueOf(emptySessionPath));
}
/**
* Return the "enable DNS lookups" flag.
*/
public boolean getEnableLookups() {
return (this.enableLookups);
}
/**
* Set the "enable DNS lookups" flag.
*
* @param enableLookups The new "enable DNS lookups" flag value
*/
public void setEnableLookups(boolean enableLookups) {
this.enableLookups = enableLookups;
setProperty("enableLookups", String.valueOf(enableLookups));
}
/**
* Return descriptive information about this Connector implementation.
*/
public String getInfo() {
return (info);
}
/**
* Return the mapper.
*/
public Mapper getMapper() {
return (mapper);
}
/**
* Return the maximum size of a POST which will be automatically
* parsed by the container.
*/
public int getMaxPostSize() {
return (maxPostSize);
}
/**
* Set the maximum size of a POST which will be automatically
* parsed by the container.
*
* @param maxPostSize The new maximum size in bytes of a POST which will
* be automatically parsed by the container
*/
public void setMaxPostSize(int maxPostSize) {
this.maxPostSize = maxPostSize;
}
/**
* Return the maximum size of a POST which will be saved by the container
* during authentication.
*/
public int getMaxSavePostSize() {
return (maxSavePostSize);
}
/**
* Set the maximum size of a POST which will be saved by the container
* during authentication.
*
* @param maxSavePostSize The new maximum size in bytes of a POST which will
* be saved by the container during authentication.
*/
public void setMaxSavePostSize(int maxSavePostSize) {
this.maxSavePostSize = maxSavePostSize;
setProperty("maxSavePostSize", String.valueOf(maxSavePostSize));
}
/**
* Return the port number on which we listen for requests.
*/
public int getPort() {
return (this.port);
}
/**
* Set the port number on which we listen for requests.
*
* @param port The new port number
*/
public void setPort(int port) {
this.port = port;
setProperty("port", String.valueOf(port));
}
/**
* Return the Coyote protocol handler in use.
*/
public String getProtocol() {
if ("org.apache.coyote.http11.Http11Protocol".equals
(getProtocolHandlerClassName())
|| "org.apache.coyote.http11.Http11AprProtocol".equals
(getProtocolHandlerClassName())) {
return "HTTP/1.1";
} else if ("org.apache.coyote.ajp.AjpProtocol".equals
(getProtocolHandlerClassName())
|| "org.apache.coyote.ajp.AjpAprProtocol".equals
(getProtocolHandlerClassName())) {
return "AJP/1.3";
}
return getProtocolHandlerClassName();
}
/**
* Set the Coyote protocol which will be used by the connector.
*
* @param protocol The Coyote protocol name
*/
public void setProtocol(String protocol) {
if (AprLifecycleListener.isAprAvailable()) {
if ("HTTP/1.1".equals(protocol)) {
setProtocolHandlerClassName
("org.apache.coyote.http11.Http11AprProtocol");
} else if ("AJP/1.3".equals(protocol)) {
setProtocolHandlerClassName
("org.apache.coyote.ajp.AjpAprProtocol");
} else if (protocol != null) {
setProtocolHandlerClassName(protocol);
} else {
setProtocolHandlerClassName
("org.apache.coyote.http11.Http11AprProtocol");
}
} else {
if ("HTTP/1.1".equals(protocol)) {
setProtocolHandlerClassName
("org.apache.coyote.http11.Http11Protocol");
} else if ("AJP/1.3".equals(protocol)) {
setProtocolHandlerClassName
("org.apache.coyote.ajp.AjpProtocol");
} else if (protocol != null) {
setProtocolHandlerClassName(protocol);
}
}
}
/**
* Return the class name of the Coyote protocol handler in use.
*/
public String getProtocolHandlerClassName() {
return (this.protocolHandlerClassName);
}
/**
* Set the class name of the Coyote protocol handler which will be used
* by the connector.
*
* @param protocolHandlerClassName The new class name
*/
public void setProtocolHandlerClassName(String protocolHandlerClassName) {
this.protocolHandlerClassName = protocolHandlerClassName;
}
/**
* Return the protocol handler associated with the connector.
*/
public ProtocolHandler getProtocolHandler() {
return (this.protocolHandler);
}
/**
* Return the proxy server name for this Connector.
*/
public String getProxyName() {
return (this.proxyName);
}
/**
* Set the proxy server name for this Connector.
*
* @param proxyName The new proxy server name
*/
public void setProxyName(String proxyName) {
if(proxyName != null && proxyName.length() > 0) {
this.proxyName = proxyName;
setProperty("proxyName", proxyName);
} else {
this.proxyName = null;
removeProperty("proxyName");
}
}
/**
* Return the proxy server port for this Connector.
*/
public int getProxyPort() {
return (this.proxyPort);
}
/**
* Set the proxy server port for this Connector.
*
* @param proxyPort The new proxy server port
*/
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
setProperty("proxyPort", String.valueOf(proxyPort));
}
/**
* Return the port number to which a request should be redirected if
* it comes in on a non-SSL port and is subject to a security constraint
* with a transport guarantee that requires SSL.
*/
public int getRedirectPort() {
return (this.redirectPort);
}
/**
* Set the redirect port number.
*
* @param redirectPort The redirect port number (non-SSL to SSL)
*/
public void setRedirectPort(int redirectPort) {
this.redirectPort = redirectPort;
setProperty("redirectPort", String.valueOf(redirectPort));
}
/**
* Return the scheme that will be assigned to requests received
* through this connector. Default value is "http".
*/
public String getScheme() {
return (this.scheme);
}
/**
* Set the scheme that will be assigned to requests received through
* this connector.
*
* @param scheme The new scheme
*/
public void setScheme(String scheme) {
this.scheme = scheme;
}
/**
* Return the secure connection flag that will be assigned to requests
* received through this connector. Default value is "false".
*/
public boolean getSecure() {
return (this.secure);
}
/**
* Set the secure connection flag that will be assigned to requests
* received through this connector.
*
* @param secure The new secure connection flag
*/
public void setSecure(boolean secure) {
this.secure = secure;
setProperty("secure", Boolean.toString(secure));
}
/**
* Return the character encoding to be used for the URI.
*/
public String getURIEncoding() {
return (this.URIEncoding);
}
/**
* Set the URI encoding to be used for the URI.
*
* @param URIEncoding The new URI character encoding.
*/
public void setURIEncoding(String URIEncoding) {
this.URIEncoding = URIEncoding;
setProperty("uRIEncoding", URIEncoding);
}
/**
* Return the true if the entity body encoding should be used for the URI.
*/
public boolean getUseBodyEncodingForURI() {
return (this.useBodyEncodingForURI);
}
/**
* Set if the entity body encoding should be used for the URI.
*
* @param useBodyEncodingForURI The new value for the flag.
*/
public void setUseBodyEncodingForURI(boolean useBodyEncodingForURI) {
this.useBodyEncodingForURI = useBodyEncodingForURI;
setProperty
("useBodyEncodingForURI", String.valueOf(useBodyEncodingForURI));
}
/**
* Indicates whether the generation of an X-Powered-By response header for
* servlet-generated responses is enabled or disabled for this Connector.
*
* @return true if generation of X-Powered-By response header is enabled,
* false otherwise
*/
public boolean getXpoweredBy() {
return xpoweredBy;
}
/**
* Enables or disables the generation of an X-Powered-By header (with value
* Servlet/2.5) for all servlet-generated responses returned by this
* Connector.
*
* @param xpoweredBy true if generation of X-Powered-By response header is
* to be enabled, false otherwise
*/
public void setXpoweredBy(boolean xpoweredBy) {
this.xpoweredBy = xpoweredBy;
setProperty("xpoweredBy", String.valueOf(xpoweredBy));
}
/**
* Enable the use of IP-based virtual hosting.
*
* @param useIPVHosts <code>true</code> if Hosts are identified by IP,
* <code>false/code> if Hosts are identified by name.
*/
public void setUseIPVHosts(boolean useIPVHosts) {
this.useIPVHosts = useIPVHosts;
setProperty("useIPVHosts", String.valueOf(useIPVHosts));
}
/**
* Test if IP-based virtual hosting is enabled.
*/
public boolean getUseIPVHosts() {
return useIPVHosts;
}
// --------------------------------------------------------- Public Methods
/**
* Create (or allocate) and return a Request object suitable for
* specifying the contents of a Request to the responsible Container.
*/
public Request createRequest() {
Request request = new Request();
request.setConnector(this);
return (request);
}
/**
* Create (or allocate) and return a Response object suitable for
* receiving the contents of a Response from the responsible Container.
*/
public Response createResponse() {
Response response = new Response();
response.setConnector(this);
return (response);
}
// ------------------------------------------------------ Lifecycle Methods
/**
* Add a lifecycle event listener to this component.
*
* @param listener The listener to add
*/
public void addLifecycleListener(LifecycleListener listener) {
lifecycle.addLifecycleListener(listener);
}
/**
* Get the lifecycle listeners associated with this lifecycle. If this
* Lifecycle has no listeners registered, a zero-length array is returned.
*/
public LifecycleListener[] findLifecycleListeners() {
return lifecycle.findLifecycleListeners();
}
/**
* Remove a lifecycle event listener from this component.
*
* @param listener The listener to add
*/
public void removeLifecycleListener(LifecycleListener listener) {
lifecycle.removeLifecycleListener(listener);
}
protected ObjectName createObjectName(String domain, String type)
throws MalformedObjectNameException {
String encodedAddr = null;
if (getProperty("address") != null) {
encodedAddr = URLEncoder.encode(getProperty("address").toString());
}
String addSuffix = (getProperty("address") == null) ? "" : ",address="
+ encodedAddr;
ObjectName _oname = new ObjectName(domain + ":type=" + type + ",port="
+ getPort() + addSuffix);
return _oname;
}
/**
* Initialize this connector (create ServerSocket here!)
*/
public void initialize()
throws LifecycleException
{
if (initialized) {
if(log.isInfoEnabled())
log.info(sm.getString("coyoteConnector.alreadyInitialized"));
return;
}
this.initialized = true;
if( oname == null && (container instanceof StandardEngine)) {
try {
// we are loaded directly, via API - and no name was given to us
StandardEngine cb=(StandardEngine)container;
oname = createObjectName(cb.getName(), "Connector");
Registry.getRegistry(null, null)
.registerComponent(this, oname, null);
controller=oname;
} catch (Exception e) {
log.error( "Error registering connector ", e);
}
if(log.isDebugEnabled())
log.debug("Creating name for connector " + oname);
}
// Initializa adapter
adapter = new CoyoteAdapter(this);
protocolHandler.setAdapter(adapter);
IntrospectionUtils.setProperty(protocolHandler, "jkHome",
System.getProperty("catalina.base"));
try {
protocolHandler.init();
} catch (Exception e) {
throw new LifecycleException
(sm.getString
("coyoteConnector.protocolHandlerInitializationFailed", e));
}
}
/**
* Pause the connector.
*/
public void pause()
throws LifecycleException {
try {
protocolHandler.pause();
} catch (Exception e) {
log.error(sm.getString
("coyoteConnector.protocolHandlerPauseFailed"), e);
}
}
/**
* Pause the connector.
*/
public void resume()
throws LifecycleException {
try {
protocolHandler.resume();
} catch (Exception e) {
log.error(sm.getString
("coyoteConnector.protocolHandlerResumeFailed"), e);
}
}
/**
* Begin processing requests via this Connector.
*
* @exception LifecycleException if a fatal startup error occurs
*/
public void start() throws LifecycleException {
if( !initialized )
initialize();
// Validate and update our current state
if (started ) {
if(log.isInfoEnabled())
log.info(sm.getString("coyoteConnector.alreadyStarted"));
return;
}
lifecycle.fireLifecycleEvent(START_EVENT, null);
started = true;
// We can't register earlier - the JMX registration of this happens
// in Server.start callback
if ( this.oname != null ) {
// We are registred - register the adapter as well.
try {
Registry.getRegistry(null, null).registerComponent
(protocolHandler, createObjectName(this.domain,"ProtocolHandler"), null);
} catch (Exception ex) {
log.error(sm.getString
("coyoteConnector.protocolRegistrationFailed"), ex);
}
} else {
if(log.isInfoEnabled())
log.info(sm.getString
("coyoteConnector.cannotRegisterProtocol"));
}
try {
protocolHandler.start();
} catch (Exception e) {
String errPrefix = "";
if(this.service != null) {
errPrefix += "service.getName(): \"" + this.service.getName() + "\"; ";
}
throw new LifecycleException
(errPrefix + " " + sm.getString
("coyoteConnector.protocolHandlerStartFailed", e));
}
if( this.domain != null ) {
mapperListener.setDomain( domain );
//mapperListener.setEngine( service.getContainer().getName() );
mapperListener.init();
try {
ObjectName mapperOname = createObjectName(this.domain,"Mapper");
if (log.isDebugEnabled())
log.debug(sm.getString(
"coyoteConnector.MapperRegistration", mapperOname));
Registry.getRegistry(null, null).registerComponent
(mapper, mapperOname, "Mapper");
} catch (Exception ex) {
log.error(sm.getString
("coyoteConnector.protocolRegistrationFailed"), ex);
}
}
}
/**
* Terminate processing requests via this Connector.
*
* @exception LifecycleException if a fatal shutdown error occurs
*/
public void stop() throws LifecycleException {
// Validate and update our current state
if (!started) {
log.error(sm.getString("coyoteConnector.notStarted"));
return;
}
lifecycle.fireLifecycleEvent(STOP_EVENT, null);
started = false;
try {
mapperListener.destroy();
Registry.getRegistry(null, null).unregisterComponent
(createObjectName(this.domain,"Mapper"));
Registry.getRegistry(null, null).unregisterComponent
(createObjectName(this.domain,"ProtocolHandler"));
} catch (MalformedObjectNameException e) {
log.error( sm.getString
("coyoteConnector.protocolUnregistrationFailed"), e);
}
try {
protocolHandler.destroy();
} catch (Exception e) {
throw new LifecycleException
(sm.getString
("coyoteConnector.protocolHandlerDestroyFailed", e));
}
}
// -------------------- JMX registration --------------------
protected String domain;
protected ObjectName oname;
protected MBeanServer mserver;
ObjectName controller;
public ObjectName getController() {
return controller;
}
public void setController(ObjectName controller) {
this.controller = controller;
}
public ObjectName getObjectName() {
return oname;
}
public String getDomain() {
return domain;
}
public ObjectName preRegister(MBeanServer server,
ObjectName name) throws Exception {
oname=name;
mserver=server;
domain=name.getDomain();
return name;
}
public void postRegister(Boolean registrationDone) {
}
public void preDeregister() throws Exception {
}
public void postDeregister() {
try {
if( started ) {
stop();
}
} catch( Throwable t ) {
log.error( "Unregistering - can't stop", t);
}
}
protected void findContainer() {
try {
// Register to the service
ObjectName parentName=new ObjectName( domain + ":" +
"type=Service");
if(log.isDebugEnabled())
log.debug("Adding to " + parentName );
if( mserver.isRegistered(parentName )) {
mserver.invoke(parentName, "addConnector", new Object[] { this },
new String[] {"org.apache.catalina.connector.Connector"});
// As a side effect we'll get the container field set
// Also initialize will be called
//return;
}
// XXX Go directly to the Engine
// initialize(); - is called by addConnector
ObjectName engName=new ObjectName( domain + ":" + "type=Engine");
if( mserver.isRegistered(engName )) {
Object obj=mserver.getAttribute(engName, "managedResource");
if(log.isDebugEnabled())
log.debug("Found engine " + obj + " " + obj.getClass());
container=(Container)obj;
// Internal initialize - we now have the Engine
initialize();
if(log.isDebugEnabled())
log.debug("Initialized");
// As a side effect we'll get the container field set
// Also initialize will be called
return;
}
} catch( Exception ex ) {
log.error( "Error finding container " + ex);
}
}
public void init() throws Exception {
if( this.getService() != null ) {
if(log.isDebugEnabled())
log.debug( "Already configured" );
return;
}
if( container==null ) {
findContainer();
}
}
public void destroy() throws Exception {
if( oname!=null && controller==oname ) {
if(log.isDebugEnabled())
log.debug("Unregister itself " + oname );
Registry.getRegistry(null, null).unregisterComponent(oname);
}
if( getService() == null)
return;
getService().removeConnector(this);
}
}
| java/org/apache/catalina/connector/Connector.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.catalina.connector;
import java.net.URLEncoder;
import java.util.HashMap;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.catalina.Container;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Service;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.util.LifecycleSupport;
import org.apache.tomcat.util.res.StringManager;
import org.apache.coyote.Adapter;
import org.apache.coyote.ProtocolHandler;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.http.mapper.Mapper;
import org.apache.tomcat.util.modeler.Registry;
/**
* Implementation of a Coyote connector for Tomcat 5.x.
*
* @author Craig R. McClanahan
* @author Remy Maucherat
* @version $Revision$ $Date$
*/
public class Connector
implements Lifecycle, MBeanRegistration
{
private static Log log = LogFactory.getLog(Connector.class);
/**
* Alternate flag to enable recycling of facades.
*/
public static final boolean RECYCLE_FACADES =
Boolean.valueOf(System.getProperty("org.apache.catalina.connector.RECYCLE_FACADES", "false")).booleanValue();
// ------------------------------------------------------------ Constructor
public Connector()
throws Exception {
this(null);
}
public Connector(String protocol)
throws Exception {
setProtocol(protocol);
// Instantiate protocol handler
try {
Class<?> clazz = Class.forName(protocolHandlerClassName);
this.protocolHandler = (ProtocolHandler) clazz.newInstance();
} catch (Exception e) {
log.error
(sm.getString
("coyoteConnector.protocolHandlerInstantiationFailed", e));
}
}
// ----------------------------------------------------- Instance Variables
/**
* The <code>Service</code> we are associated with (if any).
*/
protected Service service = null;
/**
* Do we allow TRACE ?
*/
protected boolean allowTrace = false;
/**
* The Container used for processing requests received by this Connector.
*/
protected Container container = null;
/**
* Use "/" as path for session cookies ?
*/
protected boolean emptySessionPath = false;
/**
* The "enable DNS lookups" flag for this Connector.
*/
protected boolean enableLookups = false;
/*
* Is generation of X-Powered-By response header enabled/disabled?
*/
protected boolean xpoweredBy = false;
/**
* Descriptive information about this Connector implementation.
*/
protected static final String info =
"org.apache.catalina.connector.Connector/2.1";
/**
* The lifecycle event support for this component.
*/
protected LifecycleSupport lifecycle = new LifecycleSupport(this);
/**
* The port number on which we listen for requests.
*/
protected int port = 0;
/**
* The server name to which we should pretend requests to this Connector
* were directed. This is useful when operating Tomcat behind a proxy
* server, so that redirects get constructed accurately. If not specified,
* the server name included in the <code>Host</code> header is used.
*/
protected String proxyName = null;
/**
* The server port to which we should pretent requests to this Connector
* were directed. This is useful when operating Tomcat behind a proxy
* server, so that redirects get constructed accurately. If not specified,
* the port number specified by the <code>port</code> property is used.
*/
protected int proxyPort = 0;
/**
* The redirect port for non-SSL to SSL redirects.
*/
protected int redirectPort = 443;
/**
* The request scheme that will be set on all requests received
* through this connector.
*/
protected String scheme = "http";
/**
* The secure connection flag that will be set on all requests received
* through this connector.
*/
protected boolean secure = false;
/**
* The string manager for this package.
*/
protected StringManager sm =
StringManager.getManager(Constants.Package);
/**
* Maximum size of a POST which will be automatically parsed by the
* container. 2MB by default.
*/
protected int maxPostSize = 2 * 1024 * 1024;
/**
* Maximum size of a POST which will be saved by the container
* during authentication. 4kB by default
*/
protected int maxSavePostSize = 4 * 1024;
/**
* Has this component been initialized yet?
*/
protected boolean initialized = false;
/**
* Has this component been started yet?
*/
protected boolean started = false;
/**
* The shutdown signal to our background thread
*/
protected boolean stopped = false;
/**
* Flag to use IP-based virtual hosting.
*/
protected boolean useIPVHosts = false;
/**
* The background thread.
*/
protected Thread thread = null;
/**
* Coyote Protocol handler class name.
* Defaults to the Coyote HTTP/1.1 protocolHandler.
*/
protected String protocolHandlerClassName =
"org.apache.coyote.http11.Http11Protocol";
/**
* Coyote protocol handler.
*/
protected ProtocolHandler protocolHandler = null;
/**
* Coyote adapter.
*/
protected Adapter adapter = null;
/**
* Mapper.
*/
protected Mapper mapper = new Mapper();
/**
* Mapper listener.
*/
protected MapperListener mapperListener = new MapperListener(mapper, this);
/**
* URI encoding.
*/
protected String URIEncoding = null;
/**
* URI encoding as body.
*/
protected boolean useBodyEncodingForURI = false;
protected static HashMap<String,String> replacements =
new HashMap<String,String>();
static {
replacements.put("acceptCount", "backlog");
replacements.put("connectionLinger", "soLinger");
replacements.put("connectionTimeout", "soTimeout");
replacements.put("connectionUploadTimeout", "timeout");
replacements.put("clientAuth", "clientauth");
replacements.put("keystoreFile", "keystore");
replacements.put("randomFile", "randomfile");
replacements.put("rootFile", "rootfile");
replacements.put("keystorePass", "keypass");
replacements.put("keystoreType", "keytype");
replacements.put("sslProtocol", "protocol");
replacements.put("sslProtocols", "protocols");
}
// ------------------------------------------------------------- Properties
/**
* Return a configured property.
*/
public Object getProperty(String name) {
String repl = name;
if (replacements.get(name) != null) {
repl = replacements.get(name);
}
return IntrospectionUtils.getProperty(protocolHandler, repl);
}
/**
* Set a configured property.
*/
public boolean setProperty(String name, String value) {
String repl = name;
if (replacements.get(name) != null) {
repl = replacements.get(name);
}
return IntrospectionUtils.setProperty(protocolHandler, repl, value);
}
/**
* Return a configured property.
*/
public Object getAttribute(String name) {
return getProperty(name);
}
/**
* Set a configured property.
*/
public void setAttribute(String name, Object value) {
setProperty(name, String.valueOf(value));
}
/**
* remove a configured property.
*/
public void removeProperty(String name) {
// FIXME !
//protocolHandler.removeAttribute(name);
}
/**
* Return the <code>Service</code> with which we are associated (if any).
*/
public Service getService() {
return (this.service);
}
/**
* Set the <code>Service</code> with which we are associated (if any).
*
* @param service The service that owns this Engine
*/
public void setService(Service service) {
this.service = service;
// FIXME: setProperty("service", service);
}
/**
* True if the TRACE method is allowed. Default value is "false".
*/
public boolean getAllowTrace() {
return (this.allowTrace);
}
/**
* Set the allowTrace flag, to disable or enable the TRACE HTTP method.
*
* @param allowTrace The new allowTrace flag
*/
public void setAllowTrace(boolean allowTrace) {
this.allowTrace = allowTrace;
setProperty("allowTrace", String.valueOf(allowTrace));
}
/**
* Is this connector available for processing requests?
*/
public boolean isAvailable() {
return (started);
}
/**
* Return the Container used for processing requests received by this
* Connector.
*/
public Container getContainer() {
if( container==null ) {
// Lazy - maybe it was added later
findContainer();
}
return (container);
}
/**
* Set the Container used for processing requests received by this
* Connector.
*
* @param container The new Container to use
*/
public void setContainer(Container container) {
this.container = container;
}
/**
* Return the "empty session path" flag.
*/
public boolean getEmptySessionPath() {
return (this.emptySessionPath);
}
/**
* Set the "empty session path" flag.
*
* @param emptySessionPath The new "empty session path" flag value
*/
public void setEmptySessionPath(boolean emptySessionPath) {
this.emptySessionPath = emptySessionPath;
setProperty("emptySessionPath", String.valueOf(emptySessionPath));
}
/**
* Return the "enable DNS lookups" flag.
*/
public boolean getEnableLookups() {
return (this.enableLookups);
}
/**
* Set the "enable DNS lookups" flag.
*
* @param enableLookups The new "enable DNS lookups" flag value
*/
public void setEnableLookups(boolean enableLookups) {
this.enableLookups = enableLookups;
setProperty("enableLookups", String.valueOf(enableLookups));
}
/**
* Return descriptive information about this Connector implementation.
*/
public String getInfo() {
return (info);
}
/**
* Return the mapper.
*/
public Mapper getMapper() {
return (mapper);
}
/**
* Return the maximum size of a POST which will be automatically
* parsed by the container.
*/
public int getMaxPostSize() {
return (maxPostSize);
}
/**
* Set the maximum size of a POST which will be automatically
* parsed by the container.
*
* @param maxPostSize The new maximum size in bytes of a POST which will
* be automatically parsed by the container
*/
public void setMaxPostSize(int maxPostSize) {
this.maxPostSize = maxPostSize;
}
/**
* Return the maximum size of a POST which will be saved by the container
* during authentication.
*/
public int getMaxSavePostSize() {
return (maxSavePostSize);
}
/**
* Set the maximum size of a POST which will be saved by the container
* during authentication.
*
* @param maxSavePostSize The new maximum size in bytes of a POST which will
* be saved by the container during authentication.
*/
public void setMaxSavePostSize(int maxSavePostSize) {
this.maxSavePostSize = maxSavePostSize;
setProperty("maxSavePostSize", String.valueOf(maxSavePostSize));
}
/**
* Return the port number on which we listen for requests.
*/
public int getPort() {
return (this.port);
}
/**
* Set the port number on which we listen for requests.
*
* @param port The new port number
*/
public void setPort(int port) {
this.port = port;
setProperty("port", String.valueOf(port));
}
/**
* Return the Coyote protocol handler in use.
*/
public String getProtocol() {
if ("org.apache.coyote.http11.Http11Protocol".equals
(getProtocolHandlerClassName())
|| "org.apache.coyote.http11.Http11AprProtocol".equals
(getProtocolHandlerClassName())) {
return "HTTP/1.1";
} else if ("org.apache.coyote.ajp.AjpProtocol".equals
(getProtocolHandlerClassName())
|| "org.apache.coyote.ajp.AjpAprProtocol".equals
(getProtocolHandlerClassName())) {
return "AJP/1.3";
}
return getProtocolHandlerClassName();
}
/**
* Set the Coyote protocol which will be used by the connector.
*
* @param protocol The Coyote protocol name
*/
public void setProtocol(String protocol) {
if (AprLifecycleListener.isAprAvailable()) {
if ("HTTP/1.1".equals(protocol)) {
setProtocolHandlerClassName
("org.apache.coyote.http11.Http11AprProtocol");
} else if ("AJP/1.3".equals(protocol)) {
setProtocolHandlerClassName
("org.apache.coyote.ajp.AjpAprProtocol");
} else if (protocol != null) {
setProtocolHandlerClassName(protocol);
} else {
setProtocolHandlerClassName
("org.apache.coyote.http11.Http11AprProtocol");
}
} else {
if ("HTTP/1.1".equals(protocol)) {
setProtocolHandlerClassName
("org.apache.coyote.http11.Http11Protocol");
} else if ("AJP/1.3".equals(protocol)) {
setProtocolHandlerClassName
("org.apache.coyote.ajp.AjpProtocol");
} else if (protocol != null) {
setProtocolHandlerClassName(protocol);
}
}
}
/**
* Return the class name of the Coyote protocol handler in use.
*/
public String getProtocolHandlerClassName() {
return (this.protocolHandlerClassName);
}
/**
* Set the class name of the Coyote protocol handler which will be used
* by the connector.
*
* @param protocolHandlerClassName The new class name
*/
public void setProtocolHandlerClassName(String protocolHandlerClassName) {
this.protocolHandlerClassName = protocolHandlerClassName;
}
/**
* Return the protocol handler associated with the connector.
*/
public ProtocolHandler getProtocolHandler() {
return (this.protocolHandler);
}
/**
* Return the proxy server name for this Connector.
*/
public String getProxyName() {
return (this.proxyName);
}
/**
* Set the proxy server name for this Connector.
*
* @param proxyName The new proxy server name
*/
public void setProxyName(String proxyName) {
if(proxyName != null && proxyName.length() > 0) {
this.proxyName = proxyName;
setProperty("proxyName", proxyName);
} else {
this.proxyName = null;
removeProperty("proxyName");
}
}
/**
* Return the proxy server port for this Connector.
*/
public int getProxyPort() {
return (this.proxyPort);
}
/**
* Set the proxy server port for this Connector.
*
* @param proxyPort The new proxy server port
*/
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
setProperty("proxyPort", String.valueOf(proxyPort));
}
/**
* Return the port number to which a request should be redirected if
* it comes in on a non-SSL port and is subject to a security constraint
* with a transport guarantee that requires SSL.
*/
public int getRedirectPort() {
return (this.redirectPort);
}
/**
* Set the redirect port number.
*
* @param redirectPort The redirect port number (non-SSL to SSL)
*/
public void setRedirectPort(int redirectPort) {
this.redirectPort = redirectPort;
setProperty("redirectPort", String.valueOf(redirectPort));
}
/**
* Return the scheme that will be assigned to requests received
* through this connector. Default value is "http".
*/
public String getScheme() {
return (this.scheme);
}
/**
* Set the scheme that will be assigned to requests received through
* this connector.
*
* @param scheme The new scheme
*/
public void setScheme(String scheme) {
this.scheme = scheme;
}
/**
* Return the secure connection flag that will be assigned to requests
* received through this connector. Default value is "false".
*/
public boolean getSecure() {
return (this.secure);
}
/**
* Set the secure connection flag that will be assigned to requests
* received through this connector.
*
* @param secure The new secure connection flag
*/
public void setSecure(boolean secure) {
this.secure = secure;
setProperty("secure", Boolean.toString(secure));
}
/**
* Return the character encoding to be used for the URI.
*/
public String getURIEncoding() {
return (this.URIEncoding);
}
/**
* Set the URI encoding to be used for the URI.
*
* @param URIEncoding The new URI character encoding.
*/
public void setURIEncoding(String URIEncoding) {
this.URIEncoding = URIEncoding;
setProperty("uRIEncoding", URIEncoding);
}
/**
* Return the true if the entity body encoding should be used for the URI.
*/
public boolean getUseBodyEncodingForURI() {
return (this.useBodyEncodingForURI);
}
/**
* Set if the entity body encoding should be used for the URI.
*
* @param useBodyEncodingForURI The new value for the flag.
*/
public void setUseBodyEncodingForURI(boolean useBodyEncodingForURI) {
this.useBodyEncodingForURI = useBodyEncodingForURI;
setProperty
("useBodyEncodingForURI", String.valueOf(useBodyEncodingForURI));
}
/**
* Indicates whether the generation of an X-Powered-By response header for
* servlet-generated responses is enabled or disabled for this Connector.
*
* @return true if generation of X-Powered-By response header is enabled,
* false otherwise
*/
public boolean getXpoweredBy() {
return xpoweredBy;
}
/**
* Enables or disables the generation of an X-Powered-By header (with value
* Servlet/2.5) for all servlet-generated responses returned by this
* Connector.
*
* @param xpoweredBy true if generation of X-Powered-By response header is
* to be enabled, false otherwise
*/
public void setXpoweredBy(boolean xpoweredBy) {
this.xpoweredBy = xpoweredBy;
setProperty("xpoweredBy", String.valueOf(xpoweredBy));
}
/**
* Enable the use of IP-based virtual hosting.
*
* @param useIPVHosts <code>true</code> if Hosts are identified by IP,
* <code>false/code> if Hosts are identified by name.
*/
public void setUseIPVHosts(boolean useIPVHosts) {
this.useIPVHosts = useIPVHosts;
setProperty("useIPVHosts", String.valueOf(useIPVHosts));
}
/**
* Test if IP-based virtual hosting is enabled.
*/
public boolean getUseIPVHosts() {
return useIPVHosts;
}
// --------------------------------------------------------- Public Methods
/**
* Create (or allocate) and return a Request object suitable for
* specifying the contents of a Request to the responsible Container.
*/
public Request createRequest() {
Request request = new Request();
request.setConnector(this);
return (request);
}
/**
* Create (or allocate) and return a Response object suitable for
* receiving the contents of a Response from the responsible Container.
*/
public Response createResponse() {
Response response = new Response();
response.setConnector(this);
return (response);
}
// ------------------------------------------------------ Lifecycle Methods
/**
* Add a lifecycle event listener to this component.
*
* @param listener The listener to add
*/
public void addLifecycleListener(LifecycleListener listener) {
lifecycle.addLifecycleListener(listener);
}
/**
* Get the lifecycle listeners associated with this lifecycle. If this
* Lifecycle has no listeners registered, a zero-length array is returned.
*/
public LifecycleListener[] findLifecycleListeners() {
return lifecycle.findLifecycleListeners();
}
/**
* Remove a lifecycle event listener from this component.
*
* @param listener The listener to add
*/
public void removeLifecycleListener(LifecycleListener listener) {
lifecycle.removeLifecycleListener(listener);
}
protected ObjectName createObjectName(String domain, String type)
throws MalformedObjectNameException {
String encodedAddr = null;
if (getProperty("address") != null) {
encodedAddr = URLEncoder.encode(getProperty("address").toString());
}
String addSuffix = (getProperty("address") == null) ? "" : ",address="
+ encodedAddr;
ObjectName _oname = new ObjectName(domain + ":type=" + type + ",port="
+ getPort() + addSuffix);
return _oname;
}
/**
* Initialize this connector (create ServerSocket here!)
*/
public void initialize()
throws LifecycleException
{
if (initialized) {
if(log.isInfoEnabled())
log.info(sm.getString("coyoteConnector.alreadyInitialized"));
return;
}
this.initialized = true;
if( oname == null && (container instanceof StandardEngine)) {
try {
// we are loaded directly, via API - and no name was given to us
StandardEngine cb=(StandardEngine)container;
oname = createObjectName(cb.getName(), "Connector");
Registry.getRegistry(null, null)
.registerComponent(this, oname, null);
controller=oname;
} catch (Exception e) {
log.error( "Error registering connector ", e);
}
if(log.isDebugEnabled())
log.debug("Creating name for connector " + oname);
}
// Initializa adapter
adapter = new CoyoteAdapter(this);
protocolHandler.setAdapter(adapter);
IntrospectionUtils.setProperty(protocolHandler, "jkHome",
System.getProperty("catalina.base"));
try {
protocolHandler.init();
} catch (Exception e) {
throw new LifecycleException
(sm.getString
("coyoteConnector.protocolHandlerInitializationFailed", e));
}
}
/**
* Pause the connector.
*/
public void pause()
throws LifecycleException {
try {
protocolHandler.pause();
} catch (Exception e) {
log.error(sm.getString
("coyoteConnector.protocolHandlerPauseFailed"), e);
}
}
/**
* Pause the connector.
*/
public void resume()
throws LifecycleException {
try {
protocolHandler.resume();
} catch (Exception e) {
log.error(sm.getString
("coyoteConnector.protocolHandlerResumeFailed"), e);
}
}
/**
* Begin processing requests via this Connector.
*
* @exception LifecycleException if a fatal startup error occurs
*/
public void start() throws LifecycleException {
if( !initialized )
initialize();
// Validate and update our current state
if (started ) {
if(log.isInfoEnabled())
log.info(sm.getString("coyoteConnector.alreadyStarted"));
return;
}
lifecycle.fireLifecycleEvent(START_EVENT, null);
started = true;
// We can't register earlier - the JMX registration of this happens
// in Server.start callback
if ( this.oname != null ) {
// We are registred - register the adapter as well.
try {
Registry.getRegistry(null, null).registerComponent
(protocolHandler, createObjectName(this.domain,"ProtocolHandler"), null);
} catch (Exception ex) {
log.error(sm.getString
("coyoteConnector.protocolRegistrationFailed"), ex);
}
} else {
if(log.isInfoEnabled())
log.info(sm.getString
("coyoteConnector.cannotRegisterProtocol"));
}
try {
protocolHandler.start();
} catch (Exception e) {
String errPrefix = "";
if(this.service != null) {
errPrefix += "service.getName(): \"" + this.service.getName() + "\"; ";
}
throw new LifecycleException
(errPrefix + " " + sm.getString
("coyoteConnector.protocolHandlerStartFailed", e));
}
if( this.domain != null ) {
mapperListener.setDomain( domain );
//mapperListener.setEngine( service.getContainer().getName() );
mapperListener.init();
try {
ObjectName mapperOname = createObjectName(this.domain,"Mapper");
if (log.isDebugEnabled())
log.debug(sm.getString(
"coyoteConnector.MapperRegistration", mapperOname));
Registry.getRegistry(null, null).registerComponent
(mapper, mapperOname, "Mapper");
} catch (Exception ex) {
log.error(sm.getString
("coyoteConnector.protocolRegistrationFailed"), ex);
}
}
}
/**
* Terminate processing requests via this Connector.
*
* @exception LifecycleException if a fatal shutdown error occurs
*/
public void stop() throws LifecycleException {
// Validate and update our current state
if (!started) {
log.error(sm.getString("coyoteConnector.notStarted"));
return;
}
lifecycle.fireLifecycleEvent(STOP_EVENT, null);
started = false;
try {
mapperListener.destroy();
Registry.getRegistry(null, null).unregisterComponent
(createObjectName(this.domain,"Mapper"));
Registry.getRegistry(null, null).unregisterComponent
(createObjectName(this.domain,"ProtocolHandler"));
} catch (MalformedObjectNameException e) {
log.error( sm.getString
("coyoteConnector.protocolUnregistrationFailed"), e);
}
try {
protocolHandler.destroy();
} catch (Exception e) {
throw new LifecycleException
(sm.getString
("coyoteConnector.protocolHandlerDestroyFailed", e));
}
}
// -------------------- JMX registration --------------------
protected String domain;
protected ObjectName oname;
protected MBeanServer mserver;
ObjectName controller;
public ObjectName getController() {
return controller;
}
public void setController(ObjectName controller) {
this.controller = controller;
}
public ObjectName getObjectName() {
return oname;
}
public String getDomain() {
return domain;
}
public ObjectName preRegister(MBeanServer server,
ObjectName name) throws Exception {
oname=name;
mserver=server;
domain=name.getDomain();
return name;
}
public void postRegister(Boolean registrationDone) {
}
public void preDeregister() throws Exception {
}
public void postDeregister() {
try {
if( started ) {
stop();
}
} catch( Throwable t ) {
log.error( "Unregistering - can't stop", t);
}
}
protected void findContainer() {
try {
// Register to the service
ObjectName parentName=new ObjectName( domain + ":" +
"type=Service");
if(log.isDebugEnabled())
log.debug("Adding to " + parentName );
if( mserver.isRegistered(parentName )) {
mserver.invoke(parentName, "addConnector", new Object[] { this },
new String[] {"org.apache.catalina.connector.Connector"});
// As a side effect we'll get the container field set
// Also initialize will be called
//return;
}
// XXX Go directly to the Engine
// initialize(); - is called by addConnector
ObjectName engName=new ObjectName( domain + ":" + "type=Engine");
if( mserver.isRegistered(engName )) {
Object obj=mserver.getAttribute(engName, "managedResource");
if(log.isDebugEnabled())
log.debug("Found engine " + obj + " " + obj.getClass());
container=(Container)obj;
// Internal initialize - we now have the Engine
initialize();
if(log.isDebugEnabled())
log.debug("Initialized");
// As a side effect we'll get the container field set
// Also initialize will be called
return;
}
} catch( Exception ex ) {
log.error( "Error finding container " + ex);
}
}
public void init() throws Exception {
if( this.getService() != null ) {
if(log.isDebugEnabled())
log.debug( "Already configured" );
return;
}
if( container==null ) {
findContainer();
}
}
public void destroy() throws Exception {
if( oname!=null && controller==oname ) {
if(log.isDebugEnabled())
log.debug("Unregister itself " + oname );
Registry.getRegistry(null, null).unregisterComponent(oname);
}
if( getService() == null)
return;
getService().removeConnector(this);
}
}
| Side-effect of fixing https://issues.apache.org/bugzilla/show_bug.cgi?id=47827
No need to declare throws Exception here
git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@815261 13f79535-47bb-0310-9956-ffa450edef68
| java/org/apache/catalina/connector/Connector.java | Side-effect of fixing https://issues.apache.org/bugzilla/show_bug.cgi?id=47827 No need to declare throws Exception here | <ide><path>ava/org/apache/catalina/connector/Connector.java
<ide> this(null);
<ide> }
<ide>
<del> public Connector(String protocol)
<del> throws Exception {
<add> public Connector(String protocol) {
<ide> setProtocol(protocol);
<ide> // Instantiate protocol handler
<ide> try { |
|
Java | apache-2.0 | 903b1bb728853700a7ddb3e0ae618ba6bb0ad18e | 0 | winklerm/drools,manstis/drools,Multi-Support/droolsjbpm-knowledge,manstis/drools,sutaakar/droolsjbpm-knowledge,sotty/droolsjbpm-knowledge,winklerm/drools,bernardator/droolsjbpm-knowledge,bernardator/droolsjbpm-knowledge,winklerm/drools,sutaakar/droolsjbpm-knowledge,manstis/drools,droolsjbpm/droolsjbpm-knowledge,winklerm/drools,droolsjbpm/droolsjbpm-knowledge,Multi-Support/droolsjbpm-knowledge,manstis/drools,rsynek/droolsjbpm-knowledge,reynoldsm88/droolsjbpm-knowledge,manstis/drools,rsynek/droolsjbpm-knowledge,reynoldsm88/droolsjbpm-knowledge,sotty/droolsjbpm-knowledge,winklerm/drools | /*
* 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.kie.api.builder;
/**
* A KieScanner is a scanner of the maven repositories (both local and remote)
* used to automatically discover if there are new releases for a given KieModule and its dependencies
* and eventually deploy them in the KieRepository
*/
public interface KieScanner {
/**
* Starts this KieScanner polling the maven repositories with the given interval expressed in milliseconds
* @throws An IllegalStateException if this KieScanner has been already started
*/
void start(long pollingInterval);
/**
* Stops this KieScanner
*/
void stop();
/**
* Triggers a synchronous scan
*/
void scanNow();
}
| kie-api/src/main/java/org/kie/api/builder/KieScanner.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.kie.api.builder;
import org.kie.api.Service;
/**
* A KieScanner is a scanner of the maven repositories (both local and remote)
* used to automatically discover if there are new releases for a given KieModule and its dependencies
* and eventually deploy them in the KieRepository
*/
public interface KieScanner {
/**
* Starts this KieScanner polling the maven repositories with the given interval expressed in milliseconds
* @throws An IllegalStateException if this KieScanner has been already started
*/
void start(long pollingInterval);
/**
* Stops this KieScanner
*/
void stop();
/**
* Triggers a synchronous scan
*/
void scanNow();
}
| DROOLS-440: adding JMX management mbeans to kie scanner
| kie-api/src/main/java/org/kie/api/builder/KieScanner.java | DROOLS-440: adding JMX management mbeans to kie scanner | <ide><path>ie-api/src/main/java/org/kie/api/builder/KieScanner.java
<ide>
<ide> package org.kie.api.builder;
<ide>
<del>import org.kie.api.Service;
<ide>
<ide> /**
<ide> * A KieScanner is a scanner of the maven repositories (both local and remote) |
|
Java | lgpl-2.1 | 1767b8360d341efe893c2360509c268e2f21f708 | 0 | wolfgangmm/exist,adamretter/exist,dizzzz/exist,adamretter/exist,windauer/exist,lcahlander/exist,dizzzz/exist,windauer/exist,adamretter/exist,dizzzz/exist,lcahlander/exist,wolfgangmm/exist,lcahlander/exist,adamretter/exist,dizzzz/exist,windauer/exist,adamretter/exist,wolfgangmm/exist,wolfgangmm/exist,wolfgangmm/exist,windauer/exist,eXist-db/exist,windauer/exist,adamretter/exist,eXist-db/exist,windauer/exist,eXist-db/exist,lcahlander/exist,wolfgangmm/exist,dizzzz/exist,lcahlander/exist,eXist-db/exist,lcahlander/exist,dizzzz/exist,eXist-db/exist,eXist-db/exist | /*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* [email protected]
* http://www.exist-db.org
*
* 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
*/
package org.exist.storage;
import com.evolvedbinary.j8fu.fsm.AtomicFSM;
import com.evolvedbinary.j8fu.fsm.FSM;
import com.evolvedbinary.j8fu.lazy.AtomicLazyVal;
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.Database;
import org.exist.EXistException;
import org.exist.collections.Collection;
import org.exist.collections.CollectionCache;
import org.exist.collections.CollectionConfiguration;
import org.exist.collections.CollectionConfigurationManager;
import org.exist.collections.triggers.*;
import org.exist.config.ConfigurationDocumentTrigger;
import org.exist.config.Configurator;
import org.exist.config.annotation.ConfigurationClass;
import org.exist.config.annotation.ConfigurationFieldAsAttribute;
import org.exist.debuggee.Debuggee;
import org.exist.debuggee.DebuggeeFactory;
import org.exist.dom.persistent.SymbolTable;
import org.exist.indexing.IndexManager;
import org.exist.management.AgentFactory;
import org.exist.numbering.DLNFactory;
import org.exist.numbering.NodeIdFactory;
import org.exist.plugin.PluginsManager;
import org.exist.plugin.PluginsManagerImpl;
import org.exist.repo.ClasspathHelper;
import org.exist.repo.ExistRepository;
import org.exist.scheduler.Scheduler;
import org.exist.scheduler.impl.QuartzSchedulerImpl;
import org.exist.scheduler.impl.SystemTaskJobImpl;
import org.exist.security.*;
import org.exist.security.SecurityManager;
import org.exist.security.internal.SecurityManagerImpl;
import org.exist.storage.blob.BlobStore;
import org.exist.storage.blob.BlobStoreImplService;
import org.exist.storage.blob.BlobStoreService;
import org.exist.storage.journal.JournalManager;
import org.exist.storage.lock.FileLockService;
import org.exist.storage.lock.LockManager;
import org.exist.storage.recovery.RecoveryManager;
import org.exist.storage.sync.Sync;
import org.exist.storage.sync.SyncTask;
import org.exist.storage.txn.TransactionException;
import org.exist.storage.txn.TransactionManager;
import org.exist.storage.txn.Txn;
import org.exist.util.*;
import org.exist.xmldb.ShutdownListener;
import org.exist.xmldb.XmldbURI;
import org.exist.xquery.PerformanceStats;
import org.exist.xquery.XQuery;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.ref.Reference;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.nio.file.FileStore;
import java.nio.file.Path;
import java.text.NumberFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import static com.evolvedbinary.j8fu.fsm.TransitionTable.transitionTable;
import static org.exist.util.ThreadUtils.nameInstanceThreadGroup;
import static org.exist.util.ThreadUtils.newInstanceThread;
/**
* This class controls all available instances of the database.
* Use it to configure, start and stop database instances.
* You may have multiple instances defined, each using its own configuration.
* To define multiple instances, pass an identification string to
* {@link #configure(String, int, int, Configuration, Optional)}
* and use {@link #getInstance(String)} to retrieve an instance.
*
* @author <a href="mailto:[email protected]">Wolfgang Meier</a>
* @author <a href="mailto:[email protected]">Pierrick Brihaye</a>
* @author <a href="mailto:[email protected]">Adam Retter</a>
*/
@ConfigurationClass("pool")
public class BrokerPool extends BrokerPools implements BrokerPoolConstants, Database {
private final static Logger LOG = LogManager.getLogger(BrokerPool.class);
private final BrokerPoolServicesManager servicesManager = new BrokerPoolServicesManager();
private StatusReporter statusReporter = null;
private final XQuery xqueryService = new XQuery();
//TODO : make it non-static since every database instance may have its own policy.
//TODO : make a default value that could be overwritten by the configuration
// WM: this is only used by junit tests to test the recovery process.
/**
* For testing only: triggers a database corruption by disabling the page caches. The effect is
* similar to a sudden power loss or the jvm being killed. The flag is used by some
* junit tests to test the recovery process.
*/
public static boolean FORCE_CORRUPTION = false;
/**
* <code>true</code> if the database instance is able to perform recovery.
*/
private final boolean recoveryEnabled;
/**
* The name of the database instance
*/
private final String instanceName;
private final int concurrencyLevel;
private LockManager lockManager;
/**
* Root thread group for all threads related
* to this instance.
*/
private final ThreadGroup instanceThreadGroup;
/**
* State of the BrokerPool instance
*/
private enum State {
SHUTTING_DOWN_MULTI_USER_MODE,
SHUTTING_DOWN_SYSTEM_MODE,
SHUTDOWN,
INITIALIZING,
INITIALIZING_SYSTEM_MODE,
INITIALIZING_MULTI_USER_MODE,
OPERATIONAL
}
private enum Event {
INITIALIZE,
INITIALIZE_SYSTEM_MODE,
INITIALIZE_MULTI_USER_MODE,
READY,
START_SHUTDOWN_MULTI_USER_MODE,
START_SHUTDOWN_SYSTEM_MODE,
FINISHED_SHUTDOWN,
}
@SuppressWarnings("unchecked")
private final FSM<State, Event> status = new AtomicFSM<>(State.SHUTDOWN,
transitionTable(State.class, Event.class)
.when(State.SHUTDOWN).on(Event.INITIALIZE).switchTo(State.INITIALIZING)
.when(State.INITIALIZING).on(Event.INITIALIZE_SYSTEM_MODE).switchTo(State.INITIALIZING_SYSTEM_MODE)
.when(State.INITIALIZING_SYSTEM_MODE).on(Event.INITIALIZE_MULTI_USER_MODE).switchTo(State.INITIALIZING_MULTI_USER_MODE)
.when(State.INITIALIZING_MULTI_USER_MODE).on(Event.READY).switchTo(State.OPERATIONAL)
.when(State.OPERATIONAL).on(Event.START_SHUTDOWN_MULTI_USER_MODE).switchTo(State.SHUTTING_DOWN_MULTI_USER_MODE)
.when(State.SHUTTING_DOWN_MULTI_USER_MODE).on(Event.START_SHUTDOWN_SYSTEM_MODE).switchTo(State.SHUTTING_DOWN_SYSTEM_MODE)
.when(State.SHUTTING_DOWN_SYSTEM_MODE).on(Event.FINISHED_SHUTDOWN).switchTo(State.SHUTDOWN)
.build()
);
public String getStatus() {
return status.getCurrentState().name();
}
/**
* The number of brokers for the database instance
*/
private int brokersCount = 0;
/**
* The minimal number of brokers for the database instance
*/
@ConfigurationFieldAsAttribute("min")
private final int minBrokers;
/**
* The maximal number of brokers for the database instance
*/
@ConfigurationFieldAsAttribute("max")
private final int maxBrokers;
/**
* The number of inactive brokers for the database instance
*/
private final Deque<DBBroker> inactiveBrokers = new ArrayDeque<>();
/**
* The number of active brokers for the database instance
*/
private final Map<Thread, DBBroker> activeBrokers = new ConcurrentHashMap<>();
/**
* Used when TRACE level logging is enabled
* to provide a history of broker leases
*/
private final Map<String, TraceableStateChanges<TraceableBrokerLeaseChange.BrokerInfo, TraceableBrokerLeaseChange.Change>> brokerLeaseChangeTrace = LOG.isTraceEnabled() ? new HashMap<>() : null;
private final Map<String, List<TraceableStateChanges<TraceableBrokerLeaseChange.BrokerInfo, TraceableBrokerLeaseChange.Change>>> brokerLeaseChangeTraceHistory = LOG.isTraceEnabled() ? new HashMap<>() : null;
/**
* The configuration object for the database instance
*/
private final Configuration conf;
private final ConcurrentSkipListSet<Observer> statusObservers = new ConcurrentSkipListSet<>();
/**
* <code>true</code> if a cache synchronization event is scheduled
*/
//TODO : rename as syncScheduled ?
//TODO : alternatively, delete this member and create a Sync.NOSYNC event
private boolean syncRequired = false;
/**
* The kind of scheduled cache synchronization event.
* One of {@link org.exist.storage.sync.Sync}
*/
private Sync syncEvent = Sync.MINOR;
private boolean checkpoint = false;
/**
* Indicates whether the database is operating in read-only mode
*/
@GuardedBy("itself") private Boolean readOnly = Boolean.FALSE;
@ConfigurationFieldAsAttribute("pageSize")
private final int pageSize;
private FileLockService dataLock;
/**
* The journal manager of the database instance.
*/
private Optional<JournalManager> journalManager = Optional.empty();
/**
* The transaction manager of the database instance.
*/
private TransactionManager transactionManager = null;
/**
* The Blob Store of the database instance.
*/
private BlobStoreService blobStoreService;
/**
* Delay (in ms) for running jobs to return when the database instance shuts down.
*/
@ConfigurationFieldAsAttribute("wait-before-shutdown")
private final long maxShutdownWait;
/**
* The scheduler for the database instance.
*/
@ConfigurationFieldAsAttribute("scheduler")
private Scheduler scheduler;
/**
* Manages pluggable index structures.
*/
private IndexManager indexManager;
/**
* Global symbol table used to encode element and attribute qnames.
*/
private SymbolTable symbols;
/**
* Cache synchronization on the database instance.
*/
@ConfigurationFieldAsAttribute("sync-period")
private final long majorSyncPeriod; //the period after which a major sync should occur
private long lastMajorSync = System.currentTimeMillis(); //time the last major sync occurred
private final long diskSpaceMin;
/**
* The listener that is notified when the database instance shuts down.
*/
private ShutdownListener shutdownListener = null;
/**
* The security manager of the database instance.
*/
private SecurityManager securityManager = null;
/**
* The plugin manager.
*/
private PluginsManagerImpl pluginManager = null;
/**
* The global notification service used to subscribe
* to document updates.
*/
private NotificationService notificationService = null;
/**
* The cache in which the database instance may store items.
*/
private DefaultCacheManager cacheManager;
private long reservedMem;
/**
* The pool in which the database instance's <strong>compiled</strong> XQueries are stored.
*/
private XQueryPool xQueryPool;
/**
* The monitor in which the database instance's strong>running</strong> XQueries are managed.
*/
private ProcessMonitor processMonitor;
/**
* Global performance stats to gather function execution statistics
* from all queries running on this database instance.
*/
private PerformanceStats xqueryStats;
/**
* The global manager for accessing collection configuration files from the database instance.
*/
private CollectionConfigurationManager collectionConfigurationManager = null;
/**
* The cache in which the database instance's collections are stored.
*/
//TODO : rename as collectionsCache ?
private CollectionCache collectionCache;
/**
* The pool in which the database instance's readers are stored.
*/
private XMLReaderPool xmlReaderPool;
private final NodeIdFactory nodeFactory = new DLNFactory();
private final Lock globalXUpdateLock = new ReentrantLock();
private Subject serviceModeUser = null;
private boolean inServiceMode = false;
//the time that the database was started
private final Calendar startupTime = Calendar.getInstance();
private final Optional<BrokerWatchdog> watchdog;
private final ClassLoader classLoader;
private Optional<ExistRepository> expathRepo = Optional.empty();
private StartupTriggersManager startupTriggersManager;
/**
* Configuration for Saxon.
*
* One instance per-database, lazily initialised.
*/
private AtomicLazyVal<net.sf.saxon.Configuration> saxonConfig = new AtomicLazyVal<>(net.sf.saxon.Configuration::newConfiguration);
/**
* Creates and configures the database instance.
*
* @param instanceName A name for the database instance.
* @param minBrokers The minimum number of concurrent brokers for handling requests on the database instance.
* @param maxBrokers The maximum number of concurrent brokers for handling requests on the database instance.
* @param conf The configuration object for the database instance
* @param statusObserver Observes the status of this database instance
*
* @throws EXistException If the initialization fails.
*/
//TODO : Then write a configure(int minBrokers, int maxBrokers, Configuration conf) method
BrokerPool(final String instanceName, final int minBrokers, final int maxBrokers, final Configuration conf,
final Optional<Observer> statusObserver) {
final NumberFormat nf = NumberFormat.getNumberInstance();
this.classLoader = Thread.currentThread().getContextClassLoader();
this.instanceName = instanceName;
this.instanceThreadGroup = new ThreadGroup(nameInstanceThreadGroup(instanceName));
this.maxShutdownWait = conf.getProperty(BrokerPool.PROPERTY_SHUTDOWN_DELAY, DEFAULT_MAX_SHUTDOWN_WAIT);
LOG.info("database instance '{}' will wait {} ms during shutdown", instanceName, nf.format(this.maxShutdownWait));
this.recoveryEnabled = conf.getProperty(PROPERTY_RECOVERY_ENABLED, true);
LOG.info("database instance '{}' is enabled for recovery : {}", instanceName, this.recoveryEnabled);
this.minBrokers = conf.getProperty(PROPERTY_MIN_CONNECTIONS, minBrokers);
this.maxBrokers = conf.getProperty(PROPERTY_MAX_CONNECTIONS, maxBrokers);
LOG.info("database instance '{}' will have between {} and {} brokers", instanceName, nf.format(this.minBrokers), nf.format(this.maxBrokers));
this.majorSyncPeriod = conf.getProperty(PROPERTY_SYNC_PERIOD, DEFAULT_SYNCH_PERIOD);
LOG.info("database instance '{}' will be synchronized every {} ms", instanceName, nf.format(/*this.*/majorSyncPeriod));
// convert from bytes to megabytes: 1024 * 1024
this.diskSpaceMin = 1024L * 1024L * conf.getProperty(BrokerPool.DISK_SPACE_MIN_PROPERTY, DEFAULT_DISK_SPACE_MIN);
this.pageSize = conf.getProperty(PROPERTY_PAGE_SIZE, DEFAULT_PAGE_SIZE);
//Configuration is valid, save it
this.conf = conf;
this.concurrencyLevel = Math.max(maxBrokers, 2 * Runtime.getRuntime().availableProcessors());
statusObserver.ifPresent(this.statusObservers::add);
this.watchdog = Optional.ofNullable(System.getProperty(BrokerWatchdog.TRACE_BROKERS_PROPERTY_NAME))
.filter(value -> value.equals("yes"))
.map(value -> new BrokerWatchdog());
}
/**
* Initializes the database instance.
*
* @throws EXistException
* @throws DatabaseConfigurationException
*/
void initialize() throws EXistException, DatabaseConfigurationException {
try {
_initialize();
} catch(final Throwable e) {
// remove that file lock we may have acquired in canReadDataDir
synchronized(readOnly) {
if (dataLock != null && !readOnly) {
dataLock.release();
}
}
if(e instanceof EXistException) {
throw (EXistException) e;
} else if(e instanceof DatabaseConfigurationException) {
throw (DatabaseConfigurationException) e;
} else {
throw new EXistException(e);
}
}
}
private void _initialize() throws EXistException, DatabaseConfigurationException {
this.lockManager = new LockManager(conf, concurrencyLevel);
//Flag to indicate that we are initializing
status.process(Event.INITIALIZE);
if(LOG.isDebugEnabled()) {
LOG.debug("initializing database instance '{}'...", instanceName);
}
// register core broker pool services
this.scheduler = servicesManager.register(new QuartzSchedulerImpl(this));
// NOTE: this must occur after the scheduler, and before any other service which requires access to the data directory
this.dataLock = servicesManager.register(new FileLockService("dbx_dir.lck", BrokerPool.PROPERTY_DATA_DIR, NativeBroker.DEFAULT_DATA_DIR));
this.securityManager = servicesManager.register(new SecurityManagerImpl(this));
this.cacheManager = servicesManager.register(new DefaultCacheManager(this));
this.xQueryPool = servicesManager.register(new XQueryPool());
this.processMonitor = servicesManager.register(new ProcessMonitor());
this.xqueryStats = servicesManager.register(new PerformanceStats(this));
final XMLReaderObjectFactory xmlReaderObjectFactory = servicesManager.register(new XMLReaderObjectFactory());
this.xmlReaderPool = servicesManager.register(new XMLReaderPool(xmlReaderObjectFactory, maxBrokers, 0));
final int bufferSize = Optional.of(conf.getInteger(PROPERTY_COLLECTION_CACHE_SIZE))
.filter(size -> size != -1)
.orElse(DEFAULT_COLLECTION_BUFFER_SIZE);
this.collectionCache = servicesManager.register(new CollectionCache());
this.notificationService = servicesManager.register(new NotificationService());
this.journalManager = recoveryEnabled ? Optional.of(new JournalManager()) : Optional.empty();
journalManager.ifPresent(servicesManager::register);
final SystemTaskManager systemTaskManager = servicesManager.register(new SystemTaskManager(this));
this.transactionManager = servicesManager.register(new TransactionManager(this, journalManager, systemTaskManager));
this.blobStoreService = servicesManager.register(new BlobStoreImplService());
this.symbols = servicesManager.register(new SymbolTable());
this.expathRepo = Optional.ofNullable(new ExistRepository());
expathRepo.ifPresent(servicesManager::register);
servicesManager.register(new ClasspathHelper());
this.indexManager = servicesManager.register(new IndexManager(this));
//prepare those services that require system (single-user) mode
this.pluginManager = servicesManager.register(new PluginsManagerImpl());
//Get a manager to handle further collections configuration
this.collectionConfigurationManager = servicesManager.register(new CollectionConfigurationManager(this));
this.startupTriggersManager = servicesManager.register(new StartupTriggersManager());
// this is just used for unit tests
final BrokerPoolService testBrokerPoolService = (BrokerPoolService) conf.getProperty("exist.testBrokerPoolService");
if (testBrokerPoolService != null) {
servicesManager.register(testBrokerPoolService);
}
//configure the registered services
try {
servicesManager.configureServices(conf);
} catch(final BrokerPoolServiceException e) {
throw new EXistException(e);
}
// calculate how much memory is reserved for caches to grow
final Runtime rt = Runtime.getRuntime();
final long maxMem = rt.maxMemory();
final long minFree = maxMem / 5;
reservedMem = cacheManager.getTotalMem() + collectionCache.getMaxCacheSize() + minFree;
LOG.debug("Reserved memory: {}; max: {}; min: {}", reservedMem, maxMem, minFree);
//prepare the registered services, before entering system (single-user) mode
try {
servicesManager.prepareServices(this);
} catch(final BrokerPoolServiceException e) {
throw new EXistException(e);
}
//setup database synchronization job
if(majorSyncPeriod > 0) {
final SyncTask syncTask = new SyncTask();
syncTask.configure(conf, null);
scheduler.createPeriodicJob(2500, new SystemTaskJobImpl(SyncTask.getJobName(), syncTask), 2500);
}
try {
statusReporter = new StatusReporter(SIGNAL_STARTUP);
statusObservers.forEach(statusReporter::addObserver);
final Thread statusThread = newInstanceThread(this, "startup-status-reporter", statusReporter);
statusThread.start();
// statusReporter may have to be terminated or the thread can/will hang.
try {
final boolean exportOnly = conf.getProperty(PROPERTY_EXPORT_ONLY, false);
// If the initialization fails after transactionManager has been created this method better cleans up
// or the FileSyncThread for the journal can/will hang.
try {
// Enter System Mode
try(final DBBroker systemBroker = get(Optional.of(securityManager.getSystemSubject()))) {
status.process(Event.INITIALIZE_SYSTEM_MODE);
if(isReadOnly()) {
journalManager.ifPresent(JournalManager::disableJournalling);
}
try(final Txn transaction = transactionManager.beginTransaction()) {
servicesManager.startPreSystemServices(systemBroker, transaction);
transaction.commit();
} catch(final BrokerPoolServiceException e) {
throw new EXistException(e);
}
//Run the recovery process
boolean recovered = false;
if(isRecoveryEnabled()) {
recovered = runRecovery(systemBroker);
//TODO : extract the following from this block ? What if we are not transactional ? -pb
if(!recovered) {
try {
if(systemBroker.getCollection(XmldbURI.ROOT_COLLECTION_URI) == null) {
final Txn txn = transactionManager.beginTransaction();
try {
systemBroker.getOrCreateCollection(txn, XmldbURI.ROOT_COLLECTION_URI);
transactionManager.commit(txn);
} catch(final IOException | TriggerException | PermissionDeniedException e) {
transactionManager.abort(txn);
} finally {
transactionManager.close(txn);
}
}
} catch(final PermissionDeniedException pde) {
LOG.fatal(pde.getMessage(), pde);
}
}
}
/* initialise required collections if they don't exist yet */
if(!exportOnly) {
try {
initialiseSystemCollections(systemBroker);
} catch(final PermissionDeniedException pde) {
LOG.error(pde.getMessage(), pde);
throw new EXistException(pde.getMessage(), pde);
}
}
statusReporter.setStatus(SIGNAL_READINESS);
try(final Txn transaction = transactionManager.beginTransaction()) {
servicesManager.startSystemServices(systemBroker, transaction);
transaction.commit();
} catch(final BrokerPoolServiceException e) {
throw new EXistException(e);
}
//If necessary, launch a task to repair the DB
//TODO : merge this with the recovery process ?
if(isRecoveryEnabled() && recovered) {
if(!exportOnly) {
reportStatus("Reindexing database files...");
try {
systemBroker.repair();
} catch(final PermissionDeniedException e) {
LOG.warn("Error during recovery: {}", e.getMessage(), e);
}
}
if((Boolean) conf.getProperty(PROPERTY_RECOVERY_CHECK)) {
final ConsistencyCheckTask task = new ConsistencyCheckTask();
final Properties props = new Properties();
props.setProperty("backup", "no");
props.setProperty("output", "sanity");
task.configure(conf, props);
try (final Txn transaction = transactionManager.beginTransaction()) {
task.execute(systemBroker, transaction);
transaction.commit();
}
}
}
//OK : the DB is repaired; let's make a few RW operations
statusReporter.setStatus(SIGNAL_WRITABLE);
//initialize configurations watcher trigger
if(!exportOnly) {
try {
initialiseTriggersForCollections(systemBroker, XmldbURI.SYSTEM_COLLECTION_URI);
} catch(final PermissionDeniedException pde) {
//XXX: do not catch exception!
LOG.error(pde.getMessage(), pde);
}
}
// remove temporary docs
try {
systemBroker.cleanUpTempResources(true);
} catch(final PermissionDeniedException pde) {
LOG.error(pde.getMessage(), pde);
}
sync(systemBroker, Sync.MAJOR);
// we have completed all system mode operations
// we can now prepare those services which need
// system mode before entering multi-user mode
try(final Txn transaction = transactionManager.beginTransaction()) {
servicesManager.startPreMultiUserSystemServices(systemBroker, transaction);
transaction.commit();
} catch(final BrokerPoolServiceException e) {
throw new EXistException(e);
}
}
//Create a default configuration file for the root collection
//TODO : why can't we call this from within CollectionConfigurationManager ?
//TODO : understand why we get a test suite failure
//collectionConfigurationManager.checkRootCollectionConfigCollection(broker);
//collectionConfigurationManager.checkRootCollectionConfig(broker);
//Create the minimal number of brokers required by the configuration
for(int i = 1; i < minBrokers; i++) {
createBroker();
}
status.process(Event.INITIALIZE_MULTI_USER_MODE);
// register some MBeans to provide access to this instance
AgentFactory.getInstance().initDBInstance(this);
if(LOG.isDebugEnabled()) {
LOG.debug("database instance '{}' initialized", instanceName);
}
servicesManager.startMultiUserServices(this);
status.process(Event.READY);
statusReporter.setStatus(SIGNAL_STARTED);
} catch(final Throwable t) {
transactionManager.shutdown();
throw t;
}
} catch(final EXistException e) {
throw e;
} catch(final Throwable t) {
throw new EXistException(t.getMessage(), t);
}
} finally {
if(statusReporter != null) {
statusReporter.terminate();
statusReporter = null;
}
}
}
/**
* Initialise system collections, if it doesn't exist yet
*
* @param sysBroker The system broker from before the brokerpool is populated
* @param sysCollectionUri XmldbURI of the collection to create
* @param permissions The permissions to set on the created collection
*/
private void initialiseSystemCollection(final DBBroker sysBroker, final XmldbURI sysCollectionUri, final int permissions) throws EXistException, PermissionDeniedException {
Collection collection = sysBroker.getCollection(sysCollectionUri);
if(collection == null) {
final TransactionManager transact = getTransactionManager();
try(final Txn txn = transact.beginTransaction()) {
collection = sysBroker.getOrCreateCollection(txn, sysCollectionUri);
if(collection == null) {
throw new IOException("Could not create system collection: " + sysCollectionUri);
}
collection.setPermissions(sysBroker, permissions);
sysBroker.saveCollection(txn, collection);
transact.commit(txn);
} catch(final Exception e) {
e.printStackTrace();
final String msg = "Initialisation of system collections failed: " + e.getMessage();
LOG.error(msg, e);
throw new EXistException(msg, e);
}
}
}
/**
* Initialize required system collections, if they don't exist yet
*
* @param broker - The system broker from before the brokerpool is populated
* @throws EXistException If a system collection cannot be created
*/
private void initialiseSystemCollections(final DBBroker broker) throws EXistException, PermissionDeniedException {
//create /db/system
initialiseSystemCollection(broker, XmldbURI.SYSTEM_COLLECTION_URI, Permission.DEFAULT_SYSTEM_COLLECTION_PERM);
}
private void initialiseTriggersForCollections(final DBBroker broker, final XmldbURI uri) throws EXistException, PermissionDeniedException {
final Collection collection = broker.getCollection(uri);
//initialize configurations watcher trigger
if(collection != null) {
final CollectionConfigurationManager manager = getConfigurationManager();
final CollectionConfiguration collConf = manager.getOrCreateCollectionConfiguration(broker, collection);
final DocumentTriggerProxy triggerProxy = new DocumentTriggerProxy(ConfigurationDocumentTrigger.class); //, collection.getURI());
collConf.documentTriggers().add(triggerProxy);
}
}
/**
* Get the LockManager for this database instance
*
* @return The lock manager
*/
public LockManager getLockManager() {
return lockManager;
}
/**
* Run a database recovery if required. This method is called once during
* startup from {@link org.exist.storage.BrokerPool}.
*
* @param broker the database broker
* @return true if recovery was run, false otherwise
* @throws EXistException if a database error occurs
*/
public boolean runRecovery(final DBBroker broker) throws EXistException {
final boolean forceRestart = conf.getProperty(PROPERTY_RECOVERY_FORCE_RESTART, false);
if(LOG.isDebugEnabled()) {
LOG.debug("ForceRestart = {}", forceRestart);
}
if(journalManager.isPresent()) {
final RecoveryManager recovery = new RecoveryManager(broker, journalManager.get(), forceRestart);
return recovery.recover();
} else {
throw new IllegalStateException("Cannot run recovery without a JournalManager");
}
}
public long getReservedMem() {
return reservedMem - cacheManager.getCurrentSize();
}
public int getPageSize() {
return pageSize;
}
/**
* Returns the class loader used when this BrokerPool was configured.
*
* @return the classloader
*/
public ClassLoader getClassLoader() {
return this.classLoader;
}
/**
* Whether or not the database instance is operational, i.e. initialization
* has completed
*
* @return <code>true</code> if the database instance is operational
*/
public boolean isOperational() {
return status.getCurrentState() == State.OPERATIONAL;
}
/**
* Returns the database instance's name.
*
* @return The id
*/
//TODO : rename getInstanceName
public String getId() {
return instanceName;
}
@Override
public ThreadGroup getThreadGroup() {
return instanceThreadGroup;
}
/**
* Returns the number of brokers currently serving requests for the database instance.
*
* @return The brokers count
* @deprecated use countActiveBrokers
*/
//TODO : rename as getActiveBrokers ?
public int active() {
return activeBrokers.size();
}
/**
* Returns the number of brokers currently serving requests for the database instance.
*
* @return The active brokers count.
*/
@Override
public int countActiveBrokers() {
return activeBrokers.size();
}
public Map<Thread, DBBroker> getActiveBrokers() {
return new HashMap<>(activeBrokers);
}
/**
* Returns the number of inactive brokers for the database instance.
*
* @return The brokers count
*/
//TODO : rename as getInactiveBrokers ?
public int available() {
return inactiveBrokers.size();
}
//TODO : getMin() method ?
/**
* Returns the maximal number of brokers for the database instance.
*
* @return The brokers count
*/
//TODO : rename as getMaxBrokers ?
public int getMax() {
return maxBrokers;
}
public int total() {
return brokersCount;
}
/**
* Returns whether the database instance has been configured.
*
* @return <code>true</code> if the datbase instance is configured
*/
public final boolean isInstanceConfigured() {
return conf != null;
}
/**
* Returns the configuration object for the database instance.
*
* @return The configuration
*/
public Configuration getConfiguration() {
return conf;
}
public Optional<ExistRepository> getExpathRepo() {
return expathRepo;
}
//TODO : rename as setShutdwonListener ?
public void registerShutdownListener(final ShutdownListener listener) {
//TODO : check that we are not shutting down
shutdownListener = listener;
}
public NodeIdFactory getNodeFactory() {
return nodeFactory;
}
/**
* Returns the database instance's security manager
*
* @return The security manager
*/
public SecurityManager getSecurityManager() {
return securityManager;
}
/**
* Returns the Scheduler
*
* @return The scheduler
*/
public Scheduler getScheduler() {
return scheduler;
}
@Override
public BlobStore getBlobStore() {
return blobStoreService.getBlobStore();
}
public SymbolTable getSymbols() {
return symbols;
}
public NotificationService getNotificationService() {
return notificationService;
}
/**
* Returns whether transactions can be handled by the database instance.
*
* @return <code>true</code> if transactions can be handled
*/
public boolean isRecoveryEnabled() {
synchronized(readOnly) {
return !readOnly && recoveryEnabled;
}
}
@Override
public boolean isReadOnly() {
synchronized(readOnly) {
if(!readOnly) {
final long freeSpace = FileUtils.measureFileStore(dataLock.getFile(), FileStore::getUsableSpace);
if (freeSpace != -1 && freeSpace < diskSpaceMin) {
LOG.fatal("Partition containing DATA_DIR: {} is running out of disk space [minimum: {} free: {}]. Switching eXist-db into read-only mode to prevent data loss!", dataLock.getFile().toAbsolutePath().toString(), diskSpaceMin, freeSpace);
setReadOnly();
}
}
return readOnly;
}
}
public void setReadOnly() {
LOG.warn("Switching database into read-only mode!");
synchronized (readOnly) {
readOnly = true;
}
}
public boolean isInServiceMode() {
return inServiceMode;
}
@Override
public Optional<JournalManager> getJournalManager() {
return journalManager;
}
public TransactionManager getTransactionManager() {
return transactionManager;
}
/**
* Returns a manager for accessing the database instance's collection configuration files.
*
* @return The manager
*/
@Override
public CollectionConfigurationManager getConfigurationManager() {
return collectionConfigurationManager;
}
/**
* Returns a cache in which the database instance's collections are stored.
*
* @return The cache
*/
public CollectionCache getCollectionsCache() {
return collectionCache;
}
/**
* Returns a cache in which the database instance's may store items.
*
* @return The cache
*/
@Override
public DefaultCacheManager getCacheManager() {
return cacheManager;
}
/**
* Returns the index manager which handles all additional indexes not
* being part of the database core.
*
* @return The IndexManager
*/
@Override
public IndexManager getIndexManager() {
return indexManager;
}
/**
* Returns a pool in which the database instance's <strong>compiled</strong> XQueries are stored.
*
* @return The pool
*/
public XQueryPool getXQueryPool() {
return xQueryPool;
}
/**
* Retuns the XQuery Service
*
* @return The XQuery service
*/
public XQuery getXQueryService() {
return xqueryService;
}
/**
* Returns a monitor in which the database instance's <strong>running</strong> XQueries are managed.
*
* @return The monitor
*/
public ProcessMonitor getProcessMonitor() {
return processMonitor;
}
/**
* Returns the global profiler used to gather execution statistics
* from all XQueries running on this db instance.
*
* @return the profiler
*/
public PerformanceStats getPerformanceStats() {
return xqueryStats;
}
/**
* Returns a pool in which the database instance's readers are stored.
*
* @return The pool
*/
public XMLReaderPool getParserPool() {
return xmlReaderPool;
}
/**
* Returns the global update lock for the database instance.
* This lock is used by XUpdate operations to avoid that
* concurrent XUpdate requests modify the database until all
* document locks have been correctly set.
*
* @return The global lock
*/
//TODO : rename as getUpdateLock ?
public Lock getGlobalUpdateLock() {
return globalXUpdateLock;
}
/**
* Creates an inactive broker for the database instance.
*
* @return The broker
* @throws EXistException if the broker cannot be created
*/
protected DBBroker createBroker() throws EXistException {
//TODO : in the future, don't pass the whole configuration, just the part relevant to brokers
final DBBroker broker = BrokerFactory.getInstance(this, this.getConfiguration());
inactiveBrokers.push(broker);
brokersCount++;
broker.setId(broker.getClass().getName() + '_' + instanceName + "_" + brokersCount);
if (LOG.isDebugEnabled()) {
LOG.debug("Created broker '{} for database instance '{}'", broker.getId(), instanceName);
}
return broker;
}
/**
* Get active broker for current thread
*
* Note - If you call getActiveBroker() you must not call
* release on both the returned active broker and the original
* lease from {@link BrokerPool#getBroker()} or {@link BrokerPool#get(Optional)}
* otherwise release will have been called more than get!
*
* @return Database broker
* @throws RuntimeException NO broker available for current thread.
*/
public DBBroker getActiveBroker() { //throws EXistException {
//synchronized(this) {
//Try to get an active broker
final DBBroker broker = activeBrokers.get(Thread.currentThread());
if(broker == null) {
final StringBuilder sb = new StringBuilder();
sb.append("Broker was not obtained for thread '");
sb.append(Thread.currentThread());
sb.append("'.");
sb.append(System.getProperty("line.separator"));
for(final Entry<Thread, DBBroker> entry : activeBrokers.entrySet()) {
sb.append(entry.getKey());
sb.append(" = ");
sb.append(entry.getValue());
sb.append(System.getProperty("line.separator"));
}
LOG.debug(sb.toString());
throw new RuntimeException(sb.toString());
}
return broker;
//}
}
public DBBroker authenticate(final String username, final Object credentials) throws AuthenticationException {
final Subject subject = getSecurityManager().authenticate(username, credentials);
try {
return get(Optional.ofNullable(subject));
} catch(final Exception e) {
throw new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, e);
}
}
/**
* Returns an active broker for the database instance.
*
* The current user will be inherited by this broker
*
* @return The broker
*/
public DBBroker getBroker() throws EXistException {
return get(Optional.empty());
}
/**
* Returns an active broker for the database instance.
*
* @param subject Optionally a subject to set on the broker, if a user is not provided then the
* current user assigned to the broker will be re-used
* @return The broker
* @throws EXistException If the instance is not available (stopped or not configured)
*/
//TODO : rename as getBroker ? getInstance (when refactored) ?
public DBBroker get(final Optional<Subject> subject) throws EXistException {
Objects.requireNonNull(subject, "Subject cannot be null, use BrokerPool#getBroker() instead");
if(!isInstanceConfigured()) {
throw new EXistException("database instance '" + instanceName + "' is not available");
}
//Try to get an active broker
DBBroker broker = activeBrokers.get(Thread.currentThread());
//Use it...
//TOUNDERSTAND (pb) : why not pop a broker from the inactive ones rather than maintaining reference counters ?
// WM: a thread may call this more than once in the sequence of operations, i.e. calls to get/release can
// be nested. Returning a new broker every time would lead to a deadlock condition if two threads have
// to wait for a broker to become available. We thus use reference counts and return
// the same broker instance for each thread.
if(broker != null) {
//increase its number of uses
broker.incReferenceCount();
broker.pushSubject(subject.orElseGet(broker::getCurrentSubject));
if(LOG.isTraceEnabled()) {
if(!brokerLeaseChangeTrace.containsKey(broker.getId())) {
brokerLeaseChangeTrace.put(broker.getId(), new TraceableStateChanges<>());
}
brokerLeaseChangeTrace.get(broker.getId()).add(TraceableBrokerLeaseChange.get(new TraceableBrokerLeaseChange.BrokerInfo(broker.getId(), broker.getReferenceCount())));
}
return broker;
//TODO : share the code with what is below (including notifyAll) ?
// WM: notifyAll is not necessary if we don't have to wait for a broker.
}
//No active broker : get one ASAP
while(serviceModeUser != null && subject.isPresent() && !subject.equals(Optional.ofNullable(serviceModeUser))) {
try {
LOG.debug("Db instance is in service mode. Waiting for db to become available again ...");
wait();
} catch(final InterruptedException e) {
Thread.currentThread().interrupt();
LOG.error("Interrupt detected");
}
}
synchronized(this) {
//Are there any available brokers ?
if(inactiveBrokers.isEmpty()) {
//There are no available brokers. If allowed...
if(brokersCount < maxBrokers)
//... create one
{
createBroker();
} else
//... or wait until there is one available
while(inactiveBrokers.isEmpty()) {
LOG.debug("waiting for a broker to become available");
try {
this.wait();
} catch(final InterruptedException e) {
//nothing to be done!
}
}
}
broker = inactiveBrokers.pop();
broker.prepare();
//activate the broker
activeBrokers.put(Thread.currentThread(), broker);
if(LOG.isTraceEnabled()) {
LOG.trace("+++ {}{}", Thread.currentThread(), Stacktrace.top(Thread.currentThread().getStackTrace(), Stacktrace.DEFAULT_STACK_TOP));
}
if(watchdog.isPresent()) {
watchdog.get().add(broker);
}
broker.incReferenceCount();
broker.pushSubject(subject.orElseGet(securityManager::getGuestSubject));
if(LOG.isTraceEnabled()) {
if(!brokerLeaseChangeTrace.containsKey(broker.getId())) {
brokerLeaseChangeTrace.put(broker.getId(), new TraceableStateChanges<>());
}
brokerLeaseChangeTrace.get(broker.getId()).add(TraceableBrokerLeaseChange.get(new TraceableBrokerLeaseChange.BrokerInfo(broker.getId(), broker.getReferenceCount())));
}
//Inform the other threads that we have a new-comer
// TODO: do they really need to be informed here???????
this.notifyAll();
return broker;
}
}
/**
* Releases a broker for the database instance. If it is no more used, make if invactive.
* If there are pending system maintenance tasks,
* the method will block until these tasks have finished.
*
* NOTE - this is intentionally package-private, it is only meant to be
* called internally and from {@link DBBroker#close()}
*
* @param broker The broker to be released
*/
//TODO : rename as releaseBroker ? releaseInstance (when refactored) ?
void release(final DBBroker broker) {
Objects.requireNonNull(broker, "Cannot release nothing");
if(LOG.isTraceEnabled()) {
if(!brokerLeaseChangeTrace.containsKey(broker.getId())) {
brokerLeaseChangeTrace.put(broker.getId(), new TraceableStateChanges<>());
}
brokerLeaseChangeTrace.get(broker.getId()).add(TraceableBrokerLeaseChange.release(new TraceableBrokerLeaseChange.BrokerInfo(broker.getId(), broker.getReferenceCount())));
}
//first check that the broker is active ! If not, return immediately.
broker.decReferenceCount();
if(broker.getReferenceCount() > 0) {
broker.popSubject();
//it is still in use and thus can't be marked as inactive
return;
}
synchronized(this) {
//Broker is no more used : inactivate it
for(final DBBroker inactiveBroker : inactiveBrokers) {
if(broker == inactiveBroker) {
LOG.error("Broker {} is already in the inactive list!!!", broker.getId());
return;
}
}
if(activeBrokers.remove(Thread.currentThread()) == null) {
LOG.error("release() has been called from the wrong thread for broker {}", broker.getId());
// Cleanup the state of activeBrokers
for(final Entry<Thread, DBBroker> activeBroker : activeBrokers.entrySet()) {
if(activeBroker.getValue() == broker) {
final String msg = "release() has been called from '" + Thread.currentThread() + "', but occupied at '" + activeBroker.getKey() + "'.";
final EXistException ex = new EXistException(msg);
LOG.error(msg, ex);
activeBrokers.remove(activeBroker.getKey());
break;
}
}
} else {
if(LOG.isTraceEnabled()) {
LOG.trace("--- {}{}", Thread.currentThread(), Stacktrace.top(Thread.currentThread().getStackTrace(), Stacktrace.DEFAULT_STACK_TOP));
}
}
Subject lastUser = broker.popSubject();
//guard to ensure that the broker has popped all its subjects
if(lastUser == null || broker.getCurrentSubject() != null) {
LOG.warn("Broker {} was returned with extraneous Subjects, cleaning...", broker.getId(), new IllegalStateException("DBBroker pushSubject/popSubject mismatch").fillInStackTrace());
if(LOG.isTraceEnabled()) {
broker.traceSubjectChanges();
}
//cleanup any remaining erroneous subjects
while(broker.getCurrentSubject() != null) {
lastUser = broker.popSubject();
}
}
inactiveBrokers.push(broker);
watchdog.ifPresent(wd -> wd.remove(broker));
if(LOG.isTraceEnabled()) {
if(!brokerLeaseChangeTraceHistory.containsKey(broker.getId())) {
brokerLeaseChangeTraceHistory.put(broker.getId(), new ArrayList<>());
}
try {
brokerLeaseChangeTraceHistory.get(broker.getId()).add((TraceableStateChanges<TraceableBrokerLeaseChange.BrokerInfo, TraceableBrokerLeaseChange.Change>) brokerLeaseChangeTrace.get(broker.getId()).clone());
brokerLeaseChangeTrace.get(broker.getId()).clear();
} catch(final CloneNotSupportedException e) {
LOG.error(e);
}
broker.clearSubjectChangesTrace();
}
//If the database is now idle, do some useful stuff
if(activeBrokers.size() == 0) {
//TODO : use a "clean" dedicated method (we have some below) ?
if(syncRequired) {
//Note that the broker is not yet really inactive ;-)
sync(broker, syncEvent);
this.syncRequired = false;
this.checkpoint = false;
}
if(serviceModeUser != null && !lastUser.equals(serviceModeUser)) {
inServiceMode = true;
}
}
//Inform the other threads that someone is gone
this.notifyAll();
}
}
public DBBroker enterServiceMode(final Subject user) throws PermissionDeniedException {
if(!user.hasDbaRole()) {
throw new PermissionDeniedException("Only users of group dba can switch the db to service mode");
}
serviceModeUser = user;
synchronized(this) {
if(activeBrokers.size() != 0) {
while(!inServiceMode) {
try {
wait();
} catch(final InterruptedException e) {
//nothing to be done
}
}
}
}
inServiceMode = true;
final DBBroker broker = inactiveBrokers.peek();
broker.prepare();
checkpoint = true;
sync(broker, Sync.MAJOR);
checkpoint = false;
// Return a broker that can be used to perform system tasks
return broker;
}
public void exitServiceMode(final Subject user) throws PermissionDeniedException {
if(!user.equals(serviceModeUser)) {
throw new PermissionDeniedException("The db has been locked by a different user");
}
serviceModeUser = null;
inServiceMode = false;
synchronized(this) {
this.notifyAll();
}
}
public void reportStatus(final String message) {
if(statusReporter != null) {
statusReporter.setStatus(message);
}
}
public long getMajorSyncPeriod() {
return majorSyncPeriod;
}
public long getLastMajorSync() {
return lastMajorSync;
}
/**
* Executes a waiting cache synchronization for the database instance.
*
* NOTE: This method should not be called concurrently from multiple threads.
*
* @param broker A broker responsible for executing the job
* @param syncEvent One of {@link org.exist.storage.sync.Sync}
*/
public void sync(final DBBroker broker, final Sync syncEvent) {
/**
* Database Systems - The Complete Book (Second edition)
* § 17.4.1 The Undo/Redo Rules
*
* The constraints that an undo/redo logging system must follow are summarized by the following rule:
* * UR1 Before modifying any database element X on disk because of changes
* made by some transaction T, it is necessary that the update record
* <T,X,v,w> appear on disk.
*/
journalManager.ifPresent(manager -> manager.flush(true, true));
// sync various DBX files
broker.sync(syncEvent);
//TODO : strange that it is set *after* the sunc method has been called.
try {
broker.pushSubject(securityManager.getSystemSubject());
if (syncEvent == Sync.MAJOR) {
LOG.debug("Major sync");
try {
if (!FORCE_CORRUPTION) {
transactionManager.checkpoint(checkpoint);
}
} catch (final TransactionException e) {
LOG.warn(e.getMessage(), e);
}
cacheManager.checkCaches();
if (pluginManager != null) {
pluginManager.sync(broker);
}
lastMajorSync = System.currentTimeMillis();
if (LOG.isDebugEnabled()) {
notificationService.debug();
}
} else {
cacheManager.checkDistribution();
// LOG.debug("Minor sync");
}
//TODO : touch this.syncEvent and syncRequired ?
} finally {
broker.popSubject();
}
}
/**
* Schedules a system maintenance task for the database instance. If the database is idle,
* the task will be run immediately. Otherwise, the task will be deferred
* until all running threads have returned.
*
* @param task The task
*/
//TOUNDERSTAND (pb) : synchronized, so... "schedules" or, rather, "executes" ?
public void triggerSystemTask(final SystemTask task) {
final State s = status.getCurrentState();
if(s == State.SHUTTING_DOWN_MULTI_USER_MODE || s == State.SHUTTING_DOWN_SYSTEM_MODE) {
LOG.info("Skipping SystemTask: '{}' as database is shutting down...", task.getName());
return;
} else if(s == State.SHUTDOWN) {
LOG.warn("Unable to execute SystemTask: '{}' as database is shut down!", task.getName());
return;
}
transactionManager.triggerSystemTask(task);
}
/**
* Shuts downs the database instance
*/
public void shutdown() {
shutdown(false);
}
/**
* Returns true if the BrokerPool is in the
* process of shutting down.
*
* @return true if the BrokerPool is shutting down.
*/
public boolean isShuttingDown() {
final State s = status.getCurrentState();
return s == State.SHUTTING_DOWN_MULTI_USER_MODE
|| s == State.SHUTTING_DOWN_SYSTEM_MODE;
}
/**
* Returns true if the BrokerPool is either in the
* process of shutting down, or has already shutdown.
*
* @return true if the BrokerPool is shutting down or
* has shutdown.
*/
public boolean isShuttingDownOrDown() {
final State s = status.getCurrentState();
return s == State.SHUTTING_DOWN_MULTI_USER_MODE
|| s == State.SHUTTING_DOWN_SYSTEM_MODE
|| s == State.SHUTDOWN;
}
/**
* Returns true of the BrokerPool is shutdown.
*
* @return true if the BrokerPool is shutdown.
*/
public boolean isShutDown() {
return status.getCurrentState() == State.SHUTDOWN;
}
/**
* Shuts downs the database instance
*
* @param killed <code>true</code> when the JVM is (cleanly) exiting
*/
public void shutdown(final boolean killed) {
shutdown(killed, BrokerPools::removeInstance);
}
void shutdown(final boolean killed, final Consumer<String> shutdownInstanceConsumer) {
try {
status.process(Event.START_SHUTDOWN_MULTI_USER_MODE);
} catch(final IllegalStateException e) {
// we are not operational!
LOG.warn(e);
return;
}
// notify any BrokerPoolServices that we are about to shutdown
try {
// instruct database services that we are about to stop multi-user mode
servicesManager.stopMultiUserServices(this);
} catch(final BrokerPoolServicesManagerException e) {
for(final BrokerPoolServiceException bpse : e.getServiceExceptions()) {
LOG.error(bpse.getMessage(), bpse);
}
}
try {
status.process(Event.START_SHUTDOWN_SYSTEM_MODE);
} catch(final IllegalStateException e) {
// we are not in SHUTTING_DOWN_MULTI_USER_MODE!
LOG.warn(e);
return;
}
try {
LOG.info("Database is shutting down ...");
processMonitor.stopRunningJobs();
//Shutdown the scheduler
scheduler.shutdown(true);
try {
statusReporter = new StatusReporter(SIGNAL_SHUTDOWN);
statusObservers.forEach(statusReporter::addObserver);
synchronized (this) {
final Thread statusThread = newInstanceThread(this, "shutdown-status-reporter", statusReporter);
statusThread.start();
// DW: only in debug mode
if (LOG.isDebugEnabled()) {
notificationService.debug();
}
//Notify all running tasks that we are shutting down
//Notify all running XQueries that we are shutting down
processMonitor.killAll(500);
if (isRecoveryEnabled()) {
journalManager.ifPresent(jm -> jm.flush(true, true));
}
final long waitStart = System.currentTimeMillis();
//Are there active brokers ?
if (activeBrokers.size() > 0) {
printSystemInfo();
LOG.info("Waiting {}ms for remaining threads to shut down...", maxShutdownWait);
while (activeBrokers.size() > 0) {
try {
//Wait until they become inactive...
this.wait(1000);
} catch (final InterruptedException e) {
//nothing to be done
}
//...or force the shutdown
if (maxShutdownWait > -1 && System.currentTimeMillis() - waitStart > maxShutdownWait) {
LOG.warn("Not all threads returned. Forcing shutdown ...");
break;
}
}
}
LOG.debug("Calling shutdown ...");
//TODO : replace the following code by get()/release() statements ?
// WM: deadlock risk if not all brokers returned properly.
DBBroker broker = null;
if (inactiveBrokers.isEmpty())
try {
broker = createBroker();
} catch (final EXistException e) {
LOG.warn("could not create instance for shutdown. Giving up.");
}
else
//TODO : this broker is *not* marked as active and may be reused by another process !
//TODO : use get() then release the broker ?
// WM: deadlock risk if not all brokers returned properly.
//TODO: always createBroker? -dmitriy
{
broker = inactiveBrokers.peek();
}
try {
if (broker != null) {
broker.prepare();
broker.pushSubject(securityManager.getSystemSubject());
}
try {
// instruct all database services to stop
servicesManager.stopSystemServices(broker);
} catch(final BrokerPoolServicesManagerException e) {
for(final BrokerPoolServiceException bpse : e.getServiceExceptions()) {
LOG.error(bpse.getMessage(), bpse);
}
}
//TOUNDERSTAND (pb) : shutdown() is called on only *one* broker ?
// WM: yes, the database files are shared, so only one broker is needed to close them for all
broker.shutdown();
} finally {
if(broker != null) {
broker.popSubject();
}
}
collectionCache.invalidateAll();
// final notification to database services to shutdown
servicesManager.shutdown();
// remove all remaining inactive brokers as we have shutdown now and no longer need those
inactiveBrokers.clear();
// deregister JMX MBeans
AgentFactory.getInstance().closeDBInstance(this);
//Clear the living instances container
shutdownInstanceConsumer.accept(instanceName);
synchronized (readOnly) {
if (!readOnly) {
// release the lock on the data directory
dataLock.release();
}
}
//clearing additional resources, like ThreadLocal
clearThreadLocals();
LOG.info("shutdown complete !");
if (shutdownListener != null) {
shutdownListener.shutdown(instanceName, instancesCount());
}
}
} finally {
// clear instance variables, just to be sure they will be garbage collected
// the test suite restarts the db a few hundred times
Configurator.clear(this);
transactionManager = null;
collectionCache = null;
xQueryPool = null;
processMonitor = null;
collectionConfigurationManager = null;
notificationService = null;
indexManager = null;
xmlReaderPool = null;
shutdownListener = null;
securityManager = null;
if (lockManager != null) {
lockManager.getLockTable().shutdown();
lockManager = null;
}
notificationService = null;
statusObservers.clear();
startupTriggersManager = null;
statusReporter.terminate();
statusReporter = null;
// instanceThreadGroup.destroy();
}
} finally {
status.process(Event.FINISHED_SHUTDOWN);
}
}
public void addStatusObserver(final Observer statusObserver) {
this.statusObservers.add(statusObserver);
}
public boolean removeStatusObserver(final Observer statusObserver) {
return this.statusObservers.remove(statusObserver);
}
private void clearThreadLocals() {
for (final Thread thread : Thread.getAllStackTraces().keySet()) {
try {
cleanThreadLocalsForThread(thread);
} catch (final EXistException ex) {
if (LOG.isDebugEnabled()) {
LOG.warn("Could not clear ThreadLocals for thread: {}", thread.getName());
}
}
}
}
private void cleanThreadLocalsForThread(final Thread thread) throws EXistException {
try {
// Get a reference to the thread locals table of the current thread
final Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
threadLocalsField.setAccessible(true);
final Object threadLocalTable = threadLocalsField.get(thread);
// Get a reference to the array holding the thread local variables inside the
// ThreadLocalMap of the current thread
final Class threadLocalMapClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
final Field tableField = threadLocalMapClass.getDeclaredField("table");
tableField.setAccessible(true);
final Object table = tableField.get(threadLocalTable);
// The key to the ThreadLocalMap is a WeakReference object. The referent field of this object
// is a reference to the actual ThreadLocal variable
final Field referentField = Reference.class.getDeclaredField("referent");
referentField.setAccessible(true);
for (int i = 0; i < Array.getLength(table); i++) {
// Each entry in the table array of ThreadLocalMap is an Entry object
// representing the thread local reference and its value
final Object entry = Array.get(table, i);
if (entry != null) {
// Get a reference to the thread local object and remove it from the table
final ThreadLocal threadLocal = (ThreadLocal)referentField.get(entry);
threadLocal.remove();
}
}
} catch(final Exception e) {
// We will tolerate an exception here and just log it
throw new EXistException(e);
}
}
public Optional<BrokerWatchdog> getWatchdog() {
return watchdog;
}
//TODO : move this elsewhere
public void triggerCheckpoint() {
if(syncRequired) {
return;
}
synchronized(this) {
syncEvent = Sync.MAJOR;
syncRequired = true;
checkpoint = true;
}
}
private Debuggee debuggee = null;
public Debuggee getDebuggee() {
synchronized(this) {
if(debuggee == null) {
debuggee = DebuggeeFactory.getInstance();
}
}
return debuggee;
}
public Calendar getStartupTime() {
return startupTime;
}
public void printSystemInfo() {
try(final StringWriter sout = new StringWriter();
final PrintWriter writer = new PrintWriter(sout)) {
writer.println("SYSTEM INFO");
writer.format("Database instance: %s\n", getId());
writer.println("-------------------------------------------------------------------");
watchdog.ifPresent(wd -> wd.dump(writer));
final String s = sout.toString();
LOG.info(s);
System.err.println(s);
} catch(final IOException e) {
LOG.error(e);
}
}
@ThreadSafe
private static class StatusReporter extends Observable implements Runnable {
private String status;
private volatile boolean terminate = false;
public StatusReporter(final String status) {
this.status = status;
}
public synchronized void setStatus(final String status) {
this.status = status;
this.setChanged();
this.notifyObservers(status);
}
public void terminate() {
this.terminate = true;
synchronized(this) {
this.notifyAll();
}
}
@Override
public void run() {
while(!terminate) {
synchronized(this) {
try {
wait(500);
} catch(final InterruptedException e) {
// nothing to do
}
this.setChanged();
this.notifyObservers(status);
}
}
}
}
@Override
public Path getStoragePlace() {
return (Path)conf.getProperty(BrokerPool.PROPERTY_DATA_DIR);
}
private final List<TriggerProxy<? extends DocumentTrigger>> documentTriggers = new ArrayList<>();
private final List<TriggerProxy<? extends CollectionTrigger>> collectionTriggers = new ArrayList<>();
@Override
public List<TriggerProxy<? extends DocumentTrigger>> getDocumentTriggers() {
return documentTriggers;
}
@Override
public List<TriggerProxy<? extends CollectionTrigger>> getCollectionTriggers() {
return collectionTriggers;
}
@Override
public void registerDocumentTrigger(final Class<? extends DocumentTrigger> clazz) {
documentTriggers.add(new DocumentTriggerProxy(clazz));
}
@Override
public void registerCollectionTrigger(final Class<? extends CollectionTrigger> clazz) {
collectionTriggers.add(new CollectionTriggerProxy(clazz));
}
public PluginsManager getPluginsManager() {
return pluginManager;
}
public net.sf.saxon.Configuration getSaxonConfiguration() {
return saxonConfig.get();
}
/**
* Represents a change involving {@link BrokerPool#inactiveBrokers}
* or {@link BrokerPool#activeBrokers} or {@link DBBroker#getReferenceCount}
*
* Used for tracing broker leases
*/
private static class TraceableBrokerLeaseChange extends TraceableStateChange<TraceableBrokerLeaseChange.BrokerInfo, TraceableBrokerLeaseChange.Change> {
public enum Change {
GET,
RELEASE
}
public static class BrokerInfo {
final String id;
final int referenceCount;
public BrokerInfo(final String id, final int referenceCount) {
this.id = id;
this.referenceCount = referenceCount;
}
}
private TraceableBrokerLeaseChange(final Change change, final BrokerInfo brokerInfo) {
super(change, brokerInfo);
}
@Override
public String getId() {
return getState().id;
}
@Override
public String describeState() {
return Integer.toString(getState().referenceCount);
}
static TraceableBrokerLeaseChange get(final BrokerInfo brokerInfo) {
return new TraceableBrokerLeaseChange(Change.GET, brokerInfo);
}
static TraceableBrokerLeaseChange release(final BrokerInfo brokerInfo) {
return new TraceableBrokerLeaseChange(Change.RELEASE, brokerInfo);
}
}
}
| exist-core/src/main/java/org/exist/storage/BrokerPool.java | /*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* [email protected]
* http://www.exist-db.org
*
* 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
*/
package org.exist.storage;
import com.evolvedbinary.j8fu.fsm.AtomicFSM;
import com.evolvedbinary.j8fu.fsm.FSM;
import com.evolvedbinary.j8fu.lazy.AtomicLazyVal;
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.Database;
import org.exist.EXistException;
import org.exist.collections.Collection;
import org.exist.collections.CollectionCache;
import org.exist.collections.CollectionConfiguration;
import org.exist.collections.CollectionConfigurationManager;
import org.exist.collections.triggers.*;
import org.exist.config.ConfigurationDocumentTrigger;
import org.exist.config.Configurator;
import org.exist.config.annotation.ConfigurationClass;
import org.exist.config.annotation.ConfigurationFieldAsAttribute;
import org.exist.debuggee.Debuggee;
import org.exist.debuggee.DebuggeeFactory;
import org.exist.dom.persistent.SymbolTable;
import org.exist.indexing.IndexManager;
import org.exist.management.AgentFactory;
import org.exist.numbering.DLNFactory;
import org.exist.numbering.NodeIdFactory;
import org.exist.plugin.PluginsManager;
import org.exist.plugin.PluginsManagerImpl;
import org.exist.repo.ClasspathHelper;
import org.exist.repo.ExistRepository;
import org.exist.scheduler.Scheduler;
import org.exist.scheduler.impl.QuartzSchedulerImpl;
import org.exist.scheduler.impl.SystemTaskJobImpl;
import org.exist.security.*;
import org.exist.security.SecurityManager;
import org.exist.security.internal.SecurityManagerImpl;
import org.exist.storage.blob.BlobStore;
import org.exist.storage.blob.BlobStoreImplService;
import org.exist.storage.blob.BlobStoreService;
import org.exist.storage.journal.JournalManager;
import org.exist.storage.lock.FileLockService;
import org.exist.storage.lock.LockManager;
import org.exist.storage.recovery.RecoveryManager;
import org.exist.storage.sync.Sync;
import org.exist.storage.sync.SyncTask;
import org.exist.storage.txn.TransactionException;
import org.exist.storage.txn.TransactionManager;
import org.exist.storage.txn.Txn;
import org.exist.util.*;
import org.exist.xmldb.ShutdownListener;
import org.exist.xmldb.XmldbURI;
import org.exist.xquery.PerformanceStats;
import org.exist.xquery.XQuery;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.ref.Reference;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.nio.file.FileStore;
import java.nio.file.Path;
import java.text.NumberFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import static com.evolvedbinary.j8fu.fsm.TransitionTable.transitionTable;
import static org.exist.util.ThreadUtils.nameInstanceThreadGroup;
import static org.exist.util.ThreadUtils.newInstanceThread;
/**
* This class controls all available instances of the database.
* Use it to configure, start and stop database instances.
* You may have multiple instances defined, each using its own configuration.
* To define multiple instances, pass an identification string to
* {@link #configure(String, int, int, Configuration, Optional)}
* and use {@link #getInstance(String)} to retrieve an instance.
*
* @author <a href="mailto:[email protected]">Wolfgang Meier</a>
* @author <a href="mailto:[email protected]">Pierrick Brihaye</a>
* @author <a href="mailto:[email protected]">Adam Retter</a>
*/
@ConfigurationClass("pool")
public class BrokerPool extends BrokerPools implements BrokerPoolConstants, Database {
private final static Logger LOG = LogManager.getLogger(BrokerPool.class);
private final BrokerPoolServicesManager servicesManager = new BrokerPoolServicesManager();
private StatusReporter statusReporter = null;
private final XQuery xqueryService = new XQuery();
//TODO : make it non-static since every database instance may have its own policy.
//TODO : make a default value that could be overwritten by the configuration
// WM: this is only used by junit tests to test the recovery process.
/**
* For testing only: triggers a database corruption by disabling the page caches. The effect is
* similar to a sudden power loss or the jvm being killed. The flag is used by some
* junit tests to test the recovery process.
*/
public static boolean FORCE_CORRUPTION = false;
/**
* <code>true</code> if the database instance is able to perform recovery.
*/
private final boolean recoveryEnabled;
/**
* The name of the database instance
*/
private final String instanceName;
private final int concurrencyLevel;
private LockManager lockManager;
/**
* Root thread group for all threads related
* to this instance.
*/
private final ThreadGroup instanceThreadGroup;
/**
* State of the BrokerPool instance
*/
private enum State {
SHUTTING_DOWN_MULTI_USER_MODE,
SHUTTING_DOWN_SYSTEM_MODE,
SHUTDOWN,
INITIALIZING,
INITIALIZING_SYSTEM_MODE,
INITIALIZING_MULTI_USER_MODE,
OPERATIONAL
}
private enum Event {
INITIALIZE,
INITIALIZE_SYSTEM_MODE,
INITIALIZE_MULTI_USER_MODE,
READY,
START_SHUTDOWN_MULTI_USER_MODE,
START_SHUTDOWN_SYSTEM_MODE,
FINISHED_SHUTDOWN,
}
@SuppressWarnings("unchecked")
private final FSM<State, Event> status = new AtomicFSM<>(State.SHUTDOWN,
transitionTable(State.class, Event.class)
.when(State.SHUTDOWN).on(Event.INITIALIZE).switchTo(State.INITIALIZING)
.when(State.INITIALIZING).on(Event.INITIALIZE_SYSTEM_MODE).switchTo(State.INITIALIZING_SYSTEM_MODE)
.when(State.INITIALIZING_SYSTEM_MODE).on(Event.INITIALIZE_MULTI_USER_MODE).switchTo(State.INITIALIZING_MULTI_USER_MODE)
.when(State.INITIALIZING_MULTI_USER_MODE).on(Event.READY).switchTo(State.OPERATIONAL)
.when(State.OPERATIONAL).on(Event.START_SHUTDOWN_MULTI_USER_MODE).switchTo(State.SHUTTING_DOWN_MULTI_USER_MODE)
.when(State.SHUTTING_DOWN_MULTI_USER_MODE).on(Event.START_SHUTDOWN_SYSTEM_MODE).switchTo(State.SHUTTING_DOWN_SYSTEM_MODE)
.when(State.SHUTTING_DOWN_SYSTEM_MODE).on(Event.FINISHED_SHUTDOWN).switchTo(State.SHUTDOWN)
.build()
);
public String getStatus() {
return status.getCurrentState().name();
}
/**
* The number of brokers for the database instance
*/
private int brokersCount = 0;
/**
* The minimal number of brokers for the database instance
*/
@ConfigurationFieldAsAttribute("min")
private final int minBrokers;
/**
* The maximal number of brokers for the database instance
*/
@ConfigurationFieldAsAttribute("max")
private final int maxBrokers;
/**
* The number of inactive brokers for the database instance
*/
private final Deque<DBBroker> inactiveBrokers = new ArrayDeque<>();
/**
* The number of active brokers for the database instance
*/
private final Map<Thread, DBBroker> activeBrokers = new ConcurrentHashMap<>();
/**
* Used when TRACE level logging is enabled
* to provide a history of broker leases
*/
private final Map<String, TraceableStateChanges<TraceableBrokerLeaseChange.BrokerInfo, TraceableBrokerLeaseChange.Change>> brokerLeaseChangeTrace = LOG.isTraceEnabled() ? new HashMap<>() : null;
private final Map<String, List<TraceableStateChanges<TraceableBrokerLeaseChange.BrokerInfo, TraceableBrokerLeaseChange.Change>>> brokerLeaseChangeTraceHistory = LOG.isTraceEnabled() ? new HashMap<>() : null;
/**
* The configuration object for the database instance
*/
private final Configuration conf;
private final ConcurrentSkipListSet<Observer> statusObservers = new ConcurrentSkipListSet<>();
/**
* <code>true</code> if a cache synchronization event is scheduled
*/
//TODO : rename as syncScheduled ?
//TODO : alternatively, delete this member and create a Sync.NOSYNC event
private boolean syncRequired = false;
/**
* The kind of scheduled cache synchronization event.
* One of {@link org.exist.storage.sync.Sync}
*/
private Sync syncEvent = Sync.MINOR;
private boolean checkpoint = false;
/**
* Indicates whether the database is operating in read-only mode
*/
@GuardedBy("itself") private Boolean readOnly = Boolean.FALSE;
@ConfigurationFieldAsAttribute("pageSize")
private final int pageSize;
private FileLockService dataLock;
/**
* The journal manager of the database instance.
*/
private Optional<JournalManager> journalManager = Optional.empty();
/**
* The transaction manager of the database instance.
*/
private TransactionManager transactionManager = null;
/**
* The Blob Store of the database instance.
*/
private BlobStoreService blobStoreService;
/**
* Delay (in ms) for running jobs to return when the database instance shuts down.
*/
@ConfigurationFieldAsAttribute("wait-before-shutdown")
private final long maxShutdownWait;
/**
* The scheduler for the database instance.
*/
@ConfigurationFieldAsAttribute("scheduler")
private Scheduler scheduler;
/**
* Manages pluggable index structures.
*/
private IndexManager indexManager;
/**
* Global symbol table used to encode element and attribute qnames.
*/
private SymbolTable symbols;
/**
* Cache synchronization on the database instance.
*/
@ConfigurationFieldAsAttribute("sync-period")
private final long majorSyncPeriod; //the period after which a major sync should occur
private long lastMajorSync = System.currentTimeMillis(); //time the last major sync occurred
private final long diskSpaceMin;
/**
* The listener that is notified when the database instance shuts down.
*/
private ShutdownListener shutdownListener = null;
/**
* The security manager of the database instance.
*/
private SecurityManager securityManager = null;
/**
* The plugin manager.
*/
private PluginsManagerImpl pluginManager = null;
/**
* The global notification service used to subscribe
* to document updates.
*/
private NotificationService notificationService = null;
/**
* The cache in which the database instance may store items.
*/
private DefaultCacheManager cacheManager;
private long reservedMem;
/**
* The pool in which the database instance's <strong>compiled</strong> XQueries are stored.
*/
private XQueryPool xQueryPool;
/**
* The monitor in which the database instance's strong>running</strong> XQueries are managed.
*/
private ProcessMonitor processMonitor;
/**
* Global performance stats to gather function execution statistics
* from all queries running on this database instance.
*/
private PerformanceStats xqueryStats;
/**
* The global manager for accessing collection configuration files from the database instance.
*/
private CollectionConfigurationManager collectionConfigurationManager = null;
/**
* The cache in which the database instance's collections are stored.
*/
//TODO : rename as collectionsCache ?
private CollectionCache collectionCache;
/**
* The pool in which the database instance's readers are stored.
*/
private XMLReaderPool xmlReaderPool;
private final NodeIdFactory nodeFactory = new DLNFactory();
private final Lock globalXUpdateLock = new ReentrantLock();
private Subject serviceModeUser = null;
private boolean inServiceMode = false;
//the time that the database was started
private final Calendar startupTime = Calendar.getInstance();
private final Optional<BrokerWatchdog> watchdog;
private final ClassLoader classLoader;
private Optional<ExistRepository> expathRepo = Optional.empty();
private StartupTriggersManager startupTriggersManager;
/**
* Configuration for Saxon.
*
* One instance per-database, lazily initialised.
*/
private AtomicLazyVal<net.sf.saxon.Configuration> saxonConfig = new AtomicLazyVal<>(net.sf.saxon.Configuration::newConfiguration);
/**
* Creates and configures the database instance.
*
* @param instanceName A name for the database instance.
* @param minBrokers The minimum number of concurrent brokers for handling requests on the database instance.
* @param maxBrokers The maximum number of concurrent brokers for handling requests on the database instance.
* @param conf The configuration object for the database instance
* @param statusObserver Observes the status of this database instance
*
* @throws EXistException If the initialization fails.
*/
//TODO : Then write a configure(int minBrokers, int maxBrokers, Configuration conf) method
BrokerPool(final String instanceName, final int minBrokers, final int maxBrokers, final Configuration conf,
final Optional<Observer> statusObserver) {
final NumberFormat nf = NumberFormat.getNumberInstance();
this.classLoader = Thread.currentThread().getContextClassLoader();
this.instanceName = instanceName;
this.instanceThreadGroup = new ThreadGroup(nameInstanceThreadGroup(instanceName));
this.maxShutdownWait = conf.getProperty(BrokerPool.PROPERTY_SHUTDOWN_DELAY, DEFAULT_MAX_SHUTDOWN_WAIT);
LOG.info("database instance '{}' will wait {} ms during shutdown", instanceName, nf.format(this.maxShutdownWait));
this.recoveryEnabled = conf.getProperty(PROPERTY_RECOVERY_ENABLED, true);
LOG.info("database instance '{}' is enabled for recovery : {}", instanceName, this.recoveryEnabled);
this.minBrokers = conf.getProperty(PROPERTY_MIN_CONNECTIONS, minBrokers);
this.maxBrokers = conf.getProperty(PROPERTY_MAX_CONNECTIONS, maxBrokers);
LOG.info("database instance '{}' will have between {} and {} brokers", instanceName, nf.format(this.minBrokers), nf.format(this.maxBrokers));
this.majorSyncPeriod = conf.getProperty(PROPERTY_SYNC_PERIOD, DEFAULT_SYNCH_PERIOD);
LOG.info("database instance '{}' will be synchronized every {} ms", instanceName, nf.format(/*this.*/majorSyncPeriod));
// convert from bytes to megabytes: 1024 * 1024
this.diskSpaceMin = 1024L * 1024L * conf.getProperty(BrokerPool.DISK_SPACE_MIN_PROPERTY, DEFAULT_DISK_SPACE_MIN);
this.pageSize = conf.getProperty(PROPERTY_PAGE_SIZE, DEFAULT_PAGE_SIZE);
//Configuration is valid, save it
this.conf = conf;
this.concurrencyLevel = Math.max(maxBrokers, 2 * Runtime.getRuntime().availableProcessors());
statusObserver.ifPresent(this.statusObservers::add);
this.watchdog = Optional.ofNullable(System.getProperty(BrokerWatchdog.TRACE_BROKERS_PROPERTY_NAME))
.filter(value -> value.equals("yes"))
.map(value -> new BrokerWatchdog());
}
/**
* Initializes the database instance.
*
* @throws EXistException
* @throws DatabaseConfigurationException
*/
void initialize() throws EXistException, DatabaseConfigurationException {
try {
_initialize();
} catch(final Throwable e) {
// remove that file lock we may have acquired in canReadDataDir
synchronized(readOnly) {
if (dataLock != null && !readOnly) {
dataLock.release();
}
}
if(e instanceof EXistException) {
throw (EXistException) e;
} else if(e instanceof DatabaseConfigurationException) {
throw (DatabaseConfigurationException) e;
} else {
throw new EXistException(e);
}
}
}
private void _initialize() throws EXistException, DatabaseConfigurationException {
this.lockManager = new LockManager(conf, concurrencyLevel);
//Flag to indicate that we are initializing
status.process(Event.INITIALIZE);
if(LOG.isDebugEnabled()) {
LOG.debug("initializing database instance '{}'...", instanceName);
}
// register core broker pool services
this.scheduler = servicesManager.register(new QuartzSchedulerImpl(this));
// NOTE: this must occur after the scheduler, and before any other service which requires access to the data directory
this.dataLock = servicesManager.register(new FileLockService("dbx_dir.lck", BrokerPool.PROPERTY_DATA_DIR, NativeBroker.DEFAULT_DATA_DIR));
this.securityManager = servicesManager.register(new SecurityManagerImpl(this));
this.cacheManager = servicesManager.register(new DefaultCacheManager(this));
this.xQueryPool = servicesManager.register(new XQueryPool());
this.processMonitor = servicesManager.register(new ProcessMonitor());
this.xqueryStats = servicesManager.register(new PerformanceStats(this));
final XMLReaderObjectFactory xmlReaderObjectFactory = servicesManager.register(new XMLReaderObjectFactory());
this.xmlReaderPool = servicesManager.register(new XMLReaderPool(xmlReaderObjectFactory, 5, 0));
final int bufferSize = Optional.of(conf.getInteger(PROPERTY_COLLECTION_CACHE_SIZE))
.filter(size -> size != -1)
.orElse(DEFAULT_COLLECTION_BUFFER_SIZE);
this.collectionCache = servicesManager.register(new CollectionCache());
this.notificationService = servicesManager.register(new NotificationService());
this.journalManager = recoveryEnabled ? Optional.of(new JournalManager()) : Optional.empty();
journalManager.ifPresent(servicesManager::register);
final SystemTaskManager systemTaskManager = servicesManager.register(new SystemTaskManager(this));
this.transactionManager = servicesManager.register(new TransactionManager(this, journalManager, systemTaskManager));
this.blobStoreService = servicesManager.register(new BlobStoreImplService());
this.symbols = servicesManager.register(new SymbolTable());
this.expathRepo = Optional.ofNullable(new ExistRepository());
expathRepo.ifPresent(servicesManager::register);
servicesManager.register(new ClasspathHelper());
this.indexManager = servicesManager.register(new IndexManager(this));
//prepare those services that require system (single-user) mode
this.pluginManager = servicesManager.register(new PluginsManagerImpl());
//Get a manager to handle further collections configuration
this.collectionConfigurationManager = servicesManager.register(new CollectionConfigurationManager(this));
this.startupTriggersManager = servicesManager.register(new StartupTriggersManager());
// this is just used for unit tests
final BrokerPoolService testBrokerPoolService = (BrokerPoolService) conf.getProperty("exist.testBrokerPoolService");
if (testBrokerPoolService != null) {
servicesManager.register(testBrokerPoolService);
}
//configure the registered services
try {
servicesManager.configureServices(conf);
} catch(final BrokerPoolServiceException e) {
throw new EXistException(e);
}
// calculate how much memory is reserved for caches to grow
final Runtime rt = Runtime.getRuntime();
final long maxMem = rt.maxMemory();
final long minFree = maxMem / 5;
reservedMem = cacheManager.getTotalMem() + collectionCache.getMaxCacheSize() + minFree;
LOG.debug("Reserved memory: {}; max: {}; min: {}", reservedMem, maxMem, minFree);
//prepare the registered services, before entering system (single-user) mode
try {
servicesManager.prepareServices(this);
} catch(final BrokerPoolServiceException e) {
throw new EXistException(e);
}
//setup database synchronization job
if(majorSyncPeriod > 0) {
final SyncTask syncTask = new SyncTask();
syncTask.configure(conf, null);
scheduler.createPeriodicJob(2500, new SystemTaskJobImpl(SyncTask.getJobName(), syncTask), 2500);
}
try {
statusReporter = new StatusReporter(SIGNAL_STARTUP);
statusObservers.forEach(statusReporter::addObserver);
final Thread statusThread = newInstanceThread(this, "startup-status-reporter", statusReporter);
statusThread.start();
// statusReporter may have to be terminated or the thread can/will hang.
try {
final boolean exportOnly = conf.getProperty(PROPERTY_EXPORT_ONLY, false);
// If the initialization fails after transactionManager has been created this method better cleans up
// or the FileSyncThread for the journal can/will hang.
try {
// Enter System Mode
try(final DBBroker systemBroker = get(Optional.of(securityManager.getSystemSubject()))) {
status.process(Event.INITIALIZE_SYSTEM_MODE);
if(isReadOnly()) {
journalManager.ifPresent(JournalManager::disableJournalling);
}
try(final Txn transaction = transactionManager.beginTransaction()) {
servicesManager.startPreSystemServices(systemBroker, transaction);
transaction.commit();
} catch(final BrokerPoolServiceException e) {
throw new EXistException(e);
}
//Run the recovery process
boolean recovered = false;
if(isRecoveryEnabled()) {
recovered = runRecovery(systemBroker);
//TODO : extract the following from this block ? What if we are not transactional ? -pb
if(!recovered) {
try {
if(systemBroker.getCollection(XmldbURI.ROOT_COLLECTION_URI) == null) {
final Txn txn = transactionManager.beginTransaction();
try {
systemBroker.getOrCreateCollection(txn, XmldbURI.ROOT_COLLECTION_URI);
transactionManager.commit(txn);
} catch(final IOException | TriggerException | PermissionDeniedException e) {
transactionManager.abort(txn);
} finally {
transactionManager.close(txn);
}
}
} catch(final PermissionDeniedException pde) {
LOG.fatal(pde.getMessage(), pde);
}
}
}
/* initialise required collections if they don't exist yet */
if(!exportOnly) {
try {
initialiseSystemCollections(systemBroker);
} catch(final PermissionDeniedException pde) {
LOG.error(pde.getMessage(), pde);
throw new EXistException(pde.getMessage(), pde);
}
}
statusReporter.setStatus(SIGNAL_READINESS);
try(final Txn transaction = transactionManager.beginTransaction()) {
servicesManager.startSystemServices(systemBroker, transaction);
transaction.commit();
} catch(final BrokerPoolServiceException e) {
throw new EXistException(e);
}
//If necessary, launch a task to repair the DB
//TODO : merge this with the recovery process ?
if(isRecoveryEnabled() && recovered) {
if(!exportOnly) {
reportStatus("Reindexing database files...");
try {
systemBroker.repair();
} catch(final PermissionDeniedException e) {
LOG.warn("Error during recovery: {}", e.getMessage(), e);
}
}
if((Boolean) conf.getProperty(PROPERTY_RECOVERY_CHECK)) {
final ConsistencyCheckTask task = new ConsistencyCheckTask();
final Properties props = new Properties();
props.setProperty("backup", "no");
props.setProperty("output", "sanity");
task.configure(conf, props);
try (final Txn transaction = transactionManager.beginTransaction()) {
task.execute(systemBroker, transaction);
transaction.commit();
}
}
}
//OK : the DB is repaired; let's make a few RW operations
statusReporter.setStatus(SIGNAL_WRITABLE);
//initialize configurations watcher trigger
if(!exportOnly) {
try {
initialiseTriggersForCollections(systemBroker, XmldbURI.SYSTEM_COLLECTION_URI);
} catch(final PermissionDeniedException pde) {
//XXX: do not catch exception!
LOG.error(pde.getMessage(), pde);
}
}
// remove temporary docs
try {
systemBroker.cleanUpTempResources(true);
} catch(final PermissionDeniedException pde) {
LOG.error(pde.getMessage(), pde);
}
sync(systemBroker, Sync.MAJOR);
// we have completed all system mode operations
// we can now prepare those services which need
// system mode before entering multi-user mode
try(final Txn transaction = transactionManager.beginTransaction()) {
servicesManager.startPreMultiUserSystemServices(systemBroker, transaction);
transaction.commit();
} catch(final BrokerPoolServiceException e) {
throw new EXistException(e);
}
}
//Create a default configuration file for the root collection
//TODO : why can't we call this from within CollectionConfigurationManager ?
//TODO : understand why we get a test suite failure
//collectionConfigurationManager.checkRootCollectionConfigCollection(broker);
//collectionConfigurationManager.checkRootCollectionConfig(broker);
//Create the minimal number of brokers required by the configuration
for(int i = 1; i < minBrokers; i++) {
createBroker();
}
status.process(Event.INITIALIZE_MULTI_USER_MODE);
// register some MBeans to provide access to this instance
AgentFactory.getInstance().initDBInstance(this);
if(LOG.isDebugEnabled()) {
LOG.debug("database instance '{}' initialized", instanceName);
}
servicesManager.startMultiUserServices(this);
status.process(Event.READY);
statusReporter.setStatus(SIGNAL_STARTED);
} catch(final Throwable t) {
transactionManager.shutdown();
throw t;
}
} catch(final EXistException e) {
throw e;
} catch(final Throwable t) {
throw new EXistException(t.getMessage(), t);
}
} finally {
if(statusReporter != null) {
statusReporter.terminate();
statusReporter = null;
}
}
}
/**
* Initialise system collections, if it doesn't exist yet
*
* @param sysBroker The system broker from before the brokerpool is populated
* @param sysCollectionUri XmldbURI of the collection to create
* @param permissions The permissions to set on the created collection
*/
private void initialiseSystemCollection(final DBBroker sysBroker, final XmldbURI sysCollectionUri, final int permissions) throws EXistException, PermissionDeniedException {
Collection collection = sysBroker.getCollection(sysCollectionUri);
if(collection == null) {
final TransactionManager transact = getTransactionManager();
try(final Txn txn = transact.beginTransaction()) {
collection = sysBroker.getOrCreateCollection(txn, sysCollectionUri);
if(collection == null) {
throw new IOException("Could not create system collection: " + sysCollectionUri);
}
collection.setPermissions(sysBroker, permissions);
sysBroker.saveCollection(txn, collection);
transact.commit(txn);
} catch(final Exception e) {
e.printStackTrace();
final String msg = "Initialisation of system collections failed: " + e.getMessage();
LOG.error(msg, e);
throw new EXistException(msg, e);
}
}
}
/**
* Initialize required system collections, if they don't exist yet
*
* @param broker - The system broker from before the brokerpool is populated
* @throws EXistException If a system collection cannot be created
*/
private void initialiseSystemCollections(final DBBroker broker) throws EXistException, PermissionDeniedException {
//create /db/system
initialiseSystemCollection(broker, XmldbURI.SYSTEM_COLLECTION_URI, Permission.DEFAULT_SYSTEM_COLLECTION_PERM);
}
private void initialiseTriggersForCollections(final DBBroker broker, final XmldbURI uri) throws EXistException, PermissionDeniedException {
final Collection collection = broker.getCollection(uri);
//initialize configurations watcher trigger
if(collection != null) {
final CollectionConfigurationManager manager = getConfigurationManager();
final CollectionConfiguration collConf = manager.getOrCreateCollectionConfiguration(broker, collection);
final DocumentTriggerProxy triggerProxy = new DocumentTriggerProxy(ConfigurationDocumentTrigger.class); //, collection.getURI());
collConf.documentTriggers().add(triggerProxy);
}
}
/**
* Get the LockManager for this database instance
*
* @return The lock manager
*/
public LockManager getLockManager() {
return lockManager;
}
/**
* Run a database recovery if required. This method is called once during
* startup from {@link org.exist.storage.BrokerPool}.
*
* @param broker the database broker
* @return true if recovery was run, false otherwise
* @throws EXistException if a database error occurs
*/
public boolean runRecovery(final DBBroker broker) throws EXistException {
final boolean forceRestart = conf.getProperty(PROPERTY_RECOVERY_FORCE_RESTART, false);
if(LOG.isDebugEnabled()) {
LOG.debug("ForceRestart = {}", forceRestart);
}
if(journalManager.isPresent()) {
final RecoveryManager recovery = new RecoveryManager(broker, journalManager.get(), forceRestart);
return recovery.recover();
} else {
throw new IllegalStateException("Cannot run recovery without a JournalManager");
}
}
public long getReservedMem() {
return reservedMem - cacheManager.getCurrentSize();
}
public int getPageSize() {
return pageSize;
}
/**
* Returns the class loader used when this BrokerPool was configured.
*
* @return the classloader
*/
public ClassLoader getClassLoader() {
return this.classLoader;
}
/**
* Whether or not the database instance is operational, i.e. initialization
* has completed
*
* @return <code>true</code> if the database instance is operational
*/
public boolean isOperational() {
return status.getCurrentState() == State.OPERATIONAL;
}
/**
* Returns the database instance's name.
*
* @return The id
*/
//TODO : rename getInstanceName
public String getId() {
return instanceName;
}
@Override
public ThreadGroup getThreadGroup() {
return instanceThreadGroup;
}
/**
* Returns the number of brokers currently serving requests for the database instance.
*
* @return The brokers count
* @deprecated use countActiveBrokers
*/
//TODO : rename as getActiveBrokers ?
public int active() {
return activeBrokers.size();
}
/**
* Returns the number of brokers currently serving requests for the database instance.
*
* @return The active brokers count.
*/
@Override
public int countActiveBrokers() {
return activeBrokers.size();
}
public Map<Thread, DBBroker> getActiveBrokers() {
return new HashMap<>(activeBrokers);
}
/**
* Returns the number of inactive brokers for the database instance.
*
* @return The brokers count
*/
//TODO : rename as getInactiveBrokers ?
public int available() {
return inactiveBrokers.size();
}
//TODO : getMin() method ?
/**
* Returns the maximal number of brokers for the database instance.
*
* @return The brokers count
*/
//TODO : rename as getMaxBrokers ?
public int getMax() {
return maxBrokers;
}
public int total() {
return brokersCount;
}
/**
* Returns whether the database instance has been configured.
*
* @return <code>true</code> if the datbase instance is configured
*/
public final boolean isInstanceConfigured() {
return conf != null;
}
/**
* Returns the configuration object for the database instance.
*
* @return The configuration
*/
public Configuration getConfiguration() {
return conf;
}
public Optional<ExistRepository> getExpathRepo() {
return expathRepo;
}
//TODO : rename as setShutdwonListener ?
public void registerShutdownListener(final ShutdownListener listener) {
//TODO : check that we are not shutting down
shutdownListener = listener;
}
public NodeIdFactory getNodeFactory() {
return nodeFactory;
}
/**
* Returns the database instance's security manager
*
* @return The security manager
*/
public SecurityManager getSecurityManager() {
return securityManager;
}
/**
* Returns the Scheduler
*
* @return The scheduler
*/
public Scheduler getScheduler() {
return scheduler;
}
@Override
public BlobStore getBlobStore() {
return blobStoreService.getBlobStore();
}
public SymbolTable getSymbols() {
return symbols;
}
public NotificationService getNotificationService() {
return notificationService;
}
/**
* Returns whether transactions can be handled by the database instance.
*
* @return <code>true</code> if transactions can be handled
*/
public boolean isRecoveryEnabled() {
synchronized(readOnly) {
return !readOnly && recoveryEnabled;
}
}
@Override
public boolean isReadOnly() {
synchronized(readOnly) {
if(!readOnly) {
final long freeSpace = FileUtils.measureFileStore(dataLock.getFile(), FileStore::getUsableSpace);
if (freeSpace != -1 && freeSpace < diskSpaceMin) {
LOG.fatal("Partition containing DATA_DIR: {} is running out of disk space [minimum: {} free: {}]. Switching eXist-db into read-only mode to prevent data loss!", dataLock.getFile().toAbsolutePath().toString(), diskSpaceMin, freeSpace);
setReadOnly();
}
}
return readOnly;
}
}
public void setReadOnly() {
LOG.warn("Switching database into read-only mode!");
synchronized (readOnly) {
readOnly = true;
}
}
public boolean isInServiceMode() {
return inServiceMode;
}
@Override
public Optional<JournalManager> getJournalManager() {
return journalManager;
}
public TransactionManager getTransactionManager() {
return transactionManager;
}
/**
* Returns a manager for accessing the database instance's collection configuration files.
*
* @return The manager
*/
@Override
public CollectionConfigurationManager getConfigurationManager() {
return collectionConfigurationManager;
}
/**
* Returns a cache in which the database instance's collections are stored.
*
* @return The cache
*/
public CollectionCache getCollectionsCache() {
return collectionCache;
}
/**
* Returns a cache in which the database instance's may store items.
*
* @return The cache
*/
@Override
public DefaultCacheManager getCacheManager() {
return cacheManager;
}
/**
* Returns the index manager which handles all additional indexes not
* being part of the database core.
*
* @return The IndexManager
*/
@Override
public IndexManager getIndexManager() {
return indexManager;
}
/**
* Returns a pool in which the database instance's <strong>compiled</strong> XQueries are stored.
*
* @return The pool
*/
public XQueryPool getXQueryPool() {
return xQueryPool;
}
/**
* Retuns the XQuery Service
*
* @return The XQuery service
*/
public XQuery getXQueryService() {
return xqueryService;
}
/**
* Returns a monitor in which the database instance's <strong>running</strong> XQueries are managed.
*
* @return The monitor
*/
public ProcessMonitor getProcessMonitor() {
return processMonitor;
}
/**
* Returns the global profiler used to gather execution statistics
* from all XQueries running on this db instance.
*
* @return the profiler
*/
public PerformanceStats getPerformanceStats() {
return xqueryStats;
}
/**
* Returns a pool in which the database instance's readers are stored.
*
* @return The pool
*/
public XMLReaderPool getParserPool() {
return xmlReaderPool;
}
/**
* Returns the global update lock for the database instance.
* This lock is used by XUpdate operations to avoid that
* concurrent XUpdate requests modify the database until all
* document locks have been correctly set.
*
* @return The global lock
*/
//TODO : rename as getUpdateLock ?
public Lock getGlobalUpdateLock() {
return globalXUpdateLock;
}
/**
* Creates an inactive broker for the database instance.
*
* @return The broker
* @throws EXistException if the broker cannot be created
*/
protected DBBroker createBroker() throws EXistException {
//TODO : in the future, don't pass the whole configuration, just the part relevant to brokers
final DBBroker broker = BrokerFactory.getInstance(this, this.getConfiguration());
inactiveBrokers.push(broker);
brokersCount++;
broker.setId(broker.getClass().getName() + '_' + instanceName + "_" + brokersCount);
if (LOG.isDebugEnabled()) {
LOG.debug("Created broker '{} for database instance '{}'", broker.getId(), instanceName);
}
return broker;
}
/**
* Get active broker for current thread
*
* Note - If you call getActiveBroker() you must not call
* release on both the returned active broker and the original
* lease from {@link BrokerPool#getBroker()} or {@link BrokerPool#get(Optional)}
* otherwise release will have been called more than get!
*
* @return Database broker
* @throws RuntimeException NO broker available for current thread.
*/
public DBBroker getActiveBroker() { //throws EXistException {
//synchronized(this) {
//Try to get an active broker
final DBBroker broker = activeBrokers.get(Thread.currentThread());
if(broker == null) {
final StringBuilder sb = new StringBuilder();
sb.append("Broker was not obtained for thread '");
sb.append(Thread.currentThread());
sb.append("'.");
sb.append(System.getProperty("line.separator"));
for(final Entry<Thread, DBBroker> entry : activeBrokers.entrySet()) {
sb.append(entry.getKey());
sb.append(" = ");
sb.append(entry.getValue());
sb.append(System.getProperty("line.separator"));
}
LOG.debug(sb.toString());
throw new RuntimeException(sb.toString());
}
return broker;
//}
}
public DBBroker authenticate(final String username, final Object credentials) throws AuthenticationException {
final Subject subject = getSecurityManager().authenticate(username, credentials);
try {
return get(Optional.ofNullable(subject));
} catch(final Exception e) {
throw new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, e);
}
}
/**
* Returns an active broker for the database instance.
*
* The current user will be inherited by this broker
*
* @return The broker
*/
public DBBroker getBroker() throws EXistException {
return get(Optional.empty());
}
/**
* Returns an active broker for the database instance.
*
* @param subject Optionally a subject to set on the broker, if a user is not provided then the
* current user assigned to the broker will be re-used
* @return The broker
* @throws EXistException If the instance is not available (stopped or not configured)
*/
//TODO : rename as getBroker ? getInstance (when refactored) ?
public DBBroker get(final Optional<Subject> subject) throws EXistException {
Objects.requireNonNull(subject, "Subject cannot be null, use BrokerPool#getBroker() instead");
if(!isInstanceConfigured()) {
throw new EXistException("database instance '" + instanceName + "' is not available");
}
//Try to get an active broker
DBBroker broker = activeBrokers.get(Thread.currentThread());
//Use it...
//TOUNDERSTAND (pb) : why not pop a broker from the inactive ones rather than maintaining reference counters ?
// WM: a thread may call this more than once in the sequence of operations, i.e. calls to get/release can
// be nested. Returning a new broker every time would lead to a deadlock condition if two threads have
// to wait for a broker to become available. We thus use reference counts and return
// the same broker instance for each thread.
if(broker != null) {
//increase its number of uses
broker.incReferenceCount();
broker.pushSubject(subject.orElseGet(broker::getCurrentSubject));
if(LOG.isTraceEnabled()) {
if(!brokerLeaseChangeTrace.containsKey(broker.getId())) {
brokerLeaseChangeTrace.put(broker.getId(), new TraceableStateChanges<>());
}
brokerLeaseChangeTrace.get(broker.getId()).add(TraceableBrokerLeaseChange.get(new TraceableBrokerLeaseChange.BrokerInfo(broker.getId(), broker.getReferenceCount())));
}
return broker;
//TODO : share the code with what is below (including notifyAll) ?
// WM: notifyAll is not necessary if we don't have to wait for a broker.
}
//No active broker : get one ASAP
while(serviceModeUser != null && subject.isPresent() && !subject.equals(Optional.ofNullable(serviceModeUser))) {
try {
LOG.debug("Db instance is in service mode. Waiting for db to become available again ...");
wait();
} catch(final InterruptedException e) {
Thread.currentThread().interrupt();
LOG.error("Interrupt detected");
}
}
synchronized(this) {
//Are there any available brokers ?
if(inactiveBrokers.isEmpty()) {
//There are no available brokers. If allowed...
if(brokersCount < maxBrokers)
//... create one
{
createBroker();
} else
//... or wait until there is one available
while(inactiveBrokers.isEmpty()) {
LOG.debug("waiting for a broker to become available");
try {
this.wait();
} catch(final InterruptedException e) {
//nothing to be done!
}
}
}
broker = inactiveBrokers.pop();
broker.prepare();
//activate the broker
activeBrokers.put(Thread.currentThread(), broker);
if(LOG.isTraceEnabled()) {
LOG.trace("+++ {}{}", Thread.currentThread(), Stacktrace.top(Thread.currentThread().getStackTrace(), Stacktrace.DEFAULT_STACK_TOP));
}
if(watchdog.isPresent()) {
watchdog.get().add(broker);
}
broker.incReferenceCount();
broker.pushSubject(subject.orElseGet(securityManager::getGuestSubject));
if(LOG.isTraceEnabled()) {
if(!brokerLeaseChangeTrace.containsKey(broker.getId())) {
brokerLeaseChangeTrace.put(broker.getId(), new TraceableStateChanges<>());
}
brokerLeaseChangeTrace.get(broker.getId()).add(TraceableBrokerLeaseChange.get(new TraceableBrokerLeaseChange.BrokerInfo(broker.getId(), broker.getReferenceCount())));
}
//Inform the other threads that we have a new-comer
// TODO: do they really need to be informed here???????
this.notifyAll();
return broker;
}
}
/**
* Releases a broker for the database instance. If it is no more used, make if invactive.
* If there are pending system maintenance tasks,
* the method will block until these tasks have finished.
*
* NOTE - this is intentionally package-private, it is only meant to be
* called internally and from {@link DBBroker#close()}
*
* @param broker The broker to be released
*/
//TODO : rename as releaseBroker ? releaseInstance (when refactored) ?
void release(final DBBroker broker) {
Objects.requireNonNull(broker, "Cannot release nothing");
if(LOG.isTraceEnabled()) {
if(!brokerLeaseChangeTrace.containsKey(broker.getId())) {
brokerLeaseChangeTrace.put(broker.getId(), new TraceableStateChanges<>());
}
brokerLeaseChangeTrace.get(broker.getId()).add(TraceableBrokerLeaseChange.release(new TraceableBrokerLeaseChange.BrokerInfo(broker.getId(), broker.getReferenceCount())));
}
//first check that the broker is active ! If not, return immediately.
broker.decReferenceCount();
if(broker.getReferenceCount() > 0) {
broker.popSubject();
//it is still in use and thus can't be marked as inactive
return;
}
synchronized(this) {
//Broker is no more used : inactivate it
for(final DBBroker inactiveBroker : inactiveBrokers) {
if(broker == inactiveBroker) {
LOG.error("Broker {} is already in the inactive list!!!", broker.getId());
return;
}
}
if(activeBrokers.remove(Thread.currentThread()) == null) {
LOG.error("release() has been called from the wrong thread for broker {}", broker.getId());
// Cleanup the state of activeBrokers
for(final Entry<Thread, DBBroker> activeBroker : activeBrokers.entrySet()) {
if(activeBroker.getValue() == broker) {
final String msg = "release() has been called from '" + Thread.currentThread() + "', but occupied at '" + activeBroker.getKey() + "'.";
final EXistException ex = new EXistException(msg);
LOG.error(msg, ex);
activeBrokers.remove(activeBroker.getKey());
break;
}
}
} else {
if(LOG.isTraceEnabled()) {
LOG.trace("--- {}{}", Thread.currentThread(), Stacktrace.top(Thread.currentThread().getStackTrace(), Stacktrace.DEFAULT_STACK_TOP));
}
}
Subject lastUser = broker.popSubject();
//guard to ensure that the broker has popped all its subjects
if(lastUser == null || broker.getCurrentSubject() != null) {
LOG.warn("Broker {} was returned with extraneous Subjects, cleaning...", broker.getId(), new IllegalStateException("DBBroker pushSubject/popSubject mismatch").fillInStackTrace());
if(LOG.isTraceEnabled()) {
broker.traceSubjectChanges();
}
//cleanup any remaining erroneous subjects
while(broker.getCurrentSubject() != null) {
lastUser = broker.popSubject();
}
}
inactiveBrokers.push(broker);
watchdog.ifPresent(wd -> wd.remove(broker));
if(LOG.isTraceEnabled()) {
if(!brokerLeaseChangeTraceHistory.containsKey(broker.getId())) {
brokerLeaseChangeTraceHistory.put(broker.getId(), new ArrayList<>());
}
try {
brokerLeaseChangeTraceHistory.get(broker.getId()).add((TraceableStateChanges<TraceableBrokerLeaseChange.BrokerInfo, TraceableBrokerLeaseChange.Change>) brokerLeaseChangeTrace.get(broker.getId()).clone());
brokerLeaseChangeTrace.get(broker.getId()).clear();
} catch(final CloneNotSupportedException e) {
LOG.error(e);
}
broker.clearSubjectChangesTrace();
}
//If the database is now idle, do some useful stuff
if(activeBrokers.size() == 0) {
//TODO : use a "clean" dedicated method (we have some below) ?
if(syncRequired) {
//Note that the broker is not yet really inactive ;-)
sync(broker, syncEvent);
this.syncRequired = false;
this.checkpoint = false;
}
if(serviceModeUser != null && !lastUser.equals(serviceModeUser)) {
inServiceMode = true;
}
}
//Inform the other threads that someone is gone
this.notifyAll();
}
}
public DBBroker enterServiceMode(final Subject user) throws PermissionDeniedException {
if(!user.hasDbaRole()) {
throw new PermissionDeniedException("Only users of group dba can switch the db to service mode");
}
serviceModeUser = user;
synchronized(this) {
if(activeBrokers.size() != 0) {
while(!inServiceMode) {
try {
wait();
} catch(final InterruptedException e) {
//nothing to be done
}
}
}
}
inServiceMode = true;
final DBBroker broker = inactiveBrokers.peek();
broker.prepare();
checkpoint = true;
sync(broker, Sync.MAJOR);
checkpoint = false;
// Return a broker that can be used to perform system tasks
return broker;
}
public void exitServiceMode(final Subject user) throws PermissionDeniedException {
if(!user.equals(serviceModeUser)) {
throw new PermissionDeniedException("The db has been locked by a different user");
}
serviceModeUser = null;
inServiceMode = false;
synchronized(this) {
this.notifyAll();
}
}
public void reportStatus(final String message) {
if(statusReporter != null) {
statusReporter.setStatus(message);
}
}
public long getMajorSyncPeriod() {
return majorSyncPeriod;
}
public long getLastMajorSync() {
return lastMajorSync;
}
/**
* Executes a waiting cache synchronization for the database instance.
*
* NOTE: This method should not be called concurrently from multiple threads.
*
* @param broker A broker responsible for executing the job
* @param syncEvent One of {@link org.exist.storage.sync.Sync}
*/
public void sync(final DBBroker broker, final Sync syncEvent) {
/**
* Database Systems - The Complete Book (Second edition)
* § 17.4.1 The Undo/Redo Rules
*
* The constraints that an undo/redo logging system must follow are summarized by the following rule:
* * UR1 Before modifying any database element X on disk because of changes
* made by some transaction T, it is necessary that the update record
* <T,X,v,w> appear on disk.
*/
journalManager.ifPresent(manager -> manager.flush(true, true));
// sync various DBX files
broker.sync(syncEvent);
//TODO : strange that it is set *after* the sunc method has been called.
try {
broker.pushSubject(securityManager.getSystemSubject());
if (syncEvent == Sync.MAJOR) {
LOG.debug("Major sync");
try {
if (!FORCE_CORRUPTION) {
transactionManager.checkpoint(checkpoint);
}
} catch (final TransactionException e) {
LOG.warn(e.getMessage(), e);
}
cacheManager.checkCaches();
if (pluginManager != null) {
pluginManager.sync(broker);
}
lastMajorSync = System.currentTimeMillis();
if (LOG.isDebugEnabled()) {
notificationService.debug();
}
} else {
cacheManager.checkDistribution();
// LOG.debug("Minor sync");
}
//TODO : touch this.syncEvent and syncRequired ?
} finally {
broker.popSubject();
}
}
/**
* Schedules a system maintenance task for the database instance. If the database is idle,
* the task will be run immediately. Otherwise, the task will be deferred
* until all running threads have returned.
*
* @param task The task
*/
//TOUNDERSTAND (pb) : synchronized, so... "schedules" or, rather, "executes" ?
public void triggerSystemTask(final SystemTask task) {
final State s = status.getCurrentState();
if(s == State.SHUTTING_DOWN_MULTI_USER_MODE || s == State.SHUTTING_DOWN_SYSTEM_MODE) {
LOG.info("Skipping SystemTask: '{}' as database is shutting down...", task.getName());
return;
} else if(s == State.SHUTDOWN) {
LOG.warn("Unable to execute SystemTask: '{}' as database is shut down!", task.getName());
return;
}
transactionManager.triggerSystemTask(task);
}
/**
* Shuts downs the database instance
*/
public void shutdown() {
shutdown(false);
}
/**
* Returns true if the BrokerPool is in the
* process of shutting down.
*
* @return true if the BrokerPool is shutting down.
*/
public boolean isShuttingDown() {
final State s = status.getCurrentState();
return s == State.SHUTTING_DOWN_MULTI_USER_MODE
|| s == State.SHUTTING_DOWN_SYSTEM_MODE;
}
/**
* Returns true if the BrokerPool is either in the
* process of shutting down, or has already shutdown.
*
* @return true if the BrokerPool is shutting down or
* has shutdown.
*/
public boolean isShuttingDownOrDown() {
final State s = status.getCurrentState();
return s == State.SHUTTING_DOWN_MULTI_USER_MODE
|| s == State.SHUTTING_DOWN_SYSTEM_MODE
|| s == State.SHUTDOWN;
}
/**
* Returns true of the BrokerPool is shutdown.
*
* @return true if the BrokerPool is shutdown.
*/
public boolean isShutDown() {
return status.getCurrentState() == State.SHUTDOWN;
}
/**
* Shuts downs the database instance
*
* @param killed <code>true</code> when the JVM is (cleanly) exiting
*/
public void shutdown(final boolean killed) {
shutdown(killed, BrokerPools::removeInstance);
}
void shutdown(final boolean killed, final Consumer<String> shutdownInstanceConsumer) {
try {
status.process(Event.START_SHUTDOWN_MULTI_USER_MODE);
} catch(final IllegalStateException e) {
// we are not operational!
LOG.warn(e);
return;
}
// notify any BrokerPoolServices that we are about to shutdown
try {
// instruct database services that we are about to stop multi-user mode
servicesManager.stopMultiUserServices(this);
} catch(final BrokerPoolServicesManagerException e) {
for(final BrokerPoolServiceException bpse : e.getServiceExceptions()) {
LOG.error(bpse.getMessage(), bpse);
}
}
try {
status.process(Event.START_SHUTDOWN_SYSTEM_MODE);
} catch(final IllegalStateException e) {
// we are not in SHUTTING_DOWN_MULTI_USER_MODE!
LOG.warn(e);
return;
}
try {
LOG.info("Database is shutting down ...");
processMonitor.stopRunningJobs();
//Shutdown the scheduler
scheduler.shutdown(true);
try {
statusReporter = new StatusReporter(SIGNAL_SHUTDOWN);
statusObservers.forEach(statusReporter::addObserver);
synchronized (this) {
final Thread statusThread = newInstanceThread(this, "shutdown-status-reporter", statusReporter);
statusThread.start();
// DW: only in debug mode
if (LOG.isDebugEnabled()) {
notificationService.debug();
}
//Notify all running tasks that we are shutting down
//Notify all running XQueries that we are shutting down
processMonitor.killAll(500);
if (isRecoveryEnabled()) {
journalManager.ifPresent(jm -> jm.flush(true, true));
}
final long waitStart = System.currentTimeMillis();
//Are there active brokers ?
if (activeBrokers.size() > 0) {
printSystemInfo();
LOG.info("Waiting {}ms for remaining threads to shut down...", maxShutdownWait);
while (activeBrokers.size() > 0) {
try {
//Wait until they become inactive...
this.wait(1000);
} catch (final InterruptedException e) {
//nothing to be done
}
//...or force the shutdown
if (maxShutdownWait > -1 && System.currentTimeMillis() - waitStart > maxShutdownWait) {
LOG.warn("Not all threads returned. Forcing shutdown ...");
break;
}
}
}
LOG.debug("Calling shutdown ...");
//TODO : replace the following code by get()/release() statements ?
// WM: deadlock risk if not all brokers returned properly.
DBBroker broker = null;
if (inactiveBrokers.isEmpty())
try {
broker = createBroker();
} catch (final EXistException e) {
LOG.warn("could not create instance for shutdown. Giving up.");
}
else
//TODO : this broker is *not* marked as active and may be reused by another process !
//TODO : use get() then release the broker ?
// WM: deadlock risk if not all brokers returned properly.
//TODO: always createBroker? -dmitriy
{
broker = inactiveBrokers.peek();
}
try {
if (broker != null) {
broker.prepare();
broker.pushSubject(securityManager.getSystemSubject());
}
try {
// instruct all database services to stop
servicesManager.stopSystemServices(broker);
} catch(final BrokerPoolServicesManagerException e) {
for(final BrokerPoolServiceException bpse : e.getServiceExceptions()) {
LOG.error(bpse.getMessage(), bpse);
}
}
//TOUNDERSTAND (pb) : shutdown() is called on only *one* broker ?
// WM: yes, the database files are shared, so only one broker is needed to close them for all
broker.shutdown();
} finally {
if(broker != null) {
broker.popSubject();
}
}
collectionCache.invalidateAll();
// final notification to database services to shutdown
servicesManager.shutdown();
// remove all remaining inactive brokers as we have shutdown now and no longer need those
inactiveBrokers.clear();
// deregister JMX MBeans
AgentFactory.getInstance().closeDBInstance(this);
//Clear the living instances container
shutdownInstanceConsumer.accept(instanceName);
synchronized (readOnly) {
if (!readOnly) {
// release the lock on the data directory
dataLock.release();
}
}
//clearing additional resources, like ThreadLocal
clearThreadLocals();
LOG.info("shutdown complete !");
if (shutdownListener != null) {
shutdownListener.shutdown(instanceName, instancesCount());
}
}
} finally {
// clear instance variables, just to be sure they will be garbage collected
// the test suite restarts the db a few hundred times
Configurator.clear(this);
transactionManager = null;
collectionCache = null;
xQueryPool = null;
processMonitor = null;
collectionConfigurationManager = null;
notificationService = null;
indexManager = null;
xmlReaderPool = null;
shutdownListener = null;
securityManager = null;
if (lockManager != null) {
lockManager.getLockTable().shutdown();
lockManager = null;
}
notificationService = null;
statusObservers.clear();
startupTriggersManager = null;
statusReporter.terminate();
statusReporter = null;
// instanceThreadGroup.destroy();
}
} finally {
status.process(Event.FINISHED_SHUTDOWN);
}
}
public void addStatusObserver(final Observer statusObserver) {
this.statusObservers.add(statusObserver);
}
public boolean removeStatusObserver(final Observer statusObserver) {
return this.statusObservers.remove(statusObserver);
}
private void clearThreadLocals() {
for (final Thread thread : Thread.getAllStackTraces().keySet()) {
try {
cleanThreadLocalsForThread(thread);
} catch (final EXistException ex) {
if (LOG.isDebugEnabled()) {
LOG.warn("Could not clear ThreadLocals for thread: {}", thread.getName());
}
}
}
}
private void cleanThreadLocalsForThread(final Thread thread) throws EXistException {
try {
// Get a reference to the thread locals table of the current thread
final Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
threadLocalsField.setAccessible(true);
final Object threadLocalTable = threadLocalsField.get(thread);
// Get a reference to the array holding the thread local variables inside the
// ThreadLocalMap of the current thread
final Class threadLocalMapClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
final Field tableField = threadLocalMapClass.getDeclaredField("table");
tableField.setAccessible(true);
final Object table = tableField.get(threadLocalTable);
// The key to the ThreadLocalMap is a WeakReference object. The referent field of this object
// is a reference to the actual ThreadLocal variable
final Field referentField = Reference.class.getDeclaredField("referent");
referentField.setAccessible(true);
for (int i = 0; i < Array.getLength(table); i++) {
// Each entry in the table array of ThreadLocalMap is an Entry object
// representing the thread local reference and its value
final Object entry = Array.get(table, i);
if (entry != null) {
// Get a reference to the thread local object and remove it from the table
final ThreadLocal threadLocal = (ThreadLocal)referentField.get(entry);
threadLocal.remove();
}
}
} catch(final Exception e) {
// We will tolerate an exception here and just log it
throw new EXistException(e);
}
}
public Optional<BrokerWatchdog> getWatchdog() {
return watchdog;
}
//TODO : move this elsewhere
public void triggerCheckpoint() {
if(syncRequired) {
return;
}
synchronized(this) {
syncEvent = Sync.MAJOR;
syncRequired = true;
checkpoint = true;
}
}
private Debuggee debuggee = null;
public Debuggee getDebuggee() {
synchronized(this) {
if(debuggee == null) {
debuggee = DebuggeeFactory.getInstance();
}
}
return debuggee;
}
public Calendar getStartupTime() {
return startupTime;
}
public void printSystemInfo() {
try(final StringWriter sout = new StringWriter();
final PrintWriter writer = new PrintWriter(sout)) {
writer.println("SYSTEM INFO");
writer.format("Database instance: %s\n", getId());
writer.println("-------------------------------------------------------------------");
watchdog.ifPresent(wd -> wd.dump(writer));
final String s = sout.toString();
LOG.info(s);
System.err.println(s);
} catch(final IOException e) {
LOG.error(e);
}
}
@ThreadSafe
private static class StatusReporter extends Observable implements Runnable {
private String status;
private volatile boolean terminate = false;
public StatusReporter(final String status) {
this.status = status;
}
public synchronized void setStatus(final String status) {
this.status = status;
this.setChanged();
this.notifyObservers(status);
}
public void terminate() {
this.terminate = true;
synchronized(this) {
this.notifyAll();
}
}
@Override
public void run() {
while(!terminate) {
synchronized(this) {
try {
wait(500);
} catch(final InterruptedException e) {
// nothing to do
}
this.setChanged();
this.notifyObservers(status);
}
}
}
}
@Override
public Path getStoragePlace() {
return (Path)conf.getProperty(BrokerPool.PROPERTY_DATA_DIR);
}
private final List<TriggerProxy<? extends DocumentTrigger>> documentTriggers = new ArrayList<>();
private final List<TriggerProxy<? extends CollectionTrigger>> collectionTriggers = new ArrayList<>();
@Override
public List<TriggerProxy<? extends DocumentTrigger>> getDocumentTriggers() {
return documentTriggers;
}
@Override
public List<TriggerProxy<? extends CollectionTrigger>> getCollectionTriggers() {
return collectionTriggers;
}
@Override
public void registerDocumentTrigger(final Class<? extends DocumentTrigger> clazz) {
documentTriggers.add(new DocumentTriggerProxy(clazz));
}
@Override
public void registerCollectionTrigger(final Class<? extends CollectionTrigger> clazz) {
collectionTriggers.add(new CollectionTriggerProxy(clazz));
}
public PluginsManager getPluginsManager() {
return pluginManager;
}
public net.sf.saxon.Configuration getSaxonConfiguration() {
return saxonConfig.get();
}
/**
* Represents a change involving {@link BrokerPool#inactiveBrokers}
* or {@link BrokerPool#activeBrokers} or {@link DBBroker#getReferenceCount}
*
* Used for tracing broker leases
*/
private static class TraceableBrokerLeaseChange extends TraceableStateChange<TraceableBrokerLeaseChange.BrokerInfo, TraceableBrokerLeaseChange.Change> {
public enum Change {
GET,
RELEASE
}
public static class BrokerInfo {
final String id;
final int referenceCount;
public BrokerInfo(final String id, final int referenceCount) {
this.id = id;
this.referenceCount = referenceCount;
}
}
private TraceableBrokerLeaseChange(final Change change, final BrokerInfo brokerInfo) {
super(change, brokerInfo);
}
@Override
public String getId() {
return getState().id;
}
@Override
public String describeState() {
return Integer.toString(getState().referenceCount);
}
static TraceableBrokerLeaseChange get(final BrokerInfo brokerInfo) {
return new TraceableBrokerLeaseChange(Change.GET, brokerInfo);
}
static TraceableBrokerLeaseChange release(final BrokerInfo brokerInfo) {
return new TraceableBrokerLeaseChange(Change.RELEASE, brokerInfo);
}
}
}
| [refactor] At least as many parsers as there are brokers
| exist-core/src/main/java/org/exist/storage/BrokerPool.java | [refactor] At least as many parsers as there are brokers | <ide><path>xist-core/src/main/java/org/exist/storage/BrokerPool.java
<ide> this.processMonitor = servicesManager.register(new ProcessMonitor());
<ide> this.xqueryStats = servicesManager.register(new PerformanceStats(this));
<ide> final XMLReaderObjectFactory xmlReaderObjectFactory = servicesManager.register(new XMLReaderObjectFactory());
<del> this.xmlReaderPool = servicesManager.register(new XMLReaderPool(xmlReaderObjectFactory, 5, 0));
<add> this.xmlReaderPool = servicesManager.register(new XMLReaderPool(xmlReaderObjectFactory, maxBrokers, 0));
<ide> final int bufferSize = Optional.of(conf.getInteger(PROPERTY_COLLECTION_CACHE_SIZE))
<ide> .filter(size -> size != -1)
<ide> .orElse(DEFAULT_COLLECTION_BUFFER_SIZE); |
|
Java | lgpl-2.1 | d8a1646cb0357d3761b2f6869cc7687881ebe8c7 | 0 | nallar/ForgeGradle,matthewprenger/ForgeGradle,kenzierocks/ForgeGradle,PaperMC/PaperGradle | /*
* A Gradle plugin for the creation of Minecraft mods and MinecraftForge plugins.
* Copyright (C) 2013 Minecraft Forge
*
* 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
*/
package net.minecraftforge.gradle.common;
import static net.minecraftforge.gradle.common.Constants.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import net.minecraftforge.gradle.util.json.version.ManifestVersion;
import org.gradle.api.Action;
import org.gradle.api.DefaultTask;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration.State;
import org.gradle.api.artifacts.dsl.DependencyHandler;
import org.gradle.api.artifacts.repositories.FlatDirectoryArtifactRepository;
import org.gradle.api.artifacts.repositories.MavenArtifactRepository;
import org.gradle.api.logging.Logger;
import org.gradle.api.plugins.ExtraPropertiesExtension;
import org.gradle.api.tasks.Delete;
import org.gradle.testfixtures.ProjectBuilder;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import com.google.gson.reflect.TypeToken;
import groovy.lang.Closure;
import net.minecraftforge.gradle.tasks.CrowdinDownload;
import net.minecraftforge.gradle.tasks.Download;
import net.minecraftforge.gradle.tasks.DownloadAssetsTask;
import net.minecraftforge.gradle.tasks.EtagDownloadTask;
import net.minecraftforge.gradle.tasks.ExtractConfigTask;
import net.minecraftforge.gradle.tasks.GenSrgs;
import net.minecraftforge.gradle.tasks.JenkinsChangelog;
import net.minecraftforge.gradle.tasks.MergeJars;
import net.minecraftforge.gradle.tasks.ObtainFernFlowerTask;
import net.minecraftforge.gradle.tasks.SignJar;
import net.minecraftforge.gradle.tasks.SplitJarTask;
import net.minecraftforge.gradle.util.FileLogListenner;
import net.minecraftforge.gradle.util.GradleConfigurationException;
import net.minecraftforge.gradle.util.delayed.DelayedFile;
import net.minecraftforge.gradle.util.delayed.DelayedFileTree;
import net.minecraftforge.gradle.util.delayed.DelayedString;
import net.minecraftforge.gradle.util.delayed.ReplacementProvider;
import net.minecraftforge.gradle.util.delayed.TokenReplacer;
import net.minecraftforge.gradle.util.json.JsonFactory;
import net.minecraftforge.gradle.util.json.fgversion.FGBuildStatus;
import net.minecraftforge.gradle.util.json.fgversion.FGVersion;
import net.minecraftforge.gradle.util.json.fgversion.FGVersionWrapper;
import net.minecraftforge.gradle.util.json.version.Version;
public abstract class BasePlugin<K extends BaseExtension> implements Plugin<Project>
{
public Project project;
public BasePlugin<?> otherPlugin;
public ReplacementProvider replacer = new ReplacementProvider();
private Map<String, ManifestVersion> mcManifest;
private Version mcVersionJson;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public final void apply(Project arg)
{
project = arg;
// check for gradle version
{
List<String> split = Splitter.on('.').splitToList(project.getGradle().getGradleVersion());
int major = Integer.parseInt(split.get(0));
int minor = Integer.parseInt(split.get(1).split("-")[0]);
if (major <= 1 || (major == 2 && minor < 3))
throw new RuntimeException("ForgeGradle 2.0 requires Gradle 2.3 or above.");
}
if (project.getBuildDir().getAbsolutePath().contains("!"))
{
project.getLogger().error("Build path has !, This will screw over a lot of java things as ! is used to denote archive paths, REMOVE IT if you want to continue");
throw new RuntimeException("Build path contains !");
}
// set the obvious replacements
replacer.putReplacement(REPLACE_CACHE_DIR, cacheFile("").getAbsolutePath());
replacer.putReplacement(REPLACE_BUILD_DIR, project.getBuildDir().getAbsolutePath());
// logging
{
File projectCacheDir = project.getGradle().getStartParameter().getProjectCacheDir();
if (projectCacheDir == null)
projectCacheDir = new File(project.getProjectDir(), ".gradle");
replacer.putReplacement(REPLACE_PROJECT_CACHE_DIR, projectCacheDir.getAbsolutePath());
FileLogListenner listener = new FileLogListenner(new File(projectCacheDir, "gradle.log"));
project.getLogging().addStandardOutputListener(listener);
project.getLogging().addStandardErrorListener(listener);
project.getGradle().addBuildListener(listener);
}
// extension objects
{
Type t = getClass().getGenericSuperclass();
while (t instanceof Class)
{
t = ((Class) t).getGenericSuperclass();
}
project.getExtensions().create(EXT_NAME_MC, (Class<K>) ((ParameterizedType) t).getActualTypeArguments()[0], this);
}
// add buildscript usable tasks
{
ExtraPropertiesExtension ext = project.getExtensions().getExtraProperties();
ext.set("SignJar", SignJar.class);
ext.set("Download", Download.class);
ext.set("EtagDownload", EtagDownloadTask.class);
ext.set("CrowdinDownload", CrowdinDownload.class);
ext.set("JenkinsChangelog", JenkinsChangelog.class);
}
// repos
project.allprojects(new Action<Project>() {
public void execute(Project proj)
{
addMavenRepo(proj, "forge", URL_FORGE_MAVEN);
proj.getRepositories().mavenCentral();
addMavenRepo(proj, "minecraft", URL_LIBRARY);
}
});
// do Mcp Snapshots Stuff
getRemoteJsons();
project.getConfigurations().maybeCreate(CONFIG_MCP_DATA);
project.getConfigurations().maybeCreate(CONFIG_MAPPINGS);
// set other useful configs
project.getConfigurations().maybeCreate(CONFIG_MC_DEPS);
project.getConfigurations().maybeCreate(CONFIG_MC_DEPS_CLIENT);
project.getConfigurations().maybeCreate(CONFIG_NATIVES);
// should be assumed until specified otherwise
project.getConfigurations().getByName(CONFIG_MC_DEPS).extendsFrom(project.getConfigurations().getByName(CONFIG_MC_DEPS_CLIENT));
// after eval
project.afterEvaluate(new Action<Project>() {
@Override
public void execute(Project project)
{
// dont continue if its already failed!
if (project.getState().getFailure() != null)
return;
afterEvaluate();
}
});
// some default tasks
makeCommonTasks();
// at last, apply the child plugins
applyPlugin();
}
public abstract void applyPlugin();
private static boolean displayBanner = true;
private void getRemoteJsons()
{
// MCP json
File jsonCache = cacheFile("McpMappings.json");
File etagFile = new File(jsonCache.getAbsolutePath() + ".etag");
getExtension().mcpJson = JsonFactory.GSON.fromJson(getWithEtag(URL_MCP_JSON, jsonCache, etagFile), new TypeToken<Map<String, Map<String, int[]>>>() {}.getType());
// MC manifest json
jsonCache = cacheFile("McManifest.json");
etagFile = new File(jsonCache.getAbsolutePath() + ".etag");
mcManifest = JsonFactory.GSON.fromJson(getWithEtag(URL_MC_MANIFEST, jsonCache, etagFile), new TypeToken<Map<String, ManifestVersion>>() {}.getType());
}
protected void afterEvaluate()
{
// validate MC version
if (Strings.isNullOrEmpty(getExtension().getVersion()))
{
throw new GradleConfigurationException("You must set the Minecraft version!");
}
// http://files.minecraftforge.net/maven/de/oceanlabs/mcp/mcp/1.7.10/mcp-1.7.10-srg.zip
project.getDependencies().add(CONFIG_MAPPINGS, ImmutableMap.of(
"group", "de.oceanlabs.mcp",
"name", delayedString("mcp_" + REPLACE_MCP_CHANNEL).call(),
"version", delayedString(REPLACE_MCP_VERSION + "-" + REPLACE_MC_VERSION).call(),
"ext", "zip"
));
project.getDependencies().add(CONFIG_MCP_DATA, ImmutableMap.of(
"group", "de.oceanlabs.mcp",
"name", "mcp",
"version", delayedString(REPLACE_MC_VERSION).call(),
"classifier", "srg",
"ext", "zip"
));
// Check FG Version, unless its disabled
List<String> lines = Lists.newArrayListWithExpectedSize(5);
Object disableUpdateCheck = project.getProperties().get("net.minecraftforge.gradle.disableUpdateChecker");
if (!"true".equals(disableUpdateCheck) && !"yes".equals(disableUpdateCheck) && !new Boolean(true).equals(disableUpdateCheck))
{
doFGVersionCheck(lines);
}
if (!displayBanner)
return;
Logger logger = this.project.getLogger();
logger.lifecycle("#################################################");
logger.lifecycle(" ForgeGradle {} ", this.getVersionString());
logger.lifecycle(" https://github.com/MinecraftForge/ForgeGradle ");
logger.lifecycle("#################################################");
logger.lifecycle(" Powered by MCP {} ", this.getExtension().getMcpVersion());
logger.lifecycle(" http://modcoderpack.com ");
logger.lifecycle(" by: Searge, ProfMobius, Fesh0r, ");
logger.lifecycle(" R4wk, ZeuX, IngisKahn, bspkrs ");
logger.lifecycle("#################################################");
for (String str : lines)
logger.lifecycle(str);
displayBanner = false;
}
private String getVersionString()
{
String version = this.getClass().getPackage().getImplementationVersion();
if (Strings.isNullOrEmpty(version))
{
version = this.getExtension().forgeGradleVersion + "-unknown";
}
return version;
}
protected void doFGVersionCheck(List<String> outLines)
{
String version = getExtension().forgeGradleVersion;
if (version.endsWith("-SNAPSHOT"))
{
// no version checking necessary if the are on the snapshot already
return;
}
final String checkUrl = "https://www.abrarsyed.com/ForgeGradleVersion.json";
final File jsonCache = cacheFile("ForgeGradleVersion.json");
final File etagFile = new File(jsonCache.getAbsolutePath() + ".etag");
FGVersionWrapper wrapper = JsonFactory.GSON.fromJson(getWithEtag(checkUrl, jsonCache, etagFile), FGVersionWrapper.class);
FGVersion webVersion = wrapper.versionObjects.get(version);
String latestVersion = wrapper.versions.get(wrapper.versions.size()-1);
if (webVersion == null || webVersion.status == FGBuildStatus.FINE)
{
return;
}
// broken implies outdated
if (webVersion.status == FGBuildStatus.BROKEN)
{
outLines.add("ForgeGradle "+webVersion.version+" HAS " + (webVersion.bugs.length > 1 ? "SERIOUS BUGS" : "a SERIOUS BUG") + "!");
outLines.add("UPDATE TO "+latestVersion+" IMMEDIATELY!");
outLines.add(" Bugs:");
for (String str : webVersion.bugs)
{
outLines.add(" -- "+str);
}
outLines.add("****************************");
return;
}
else if (webVersion.status == FGBuildStatus.OUTDATED)
{
outLines.add("ForgeGradle "+latestVersion + " is out! You should update!");
outLines.add(" Features:");
for (int i = webVersion.index; i < wrapper.versions.size(); i++)
{
for (String feature : wrapper.versionObjects.get(wrapper.versions.get(i)).changes)
{
outLines.add(" -- " + feature);
}
}
outLines.add("****************************");
}
onVersionCheck(webVersion, wrapper);
}
/**
* Function to do stuff with the version check json information. Is called afterEvaluate
*
* @param version The ForgeGradle version
* @param wrapper Version wrapper
*/
protected void onVersionCheck(FGVersion version, FGVersionWrapper wrapper)
{
// not required.. but you probably wanan implement this
}
@SuppressWarnings("serial")
private void makeCommonTasks()
{
EtagDownloadTask getVersionJson = makeTask(TASK_DL_VERSION_JSON, EtagDownloadTask.class);
{
getVersionJson.setUrl(new Closure<String>(null, null) {
@Override
public String call()
{
return mcManifest.get(getExtension().getVersion()).url;
}
});
getVersionJson.setFile(delayedFile(JSON_VERSION));
getVersionJson.setDieWithError(false);
getVersionJson.doLast(new Closure<Boolean>(project) // normalizes to linux endings
{
@Override
public Boolean call()
{
try
{
// normalize the line endings...
File json = delayedFile(JSON_VERSION).call();
if (!json.exists())
return true;
List<String> lines = Files.readLines(json, Charsets.UTF_8);
StringBuilder buf = new StringBuilder();
for (String line : lines)
{
buf = buf.append(line).append('\n');
}
Files.write(buf.toString().getBytes(Charsets.UTF_8), json);
// grab the AssetIndex if it isnt already there
if (!replacer.hasReplacement(REPLACE_ASSET_INDEX))
{
parseAndStoreVersion(json, json.getParentFile());
}
}
catch (Throwable t)
{
Throwables.propagate(t);
}
return true;
}
});
}
ExtractConfigTask extractNatives = makeTask(TASK_EXTRACT_NATIVES, ExtractConfigTask.class);
{
extractNatives.setDestinationDir(delayedFile(DIR_NATIVES));
extractNatives.setConfig(CONFIG_NATIVES);
extractNatives.exclude("META-INF/**", "META-INF/**");
extractNatives.setDoesCache(true);
extractNatives.dependsOn(getVersionJson);
}
EtagDownloadTask getAssetsIndex = makeTask(TASK_DL_ASSET_INDEX, EtagDownloadTask.class);
{
getAssetsIndex.setUrl(new Closure<String>(null, null) {
@Override
public String call()
{
return mcVersionJson.assetIndex.url;
}
});
getAssetsIndex.setFile(delayedFile(JSON_ASSET_INDEX));
getAssetsIndex.setDieWithError(false);
getAssetsIndex.dependsOn(getVersionJson);
}
DownloadAssetsTask getAssets = makeTask(TASK_DL_ASSETS, DownloadAssetsTask.class);
{
getAssets.setAssetsDir(delayedFile(DIR_ASSETS));
getAssets.setAssetsIndex(delayedFile(JSON_ASSET_INDEX));
getAssets.dependsOn(getAssetsIndex);
}
Download dlClient = makeTask(TASK_DL_CLIENT, Download.class);
{
dlClient.setOutput(delayedFile(JAR_CLIENT_FRESH));
dlClient.setUrl(new Closure<String>(null, null) {
@Override
public String call()
{
return mcVersionJson.getClientUrl();
}
});
dlClient.dependsOn(getVersionJson);
}
Download dlServer = makeTask(TASK_DL_SERVER, Download.class);
{
dlServer.setOutput(delayedFile(JAR_SERVER_FRESH));
dlServer.setUrl(new Closure<String>(null, null) {
@Override
public String call()
{
return mcVersionJson.getServerUrl();
}
});
dlServer.dependsOn(getVersionJson);
}
SplitJarTask splitServer = makeTask(TASK_SPLIT_SERVER, SplitJarTask.class);
{
splitServer.setInJar(delayedFile(JAR_SERVER_FRESH));
splitServer.setOutFirst(delayedFile(JAR_SERVER_PURE));
splitServer.setOutSecond(delayedFile(JAR_SERVER_DEPS));
splitServer.exclude("org/bouncycastle", "org/bouncycastle/*", "org/bouncycastle/**");
splitServer.exclude("org/apache", "org/apache/*", "org/apache/**");
splitServer.exclude("com/google", "com/google/*", "com/google/**");
splitServer.exclude("com/mojang/authlib", "com/mojang/authlib/*", "com/mojang/authlib/**");
splitServer.exclude("com/mojang/util", "com/mojang/util/*", "com/mojang/util/**");
splitServer.exclude("gnu/trove", "gnu/trove/*", "gnu/trove/**");
splitServer.exclude("io/netty", "io/netty/*", "io/netty/**");
splitServer.exclude("javax/annotation", "javax/annotation/*", "javax/annotation/**");
splitServer.exclude("argo", "argo/*", "argo/**");
splitServer.dependsOn(dlServer);
}
MergeJars merge = makeTask(TASK_MERGE_JARS, MergeJars.class);
{
merge.setClient(delayedFile(JAR_CLIENT_FRESH));
merge.setServer(delayedFile(JAR_SERVER_PURE));
merge.setOutJar(delayedFile(JAR_MERGED));
merge.dependsOn(dlClient, splitServer);
merge.setGroup(null);
merge.setDescription(null);
}
ExtractConfigTask extractMcpData = makeTask(TASK_EXTRACT_MCP, ExtractConfigTask.class);
{
extractMcpData.setDestinationDir(delayedFile(DIR_MCP_DATA));
extractMcpData.setConfig(CONFIG_MCP_DATA);
extractMcpData.setDoesCache(true);
}
ExtractConfigTask extractMcpMappings = makeTask(TASK_EXTRACT_MAPPINGS, ExtractConfigTask.class);
{
extractMcpMappings.setDestinationDir(delayedFile(DIR_MCP_MAPPINGS));
extractMcpMappings.setConfig(CONFIG_MAPPINGS);
extractMcpMappings.setDoesCache(true);
}
GenSrgs genSrgs = makeTask(TASK_GENERATE_SRGS, GenSrgs.class);
{
genSrgs.setInSrg(delayedFile(MCP_DATA_SRG));
genSrgs.setInExc(delayedFile(MCP_DATA_EXC));
genSrgs.setMethodsCsv(delayedFile(CSV_METHOD));
genSrgs.setFieldsCsv(delayedFile(CSV_FIELD));
genSrgs.setNotchToSrg(delayedFile(Constants.SRG_NOTCH_TO_SRG));
genSrgs.setNotchToMcp(delayedFile(Constants.SRG_NOTCH_TO_MCP));
genSrgs.setSrgToMcp(delayedFile(SRG_SRG_TO_MCP));
genSrgs.setMcpToSrg(delayedFile(SRG_MCP_TO_SRG));
genSrgs.setMcpToNotch(delayedFile(SRG_MCP_TO_NOTCH));
genSrgs.setSrgExc(delayedFile(EXC_SRG));
genSrgs.setMcpExc(delayedFile(EXC_MCP));
genSrgs.setDoesCache(true);
genSrgs.dependsOn(extractMcpData, extractMcpMappings);
}
ObtainFernFlowerTask ffTask = makeTask(TASK_DL_FERNFLOWER, ObtainFernFlowerTask.class);
{
ffTask.setMcpUrl(delayedString(URL_FF));
ffTask.setFfJar(delayedFile(JAR_FERNFLOWER));
ffTask.setDoesCache(true);
}
Delete clearCache = makeTask(TASK_CLEAN_CACHE, Delete.class);
{
clearCache.delete(delayedFile(REPLACE_CACHE_DIR), delayedFile(DIR_LOCAL_CACHE));
clearCache.setGroup(GROUP_FG);
clearCache.setDescription("Cleares the ForgeGradle cache. DONT RUN THIS unless you want a fresh start, or the dev tells you to.");
}
}
/**
* @return the extension object with name
* @see Constants#EXT_NAME_MC
*/
@SuppressWarnings("unchecked")
public final K getExtension()
{
return (K) project.getExtensions().getByName(EXT_NAME_MC);
}
public DefaultTask makeTask(String name)
{
return makeTask(name, DefaultTask.class);
}
public DefaultTask maybeMakeTask(String name)
{
return maybeMakeTask(name, DefaultTask.class);
}
public <T extends Task> T makeTask(String name, Class<T> type)
{
return makeTask(project, name, type);
}
public <T extends Task> T maybeMakeTask(String name, Class<T> type)
{
return maybeMakeTask(project, name, type);
}
public static <T extends Task> T maybeMakeTask(Project proj, String name, Class<T> type)
{
return (T) proj.getTasks().maybeCreate(name, type);
}
public static <T extends Task> T makeTask(Project proj, String name, Class<T> type)
{
return (T) proj.getTasks().create(name, type);
}
public static Project buildProject(File buildFile, Project parent)
{
ProjectBuilder builder = ProjectBuilder.builder();
if (buildFile != null)
{
builder = builder.withProjectDir(buildFile.getParentFile()).withName(buildFile.getParentFile().getName());
}
else
{
builder = builder.withProjectDir(new File("."));
}
if (parent != null)
{
builder = builder.withParent(parent);
}
Project project = builder.build();
if (buildFile != null)
{
project.apply(ImmutableMap.of("from", buildFile.getAbsolutePath()));
}
return project;
}
public void applyExternalPlugin(String plugin)
{
project.apply(ImmutableMap.of("plugin", plugin));
}
public MavenArtifactRepository addMavenRepo(Project proj, final String name, final String url)
{
return proj.getRepositories().maven(new Action<MavenArtifactRepository>() {
@Override
public void execute(MavenArtifactRepository repo)
{
repo.setName(name);
repo.setUrl(url);
}
});
}
public FlatDirectoryArtifactRepository addFlatRepo(Project proj, final String name, final Object... dirs)
{
return proj.getRepositories().flatDir(new Action<FlatDirectoryArtifactRepository>() {
@Override
public void execute(FlatDirectoryArtifactRepository repo)
{
repo.setName(name);
repo.dirs(dirs);
}
});
}
protected String getWithEtag(String strUrl, File cache, File etagFile)
{
try
{
if (project.getGradle().getStartParameter().isOffline()) // dont even try the internet
return Files.toString(cache, Charsets.UTF_8);
// dude, its been less than 1 minute since the last time..
if (cache.exists() && cache.lastModified() + 60000 >= System.currentTimeMillis())
return Files.toString(cache, Charsets.UTF_8);
String etag;
if (etagFile.exists())
{
etag = Files.toString(etagFile, Charsets.UTF_8);
}
else
{
etagFile.getParentFile().mkdirs();
etag = "";
}
URL url = new URL(strUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setInstanceFollowRedirects(true);
con.setRequestProperty("User-Agent", USER_AGENT);
con.setIfModifiedSince(cache.lastModified());
if (!Strings.isNullOrEmpty(etag))
{
con.setRequestProperty("If-None-Match", etag);
}
con.connect();
String out = null;
if (con.getResponseCode() == 304)
{
// the existing file is good
Files.touch(cache); // touch it to update last-modified time, to wait another minute
out = Files.toString(cache, Charsets.UTF_8);
}
else if (con.getResponseCode() == 200)
{
InputStream stream = con.getInputStream();
byte[] data = ByteStreams.toByteArray(stream);
Files.write(data, cache);
stream.close();
// write etag
etag = con.getHeaderField("ETag");
if (Strings.isNullOrEmpty(etag))
{
Files.touch(etagFile);
}
else
{
Files.write(etag, etagFile, Charsets.UTF_8);
}
out = new String(data);
}
else
{
project.getLogger().error("Etag download for " + strUrl + " failed with code " + con.getResponseCode());
}
con.disconnect();
return out;
}
catch (Exception e)
{
e.printStackTrace();
}
if (cache.exists())
{
try
{
return Files.toString(cache, Charsets.UTF_8);
}
catch (IOException e)
{
Throwables.propagate(e);
}
}
throw new RuntimeException("Unable to obtain url (" + strUrl + ") with etag!");
}
/**
* Parses the version json in the provided file, and saves it in memory.
* Also populates the McDeps and natives configurations.
* Also sets the ASSET_INDEX replacement string
* Does nothing (returns null) if the file is not found, but hard-crashes if it could not be parsed.
* @param file version file to parse
* @param inheritanceDirs folders to look for the parent json, should include DIR_JSON
* @return NULL if the file doesnt exist
*/
protected Version parseAndStoreVersion(File file, File... inheritanceDirs)
{
if (!file.exists())
return null;
Version version = null;
if (version == null)
{
try
{
version = JsonFactory.loadVersion(file, delayedString(REPLACE_MC_VERSION).call(), inheritanceDirs);
}
catch (Exception e)
{
project.getLogger().error("" + file + " could not be parsed");
Throwables.propagate(e);
}
}
// apply the dep info.
DependencyHandler handler = project.getDependencies();
// actual dependencies
if (project.getConfigurations().getByName(CONFIG_MC_DEPS).getState() == State.UNRESOLVED)
{
for (net.minecraftforge.gradle.util.json.version.Library lib : version.getLibraries())
{
if (lib.natives == null)
{
String configName = CONFIG_MC_DEPS;
if (lib.name.contains("java3d")
|| lib.name.contains("paulscode")
|| lib.name.contains("lwjgl")
|| lib.name.contains("twitch")
|| lib.name.contains("jinput"))
{
configName = CONFIG_MC_DEPS_CLIENT;
}
handler.add(configName, lib.getArtifactName());
}
}
}
else
project.getLogger().debug("RESOLVED: " + CONFIG_MC_DEPS);
// the natives
if (project.getConfigurations().getByName(CONFIG_NATIVES).getState() == State.UNRESOLVED)
{
for (net.minecraftforge.gradle.util.json.version.Library lib : version.getLibraries())
{
if (lib.natives != null)
handler.add(CONFIG_NATIVES, lib.getArtifactName());
}
}
else
project.getLogger().debug("RESOLVED: " + CONFIG_NATIVES);
// set asset index
replacer.putReplacement(REPLACE_ASSET_INDEX, version.assetIndex.id);
this.mcVersionJson = version;
return version;
}
// DELAYED STUFF ONLY ------------------------------------------------------------------------
private LoadingCache<String, TokenReplacer> replacerCache = CacheBuilder.newBuilder()
.weakValues()
.build(
new CacheLoader<String, TokenReplacer>() {
public TokenReplacer load(String key)
{
return new TokenReplacer(replacer, key);
}
});
private LoadingCache<String, DelayedString> stringCache = CacheBuilder.newBuilder()
.weakValues()
.build(
new CacheLoader<String, DelayedString>() {
public DelayedString load(String key)
{
return new DelayedString(replacerCache.getUnchecked(key));
}
});
private LoadingCache<String, DelayedFile> fileCache = CacheBuilder.newBuilder()
.weakValues()
.build(
new CacheLoader<String, DelayedFile>() {
public DelayedFile load(String key)
{
return new DelayedFile(project, replacerCache.getUnchecked(key));
}
});
public DelayedString delayedString(String path)
{
return stringCache.getUnchecked(path);
}
public DelayedFile delayedFile(String path)
{
return fileCache.getUnchecked(path);
}
public DelayedFileTree delayedTree(String path)
{
return new DelayedFileTree(project, replacerCache.getUnchecked(path));
}
protected File cacheFile(String path)
{
return new File(project.getGradle().getGradleUserHomeDir(), "caches/minecraft/" + path);
}
}
| src/main/java/net/minecraftforge/gradle/common/BasePlugin.java | /*
* A Gradle plugin for the creation of Minecraft mods and MinecraftForge plugins.
* Copyright (C) 2013 Minecraft Forge
*
* 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
*/
package net.minecraftforge.gradle.common;
import static net.minecraftforge.gradle.common.Constants.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import net.minecraftforge.gradle.util.json.version.ManifestVersion;
import org.gradle.api.Action;
import org.gradle.api.DefaultTask;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration.State;
import org.gradle.api.artifacts.dsl.DependencyHandler;
import org.gradle.api.artifacts.repositories.FlatDirectoryArtifactRepository;
import org.gradle.api.artifacts.repositories.MavenArtifactRepository;
import org.gradle.api.logging.Logger;
import org.gradle.api.plugins.ExtraPropertiesExtension;
import org.gradle.api.tasks.Delete;
import org.gradle.testfixtures.ProjectBuilder;
import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import com.google.gson.reflect.TypeToken;
import groovy.lang.Closure;
import net.minecraftforge.gradle.tasks.CrowdinDownload;
import net.minecraftforge.gradle.tasks.Download;
import net.minecraftforge.gradle.tasks.DownloadAssetsTask;
import net.minecraftforge.gradle.tasks.EtagDownloadTask;
import net.minecraftforge.gradle.tasks.ExtractConfigTask;
import net.minecraftforge.gradle.tasks.GenSrgs;
import net.minecraftforge.gradle.tasks.JenkinsChangelog;
import net.minecraftforge.gradle.tasks.MergeJars;
import net.minecraftforge.gradle.tasks.ObtainFernFlowerTask;
import net.minecraftforge.gradle.tasks.SignJar;
import net.minecraftforge.gradle.tasks.SplitJarTask;
import net.minecraftforge.gradle.util.FileLogListenner;
import net.minecraftforge.gradle.util.GradleConfigurationException;
import net.minecraftforge.gradle.util.delayed.DelayedFile;
import net.minecraftforge.gradle.util.delayed.DelayedFileTree;
import net.minecraftforge.gradle.util.delayed.DelayedString;
import net.minecraftforge.gradle.util.delayed.ReplacementProvider;
import net.minecraftforge.gradle.util.delayed.TokenReplacer;
import net.minecraftforge.gradle.util.json.JsonFactory;
import net.minecraftforge.gradle.util.json.fgversion.FGBuildStatus;
import net.minecraftforge.gradle.util.json.fgversion.FGVersion;
import net.minecraftforge.gradle.util.json.fgversion.FGVersionWrapper;
import net.minecraftforge.gradle.util.json.version.Version;
public abstract class BasePlugin<K extends BaseExtension> implements Plugin<Project>
{
public Project project;
public BasePlugin<?> otherPlugin;
public ReplacementProvider replacer = new ReplacementProvider();
private Map<String, ManifestVersion> mcManifest;
private Version mcVersionJson;
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public final void apply(Project arg)
{
project = arg;
// check for gradle version
{
List<String> split = Splitter.on('.').splitToList(project.getGradle().getGradleVersion());
int major = Integer.parseInt(split.get(0));
int minor = Integer.parseInt(split.get(1).split("-")[0]);
if (major <= 1 || (major == 2 && minor < 3))
throw new RuntimeException("ForgeGradle 2.0 requires Gradle 2.3 or above.");
}
if (project.getBuildDir().getAbsolutePath().contains("!"))
{
project.getLogger().error("Build path has !, This will screw over a lot of java things as ! is used to denote archive paths, REMOVE IT if you want to continue");
throw new RuntimeException("Build path contains !");
}
// set the obvious replacements
replacer.putReplacement(REPLACE_CACHE_DIR, cacheFile("").getAbsolutePath());
replacer.putReplacement(REPLACE_BUILD_DIR, project.getBuildDir().getAbsolutePath());
// logging
{
File projectCacheDir = project.getGradle().getStartParameter().getProjectCacheDir();
if (projectCacheDir == null)
projectCacheDir = new File(project.getProjectDir(), ".gradle");
replacer.putReplacement(REPLACE_PROJECT_CACHE_DIR, projectCacheDir.getAbsolutePath());
FileLogListenner listener = new FileLogListenner(new File(projectCacheDir, "gradle.log"));
project.getLogging().addStandardOutputListener(listener);
project.getLogging().addStandardErrorListener(listener);
project.getGradle().addBuildListener(listener);
}
// extension objects
{
Type t = getClass().getGenericSuperclass();
while (t instanceof Class)
{
t = ((Class) t).getGenericSuperclass();
}
project.getExtensions().create(EXT_NAME_MC, (Class<K>) ((ParameterizedType) t).getActualTypeArguments()[0], this);
}
// add buildscript usable tasks
{
ExtraPropertiesExtension ext = project.getExtensions().getExtraProperties();
ext.set("SignJar", SignJar.class);
ext.set("Download", Download.class);
ext.set("EtagDownload", EtagDownloadTask.class);
ext.set("CrowdinDownload", CrowdinDownload.class);
ext.set("JenkinsChangelog", JenkinsChangelog.class);
}
// repos
project.allprojects(new Action<Project>() {
public void execute(Project proj)
{
addMavenRepo(proj, "forge", URL_FORGE_MAVEN);
proj.getRepositories().mavenCentral();
addMavenRepo(proj, "minecraft", URL_LIBRARY);
}
});
// do Mcp Snapshots Stuff
getRemoteJsons();
project.getConfigurations().maybeCreate(CONFIG_MCP_DATA);
project.getConfigurations().maybeCreate(CONFIG_MAPPINGS);
// set other useful configs
project.getConfigurations().maybeCreate(CONFIG_MC_DEPS);
project.getConfigurations().maybeCreate(CONFIG_MC_DEPS_CLIENT);
project.getConfigurations().maybeCreate(CONFIG_NATIVES);
// should be assumed until specified otherwise
project.getConfigurations().getByName(CONFIG_MC_DEPS).extendsFrom(project.getConfigurations().getByName(CONFIG_MC_DEPS_CLIENT));
// after eval
project.afterEvaluate(new Action<Project>() {
@Override
public void execute(Project project)
{
// dont continue if its already failed!
if (project.getState().getFailure() != null)
return;
afterEvaluate();
}
});
// some default tasks
makeCommonTasks();
// at last, apply the child plugins
applyPlugin();
}
public abstract void applyPlugin();
private static boolean displayBanner = true;
private void getRemoteJsons()
{
// MCP json
File jsonCache = cacheFile("McpMappings.json");
File etagFile = new File(jsonCache.getAbsolutePath() + ".etag");
getExtension().mcpJson = JsonFactory.GSON.fromJson(getWithEtag(URL_MCP_JSON, jsonCache, etagFile), new TypeToken<Map<String, Map<String, int[]>>>() {}.getType());
// MC manifest json
jsonCache = cacheFile("McManifest.json");
etagFile = new File(jsonCache.getAbsolutePath() + ".etag");
mcManifest = JsonFactory.GSON.fromJson(getWithEtag(URL_MC_MANIFEST, jsonCache, etagFile), new TypeToken<Map<String, ManifestVersion>>() {}.getType());
}
protected void afterEvaluate()
{
// validate MC version
if (Strings.isNullOrEmpty(getExtension().getVersion()))
{
throw new GradleConfigurationException("You must set the Minecraft version!");
}
// http://files.minecraftforge.net/maven/de/oceanlabs/mcp/mcp/1.7.10/mcp-1.7.10-srg.zip
project.getDependencies().add(CONFIG_MAPPINGS, ImmutableMap.of(
"group", "de.oceanlabs.mcp",
"name", delayedString("mcp_" + REPLACE_MCP_CHANNEL).call(),
"version", delayedString(REPLACE_MCP_VERSION + "-" + REPLACE_MC_VERSION).call(),
"ext", "zip"
));
project.getDependencies().add(CONFIG_MCP_DATA, ImmutableMap.of(
"group", "de.oceanlabs.mcp",
"name", "mcp",
"version", delayedString(REPLACE_MC_VERSION).call(),
"classifier", "srg",
"ext", "zip"
));
// Check FG Version, unless its disabled
List<String> lines = Lists.newArrayListWithExpectedSize(5);
Object disableUpdateCheck = project.getProperties().get("net.minecraftforge.gradle.disableUpdateChecker");
if (!"true".equals(disableUpdateCheck) && !"yes".equals(disableUpdateCheck) && !new Boolean(true).equals(disableUpdateCheck))
{
doFGVersionCheck(lines);
}
if (!displayBanner)
return;
Logger logger = this.project.getLogger();
logger.lifecycle("#################################################");
logger.lifecycle(" ForgeGradle {} ", this.getVersionString());
logger.lifecycle(" https://github.com/MinecraftForge/ForgeGradle ");
logger.lifecycle("#################################################");
logger.lifecycle(" Powered by MCP {} ", this.getExtension().getMcpVersion());
logger.lifecycle(" http://modcoderpack.com ");
logger.lifecycle(" by: Searge, ProfMobius, Fesh0r, ");
logger.lifecycle(" R4wk, ZeuX, IngisKahn, bspkrs ");
logger.lifecycle("#################################################");
for (String str : lines)
logger.lifecycle(str);
displayBanner = false;
}
private String getVersionString()
{
String version = this.getClass().getPackage().getImplementationVersion();
if (Strings.isNullOrEmpty(version))
{
version = this.getExtension().forgeGradleVersion + "-unknown";
}
return version;
}
protected void doFGVersionCheck(List<String> outLines)
{
String version = getExtension().forgeGradleVersion;
if (version.endsWith("-SNAPSHOT"))
{
// no version checking necessary if the are on the snapshot already
return;
}
final String checkUrl = "https://www.abrarsyed.com/ForgeGradleVersion.json";
final File jsonCache = cacheFile("ForgeGradleVersion.json");
final File etagFile = new File(jsonCache.getAbsolutePath() + ".etag");
FGVersionWrapper wrapper = JsonFactory.GSON.fromJson(getWithEtag(checkUrl, jsonCache, etagFile), FGVersionWrapper.class);
FGVersion webVersion = wrapper.versionObjects.get(version);
String latestVersion = wrapper.versions.get(wrapper.versions.size()-1);
if (webVersion == null || webVersion.status == FGBuildStatus.FINE)
{
return;
}
// broken implies outdated
if (webVersion.status == FGBuildStatus.BROKEN)
{
outLines.add("ForgeGradle "+webVersion.version+" HAS " + (webVersion.bugs.length > 1 ? "SERIOUS BUGS" : "a SERIOUS BUG") + "!");
outLines.add("UPDATE TO "+latestVersion+" IMMEDIATELY!");
outLines.add(" Bugs:");
for (String str : webVersion.bugs)
{
outLines.add(" -- "+str);
}
outLines.add("****************************");
return;
}
else if (webVersion.status == FGBuildStatus.OUTDATED)
{
outLines.add("ForgeGradle "+latestVersion + " is out! You should update!");
outLines.add(" Features:");
for (int i = webVersion.index; i < wrapper.versions.size(); i++)
{
for (String feature : wrapper.versionObjects.get(wrapper.versions.get(i)).changes)
{
outLines.add(" -- " + feature);
}
}
outLines.add("****************************");
}
onVersionCheck(webVersion, wrapper);
}
/**
* Function to do stuff with the version check json information. Is called afterEvaluate
*
* @param version The ForgeGradle version
* @param wrapper Version wrapper
*/
protected void onVersionCheck(FGVersion version, FGVersionWrapper wrapper)
{
// not required.. but you probably wanan implement this
}
@SuppressWarnings("serial")
private void makeCommonTasks()
{
Download dlClient = makeTask(TASK_DL_CLIENT, Download.class);
{
dlClient.setOutput(delayedFile(JAR_CLIENT_FRESH));
dlClient.setUrl(new Closure<String>(null, null) {
@Override
public String call()
{
return mcVersionJson.getClientUrl();
}
});
}
Download dlServer = makeTask(TASK_DL_SERVER, Download.class);
{
dlServer.setOutput(delayedFile(JAR_SERVER_FRESH));
dlServer.setUrl(new Closure<String>(null, null) {
@Override
public String call()
{
return mcVersionJson.getServerUrl();
}
});
}
SplitJarTask splitServer = makeTask(TASK_SPLIT_SERVER, SplitJarTask.class);
{
splitServer.setInJar(delayedFile(JAR_SERVER_FRESH));
splitServer.setOutFirst(delayedFile(JAR_SERVER_PURE));
splitServer.setOutSecond(delayedFile(JAR_SERVER_DEPS));
splitServer.exclude("org/bouncycastle", "org/bouncycastle/*", "org/bouncycastle/**");
splitServer.exclude("org/apache", "org/apache/*", "org/apache/**");
splitServer.exclude("com/google", "com/google/*", "com/google/**");
splitServer.exclude("com/mojang/authlib", "com/mojang/authlib/*", "com/mojang/authlib/**");
splitServer.exclude("com/mojang/util", "com/mojang/util/*", "com/mojang/util/**");
splitServer.exclude("gnu/trove", "gnu/trove/*", "gnu/trove/**");
splitServer.exclude("io/netty", "io/netty/*", "io/netty/**");
splitServer.exclude("javax/annotation", "javax/annotation/*", "javax/annotation/**");
splitServer.exclude("argo", "argo/*", "argo/**");
splitServer.dependsOn(dlServer);
}
MergeJars merge = makeTask(TASK_MERGE_JARS, MergeJars.class);
{
merge.setClient(delayedFile(JAR_CLIENT_FRESH));
merge.setServer(delayedFile(JAR_SERVER_PURE));
merge.setOutJar(delayedFile(JAR_MERGED));
merge.dependsOn(dlClient, splitServer);
merge.setGroup(null);
merge.setDescription(null);
}
EtagDownloadTask getVersionJson = makeTask(TASK_DL_VERSION_JSON, EtagDownloadTask.class);
{
getVersionJson.setUrl(new Closure<String>(null, null) {
@Override
public String call()
{
return mcManifest.get(getExtension().getVersion()).url;
}
});
getVersionJson.setFile(delayedFile(JSON_VERSION));
getVersionJson.setDieWithError(false);
getVersionJson.doLast(new Closure<Boolean>(project) // normalizes to linux endings
{
@Override
public Boolean call()
{
try
{
// normalize the line endings...
File json = delayedFile(JSON_VERSION).call();
if (!json.exists())
return true;
List<String> lines = Files.readLines(json, Charsets.UTF_8);
StringBuilder buf = new StringBuilder();
for (String line : lines)
{
buf = buf.append(line).append('\n');
}
Files.write(buf.toString().getBytes(Charsets.UTF_8), json);
// grab the AssetIndex if it isnt already there
if (!replacer.hasReplacement(REPLACE_ASSET_INDEX))
{
parseAndStoreVersion(json, json.getParentFile());
}
}
catch (Throwable t)
{
Throwables.propagate(t);
}
return true;
}
});
}
ExtractConfigTask extractNatives = makeTask(TASK_EXTRACT_NATIVES, ExtractConfigTask.class);
{
extractNatives.setDestinationDir(delayedFile(DIR_NATIVES));
extractNatives.setConfig(CONFIG_NATIVES);
extractNatives.exclude("META-INF/**", "META-INF/**");
extractNatives.setDoesCache(true);
extractNatives.dependsOn(getVersionJson);
}
EtagDownloadTask getAssetsIndex = makeTask(TASK_DL_ASSET_INDEX, EtagDownloadTask.class);
{
getAssetsIndex.setUrl(new Closure<String>(null, null) {
@Override
public String call()
{
return mcVersionJson.assetIndex.url;
}
});
getAssetsIndex.setFile(delayedFile(JSON_ASSET_INDEX));
getAssetsIndex.setDieWithError(false);
getAssetsIndex.dependsOn(getVersionJson);
}
DownloadAssetsTask getAssets = makeTask(TASK_DL_ASSETS, DownloadAssetsTask.class);
{
getAssets.setAssetsDir(delayedFile(DIR_ASSETS));
getAssets.setAssetsIndex(delayedFile(JSON_ASSET_INDEX));
getAssets.dependsOn(getAssetsIndex);
}
ExtractConfigTask extractMcpData = makeTask(TASK_EXTRACT_MCP, ExtractConfigTask.class);
{
extractMcpData.setDestinationDir(delayedFile(DIR_MCP_DATA));
extractMcpData.setConfig(CONFIG_MCP_DATA);
extractMcpData.setDoesCache(true);
}
ExtractConfigTask extractMcpMappings = makeTask(TASK_EXTRACT_MAPPINGS, ExtractConfigTask.class);
{
extractMcpMappings.setDestinationDir(delayedFile(DIR_MCP_MAPPINGS));
extractMcpMappings.setConfig(CONFIG_MAPPINGS);
extractMcpMappings.setDoesCache(true);
}
GenSrgs genSrgs = makeTask(TASK_GENERATE_SRGS, GenSrgs.class);
{
genSrgs.setInSrg(delayedFile(MCP_DATA_SRG));
genSrgs.setInExc(delayedFile(MCP_DATA_EXC));
genSrgs.setMethodsCsv(delayedFile(CSV_METHOD));
genSrgs.setFieldsCsv(delayedFile(CSV_FIELD));
genSrgs.setNotchToSrg(delayedFile(Constants.SRG_NOTCH_TO_SRG));
genSrgs.setNotchToMcp(delayedFile(Constants.SRG_NOTCH_TO_MCP));
genSrgs.setSrgToMcp(delayedFile(SRG_SRG_TO_MCP));
genSrgs.setMcpToSrg(delayedFile(SRG_MCP_TO_SRG));
genSrgs.setMcpToNotch(delayedFile(SRG_MCP_TO_NOTCH));
genSrgs.setSrgExc(delayedFile(EXC_SRG));
genSrgs.setMcpExc(delayedFile(EXC_MCP));
genSrgs.setDoesCache(true);
genSrgs.dependsOn(extractMcpData, extractMcpMappings);
}
ObtainFernFlowerTask ffTask = makeTask(TASK_DL_FERNFLOWER, ObtainFernFlowerTask.class);
{
ffTask.setMcpUrl(delayedString(URL_FF));
ffTask.setFfJar(delayedFile(JAR_FERNFLOWER));
ffTask.setDoesCache(true);
}
Delete clearCache = makeTask(TASK_CLEAN_CACHE, Delete.class);
{
clearCache.delete(delayedFile(REPLACE_CACHE_DIR), delayedFile(DIR_LOCAL_CACHE));
clearCache.setGroup(GROUP_FG);
clearCache.setDescription("Cleares the ForgeGradle cache. DONT RUN THIS unless you want a fresh start, or the dev tells you to.");
}
}
/**
* @return the extension object with name
* @see Constants#EXT_NAME_MC
*/
@SuppressWarnings("unchecked")
public final K getExtension()
{
return (K) project.getExtensions().getByName(EXT_NAME_MC);
}
public DefaultTask makeTask(String name)
{
return makeTask(name, DefaultTask.class);
}
public DefaultTask maybeMakeTask(String name)
{
return maybeMakeTask(name, DefaultTask.class);
}
public <T extends Task> T makeTask(String name, Class<T> type)
{
return makeTask(project, name, type);
}
public <T extends Task> T maybeMakeTask(String name, Class<T> type)
{
return maybeMakeTask(project, name, type);
}
public static <T extends Task> T maybeMakeTask(Project proj, String name, Class<T> type)
{
return (T) proj.getTasks().maybeCreate(name, type);
}
public static <T extends Task> T makeTask(Project proj, String name, Class<T> type)
{
return (T) proj.getTasks().create(name, type);
}
public static Project buildProject(File buildFile, Project parent)
{
ProjectBuilder builder = ProjectBuilder.builder();
if (buildFile != null)
{
builder = builder.withProjectDir(buildFile.getParentFile()).withName(buildFile.getParentFile().getName());
}
else
{
builder = builder.withProjectDir(new File("."));
}
if (parent != null)
{
builder = builder.withParent(parent);
}
Project project = builder.build();
if (buildFile != null)
{
project.apply(ImmutableMap.of("from", buildFile.getAbsolutePath()));
}
return project;
}
public void applyExternalPlugin(String plugin)
{
project.apply(ImmutableMap.of("plugin", plugin));
}
public MavenArtifactRepository addMavenRepo(Project proj, final String name, final String url)
{
return proj.getRepositories().maven(new Action<MavenArtifactRepository>() {
@Override
public void execute(MavenArtifactRepository repo)
{
repo.setName(name);
repo.setUrl(url);
}
});
}
public FlatDirectoryArtifactRepository addFlatRepo(Project proj, final String name, final Object... dirs)
{
return proj.getRepositories().flatDir(new Action<FlatDirectoryArtifactRepository>() {
@Override
public void execute(FlatDirectoryArtifactRepository repo)
{
repo.setName(name);
repo.dirs(dirs);
}
});
}
protected String getWithEtag(String strUrl, File cache, File etagFile)
{
try
{
if (project.getGradle().getStartParameter().isOffline()) // dont even try the internet
return Files.toString(cache, Charsets.UTF_8);
// dude, its been less than 1 minute since the last time..
if (cache.exists() && cache.lastModified() + 60000 >= System.currentTimeMillis())
return Files.toString(cache, Charsets.UTF_8);
String etag;
if (etagFile.exists())
{
etag = Files.toString(etagFile, Charsets.UTF_8);
}
else
{
etagFile.getParentFile().mkdirs();
etag = "";
}
URL url = new URL(strUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setInstanceFollowRedirects(true);
con.setRequestProperty("User-Agent", USER_AGENT);
con.setIfModifiedSince(cache.lastModified());
if (!Strings.isNullOrEmpty(etag))
{
con.setRequestProperty("If-None-Match", etag);
}
con.connect();
String out = null;
if (con.getResponseCode() == 304)
{
// the existing file is good
Files.touch(cache); // touch it to update last-modified time, to wait another minute
out = Files.toString(cache, Charsets.UTF_8);
}
else if (con.getResponseCode() == 200)
{
InputStream stream = con.getInputStream();
byte[] data = ByteStreams.toByteArray(stream);
Files.write(data, cache);
stream.close();
// write etag
etag = con.getHeaderField("ETag");
if (Strings.isNullOrEmpty(etag))
{
Files.touch(etagFile);
}
else
{
Files.write(etag, etagFile, Charsets.UTF_8);
}
out = new String(data);
}
else
{
project.getLogger().error("Etag download for " + strUrl + " failed with code " + con.getResponseCode());
}
con.disconnect();
return out;
}
catch (Exception e)
{
e.printStackTrace();
}
if (cache.exists())
{
try
{
return Files.toString(cache, Charsets.UTF_8);
}
catch (IOException e)
{
Throwables.propagate(e);
}
}
throw new RuntimeException("Unable to obtain url (" + strUrl + ") with etag!");
}
/**
* Parses the version json in the provided file, and saves it in memory.
* Also populates the McDeps and natives configurations.
* Also sets the ASSET_INDEX replacement string
* Does nothing (returns null) if the file is not found, but hard-crashes if it could not be parsed.
* @param file version file to parse
* @param inheritanceDirs folders to look for the parent json, should include DIR_JSON
* @return NULL if the file doesnt exist
*/
protected Version parseAndStoreVersion(File file, File... inheritanceDirs)
{
if (!file.exists())
return null;
Version version = null;
if (version == null)
{
try
{
version = JsonFactory.loadVersion(file, delayedString(REPLACE_MC_VERSION).call(), inheritanceDirs);
}
catch (Exception e)
{
project.getLogger().error("" + file + " could not be parsed");
Throwables.propagate(e);
}
}
// apply the dep info.
DependencyHandler handler = project.getDependencies();
// actual dependencies
if (project.getConfigurations().getByName(CONFIG_MC_DEPS).getState() == State.UNRESOLVED)
{
for (net.minecraftforge.gradle.util.json.version.Library lib : version.getLibraries())
{
if (lib.natives == null)
{
String configName = CONFIG_MC_DEPS;
if (lib.name.contains("java3d")
|| lib.name.contains("paulscode")
|| lib.name.contains("lwjgl")
|| lib.name.contains("twitch")
|| lib.name.contains("jinput"))
{
configName = CONFIG_MC_DEPS_CLIENT;
}
handler.add(configName, lib.getArtifactName());
}
}
}
else
project.getLogger().debug("RESOLVED: " + CONFIG_MC_DEPS);
// the natives
if (project.getConfigurations().getByName(CONFIG_NATIVES).getState() == State.UNRESOLVED)
{
for (net.minecraftforge.gradle.util.json.version.Library lib : version.getLibraries())
{
if (lib.natives != null)
handler.add(CONFIG_NATIVES, lib.getArtifactName());
}
}
else
project.getLogger().debug("RESOLVED: " + CONFIG_NATIVES);
// set asset index
replacer.putReplacement(REPLACE_ASSET_INDEX, version.assetIndex.id);
this.mcVersionJson = version;
return version;
}
// DELAYED STUFF ONLY ------------------------------------------------------------------------
private LoadingCache<String, TokenReplacer> replacerCache = CacheBuilder.newBuilder()
.weakValues()
.build(
new CacheLoader<String, TokenReplacer>() {
public TokenReplacer load(String key)
{
return new TokenReplacer(replacer, key);
}
});
private LoadingCache<String, DelayedString> stringCache = CacheBuilder.newBuilder()
.weakValues()
.build(
new CacheLoader<String, DelayedString>() {
public DelayedString load(String key)
{
return new DelayedString(replacerCache.getUnchecked(key));
}
});
private LoadingCache<String, DelayedFile> fileCache = CacheBuilder.newBuilder()
.weakValues()
.build(
new CacheLoader<String, DelayedFile>() {
public DelayedFile load(String key)
{
return new DelayedFile(project, replacerCache.getUnchecked(key));
}
});
public DelayedString delayedString(String path)
{
return stringCache.getUnchecked(path);
}
public DelayedFile delayedFile(String path)
{
return fileCache.getUnchecked(path);
}
public DelayedFileTree delayedTree(String path)
{
return new DelayedFileTree(project, replacerCache.getUnchecked(path));
}
protected File cacheFile(String path)
{
return new File(project.getGradle().getGradleUserHomeDir(), "caches/minecraft/" + path);
}
}
| fixed NPE when downloading MC jars
| src/main/java/net/minecraftforge/gradle/common/BasePlugin.java | fixed NPE when downloading MC jars | <ide><path>rc/main/java/net/minecraftforge/gradle/common/BasePlugin.java
<ide> @SuppressWarnings("serial")
<ide> private void makeCommonTasks()
<ide> {
<del> Download dlClient = makeTask(TASK_DL_CLIENT, Download.class);
<del> {
<del> dlClient.setOutput(delayedFile(JAR_CLIENT_FRESH));
<del> dlClient.setUrl(new Closure<String>(null, null) {
<del> @Override
<del> public String call()
<del> {
<del> return mcVersionJson.getClientUrl();
<del> }
<del> });
<del> }
<del>
<del> Download dlServer = makeTask(TASK_DL_SERVER, Download.class);
<del> {
<del> dlServer.setOutput(delayedFile(JAR_SERVER_FRESH));
<del> dlServer.setUrl(new Closure<String>(null, null) {
<del> @Override
<del> public String call()
<del> {
<del> return mcVersionJson.getServerUrl();
<del> }
<del> });
<del> }
<del>
<del> SplitJarTask splitServer = makeTask(TASK_SPLIT_SERVER, SplitJarTask.class);
<del> {
<del> splitServer.setInJar(delayedFile(JAR_SERVER_FRESH));
<del> splitServer.setOutFirst(delayedFile(JAR_SERVER_PURE));
<del> splitServer.setOutSecond(delayedFile(JAR_SERVER_DEPS));
<del>
<del> splitServer.exclude("org/bouncycastle", "org/bouncycastle/*", "org/bouncycastle/**");
<del> splitServer.exclude("org/apache", "org/apache/*", "org/apache/**");
<del> splitServer.exclude("com/google", "com/google/*", "com/google/**");
<del> splitServer.exclude("com/mojang/authlib", "com/mojang/authlib/*", "com/mojang/authlib/**");
<del> splitServer.exclude("com/mojang/util", "com/mojang/util/*", "com/mojang/util/**");
<del> splitServer.exclude("gnu/trove", "gnu/trove/*", "gnu/trove/**");
<del> splitServer.exclude("io/netty", "io/netty/*", "io/netty/**");
<del> splitServer.exclude("javax/annotation", "javax/annotation/*", "javax/annotation/**");
<del> splitServer.exclude("argo", "argo/*", "argo/**");
<del>
<del> splitServer.dependsOn(dlServer);
<del> }
<del>
<del> MergeJars merge = makeTask(TASK_MERGE_JARS, MergeJars.class);
<del> {
<del> merge.setClient(delayedFile(JAR_CLIENT_FRESH));
<del> merge.setServer(delayedFile(JAR_SERVER_PURE));
<del> merge.setOutJar(delayedFile(JAR_MERGED));
<del> merge.dependsOn(dlClient, splitServer);
<del>
<del> merge.setGroup(null);
<del> merge.setDescription(null);
<del> }
<del>
<ide> EtagDownloadTask getVersionJson = makeTask(TASK_DL_VERSION_JSON, EtagDownloadTask.class);
<ide> {
<ide> getVersionJson.setUrl(new Closure<String>(null, null) {
<ide> getAssets.setAssetsDir(delayedFile(DIR_ASSETS));
<ide> getAssets.setAssetsIndex(delayedFile(JSON_ASSET_INDEX));
<ide> getAssets.dependsOn(getAssetsIndex);
<add> }
<add>
<add> Download dlClient = makeTask(TASK_DL_CLIENT, Download.class);
<add> {
<add> dlClient.setOutput(delayedFile(JAR_CLIENT_FRESH));
<add> dlClient.setUrl(new Closure<String>(null, null) {
<add> @Override
<add> public String call()
<add> {
<add> return mcVersionJson.getClientUrl();
<add> }
<add> });
<add>
<add> dlClient.dependsOn(getVersionJson);
<add> }
<add>
<add> Download dlServer = makeTask(TASK_DL_SERVER, Download.class);
<add> {
<add> dlServer.setOutput(delayedFile(JAR_SERVER_FRESH));
<add> dlServer.setUrl(new Closure<String>(null, null) {
<add> @Override
<add> public String call()
<add> {
<add> return mcVersionJson.getServerUrl();
<add> }
<add> });
<add>
<add> dlServer.dependsOn(getVersionJson);
<add> }
<add>
<add> SplitJarTask splitServer = makeTask(TASK_SPLIT_SERVER, SplitJarTask.class);
<add> {
<add> splitServer.setInJar(delayedFile(JAR_SERVER_FRESH));
<add> splitServer.setOutFirst(delayedFile(JAR_SERVER_PURE));
<add> splitServer.setOutSecond(delayedFile(JAR_SERVER_DEPS));
<add>
<add> splitServer.exclude("org/bouncycastle", "org/bouncycastle/*", "org/bouncycastle/**");
<add> splitServer.exclude("org/apache", "org/apache/*", "org/apache/**");
<add> splitServer.exclude("com/google", "com/google/*", "com/google/**");
<add> splitServer.exclude("com/mojang/authlib", "com/mojang/authlib/*", "com/mojang/authlib/**");
<add> splitServer.exclude("com/mojang/util", "com/mojang/util/*", "com/mojang/util/**");
<add> splitServer.exclude("gnu/trove", "gnu/trove/*", "gnu/trove/**");
<add> splitServer.exclude("io/netty", "io/netty/*", "io/netty/**");
<add> splitServer.exclude("javax/annotation", "javax/annotation/*", "javax/annotation/**");
<add> splitServer.exclude("argo", "argo/*", "argo/**");
<add>
<add> splitServer.dependsOn(dlServer);
<add> }
<add>
<add> MergeJars merge = makeTask(TASK_MERGE_JARS, MergeJars.class);
<add> {
<add> merge.setClient(delayedFile(JAR_CLIENT_FRESH));
<add> merge.setServer(delayedFile(JAR_SERVER_PURE));
<add> merge.setOutJar(delayedFile(JAR_MERGED));
<add> merge.dependsOn(dlClient, splitServer);
<add>
<add> merge.setGroup(null);
<add> merge.setDescription(null);
<ide> }
<ide>
<ide> ExtractConfigTask extractMcpData = makeTask(TASK_EXTRACT_MCP, ExtractConfigTask.class); |
|
Java | mpl-2.0 | e8bb799d529de5baacb5a81682f611c8c5c4bad2 | 0 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core | /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ScShapeObj.java,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2005-11-02 18:07:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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 mod._sc;
import java.io.PrintWriter;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
import util.DefaultDsc;
import util.DrawTools;
import util.InstCreator;
import util.SOfficeFactory;
import util.utils;
import com.sun.star.beans.XPropertySet;
import com.sun.star.drawing.XShape;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.style.XStyle;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
public class ScShapeObj extends TestCase {
static XComponent xSheetDoc;
protected void initialize( TestParameters tParam, PrintWriter log ) {
SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF() );
try {
log.println( "creating a sheetdoc" );
xSheetDoc = (XComponent) UnoRuntime.queryInterface(XComponent.class, SOF.createCalcDoc(null));
} catch ( com.sun.star.uno.Exception e ) {
// Some exception occures.FAILED
e.printStackTrace( log );
throw new StatusException( "Couldn't create document", e );
}
}
protected void cleanup( TestParameters tParam, PrintWriter log ) {
log.println( " disposing xSheetDoc " );
util.DesktopTools.closeDoc(xSheetDoc);
}
/**
* Creating a Testenvironment for the interfaces to be tested.
* Creates an instance of the service
* <code>com.sun.star.drawing.EllipseShape</code> as tested component
* and adds it to the document.
* Object relations created :
* <ul>
* <li> <code>'Style1', 'Style2'</code> for
* {@link ifc.drawing._Shape} :
* two values of 'Style' property. The first is taken
* from the shape tested, the second from another
* shape added to the draw page. </li>
* <li> <code>'XTEXTINFO'</code> for
* {@link ifc.text._XText} :
* creator which can create instnaces of
* <code>com.sun.star.text.TextField.URL</code>
* service. </li>
* </ul>
*/
protected TestEnvironment createTestEnvironment
(TestParameters tParam, PrintWriter log) {
XInterface oObj = null;
XShape oShape = null;
// creation of testobject here
// first we write what we are intend to do to log file
log.println( "creating a test environment" );
SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF());
oShape = SOF.createShape(xSheetDoc,5000, 3500, 7500, 5000,"Rectangle");
DrawTools.getShapes(DrawTools.getDrawPage(xSheetDoc,0)).add(oShape);
oObj = oShape ;
for (int i=0; i < 10; i++) {
DrawTools.getShapes(DrawTools.getDrawPage(xSheetDoc,0)).add(
SOF.createShape(xSheetDoc,
5000, 3500, 7510 + 10 * i, 5010 + 10 * i, "Rectangle"));
}
// create test environment here
TestEnvironment tEnv = new TestEnvironment( oShape );
log.println("Implementation name: "+util.utils.getImplName(oObj));
tEnv.addObjRelation("DOCUMENT",xSheetDoc);
return tEnv;
} // finish method getTestEnvironment
} // finish class ScShapeObj
| qadevOOo/tests/java/mod/_sc/ScShapeObj.java | /*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ScShapeObj.java,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:59:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* 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 mod._sc;
import java.io.PrintWriter;
import lib.StatusException;
import lib.TestCase;
import lib.TestEnvironment;
import lib.TestParameters;
import util.DefaultDsc;
import util.DrawTools;
import util.InstCreator;
import util.SOfficeFactory;
import util.utils;
import com.sun.star.beans.XPropertySet;
import com.sun.star.drawing.XShape;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.style.XStyle;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XInterface;
public class ScShapeObj extends TestCase {
XComponent xSheetDoc;
protected void initialize( TestParameters tParam, PrintWriter log ) {
SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF() );
try {
log.println( "creating a sheetdoc" );
xSheetDoc = (XComponent) UnoRuntime.queryInterface(XComponent.class, SOF.createCalcDoc(null));
} catch ( com.sun.star.uno.Exception e ) {
// Some exception occures.FAILED
e.printStackTrace( log );
throw new StatusException( "Couldn't create document", e );
}
}
protected void cleanup( TestParameters tParam, PrintWriter log ) {
log.println( " disposing xSheetDoc " );
util.DesktopTools.closeDoc(xSheetDoc);
}
/**
* Creating a Testenvironment for the interfaces to be tested.
* Creates an instance of the service
* <code>com.sun.star.drawing.EllipseShape</code> as tested component
* and adds it to the document.
* Object relations created :
* <ul>
* <li> <code>'Style1', 'Style2'</code> for
* {@link ifc.drawing._Shape} :
* two values of 'Style' property. The first is taken
* from the shape tested, the second from another
* shape added to the draw page. </li>
* <li> <code>'XTEXTINFO'</code> for
* {@link ifc.text._XText} :
* creator which can create instnaces of
* <code>com.sun.star.text.TextField.URL</code>
* service. </li>
* </ul>
*/
protected TestEnvironment createTestEnvironment
(TestParameters tParam, PrintWriter log) {
XInterface oObj = null;
XShape oShape = null;
// creation of testobject here
// first we write what we are intend to do to log file
log.println( "creating a test environment" );
SOfficeFactory SOF = SOfficeFactory.getFactory( (XMultiServiceFactory)tParam.getMSF());
oShape = SOF.createShape(xSheetDoc,5000, 3500, 7500, 5000,"Rectangle");
DrawTools.getShapes(DrawTools.getDrawPage(xSheetDoc,0)).add(oShape);
oObj = oShape ;
for (int i=0; i < 10; i++) {
DrawTools.getShapes(DrawTools.getDrawPage(xSheetDoc,0)).add(
SOF.createShape(xSheetDoc,
5000, 3500, 7510 + 10 * i, 5010 + 10 * i, "Rectangle"));
}
// create test environment here
TestEnvironment tEnv = new TestEnvironment( oShape );
log.println("Implementation name: "+util.utils.getImplName(oObj));
tEnv.addObjRelation("DOCUMENT",xSheetDoc);
return tEnv;
} // finish method getTestEnvironment
} // finish class ScShapeObj
| INTEGRATION: CWS qadev24 (1.2.72); FILE MERGED
2005/09/19 15:14:13 cn 1.2.72.2: RESYNC: (1.2-1.3); FILE MERGED
2005/09/13 07:58:26 cn 1.2.72.1: #i54533# define class variables for documents as 'static'
| qadevOOo/tests/java/mod/_sc/ScShapeObj.java | INTEGRATION: CWS qadev24 (1.2.72); FILE MERGED 2005/09/19 15:14:13 cn 1.2.72.2: RESYNC: (1.2-1.3); FILE MERGED 2005/09/13 07:58:26 cn 1.2.72.1: #i54533# define class variables for documents as 'static' | <ide><path>adevOOo/tests/java/mod/_sc/ScShapeObj.java
<ide> *
<ide> * $RCSfile: ScShapeObj.java,v $
<ide> *
<del> * $Revision: 1.3 $
<add> * $Revision: 1.4 $
<ide> *
<del> * last change: $Author: rt $ $Date: 2005-09-09 02:59:51 $
<add> * last change: $Author: kz $ $Date: 2005-11-02 18:07:34 $
<ide> *
<ide> * The Contents of this file are made available subject to
<ide> * the terms of GNU Lesser General Public License Version 2.1.
<ide>
<ide> public class ScShapeObj extends TestCase {
<ide>
<del> XComponent xSheetDoc;
<add> static XComponent xSheetDoc;
<ide>
<ide> protected void initialize( TestParameters tParam, PrintWriter log ) {
<ide> |
|
Java | mit | 11bf781e8e204c485f4cef371bfc5da902def6e4 | 0 | peichhorn/tinyaudioplayer | package de.fips.plugin.tinyaudioplayer.audio;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import java.io.File;
import java.net.URI;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
public class PlaylistAudioPlayerTest {
private IPlaybackListener playbackListener;
private Playlist playlist;
private URI location;
private PlaylistAudioPlayer player;
private SingleTrackAudioPlayer internalPlayer;
@Before
public void setup() {
// setup
playbackListener = mock(IPlaybackListener.class);
playlist = spy(new Playlist());
location = new File("Track 01.mp3").toURI();
playlist.add(new PlaylistItem("Track 01", location, 220));
player = spy(new PlaylistAudioPlayer(playlist));
internalPlayer = mock(SingleTrackAudioPlayer.class);
player.setPlaybackHandler(playbackListener);
doReturn(internalPlayer).when(player).createInternalPlayer(any(URI.class), anyFloat(), anyBoolean());
}
@Test
public void whenInternalPlayerIsNotRunning_play_shouldCreateNewInternalPlayerWithCurrentTrack() {
// run
player.play();
// assert
verify(player).createInternalPlayer(eq(location), anyFloat(), anyBoolean());
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
}
@Test
public void whenInternalPlayerIsRunning_play_shouldStopRunningInternalPlayerAndCreateNewInternalPlayer() {
// run
player.play();
player.play();
// assert
verify(player, times(2)).createInternalPlayer(eq(location), anyFloat(), anyBoolean());
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
inorder.verify(internalPlayer).stop();
inorder.verify(internalPlayer).removePlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
}
@Test
public void whenInternalPlayerIsPaused_play_shouldContinuePlaying() {
// run
player.play();
player.pause();
doReturn(true).when(internalPlayer).isPaused();
player.play();
// assert
verify(player).createInternalPlayer(eq(location), anyFloat(), anyBoolean());
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
inorder.verify(internalPlayer).pause();
inorder.verify(internalPlayer).play();
}
@Test
public void whenInternalPlayerIsNotRunning_stop_shouldDoNothing() {
// run
player.stop();
// assert
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer, never()).removePlaybackListener(any(IPlaybackListener.class));
inorder.verify(internalPlayer, never()).stop();
}
@Test
public void whenInternalPlayerIsPaused_pause_shouldContinuePlaying() {
// run
player.play();
player.pause();
doReturn(true).when(internalPlayer).isPaused();
player.pause();
// assert
verify(player).createInternalPlayer(eq(location), anyFloat(), anyBoolean());
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
inorder.verify(internalPlayer).pause();
inorder.verify(internalPlayer).play();
}
@Test
public void whenInternalPlayerIsNotRunning_previous_shouldJustChangeToThePreviousTrack() {
// run
player.previous();
// assert
verify(playlist).previous();
}
@Test
public void whenInternalPlayerIsRunning_previous_shouldStopRunningInternalPlayerAndPlayPreviousTrack() {
// run
player.play();
player.previous();
// assert
verify(player, times(2)).createInternalPlayer(eq(location), anyFloat(), anyBoolean());
verify(playlist).previous();
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
inorder.verify(internalPlayer).stop();
inorder.verify(internalPlayer).removePlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
}
@Test
public void whenInternalPlayerIsNotRunning_next_shouldJustChangeToTheNextTrack() {
// run
player.next();
// assert
verify(playlist).next();
}
@Test
public void whenInternalPlayerIsRunning_next_shouldStopRunningInternalPlayerAndPlayNextTrack() {
// run
player.play();
player.next();
// assert
verify(player, times(2)).createInternalPlayer(eq(location), anyFloat(), anyBoolean());
verify(playlist).next();
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
inorder.verify(internalPlayer).stop();
inorder.verify(internalPlayer).removePlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
}
@Test
public void testToggleShuffle() {
// run
player.toggleShuffle();
// assert
verify(playlist).toggleShuffle();
}
@Test
public void testToggleRepeat() {
// run
player.toggleRepeat();
// assert
verify(playlist).toggleRepeat();
}
}
| test/main/de/fips/plugin/tinyaudioplayer/audio/PlaylistAudioPlayerTest.java | package de.fips.plugin.tinyaudioplayer.audio;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import java.io.File;
import java.net.URI;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
public class PlaylistAudioPlayerTest {
private IPlaybackListener playbackListener;
private Playlist playlist;
private URI location;
private PlaylistAudioPlayer player;
private SingleTrackAudioPlayer internalPlayer;
@Before
public void setup() {
// setup
playbackListener = mock(IPlaybackListener.class);
playlist = spy(new Playlist());
location = new File("Track 01.mp3").toURI();
playlist.add(new PlaylistItem("Track 01", location, 220));
player = spy(new PlaylistAudioPlayer(playlist));
internalPlayer = mock(SingleTrackAudioPlayer.class);
player.setPlaybackHandler(playbackListener);
doReturn(internalPlayer).when(player).createInternalPlayer(any(URI.class), anyFloat(), anyBoolean());
}
@Test
public void whenInternalPlayerIsNotRunning_play_shouldCreateNewInternalPlayerWithCurrentTrack() {
// run
player.play();
// assert
verify(player).createInternalPlayer(eq(location), anyFloat(), anyBoolean());
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
}
@Test
public void whenInternalPlayerIsRunning_play_shouldStopRunningInternalPlayerAndCreateNewInternalPlayer() {
// run
player.play();
player.play();
// assert
verify(player, times(2)).createInternalPlayer(eq(location), anyFloat(), anyBoolean());
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
inorder.verify(internalPlayer).stop();
inorder.verify(internalPlayer).removePlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
}
@Test
public void whenInternalPlayerIsPaused_play_shouldContinuePlaying() {
// run
player.play();
player.pause();
doReturn(true).when(internalPlayer).isPaused();
player.play();
// assert
verify(player).createInternalPlayer(eq(location), anyFloat(), anyBoolean());
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
inorder.verify(internalPlayer).pause();
inorder.verify(internalPlayer).play();
}
@Test
public void whenInternalPlayerIsNotRunning_stop_shouldDoNothing() {
// run
player.stop();
// assert
verify(internalPlayer, never()).removePlaybackListener(any(IPlaybackListener.class));
verify(internalPlayer, never()).stop();
}
@Test
public void whenInternalPlayerIsPaused_pause_shouldContinuePlaying() {
// run
player.play();
player.pause();
doReturn(true).when(internalPlayer).isPaused();
player.pause();
// assert
verify(player).createInternalPlayer(eq(location), anyFloat(), anyBoolean());
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
inorder.verify(internalPlayer).pause();
inorder.verify(internalPlayer).play();
}
@Test
public void whenInternalPlayerIsNotRunning_previous_shouldJustChangeToThePreviousTrack() {
// run
player.previous();
// assert
verify(playlist).previous();
}
@Test
public void whenInternalPlayerIsRunning_previous_shouldStopRunningInternalPlayerAndPlayPreviousTrack() {
// run
player.play();
player.previous();
// assert
verify(player, times(2)).createInternalPlayer(eq(location), anyFloat(), anyBoolean());
verify(playlist).previous();
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
inorder.verify(internalPlayer).stop();
inorder.verify(internalPlayer).removePlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
}
@Test
public void whenInternalPlayerIsNotRunning_next_shouldJustChangeToTheNextTrack() {
// run
player.next();
// assert
verify(playlist).next();
}
@Test
public void whenInternalPlayerIsRunning_next_shouldStopRunningInternalPlayerAndPlayNextTrack() {
// run
player.play();
player.next();
// assert
verify(player, times(2)).createInternalPlayer(eq(location), anyFloat(), anyBoolean());
verify(playlist).next();
final InOrder inorder = inOrder(internalPlayer);
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
inorder.verify(internalPlayer).stop();
inorder.verify(internalPlayer).removePlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).addPlaybackListener(eq(playbackListener));
inorder.verify(internalPlayer).play();
}
@Test
public void testToggleShuffle() {
// run
player.toggleShuffle();
// assert
verify(playlist).toggleShuffle();
}
@Test
public void testToggleRepeat() {
// run
player.toggleRepeat();
// assert
verify(playlist).toggleRepeat();
}
}
| cleanup
| test/main/de/fips/plugin/tinyaudioplayer/audio/PlaylistAudioPlayerTest.java | cleanup | <ide><path>est/main/de/fips/plugin/tinyaudioplayer/audio/PlaylistAudioPlayerTest.java
<ide> // run
<ide> player.stop();
<ide> // assert
<del> verify(internalPlayer, never()).removePlaybackListener(any(IPlaybackListener.class));
<del> verify(internalPlayer, never()).stop();
<add> final InOrder inorder = inOrder(internalPlayer);
<add> inorder.verify(internalPlayer, never()).removePlaybackListener(any(IPlaybackListener.class));
<add> inorder.verify(internalPlayer, never()).stop();
<ide> }
<ide>
<ide> @Test |
|
JavaScript | mit | 7104664a309e26d47cb9535db8e70583754f9374 | 0 | remko/ampersand-view,AmpersandJS/ampersand-view | var test = require('tape');
var AmpersandModel = require('ampersand-model');
var AmpersandCollection = require('ampersand-rest-collection');
var AmpersandView = require('../ampersand-view');
var contains = function (str1, str2) {
return str1.indexOf(str2) !== -1;
};
var Model = AmpersandModel.extend({
props: {
id: 'number',
name: ['string', true],
html: 'string',
url: 'string',
something: 'string',
fireDanger: 'string'
},
session: {
active: 'boolean'
},
derived: {
classes: {
deps: ['something', 'fireDanger', 'active'],
fn: function () {
return this.something + this.active;
}
}
}
});
function getView(bindings, model) {
if (!bindings.template) {
bindings.template = '<li><span></span><img></li>';
}
var View = AmpersandView.extend(bindings);
var view = new View({
model: model || new Model()
});
return view.renderWithTemplate();
}
test('event behavior with over-ridden `render` & `remove` fns', function (t) {
var renderCount = 0;
var removeCount = 0;
t.plan(7);
var ChildView = AmpersandView.extend({
render: function() {
AmpersandView.prototype.render.call(this);
t.ok(true, 'child view render called');
}
});
var GrandChildView = AmpersandView.extend({
render: function() {
ChildView.prototype.render.call(this);
t.ok(true, 'grand child view render called');
}
});
var detachedEl = document.createElement('div');
var view = new GrandChildView({
template: '<span></span>',
el: detachedEl
});
view.on('render', function(view, value) {
++renderCount;
t.ok(true, 'view `render` event happened on `render()`');
});
view.on('remove', function(view, value) {
++removeCount;
});
view.render();
t.equal(removeCount, 0, '`remove` event not called, pre- or post- render()');
t.equal(renderCount, 1, '`render` triggered exactly once, post- render()');
view.remove();
t.equal(removeCount, 1, '`remove` triggered exactly once, post- remove()');
t.equal(renderCount, 1, '`render` not triggered, post- remove()');
t.end();
});
test('standard `rendered` attr behavior', function (t) {
var caughtRenderEvt = false;
var detachedEl = document.createElement('div');
var view = new AmpersandView({
template: '<span></span>',
el: detachedEl
});
view.on('change:rendered', function() {
caughtRenderEvt = !caughtRenderEvt;
});
t.notOk(view.rendered, 'view not `rendered` prior to `render()` call');
view.render();
t.ok(view.rendered, 'view `rendered` post `render()` call');
t.ok(caughtRenderEvt, 'view `rendered` evt observed on `render()` call');
view.remove();
t.notOk(caughtRenderEvt, 'view `rendered` evt observed on `remove()` call');
t.notOk(view.rendered, 'view not `rendered` post `remove()` call');
t.end();
});
test('user over-ridden `render()` and `remove()` behavior', function (t) {
var view;
var RenderTestView = AmpersandView.extend({
template: '<span></span>',
render: function() {
t.ok(true, 'user defined `render()` executed');
},
remove: function() {
t.ok(true, 'user defined `remove()` executed');
}
});
t.plan(4);
view = new RenderTestView();
view.on('change:rendered', function() {
t.ok(true, '`rendered` triggered on custom render/remove');
});
view.render();
view.remove();
t.end();
});
test('Model, collection, and el become properties', function (t) {
var model = new Model();
var collection = new AmpersandCollection();
var el = document.createElement('div');
var view = new AmpersandView({
model: model,
collection: collection,
el: el
});
t.equal(view.model, model);
t.equal(view.collection, collection);
t.equal(view.el, el);
t.end();
});
test('registerSubview', function (t) {
var removeCalled = 0;
var SubView = AmpersandView.extend({
template: '<div></div>',
render: function () {
this.renderWithTemplate();
this.el.className = 'subview';
},
remove: function () {
removeCalled++;
}
});
var View = AmpersandView.extend({
template: '<section><div id="parent"></div></section>',
render: function () {
this.renderWithTemplate();
// all of these should work
this.renderSubview(new SubView(), this.query('#parent'));
this.renderSubview(new SubView(), '#parent');
// some other thing with a remove method
this.registerSubview({remove: function () {
removeCalled++;
}});
}
});
var main = new View({
el: document.createElement('div')
});
main.render();
t.equal(main.queryAll('.subview').length, 2);
main.remove();
t.equal(removeCalled, 3);
t.end();
});
test('registerSubview: default container to this.el', function (t) {
var removeCalled = 0;
var SubView = AmpersandView.extend({
template: '<div></div>',
render: function () {
this.renderWithTemplate();
this.el.className = 'subview';
},
remove: function () {
removeCalled++;
}
});
var View = AmpersandView.extend({
template: '<section></section>',
render: function () {
this.renderWithTemplate();
this.renderSubview(new SubView());
this.renderSubview(new SubView());
}
});
var main = new View({
el: document.createElement('div')
});
main.render();
t.equal(main.queryAll('.subview').length, 2);
t.equal(main.el.childNodes.length, 2);
main.remove();
t.equal(removeCalled, 2);
t.end();
});
test('caching elements', function(t) {
var View = AmpersandView.extend({
template: '<p><span></span></p>',
render: function () {
this.renderWithTemplate();
return this.cacheElements(({span:'span'}));
}
});
var instance = new View(),
rendered = instance.render();
t.equal(instance, rendered);
t.equal(typeof rendered.span, 'object');
t.end();
});
test('listen to and run', function (t) {
t.plan(1);
var model = new Model({
props: {
name: 'string'
}
});
var View = AmpersandView.extend({
initialize: function () {
this.model = model;
this.listenToAndRun(this.model, 'something', this.handler);
t.end();
},
handler: function () {
t.pass('handler ran');
}
});
new View();
});
test('text bindings', function (t) {
var view = getView({
bindings: {
'model.name': 'span'
}
});
t.equal(view.query('span').textContent, '');
view.model.set('name', 'henrik');
t.equal(view.query('span').textContent, 'henrik');
t.end();
});
test('src bindings', function (t) {
var view = getView({
bindings: {
'model.url': {
type: 'attribute',
name: 'src',
selector: 'img'
}
}
});
var img = view.query('img');
t.equal(img.getAttribute('src'), '');
view.model.set('url', 'http://robohash.com/whammo');
t.equal(img.getAttribute('src'), 'http://robohash.com/whammo');
t.end();
});
test('href bindings', function (t) {
var view = getView({
template: '<a href=""></a>',
bindings: {
'model.url': {
type: 'attribute',
name: 'href',
selector: ''
}
}
});
var el = view.el;
t.equal(el.getAttribute('href'), '');
view.model.set('url', 'http://robohash.com/whammo');
t.equal(el.getAttribute('href'), 'http://robohash.com/whammo');
t.end();
});
test('input bindings', function (t) {
var view = getView({
template: '<li><input></li>',
bindings: {
'model.something': {
type: 'attribute',
selector: 'input',
name: 'value'
}
}
});
var input = view.query('input');
t.equal(input.value, '');
view.model.set('something', 'yo');
t.equal(input.value, 'yo');
t.end();
});
test('class bindings', function (t) {
var model = new Model();
model.set({
fireDanger: 'high',
active: true
});
var view = getView({
template: '<li></li>',
bindings: {
'model.fireDanger': {
type: 'class'
},
'model.active': {
type: 'booleanClass'
}
}
}, model);
var className = view.el.className;
t.ok(contains(className, 'active'));
t.ok(contains(className, 'high'));
model.set('fireDanger', 'low');
className = view.el.className;
t.ok(!contains(className, 'high'));
t.ok(contains(className, 'low'));
model.set('active', false);
className = view.el.className;
t.ok(!contains(className, 'active'));
t.ok(contains(className, 'low'));
t.end();
});
test('nested binding definitions', function (t) {
var model = new Model();
model.set({
active: true
});
var View = AmpersandView.extend({
autoRender: true,
template: '<li><div></div></li>',
bindings: {
'model.active': [
{
type: 'booleanAttribute',
name: 'data-active',
selector: 'div'
},
{
type: 'booleanAttribute',
name: 'data-something',
selector: 'div'
},
{
selector: 'div'
},
{
type: 'booleanClass'
}
]
}
});
var view = new View({model: model});
var li = view.el;
var div = li.firstChild;
t.ok(div.hasAttribute('data-active'));
t.ok(div.hasAttribute('data-something'));
t.equal(div.textContent, 'true');
t.ok(contains(li.className, 'active'));
t.end();
});
test('renderAndBind with no model', function (t) {
var View = AmpersandView.extend({
template: '<li><span></span><img></li>'
});
var view = new View();
t.ok(view.renderWithTemplate()); //Should not throw error
t.end();
});
test('queryByHook', function (t) {
var View = AmpersandView.extend({
template: '<li data-hook="list-item"><span data-hook="username"></span><img data-hook="user-avatar"></li>'
});
var view = new View();
view.renderWithTemplate();
t.ok(view.queryByHook('username') instanceof Element, 'should find username element');
t.ok(view.queryByHook('user-avatar') instanceof Element, 'should find username');
t.ok(view.queryByHook('nothing') === undefined, 'should find username');
t.ok(view.queryByHook('list-item') instanceof Element, 'should also work for root element');
t.end();
});
test('queryAllByHook', function (t) {
var View = AmpersandView.extend({
template: '<li data-hook="list-item"><span data-hook="username info"></span><img data-hook="user-avatar info"></li>'
});
var view = new View();
view.renderWithTemplate();
t.ok(view.queryAllByHook('info') instanceof Array, 'should return array of results');
t.equal(view.queryAllByHook('info').length, 2, 'should find all relevant elements');
t.ok(view.queryAllByHook('info')[0] instanceof Element, 'should be able to access found elements');
t.ok(view.queryAllByHook('info')[1] instanceof Element, 'should be able to access found elements');
t.deepEqual(view.queryAllByHook('nothing'), [], 'should return empty array if no results found');
t.end();
});
test('throw on multiple root elements', function (t) {
var View = AmpersandView.extend({
template: '<li></li><div></div>'
});
var view = new View();
t.throws(view.renderWithTemplate, Error, 'Throws error on multiple root elements');
t.end();
});
test('queryAll should return an array', function (t) {
var View = AmpersandView.extend({
autoRender: true,
template: '<ul><li></li><li></li><li></li></ul>'
});
var view = new View();
var all = view.queryAll('li');
t.ok(all instanceof Array);
t.ok(all.forEach);
t.equal(all.length, 3);
t.end();
});
test('get should return undefined if no match', function (t) {
var View = AmpersandView.extend({
autoRender: true,
template: '<ul></ul>'
});
var view = new View();
var el = view.query('div');
t.equal(typeof el, 'undefined');
t.strictEqual(view.query(''), view.el);
t.strictEqual(view.query(), view.el);
t.strictEqual(view.query(view.el), view.el);
t.end();
});
test('get should work for root element too', function (t) {
var View = AmpersandView.extend({
autoRender: true,
template: '<ul></ul>'
});
var view = new View();
t.equal(view.query('ul'), view.el);
t.end();
});
test('queryAll should include root element if matches', function (t) {
var View = AmpersandView.extend({
autoRender: true,
template: '<div class="test"><div class="test deep"><div class="test deep"></div></div></div>'
});
var view = new View();
var hasTestClass = view.queryAll('.test');
var hasDeepClass = view.queryAll('.deep');
t.equal(hasTestClass.length, 3);
t.equal(hasDeepClass.length, 2);
t.ok(hasTestClass instanceof Array);
t.ok(hasDeepClass instanceof Array);
t.ok(view.queryAll('bogus') instanceof Array);
t.end();
});
test('query should throw an error if view was not rendered', function (t) {
var View = AmpersandView.extend({
autoRender: false,
template: '<div class="test"><div class="test deep"><div class="test deep"></div></div></div>'
});
var view = new View();
t.throws((function () {
view.query('.test');
}), Error, 'Throws error on query with selector');
t.throws((function () {
view.query('');
}), Error, 'Throws error on query with empty selector');
t.end();
});
test('query should not throw an error if view was rendered', function (t) {
var View = AmpersandView.extend({
autoRender: false,
template: '<div class="test"><div class="test deep"><div class="test deep"></div></div></div>'
});
var view = new View();
view.render();
t.doesNotThrow((function () {
view.query('.test');
}), Error, 'Does not throws error on query');
t.doesNotThrow((function () {
view.query('');
}), Error, 'Does not throws error on empty selector');
t.end();
});
test('queryAll should throw an error if view was not rendered', function (t) {
var View = AmpersandView.extend({
autoRender: false,
template: '<div class="test"><div class="test deep"><div class="test deep"></div></div></div>'
});
var view = new View();
t.throws((function () {
view.queryAll('div');
}), Error, 'Throws error on queryAll');
t.throws((function () {
view.queryAll('');
}), Error, 'Throws error on queryAll with empty selector');
t.end();
});
test('queryAll should not throw an error if view was rendered', function (t) {
var View = AmpersandView.extend({
autoRender: false,
template: '<div class="test"><div class="test deep"><div class="test deep"></div></div></div>'
});
var view = new View();
view.render();
t.doesNotThrow((function () {
view.queryAll('div');
}), Error, 'Does not throw error on queryAll');
t.doesNotThrow((function () {
view.queryAll('');
}), Error, 'Does not throw error on queryAll with empty selector');
t.end();
});
//test('focus/blur events should work in events hash. Issue #8', function (t) {
// t.plan(2);
// var View = AmpersandView.extend({
// events: {
// 'focus #thing': 'handleFocus',
// 'blur #thing': 'handleBlur'
// },
// autoRender: true,
// template: '<div><input id="thing"></div></div>',
// handleFocus: function () {
// t.pass('focus called');
// },
// handleBlur: function () {
// t.pass('blur called');
// t.end();
// }
// });
// var view = new View();
// // should be able to do this without
// // ending up with too many handlers
// view.delegateEvents();
// view.delegateEvents();
// view.delegateEvents();
//
// document.body.appendChild(view.el);
// view.el.firstChild.focus();
// view.el.firstChild.blur();
// document.body.removeChild(view.el);
//});
test('ability to mix in state properties', function (t) {
var View = AmpersandView.extend({
template: '<div></div>',
render: function () {
this.el = document.createElement('div');
}
});
var view = new View();
view.on('change:el', function () {
t.pass('woohoo!');
t.end();
});
view.render();
});
test('Ability to add other state properties', function (t) {
var View = AmpersandView.extend({
props: {
thing: 'boolean'
},
template: '<div></div>'
});
var view = new View();
view.on('change:thing', function () {
t.pass('woohoo!');
t.end();
});
view.thing = true;
});
test('Multi-inheritance of state properties works too', function (t) {
t.plan(2);
var View = AmpersandView.extend({
props: {
thing: 'boolean'
},
template: '<div></div>'
});
var SecondView = View.extend({
props: {
otherThing: 'boolean'
}
});
var view = window.view = new SecondView();
view.on('change:thing', function () {
t.pass('woohoo!');
});
view.on('change:otherThing', function () {
t.pass('woohoo!');
t.end();
});
view.thing = true;
view.otherThing = true;
});
test('Setting an `el` should only fire change if new instance of element', function (t) {
t.plan(1);
var View = AmpersandView.extend({
template: '<div></div>',
autoRender: true
});
var view = new View();
t.ok(view.el);
t.once('change:el', function () {
t.pass('this should fire');
});
t.el = document.createElement('div');
t.once('change:el', function () {
t.fail('this should *not* fire');
});
var el = t.el;
el.innerHTML = '<span></span>';
t.el = el;
t.end();
});
test('Should be able to bind multiple models in bindings hash', function (t) {
var Person = Model.extend({
props: {
name: 'string'
}
});
var View = AmpersandView.extend({
template: '<div><span id="model1"></span><span id="model2"></span></div>',
autoRender: true,
props: {
model1: 'model',
model2: 'model'
},
bindings: {
'model1.name': '#model1',
'model2.name': {
type: 'class',
selector: '#model2'
}
}
});
var view = new View({
model1: new Person({name: 'henrik'}),
model2: new Person({name: 'larry'})
});
t.equal(view.el.firstChild.textContent, 'henrik');
t.equal(view.el.children[1].className.trim(), 'larry');
t.end();
});
test('Should be able to declare bindings first, before model is added', function (t) {
var Person = Model.extend({props: {name: 'string'}});
var View = AmpersandView.extend({
template: '<div></div>',
autoRender: true,
bindings: {
'model.name': ''
}
});
var view = new View();
t.equal(view.el.textContent, '');
view.model = new Person({name: 'henrik'});
t.equal(view.el.textContent, 'henrik');
view.model.name = 'something new';
t.equal(view.el.textContent, 'something new');
t.end();
});
test('Should be able to swap out models and bindings should still work', function (t) {
var Person = Model.extend({props: {name: 'string'}});
var View = AmpersandView.extend({
template: '<div></div>',
autoRender: true,
bindings: {
'model.name': ''
}
});
var p1 = new Person({name: 'first'});
var p2 = new Person({name: 'second'});
var view = new View();
t.equal(view.el.textContent, '');
view.model = p1;
t.equal(view.el.textContent, 'first');
view.model = p2;
t.equal(view.el.textContent, 'second');
// make sure it's not still bound to first
p1.name = 'third';
t.equal(view.el.textContent, 'second');
t.end();
});
test('Should be able to re-render and maintain bindings', function (t) {
var Person = Model.extend({props: {name: 'string'}});
var View = AmpersandView.extend({
template: '<div></div>',
autoRender: true,
bindings: {
'model.name': ''
}
});
var p1 = new Person({name: 'first'});
var view = new View({model: p1});
var el1 = view.el;
t.equal(view.el.textContent, 'first');
view.renderWithTemplate();
var el2 = view.el;
t.ok(el1 !== el2, 'sanity check to make sure it\'s a new element');
t.equal(el2.textContent, 'first', 'new one should have the binding still');
p1.name = 'third';
t.equal(el2.textContent, 'third', 'new element should also get the change');
t.end();
});
test('trigger `remove` event when view is removed', function (t) {
var View = AmpersandView.extend({
template: '<div></div>',
autoRender: true
});
var view = new View();
view.on('remove', function () {
t.pass('remove fired');
t.end();
});
view.remove();
});
test('trigger `remove` when view is removed using listenTo', function (t) {
var View = AmpersandView.extend({
template: '<div></div>',
autoRender: true
});
var view = new View();
view.listenTo(view, 'remove', function() {
t.pass('remove fired');
t.end();
});
view.remove();
});
test('declarative subViews basics', function (t) {
var Sub = AmpersandView.extend({
template: '<span></span>'
});
var View = AmpersandView.extend({
template: '<div><div class="container"></div></div>',
autoRender: true,
subviews: {
sub1: {
selector: '.container',
constructor: Sub
}
}
});
var view = new View();
t.equal(view.el.innerHTML, '<span></span>');
t.end();
});
test('subViews declaraction can accept a CSS selector string via `container` property for backwards compatibility (#114)', function (t) {
var Sub = AmpersandView.extend({
template: '<span></span>'
});
var View = AmpersandView.extend({
template: '<div><div class="container"></div></div>',
autoRender: true,
subviews: {
sub1: {
container: '.container',
constructor: Sub
}
}
});
var view = new View();
t.equal(view.el.innerHTML, '<span></span>');
t.end();
});
test('subview hook can include special characters', function (t) {
var Sub = AmpersandView.extend({
template: '<span></span>'
});
var View = AmpersandView.extend({
template: '<div><div data-hook="test.hi-there"></div></div>',
autoRender: true,
subviews: {
sub1: {
hook: 'test.hi-there',
constructor: Sub
}
}
});
var view = new View();
t.equal(view.el.innerHTML, '<span></span>');
t.end();
});
test('make sure subviews dont fire until their `waitFor` is done', function (t) {
var Sub = AmpersandView.extend({
template: '<span>yes</span>'
});
var View = AmpersandView.extend({
template: '<div><span class="container"></span><span data-hook="sub"></span></div>',
autoRender: true,
props: {
model2: 'state'
},
subviews: {
sub1: {
waitFor: 'model',
selector: '.container',
constructor: Sub
},
sub2: {
waitFor: 'model2',
hook: 'sub',
constructor: Sub
}
}
});
var view = new View();
t.equal(view._events.change.length, 2);
t.equal(view.el.outerHTML, '<div><span class="container"></span><span data-hook="sub"></span></div>');
view.model = new Model();
t.equal(view._events.change.length, 1);
t.equal(view.el.outerHTML, '<div><span>yes</span><span data-hook="sub"></span></div>');
view.model2 = new Model();
t.equal(view.el.outerHTML, '<div><span>yes</span><span>yes</span></div>');
t.notOk(view._events.change);
t.end();
});
test('make sure template can return a dom node', function (t) {
var Sub = AmpersandView.extend({
template: function () {
return document.createElement('div');
}
});
var view = new Sub();
view.render();
t.end();
});
test('template can be passed as viewOption', function (t) {
t.plan(1);
var View = AmpersandView.extend({
autoRender: true
});
var view = new View({
template: '<span></span>'
});
t.equal(view.el.outerHTML, '<span></span>');
t.end();
});
test('events are bound if there is an el in the constructor', function (t) {
t.plan(1);
var event = document.createEvent("MouseEvent");
var View = AmpersandView.extend({
template: function () {
return document.createElement('div');
},
events: {
'click div': 'divClicked'
},
divClicked: function (e) {
t.ok(true, 'event fired');
t.end();
}
});
var view = new View({el: document.createElement('div')});
event.initMouseEvent('click');
view.el.dispatchEvent(event);
});
| test/main.js | var test = require('tape');
var AmpersandModel = require('ampersand-model');
var AmpersandCollection = require('ampersand-rest-collection');
var AmpersandView = require('../ampersand-view');
var contains = function (str1, str2) {
return str1.indexOf(str2) !== -1;
};
var Model = AmpersandModel.extend({
props: {
id: 'number',
name: ['string', true],
html: 'string',
url: 'string',
something: 'string',
fireDanger: 'string'
},
session: {
active: 'boolean'
},
derived: {
classes: {
deps: ['something', 'fireDanger', 'active'],
fn: function () {
return this.something + this.active;
}
}
}
});
function getView(bindings, model) {
if (!bindings.template) {
bindings.template = '<li><span></span><img></li>';
}
var View = AmpersandView.extend(bindings);
var view = new View({
model: model || new Model()
});
return view.renderWithTemplate();
}
test('event behavior with over-ridden `render` & `remove` fns', function (t) {
var renderCount = 0;
var removeCount = 0;
t.plan(7);
var ChildView = AmpersandView.extend({
render: function() {
AmpersandView.prototype.render.call(this);
t.ok(true, 'child view render called');
}
});
var GrandChildView = AmpersandView.extend({
render: function() {
ChildView.prototype.render.call(this);
t.ok(true, 'grand child view render called');
}
});
var detachedEl = document.createElement('div');
var view = new GrandChildView({
template: '<span></span>',
el: detachedEl
});
view.on('render', function(view, value) {
++renderCount;
t.ok(true, 'view `render` event happened on `render()`');
});
view.on('remove', function(view, value) {
++removeCount;
});
view.render();
t.equal(removeCount, 0, '`remove` event not called, pre- or post- render()');
t.equal(renderCount, 1, '`render` triggered exactly once, post- render()');
view.remove();
t.equal(removeCount, 1, '`remove` triggered exactly once, post- remove()');
t.equal(renderCount, 1, '`render` triggered exactly once, post- remove()');
t.end();
});
test('standard `rendered` attr behavior', function (t) {
var caughtRenderEvt = false;
var detachedEl = document.createElement('div');
var view = new AmpersandView({
template: '<span></span>',
el: detachedEl
});
view.on('change:rendered', function() {
caughtRenderEvt = !caughtRenderEvt;
});
t.notOk(view.rendered, 'view not `rendered` prior to `render()` call');
view.render();
t.ok(view.rendered, 'view `rendered` post `render()` call');
t.ok(caughtRenderEvt, 'view `rendered` evt observed on `render()` call');
view.remove();
t.notOk(caughtRenderEvt, 'view `rendered` evt observed on `remove()` call');
t.notOk(view.rendered, 'view not `rendered` post `remove()` call');
t.end();
});
test('user over-ridden `render()` and `remove()` behavior', function (t) {
var view;
var RenderTestView = AmpersandView.extend({
template: '<span></span>',
render: function() {
t.ok(true, 'user defined `render()` executed');
},
remove: function() {
t.ok(true, 'user defined `remove()` executed');
}
});
t.plan(4);
view = new RenderTestView();
view.on('change:rendered', function() {
t.ok(true, '`rendered` triggered on custom render/remove');
});
view.render();
view.remove();
t.end();
});
test('Model, collection, and el become properties', function (t) {
var model = new Model();
var collection = new AmpersandCollection();
var el = document.createElement('div');
var view = new AmpersandView({
model: model,
collection: collection,
el: el
});
t.equal(view.model, model);
t.equal(view.collection, collection);
t.equal(view.el, el);
t.end();
});
test('registerSubview', function (t) {
var removeCalled = 0;
var SubView = AmpersandView.extend({
template: '<div></div>',
render: function () {
this.renderWithTemplate();
this.el.className = 'subview';
},
remove: function () {
removeCalled++;
}
});
var View = AmpersandView.extend({
template: '<section><div id="parent"></div></section>',
render: function () {
this.renderWithTemplate();
// all of these should work
this.renderSubview(new SubView(), this.query('#parent'));
this.renderSubview(new SubView(), '#parent');
// some other thing with a remove method
this.registerSubview({remove: function () {
removeCalled++;
}});
}
});
var main = new View({
el: document.createElement('div')
});
main.render();
t.equal(main.queryAll('.subview').length, 2);
main.remove();
t.equal(removeCalled, 3);
t.end();
});
test('registerSubview: default container to this.el', function (t) {
var removeCalled = 0;
var SubView = AmpersandView.extend({
template: '<div></div>',
render: function () {
this.renderWithTemplate();
this.el.className = 'subview';
},
remove: function () {
removeCalled++;
}
});
var View = AmpersandView.extend({
template: '<section></section>',
render: function () {
this.renderWithTemplate();
this.renderSubview(new SubView());
this.renderSubview(new SubView());
}
});
var main = new View({
el: document.createElement('div')
});
main.render();
t.equal(main.queryAll('.subview').length, 2);
t.equal(main.el.childNodes.length, 2);
main.remove();
t.equal(removeCalled, 2);
t.end();
});
test('caching elements', function(t) {
var View = AmpersandView.extend({
template: '<p><span></span></p>',
render: function () {
this.renderWithTemplate();
return this.cacheElements(({span:'span'}));
}
});
var instance = new View(),
rendered = instance.render();
t.equal(instance, rendered);
t.equal(typeof rendered.span, 'object');
t.end();
});
test('listen to and run', function (t) {
t.plan(1);
var model = new Model({
props: {
name: 'string'
}
});
var View = AmpersandView.extend({
initialize: function () {
this.model = model;
this.listenToAndRun(this.model, 'something', this.handler);
t.end();
},
handler: function () {
t.pass('handler ran');
}
});
new View();
});
test('text bindings', function (t) {
var view = getView({
bindings: {
'model.name': 'span'
}
});
t.equal(view.query('span').textContent, '');
view.model.set('name', 'henrik');
t.equal(view.query('span').textContent, 'henrik');
t.end();
});
test('src bindings', function (t) {
var view = getView({
bindings: {
'model.url': {
type: 'attribute',
name: 'src',
selector: 'img'
}
}
});
var img = view.query('img');
t.equal(img.getAttribute('src'), '');
view.model.set('url', 'http://robohash.com/whammo');
t.equal(img.getAttribute('src'), 'http://robohash.com/whammo');
t.end();
});
test('href bindings', function (t) {
var view = getView({
template: '<a href=""></a>',
bindings: {
'model.url': {
type: 'attribute',
name: 'href',
selector: ''
}
}
});
var el = view.el;
t.equal(el.getAttribute('href'), '');
view.model.set('url', 'http://robohash.com/whammo');
t.equal(el.getAttribute('href'), 'http://robohash.com/whammo');
t.end();
});
test('input bindings', function (t) {
var view = getView({
template: '<li><input></li>',
bindings: {
'model.something': {
type: 'attribute',
selector: 'input',
name: 'value'
}
}
});
var input = view.query('input');
t.equal(input.value, '');
view.model.set('something', 'yo');
t.equal(input.value, 'yo');
t.end();
});
test('class bindings', function (t) {
var model = new Model();
model.set({
fireDanger: 'high',
active: true
});
var view = getView({
template: '<li></li>',
bindings: {
'model.fireDanger': {
type: 'class'
},
'model.active': {
type: 'booleanClass'
}
}
}, model);
var className = view.el.className;
t.ok(contains(className, 'active'));
t.ok(contains(className, 'high'));
model.set('fireDanger', 'low');
className = view.el.className;
t.ok(!contains(className, 'high'));
t.ok(contains(className, 'low'));
model.set('active', false);
className = view.el.className;
t.ok(!contains(className, 'active'));
t.ok(contains(className, 'low'));
t.end();
});
test('nested binding definitions', function (t) {
var model = new Model();
model.set({
active: true
});
var View = AmpersandView.extend({
autoRender: true,
template: '<li><div></div></li>',
bindings: {
'model.active': [
{
type: 'booleanAttribute',
name: 'data-active',
selector: 'div'
},
{
type: 'booleanAttribute',
name: 'data-something',
selector: 'div'
},
{
selector: 'div'
},
{
type: 'booleanClass'
}
]
}
});
var view = new View({model: model});
var li = view.el;
var div = li.firstChild;
t.ok(div.hasAttribute('data-active'));
t.ok(div.hasAttribute('data-something'));
t.equal(div.textContent, 'true');
t.ok(contains(li.className, 'active'));
t.end();
});
test('renderAndBind with no model', function (t) {
var View = AmpersandView.extend({
template: '<li><span></span><img></li>'
});
var view = new View();
t.ok(view.renderWithTemplate()); //Should not throw error
t.end();
});
test('queryByHook', function (t) {
var View = AmpersandView.extend({
template: '<li data-hook="list-item"><span data-hook="username"></span><img data-hook="user-avatar"></li>'
});
var view = new View();
view.renderWithTemplate();
t.ok(view.queryByHook('username') instanceof Element, 'should find username element');
t.ok(view.queryByHook('user-avatar') instanceof Element, 'should find username');
t.ok(view.queryByHook('nothing') === undefined, 'should find username');
t.ok(view.queryByHook('list-item') instanceof Element, 'should also work for root element');
t.end();
});
test('queryAllByHook', function (t) {
var View = AmpersandView.extend({
template: '<li data-hook="list-item"><span data-hook="username info"></span><img data-hook="user-avatar info"></li>'
});
var view = new View();
view.renderWithTemplate();
t.ok(view.queryAllByHook('info') instanceof Array, 'should return array of results');
t.equal(view.queryAllByHook('info').length, 2, 'should find all relevant elements');
t.ok(view.queryAllByHook('info')[0] instanceof Element, 'should be able to access found elements');
t.ok(view.queryAllByHook('info')[1] instanceof Element, 'should be able to access found elements');
t.deepEqual(view.queryAllByHook('nothing'), [], 'should return empty array if no results found');
t.end();
});
test('throw on multiple root elements', function (t) {
var View = AmpersandView.extend({
template: '<li></li><div></div>'
});
var view = new View();
t.throws(view.renderWithTemplate, Error, 'Throws error on multiple root elements');
t.end();
});
test('queryAll should return an array', function (t) {
var View = AmpersandView.extend({
autoRender: true,
template: '<ul><li></li><li></li><li></li></ul>'
});
var view = new View();
var all = view.queryAll('li');
t.ok(all instanceof Array);
t.ok(all.forEach);
t.equal(all.length, 3);
t.end();
});
test('get should return undefined if no match', function (t) {
var View = AmpersandView.extend({
autoRender: true,
template: '<ul></ul>'
});
var view = new View();
var el = view.query('div');
t.equal(typeof el, 'undefined');
t.strictEqual(view.query(''), view.el);
t.strictEqual(view.query(), view.el);
t.strictEqual(view.query(view.el), view.el);
t.end();
});
test('get should work for root element too', function (t) {
var View = AmpersandView.extend({
autoRender: true,
template: '<ul></ul>'
});
var view = new View();
t.equal(view.query('ul'), view.el);
t.end();
});
test('queryAll should include root element if matches', function (t) {
var View = AmpersandView.extend({
autoRender: true,
template: '<div class="test"><div class="test deep"><div class="test deep"></div></div></div>'
});
var view = new View();
var hasTestClass = view.queryAll('.test');
var hasDeepClass = view.queryAll('.deep');
t.equal(hasTestClass.length, 3);
t.equal(hasDeepClass.length, 2);
t.ok(hasTestClass instanceof Array);
t.ok(hasDeepClass instanceof Array);
t.ok(view.queryAll('bogus') instanceof Array);
t.end();
});
test('query should throw an error if view was not rendered', function (t) {
var View = AmpersandView.extend({
autoRender: false,
template: '<div class="test"><div class="test deep"><div class="test deep"></div></div></div>'
});
var view = new View();
t.throws((function () {
view.query('.test');
}), Error, 'Throws error on query with selector');
t.throws((function () {
view.query('');
}), Error, 'Throws error on query with empty selector');
t.end();
});
test('query should not throw an error if view was rendered', function (t) {
var View = AmpersandView.extend({
autoRender: false,
template: '<div class="test"><div class="test deep"><div class="test deep"></div></div></div>'
});
var view = new View();
view.render();
t.doesNotThrow((function () {
view.query('.test');
}), Error, 'Does not throws error on query');
t.doesNotThrow((function () {
view.query('');
}), Error, 'Does not throws error on empty selector');
t.end();
});
test('queryAll should throw an error if view was not rendered', function (t) {
var View = AmpersandView.extend({
autoRender: false,
template: '<div class="test"><div class="test deep"><div class="test deep"></div></div></div>'
});
var view = new View();
t.throws((function () {
view.queryAll('div');
}), Error, 'Throws error on queryAll');
t.throws((function () {
view.queryAll('');
}), Error, 'Throws error on queryAll with empty selector');
t.end();
});
test('queryAll should not throw an error if view was rendered', function (t) {
var View = AmpersandView.extend({
autoRender: false,
template: '<div class="test"><div class="test deep"><div class="test deep"></div></div></div>'
});
var view = new View();
view.render();
t.doesNotThrow((function () {
view.queryAll('div');
}), Error, 'Does not throw error on queryAll');
t.doesNotThrow((function () {
view.queryAll('');
}), Error, 'Does not throw error on queryAll with empty selector');
t.end();
});
//test('focus/blur events should work in events hash. Issue #8', function (t) {
// t.plan(2);
// var View = AmpersandView.extend({
// events: {
// 'focus #thing': 'handleFocus',
// 'blur #thing': 'handleBlur'
// },
// autoRender: true,
// template: '<div><input id="thing"></div></div>',
// handleFocus: function () {
// t.pass('focus called');
// },
// handleBlur: function () {
// t.pass('blur called');
// t.end();
// }
// });
// var view = new View();
// // should be able to do this without
// // ending up with too many handlers
// view.delegateEvents();
// view.delegateEvents();
// view.delegateEvents();
//
// document.body.appendChild(view.el);
// view.el.firstChild.focus();
// view.el.firstChild.blur();
// document.body.removeChild(view.el);
//});
test('ability to mix in state properties', function (t) {
var View = AmpersandView.extend({
template: '<div></div>',
render: function () {
this.el = document.createElement('div');
}
});
var view = new View();
view.on('change:el', function () {
t.pass('woohoo!');
t.end();
});
view.render();
});
test('Ability to add other state properties', function (t) {
var View = AmpersandView.extend({
props: {
thing: 'boolean'
},
template: '<div></div>'
});
var view = new View();
view.on('change:thing', function () {
t.pass('woohoo!');
t.end();
});
view.thing = true;
});
test('Multi-inheritance of state properties works too', function (t) {
t.plan(2);
var View = AmpersandView.extend({
props: {
thing: 'boolean'
},
template: '<div></div>'
});
var SecondView = View.extend({
props: {
otherThing: 'boolean'
}
});
var view = window.view = new SecondView();
view.on('change:thing', function () {
t.pass('woohoo!');
});
view.on('change:otherThing', function () {
t.pass('woohoo!');
t.end();
});
view.thing = true;
view.otherThing = true;
});
test('Setting an `el` should only fire change if new instance of element', function (t) {
t.plan(1);
var View = AmpersandView.extend({
template: '<div></div>',
autoRender: true
});
var view = new View();
t.ok(view.el);
t.once('change:el', function () {
t.pass('this should fire');
});
t.el = document.createElement('div');
t.once('change:el', function () {
t.fail('this should *not* fire');
});
var el = t.el;
el.innerHTML = '<span></span>';
t.el = el;
t.end();
});
test('Should be able to bind multiple models in bindings hash', function (t) {
var Person = Model.extend({
props: {
name: 'string'
}
});
var View = AmpersandView.extend({
template: '<div><span id="model1"></span><span id="model2"></span></div>',
autoRender: true,
props: {
model1: 'model',
model2: 'model'
},
bindings: {
'model1.name': '#model1',
'model2.name': {
type: 'class',
selector: '#model2'
}
}
});
var view = new View({
model1: new Person({name: 'henrik'}),
model2: new Person({name: 'larry'})
});
t.equal(view.el.firstChild.textContent, 'henrik');
t.equal(view.el.children[1].className.trim(), 'larry');
t.end();
});
test('Should be able to declare bindings first, before model is added', function (t) {
var Person = Model.extend({props: {name: 'string'}});
var View = AmpersandView.extend({
template: '<div></div>',
autoRender: true,
bindings: {
'model.name': ''
}
});
var view = new View();
t.equal(view.el.textContent, '');
view.model = new Person({name: 'henrik'});
t.equal(view.el.textContent, 'henrik');
view.model.name = 'something new';
t.equal(view.el.textContent, 'something new');
t.end();
});
test('Should be able to swap out models and bindings should still work', function (t) {
var Person = Model.extend({props: {name: 'string'}});
var View = AmpersandView.extend({
template: '<div></div>',
autoRender: true,
bindings: {
'model.name': ''
}
});
var p1 = new Person({name: 'first'});
var p2 = new Person({name: 'second'});
var view = new View();
t.equal(view.el.textContent, '');
view.model = p1;
t.equal(view.el.textContent, 'first');
view.model = p2;
t.equal(view.el.textContent, 'second');
// make sure it's not still bound to first
p1.name = 'third';
t.equal(view.el.textContent, 'second');
t.end();
});
test('Should be able to re-render and maintain bindings', function (t) {
var Person = Model.extend({props: {name: 'string'}});
var View = AmpersandView.extend({
template: '<div></div>',
autoRender: true,
bindings: {
'model.name': ''
}
});
var p1 = new Person({name: 'first'});
var view = new View({model: p1});
var el1 = view.el;
t.equal(view.el.textContent, 'first');
view.renderWithTemplate();
var el2 = view.el;
t.ok(el1 !== el2, 'sanity check to make sure it\'s a new element');
t.equal(el2.textContent, 'first', 'new one should have the binding still');
p1.name = 'third';
t.equal(el2.textContent, 'third', 'new element should also get the change');
t.end();
});
test('trigger `remove` event when view is removed', function (t) {
var View = AmpersandView.extend({
template: '<div></div>',
autoRender: true
});
var view = new View();
view.on('remove', function () {
t.pass('remove fired');
t.end();
});
view.remove();
});
test('trigger `remove` when view is removed using listenTo', function (t) {
var View = AmpersandView.extend({
template: '<div></div>',
autoRender: true
});
var view = new View();
view.listenTo(view, 'remove', function() {
t.pass('remove fired');
t.end();
});
view.remove();
});
test('declarative subViews basics', function (t) {
var Sub = AmpersandView.extend({
template: '<span></span>'
});
var View = AmpersandView.extend({
template: '<div><div class="container"></div></div>',
autoRender: true,
subviews: {
sub1: {
selector: '.container',
constructor: Sub
}
}
});
var view = new View();
t.equal(view.el.innerHTML, '<span></span>');
t.end();
});
test('subViews declaraction can accept a CSS selector string via `container` property for backwards compatibility (#114)', function (t) {
var Sub = AmpersandView.extend({
template: '<span></span>'
});
var View = AmpersandView.extend({
template: '<div><div class="container"></div></div>',
autoRender: true,
subviews: {
sub1: {
container: '.container',
constructor: Sub
}
}
});
var view = new View();
t.equal(view.el.innerHTML, '<span></span>');
t.end();
});
test('subview hook can include special characters', function (t) {
var Sub = AmpersandView.extend({
template: '<span></span>'
});
var View = AmpersandView.extend({
template: '<div><div data-hook="test.hi-there"></div></div>',
autoRender: true,
subviews: {
sub1: {
hook: 'test.hi-there',
constructor: Sub
}
}
});
var view = new View();
t.equal(view.el.innerHTML, '<span></span>');
t.end();
});
test('make sure subviews dont fire until their `waitFor` is done', function (t) {
var Sub = AmpersandView.extend({
template: '<span>yes</span>'
});
var View = AmpersandView.extend({
template: '<div><span class="container"></span><span data-hook="sub"></span></div>',
autoRender: true,
props: {
model2: 'state'
},
subviews: {
sub1: {
waitFor: 'model',
selector: '.container',
constructor: Sub
},
sub2: {
waitFor: 'model2',
hook: 'sub',
constructor: Sub
}
}
});
var view = new View();
t.equal(view._events.change.length, 2);
t.equal(view.el.outerHTML, '<div><span class="container"></span><span data-hook="sub"></span></div>');
view.model = new Model();
t.equal(view._events.change.length, 1);
t.equal(view.el.outerHTML, '<div><span>yes</span><span data-hook="sub"></span></div>');
view.model2 = new Model();
t.equal(view.el.outerHTML, '<div><span>yes</span><span>yes</span></div>');
t.notOk(view._events.change);
t.end();
});
test('make sure template can return a dom node', function (t) {
var Sub = AmpersandView.extend({
template: function () {
return document.createElement('div');
}
});
var view = new Sub();
view.render();
t.end();
});
test('template can be passed as viewOption', function (t) {
t.plan(1);
var View = AmpersandView.extend({
autoRender: true
});
var view = new View({
template: '<span></span>'
});
t.equal(view.el.outerHTML, '<span></span>');
t.end();
});
test('events are bound if there is an el in the constructor', function (t) {
t.plan(1);
var event = document.createEvent("MouseEvent");
var View = AmpersandView.extend({
template: function () {
return document.createElement('div');
},
events: {
'click div': 'divClicked'
},
divClicked: function (e) {
t.ok(true, 'event fired');
t.end();
}
});
var view = new View({el: document.createElement('div')});
event.initMouseEvent('click');
view.el.dispatchEvent(event);
});
| patch render test descriptor
| test/main.js | patch render test descriptor | <ide><path>est/main.js
<ide> t.equal(renderCount, 1, '`render` triggered exactly once, post- render()');
<ide> view.remove();
<ide> t.equal(removeCount, 1, '`remove` triggered exactly once, post- remove()');
<del> t.equal(renderCount, 1, '`render` triggered exactly once, post- remove()');
<add> t.equal(renderCount, 1, '`render` not triggered, post- remove()');
<ide> t.end();
<ide> });
<ide> |
|
JavaScript | mit | 019a535a6963a8b5d3d0640231171d545f31c76c | 0 | yangshun/builder-news | function MainCtrl ($scope) {
var HACKER_NEWS_API = 'https://www.kimonolabs.com/api/2he37zjs';
var DESIGNER_NEWS_API = 'https://www.kimonolabs.com/api/6dts50j0';
var ACCESS_TOKEN = 'lC5em34Ewkmh4mK8CPTGeEDJer15kwus';
$scope.news = [];
$scope.displayedNews = [];
$scope.currentFilter = 'all';
$scope.selectedItem = null;
$scope.loaded = false;
$scope.newsTypes = [
{id: 'all', name: 'All'},
{id: 'hackernews', name: 'Hacker News'},
{id: 'designernews', name: 'Designer News'}
];
$scope.linkTypes = {designernews: 'Designer News', hackernews: 'Hacker News'};
localforage.getItem('favourites', function (favourites) {
if (!favourites) {
favourites = [];
}
$scope.favourites = favourites;
});
localforage.getItem('defaultNews', function (defaultNews) {
if (!defaultNews) {
defaultNews = 'all';
}
$scope.defaultNews = defaultNews;
$scope.currentFilter = $scope.defaultNews;
});
localforage.getItem('defaultLimit', function (defaultLimit) {
if (!defaultLimit) {
defaultLimit = 30;
}
$scope.defaultLimit = defaultLimit;
$scope.$apply();
});
function calculateTimeAgo (timeAgoString) {
if (timeAgoString.indexOf('minute') > -1) {
return parseInt(timeAgoString);
} else if (timeAgoString.indexOf('hour') > -1) {
return parseInt(timeAgoString) * 60;
} else if (timeAgoString.indexOf('day') > -1) {
return parseInt(timeAgoString) * 60 * 24;
}
}
$.subscribe('chui/navigate/enter', function (event, id) {
if (id === 'main') {
$scope.displayNews($scope.currentFilter);
}
});
$scope.displayNews = function (type) {
$scope.displayedNews = _.filter($scope.news, function (item) {
if (type !== 'all') {
return item.type === type;
}
return true;
});
var animations = {
all: 'bounceInUp',
hackernews: 'bounceInLeft',
designernews: 'bounceInRight'
};
$('.builder-news li').removeClass('animated ' + _.values(animations).join(' '));
var i = 0;
setTimeout(function () {
$('.builder-news li').each(function () {
var that = this;
(function (delay) {
setTimeout(function () {
$(that).addClass('animated ' + animations[type]);
}, delay);
}(i * 100));
i++;
});
}, 0);
};
$scope.openLink = function (url) {
window.open(url, '_blank');
};
$scope.bookmarkItem = function (item) {
if (_.pluck($scope.favourites, 'url').indexOf(item.url) > -1) {
$.UIPopup({
id: 'warning',
title: 'Remove Favourite',
message: 'Do you really want to remove the favourited link "' + item.title + '"?',
cancelButton: 'No',
continueButton: 'Yes',
callback: function() {
$scope.favourites = _.reject($scope.favourites, function(bm) {
return bm.url == item.url;
});
localforage.setItem('favourites', $scope.favourites);
$scope.$apply();
}
});
} else {
$scope.favourites.push(item);
localforage.setItem('favourites', $scope.favourites);
}
};
$scope.checkBookmark = function (url) {
if (_.pluck($scope.favourites, 'url').indexOf(url) > -1) {
return 'fa-star';
} else {
return 'fa-star-o';
}
};
var hackerNews = [];
var hackerNewsLoaded = false;
$.ajax({
method: 'GET',
url: HACKER_NEWS_API + '?apikey=' + ACCESS_TOKEN,
dataType: 'jsonp',
crossDomain: true,
success: function (data) {
for (var i = 0; i < data.results.collection1.length; i++) {
var item = data.results.collection1[i];
item.rank = i + 1;
item.type = 'hackernews';
item.url = item.title.href;
item.title = item.title.text;
item.domain = item.domain.replace('(', '').replace(')', '');
item.comments = item.comments.text;
item.author = item.author.text;
item.time = item.details.text.split(' ').slice(4, 7).join(' ');
item.time_ago = calculateTimeAgo(item.time);
item.points_text = item.points;
item.points = parseInt(item.points_text);
delete item.details;
hackerNews.push(item);
}
hackerNewsLoaded = true;
if (designerNewsLoaded) {
combineNews();
}
},
error: function (data) {
console.log(data);
}
});
var designerNews = [];
var designerNewsLoaded = false;
$.ajax({
method: 'GET',
url: DESIGNER_NEWS_API + '?apikey=' + ACCESS_TOKEN,
dataType: 'jsonp',
crossDomain: true,
success: function (data) {
for (var i = 0; i < data.results.collection1.length; i++) {
var item = data.results.collection1[i];
item.rank = i + 1;
item.type = 'designernews';
var domainExists = item.title.text.indexOf('(');
if (domainExists > -1) {
var domain = item.title.text.slice(domainExists);
item.title.text = item.title.text.replace(domain, '');
item.domain = domain.replace('(', '').replace(')', '');
}
item.url = item.title.href;
item.title = item.title.text;
item.time = item.time.replace('hrs', 'hours').replace('mins', 'minutes');
item.time_ago = calculateTimeAgo(item.time);
item.author = item.author.text;
item.comments = item.comments.text;
item.points_text = item.points.text;
item.points = parseInt(item.points_text) * 10 // Give Designer News more weight;
designerNews.push(item);
}
designerNewsLoaded = true;
if (hackerNewsLoaded) {
combineNews();
}
},
error: function (data) {
console.log(data);
}
});
function combineNews () {
$scope.news = $scope.news.concat(hackerNews).concat(designerNews);
$scope.news = _.sortBy($scope.news, function (item) {
return item.points;
});
$scope.news.reverse();
$scope.loaded = true;
$scope.displayNews($scope.defaultNews);
var i = 0;
$('.builder-news').addClass('loaded');
$scope.$apply();
}
$scope.setDefaultLimit = function (number) {
localforage.setItem('defaultLimit', $scope.defaultLimit);
};
$scope.setDefaultNews = function (type) {
localforage.setItem('defaultNews', type);
};
$scope.aboutLinks = [
{
url: 'https://news.ycombinator.com/news',
class: 'fa fa-hacker-news fa-lg hackernews',
text: 'Hacker News Homepage'
},
{
url: 'https://news.layervault.com',
class: 'fa fa-picture-o fa-lg designernews',
text: 'Designer News Homepage'
},
{
url: 'https://github.com/yangshun/builder-news',
class: 'fa fa-github fa-lg',
text: 'Builder News on Github'
},
{
url: 'mailto:[email protected]',
class: 'fa fa-envelope-o fa-lg contact-icon',
text: 'Send Feedback'
}
];
} | js/app.js | function MainCtrl ($scope) {
var HACKER_NEWS_API = 'https://www.kimonolabs.com/api/2he37zjs';
var DESIGNER_NEWS_API = 'https://www.kimonolabs.com/api/6dts50j0';
var ACCESS_TOKEN = 'lC5em34Ewkmh4mK8CPTGeEDJer15kwus';
$scope.news = [];
$scope.displayedNews = [];
$scope.currentFilter = 'all';
$scope.selectedItem = null;
$scope.loaded = false;
$scope.newsTypes = [
{id: 'all', name: 'All'},
{id: 'hackernews', name: 'Hacker News'},
{id: 'designernews', name: 'Designer News'}
];
$scope.linkTypes = {designernews: 'Designer News', hackernews: 'Hacker News'};
localforage.getItem('favourites', function (favourites) {
if (!favourites) {
favourites = [];
}
$scope.favourites = favourites;
});
localforage.getItem('defaultNews', function (defaultNews) {
if (!defaultNews) {
defaultNews = 'all';
}
$scope.defaultNews = defaultNews;
$scope.currentFilter = $scope.defaultNews;
});
localforage.getItem('defaultLimit', function (defaultLimit) {
if (!defaultLimit) {
defaultLimit = 30;
}
$scope.defaultLimit = defaultLimit;
$scope.$apply();
});
function calculateTimeAgo (timeAgoString) {
if (timeAgoString.indexOf('minute') > -1) {
return parseInt(timeAgoString);
} else if (timeAgoString.indexOf('hour') > -1) {
return parseInt(timeAgoString) * 60;
} else if (timeAgoString.indexOf('day') > -1) {
return parseInt(timeAgoString) * 60 * 24;
}
}
$.subscribe('chui/navigate/enter', function (event, id) {
if (id === 'main') {
$scope.displayNews($scope.currentFilter);
}
});
$scope.displayNews = function (type) {
$scope.displayedNews = _.filter($scope.news, function (item) {
if (type !== 'all') {
return item.type === type;
}
return true;
});
var animations = {
all: 'bounceInUp',
hackernews: 'bounceInLeft',
designernews: 'bounceInRight'
}
$('.builder-news li').removeClass('animated bounceInUp bounceInLeft bounceInRight');
var i = 0;
setTimeout(function () {
$('.builder-news li').each(function () {
var that = this;
(function (delay) {
setTimeout(function () {
$(that).addClass('animated ' + animations[type]);
}, delay);
}(i * 100));
i++;
});
}, 0);
};
$scope.openLink = function (url) {
window.open(url, '_blank');
};
$scope.bookmarkItem = function (item) {
if (_.pluck($scope.favourites, 'url').indexOf(item.url) > -1) {
$.UIPopup({
id: 'warning',
title: 'Remove Favourite',
message: 'Do you really want to remove the favourited link "' + item.title + '"?',
cancelButton: 'No',
continueButton: 'Yes',
callback: function() {
$scope.favourites = _.reject($scope.favourites, function(bm) {
return bm.url == item.url;
});
localforage.setItem('favourites', $scope.favourites);
$scope.$apply();
}
});
} else {
$scope.favourites.push(item);
localforage.setItem('favourites', $scope.favourites);
}
};
$scope.checkBookmark = function (url) {
if (_.pluck($scope.favourites, 'url').indexOf(url) > -1) {
return 'fa-star';
} else {
return 'fa-star-o';
}
};
var hackerNews = [];
var hackerNewsLoaded = false;
$.ajax({
method: 'GET',
url: HACKER_NEWS_API + '?apikey=' + ACCESS_TOKEN,
dataType: 'jsonp',
crossDomain: true,
success: function (data) {
for (var i = 0; i < data.results.collection1.length; i++) {
var item = data.results.collection1[i];
item.rank = i + 1;
item.type = 'hackernews';
item.url = item.title.href;
item.title = item.title.text;
item.domain = item.domain.replace('(', '').replace(')', '');
item.comments = item.comments.text;
item.author = item.author.text;
item.time = item.details.text.split(' ').slice(4, 7).join(' ');
item.time_ago = calculateTimeAgo(item.time);
item.points_text = item.points;
item.points = parseInt(item.points_text);
delete item.details;
hackerNews.push(item);
}
hackerNewsLoaded = true;
if (designerNewsLoaded) {
combineNews();
}
},
error: function (data) {
console.log(data);
}
});
var designerNews = [];
var designerNewsLoaded = false;
$.ajax({
method: 'GET',
url: DESIGNER_NEWS_API + '?apikey=' + ACCESS_TOKEN,
dataType: 'jsonp',
crossDomain: true,
success: function (data) {
for (var i = 0; i < data.results.collection1.length; i++) {
var item = data.results.collection1[i];
item.rank = i + 1;
item.type = 'designernews';
var domainExists = item.title.text.indexOf('(');
if (domainExists > -1) {
var domain = item.title.text.slice(domainExists);
item.title.text = item.title.text.replace(domain, '');
item.domain = domain.replace('(', '').replace(')', '');
}
item.url = item.title.href;
item.title = item.title.text;
item.time = item.time.replace('hrs', 'hours').replace('mins', 'minutes');
item.time_ago = calculateTimeAgo(item.time);
item.author = item.author.text;
item.comments = item.comments.text;
item.points_text = item.points.text;
item.points = parseInt(item.points_text) * 10 // Give Designer News more weight;
designerNews.push(item);
}
designerNewsLoaded = true;
if (hackerNewsLoaded) {
combineNews();
}
},
error: function (data) {
console.log(data);
}
});
function combineNews () {
$scope.news = $scope.news.concat(hackerNews).concat(designerNews);
$scope.news = _.sortBy($scope.news, function (item) {
return item.points;
});
$scope.news.reverse();
$scope.loaded = true;
$scope.displayNews($scope.defaultNews);
var i = 0;
$('.builder-news').addClass('loaded');
$scope.$apply();
}
$scope.setDefaultLimit = function (number) {
localforage.setItem('defaultLimit', $scope.defaultLimit);
};
$scope.setDefaultNews = function (type) {
localforage.setItem('defaultNews', type);
};
$scope.aboutLinks = [
{
url: 'https://news.ycombinator.com/news',
class: 'fa fa-hacker-news fa-lg hackernews',
text: 'Hacker News Homepage'
},
{
url: 'https://news.layervault.com',
class: 'fa fa-picture-o fa-lg designernews',
text: 'Designer News Homepage'
},
{
url: 'https://github.com/yangshun/builder-news',
class: 'fa fa-github fa-lg',
text: 'Builder News on Github'
},
{
url: 'mailto:[email protected]',
class: 'fa fa-envelope-o fa-lg contact-icon',
text: 'Send Feedback'
}
];
} | Don't hardcode the animations
| js/app.js | Don't hardcode the animations | <ide><path>s/app.js
<ide> all: 'bounceInUp',
<ide> hackernews: 'bounceInLeft',
<ide> designernews: 'bounceInRight'
<del> }
<del> $('.builder-news li').removeClass('animated bounceInUp bounceInLeft bounceInRight');
<add> };
<add> $('.builder-news li').removeClass('animated ' + _.values(animations).join(' '));
<ide> var i = 0;
<ide> setTimeout(function () {
<ide> $('.builder-news li').each(function () { |
|
Java | apache-2.0 | 2e7fa47bcb33cdb88b15f026f6fa324b9a5dde4c | 0 | MICommunity/psi-jami,MICommunity/psi-jami,MICommunity/psi-jami | package psidev.psi.mi.jami.utils;
import psidev.psi.mi.jami.model.CvTerm;
import psidev.psi.mi.jami.model.Interactor;
import psidev.psi.mi.jami.model.impl.DefaultInteractor;
/**
* Factory for interactors
*
* @author Marine Dumousseau ([email protected])
* @version $Id$
* @since <pre>11/02/13</pre>
*/
public class InteractorUtils {
public static Interactor createUnknownBasicInteractor(){
return new DefaultInteractor("unknown", CvTermUtils.createMICvTerm(Interactor.UNKNOWN_INTERACTOR, Interactor.UNKNOWN_INTERACTOR_MI));
}
/**
* To know if an interactor have a specific interactor type.
* @param interactor
* @param typeId
* @param typeName
* @return true if the interactor has the type with given name/identifier
*/
public static boolean doesInteractorHaveType(Interactor interactor, String typeId, String typeName){
if (interactor == null || (typeName == null && typeId == null)){
return false;
}
CvTerm type = interactor.getInteractorType();
if (type == null){
return false;
}
// we can compare identifiers
if (typeId != null && type.getMIIdentifier() != null){
// we have the same type id
return type.getMIIdentifier().equals(typeId);
}
// we need to compare type names
else if (typeName != null) {
return typeName.toLowerCase().trim().equals(type.getShortName().toLowerCase().trim());
}
return false;
}
}
| jami-core/src/main/java/psidev/psi/mi/jami/utils/InteractorUtils.java | package psidev.psi.mi.jami.utils;
import psidev.psi.mi.jami.model.Interactor;
import psidev.psi.mi.jami.model.impl.DefaultInteractor;
/**
* Factory for interactors
*
* @author Marine Dumousseau ([email protected])
* @version $Id$
* @since <pre>11/02/13</pre>
*/
public class InteractorUtils {
public static Interactor createUnknownBasicInteractor(){
return new DefaultInteractor("unknown", CvTermUtils.createMICvTerm(Interactor.UNKNOWN_INTERACTOR, Interactor.UNKNOWN_INTERACTOR_MI));
}
}
| Added a utility method in InteractorUtils | jami-core/src/main/java/psidev/psi/mi/jami/utils/InteractorUtils.java | Added a utility method in InteractorUtils | <ide><path>ami-core/src/main/java/psidev/psi/mi/jami/utils/InteractorUtils.java
<ide> package psidev.psi.mi.jami.utils;
<ide>
<add>import psidev.psi.mi.jami.model.CvTerm;
<ide> import psidev.psi.mi.jami.model.Interactor;
<ide> import psidev.psi.mi.jami.model.impl.DefaultInteractor;
<ide>
<ide> public static Interactor createUnknownBasicInteractor(){
<ide> return new DefaultInteractor("unknown", CvTermUtils.createMICvTerm(Interactor.UNKNOWN_INTERACTOR, Interactor.UNKNOWN_INTERACTOR_MI));
<ide> }
<add>
<add> /**
<add> * To know if an interactor have a specific interactor type.
<add> * @param interactor
<add> * @param typeId
<add> * @param typeName
<add> * @return true if the interactor has the type with given name/identifier
<add> */
<add> public static boolean doesInteractorHaveType(Interactor interactor, String typeId, String typeName){
<add>
<add> if (interactor == null || (typeName == null && typeId == null)){
<add> return false;
<add> }
<add>
<add> CvTerm type = interactor.getInteractorType();
<add> if (type == null){
<add> return false;
<add> }
<add>
<add> // we can compare identifiers
<add> if (typeId != null && type.getMIIdentifier() != null){
<add> // we have the same type id
<add> return type.getMIIdentifier().equals(typeId);
<add> }
<add> // we need to compare type names
<add> else if (typeName != null) {
<add> return typeName.toLowerCase().trim().equals(type.getShortName().toLowerCase().trim());
<add> }
<add>
<add> return false;
<add> }
<ide> } |
|
JavaScript | apache-2.0 | 3dac7f6f06e84b792b3ab60ff05eb4b362f021f4 | 0 | vire/reality-plugin,vire/reality-plugin,realreality/reality-plugin,realreality/reality-plugin | import moment from 'moment';
import { GMAPS_API_KEY, MAPS_URL } from '../rr';
import RR from '../rr';
import { ga } from '../utils';
const loadAvailability = function(travelMode, fromAddress, toAddress) {
const DEPARTURE_TIME = moment()
/* we need this date to be stable at least during a month because of caching,
1 month in future seems as maximum for transit data */
.startOf('month').add(1, 'weeks')
.isoWeekday('Monday').startOf('day')
.hours(8).minutes(0); /* assume that on monday 8:30 will be worst traffic */
RR.logDebug('Availability Departure time: ', DEPARTURE_TIME.toObject());
const DIST_MATRIX_URL = `${MAPS_URL}/distancematrix/json`;
let distanceMatrixApiUrl = DIST_MATRIX_URL + '?origins=' + encodeURI(fromAddress) +
'&destinations=' + encodeURI(toAddress) +
'&mode=' + travelMode +
'&departure_time=' + DEPARTURE_TIME.unix() +
'&language=cs&key=' + GMAPS_API_KEY;
if (travelMode === 'driving') {
distanceMatrixApiUrl += '&traffic_model=pessimistic';
}
return fetch(distanceMatrixApiUrl).then(response => response.json());
};
export const AvailabilityComponent = {
template: '#availability-component',
props: ['pois', 'label', 'type', 'addressFrom'],
data: function() {
return {
showInput: false,
newPoiAddress: '',
enrichedPois: []
};
},
methods: {
showInputBox: function(event) {
RR.logDebug('Showing input box');
this.showInput = true;
},
hideInputBox: function(event) {
RR.logDebug('Hiding input box');
this.showInput = false;
},
cancelInputBox: function(event) {
RR.logDebug('Cancelling input box');
ga('rr.send', 'event', 'Availibility-Component', 'cancel-input-box-clicked'); /* TODO: mbernhard - should be propagated as an event and ga called in event handler to decouple GA code and component */
this.hideInputBox();
this.newPoiAddress = '';
},
addPoi: function(event) {
const newPoiAddress = event.target.value;
this.$emit('poi-added', newPoiAddress, this.type);
this.hideInputBox();
this.newPoiAddress = '';
},
removePoi: function(poi, index) {
this.$emit('poi-removed', poi, index);
}
},
watch: {
pois: function(pois) {
this.enrichedPois = [];
pois.forEach((element, index, array) => {
const addressTo = element.address.input;
const addressFrom = this.addressFrom;
const poiCopy = $.extend({}, element);
poiCopy.duration = 'N/A';
poiCopy.address.interpreted = 'N/A';
this.enrichedPois.splice(index, 1, poiCopy);
RR.logDebug('Loading ', this.type, ' data from:', addressFrom, 'to: ', addressTo);
loadAvailability(this.type, addressFrom, addressTo)
.then((data) => {
RR.logDebug(this.type, ' data response: ', data);
const poiCopy = $.extend({}, element);
try {
const distancesArray = data.rows[0].elements;
const distance = distancesArray[0];
poiCopy.address.interpreted = data.destination_addresses[0];
poiCopy.duration = distance.duration.text;
} catch (ex) {
RR.logError('Error when parsing availibility data: ', ex);
}
this.enrichedPois.splice(index, 1, poiCopy);
});
});
}
}
};
| src/js/components/Availability.js | import moment from 'moment';
import { GMAPS_API_KEY, MAPS_URL } from '../rr';
import RR from '../rr';
import { ga } from '../utils';
const loadAvailability = function(travelMode, fromAddress, toAddress) {
const DEPARTURE_TIME = moment()
/* we need this date to be stable at least during a month because of caching,
1 month in future seems as maximum for transit data */
.startOf('month').add(1, 'weeks').add(2, 'months')
.isoWeekday('Monday').startOf('day')
.hours(8).minutes(0); /* assume that on monday 8:30 will be worst traffic */
RR.logDebug('Availability Departure time: ', DEPARTURE_TIME.toObject());
const DIST_MATRIX_URL = `${MAPS_URL}/distancematrix/json`;
const distanceMatrixApiUrl = DIST_MATRIX_URL + '?origins=' + encodeURI(fromAddress) +
'&destinations=' + encodeURI(toAddress) +
'&mode=' + travelMode +
'&departure_time=' + DEPARTURE_TIME.unix() +
'&language=cs&key=' + GMAPS_API_KEY;
return fetch(distanceMatrixApiUrl).then(response => response.json());
};
export const AvailabilityComponent = {
template: '#availability-component',
props: ['pois', 'label', 'type', 'addressFrom'],
data: function() {
return {
showInput: false,
newPoiAddress: '',
enrichedPois: []
};
},
methods: {
showInputBox: function(event) {
RR.logDebug('Showing input box');
this.showInput = true;
},
hideInputBox: function(event) {
RR.logDebug('Hiding input box');
this.showInput = false;
},
cancelInputBox: function(event) {
RR.logDebug('Cancelling input box');
ga('rr.send', 'event', 'Availibility-Component', 'cancel-input-box-clicked'); /* TODO: mbernhard - should be propagated as an event and ga called in event handler to decouple GA code and component */
this.hideInputBox();
this.newPoiAddress = '';
},
addPoi: function(event) {
const newPoiAddress = event.target.value;
this.$emit('poi-added', newPoiAddress, this.type);
this.hideInputBox();
this.newPoiAddress = '';
},
removePoi: function(poi, index) {
this.$emit('poi-removed', poi, index);
}
},
watch: {
pois: function(pois) {
this.enrichedPois = [];
pois.forEach((element, index, array) => {
const addressTo = element.address.input;
const addressFrom = this.addressFrom;
const poiCopy = $.extend({}, element);
poiCopy.duration = 'N/A';
poiCopy.address.interpreted = 'N/A';
this.enrichedPois.splice(index, 1, poiCopy);
RR.logDebug('Loading ', this.type, ' data from:', addressFrom, 'to: ', addressTo);
loadAvailability(this.type, addressFrom, addressTo)
.then((data) => {
RR.logDebug(this.type, ' data response: ', data);
const poiCopy = $.extend({}, element);
try {
const distancesArray = data.rows[0].elements;
const distance = distancesArray[0];
poiCopy.address.interpreted = data.destination_addresses[0];
poiCopy.duration = distance.duration.text;
} catch (ex) {
RR.logError('Error when parsing availibility data: ', ex);
}
this.enrichedPois.splice(index, 1, poiCopy);
});
});
}
}
};
| fix #61 nekdy se nezobrazuje dostupnost MHD
| src/js/components/Availability.js | fix #61 nekdy se nezobrazuje dostupnost MHD | <ide><path>rc/js/components/Availability.js
<ide> const DEPARTURE_TIME = moment()
<ide> /* we need this date to be stable at least during a month because of caching,
<ide> 1 month in future seems as maximum for transit data */
<del> .startOf('month').add(1, 'weeks').add(2, 'months')
<add> .startOf('month').add(1, 'weeks')
<ide> .isoWeekday('Monday').startOf('day')
<ide> .hours(8).minutes(0); /* assume that on monday 8:30 will be worst traffic */
<ide> RR.logDebug('Availability Departure time: ', DEPARTURE_TIME.toObject());
<ide>
<ide> const DIST_MATRIX_URL = `${MAPS_URL}/distancematrix/json`;
<del> const distanceMatrixApiUrl = DIST_MATRIX_URL + '?origins=' + encodeURI(fromAddress) +
<add> let distanceMatrixApiUrl = DIST_MATRIX_URL + '?origins=' + encodeURI(fromAddress) +
<ide> '&destinations=' + encodeURI(toAddress) +
<ide> '&mode=' + travelMode +
<ide> '&departure_time=' + DEPARTURE_TIME.unix() +
<ide> '&language=cs&key=' + GMAPS_API_KEY;
<del>
<add>
<add> if (travelMode === 'driving') {
<add> distanceMatrixApiUrl += '&traffic_model=pessimistic';
<add> }
<add>
<ide> return fetch(distanceMatrixApiUrl).then(response => response.json());
<ide> };
<ide> |
|
Java | bsd-3-clause | error: pathspec 'core/src/main/java/org/hisp/dhis/android/core/imports/TrackerImportConflictStore.java' did not match any file(s) known to git
| 22ce8b27571256b2b89cba8fdd57ee15112a0be0 | 1 | dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk,dhis2/dhis2-android-sdk | /*
* Copyright (c) 2004-2019, 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.android.core.imports;
import org.hisp.dhis.android.core.arch.db.binders.StatementBinder;
import org.hisp.dhis.android.core.common.ObjectStore;
import org.hisp.dhis.android.core.common.StoreFactory;
import org.hisp.dhis.android.core.data.database.DatabaseAdapter;
import static org.hisp.dhis.android.core.utils.StoreUtils.sqLiteBind;
public final class TrackerImportConflictStore {
private static final StatementBinder<TrackerImportConflict> BINDER = (o, sqLiteStatement) -> {
sqLiteBind(sqLiteStatement, 1, o.conflict());
sqLiteBind(sqLiteStatement, 2, o.value());
sqLiteBind(sqLiteStatement, 3, o.trackedEntityInstance());
sqLiteBind(sqLiteStatement, 4, o.enrollment());
sqLiteBind(sqLiteStatement, 5, o.event());
sqLiteBind(sqLiteStatement, 6, o.tableReference());
sqLiteBind(sqLiteStatement, 7, o.errorCode());
sqLiteBind(sqLiteStatement, 8, o.status());
sqLiteBind(sqLiteStatement, 9, o.created());
};
private TrackerImportConflictStore() {
}
public static ObjectStore<TrackerImportConflict> create(DatabaseAdapter databaseAdapter) {
return StoreFactory.objectStore(databaseAdapter, TrackerImportConflictTableInfo.TABLE_INFO, BINDER,
TrackerImportConflict::create);
}
} | core/src/main/java/org/hisp/dhis/android/core/imports/TrackerImportConflictStore.java | [ANDROSDK-772] Add TrackerImportConflictStore
| core/src/main/java/org/hisp/dhis/android/core/imports/TrackerImportConflictStore.java | [ANDROSDK-772] Add TrackerImportConflictStore | <ide><path>ore/src/main/java/org/hisp/dhis/android/core/imports/TrackerImportConflictStore.java
<add>/*
<add> * Copyright (c) 2004-2019, University of Oslo
<add> * All rights reserved.
<add> *
<add> * Redistribution and use in source and binary forms, with or without
<add> * modification, are permitted provided that the following conditions are met:
<add> * Redistributions of source code must retain the above copyright notice, this
<add> * list of conditions and the following disclaimer.
<add> *
<add> * Redistributions in binary form must reproduce the above copyright notice,
<add> * this list of conditions and the following disclaimer in the documentation
<add> * and/or other materials provided with the distribution.
<add> * Neither the name of the HISP project nor the names of its contributors may
<add> * be used to endorse or promote products derived from this software without
<add> * specific prior written permission.
<add> *
<add> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
<add> * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
<add> * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
<add> * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
<add> * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
<add> * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
<add> * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
<add> * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
<add> * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
<add> * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<add> */
<add>
<add>package org.hisp.dhis.android.core.imports;
<add>
<add>import org.hisp.dhis.android.core.arch.db.binders.StatementBinder;
<add>import org.hisp.dhis.android.core.common.ObjectStore;
<add>import org.hisp.dhis.android.core.common.StoreFactory;
<add>import org.hisp.dhis.android.core.data.database.DatabaseAdapter;
<add>
<add>import static org.hisp.dhis.android.core.utils.StoreUtils.sqLiteBind;
<add>
<add>public final class TrackerImportConflictStore {
<add>
<add> private static final StatementBinder<TrackerImportConflict> BINDER = (o, sqLiteStatement) -> {
<add> sqLiteBind(sqLiteStatement, 1, o.conflict());
<add> sqLiteBind(sqLiteStatement, 2, o.value());
<add> sqLiteBind(sqLiteStatement, 3, o.trackedEntityInstance());
<add> sqLiteBind(sqLiteStatement, 4, o.enrollment());
<add> sqLiteBind(sqLiteStatement, 5, o.event());
<add> sqLiteBind(sqLiteStatement, 6, o.tableReference());
<add> sqLiteBind(sqLiteStatement, 7, o.errorCode());
<add> sqLiteBind(sqLiteStatement, 8, o.status());
<add> sqLiteBind(sqLiteStatement, 9, o.created());
<add> };
<add>
<add> private TrackerImportConflictStore() {
<add> }
<add>
<add> public static ObjectStore<TrackerImportConflict> create(DatabaseAdapter databaseAdapter) {
<add> return StoreFactory.objectStore(databaseAdapter, TrackerImportConflictTableInfo.TABLE_INFO, BINDER,
<add> TrackerImportConflict::create);
<add> }
<add>} |
|
Java | apache-2.0 | 92f40eefd744657dd4707c4b0fc56c291f42b732 | 0 | OpenHFT/Chronicle-Wire,OpenHFT/Chronicle-Wire | /*
* Copyright 2016 higherfrequencytrading.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 net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.BytesIn;
import net.openhft.chronicle.bytes.BytesOut;
import net.openhft.chronicle.core.io.IORuntimeException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.function.Supplier;
/*
* Created by Peter Lawrey on 27/03/16.
*/
public class VanillaMessageHistory extends AbstractMarshallable implements MessageHistory {
public static final int MESSAGE_HISTORY_LENGTH = 20;
private static final ThreadLocal<MessageHistory> THREAD_LOCAL =
ThreadLocal.withInitial((Supplier<MessageHistory>) () -> {
@NotNull VanillaMessageHistory veh = new VanillaMessageHistory();
veh.addSourceDetails(true);
return veh;
});
private int sources;
@NotNull
private int[] sourceIdArray = new int[MESSAGE_HISTORY_LENGTH];
@NotNull
private long[] sourceIndexArray = new long[MESSAGE_HISTORY_LENGTH];
private int timings;
@NotNull
private long[] timingsArray = new long[MESSAGE_HISTORY_LENGTH * 2];
private boolean addSourceDetails = false;
static MessageHistory getThreadLocal() {
return THREAD_LOCAL.get();
}
static void setThreadLocal(MessageHistory md) {
THREAD_LOCAL.set(md);
}
public void addSourceDetails(boolean addSourceDetails) {
this.addSourceDetails = addSourceDetails;
}
@Override
public void reset() {
sources = timings = 0;
}
@Override
public void reset(int sourceId, long sourceIndex) {
sources = 1;
sourceIdArray[0] = sourceId;
sourceIndexArray[0] = sourceIndex;
timings = 1;
timingsArray[0] = System.nanoTime();
}
@Override
public int lastSourceId() {
return sources <= 0 ? -1 : sourceIdArray[sources - 1];
}
@Override
public long lastSourceIndex() {
return sources <= 0 ? -1 : sourceIndexArray[sources - 1];
}
@Override
public int timings() {
return timings;
}
@Override
public long timing(int n) {
return timingsArray[n];
}
@Override
public int sources() {
return sources;
}
@Override
public int sourceId(int n) {
return sourceIdArray[n];
}
@Override
public long sourceIndex(int n) {
return sourceIndexArray[n];
}
@Override
public void readMarshallable(@NotNull WireIn wire) throws IORuntimeException {
sources = 0;
wire.read(() -> "sources").sequence(this, (t, in) -> {
while (in.hasNextSequenceItem()) {
t.addSource(in.int32(), in.int64());
}
});
timings = 0;
wire.read(() -> "timings").sequence(this, (t, in) -> {
while (in.hasNextSequenceItem()) {
t.addTiming(in.int64());
}
});
if (addSourceDetails) {
@Nullable Object o = wire.parent();
if (o instanceof SourceContext) {
@Nullable SourceContext dc = (SourceContext) o;
addSource(dc.sourceId(), dc.index());
}
addTiming(System.nanoTime());
}
}
@Override
public void writeMarshallable(@NotNull WireOut wire) {
wire.write("sources").sequence(this, (t, out) -> {
for (int i = 0; i < t.sources; i++) {
out.uint32(t.sourceIdArray[i]);
out.int64_0x(t.sourceIndexArray[i]);
}
});
wire.write("timings").sequence(this, (t, out) -> {
for (int i = 0; i < t.timings; i++) {
out.int64(t.timingsArray[i]);
}
out.int64(System.nanoTime());
});
}
@Override
public void readMarshallable(@NotNull BytesIn bytes) throws IORuntimeException {
sources = bytes.readUnsignedByte();
for (int i = 0; i < sources; i++)
sourceIdArray[i] = bytes.readInt();
for (int i = 0; i < sources; i++)
sourceIndexArray[i] = bytes.readLong();
timings = bytes.readUnsignedByte();
for (int i = 0; i < timings; i++)
timingsArray[i] = bytes.readLong();
}
@Override
public void writeMarshallable(@NotNull BytesOut bytes) {
bytes.writeUnsignedByte(sources);
for (int i = 0; i < sources; i++)
bytes.writeInt(sourceIdArray[i]);
for (int i = 0; i < sources; i++)
bytes.writeLong(sourceIndexArray[i]);
bytes.writeUnsignedByte(timings + 1 );// one more time for this output
for (int i = 0; i < timings; i++) {
bytes.writeLong(timingsArray[i]);
}
bytes.writeLong(System.nanoTime()); // add time for this output
}
public void addSource(int id, long index) {
sourceIdArray[sources] = id;
sourceIndexArray[sources++] = index;
}
public void addTiming(long l) {
if (timings >= timingsArray.length) {
throw new IllegalStateException("Have exceeded message history size: " + this.toString());
}
timingsArray[timings++] = l;
}
}
| src/main/java/net/openhft/chronicle/wire/VanillaMessageHistory.java | /*
* Copyright 2016 higherfrequencytrading.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 net.openhft.chronicle.wire;
import net.openhft.chronicle.bytes.BytesIn;
import net.openhft.chronicle.bytes.BytesOut;
import net.openhft.chronicle.core.io.IORuntimeException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.function.Supplier;
/*
* Created by Peter Lawrey on 27/03/16.
*/
public class VanillaMessageHistory extends AbstractMarshallable implements MessageHistory {
public static final int MESSAGE_HISTORY_LENGTH = 20;
private static final ThreadLocal<MessageHistory> THREAD_LOCAL =
ThreadLocal.withInitial((Supplier<MessageHistory>) () -> {
@NotNull VanillaMessageHistory veh = new VanillaMessageHistory();
veh.addSourceDetails(true);
return veh;
});
private int sources;
@NotNull
private int[] sourceIdArray = new int[MESSAGE_HISTORY_LENGTH];
@NotNull
private long[] sourceIndexArray = new long[MESSAGE_HISTORY_LENGTH];
private int timings;
@NotNull
private long[] timingsArray = new long[MESSAGE_HISTORY_LENGTH * 2];
private boolean addSourceDetails = false;
static MessageHistory getThreadLocal() {
return THREAD_LOCAL.get();
}
static void setThreadLocal(MessageHistory md) {
THREAD_LOCAL.set(md);
}
public void addSourceDetails(boolean addSourceDetails) {
this.addSourceDetails = addSourceDetails;
}
@Override
public void reset() {
sources = timings = 0;
}
@Override
public void reset(int sourceId, long sourceIndex) {
sources = 1;
sourceIdArray[0] = sourceId;
sourceIndexArray[0] = sourceIndex;
timings = 1;
timingsArray[0] = System.nanoTime();
}
@Override
public int lastSourceId() {
return sources <= 0 ? -1 : sourceIdArray[sources - 1];
}
@Override
public long lastSourceIndex() {
return sources <= 0 ? -1 : sourceIndexArray[sources - 1];
}
@Override
public int timings() {
return timings;
}
@Override
public long timing(int n) {
return timingsArray[n];
}
@Override
public int sources() {
return sources;
}
@Override
public int sourceId(int n) {
return sourceIdArray[n];
}
@Override
public long sourceIndex(int n) {
return sourceIndexArray[n];
}
@Override
public void readMarshallable(@NotNull WireIn wire) throws IORuntimeException {
sources = 0;
wire.read(() -> "sources").sequence(this, (t, in) -> {
while (in.hasNextSequenceItem()) {
t.addSource(in.int32(), in.int64());
}
});
timings = 0;
wire.read(() -> "timings").sequence(this, (t, in) -> {
while (in.hasNextSequenceItem()) {
t.addTiming(in.int64());
}
});
if (addSourceDetails) {
@Nullable Object o = wire.parent();
if (o instanceof SourceContext) {
@Nullable SourceContext dc = (SourceContext) o;
addSource(dc.sourceId(), dc.index());
}
addTiming(System.nanoTime());
}
}
@Override
public void writeMarshallable(@NotNull WireOut wire) {
wire.write("sources").sequence(this, (t, out) -> {
for (int i = 0; i < t.sources; i++) {
out.uint32(t.sourceIdArray[i]);
out.int64_0x(t.sourceIndexArray[i]);
}
});
wire.write("timings").sequence(this, (t, out) -> {
for (int i = 0; i < t.timings; i++) {
out.int64(t.timingsArray[i]);
}
out.int64(System.nanoTime());
});
}
@Override
public void readMarshallable(@NotNull BytesIn bytes) throws IORuntimeException {
sources = bytes.readUnsignedByte();
for (int i = 0; i < sources; i++)
sourceIdArray[i] = bytes.readInt();
for (int i = 0; i < sources; i++)
sourceIndexArray[i] = bytes.readLong();
timings = bytes.readUnsignedByte();
for (int i = 0; i < timings; i++)
timingsArray[i] = bytes.readLong();
}
@Override
public void writeMarshallable(@NotNull BytesOut bytes) {
bytes.writeUnsignedByte(sources);
for (int i = 0; i < sources; i++)
bytes.writeInt(sourceIdArray[i]);
for (int i = 0; i < sources; i++)
bytes.writeLong(sourceIndexArray[i]);
bytes.writeUnsignedByte(timings);
for (int i = 0; i < timings; i++)
bytes.writeLong(timingsArray[i]);
}
public void addSource(int id, long index) {
sourceIdArray[sources] = id;
sourceIndexArray[sources++] = index;
}
public void addTiming(long l) {
if (timings >= timingsArray.length) {
throw new IllegalStateException("Have exceeded message history size: " + this.toString());
}
timingsArray[timings++] = l;
}
}
| Add timing when writing bytes as per when writing wire.
| src/main/java/net/openhft/chronicle/wire/VanillaMessageHistory.java | Add timing when writing bytes as per when writing wire. | <ide><path>rc/main/java/net/openhft/chronicle/wire/VanillaMessageHistory.java
<ide> for (int i = 0; i < sources; i++)
<ide> bytes.writeLong(sourceIndexArray[i]);
<ide>
<del> bytes.writeUnsignedByte(timings);
<del> for (int i = 0; i < timings; i++)
<add> bytes.writeUnsignedByte(timings + 1 );// one more time for this output
<add> for (int i = 0; i < timings; i++) {
<ide> bytes.writeLong(timingsArray[i]);
<add> }
<add> bytes.writeLong(System.nanoTime()); // add time for this output
<ide> }
<ide>
<ide> public void addSource(int id, long index) { |
|
Java | apache-2.0 | 77d24b6a34465a318170dce25506dc3e16b93ad1 | 0 | dianping/cat,dianping/cat,dianping/cat,dianping/cat,dianping/cat,dianping/cat,dianping/cat | /*
* Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved.
*
* 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 com.dianping.cat.consumer;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.dianping.cat.consumer.core.aggregation.CompositeFormatTest;
import com.dianping.cat.consumer.core.aggregation.DefaultFormatTest;
import com.dianping.cat.consumer.cross.CrossAnalyzerTest;
import com.dianping.cat.consumer.cross.CrossInfoTest;
import com.dianping.cat.consumer.cross.CrossReportMergerTest;
import com.dianping.cat.consumer.event.EventAnalyzerTest;
import com.dianping.cat.consumer.event.EventReportMergerTest;
import com.dianping.cat.consumer.heartbeat.HeartbeatAnalyzerTest;
import com.dianping.cat.consumer.heartbeat.HeartbeatReportMergerTest;
import com.dianping.cat.consumer.matrix.MatrixAnalyzerTest;
import com.dianping.cat.consumer.matrix.MatrixModelTest;
import com.dianping.cat.consumer.matrix.MatrixReportMergerTest;
import com.dianping.cat.consumer.problem.ProblemAnalyzerTest;
import com.dianping.cat.consumer.problem.ProblemFilterTest;
import com.dianping.cat.consumer.problem.ProblemHandlerTest;
import com.dianping.cat.consumer.problem.ProblemReportConvertorTest;
import com.dianping.cat.consumer.problem.ProblemReportMergerTest;
import com.dianping.cat.consumer.problem.ProblemReportTest;
import com.dianping.cat.consumer.state.StateAnalyzerTest;
import com.dianping.cat.consumer.state.StateReportMergerTest;
import com.dianping.cat.consumer.top.TopAnalyzerTest;
import com.dianping.cat.consumer.top.TopReportMergerTest;
import com.dianping.cat.consumer.transaction.TransactionAnalyzerTest;
import com.dianping.cat.consumer.transaction.TransactionReportMergerTest;
import com.dianping.cat.consumer.transaction.TransactionReportTest;
@RunWith(Suite.class)
@SuiteClasses({
ProblemHandlerTest.class,
/* transaction */
TransactionAnalyzerTest.class,
TransactionReportTest.class,
TransactionReportMergerTest.class,
/* event */
EventAnalyzerTest.class,
EventReportMergerTest.class,
/* heartbeat */
HeartbeatAnalyzerTest.class,
HeartbeatReportMergerTest.class,
/* state */
StateAnalyzerTest.class,
StateReportMergerTest.class,
/* top */
TopAnalyzerTest.class,
TopReportMergerTest.class,
/* problem */
ProblemHandlerTest.class,
ProblemReportTest.class,
ProblemAnalyzerTest.class,
ProblemReportMergerTest.class,
CompositeFormatTest.class,
DefaultFormatTest.class,
ProblemFilterTest.class,
//MetricAnalyzerTest.class,
ProblemReportConvertorTest.class,
CrossInfoTest.class,
CrossReportMergerTest.class,
MatrixModelTest.class,
MatrixReportMergerTest.class,
CrossAnalyzerTest.class,
MatrixAnalyzerTest.class, })
public class AllTests {
}
| cat-consumer/src/test/java/com/dianping/cat/consumer/AllTests.java | /*
* Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved.
*
* 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 com.dianping.cat.consumer;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.dianping.cat.consumer.core.aggregation.CompositeFormatTest;
import com.dianping.cat.consumer.core.aggregation.DefaultFormatTest;
import com.dianping.cat.consumer.cross.CrossAnalyzerTest;
import com.dianping.cat.consumer.cross.CrossInfoTest;
import com.dianping.cat.consumer.cross.CrossReportMergerTest;
import com.dianping.cat.consumer.event.EventAnalyzerTest;
import com.dianping.cat.consumer.event.EventReportMergerTest;
import com.dianping.cat.consumer.heartbeat.HeartbeatAnalyzerTest;
import com.dianping.cat.consumer.heartbeat.HeartbeatReportMergerTest;
import com.dianping.cat.consumer.matrix.MatrixAnalyzerTest;
import com.dianping.cat.consumer.matrix.MatrixModelTest;
import com.dianping.cat.consumer.matrix.MatrixReportMergerTest;
import com.dianping.cat.consumer.problem.ProblemAnalyzerTest;
import com.dianping.cat.consumer.problem.ProblemFilterTest;
import com.dianping.cat.consumer.problem.ProblemHandlerTest;
import com.dianping.cat.consumer.problem.ProblemReportConvertorTest;
import com.dianping.cat.consumer.problem.ProblemReportMergerTest;
import com.dianping.cat.consumer.problem.ProblemReportTest;
import com.dianping.cat.consumer.state.StateAnalyzerTest;
import com.dianping.cat.consumer.state.StateReportMergerTest;
import com.dianping.cat.consumer.top.TopAnalyzerTest;
import com.dianping.cat.consumer.top.TopReportMergerTest;
import com.dianping.cat.consumer.transaction.TransactionAnalyzerTest;
import com.dianping.cat.consumer.transaction.TransactionReportMergerTest;
import com.dianping.cat.consumer.transaction.TransactionReportTest;
import com.dianping.cat.consumer.transaction.TransactionReportTypeAggergatorTest;
@RunWith(Suite.class)
@SuiteClasses({
ProblemHandlerTest.class,
/* transaction */
TransactionAnalyzerTest.class,
TransactionReportTest.class,
TransactionReportMergerTest.class,
/* event */
EventAnalyzerTest.class,
EventReportMergerTest.class,
/* heartbeat */
HeartbeatAnalyzerTest.class,
HeartbeatReportMergerTest.class,
/* state */
StateAnalyzerTest.class,
StateReportMergerTest.class,
/* top */
TopAnalyzerTest.class,
TopReportMergerTest.class,
/* problem */
ProblemHandlerTest.class,
ProblemReportTest.class,
ProblemAnalyzerTest.class,
ProblemReportMergerTest.class,
CompositeFormatTest.class,
DefaultFormatTest.class,
TransactionReportTypeAggergatorTest.class,
ProblemFilterTest.class,
//MetricAnalyzerTest.class,
ProblemReportConvertorTest.class,
CrossInfoTest.class,
CrossReportMergerTest.class,
MatrixModelTest.class,
MatrixReportMergerTest.class,
CrossAnalyzerTest.class,
MatrixAnalyzerTest.class, })
public class AllTests {
}
| remove invalid test case
| cat-consumer/src/test/java/com/dianping/cat/consumer/AllTests.java | remove invalid test case | <ide><path>at-consumer/src/test/java/com/dianping/cat/consumer/AllTests.java
<ide> import com.dianping.cat.consumer.transaction.TransactionAnalyzerTest;
<ide> import com.dianping.cat.consumer.transaction.TransactionReportMergerTest;
<ide> import com.dianping.cat.consumer.transaction.TransactionReportTest;
<del>import com.dianping.cat.consumer.transaction.TransactionReportTypeAggergatorTest;
<ide>
<ide> @RunWith(Suite.class)
<ide> @SuiteClasses({
<ide>
<ide> DefaultFormatTest.class,
<ide>
<del> TransactionReportTypeAggergatorTest.class,
<del>
<ide> ProblemFilterTest.class,
<ide>
<ide> //MetricAnalyzerTest.class, |
|
JavaScript | mit | 4357bc400296d88a5a466b5f2ee70fb436174ef6 | 0 | moustacheminer/discordmail,moustacheminer/discordmail | console.log('Welcome to Moustacheminer Server Services');
const r = require('./db');
const path = require('path');
const cors = require('cors');
const i18n = require('i18n');
const api = require('./api');
const url = require('./url');
const docs = require('./docs');
const mail = require('./mail');
const lang = require('./lang');
const auth = require('./auth');
const config = require('config');
const express = require('express');
const discord = require('./discord');
const engines = require('consolidate');
const bodyParser = require('body-parser');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const authentication = require('./auth/auth');
const app = express();
i18n.configure({
directory: path.join(__dirname, '..', 'locales'),
cookie: 'lang',
defaultLocale: 'en-gb',
autoReload: true,
updateFiles: false
});
// Middleware
app.enable('trust proxy')
.use(bodyParser.json({
limit: '20mb'
}))
.use(bodyParser.urlencoded({
extended: true,
limit: '20mb'
}))
.use(cookieParser(config.get('webserver').secret))
.use(session({
secret: config.get('webserver').secret,
resave: true,
saveUninitialized: true,
proxy: true
}))
.use(i18n.init)
.set('views', path.join(__dirname, '/dynamic'))
.engine('html', engines.pug)
.set('view engine', 'html')
.use(cors())
.use(authentication.initialize())
.use(authentication.session())
.use((req, res, next) => {
res.locals.domain = config.get('api').mailgun.domain;
if (req.user) {
r.table('registrations')
.get(req.user.id)
.run(r.conn, (err, result) => {
if (err) {
res.status(500).render('error.pug', { status: 500 });
} else {
req.user.dmail = result;
res.locals.user = req.user;
}
next();
});
} else {
next();
}
})
.get('/', async (req, res) => {
const count = await r.table('registrations').count().run(r.conn);
res.status(200).render('index.pug', {
discord,
count
});
})
.use('/api', api)
.use('/docs', docs)
.use('/url', url)
.use('/mail', mail)
.use('/lang', lang)
.use('/auth', auth)
.use(express.static(path.join(__dirname, '/static')))
.use('*', (req, res) => res.status(404).render('error.pug', { status: 404 }));
console.log('Listening on', config.get('webserver').port);
app.listen(config.get('webserver').port);
| server/index.js | console.log('Welcome to Moustacheminer Server Services');
const config = require('config');
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const engines = require('consolidate');
const path = require('path');
const cors = require('cors');
const i18n = require('i18n');
const discord = require('./discord');
const api = require('./api');
const docs = require('./docs');
const url = require('./url');
const mail = require('./mail');
const lang = require('./lang');
const auth = require('./auth');
const r = require('./db');
const authentication = require('./auth/auth');
const session = require('express-session');
const app = express();
i18n.configure({
directory: path.join(__dirname, '..', 'locales'),
cookie: 'lang',
defaultLocale: 'en-gb',
autoReload: true,
updateFiles: false
});
// Middleware
app.enable('trust proxy')
.use(bodyParser.json({
limit: '20mb'
}))
.use(bodyParser.urlencoded({
extended: true,
limit: '20mb'
}))
.use(cookieParser(config.get('webserver').secret))
.use(session({
secret: config.get('webserver').secret,
resave: true,
saveUninitialized: true,
proxy: true
}))
.use(i18n.init)
.set('views', path.join(__dirname, '/dynamic'))
.engine('html', engines.pug)
.set('view engine', 'html')
.use(cors())
.use(authentication.initialize())
.use(authentication.session())
.use((req, res, next) => {
res.locals.domain = config.get('api').mailgun.domain;
if (req.user) {
r.table('registrations')
.get(req.user.id)
.run(r.conn, (err, result) => {
if (err) {
res.status(500).render('error.pug', { status: 500 });
} else {
req.user.dmail = result;
res.locals.user = req.user;
}
next();
});
} else {
next();
}
})
.get('/', async (req, res) => {
const count = await r.table('registrations').count().run(r.conn);
res.status(200).render('index.pug', {
discord,
count
});
})
.use('/api', api)
.use('/docs', docs)
.use('/url', url)
.use('/mail', mail)
.use('/lang', lang)
.use('/auth', auth)
.use(express.static(path.join(__dirname, '/static')))
.use('*', (req, res) => res.status(404).render('error.pug', { status: 404 }));
console.log('Listening on', config.get('webserver').port);
app.listen(config.get('webserver').port);
| Sort requires in length order
| server/index.js | Sort requires in length order | <ide><path>erver/index.js
<ide> console.log('Welcome to Moustacheminer Server Services');
<ide>
<del>const config = require('config');
<del>const express = require('express');
<del>const bodyParser = require('body-parser');
<del>const cookieParser = require('cookie-parser');
<del>const engines = require('consolidate');
<add>const r = require('./db');
<ide> const path = require('path');
<ide> const cors = require('cors');
<ide> const i18n = require('i18n');
<del>const discord = require('./discord');
<ide> const api = require('./api');
<add>const url = require('./url');
<ide> const docs = require('./docs');
<del>const url = require('./url');
<ide> const mail = require('./mail');
<ide> const lang = require('./lang');
<ide> const auth = require('./auth');
<del>const r = require('./db');
<add>const config = require('config');
<add>const express = require('express');
<add>const discord = require('./discord');
<add>const engines = require('consolidate');
<add>const bodyParser = require('body-parser');
<add>const session = require('express-session');
<add>const cookieParser = require('cookie-parser');
<ide> const authentication = require('./auth/auth');
<del>const session = require('express-session');
<ide>
<ide> const app = express();
<ide> |
|
Java | apache-2.0 | 1cbb2f78890330dd2c3a6cab354336993dfd2a9c | 0 | ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp | /*******************************************************************************
* 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.ofbiz.order.order;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilFormatOut;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilNumber;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.common.DataModelConstants;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntity;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityConditionList;
import org.ofbiz.entity.condition.EntityExpr;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.model.DynamicViewEntity;
import org.ofbiz.entity.model.ModelKeyMap;
import org.ofbiz.entity.util.EntityListIterator;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.product.config.ProductConfigWorker;
import org.ofbiz.product.config.ProductConfigWrapper;
import org.ofbiz.product.product.ProductWorker;
import org.ofbiz.product.store.ProductStoreWorker;
import org.ofbiz.security.Security;
import org.ofbiz.service.LocalDispatcher;
import sun.net.www.content.text.Generic;
/**
* Utility class for easily extracting important information from orders
*
* <p>NOTE: in the current scheme order adjustments are never included in tax or shipping,
* but order item adjustments ARE included in tax and shipping calcs unless they are
* tax or shipping adjustments or the includeInTax or includeInShipping are set to N.</p>
*/
public class OrderReadHelper {
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
// scales and rounding modes for BigDecimal math
public static final int scale = UtilNumber.getBigDecimalScale("order.decimals");
public static final RoundingMode rounding = UtilNumber.getRoundingMode("order.rounding");
public static final int taxCalcScale = UtilNumber.getBigDecimalScale("salestax.calc.decimals");
public static final int taxFinalScale = UtilNumber.getBigDecimalScale("salestax.final.decimals");
public static final RoundingMode taxRounding = UtilNumber.getRoundingMode("salestax.rounding");
public static final BigDecimal ZERO = (BigDecimal.ZERO).setScale(scale, rounding);
public static final BigDecimal percentage = (new BigDecimal("0.01")).setScale(scale, rounding);
/**
* SCIPIO: Custom flag used to determine whether only one subscription is allowed per order or not.
*/
public static final boolean subscriptionSingleOrderItem = UtilProperties.getPropertyAsBoolean("order", "order.item.subscription.singleOrderItem", false);
/**
* SCIPIO: Sales channels which only fully work with a webSiteId on OrderHeader.
* @see #getWebSiteSalesChannelIds
*/
private static final Set<String> webSiteSalesChannelIds = Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(
UtilProperties.getPropertyValue("order", "order.webSiteSalesChannelIds").split(","))));
protected GenericValue orderHeader = null;
protected List<GenericValue> orderItemAndShipGrp = null;
protected List<GenericValue> orderItems = null;
protected List<GenericValue> adjustments = null;
protected List<GenericValue> paymentPrefs = null;
protected List<GenericValue> orderStatuses = null;
protected List<GenericValue> orderItemPriceInfos = null;
protected List<GenericValue> orderItemShipGrpInvResList = null;
protected List<GenericValue> orderItemIssuances = null;
protected List<GenericValue> orderReturnItems = null;
protected Map<GenericValue, List<GenericValue>> orderSubscriptionItems = null; // SCIPIO
protected BigDecimal totalPrice = null;
protected LocalDispatcher dispatcher; // SCIPIO: Optional dispatcher
protected Locale locale; // SCIPIO: Optional locale
protected OrderReadHelper() {}
// SCIPIO: Added dispatcher overload
public OrderReadHelper(LocalDispatcher dispatcher, Locale locale, GenericValue orderHeader, List<GenericValue> adjustments, List<GenericValue> orderItems) {
this.dispatcher = dispatcher; // SCIPIO
this.locale = locale;
this.orderHeader = orderHeader;
this.adjustments = adjustments;
this.orderItems = orderItems;
if (this.orderHeader != null && !"OrderHeader".equals(this.orderHeader.getEntityName())) {
try {
this.orderHeader = orderHeader.getDelegator().findOne("OrderHeader", UtilMisc.toMap("orderId",
orderHeader.getString("orderId")), false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
this.orderHeader = null;
}
} else if (this.orderHeader == null && orderItems != null) {
GenericValue firstItem = EntityUtil.getFirst(orderItems);
try {
this.orderHeader = firstItem.getRelatedOne("OrderHeader", false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
this.orderHeader = null;
}
}
if (this.orderHeader == null) {
if (orderHeader == null) {
throw new IllegalArgumentException("Order header passed is null, or is otherwise invalid");
}
throw new IllegalArgumentException("Order header passed in is not valid for orderId [" + orderHeader.getString("orderId") + "]");
}
}
public OrderReadHelper(GenericValue orderHeader, List<GenericValue> adjustments, List<GenericValue> orderItems) {
this(null, null, orderHeader, adjustments, orderItems); // SCIPIO: delegating
}
public OrderReadHelper(LocalDispatcher dispatcher, Locale locale, GenericValue orderHeader) { // SCIPIO: Added dispatcher overload
this(dispatcher, locale, orderHeader, null, null);
}
public OrderReadHelper(GenericValue orderHeader) {
this(orderHeader, null, null);
}
public OrderReadHelper(LocalDispatcher dispatcher, Locale locale, List<GenericValue> adjustments, List<GenericValue> orderItems) { // SCIPIO: Added dispatcher overload
this.dispatcher = dispatcher;
this.locale = locale;
this.adjustments = adjustments;
this.orderItems = orderItems;
}
public OrderReadHelper(List<GenericValue> adjustments, List<GenericValue> orderItems) {
this((LocalDispatcher) null, (Locale) null, adjustments, orderItems); // SCIPIO: delegating
}
public OrderReadHelper(Delegator delegator, LocalDispatcher dispatcher, Locale locale, String orderId) { // SCIPIO: Added dispatcher overload
this.dispatcher = dispatcher;
this.locale = locale;
try {
this.orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
} catch (GenericEntityException e) {
String errMsg = "Error finding order with ID [" + orderId + "]: " + e.toString();
Debug.logError(e, errMsg, module);
throw new IllegalArgumentException(errMsg);
}
if (this.orderHeader == null) {
throw new IllegalArgumentException("Order not found with orderId [" + orderId + "]");
}
}
public OrderReadHelper(Delegator delegator, String orderId) {
this(delegator, null, null, orderId); // SCIPIO: delegating
}
// ==========================================
// ========== Generic Methods (SCIPIO) ======
// ==========================================
/**
* SCIPIO: Returns the delegator (for the order header).
*/
protected Delegator getDelegator() {
return orderHeader.getDelegator();
}
/**
* SCIPIO: Returns the dispatcher IF present (may be null!).
*/
protected LocalDispatcher getDispatcher() {
return dispatcher;
}
/**
* SCIPIO: Returns the "current" display locale IF present (may be null!).
*/
protected Locale getLocale() {
return locale;
}
// ==========================================
// ========== Order Header Methods ==========
// ==========================================
public String getOrderId() {
return orderHeader.getString("orderId");
}
public String getWebSiteId() {
return orderHeader.getString("webSiteId");
}
/**
* SCIPIO: Returns the OrderHeader.webSiteId field if set;
* otherwise returns the default website associated with the
* ProductStore pointed to by OrderHeader.productStoreId.
* <p>
* The default website is the one marked with WebSite.isStoreDefault Y
* OR if the store only has one website, that website is returned.
* <p>
* <strong>NOTE:</strong> If there are multiple WebSites but none is marked with isStoreDefault Y,
* logs a warning and returns null - by design - in a frontend environment there must be no ambiguity as to which
* store should be used by default! (Otherwise, if ambiguous, could be picking a WebSite
* intended for backend usage only, e.g. cms preview!)
* <p>
* Added 2018-10-02.
*/
public String getWebSiteIdOrStoreDefault() {
String webSiteId = getWebSiteId();
if (webSiteId == null) {
String productStoreId = getProductStoreId();
if (productStoreId != null) {
webSiteId = ProductStoreWorker.getStoreDefaultWebSiteId(orderHeader.getDelegator(),
productStoreId, true);
}
}
return webSiteId;
}
public String getProductStoreId() {
return orderHeader.getString("productStoreId");
}
/**
* Returns the ProductStore of this Order or null in case of Exception
*/
public GenericValue getProductStore() {
String productStoreId = orderHeader.getString("productStoreId");
try {
Delegator delegator = orderHeader.getDelegator();
GenericValue productStore = EntityQuery.use(delegator).from("ProductStore").where("productStoreId", productStoreId).cache().queryOne();
return productStore;
} catch (GenericEntityException ex) {
Debug.logError(ex, "Failed to get product store for order header [" + orderHeader + "] due to exception " + ex.getMessage(), module);
return null;
}
}
public String getOrderTypeId() {
return orderHeader.getString("orderTypeId");
}
public String getCurrency() {
return orderHeader.getString("currencyUom");
}
public String getOrderName() {
return orderHeader.getString("orderName");
}
public List<GenericValue> getAdjustments() {
if (adjustments == null) {
try {
adjustments = orderHeader.getRelated("OrderAdjustment", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (adjustments == null) {
adjustments = new ArrayList<>();
}
}
return adjustments;
}
public List<GenericValue> getPaymentPreferences() {
if (paymentPrefs == null) {
try {
paymentPrefs = orderHeader.getRelated("OrderPaymentPreference", null, UtilMisc.toList("orderPaymentPreferenceId"), false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
return paymentPrefs;
}
/**
* Returns a Map of paymentMethodId -> amount charged (BigDecimal) based on PaymentGatewayResponse.
* @return returns a Map of paymentMethodId -> amount charged (BigDecimal) based on PaymentGatewayResponse.
*/
public Map<String, BigDecimal> getReceivedPaymentTotalsByPaymentMethod() {
Map<String, BigDecimal> paymentMethodAmounts = new HashMap<>();
List<GenericValue> paymentPrefs = getPaymentPreferences();
for (GenericValue paymentPref : paymentPrefs) {
List<GenericValue> payments = new ArrayList<>();
try {
List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PMNT_RECEIVED"),
EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PMNT_CONFIRMED"));
payments = paymentPref.getRelated("Payment", null, null, false);
payments = EntityUtil.filterByOr(payments, exprs);
List<EntityExpr> conds = UtilMisc.toList(EntityCondition.makeCondition("paymentTypeId", EntityOperator.EQUALS, "CUSTOMER_PAYMENT"),
EntityCondition.makeCondition("paymentTypeId", EntityOperator.EQUALS, "CUSTOMER_DEPOSIT"),
EntityCondition.makeCondition("paymentTypeId", EntityOperator.EQUALS, "INTEREST_RECEIPT"),
EntityCondition.makeCondition("paymentTypeId", EntityOperator.EQUALS, "GC_DEPOSIT"),
EntityCondition.makeCondition("paymentTypeId", EntityOperator.EQUALS, "POS_PAID_IN"));
payments = EntityUtil.filterByOr(payments, conds);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
BigDecimal chargedToPaymentPref = ZERO;
for (GenericValue payment : payments) {
if (payment.get("amount") != null) {
chargedToPaymentPref = chargedToPaymentPref.add(payment.getBigDecimal("amount")).setScale(scale+1, rounding);
}
}
if (chargedToPaymentPref.compareTo(ZERO) > 0) {
// key of the resulting map is paymentMethodId or paymentMethodTypeId if the paymentMethodId is not available
String paymentMethodKey = paymentPref.getString("paymentMethodId") != null ? paymentPref.getString("paymentMethodId") : paymentPref.getString("paymentMethodTypeId");
if (paymentMethodAmounts.containsKey(paymentMethodKey)) {
BigDecimal value = paymentMethodAmounts.get(paymentMethodKey);
if (value != null) {
chargedToPaymentPref = chargedToPaymentPref.add(value);
}
}
paymentMethodAmounts.put(paymentMethodKey, chargedToPaymentPref.setScale(scale, rounding));
}
}
return paymentMethodAmounts;
}
/**
* Returns a Map of paymentMethodId -> amount refunded
* @return returns a Map of paymentMethodId -> amount refunded
*/
public Map<String, BigDecimal> getReturnedTotalsByPaymentMethod() {
Map<String, BigDecimal> paymentMethodAmounts = new HashMap<>();
List<GenericValue> paymentPrefs = getPaymentPreferences();
for (GenericValue paymentPref : paymentPrefs) {
List<GenericValue> returnItemResponses = new ArrayList<>();
try {
returnItemResponses = orderHeader.getDelegator().findByAnd("ReturnItemResponse", UtilMisc.toMap("orderPaymentPreferenceId", paymentPref.getString("orderPaymentPreferenceId")), null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
BigDecimal refundedToPaymentPref = ZERO;
for (GenericValue returnItemResponse : returnItemResponses) {
refundedToPaymentPref = refundedToPaymentPref.add(returnItemResponse.getBigDecimal("responseAmount")).setScale(scale+1, rounding);
}
if (refundedToPaymentPref.compareTo(ZERO) == 1) {
String paymentMethodId = paymentPref.getString("paymentMethodId") != null ? paymentPref.getString("paymentMethodId") : paymentPref.getString("paymentMethodTypeId");
paymentMethodAmounts.put(paymentMethodId, refundedToPaymentPref.setScale(scale, rounding));
}
}
return paymentMethodAmounts;
}
public List<GenericValue> getOrderPayments() {
return getOrderPayments(null);
}
public List<GenericValue> getOrderPayments(GenericValue orderPaymentPreference) {
List<GenericValue> orderPayments = new ArrayList<>();
List<GenericValue> prefs = null;
if (orderPaymentPreference == null) {
prefs = getPaymentPreferences();
} else {
prefs = UtilMisc.toList(orderPaymentPreference);
}
if (prefs != null) {
for (GenericValue payPref : prefs) {
try {
orderPayments.addAll(payPref.getRelated("Payment", null, null, false));
} catch (GenericEntityException e) {
Debug.logError(e, module);
return null;
}
}
}
return orderPayments;
}
public List<GenericValue> getOrderStatuses() {
if (orderStatuses == null) {
try {
orderStatuses = orderHeader.getRelated("OrderStatus", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
return orderStatuses;
}
public List<GenericValue> getOrderTerms() {
try {
return orderHeader.getRelated("OrderTerm", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return null;
}
}
/**
* Return the number of days from termDays of first FIN_PAYMENT_TERM
* @return number of days from termDays of first FIN_PAYMENT_TERM
*/
public Long getOrderTermNetDays() {
List<GenericValue> orderTerms = EntityUtil.filterByAnd(getOrderTerms(), UtilMisc.toMap("termTypeId", "FIN_PAYMENT_TERM"));
if (UtilValidate.isEmpty(orderTerms)) {
return null;
} else if (orderTerms.size() > 1) {
Debug.logWarning("Found " + orderTerms.size() + " FIN_PAYMENT_TERM order terms for orderId [" + getOrderId() + "], using the first one ", module);
}
return orderTerms.get(0).getLong("termDays");
}
public String getShippingMethod(String shipGroupSeqId) {
try {
GenericValue shipGroup = orderHeader.getDelegator().findOne("OrderItemShipGroup",
UtilMisc.toMap("orderId", orderHeader.getString("orderId"), "shipGroupSeqId", shipGroupSeqId), false);
if (shipGroup != null) {
GenericValue carrierShipmentMethod = shipGroup.getRelatedOne("CarrierShipmentMethod", false);
if (carrierShipmentMethod != null) {
GenericValue shipmentMethodType = carrierShipmentMethod.getRelatedOne("ShipmentMethodType", false);
if (shipmentMethodType != null) {
return UtilFormatOut.checkNull(shipGroup.getString("carrierPartyId")) + " " +
UtilFormatOut.checkNull(shipmentMethodType.getString("description"));
}
}
return UtilFormatOut.checkNull(shipGroup.getString("carrierPartyId"));
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return "";
}
public String getShippingMethodCode(String shipGroupSeqId) {
try {
GenericValue shipGroup = orderHeader.getDelegator().findOne("OrderItemShipGroup",
UtilMisc.toMap("orderId", orderHeader.getString("orderId"), "shipGroupSeqId", shipGroupSeqId), false);
if (shipGroup != null) {
GenericValue carrierShipmentMethod = shipGroup.getRelatedOne("CarrierShipmentMethod", false);
if (carrierShipmentMethod != null) {
GenericValue shipmentMethodType = carrierShipmentMethod.getRelatedOne("ShipmentMethodType", false);
if (shipmentMethodType != null) {
return UtilFormatOut.checkNull(shipmentMethodType.getString("shipmentMethodTypeId")) + "@" + UtilFormatOut.checkNull(shipGroup.getString("carrierPartyId"));
}
}
return UtilFormatOut.checkNull(shipGroup.getString("carrierPartyId"));
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return "";
}
public boolean hasShippingAddress() {
if (UtilValidate.isNotEmpty(this.getShippingLocations())) {
return true;
}
return false;
}
public boolean hasPhysicalProductItems() throws GenericEntityException {
for (GenericValue orderItem : this.getOrderItems()) {
GenericValue product = orderItem.getRelatedOne("Product", true);
if (product != null) {
GenericValue productType = product.getRelatedOne("ProductType", true);
if ("Y".equals(productType.getString("isPhysical"))) {
return true;
}
}
}
return false;
}
public GenericValue getOrderItemShipGroup(String shipGroupSeqId) {
try {
return orderHeader.getDelegator().findOne("OrderItemShipGroup",
UtilMisc.toMap("orderId", orderHeader.getString("orderId"), "shipGroupSeqId", shipGroupSeqId), false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public List<GenericValue> getOrderItemShipGroups() {
try {
return orderHeader.getRelated("OrderItemShipGroup", null, UtilMisc.toList("shipGroupSeqId"), false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public List<GenericValue> getShippingLocations() {
List<GenericValue> shippingLocations = new ArrayList<>();
List<GenericValue> shippingCms = this.getOrderContactMechs("SHIPPING_LOCATION");
if (shippingCms != null) {
for (GenericValue ocm : shippingCms) {
if (ocm != null) {
try {
GenericValue addr = ocm.getDelegator().findOne("PostalAddress",
UtilMisc.toMap("contactMechId", ocm.getString("contactMechId")), false);
if (addr != null) {
shippingLocations.add(addr);
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
}
}
}
return shippingLocations;
}
public GenericValue getShippingAddress(String shipGroupSeqId) {
try {
GenericValue shipGroup = orderHeader.getDelegator().findOne("OrderItemShipGroup",
UtilMisc.toMap("orderId", orderHeader.getString("orderId"), "shipGroupSeqId", shipGroupSeqId), false);
if (shipGroup != null) {
return shipGroup.getRelatedOne("PostalAddress", false);
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
/** @deprecated */
@Deprecated
public GenericValue getShippingAddress() {
try {
GenericValue orderContactMech = EntityUtil.getFirst(orderHeader.getRelated("OrderContactMech", UtilMisc.toMap("contactMechPurposeTypeId", "SHIPPING_LOCATION"), null, false));
if (orderContactMech != null) {
GenericValue contactMech = orderContactMech.getRelatedOne("ContactMech", false);
if (contactMech != null) {
return contactMech.getRelatedOne("PostalAddress", false);
}
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public List<GenericValue> getBillingLocations() {
List<GenericValue> billingLocations = new ArrayList<>();
List<GenericValue> billingCms = this.getOrderContactMechs("BILLING_LOCATION");
if (billingCms != null) {
for (GenericValue ocm : billingCms) {
if (ocm != null) {
try {
GenericValue addr = ocm.getDelegator().findOne("PostalAddress",
UtilMisc.toMap("contactMechId", ocm.getString("contactMechId")), false);
if (addr != null) {
billingLocations.add(addr);
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
}
}
}
return billingLocations;
}
/** @deprecated */
@Deprecated
public GenericValue getBillingAddress() {
GenericValue billingAddress = null;
try {
GenericValue orderContactMech = EntityUtil.getFirst(orderHeader.getRelated("OrderContactMech", UtilMisc.toMap("contactMechPurposeTypeId", "BILLING_LOCATION"), null, false));
if (orderContactMech != null) {
GenericValue contactMech = orderContactMech.getRelatedOne("ContactMech", false);
if (contactMech != null) {
billingAddress = contactMech.getRelatedOne("PostalAddress", false);
}
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
if (billingAddress == null) {
// get the address from the billing account
GenericValue billingAccount = getBillingAccount();
if (billingAccount != null) {
try {
billingAddress = billingAccount.getRelatedOne("PostalAddress", false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
} else {
// get the address from the first payment method
GenericValue paymentPreference = EntityUtil.getFirst(getPaymentPreferences());
if (paymentPreference != null) {
try {
GenericValue paymentMethod = paymentPreference.getRelatedOne("PaymentMethod", false);
if (paymentMethod != null) {
GenericValue creditCard = paymentMethod.getRelatedOne("CreditCard", false);
if (creditCard != null) {
billingAddress = creditCard.getRelatedOne("PostalAddress", false);
} else {
GenericValue eftAccount = paymentMethod.getRelatedOne("EftAccount", false);
if (eftAccount != null) {
billingAddress = eftAccount.getRelatedOne("PostalAddress", false);
}
}
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
}
}
}
return billingAddress;
}
public List<GenericValue> getOrderContactMechs(String purposeTypeId) {
try {
return orderHeader.getRelated("OrderContactMech", UtilMisc.toMap("contactMechPurposeTypeId", purposeTypeId), null, false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public Timestamp getEarliestShipByDate() {
try {
List<GenericValue> groups = orderHeader.getRelated("OrderItemShipGroup", null, UtilMisc.toList("shipByDate"), false);
if (groups.size() > 0) {
GenericValue group = groups.get(0);
return group.getTimestamp("shipByDate");
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public Timestamp getLatestShipAfterDate() {
try {
List<GenericValue> groups = orderHeader.getRelated("OrderItemShipGroup", null, UtilMisc.toList("shipAfterDate DESC"), false);
if (groups.size() > 0) {
GenericValue group = groups.get(0);
return group.getTimestamp("shipAfterDate");
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public String getCurrentStatusString() {
GenericValue statusItem = null;
try {
statusItem = orderHeader.getRelatedOne("StatusItem", true);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (statusItem != null) {
return statusItem.getString("description");
}
return orderHeader.getString("statusId");
}
public String getStatusString(Locale locale) {
List<GenericValue> orderStatusList = this.getOrderHeaderStatuses();
if (UtilValidate.isEmpty(orderStatusList)) {
return "";
}
Iterator<GenericValue> orderStatusIter = orderStatusList.iterator();
StringBuilder orderStatusString = new StringBuilder(50);
try {
boolean isCurrent = true;
while (orderStatusIter.hasNext()) {
GenericValue orderStatus = orderStatusIter.next();
GenericValue statusItem = orderStatus.getRelatedOne("StatusItem", true);
if (statusItem != null) {
orderStatusString.append(statusItem.get("description", locale));
} else {
orderStatusString.append(orderStatus.getString("statusId"));
}
if (isCurrent && orderStatusIter.hasNext()) {
orderStatusString.append(" (");
isCurrent = false;
} else {
if (orderStatusIter.hasNext()) {
orderStatusString.append("/");
} else {
if (!isCurrent) {
orderStatusString.append(")");
}
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Error getting Order Status information: " + e.toString(), module);
}
return orderStatusString.toString();
}
public GenericValue getBillingAccount() {
GenericValue billingAccount = null;
try {
billingAccount = orderHeader.getRelatedOne("BillingAccount", false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return billingAccount;
}
/**
* Returns the OrderPaymentPreference.maxAmount for the billing account associated with the order, or 0 if there is no
* billing account or no max amount set
*/
public BigDecimal getBillingAccountMaxAmount() {
if (getBillingAccount() == null) {
return BigDecimal.ZERO;
}
List<GenericValue> paymentPreferences = null;
try {
Delegator delegator = orderHeader.getDelegator();
paymentPreferences = EntityQuery.use(delegator).from("OrderPurchasePaymentSummary")
.where("orderId", orderHeader.get("orderId")).queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
List<EntityExpr> exprs = UtilMisc.toList(
EntityCondition.makeCondition("paymentMethodTypeId", "EXT_BILLACT"),
EntityCondition.makeCondition("preferenceStatusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED"));
GenericValue billingAccountPaymentPreference = EntityUtil.getFirst(EntityUtil.filterByAnd(paymentPreferences, exprs));
if ((billingAccountPaymentPreference != null) && (billingAccountPaymentPreference.getBigDecimal("maxAmount") != null)) {
return billingAccountPaymentPreference.getBigDecimal("maxAmount");
}
return BigDecimal.ZERO;
}
/**
* Returns party from OrderRole of BILL_TO_CUSTOMER
*/
public GenericValue getBillToParty() {
return this.getPartyFromRole("BILL_TO_CUSTOMER");
}
/**
* Returns party from OrderRole of BILL_FROM_VENDOR
*/
public GenericValue getBillFromParty() {
return this.getPartyFromRole("BILL_FROM_VENDOR");
}
/**
* Returns party from OrderRole of SHIP_TO_CUSTOMER
*/
public GenericValue getShipToParty() {
return this.getPartyFromRole("SHIP_TO_CUSTOMER");
}
/**
* Returns party from OrderRole of PLACING_CUSTOMER
*/
public GenericValue getPlacingParty() {
return this.getPartyFromRole("PLACING_CUSTOMER");
}
/**
* Returns party from OrderRole of END_USER_CUSTOMER
*/
public GenericValue getEndUserParty() {
return this.getPartyFromRole("END_USER_CUSTOMER");
}
/**
* Returns party from OrderRole of SUPPLIER_AGENT
*/
public GenericValue getSupplierAgent() {
return this.getPartyFromRole("SUPPLIER_AGENT");
}
/**
* SCIPIO: Returns party from OrderRole of BILL_TO_CUSTOMER.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getBillToPartyId() {
return this.getPartyIdFromRole("BILL_TO_CUSTOMER");
}
/**
* SCIPIO: Returns partyId from OrderRole of BILL_FROM_VENDOR.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getBillFromPartyId() {
return this.getPartyIdFromRole("BILL_FROM_VENDOR");
}
/**
* SCIPIO: Returns partyId from OrderRole of SHIP_TO_CUSTOMER.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getShipToPartyId() {
return this.getPartyIdFromRole("SHIP_TO_CUSTOMER");
}
/**
* SCIPIO: Returns partyId from OrderRole of PLACING_CUSTOMER.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getPlacingPartyId() {
return this.getPartyIdFromRole("PLACING_CUSTOMER");
}
/**
* SCIPIO: Returns partyId from OrderRole of END_USER_CUSTOMER.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getEndUserPartyId() {
return this.getPartyIdFromRole("END_USER_CUSTOMER");
}
/**
* SCIPIO: Returns partyId from OrderRole of SUPPLIER_AGENT.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getSupplierAgentPartyId() {
return this.getPartyIdFromRole("SUPPLIER_AGENT");
}
public GenericValue getPartyFromRole(String roleTypeId) {
Delegator delegator = orderHeader.getDelegator();
GenericValue partyObject = null;
try {
GenericValue orderRole = EntityUtil.getFirst(orderHeader.getRelated("OrderRole", UtilMisc.toMap("roleTypeId", roleTypeId), null, false));
if (orderRole != null) {
partyObject = EntityQuery.use(delegator).from("Person").where("partyId", orderRole.getString("partyId")).queryOne();
if (partyObject == null) {
partyObject = EntityQuery.use(delegator).from("PartyGroup").where("partyId", orderRole.getString("partyId")).queryOne();
// SCIPIO: 2019-02-27: WARN: when no Person or PartyGroup, most likely the entity data is not appropriate
// for use by (callers of) this method; alternatively, the data may be incomplete.
// This is clear due to some templates unconditionally falling back to PartyGroup.groupName when no Person record.
if (partyObject == null) {
GenericValue party = EntityQuery.use(delegator).from("Party").where("partyId", orderRole.getString("partyId")).queryOne();
if (party != null) {
Debug.logWarning("getPartyFromRole: Party '" + orderRole.getString("partyId")
+ "' (from orderId '" + getOrderId() + "', roleTypeId '" + roleTypeId + "', partyTypeId '"
+ party.get("partyTypeId") + "') has no Person or PartyGroup"
+ " (unsupported configuration); returning null", module);
} else {
Debug.logError("getPartyFromRole: Party '" + orderRole.getString("partyId")
+ "' (from orderId '" + getOrderId() + "', roleTypeId '" + roleTypeId + "') does not exist (bad partyId)"
+ "; returning null", module);
}
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return partyObject;
}
/**
* SCIPIO: Returns the partyId from the specified OrderRole for the order.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getPartyIdFromRole(String roleTypeId) { // SCIPIO: Added 2019-02
try {
GenericValue orderRole = EntityUtil.getFirst(orderHeader.getRelated("OrderRole", UtilMisc.toMap("roleTypeId", roleTypeId), null, false));
if (orderRole != null) {
return orderRole.getString("partyId");
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return null;
}
public String getDistributorId() {
try {
GenericEntity distributorRole = EntityUtil.getFirst(orderHeader.getRelated("OrderRole", UtilMisc.toMap("roleTypeId", "DISTRIBUTOR"), null, false));
return distributorRole == null ? null : distributorRole.getString("partyId");
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public String getAffiliateId() {
try {
GenericEntity distributorRole = EntityUtil.getFirst(orderHeader.getRelated("OrderRole", UtilMisc.toMap("roleTypeId", "AFFILIATE"), null, false));
return distributorRole == null ? null : distributorRole.getString("partyId");
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public BigDecimal getShippingTotal() {
return OrderReadHelper.calcOrderAdjustments(getOrderHeaderAdjustments(), getOrderItemsSubTotal(), false, false, true);
}
public BigDecimal getHeaderTaxTotal() {
return OrderReadHelper.calcOrderAdjustments(getOrderHeaderAdjustments(), getOrderItemsSubTotal(), false, true, false);
}
public BigDecimal getTaxTotal() {
return OrderReadHelper.calcOrderAdjustments(getAdjustments(), getOrderItemsSubTotal(), false, true, false);
}
public Set<String> getItemFeatureSet(GenericValue item) {
Set<String> featureSet = new LinkedHashSet<>();
List<GenericValue> featureAppls = null;
if (item.get("productId") != null) {
try {
featureAppls = item.getDelegator().findByAnd("ProductFeatureAppl", UtilMisc.toMap("productId", item.getString("productId")), null, true);
List<EntityExpr> filterExprs = UtilMisc.toList(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "STANDARD_FEATURE"));
filterExprs.add(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "REQUIRED_FEATURE"));
featureAppls = EntityUtil.filterByOr(featureAppls, filterExprs);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get ProductFeatureAppl for item : " + item, module);
}
if (featureAppls != null) {
for (GenericValue appl : featureAppls) {
featureSet.add(appl.getString("productFeatureId"));
}
}
}
// get the ADDITIONAL_FEATURE adjustments
List<GenericValue> additionalFeatures = null;
try {
additionalFeatures = item.getRelated("OrderAdjustment", UtilMisc.toMap("orderAdjustmentTypeId", "ADDITIONAL_FEATURE"), null, false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get OrderAdjustment from item : " + item, module);
}
if (additionalFeatures != null) {
for (GenericValue adj : additionalFeatures) {
String featureId = adj.getString("productFeatureId");
if (featureId != null) {
featureSet.add(featureId);
}
}
}
return featureSet;
}
public Map<String, BigDecimal> getFeatureIdQtyMap(String shipGroupSeqId) {
Map<String, BigDecimal> featureMap = new HashMap<>();
List<GenericValue> validItems = getValidOrderItems(shipGroupSeqId);
if (validItems != null) {
for (GenericValue item : validItems) {
List<GenericValue> featureAppls = null;
if (item.get("productId") != null) {
try {
featureAppls = item.getDelegator().findByAnd("ProductFeatureAppl", UtilMisc.toMap("productId", item.getString("productId")), null, true);
List<EntityExpr> filterExprs = UtilMisc.toList(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "STANDARD_FEATURE"));
filterExprs.add(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "REQUIRED_FEATURE"));
featureAppls = EntityUtil.filterByOr(featureAppls, filterExprs);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get ProductFeatureAppl for item : " + item, module);
}
if (featureAppls != null) {
for (GenericValue appl : featureAppls) {
BigDecimal lastQuantity = featureMap.get(appl.getString("productFeatureId"));
if (lastQuantity == null) {
lastQuantity = BigDecimal.ZERO;
}
BigDecimal newQuantity = lastQuantity.add(getOrderItemQuantity(item));
featureMap.put(appl.getString("productFeatureId"), newQuantity);
}
}
}
// get the ADDITIONAL_FEATURE adjustments
List<GenericValue> additionalFeatures = null;
try {
additionalFeatures = item.getRelated("OrderAdjustment", UtilMisc.toMap("orderAdjustmentTypeId", "ADDITIONAL_FEATURE"), null, false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get OrderAdjustment from item : " + item, module);
}
if (additionalFeatures != null) {
for (GenericValue adj : additionalFeatures) {
String featureId = adj.getString("productFeatureId");
if (featureId != null) {
BigDecimal lastQuantity = featureMap.get(featureId);
if (lastQuantity == null) {
lastQuantity = BigDecimal.ZERO;
}
BigDecimal newQuantity = lastQuantity.add(getOrderItemQuantity(item));
featureMap.put(featureId, newQuantity);
}
}
}
}
}
return featureMap;
}
public boolean shippingApplies() {
boolean shippingApplies = false;
List<GenericValue> validItems = this.getValidOrderItems();
if (validItems != null) {
for (GenericValue item : validItems) {
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
shippingApplies = true;
break;
}
}
}
}
return shippingApplies;
}
public boolean taxApplies() {
boolean taxApplies = false;
List<GenericValue> validItems = this.getValidOrderItems();
if (validItems != null) {
for (GenericValue item : validItems) {
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
}
if (product != null) {
if (ProductWorker.taxApplies(product)) {
taxApplies = true;
break;
}
}
}
}
return taxApplies;
}
public BigDecimal getShippableTotal(String shipGroupSeqId) {
BigDecimal shippableTotal = ZERO;
List<GenericValue> validItems = getValidOrderItems(shipGroupSeqId);
if (validItems != null) {
for (GenericValue item : validItems) {
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
return ZERO;
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
shippableTotal = shippableTotal.add(OrderReadHelper.getOrderItemSubTotal(item, getAdjustments(), false, true)).setScale(scale, rounding);
}
}
}
}
return shippableTotal.setScale(scale, rounding);
}
public BigDecimal getShippableQuantity() {
BigDecimal shippableQuantity = ZERO;
List<GenericValue> shipGroups = getOrderItemShipGroups();
if (UtilValidate.isNotEmpty(shipGroups)) {
for (GenericValue shipGroup : shipGroups) {
shippableQuantity = shippableQuantity.add(getShippableQuantity(shipGroup.getString("shipGroupSeqId")));
}
}
return shippableQuantity.setScale(scale, rounding);
}
public BigDecimal getShippableQuantity(String shipGroupSeqId) {
BigDecimal shippableQuantity = ZERO;
List<GenericValue> validItems = getValidOrderItems(shipGroupSeqId);
if (validItems != null) {
for (GenericValue item : validItems) {
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
return ZERO;
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
shippableQuantity = shippableQuantity.add(getOrderItemQuantity(item)).setScale(scale, rounding);
}
}
}
}
return shippableQuantity.setScale(scale, rounding);
}
public BigDecimal getShippableWeight(String shipGroupSeqId) {
BigDecimal shippableWeight = ZERO;
List<GenericValue> validItems = getValidOrderItems(shipGroupSeqId);
if (validItems != null) {
for (GenericValue item : validItems) {
shippableWeight = shippableWeight.add(this.getItemWeight(item).multiply(getOrderItemQuantity(item))).setScale(scale, rounding);
}
}
return shippableWeight.setScale(scale, rounding);
}
public BigDecimal getItemWeight(GenericValue item) {
Delegator delegator = orderHeader.getDelegator();
BigDecimal itemWeight = ZERO;
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
return BigDecimal.ZERO;
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
BigDecimal weight = product.getBigDecimal("weight");
String isVariant = product.getString("isVariant");
if (weight == null && "Y".equals(isVariant)) {
// get the virtual product and check its weight
try {
String virtualId = ProductWorker.getVariantVirtualId(product);
if (UtilValidate.isNotEmpty(virtualId)) {
GenericValue virtual = EntityQuery.use(delegator).from("Product").where("productId", virtualId).cache().queryOne();
if (virtual != null) {
weight = virtual.getBigDecimal("weight");
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting virtual product");
}
}
if (weight != null) {
itemWeight = weight;
}
}
}
return itemWeight;
}
/**
* SCIPIO: Returns a map containing "weight" and "weightUomId" keys, or null.
* NOTE: This follows {@link #getItemWeight(GenericValue)} and returns null if
* shipping does not apply to the product.
*/
public Map<String, Object> getItemWeightInfo(GenericValue item) {
Delegator delegator = orderHeader.getDelegator();
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem", module);
return null;
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
BigDecimal weight = product.getBigDecimal("weight");
String isVariant = product.getString("isVariant");
if (weight == null && "Y".equals(isVariant)) {
// get the virtual product and check its weight
try {
String virtualId = ProductWorker.getVariantVirtualId(product);
if (UtilValidate.isNotEmpty(virtualId)) {
GenericValue virtual = EntityQuery.use(delegator).from("Product").where("productId", virtualId).cache().queryOne();
if (virtual != null) {
weight = virtual.getBigDecimal("weight");
product = virtual;
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting virtual product");
}
}
return product;
}
}
return null;
}
public List<BigDecimal> getShippableSizes() {
List<BigDecimal> shippableSizes = new ArrayList<>();
List<GenericValue> validItems = getValidOrderItems();
if (validItems != null) {
for (GenericValue item : validItems) {
shippableSizes.add(this.getItemSize(item));
}
}
return shippableSizes;
}
/**
* Get the total payment preference amount by payment type. Specify null to get amount
* for all preference types. TODO: filter by status as well?
*/
public BigDecimal getOrderPaymentPreferenceTotalByType(String paymentMethodTypeId) {
BigDecimal total = ZERO;
for (GenericValue preference : getPaymentPreferences()) {
if (preference.get("maxAmount") == null) {
continue;
}
if (paymentMethodTypeId == null || paymentMethodTypeId.equals(preference.get("paymentMethodTypeId"))) {
total = total.add(preference.getBigDecimal("maxAmount")).setScale(scale, rounding);
}
}
return total;
}
/**
* SCIPIO: Get the total payment preference amount for each payment method
* or type.
*/
public Map<String, BigDecimal> getOrderPaymentPreferenceTotalsByIdOrType() {
Map<String, BigDecimal> totals = new HashMap<>();
for (GenericValue preference : getPaymentPreferences()) {
if (preference.get("maxAmount") == null)
continue;
if (UtilValidate.isNotEmpty(preference.getString("paymentMethodId"))) {
BigDecimal total = totals.get(preference.getString("paymentMethodId"));
if (total == null) {
total = BigDecimal.ZERO;
}
total = total.add(preference.getBigDecimal("maxAmount")).setScale(scale, rounding);
totals.put(preference.getString("paymentMethodId"), total);
} else if (UtilValidate.isNotEmpty(preference.getString("paymentMethodTypeId"))) {
BigDecimal total = totals.get(preference.getString("paymentMethodTypeId"));
if (total == null) {
total = BigDecimal.ZERO;
}
total = total.add(preference.getBigDecimal("maxAmount")).setScale(scale, rounding);
totals.put(preference.getString("paymentMethodTypeId"), total);
}
}
return totals;
}
public BigDecimal getCreditCardPaymentPreferenceTotal() {
return getOrderPaymentPreferenceTotalByType("CREDIT_CARD");
}
public BigDecimal getBillingAccountPaymentPreferenceTotal() {
return getOrderPaymentPreferenceTotalByType("EXT_BILLACT");
}
public BigDecimal getGiftCardPaymentPreferenceTotal() {
return getOrderPaymentPreferenceTotalByType("GIFT_CARD");
}
/**
* Get the total payment received amount by payment type. Specify null to get amount
* over all types. This method works by going through all the PaymentAndApplications
* for all order Invoices that have status PMNT_RECEIVED.
*/
public BigDecimal getOrderPaymentReceivedTotalByType(String paymentMethodTypeId) {
BigDecimal total = ZERO;
try {
// get a set of invoice IDs that belong to the order
List<GenericValue> orderItemBillings = orderHeader.getRelated("OrderItemBilling", null, null, false);
Set<String> invoiceIds = new HashSet<>();
for (GenericValue orderItemBilling : orderItemBillings) {
invoiceIds.add(orderItemBilling.getString("invoiceId"));
}
// get the payments of the desired type for these invoices TODO: in models where invoices can have many orders, this needs to be refined
List<EntityExpr> conditions = UtilMisc.toList(
EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PMNT_RECEIVED"),
EntityCondition.makeCondition("invoiceId", EntityOperator.IN, invoiceIds));
if (paymentMethodTypeId != null) {
conditions.add(EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, paymentMethodTypeId));
}
EntityConditionList<EntityExpr> ecl = EntityCondition.makeCondition(conditions, EntityOperator.AND);
List<GenericValue> payments = orderHeader.getDelegator().findList("PaymentAndApplication", ecl, null, null, null, true);
for (GenericValue payment : payments) {
if (payment.get("amountApplied") == null) {
continue;
}
total = total.add(payment.getBigDecimal("amountApplied")).setScale(scale, rounding);
}
} catch (GenericEntityException e) {
Debug.logError(e, e.getMessage(), module);
}
return total;
}
public BigDecimal getItemSize(GenericValue item) {
Delegator delegator = orderHeader.getDelegator();
BigDecimal size = BigDecimal.ZERO;
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem", module);
return BigDecimal.ZERO;
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
BigDecimal height = product.getBigDecimal("shippingHeight");
BigDecimal width = product.getBigDecimal("shippingWidth");
BigDecimal depth = product.getBigDecimal("shippingDepth");
String isVariant = product.getString("isVariant");
if ((height == null || width == null || depth == null) && "Y".equals(isVariant)) {
// get the virtual product and check its values
try {
String virtualId = ProductWorker.getVariantVirtualId(product);
if (UtilValidate.isNotEmpty(virtualId)) {
GenericValue virtual = EntityQuery.use(delegator).from("Product").where("productId", virtualId).cache().queryOne();
if (virtual != null) {
if (height == null) {
height = virtual.getBigDecimal("shippingHeight");
}
if (width == null) {
width = virtual.getBigDecimal("shippingWidth");
}
if (depth == null) {
depth = virtual.getBigDecimal("shippingDepth");
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting virtual product");
}
}
if (height == null) {
height = BigDecimal.ZERO;
}
if (width == null) {
width = BigDecimal.ZERO;
}
if (depth == null) {
depth = BigDecimal.ZERO;
}
// determine girth (longest field is length)
BigDecimal[] sizeInfo = { height, width, depth };
Arrays.sort(sizeInfo);
size = sizeInfo[0].multiply(new BigDecimal("2")).add(sizeInfo[1].multiply(new BigDecimal("2"))).add(sizeInfo[2]);
}
}
return size;
}
public long getItemPiecesIncluded(GenericValue item) {
Delegator delegator = orderHeader.getDelegator();
long piecesIncluded = 1;
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem; returning 1", module);
return 1;
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
Long pieces = product.getLong("piecesIncluded");
String isVariant = product.getString("isVariant");
if (pieces == null && isVariant != null && "Y".equals(isVariant)) {
// get the virtual product and check its weight
GenericValue virtual = null;
try {
virtual = EntityQuery.use(delegator).from("ProductAssoc")
.where("productIdTo", product.get("productId"),
"productAssocTypeId", "PRODUCT_VARIANT")
.orderBy("-fromDate")
.filterByDate().queryFirst();
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting virtual product");
}
if (virtual != null) {
try {
GenericValue virtualProduct = virtual.getRelatedOne("MainProduct", false);
pieces = virtualProduct.getLong("piecesIncluded");
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting virtual product");
}
}
}
if (pieces != null) {
piecesIncluded = pieces;
}
}
}
return piecesIncluded;
}
public List<Map<String, Object>> getShippableItemInfo(String shipGroupSeqId) {
List<Map<String, Object>> shippableInfo = new ArrayList<>();
List<GenericValue> validItems = getValidOrderItems(shipGroupSeqId);
if (validItems != null) {
for (GenericValue item : validItems) {
shippableInfo.add(this.getItemInfoMap(item));
}
}
return shippableInfo;
}
public Map<String, Object> getItemInfoMap(GenericValue item) {
Map<String, Object> itemInfo = new HashMap<>();
itemInfo.put("productId", item.getString("productId"));
itemInfo.put("quantity", getOrderItemQuantity(item));
// SCIPIO: 2019-03-01: included weight uom ID
//itemInfo.put("weight", this.getItemWeight(item));
BigDecimal weight = null;
String weightUomId = null;
Map<String, Object> weightInfo = this.getItemWeightInfo(item);
if (weightInfo != null) {
weight = (BigDecimal) weightInfo.get("weight");
weightUomId = (String) weightInfo.get("weightUomId");
}
itemInfo.put("weight", weight != null ? weight : BigDecimal.ZERO);
itemInfo.put("weightUomId", weightUomId);
itemInfo.put("size", this.getItemSize(item));
itemInfo.put("piecesIncluded", this.getItemPiecesIncluded(item));
itemInfo.put("featureSet", this.getItemFeatureSet(item));
return itemInfo;
}
public String getOrderEmailString() {
Delegator delegator = orderHeader.getDelegator();
// get the email addresses from the order contact mech(s)
List<GenericValue> orderContactMechs = null;
try {
orderContactMechs = EntityQuery.use(delegator).from("OrderContactMech")
.where("orderId", orderHeader.get("orderId"),
"contactMechPurposeTypeId", "ORDER_EMAIL")
.queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problems getting order contact mechs", module);
}
StringBuilder emails = new StringBuilder();
if (orderContactMechs != null) {
for (GenericValue orderContactMech : orderContactMechs) {
try {
GenericValue contactMech = orderContactMech.getRelatedOne("ContactMech", false);
emails.append(emails.length() > 0 ? "," : "").append(contactMech.getString("infoString"));
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problems getting contact mech from order contact mech", module);
}
}
}
return emails.toString();
}
/**
* SCIPIO: Alternate to getOrderEmailString that returns as a list.
*/
public List<String> getOrderEmailList() {
Delegator delegator = orderHeader.getDelegator();
// get the email addresses from the order contact mech(s)
List<GenericValue> orderContactMechs = null;
try {
orderContactMechs = EntityQuery.use(delegator).from("OrderContactMech")
.where("orderId", orderHeader.get("orderId"), "contactMechPurposeTypeId", "ORDER_EMAIL").queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problems getting order contact mechs", module);
}
List<String> emails = new ArrayList<>();
if (orderContactMechs != null) {
for (GenericValue orderContactMech : orderContactMechs) {
try {
GenericValue contactMech = orderContactMech.getRelatedOne("ContactMech", false);
emails.add(contactMech.getString("infoString"));
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problems getting contact mech from order contact mech", module);
}
}
}
return emails;
}
/**
* SCIPIO: return all OrderIds that match the current email address and that are not rejected or cancelled
*/
public List getAllCustomerOrderIdsFromOrderEmail() {
return getAllCustomerOrderIdsFromEmail(getOrderEmailString(),new ArrayList<String>());
}
public List getAllCustomerOrderIdsFromOrderEmail(List<String>filteredStatusIds) {
return getAllCustomerOrderIdsFromEmail(getOrderEmailString(),filteredStatusIds);
}
/**
* SCIPIO: return all OrderIds that match the email address
*/
public List<String> getAllCustomerOrderIdsFromEmail(String emailAddress,List<String>filteredStatusIds) {
List<String> orderList = new ArrayList<>();
try {
List<GenericValue> vl = getAllCustomerOrderIdsFromEmailGenericValue(emailAddress,filteredStatusIds);
for (GenericValue n : vl) {
String orderId = n.getString("orderId");
orderList.add(orderId);
}
} catch (Exception e) {
Debug.logError(e,module);
}
return orderList;
}
public List<GenericValue> getAllCustomerOrderIdsFromEmailGenericValue(String emailAddress, List<String>filteredStatusIds) {
Delegator delegator = orderHeader.getDelegator();
List<GenericValue> orderList = new ArrayList<GenericValue>();
int rfmDays = UtilProperties.getPropertyAsInteger("order.properties","order.rfm.days",730);
DynamicViewEntity dve = new DynamicViewEntity();
dve.addMemberEntity("OH", "OrderHeader");
dve.addMemberEntity("OHR", "OrderRole");
dve.addMemberEntity("OCM", "OrderContactMech");
dve.addMemberEntity("CM", "ContactMech");
dve.addAlias("OH", "orderDate",null,null,null,true,null);
dve.addAlias("OH", "statusId",null,null,null,false,null);
dve.addAlias("OHR", "orderId", null, null, null, false, null);
dve.addAlias("OHR", "partyId", null, null, null, false, null);
dve.addAlias("OHR", "roleTypeId", null, null, null, false, null);
dve.addAlias("OCM", "contactMechPurposeTypeId", null, null, null, true, null);
dve.addAlias("CM", "emailAddress", "infoString", null, null, true, null);
dve.addViewLink("OH", "OHR", Boolean.FALSE, ModelKeyMap.makeKeyMapList("orderId", "orderId"));
dve.addViewLink("OH", "OCM", Boolean.FALSE, ModelKeyMap.makeKeyMapList("orderId", "orderId"));
dve.addViewLink("OCM", "CM", Boolean.FALSE, ModelKeyMap.makeKeyMapList("contactMechId", "contactMechId"));
List<EntityCondition> exprListStatus = new ArrayList<>();
EntityCondition expr = EntityCondition.makeCondition("emailAddress", EntityOperator.EQUALS, emailAddress);
exprListStatus.add(expr);
expr = EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "PLACING_CUSTOMER");
exprListStatus.add(expr);
expr = EntityCondition.makeCondition("contactMechPurposeTypeId", EntityOperator.EQUALS, "ORDER_EMAIL");
exprListStatus.add(expr);
if(UtilValidate.isNotEmpty(filteredStatusIds)){
expr = EntityCondition.makeCondition("statusId", EntityOperator.NOT_IN, filteredStatusIds);
exprListStatus.add(expr);
}
if(rfmDays>0){
Calendar currentDayCal = Calendar.getInstance();
currentDayCal.set(Calendar.DATE, -rfmDays);
exprListStatus.add(EntityCondition.makeCondition("orderDate", EntityOperator.GREATER_THAN_EQUAL_TO, UtilDateTime.toTimestamp(currentDayCal.getTime())));
}
EntityCondition andCond = EntityCondition.makeCondition(exprListStatus, EntityOperator.AND);
try {
EntityListIterator customerOrdersIterator = delegator.findListIteratorByCondition(dve,andCond,null,UtilMisc.toList("orderId"),UtilMisc.toList("-orderDate"),null);
orderList = customerOrdersIterator.getCompleteList();
} catch (GenericEntityException e) {
Debug.logError(e,module);
}
return orderList.stream().distinct()
.collect(Collectors.toList());
}
public BigDecimal getOrderGrandTotal() {
if (totalPrice == null) {
totalPrice = getOrderGrandTotal(getValidOrderItems(), getAdjustments());
} // else already set
return totalPrice;
}
/**
* Gets the amount open on the order that is not covered by the relevant OrderPaymentPreferences.
* This works by adding up the amount allocated to each unprocessed OrderPaymentPreference and the
* amounts received and refunded as payments for the settled ones.
*/
public BigDecimal getOrderOpenAmount() throws GenericEntityException {
BigDecimal total = getOrderGrandTotal();
BigDecimal openAmount = BigDecimal.ZERO;
List<GenericValue> prefs = getPaymentPreferences();
// add up the covered amount, but skip preferences which are declined or cancelled
for (GenericValue pref : prefs) {
if ("PAYMENT_CANCELLED".equals(pref.get("statusId")) || "PAYMENT_DECLINED".equals(pref.get("statusId"))) {
continue;
} else if ("PAYMENT_SETTLED".equals(pref.get("statusId"))) {
List<GenericValue> responses = pref.getRelated("PaymentGatewayResponse", UtilMisc.toMap("transCodeEnumId", "PGT_CAPTURE"), null, false);
for (GenericValue response : responses) {
BigDecimal amount = response.getBigDecimal("amount");
if (amount != null) {
openAmount = openAmount.add(amount);
}
}
responses = pref.getRelated("PaymentGatewayResponse", UtilMisc.toMap("transCodeEnumId", "PGT_REFUND"), null, false);
for (GenericValue response : responses) {
BigDecimal amount = response.getBigDecimal("amount");
if (amount != null) {
openAmount = openAmount.subtract(amount);
}
}
} else {
// all others are currently "unprocessed" payment preferences
BigDecimal maxAmount = pref.getBigDecimal("maxAmount");
if (maxAmount != null) {
openAmount = openAmount.add(maxAmount);
}
}
}
openAmount = total.subtract(openAmount).setScale(scale, rounding);
// return either a positive amount or positive zero
return openAmount.compareTo(BigDecimal.ZERO) > 0 ? openAmount : BigDecimal.ZERO;
}
public List<GenericValue> getOrderHeaderAdjustments() {
return getOrderHeaderAdjustments(getAdjustments(), null);
}
public List<GenericValue> getOrderHeaderAdjustments(String shipGroupSeqId) {
return getOrderHeaderAdjustments(getAdjustments(), shipGroupSeqId);
}
public List<GenericValue> getOrderHeaderAdjustmentsTax(String shipGroupSeqId) {
return filterOrderAdjustments(getOrderHeaderAdjustments(getAdjustments(), shipGroupSeqId), false, true, false, false, false);
}
public List<GenericValue> getOrderHeaderAdjustmentsToShow() {
return filterOrderAdjustments(getOrderHeaderAdjustments(), true, false, false, false, false);
}
public List<GenericValue> getOrderHeaderStatuses() {
return getOrderHeaderStatuses(getOrderStatuses());
}
public BigDecimal getOrderAdjustmentsTotal() {
return getOrderAdjustmentsTotal(getValidOrderItems(), getAdjustments());
}
public BigDecimal getOrderAdjustmentTotal(GenericValue adjustment) {
return calcOrderAdjustment(adjustment, getOrderItemsSubTotal());
}
public int hasSurvey() {
Delegator delegator = orderHeader.getDelegator();
List<GenericValue> surveys = null;
try {
surveys = EntityQuery.use(delegator).from("SurveyResponse")
.where("orderId", orderHeader.get("orderId")).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
int size = 0;
if (surveys != null) {
size = surveys.size();
}
return size;
}
// ========================================
// ========== Order Item Methods ==========
// ========================================
public List<GenericValue> getOrderItems() {
if (orderItems == null) {
try {
orderItems = orderHeader.getRelated("OrderItem", null, UtilMisc.toList("orderItemSeqId"), false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
}
return orderItems;
}
public List<GenericValue> getOrderItemAndShipGroupAssoc() {
if (orderItemAndShipGrp == null) {
try {
orderItemAndShipGrp = orderHeader.getDelegator().findByAnd("OrderItemAndShipGroupAssoc",
UtilMisc.toMap("orderId", orderHeader.getString("orderId")), null, false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
}
return orderItemAndShipGrp;
}
public List<GenericValue> getOrderItemAndShipGroupAssoc(String shipGroupSeqId) {
List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("shipGroupSeqId", EntityOperator.EQUALS, shipGroupSeqId));
return EntityUtil.filterByAnd(getOrderItemAndShipGroupAssoc(), exprs);
}
public List<GenericValue> getValidOrderItems() {
List<EntityExpr> exprs = UtilMisc.toList(
EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"),
EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED"));
return EntityUtil.filterByAnd(getOrderItems(), exprs);
}
public boolean getPastEtaOrderItems(String orderId) {
Delegator delegator = orderHeader.getDelegator();
GenericValue orderDeliverySchedule = null;
try {
orderDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", "_NA_").queryOne();
} catch (GenericEntityException e) {
if (Debug.infoOn()) {
Debug.logInfo(" OrderDeliverySchedule not found for order " + orderId, module);
}
return false;
}
if (orderDeliverySchedule == null) {
return false;
}
Timestamp estimatedShipDate = orderDeliverySchedule.getTimestamp("estimatedReadyDate");
return estimatedShipDate != null && UtilDateTime.nowTimestamp().after(estimatedShipDate);
}
public boolean getRejectedOrderItems() {
List<GenericValue> items = getOrderItems();
for (GenericValue item : items) {
List<GenericValue> receipts = null;
try {
receipts = item.getRelated("ShipmentReceipt", null, null, false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
if (UtilValidate.isNotEmpty(receipts)) {
for (GenericValue rec : receipts) {
BigDecimal rejected = rec.getBigDecimal("quantityRejected");
if (rejected != null && rejected.compareTo(BigDecimal.ZERO) > 0) {
return true;
}
}
}
}
return false;
}
public boolean getPartiallyReceivedItems() {
List<GenericValue> items = getOrderItems();
for (GenericValue item : items) {
List<GenericValue> receipts = null;
try {
receipts = item.getRelated("ShipmentReceipt", null, null, false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
if (UtilValidate.isNotEmpty(receipts)) {
for (GenericValue rec : receipts) {
BigDecimal acceptedQuantity = rec.getBigDecimal("quantityAccepted");
BigDecimal orderedQuantity = (BigDecimal) item.get("quantity");
if (acceptedQuantity.intValue() != orderedQuantity.intValue() && acceptedQuantity.intValue() > 0) {
return true;
}
}
}
}
return false;
}
public List<GenericValue> getValidOrderItems(String shipGroupSeqId) {
if (shipGroupSeqId == null) {
return getValidOrderItems();
}
List<EntityExpr> exprs = UtilMisc.toList(
EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"),
EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED"),
EntityCondition.makeCondition("shipGroupSeqId", EntityOperator.EQUALS, shipGroupSeqId));
return EntityUtil.filterByAnd(getOrderItemAndShipGroupAssoc(), exprs);
}
public GenericValue getOrderItem(String orderItemSeqId) {
List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItemSeqId));
return EntityUtil.getFirst(EntityUtil.filterByAnd(getOrderItems(), exprs));
}
public List<GenericValue> getValidDigitalItems() {
List<GenericValue> digitalItems = new ArrayList<>();
// only approved or complete items apply
List<EntityExpr> exprs = UtilMisc.toList(
EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ITEM_APPROVED"),
EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ITEM_COMPLETED"));
List<GenericValue> items = EntityUtil.filterByOr(getOrderItems(), exprs);
for (GenericValue item : items) {
if (item.get("productId") != null) {
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get Product from OrderItem", module);
}
if (product != null) {
GenericValue productType = null;
try {
productType = product.getRelatedOne("ProductType", false);
} catch (GenericEntityException e) {
Debug.logError(e, "ERROR: Unable to get ProductType from Product", module);
}
if (productType != null) {
String isDigital = productType.getString("isDigital");
if (isDigital != null && "Y".equalsIgnoreCase(isDigital)) {
// make sure we have an OrderItemBilling record
List<GenericValue> orderItemBillings = null;
try {
orderItemBillings = item.getRelated("OrderItemBilling", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get OrderItemBilling from OrderItem");
}
if (UtilValidate.isNotEmpty(orderItemBillings)) {
// get the ProductContent records
List<GenericValue> productContents = null;
try {
productContents = product.getRelated("ProductContent", null, null, false);
} catch (GenericEntityException e) {
Debug.logError("Unable to get ProductContent from Product", module);
}
List<EntityExpr> cExprs = UtilMisc.toList(
EntityCondition.makeCondition("productContentTypeId", EntityOperator.EQUALS, "DIGITAL_DOWNLOAD"),
EntityCondition.makeCondition("productContentTypeId", EntityOperator.EQUALS, "FULFILLMENT_EMAIL"),
EntityCondition.makeCondition("productContentTypeId", EntityOperator.EQUALS, "FULFILLMENT_EXTERNAL"));
// add more as needed
productContents = EntityUtil.filterByDate(productContents);
productContents = EntityUtil.filterByOr(productContents, cExprs);
if (UtilValidate.isNotEmpty(productContents)) {
// make sure we are still within the allowed timeframe and use limits
for (GenericValue productContent : productContents) {
Timestamp fromDate = productContent.getTimestamp("purchaseFromDate");
Timestamp thruDate = productContent.getTimestamp("purchaseThruDate");
if (fromDate == null || item.getTimestamp("orderDate").after(fromDate)) {
if (thruDate == null || item.getTimestamp("orderDate").before(thruDate)) {
// TODO: Implement use count and days
digitalItems.add(item);
}
}
}
}
}
}
}
}
}
}
return digitalItems;
}
public List<GenericValue> getOrderItemAdjustments(GenericValue orderItem) {
return getOrderItemAdjustmentList(orderItem, getAdjustments());
}
public String getCurrentOrderItemWorkEffort(GenericValue orderItem) {
String orderItemSeqId = orderItem.getString("orderItemSeqId");
String orderId = orderItem.getString("orderId");
Delegator delegator = orderItem.getDelegator();
GenericValue workOrderItemFulFillment = null;
GenericValue workEffort = null;
try {
workOrderItemFulFillment = EntityQuery.use(delegator).from("WorkOrderItemFulfillment")
.where("orderId", orderId, "orderItemSeqId", orderItemSeqId)
.cache().queryFirst();
if (workOrderItemFulFillment != null) {
workEffort = workOrderItemFulFillment.getRelatedOne("WorkEffort", false);
}
} catch (GenericEntityException e) {
return null;
}
if (workEffort != null) {
return workEffort.getString("workEffortId");
}
return null;
}
public String getCurrentItemStatus(GenericValue orderItem) {
GenericValue statusItem = null;
try {
statusItem = orderItem.getRelatedOne("StatusItem", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Trouble getting StatusItem : " + orderItem, module);
}
if (statusItem == null || statusItem.get("description") == null) {
return "Not Available";
}
return statusItem.getString("description");
}
public List<GenericValue> getOrderItemPriceInfos(GenericValue orderItem) {
if (orderItem == null) {
return null;
}
if (this.orderItemPriceInfos == null) {
Delegator delegator = orderHeader.getDelegator();
try {
orderItemPriceInfos = EntityQuery.use(delegator).from("OrderItemPriceInfo")
.where("orderId", orderHeader.get("orderId")).queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
}
String orderItemSeqId = (String) orderItem.get("orderItemSeqId");
return EntityUtil.filterByAnd(this.orderItemPriceInfos, UtilMisc.toMap("orderItemSeqId", orderItemSeqId));
}
public List<GenericValue> getOrderItemShipGroupAssocs(GenericValue orderItem) {
if (orderItem == null) {
return null;
}
try {
return orderHeader.getDelegator().findByAnd("OrderItemShipGroupAssoc",
UtilMisc.toMap("orderId", orderItem.getString("orderId"), "orderItemSeqId", orderItem.getString("orderItemSeqId")), UtilMisc.toList("shipGroupSeqId"), false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public List<GenericValue> getOrderItemShipGrpInvResList(GenericValue orderItem) {
if (orderItem == null) {
return null;
}
if (this.orderItemShipGrpInvResList == null) {
Delegator delegator = orderItem.getDelegator();
try {
orderItemShipGrpInvResList = EntityQuery.use(delegator).from("OrderItemShipGrpInvRes")
.where("orderId", orderItem.get("orderId")).queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Trouble getting OrderItemShipGrpInvRes List", module);
}
}
return EntityUtil.filterByAnd(orderItemShipGrpInvResList, UtilMisc.toMap("orderItemSeqId", orderItem.getString("orderItemSeqId")));
}
public List<GenericValue> getOrderItemIssuances(GenericValue orderItem) {
return this.getOrderItemIssuances(orderItem, null);
}
public List<GenericValue> getOrderItemIssuances(GenericValue orderItem, String shipmentId) {
if (orderItem == null) {
return null;
}
if (this.orderItemIssuances == null) {
Delegator delegator = orderItem.getDelegator();
try {
orderItemIssuances = EntityQuery.use(delegator).from("ItemIssuance")
.where("orderId", orderItem.get("orderId")).queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Trouble getting ItemIssuance(s)", module);
}
}
// filter the issuances
Map<String, Object> filter = UtilMisc.toMap("orderItemSeqId", orderItem.get("orderItemSeqId"));
if (shipmentId != null) {
filter.put("shipmentId", shipmentId);
}
return EntityUtil.filterByAnd(orderItemIssuances, filter);
}
/** Get a set of productIds in the order. */
public Collection<String> getOrderProductIds() {
Set<String> productIds = new HashSet<>();
for (GenericValue orderItem : getOrderItems()) {
if (orderItem.get("productId") != null) {
productIds.add(orderItem.getString("productId"));
}
}
return productIds;
}
public List<GenericValue> getOrderReturnItems() {
Delegator delegator = orderHeader.getDelegator();
if (this.orderReturnItems == null) {
try {
this.orderReturnItems = EntityQuery.use(delegator).from("ReturnItem").where("orderId", orderHeader.get("orderId")).orderBy("returnItemSeqId").queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting ReturnItem from order", module);
return null;
}
}
return this.orderReturnItems;
}
/**
* Get the quantity returned per order item.
* In other words, this method will count the ReturnItems
* related to each OrderItem.
*
* @return Map of returned quantities as BigDecimals keyed to the orderItemSeqId
*/
public Map<String, BigDecimal> getOrderItemReturnedQuantities() {
List<GenericValue> returnItems = getOrderReturnItems();
// since we don't have a handy grouped view entity, we'll have to group the return items by hand
Map<String, BigDecimal> returnMap = new HashMap<>();
for (GenericValue orderItem : this.getValidOrderItems()) {
List<GenericValue> group = EntityUtil.filterByAnd(returnItems, UtilMisc.toList(
EntityCondition.makeCondition("orderId", orderItem.get("orderId")),
EntityCondition.makeCondition("orderItemSeqId", orderItem.get("orderItemSeqId")),
EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "RETURN_CANCELLED")));
// add up the returned quantities for this group TODO: received quantity should be used eventually
BigDecimal returned = BigDecimal.ZERO;
for (GenericValue returnItem : group) {
if (returnItem.getBigDecimal("returnQuantity") != null) {
returned = returned.add(returnItem.getBigDecimal("returnQuantity"));
}
}
// the quantity returned per order item
returnMap.put(orderItem.getString("orderItemSeqId"), returned);
}
return returnMap;
}
/**
* Get the total quantity of returned items for an order. This will count
* only the ReturnItems that are directly correlated to an OrderItem.
*/
public BigDecimal getOrderReturnedQuantity() {
List<GenericValue> returnedItemsBase = getOrderReturnItems();
List<GenericValue> returnedItems = new ArrayList<>(returnedItemsBase.size());
// filter just order items
List<EntityExpr> orderItemExprs = UtilMisc.toList(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_PROD_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_FPROD_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_DPROD_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_FDPROD_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_PROD_FEATR_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_SPROD_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_WE_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_TE_ITEM"));
returnedItemsBase = EntityUtil.filterByOr(returnedItemsBase, orderItemExprs);
// get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
BigDecimal returnedQuantity = ZERO;
for (GenericValue returnedItem : returnedItems) {
if (returnedItem.get("returnQuantity") != null) {
returnedQuantity = returnedQuantity.add(returnedItem.getBigDecimal("returnQuantity")).setScale(scale, rounding);
}
}
return returnedQuantity.setScale(scale, rounding);
}
/**
* Get the returned total by return type (credit, refund, etc.). Specify returnTypeId = null to get sum over all
* return types. Specify includeAll = true to sum up over all return statuses except cancelled. Specify includeAll
* = false to sum up over ACCEPTED,RECEIVED And COMPLETED returns.
*/
public BigDecimal getOrderReturnedTotalByTypeBd(String returnTypeId, boolean includeAll) {
List<GenericValue> returnedItemsBase = getOrderReturnItems();
if (returnTypeId != null) {
returnedItemsBase = EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("returnTypeId", returnTypeId));
}
List<GenericValue> returnedItems = new ArrayList<>(returnedItemsBase.size());
// get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
if (!includeAll) {
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_ACCEPTED")));
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
} else {
// otherwise get all of them except cancelled ones
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase,
UtilMisc.toList(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "RETURN_CANCELLED"))));
}
BigDecimal returnedAmount = ZERO;
String orderId = orderHeader.getString("orderId");
List<String> returnHeaderList = new ArrayList<>();
for (GenericValue returnedItem : returnedItems) {
if ((returnedItem.get("returnPrice") != null) && (returnedItem.get("returnQuantity") != null)) {
returnedAmount = returnedAmount.add(returnedItem.getBigDecimal("returnPrice").multiply(returnedItem.getBigDecimal("returnQuantity")).setScale(scale, rounding));
}
Map<String, Object> itemAdjustmentCondition = UtilMisc.toMap("returnId", returnedItem.get("returnId"), "returnItemSeqId", returnedItem.get("returnItemSeqId"));
if (UtilValidate.isNotEmpty(returnTypeId)) {
itemAdjustmentCondition.put("returnTypeId", returnTypeId);
}
returnedAmount = returnedAmount.add(getReturnAdjustmentTotal(orderHeader.getDelegator(), itemAdjustmentCondition));
if (orderId.equals(returnedItem.getString("orderId")) && (!returnHeaderList.contains(returnedItem.getString("returnId")))) {
returnHeaderList.add(returnedItem.getString("returnId"));
}
}
// get returnedAmount from returnHeader adjustments whose orderId must equals to current orderHeader.orderId
for (String returnId : returnHeaderList) {
Map<String, Object> returnHeaderAdjFilter = UtilMisc.<String, Object>toMap("returnId", returnId, "returnItemSeqId", "_NA_", "returnTypeId", returnTypeId);
returnedAmount = returnedAmount.add(getReturnAdjustmentTotal(orderHeader.getDelegator(), returnHeaderAdjFilter)).setScale(scale, rounding);
}
return returnedAmount.setScale(scale, rounding);
}
/** Gets the total return credit for COMPLETED and RECEIVED returns. */
public BigDecimal getOrderReturnedCreditTotalBd() {
return getOrderReturnedTotalByTypeBd("RTN_CREDIT", false);
}
/** Gets the total return refunded for COMPLETED and RECEIVED returns. */
public BigDecimal getOrderReturnedRefundTotalBd() {
return getOrderReturnedTotalByTypeBd("RTN_REFUND", false);
}
/** Gets the total return amount (all return types) for COMPLETED and RECEIVED returns. */
public BigDecimal getOrderReturnedTotal() {
return getOrderReturnedTotalByTypeBd(null, false);
}
/**
* Gets the total returned over all return types. Specify true to include all return statuses
* except cancelled. Specify false to include only COMPLETED and RECEIVED returns.
*/
public BigDecimal getOrderReturnedTotal(boolean includeAll) {
return getOrderReturnedTotalByTypeBd(null, includeAll);
}
public BigDecimal getOrderNonReturnedTaxAndShipping() {
// first make a Map of orderItemSeqId key, returnQuantity value
List<GenericValue> returnedItemsBase = getOrderReturnItems();
List<GenericValue> returnedItems = new ArrayList<>(returnedItemsBase.size());
// get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
Map<String, BigDecimal> itemReturnedQuantities = new HashMap<>();
for (GenericValue returnedItem : returnedItems) {
String orderItemSeqId = returnedItem.getString("orderItemSeqId");
BigDecimal returnedQuantity = returnedItem.getBigDecimal("returnQuantity");
if (orderItemSeqId != null && returnedQuantity != null) {
BigDecimal existingQuantity = itemReturnedQuantities.get(orderItemSeqId);
if (existingQuantity == null) {
itemReturnedQuantities.put(orderItemSeqId, returnedQuantity);
} else {
itemReturnedQuantities.put(orderItemSeqId, returnedQuantity.add(existingQuantity));
}
}
}
// then go through all order items and for the quantity not returned calculate it's portion of the item, and of the entire order
BigDecimal totalSubTotalNotReturned = ZERO;
BigDecimal totalTaxNotReturned = ZERO;
BigDecimal totalShippingNotReturned = ZERO;
for (GenericValue orderItem : this.getValidOrderItems()) {
BigDecimal itemQuantityDbl = orderItem.getBigDecimal("quantity");
if (itemQuantityDbl == null || itemQuantityDbl.compareTo(ZERO) == 0) {
continue;
}
BigDecimal itemQuantity = itemQuantityDbl;
BigDecimal itemSubTotal = this.getOrderItemSubTotal(orderItem);
BigDecimal itemTaxes = this.getOrderItemTax(orderItem);
BigDecimal itemShipping = this.getOrderItemShipping(orderItem);
BigDecimal quantityReturned = itemReturnedQuantities.get(orderItem.get("orderItemSeqId"));
if (quantityReturned == null) {
quantityReturned = BigDecimal.ZERO;
}
BigDecimal quantityNotReturned = itemQuantity.subtract(quantityReturned);
// pro-rated factor (quantity not returned / total items ordered), which shouldn't be rounded to 2 decimals
BigDecimal factorNotReturned = quantityNotReturned.divide(itemQuantity, 100, rounding);
BigDecimal subTotalNotReturned = itemSubTotal.multiply(factorNotReturned).setScale(scale, rounding);
// calculate tax and shipping adjustments for each item, add to accumulators
BigDecimal itemTaxNotReturned = itemTaxes.multiply(factorNotReturned).setScale(scale, rounding);
BigDecimal itemShippingNotReturned = itemShipping.multiply(factorNotReturned).setScale(scale, rounding);
totalSubTotalNotReturned = totalSubTotalNotReturned.add(subTotalNotReturned);
totalTaxNotReturned = totalTaxNotReturned.add(itemTaxNotReturned);
totalShippingNotReturned = totalShippingNotReturned.add(itemShippingNotReturned);
}
// calculate tax and shipping adjustments for entire order, add to result
BigDecimal orderItemsSubTotal = this.getOrderItemsSubTotal();
BigDecimal orderFactorNotReturned = ZERO;
if (orderItemsSubTotal.signum() != 0) {
// pro-rated factor (subtotal not returned / item subtotal), which shouldn't be rounded to 2 decimals
orderFactorNotReturned = totalSubTotalNotReturned.divide(orderItemsSubTotal, 100, rounding);
}
BigDecimal orderTaxNotReturned = this.getHeaderTaxTotal().multiply(orderFactorNotReturned).setScale(scale, rounding);
BigDecimal orderShippingNotReturned = this.getShippingTotal().multiply(orderFactorNotReturned).setScale(scale, rounding);
return totalTaxNotReturned.add(totalShippingNotReturned).add(orderTaxNotReturned).add(orderShippingNotReturned).setScale(scale, rounding);
}
/** Gets the total refunded to the order billing account by type. Specify null to get total over all types. */
public BigDecimal getBillingAccountReturnedTotalByTypeBd(String returnTypeId) {
BigDecimal returnedAmount = ZERO;
List<GenericValue> returnedItemsBase = getOrderReturnItems();
if (returnTypeId != null) {
returnedItemsBase = EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("returnTypeId", returnTypeId));
}
List<GenericValue> returnedItems = new ArrayList<>(returnedItemsBase.size());
// get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
// sum up the return items that have a return item response with a billing account defined
try {
for (GenericValue returnItem : returnedItems) {
GenericValue returnItemResponse = returnItem.getRelatedOne("ReturnItemResponse", false);
if (returnItemResponse == null) {
continue;
}
if (returnItemResponse.get("billingAccountId") == null) {
continue;
}
// we can just add the response amounts
returnedAmount = returnedAmount.add(returnItemResponse.getBigDecimal("responseAmount")).setScale(scale, rounding);
}
} catch (GenericEntityException e) {
Debug.logError(e, e.getMessage(), module);
}
return returnedAmount;
}
/** Get the total return credited to the order billing accounts */
public BigDecimal getBillingAccountReturnedCreditTotalBd() {
return getBillingAccountReturnedTotalByTypeBd("RTN_CREDIT");
}
/** Get the total return refunded to the order billing accounts */
public BigDecimal getBillingAccountReturnedRefundTotalBd() {
return getBillingAccountReturnedTotalByTypeBd("RTN_REFUND");
}
/** Gets the total return credited amount with refunds and credits to the billing account figured in */
public BigDecimal getReturnedCreditTotalWithBillingAccountBd() {
return getOrderReturnedCreditTotalBd().add(getBillingAccountReturnedRefundTotalBd()).subtract(getBillingAccountReturnedCreditTotalBd());
}
/** Gets the total return refund amount with refunds and credits to the billing account figured in */
public BigDecimal getReturnedRefundTotalWithBillingAccountBd() {
return getOrderReturnedRefundTotalBd().add(getBillingAccountReturnedCreditTotalBd()).subtract(getBillingAccountReturnedRefundTotalBd());
}
public BigDecimal getOrderBackorderQuantity() {
BigDecimal backorder = ZERO;
List<GenericValue> items = this.getValidOrderItems();
if (items != null) {
for (GenericValue item : items) {
List<GenericValue> reses = this.getOrderItemShipGrpInvResList(item);
if (reses != null) {
for (GenericValue res : reses) {
BigDecimal nav = res.getBigDecimal("quantityNotAvailable");
if (nav != null) {
backorder = backorder.add(nav).setScale(scale, rounding);
}
}
}
}
}
return backorder.setScale(scale, rounding);
}
public BigDecimal getItemPickedQuantityBd(GenericValue orderItem) {
BigDecimal quantityPicked = ZERO;
EntityConditionList<EntityExpr> pickedConditions = EntityCondition.makeCondition(UtilMisc.toList(
EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderItem.get("orderId")),
EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItem.getString("orderItemSeqId")),
EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PICKLIST_CANCELLED")),
EntityOperator.AND);
List<GenericValue> picked = null;
try {
picked = orderHeader.getDelegator().findList("PicklistAndBinAndItem", pickedConditions, null, null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
this.orderHeader = null;
}
if (picked != null) {
for (GenericValue pickedItem : picked) {
BigDecimal issueQty = pickedItem.getBigDecimal("quantity");
if (issueQty != null) {
quantityPicked = quantityPicked.add(issueQty).setScale(scale, rounding);
}
}
}
return quantityPicked.setScale(scale, rounding);
}
public BigDecimal getItemShippedQuantity(GenericValue orderItem) {
BigDecimal quantityShipped = ZERO;
List<GenericValue> issuance = getOrderItemIssuances(orderItem);
if (issuance != null) {
for (GenericValue issue : issuance) {
BigDecimal issueQty = issue.getBigDecimal("quantity");
BigDecimal cancelQty = issue.getBigDecimal("cancelQuantity");
if (cancelQty == null) {
cancelQty = ZERO;
}
if (issueQty == null) {
issueQty = ZERO;
}
quantityShipped = quantityShipped.add(issueQty.subtract(cancelQty)).setScale(scale, rounding);
}
}
return quantityShipped.setScale(scale, rounding);
}
public BigDecimal getItemShipGroupAssocShippedQuantity(GenericValue orderItem, String shipGroupSeqId) {
BigDecimal quantityShipped = ZERO;
if (orderItem == null) {
return null;
}
if (this.orderItemIssuances == null) {
Delegator delegator = orderItem.getDelegator();
try {
orderItemIssuances = EntityQuery.use(delegator).from("ItemIssuance").where("orderId", orderItem.get("orderId"), "shipGroupSeqId", shipGroupSeqId).queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Trouble getting ItemIssuance(s)", module);
}
}
// filter the issuance
Map<String, Object> filter = UtilMisc.toMap("orderItemSeqId", orderItem.get("orderItemSeqId"), "shipGroupSeqId", shipGroupSeqId);
List<GenericValue> issuances = EntityUtil.filterByAnd(orderItemIssuances, filter);
if (UtilValidate.isNotEmpty(issuances)) {
for (GenericValue issue : issuances) {
BigDecimal issueQty = issue.getBigDecimal("quantity");
BigDecimal cancelQty = issue.getBigDecimal("cancelQuantity");
if (cancelQty == null) {
cancelQty = ZERO;
}
if (issueQty == null) {
issueQty = ZERO;
}
quantityShipped = quantityShipped.add(issueQty.subtract(cancelQty)).setScale(scale, rounding);
}
}
return quantityShipped.setScale(scale, rounding);
}
public BigDecimal getItemReservedQuantity(GenericValue orderItem) {
BigDecimal reserved = ZERO;
List<GenericValue> reses = getOrderItemShipGrpInvResList(orderItem);
if (reses != null) {
for (GenericValue res : reses) {
BigDecimal quantity = res.getBigDecimal("quantity");
if (quantity != null) {
reserved = reserved.add(quantity).setScale(scale, rounding);
}
}
}
return reserved.setScale(scale, rounding);
}
public BigDecimal getItemBackorderedQuantity(GenericValue orderItem) {
BigDecimal backOrdered = ZERO;
Timestamp shipDate = orderItem.getTimestamp("estimatedShipDate");
Timestamp autoCancel = orderItem.getTimestamp("autoCancelDate");
List<GenericValue> reses = getOrderItemShipGrpInvResList(orderItem);
if (reses != null) {
for (GenericValue res : reses) {
Timestamp promised = res.getTimestamp("currentPromisedDate");
if (promised == null) {
promised = res.getTimestamp("promisedDatetime");
}
if (autoCancel != null || (shipDate != null && shipDate.after(promised))) {
BigDecimal resQty = res.getBigDecimal("quantity");
if (resQty != null) {
backOrdered = backOrdered.add(resQty).setScale(scale, rounding);
}
}
}
}
return backOrdered;
}
public BigDecimal getItemPendingShipmentQuantity(GenericValue orderItem) {
BigDecimal reservedQty = getItemReservedQuantity(orderItem);
BigDecimal backordered = getItemBackorderedQuantity(orderItem);
return reservedQty.subtract(backordered).setScale(scale, rounding);
}
public BigDecimal getItemCanceledQuantity(GenericValue orderItem) {
BigDecimal cancelQty = orderItem.getBigDecimal("cancelQuantity");
if (cancelQty == null) {
cancelQty = BigDecimal.ZERO;
}
return cancelQty;
}
public BigDecimal getTotalOrderItemsQuantity() {
List<GenericValue> orderItems = getValidOrderItems();
BigDecimal totalItems = ZERO;
for (int i = 0; i < orderItems.size(); i++) {
GenericValue oi = orderItems.get(i);
totalItems = totalItems.add(getOrderItemQuantity(oi)).setScale(scale, rounding);
}
return totalItems.setScale(scale, rounding);
}
public BigDecimal getTotalOrderItemsOrderedQuantity() {
List<GenericValue> orderItems = getValidOrderItems();
BigDecimal totalItems = ZERO;
for (int i = 0; i < orderItems.size(); i++) {
GenericValue oi = orderItems.get(i);
totalItems = totalItems.add(oi.getBigDecimal("quantity")).setScale(scale, rounding);
}
return totalItems;
}
public BigDecimal getOrderItemsSubTotal() {
return getOrderItemsSubTotal(getValidOrderItems(), getAdjustments());
}
public BigDecimal getOrderItemSubTotal(GenericValue orderItem) {
return getOrderItemSubTotal(orderItem, getAdjustments());
}
public BigDecimal getOrderItemsTotal() {
return getOrderItemsTotal(getValidOrderItems(), getAdjustments());
}
public BigDecimal getOrderItemTotal(GenericValue orderItem) {
return getOrderItemTotal(orderItem, getAdjustments());
}
public BigDecimal getOrderItemTax(GenericValue orderItem) {
return getOrderItemAdjustmentsTotal(orderItem, false, true, false);
}
public BigDecimal getOrderItemShipping(GenericValue orderItem) {
return getOrderItemAdjustmentsTotal(orderItem, false, false, true);
}
public BigDecimal getOrderItemAdjustmentsTotal(GenericValue orderItem, boolean includeOther, boolean includeTax, boolean includeShipping) {
return getOrderItemAdjustmentsTotal(orderItem, getAdjustments(), includeOther, includeTax, includeShipping);
}
public BigDecimal getOrderItemAdjustmentsTotal(GenericValue orderItem) {
return getOrderItemAdjustmentsTotal(orderItem, true, false, false);
}
public BigDecimal getOrderItemAdjustmentTotal(GenericValue orderItem, GenericValue adjustment) {
return calcItemAdjustment(adjustment, orderItem);
}
public String getAdjustmentType(GenericValue adjustment) {
GenericValue adjustmentType = null;
try {
adjustmentType = adjustment.getRelatedOne("OrderAdjustmentType", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problems with order adjustment", module);
}
if (adjustmentType == null || adjustmentType.get("description") == null) {
return "";
}
return adjustmentType.getString("description");
}
public List<GenericValue> getOrderItemStatuses(GenericValue orderItem) {
return getOrderItemStatuses(orderItem, getOrderStatuses());
}
public String getCurrentItemStatusString(GenericValue orderItem) {
GenericValue statusItem = null;
try {
statusItem = orderItem.getRelatedOne("StatusItem", true);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (statusItem != null) {
return statusItem.getString("description");
}
return orderHeader.getString("statusId");
}
/** Fetches the set of order items with the given EntityCondition. */
public List<GenericValue> getOrderItemsByCondition(EntityCondition entityCondition) {
return EntityUtil.filterByCondition(getOrderItems(), entityCondition);
}
public Set<String> getProductPromoCodesEntered() {
Delegator delegator = orderHeader.getDelegator();
Set<String> productPromoCodesEntered = new HashSet<>();
try {
for (GenericValue orderProductPromoCode : EntityQuery.use(delegator).from("OrderProductPromoCode").where("orderId", orderHeader.get("orderId")).cache().queryList()) {
productPromoCodesEntered.add(orderProductPromoCode.getString("productPromoCodeId"));
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return productPromoCodesEntered;
}
public List<GenericValue> getProductPromoUse() {
Delegator delegator = orderHeader.getDelegator();
try {
return EntityQuery.use(delegator).from("ProductPromoUse").where("orderId", orderHeader.get("orderId")).cache().queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return new ArrayList<>();
}
/**
* Checks to see if this user has read permission on this order
* @param userLogin The UserLogin value object to check
* @return boolean True if we have read permission
*/
public boolean hasPermission(Security security, GenericValue userLogin) {
return OrderReadHelper.hasPermission(security, userLogin, orderHeader);
}
/**
* Getter for property orderHeader.
* @return Value of property orderHeader.
*/
public GenericValue getOrderHeader() {
return orderHeader;
}
// ======================================================
// =================== Static Methods ===================
// ======================================================
public static GenericValue getOrderHeader(Delegator delegator, String orderId) {
GenericValue orderHeader = null;
if (orderId != null && delegator != null) {
try {
orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Cannot get order header for orderId [" + orderId + "]", module); // SCIPIO: Improved logging
}
}
return orderHeader;
}
public static BigDecimal getOrderItemQuantity(GenericValue orderItem) {
BigDecimal cancelQty = orderItem.getBigDecimal("cancelQuantity");
BigDecimal orderQty = orderItem.getBigDecimal("quantity");
if (cancelQty == null) {
cancelQty = ZERO;
}
if (orderQty == null) {
orderQty = ZERO;
}
return orderQty.subtract(cancelQty);
}
public static BigDecimal getOrderItemShipGroupQuantity(GenericValue shipGroupAssoc) {
BigDecimal cancelQty = shipGroupAssoc.getBigDecimal("cancelQuantity");
BigDecimal orderQty = shipGroupAssoc.getBigDecimal("quantity");
if (cancelQty == null) {
cancelQty = BigDecimal.ZERO;
}
if (orderQty == null) {
orderQty = BigDecimal.ZERO;
}
return orderQty.subtract(cancelQty);
}
public static GenericValue getProductStoreFromOrder(Delegator delegator, String orderId) {
GenericValue orderHeader = getOrderHeader(delegator, orderId);
if (orderHeader == null) {
Debug.logError("Could not find OrderHeader for orderId [" + orderId + "] in getProductStoreFromOrder, returning null", module); // SCIPIO: Changed to error, why ever?
}
return getProductStoreFromOrder(orderHeader);
}
public static GenericValue getProductStoreFromOrder(GenericValue orderHeader) {
if (orderHeader == null) {
return null;
}
Delegator delegator = orderHeader.getDelegator();
GenericValue productStore = null;
if (orderHeader.get("productStoreId") != null) {
try {
productStore = EntityQuery.use(delegator).from("ProductStore").where("productStoreId", orderHeader.getString("productStoreId")).cache().queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Cannot locate ProductStore from OrderHeader for orderId [" + orderHeader.get("orderId") + "]", module);
}
} else {
Debug.logError("Null header or productStoreId for orderId [" + orderHeader.get("orderId") + "]", module);
}
return productStore;
}
public static BigDecimal getOrderGrandTotal(List<GenericValue> orderItems, List<GenericValue> adjustments) {
Map<String, Object> orderTaxByTaxAuthGeoAndParty = getOrderTaxByTaxAuthGeoAndParty(adjustments);
BigDecimal taxGrandTotal = (BigDecimal) orderTaxByTaxAuthGeoAndParty.get("taxGrandTotal");
adjustments = EntityUtil.filterByAnd(adjustments, UtilMisc.toList(EntityCondition.makeCondition("orderAdjustmentTypeId", EntityOperator.NOT_EQUAL, "SALES_TAX")));
BigDecimal total = getOrderItemsTotal(orderItems, adjustments);
BigDecimal adj = getOrderAdjustmentsTotal(orderItems, adjustments);
total = ((total.add(taxGrandTotal)).add(adj)).setScale(scale, rounding);
return total;
}
public static List<GenericValue> getOrderHeaderAdjustments(List<GenericValue> adjustments, String shipGroupSeqId) {
List<EntityExpr> contraints1 = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, null));
List<EntityExpr> contraints2 = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, DataModelConstants.SEQ_ID_NA));
List<EntityExpr> contraints3 = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, ""));
List<EntityExpr> contraints4 = new ArrayList<>();
if (shipGroupSeqId != null) {
contraints4.add(EntityCondition.makeCondition("shipGroupSeqId", EntityOperator.EQUALS, shipGroupSeqId));
}
List<GenericValue> toFilter = null;
List<GenericValue> adj = new ArrayList<>();
if (shipGroupSeqId != null) {
toFilter = EntityUtil.filterByAnd(adjustments, contraints4);
} else {
toFilter = adjustments;
}
adj.addAll(EntityUtil.filterByAnd(toFilter, contraints1));
adj.addAll(EntityUtil.filterByAnd(toFilter, contraints2));
adj.addAll(EntityUtil.filterByAnd(toFilter, contraints3));
return adj;
}
public static List<GenericValue> getOrderHeaderStatuses(List<GenericValue> orderStatuses) {
List<EntityExpr> contraints1 = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, null));
contraints1.add(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, DataModelConstants.SEQ_ID_NA));
contraints1.add(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, ""));
List<EntityExpr> contraints2 = UtilMisc.toList(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.EQUALS, null));
contraints2.add(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.EQUALS, DataModelConstants.SEQ_ID_NA));
contraints2.add(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.EQUALS, ""));
List<GenericValue> newOrderStatuses = new ArrayList<>();
newOrderStatuses.addAll(EntityUtil.filterByOr(orderStatuses, contraints1));
return EntityUtil.orderBy(EntityUtil.filterByOr(newOrderStatuses, contraints2), UtilMisc.toList("-statusDatetime"));
}
public static BigDecimal getOrderAdjustmentsTotal(List<GenericValue> orderItems, List<GenericValue> adjustments) {
return calcOrderAdjustments(getOrderHeaderAdjustments(adjustments, null), getOrderItemsSubTotal(orderItems, adjustments), true, true, true);
}
public static List<GenericValue> getOrderSurveyResponses(GenericValue orderHeader) {
Delegator delegator = orderHeader.getDelegator();
String orderId = orderHeader.getString("orderId");
List<GenericValue> responses = null;
try {
responses = EntityQuery.use(delegator).from("SurveyResponse").where("orderId", orderId, "orderItemSeqId", "_NA_").queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (responses == null) {
responses = new ArrayList<>();
}
return responses;
}
public static List<GenericValue> getOrderItemSurveyResponse(GenericValue orderItem) {
Delegator delegator = orderItem.getDelegator();
String orderItemSeqId = orderItem.getString("orderItemSeqId");
String orderId = orderItem.getString("orderId");
List<GenericValue> responses = null;
try {
responses = EntityQuery.use(delegator).from("SurveyResponse").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (responses == null) {
responses = new ArrayList<>();
}
return responses;
}
// ================= Order Adjustments =================
public static BigDecimal calcOrderAdjustments(List<GenericValue> orderHeaderAdjustments, BigDecimal subTotal, boolean includeOther, boolean includeTax, boolean includeShipping) {
BigDecimal adjTotal = ZERO;
if (UtilValidate.isNotEmpty(orderHeaderAdjustments)) {
List<GenericValue> filteredAdjs = filterOrderAdjustments(orderHeaderAdjustments, includeOther, includeTax, includeShipping, false, false);
for (GenericValue orderAdjustment : filteredAdjs) {
adjTotal = adjTotal.add(OrderReadHelper.calcOrderAdjustment(orderAdjustment, subTotal)).setScale(scale, rounding);
}
}
return adjTotal.setScale(scale, rounding);
}
public static BigDecimal calcOrderAdjustment(GenericValue orderAdjustment, BigDecimal orderSubTotal) {
BigDecimal adjustment = ZERO;
if (orderAdjustment.get("amount") != null) {
BigDecimal amount = orderAdjustment.getBigDecimal("amount");
adjustment = adjustment.add(amount);
} else if (orderAdjustment.get("sourcePercentage") != null) {
BigDecimal percent = orderAdjustment.getBigDecimal("sourcePercentage");
BigDecimal amount = orderSubTotal.multiply(percent).multiply(percentage);
adjustment = adjustment.add(amount);
}
if ("SALES_TAX".equals(orderAdjustment.get("orderAdjustmentTypeId"))) {
return adjustment.setScale(taxCalcScale, taxRounding);
}
return adjustment.setScale(scale, rounding);
}
// ================= Order Item Adjustments =================
public static BigDecimal getOrderItemsSubTotal(List<GenericValue> orderItems, List<GenericValue> adjustments) {
return getOrderItemsSubTotal(orderItems, adjustments, null);
}
public static BigDecimal getOrderItemsSubTotal(List<GenericValue> orderItems, List<GenericValue> adjustments, List<GenericValue> workEfforts) {
BigDecimal result = ZERO;
Iterator<GenericValue> itemIter = UtilMisc.toIterator(orderItems);
while (itemIter != null && itemIter.hasNext()) {
GenericValue orderItem = itemIter.next();
BigDecimal itemTotal = getOrderItemSubTotal(orderItem, adjustments);
if (workEfforts != null && orderItem.getString("orderItemTypeId").compareTo("RENTAL_ORDER_ITEM") == 0) {
Iterator<GenericValue> weIter = UtilMisc.toIterator(workEfforts);
while (weIter != null && weIter.hasNext()) {
GenericValue workEffort = weIter.next();
if (workEffort.getString("workEffortId").compareTo(orderItem.getString("orderItemSeqId")) == 0) {
itemTotal = itemTotal.multiply(getWorkEffortRentalQuantity(workEffort)).setScale(scale, rounding);
break;
}
}
}
result = result.add(itemTotal).setScale(scale, rounding);
}
return result.setScale(scale, rounding);
}
/** The passed adjustments can be all adjustments for the order, ie for all line items */
public static BigDecimal getOrderItemSubTotal(GenericValue orderItem, List<GenericValue> adjustments) {
return getOrderItemSubTotal(orderItem, adjustments, false, false);
}
/** The passed adjustments can be all adjustments for the order, ie for all line items */
public static BigDecimal getOrderItemSubTotal(GenericValue orderItem, List<GenericValue> adjustments, boolean forTax, boolean forShipping) {
BigDecimal unitPrice = orderItem.getBigDecimal("unitPrice");
BigDecimal quantity = getOrderItemQuantity(orderItem);
BigDecimal result = ZERO;
if (unitPrice == null || quantity == null) {
Debug.logWarning("[getOrderItemTotal] unitPrice or quantity are null, using 0 for the item base price", module);
} else {
if (Debug.verboseOn()) {
Debug.logVerbose("Unit Price : " + unitPrice + " / " + "Quantity : " + quantity, module);
}
result = unitPrice.multiply(quantity);
if ("RENTAL_ORDER_ITEM".equals(orderItem.getString("orderItemTypeId"))) {
// retrieve related work effort when required.
List<GenericValue> workOrderItemFulfillments = null;
try {
workOrderItemFulfillments = orderItem.getDelegator().findByAnd("WorkOrderItemFulfillment", UtilMisc.toMap("orderId", orderItem.getString("orderId"), "orderItemSeqId", orderItem.getString("orderItemSeqId")), null, true);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (workOrderItemFulfillments != null) {
Iterator<GenericValue> iter = workOrderItemFulfillments.iterator();
if (iter.hasNext()) {
GenericValue WorkOrderItemFulfillment = iter.next();
GenericValue workEffort = null;
try {
workEffort = WorkOrderItemFulfillment.getRelatedOne("WorkEffort", true);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
result = result.multiply(getWorkEffortRentalQuantity(workEffort));
}
}
}
}
// subtotal also includes non tax and shipping adjustments; tax and shipping will be calculated using this adjusted value
result = result.add(getOrderItemAdjustmentsTotal(orderItem, adjustments, true, false, false, forTax, forShipping));
return result.setScale(scale, rounding);
}
public static BigDecimal getOrderItemsTotal(List<GenericValue> orderItems, List<GenericValue> adjustments) {
BigDecimal result = ZERO;
Iterator<GenericValue> itemIter = UtilMisc.toIterator(orderItems);
while (itemIter != null && itemIter.hasNext()) {
result = result.add(getOrderItemTotal(itemIter.next(), adjustments));
}
return result.setScale(scale, rounding);
}
public static BigDecimal getOrderItemTotal(GenericValue orderItem, List<GenericValue> adjustments) {
// add tax and shipping to subtotal
return getOrderItemSubTotal(orderItem, adjustments).add(getOrderItemAdjustmentsTotal(orderItem, adjustments, false, true, true));
}
public static BigDecimal calcOrderPromoAdjustmentsBd(List<GenericValue> allOrderAdjustments) {
BigDecimal promoAdjTotal = ZERO;
List<GenericValue> promoAdjustments = EntityUtil.filterByAnd(allOrderAdjustments, UtilMisc.toMap("orderAdjustmentTypeId", "PROMOTION_ADJUSTMENT"));
if (UtilValidate.isNotEmpty(promoAdjustments)) {
Iterator<GenericValue> promoAdjIter = promoAdjustments.iterator();
while (promoAdjIter.hasNext()) {
GenericValue promoAdjustment = promoAdjIter.next();
if (promoAdjustment != null) {
BigDecimal amount = promoAdjustment.getBigDecimal("amount").setScale(taxCalcScale, taxRounding);
promoAdjTotal = promoAdjTotal.add(amount);
}
}
}
return promoAdjTotal.setScale(scale, rounding);
}
public static BigDecimal getWorkEffortRentalLength(GenericValue workEffort) {
BigDecimal length = null;
if (workEffort.get("estimatedStartDate") != null && workEffort.get("estimatedCompletionDate") != null) {
length = new BigDecimal(UtilDateTime.getInterval(workEffort.getTimestamp("estimatedStartDate"), workEffort.getTimestamp("estimatedCompletionDate")) / 86400000);
}
return length;
}
public static BigDecimal getWorkEffortRentalQuantity(GenericValue workEffort) {
BigDecimal persons = BigDecimal.ONE;
if (workEffort.get("reservPersons") != null) {
persons = workEffort.getBigDecimal("reservPersons");
}
BigDecimal secondPersonPerc = ZERO;
if (workEffort.get("reserv2ndPPPerc") != null) {
secondPersonPerc = workEffort.getBigDecimal("reserv2ndPPPerc");
}
BigDecimal nthPersonPerc = ZERO;
if (workEffort.get("reservNthPPPerc") != null) {
nthPersonPerc = workEffort.getBigDecimal("reservNthPPPerc");
}
long length = 1;
if (workEffort.get("estimatedStartDate") != null && workEffort.get("estimatedCompletionDate") != null) {
length = (workEffort.getTimestamp("estimatedCompletionDate").getTime() - workEffort.getTimestamp("estimatedStartDate").getTime()) / 86400000;
}
BigDecimal rentalAdjustment = ZERO;
if (persons.compareTo(BigDecimal.ONE) == 1) {
if (persons.compareTo(new BigDecimal(2)) == 1) {
persons = persons.subtract(new BigDecimal(2));
if (nthPersonPerc.signum() == 1) {
rentalAdjustment = persons.multiply(nthPersonPerc);
} else {
rentalAdjustment = persons.multiply(secondPersonPerc);
}
persons = new BigDecimal("2");
}
if (persons.compareTo(new BigDecimal("2")) == 0) {
rentalAdjustment = rentalAdjustment.add(secondPersonPerc);
}
}
rentalAdjustment = rentalAdjustment.add(new BigDecimal(100)); // add final 100 percent for first person
rentalAdjustment = rentalAdjustment.divide(new BigDecimal(100), scale, rounding).multiply(new BigDecimal(String.valueOf(length)));
return rentalAdjustment; // return total rental adjustment
}
public static BigDecimal getAllOrderItemsAdjustmentsTotal(List<GenericValue> orderItems, List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping) {
BigDecimal result = ZERO;
Iterator<GenericValue> itemIter = UtilMisc.toIterator(orderItems);
while (itemIter != null && itemIter.hasNext()) {
result = result.add(getOrderItemAdjustmentsTotal(itemIter.next(), adjustments, includeOther, includeTax, includeShipping));
}
return result.setScale(scale, rounding);
}
/** The passed adjustments can be all adjustments for the order, ie for all line items */
public static BigDecimal getOrderItemAdjustmentsTotal(GenericValue orderItem, List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping) {
return getOrderItemAdjustmentsTotal(orderItem, adjustments, includeOther, includeTax, includeShipping, false, false);
}
/** The passed adjustments can be all adjustments for the order, ie for all line items */
public static BigDecimal getOrderItemAdjustmentsTotal(GenericValue orderItem, List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
return calcItemAdjustments(getOrderItemQuantity(orderItem), orderItem.getBigDecimal("unitPrice"),
getOrderItemAdjustmentList(orderItem, adjustments),
includeOther, includeTax, includeShipping, forTax, forShipping);
}
public static List<GenericValue> getOrderItemAdjustmentList(GenericValue orderItem, List<GenericValue> adjustments) {
return EntityUtil.filterByAnd(adjustments, UtilMisc.toMap("orderItemSeqId", orderItem.get("orderItemSeqId")));
}
public static List<GenericValue> getOrderItemStatuses(GenericValue orderItem, List<GenericValue> orderStatuses) {
List<EntityExpr> contraints1 = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItem.get("orderItemSeqId")));
List<EntityExpr> contraints2 = UtilMisc.toList(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.EQUALS, null));
contraints2.add(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.EQUALS, DataModelConstants.SEQ_ID_NA));
contraints2.add(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.EQUALS, ""));
List<GenericValue> newOrderStatuses = new ArrayList<>();
newOrderStatuses.addAll(EntityUtil.filterByAnd(orderStatuses, contraints1));
return EntityUtil.orderBy(EntityUtil.filterByOr(newOrderStatuses, contraints2), UtilMisc.toList("-statusDatetime"));
}
// Order Item Adjs Utility Methods
public static BigDecimal calcItemAdjustments(BigDecimal quantity, BigDecimal unitPrice, List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
BigDecimal adjTotal = ZERO;
if (UtilValidate.isNotEmpty(adjustments)) {
List<GenericValue> filteredAdjs = filterOrderAdjustments(adjustments, includeOther, includeTax, includeShipping, forTax, forShipping);
for (GenericValue orderAdjustment : filteredAdjs) {
adjTotal = adjTotal.add(OrderReadHelper.calcItemAdjustment(orderAdjustment, quantity, unitPrice));
}
}
return adjTotal;
}
public static BigDecimal calcItemAdjustmentsRecurringBd(BigDecimal quantity, BigDecimal unitPrice, List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
BigDecimal adjTotal = ZERO;
if (UtilValidate.isNotEmpty(adjustments)) {
List<GenericValue> filteredAdjs = filterOrderAdjustments(adjustments, includeOther, includeTax, includeShipping, forTax, forShipping);
for (GenericValue orderAdjustment : filteredAdjs) {
adjTotal = adjTotal.add(OrderReadHelper.calcItemAdjustmentRecurringBd(orderAdjustment, quantity, unitPrice)).setScale(scale, rounding);
}
}
return adjTotal;
}
public static BigDecimal calcItemAdjustment(GenericValue itemAdjustment, GenericValue item) {
return calcItemAdjustment(itemAdjustment, getOrderItemQuantity(item), item.getBigDecimal("unitPrice"));
}
public static BigDecimal calcItemAdjustment(GenericValue itemAdjustment, BigDecimal quantity, BigDecimal unitPrice) {
BigDecimal adjustment = ZERO;
if (itemAdjustment.get("amount") != null) {
// shouldn't round amounts here, wait until item total is added up otherwise incremental errors are introduced, and there is code that calls this method that does that already:
//adjustment = adjustment.add(setScaleByType("SALES_TAX".equals(itemAdjustment.get("orderAdjustmentTypeId")), itemAdjustment.getBigDecimal("amount")));
adjustment = adjustment.add(itemAdjustment.getBigDecimal("amount"));
} else if (itemAdjustment.get("sourcePercentage") != null) {
// see comment above about rounding:
//adjustment = adjustment.add(setScaleByType("SALES_TAX".equals(itemAdjustment.get("orderAdjustmentTypeId")), itemAdjustment.getBigDecimal("sourcePercentage").multiply(quantity).multiply(unitPrice).multiply(percentage)));
adjustment = adjustment.add(itemAdjustment.getBigDecimal("sourcePercentage").multiply(quantity).multiply(unitPrice).multiply(percentage));
}
if (Debug.verboseOn()) {
Debug.logVerbose("calcItemAdjustment: " + itemAdjustment + ", quantity=" + quantity + ", unitPrice=" + unitPrice + ", adjustment=" + adjustment, module);
}
return adjustment;
}
public static BigDecimal calcItemAdjustmentRecurringBd(GenericValue itemAdjustment, BigDecimal quantity, BigDecimal unitPrice) {
BigDecimal adjustmentRecurring = ZERO;
if (itemAdjustment.get("recurringAmount") != null) {
adjustmentRecurring = adjustmentRecurring.add(setScaleByType("SALES_TAX".equals(itemAdjustment.get("orderAdjustmentTypeId")), itemAdjustment.getBigDecimal("recurringAmount")));
}
if (Debug.verboseOn()) {
Debug.logVerbose("calcItemAdjustmentRecurring: " + itemAdjustment + ", quantity=" + quantity + ", unitPrice=" + unitPrice + ", adjustmentRecurring=" + adjustmentRecurring, module);
}
return adjustmentRecurring.setScale(scale, rounding);
}
public static List<GenericValue> filterOrderAdjustments(List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
List<GenericValue> newOrderAdjustmentsList = new ArrayList<>();
if (UtilValidate.isNotEmpty(adjustments)) {
for (GenericValue orderAdjustment : adjustments) {
boolean includeAdjustment = false;
if ("SALES_TAX".equals(orderAdjustment.getString("orderAdjustmentTypeId")) ||
"VAT_TAX".equals(orderAdjustment.getString("orderAdjustmentTypeId")) ||
"VAT_PRICE_CORRECT".equals(orderAdjustment.getString("orderAdjustmentTypeId"))) {
if (includeTax) {
includeAdjustment = true;
}
} else if ("SHIPPING_CHARGES".equals(orderAdjustment.getString("orderAdjustmentTypeId"))) {
if (includeShipping) {
includeAdjustment = true;
}
} else {
if (includeOther) {
includeAdjustment = true;
}
}
// default to yes, include for shipping; so only exclude if includeInShipping is N, or false; if Y or null or anything else it will be included
if (forTax && "N".equals(orderAdjustment.getString("includeInTax"))) {
includeAdjustment = false;
}
// default to yes, include for shipping; so only exclude if includeInShipping is N, or false; if Y or null or anything else it will be included
if (forShipping && "N".equals(orderAdjustment.getString("includeInShipping"))) {
includeAdjustment = false;
}
if (includeAdjustment) {
newOrderAdjustmentsList.add(orderAdjustment);
}
}
}
return newOrderAdjustmentsList;
}
public static BigDecimal getQuantityOnOrder(Delegator delegator, String productId) {
BigDecimal quantity = BigDecimal.ZERO;
// first find all open purchase orders
List<GenericValue> openOrders = null;
try {
openOrders = EntityQuery.use(delegator).from("OrderHeaderAndItems")
.where(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "PURCHASE_ORDER"),
EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"),
EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED"),
EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_COMPLETED"),
EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId))
.queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (UtilValidate.isNotEmpty(openOrders)) {
for (GenericValue order : openOrders) {
BigDecimal thisQty = order.getBigDecimal("quantity");
if (thisQty == null) {
thisQty = BigDecimal.ZERO;
}
quantity = quantity.add(thisQty);
}
}
return quantity;
}
/**
* Checks to see if this user has read permission on the specified order
* @param userLogin The UserLogin value object to check
* @param orderHeader The OrderHeader for the specified order
* @return boolean True if we have read permission
*/
public static boolean hasPermission(Security security, GenericValue userLogin, GenericValue orderHeader) {
if (userLogin == null || orderHeader == null) {
return false;
}
if (security.hasEntityPermission("ORDERMGR", "_VIEW", userLogin)) {
return true;
} else if (security.hasEntityPermission("ORDERMGR", "_ROLEVIEW", userLogin)) {
List<GenericValue> orderRoles = null;
try {
orderRoles = orderHeader.getRelated("OrderRole", UtilMisc.toMap("partyId", userLogin.getString("partyId")), null, false);
} catch (GenericEntityException e) {
Debug.logError(e, "Cannot get OrderRole from OrderHeader", module);
}
if (UtilValidate.isNotEmpty(orderRoles)) {
// we are in at least one role
return true;
}
}
return false;
}
public static OrderReadHelper getHelper(GenericValue orderHeader) {
return new OrderReadHelper(orderHeader);
}
/**
* Get orderAdjustments that have no corresponding returnAdjustment
* @return return the order adjustments that have no corresponding with return adjustment
*/
public List<GenericValue> getAvailableOrderHeaderAdjustments() {
List<GenericValue> orderHeaderAdjustments = this.getOrderHeaderAdjustments();
List<GenericValue> filteredAdjustments = new ArrayList<>();
for (GenericValue orderAdjustment : orderHeaderAdjustments) {
long count = 0;
try {
count = orderHeader.getDelegator().findCountByCondition("ReturnAdjustment",
EntityCondition.makeCondition("orderAdjustmentId", EntityOperator.EQUALS, orderAdjustment.get("orderAdjustmentId")), null, null);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (count == 0) {
filteredAdjustments.add(orderAdjustment);
}
}
return filteredAdjustments;
}
/**
* Get the total return adjustments for a set of key -> value condition pairs. Done for code efficiency.
* @param delegator the delegator
* @param condition a map of the conditions to use
* @return Get the total return adjustments
*/
public static BigDecimal getReturnAdjustmentTotal(Delegator delegator, Map<String, Object> condition) {
BigDecimal total = ZERO;
List<GenericValue> adjustments;
try {
// TODO: find on a view-entity with a sum is probably more efficient
adjustments = EntityQuery.use(delegator).from("ReturnAdjustment").where(condition).queryList();
if (adjustments != null) {
for (GenericValue returnAdjustment : adjustments) {
total = total.add(setScaleByType("RET_SALES_TAX_ADJ".equals(returnAdjustment.get("returnAdjustmentTypeId")), returnAdjustment.getBigDecimal("amount")));
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return total;
}
// little helper method to set the scale according to tax type
public static BigDecimal setScaleByType(boolean isTax, BigDecimal value) {
return isTax ? value.setScale(taxCalcScale, taxRounding) : value.setScale(scale, rounding);
}
/** Get the quantity of order items that have been invoiced */
public static BigDecimal getOrderItemInvoicedQuantity(GenericValue orderItem) {
BigDecimal invoiced = BigDecimal.ZERO;
try {
// this is simply the sum of quantity billed in all related OrderItemBillings
List<GenericValue> billings = orderItem.getRelated("OrderItemBilling", null, null, false);
for (GenericValue billing : billings) {
BigDecimal quantity = billing.getBigDecimal("quantity");
if (quantity != null) {
invoiced = invoiced.add(quantity);
}
}
} catch (GenericEntityException e) {
Debug.logError(e, e.getMessage(), module);
}
return invoiced;
}
public List<GenericValue> getOrderPaymentStatuses() {
return getOrderPaymentStatuses(getOrderStatuses());
}
public static List<GenericValue> getOrderPaymentStatuses(List<GenericValue> orderStatuses) {
List<EntityExpr> contraints1 = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, null));
contraints1.add(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, DataModelConstants.SEQ_ID_NA));
contraints1.add(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, ""));
List<EntityExpr> contraints2 = UtilMisc.toList(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.NOT_EQUAL, null));
List<GenericValue> newOrderStatuses = new ArrayList<>();
newOrderStatuses.addAll(EntityUtil.filterByOr(orderStatuses, contraints1));
return EntityUtil.orderBy(EntityUtil.filterByAnd(newOrderStatuses, contraints2), UtilMisc.toList("-statusDatetime"));
}
public static String getOrderItemAttribute(GenericValue orderItem, String attributeName) {
String attributeValue = null;
if (orderItem != null) {
try {
GenericValue orderItemAttribute = EntityUtil.getFirst(orderItem.getRelated("OrderItemAttribute", UtilMisc.toMap("attrName", attributeName), null, false));
if (orderItemAttribute != null) {
attributeValue = orderItemAttribute.getString("attrValue");
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
return attributeValue;
}
public String getOrderAttribute(String attributeName) {
String attributeValue = null;
if (orderHeader != null) {
try {
GenericValue orderAttribute = EntityUtil.getFirst(orderHeader.getRelated("OrderAttribute", UtilMisc.toMap("attrName", attributeName), null, false));
if (orderAttribute != null) {
attributeValue = orderAttribute.getString("attrValue");
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
return attributeValue;
}
/** SCIPIO: generalized the tax calculation */
public static Map<String, Object> getCommonOrderTaxByTaxAuthGeoAndParty(List<GenericValue> orderAdjustmentsOriginal) {
BigDecimal taxGrandTotal = BigDecimal.ZERO;
List<Map<String, Object>> taxByTaxAuthGeoAndPartyList = new ArrayList<>();
List<GenericValue> orderAdjustmentsToUse = new ArrayList<>();
if (UtilValidate.isNotEmpty(orderAdjustmentsOriginal)) {
orderAdjustmentsToUse.addAll(orderAdjustmentsOriginal);
// get orderAdjustment where orderAdjustmentTypeId is SALES_TAX.
orderAdjustmentsToUse = EntityUtil.orderBy(orderAdjustmentsToUse, UtilMisc.toList("taxAuthGeoId", "taxAuthPartyId"));
// get the list of all distinct taxAuthGeoId and taxAuthPartyId. It is for getting the number of taxAuthGeo and taxAuthPartyId in adjustments.
List<String> distinctTaxAuthGeoIdList = EntityUtil.getFieldListFromEntityList(orderAdjustmentsToUse, "taxAuthGeoId", true);
List<String> distinctTaxAuthPartyIdList = EntityUtil.getFieldListFromEntityList(orderAdjustmentsToUse, "taxAuthPartyId", true);
// Keep a list of amount that have been added to make sure none are missed (if taxAuth* information is missing)
List<GenericValue> processedAdjustments = new ArrayList<>();
// For each taxAuthGeoId get and add amount from orderAdjustment
for (String taxAuthGeoId : distinctTaxAuthGeoIdList) {
for (String taxAuthPartyId : distinctTaxAuthPartyIdList) {
// get all records for orderAdjustments filtered by taxAuthGeoId and taxAuthPartyId
List<GenericValue> orderAdjByTaxAuthGeoAndPartyIds = EntityUtil.filterByAnd(orderAdjustmentsToUse, UtilMisc.toMap("taxAuthGeoId", taxAuthGeoId, "taxAuthPartyId", taxAuthPartyId));
if (UtilValidate.isNotEmpty(orderAdjByTaxAuthGeoAndPartyIds)) {
BigDecimal totalAmount = BigDecimal.ZERO;
// Now for each orderAdjustment record get and add amount.
for (GenericValue orderAdjustment : orderAdjByTaxAuthGeoAndPartyIds) {
BigDecimal amount = orderAdjustment.getBigDecimal("amount");
if (amount != null) {
totalAmount = totalAmount.add(amount);
}
if ("VAT_TAX".equals(orderAdjustment.getString("orderAdjustmentTypeId")) &&
orderAdjustment.get("amountAlreadyIncluded") != null) {
// this is the only case where the VAT_TAX amountAlreadyIncluded should be added in, and should just be for display and not to calculate the order grandTotal
totalAmount = totalAmount.add(orderAdjustment.getBigDecimal("amountAlreadyIncluded"));
}
totalAmount = totalAmount.setScale(taxCalcScale, taxRounding);
processedAdjustments.add(orderAdjustment);
}
totalAmount = totalAmount.setScale(taxFinalScale, taxRounding);
taxByTaxAuthGeoAndPartyList.add(UtilMisc.<String, Object>toMap("taxAuthPartyId", taxAuthPartyId, "taxAuthGeoId", taxAuthGeoId, "totalAmount", totalAmount));
taxGrandTotal = taxGrandTotal.add(totalAmount);
}
}
}
// Process any adjustments that got missed
List<GenericValue> missedAdjustments = new ArrayList<>();
missedAdjustments.addAll(orderAdjustmentsToUse);
missedAdjustments.removeAll(processedAdjustments);
for (GenericValue orderAdjustment : missedAdjustments) {
taxGrandTotal = taxGrandTotal.add(orderAdjustment.getBigDecimal("amount").setScale(taxCalcScale, taxRounding));
}
taxGrandTotal = taxGrandTotal.setScale(taxFinalScale, taxRounding);
}
Map<String, Object> result = new HashMap<>();
result.put("taxByTaxAuthGeoAndPartyList", taxByTaxAuthGeoAndPartyList);
result.put("taxGrandTotal", taxGrandTotal);
return result;
}
public static Map<String, Object> getOrderSalesTaxByTaxAuthGeoAndParty(List<GenericValue> orderAdjustments) {
orderAdjustments = EntityUtil.filterByAnd(orderAdjustments, UtilMisc.toMap("orderAdjustmentTypeId", "SALES_TAX"));
return getCommonOrderTaxByTaxAuthGeoAndParty(orderAdjustments);
}
/** SCIPIO: Added VAT calculation */
public static Map<String, Object> getOrderVATTaxByTaxAuthGeoAndParty(List<GenericValue> orderAdjustments) {
orderAdjustments = EntityUtil.filterByAnd(orderAdjustments, UtilMisc.toMap("orderAdjustmentTypeId", "VAT_TAX"));
return getCommonOrderTaxByTaxAuthGeoAndParty(orderAdjustments);
}
public static Map<String, Object> getOrderTaxByTaxAuthGeoAndParty(List<GenericValue> orderAdjustments) {
orderAdjustments = EntityUtil.filterByAnd(orderAdjustments, UtilMisc.toMap("orderAdjustmentTypeId", "SALES_TAX"));
return getCommonOrderTaxByTaxAuthGeoAndParty(orderAdjustments);
}
public static Map<String, Object> getOrderTaxByTaxAuthGeoAndPartyForDisplay(List<GenericValue> orderAdjustmentsOriginal) {
orderAdjustmentsOriginal.addAll(EntityUtil.filterByAnd(orderAdjustmentsOriginal, UtilMisc.toMap("orderAdjustmentTypeId", "SALES_TAX")));
orderAdjustmentsOriginal.addAll(EntityUtil.filterByAnd(orderAdjustmentsOriginal, UtilMisc.toMap("orderAdjustmentTypeId", "VAT_TAX")));
return getCommonOrderTaxByTaxAuthGeoAndParty(orderAdjustmentsOriginal);
}
public static Map<String, Object> getOrderItemTaxByTaxAuthGeoAndPartyForDisplay(GenericValue orderItem, List<GenericValue> orderAdjustmentsOriginal) {
return getOrderTaxByTaxAuthGeoAndPartyForDisplay(getOrderItemAdjustmentList(orderItem, orderAdjustmentsOriginal));
}
public BigDecimal getTotalTax(List<GenericValue> taxAdjustments) {
Map<String, Object> taxByAuthority = OrderReadHelper.getOrderTaxByTaxAuthGeoAndParty(taxAdjustments);
BigDecimal taxTotal = (BigDecimal) taxByAuthority.get("taxGrandTotal");
return taxTotal;
}
/** SCIPIO: Added VAT Tax calculation */
public BigDecimal getTotalVATTax(List<GenericValue> taxAdjustments) {
Map<String, Object> taxByAuthority = OrderReadHelper.getOrderVATTaxByTaxAuthGeoAndParty(taxAdjustments);
BigDecimal taxTotal = (BigDecimal) taxByAuthority.get("taxGrandTotal");
return taxTotal;
}
/**
* Calculates the "available" balance of a billing account, which is the
* net balance minus amount of pending (not cancelled, rejected, or received) order payments.
* When looking at using a billing account for a new order, you should use this method.
* @param billingAccount the billing account record
* @return return the "available" balance of a billing account
* @throws GenericEntityException
*/
public static BigDecimal getBillingAccountBalance(GenericValue billingAccount) throws GenericEntityException {
Delegator delegator = billingAccount.getDelegator();
String billingAccountId = billingAccount.getString("billingAccountId");
BigDecimal balance = ZERO;
BigDecimal accountLimit = getAccountLimit(billingAccount);
balance = balance.add(accountLimit);
// pending (not cancelled, rejected, or received) order payments
List<GenericValue> orderPaymentPreferenceSums = EntityQuery.use(delegator)
.select("maxAmount")
.from("OrderPurchasePaymentSummary")
.where(EntityCondition.makeCondition("billingAccountId", EntityOperator.EQUALS, billingAccountId),
EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "EXT_BILLACT"),
EntityCondition.makeCondition("statusId", EntityOperator.NOT_IN, UtilMisc.toList("ORDER_CANCELLED", "ORDER_REJECTED")),
EntityCondition.makeCondition("preferenceStatusId", EntityOperator.NOT_IN, UtilMisc.toList("PAYMENT_SETTLED", "PAYMENT_RECEIVED", "PAYMENT_DECLINED", "PAYMENT_CANCELLED"))) // PAYMENT_NOT_AUTH
.queryList();
for (GenericValue orderPaymentPreferenceSum : orderPaymentPreferenceSums) {
BigDecimal maxAmount = orderPaymentPreferenceSum.getBigDecimal("maxAmount");
balance = maxAmount != null ? balance.subtract(maxAmount) : balance;
}
List<GenericValue> paymentAppls = EntityQuery.use(delegator).from("PaymentApplication").where("billingAccountId", billingAccountId).queryList();
// TODO: cancelled payments?
for (GenericValue paymentAppl : paymentAppls) {
if (paymentAppl.getString("invoiceId") == null) {
BigDecimal amountApplied = paymentAppl.getBigDecimal("amountApplied");
balance = balance.add(amountApplied);
}
}
balance = balance.setScale(scale, rounding);
return balance;
}
/**
* Returns the accountLimit of the BillingAccount or BigDecimal ZERO if it is null
* @param billingAccount
* @throws GenericEntityException
*/
public static BigDecimal getAccountLimit(GenericValue billingAccount) throws GenericEntityException {
if (billingAccount.getBigDecimal("accountLimit") != null) {
return billingAccount.getBigDecimal("accountLimit");
}
Debug.logWarning("Billing Account [" + billingAccount.getString("billingAccountId") + "] does not have an account limit defined, assuming zero.", module);
return ZERO;
}
public List<BigDecimal> getShippableSizes(String shipGrouSeqId) {
List<BigDecimal> shippableSizes = new ArrayList<>();
List<GenericValue> validItems = getValidOrderItems(shipGrouSeqId);
if (validItems != null) {
Iterator<GenericValue> i = validItems.iterator();
while (i.hasNext()) {
GenericValue item = i.next();
shippableSizes.add(this.getItemSize(item));
}
}
return shippableSizes;
}
public BigDecimal getItemReceivedQuantity(GenericValue orderItem) {
BigDecimal totalReceived = BigDecimal.ZERO;
try {
if (orderItem != null) {
EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(
EntityCondition.makeCondition("orderId", orderItem.getString("orderId")),
EntityCondition.makeCondition("quantityAccepted", EntityOperator.GREATER_THAN, BigDecimal.ZERO),
EntityCondition.makeCondition("orderItemSeqId", orderItem.getString("orderItemSeqId"))));
Delegator delegator = orderItem.getDelegator();
List<GenericValue> shipmentReceipts = EntityQuery.use(delegator).select("quantityAccepted", "quantityRejected").from("ShipmentReceiptAndItem").where(cond).queryList();
for (GenericValue shipmentReceipt : shipmentReceipts) {
if (shipmentReceipt.getBigDecimal("quantityAccepted") != null) {
totalReceived = totalReceived.add(shipmentReceipt.getBigDecimal("quantityAccepted"));
}
if (shipmentReceipt.getBigDecimal("quantityRejected") != null) {
totalReceived = totalReceived.add(shipmentReceipt.getBigDecimal("quantityRejected"));
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return totalReceived;
}
// ================= Order Subscriptions (SCIPIO) =================
/**
* SCIPIO: Retrieve all subscription of the entire order
*/
public Map<GenericValue, List<GenericValue>> getItemSubscriptions() throws GenericEntityException {
if (orderItems == null) {
getValidOrderItems();
}
if (orderItems != null) {
for (GenericValue orderItem : orderItems) {
List<GenericValue> productSubscriptions = getItemSubscriptions(orderItem);
for (GenericValue productSubscription : productSubscriptions) {
Debug.log("Found orderItem [" + orderItem.getString("orderItemSeqId") + "#" + orderItem.getString("productId") + "] with subscription id ["
+ productSubscription.getString("subscriptionResourceId") + "]");
}
}
return this.orderSubscriptionItems;
}
return null;
}
/**
* SCIPIO: Retrieve all subscriptions associated to an orderItem
*/
public List<GenericValue> getItemSubscriptions(GenericValue orderItem) throws GenericEntityException {
Delegator delegator = orderItem.getDelegator();
if (this.orderSubscriptionItems == null) {
this.orderSubscriptionItems = new HashMap<>();
}
List<GenericValue> productSubscriptionResources = EntityQuery.use(delegator).from("ProductSubscriptionResource")
.where("productId", orderItem.getString("productId")).cache(true).filterByDate().queryList();
if (UtilValidate.isNotEmpty(productSubscriptionResources)) {
this.orderSubscriptionItems.put(orderItem, productSubscriptionResources);
}
return productSubscriptionResources;
}
/**
* SCIPIO: Checks if any order item has an underlying subscription/s bound to it.
*/
public boolean hasSubscriptions() {
return UtilValidate.isNotEmpty(this.orderSubscriptionItems);
}
/**
* SCIPIO: Checks if an order item has an underlying subscription/s bound to it.
*/
public boolean hasSubscriptions(GenericValue orderItem) {
return UtilValidate.isNotEmpty(this.orderSubscriptionItems) && this.orderSubscriptionItems.containsKey(orderItem);
}
/**
* SCIPIO: Check if the order contains only subscription items
*/
public boolean orderContainsSubscriptionItemsOnly() {
if (orderItems != null && orderSubscriptionItems != null) {
for (GenericValue orderItem : orderItems) {
if (!orderSubscriptionItems.containsKey(orderItem)) {
return false;
}
}
return true;
}
return false;
}
public BigDecimal getSubscriptionItemsSubTotal() {
BigDecimal subscriptionItemsSubTotal = BigDecimal.ZERO;
if (UtilValidate.isNotEmpty(orderSubscriptionItems)) {
List<GenericValue> subscriptionItems = new ArrayList<>(orderSubscriptionItems.keySet());
subscriptionItemsSubTotal = getOrderItemsSubTotal(subscriptionItems, getAdjustments());
}
return subscriptionItemsSubTotal;
}
public BigDecimal getSubscriptionItemSubTotal(GenericValue orderItem) {
return getOrderItemSubTotal(orderItem, getAdjustments());
}
public BigDecimal getSubscriptionItemsTotal() {
BigDecimal subscriptionItemsTotal = BigDecimal.ZERO;
if (UtilValidate.isNotEmpty(orderSubscriptionItems)) {
List<GenericValue> subscriptionItems = new ArrayList<>(orderSubscriptionItems.keySet());
subscriptionItemsTotal = getOrderItemsTotal(subscriptionItems, getAdjustments());
}
return subscriptionItemsTotal;
}
public BigDecimal getSubscriptionItemTotal(GenericValue orderItem) {
return getOrderItemTotal(orderItem, getAdjustments());
}
public BigDecimal getSubscriptionItemTax(GenericValue orderItem) {
return getOrderItemAdjustmentsTotal(orderItem, false, true, false);
}
/**
* SCIPIO: Returns the salesChannelEnumIds of the channels which can be considered "web" channels
* or in other words require a webSiteId to work properly.
*/
public static Set<String> getWebSiteSalesChannelIds(Delegator delegator) {
return webSiteSalesChannelIds;
}
public ProductConfigWrapper getProductConfigWrapperForOrderItem(GenericValue orderItem) { // SCIPIO
try {
GenericValue product = orderItem.getRelatedOne("Product");
if (ProductWorker.isConfigProductConfig(product)) {
String configurableProductId = ProductWorker.getInstanceAggregatedId(getDelegator(), product.getString("productId"));
if (configurableProductId != null) {
return ProductConfigWorker.loadProductConfigWrapper(getDelegator(), getDispatcher(), product.getString("configId"),
configurableProductId, getOrderHeader().getString("productStoreId"), orderItem.getString("prodCatalogId"),
getOrderHeader().getString("webSiteId"), getOrderHeader().getString("currencyUom"), locale, null);
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return null;
}
public ProductConfigWrapper getProductConfigWrapperForOrderItem(String orderItemSeqId) { // SCIPIO
GenericValue orderItem = getOrderItem(orderItemSeqId);
return (orderItem != null) ? getProductConfigWrapperForOrderItem(orderItem) : null;
}
public Map<String, ProductConfigWrapper> getProductConfigWrappersByOrderItemSeqId(Collection<GenericValue> orderItems) { // SCIPIO
Map<String, ProductConfigWrapper> pcwMap = new HashMap<>();
if (orderItems != null) {
for(GenericValue orderItem : orderItems) {
ProductConfigWrapper pcw = getProductConfigWrapperForOrderItem(orderItem);
if (pcw != null) {
pcwMap.put(orderItem.getString("orderItemSeqId"), pcw);
}
}
}
return pcwMap;
}
public Map<String, ProductConfigWrapper> getProductConfigWrappersByOrderItemSeqId() { // SCIPIO
return getProductConfigWrappersByOrderItemSeqId(getOrderItems());
}
public Map<String, ProductConfigWrapper> getProductConfigWrappersByProductId() { // SCIPIO
Map<String, ProductConfigWrapper> pcwMap = new HashMap<>();
if (orderItems != null) {
for(GenericValue orderItem : orderItems) {
String productId = orderItem.getString("productId");
if (pcwMap.get(productId) != null) {
continue;
}
ProductConfigWrapper pcw = getProductConfigWrapperForOrderItem(orderItem);
if (pcw != null) {
pcwMap.put(productId, pcw);
}
}
}
return pcwMap;
}
public Map<String, String> getOrderAdjustmentReturnItemTypeMap(String returnHeaderTypeId) { // SCIPIO
return getOrderAdjustmentReturnItemTypeMap(getDelegator(), returnHeaderTypeId);
}
public static Map<String, String> getOrderAdjustmentReturnItemTypeMap(Delegator delegator, String returnHeaderTypeId) { // SCIPIO
Map<String, String> typeMap = new HashMap<>();
try {
List<GenericValue> valueList = delegator.from("ReturnItemTypeMap").where("returnHeaderTypeId", returnHeaderTypeId).cache().queryList();
if (valueList != null) {
for (GenericValue value : valueList) {
typeMap.put(value.getString("returnItemMapKey"), value.getString("returnItemTypeId"));
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return typeMap;
}
/**
* SCIPIO: Returns the adjustments for the specified item from the returnableItems map returned by the getReturnableItems service using orderItemSeqId.
*/
public static List<GenericValue> getOrderItemAdjustmentsFromReturnableItems(Map<GenericValue, Map<String, Object>> returnableItems, String orderItemSeqId) {
Map<String, Object> info = getReturnableItemInfo(returnableItems, orderItemSeqId);
return (info != null) ? UtilGenerics.cast(info.get("adjustments")) : null;
}
/**
* SCIPIO: Keys into the returnableItems map returned by the getReturnableItems service using orderItemSeqId.
*/
public static Map<String, Object> getReturnableItemInfo(Map<GenericValue, Map<String, Object>> returnableItems, String orderItemSeqId) {
if (returnableItems == null || orderItemSeqId == null) {
return null;
}
for(Map.Entry<GenericValue, Map<String, Object>> entry : returnableItems.entrySet()) {
if ("OrderItem".equals(entry.getKey().getEntityName()) && orderItemSeqId.equals(entry.getKey().get("orderItemSeqId"))) {
return entry.getValue();
}
}
return null;
}
/**
* SCIPIO: returns a map of valuable order and return stats for a customer
*/
public Map<String, Object> getCustomerOrderMktgStats(List<String> orderIds, Boolean removeEmptyOrders, List<String>includedOrderItemStatusIds, List<String>excludedReturnItemStatusIds) {
Map<String,Object> resultMap = new HashMap<>();
Delegator delegator = getDelegator();
//Remove orders from list that are "replacements" or "empty"
if(removeEmptyOrders){
List<EntityCondition> exl = new ArrayList<>();
exl.add(EntityCondition.makeCondition("orderId", EntityOperator.IN, orderIds));
exl.add(EntityCondition.makeCondition("grandTotal", EntityOperator.EQUALS, BigDecimal.ZERO));
try{
List<GenericValue> negativeOrders = delegator.findList("OrderHeader", EntityCondition.makeCondition(exl, EntityOperator.AND),
UtilMisc.toSet("orderId"),
null,
null,
true);
for(GenericValue n : negativeOrders){
orderIds.remove(n.getString("orderId"));
}
}catch(Exception e){
Debug.logWarning("Could not fetch results from ",module);
}
}
Integer orderCount = orderIds.size();
Integer returnCount = 0;
BigDecimal orderItemValue = BigDecimal.ZERO;
BigDecimal returnItemValue = BigDecimal.ZERO;
BigDecimal orderItemCount = BigDecimal.ZERO;
BigDecimal returnItemCount = BigDecimal.ZERO;
int rfmRecency = 0;
DynamicViewEntity itemEntity = new DynamicViewEntity();
itemEntity.addMemberEntity("OI", "OrderItem");
itemEntity.addMemberEntity("OH", "OrderHeader");
itemEntity.addAlias("OI", "orderId", null, null, null, true, null);
itemEntity.addAlias("OI", "statusId", null, null, null, true, null);
itemEntity.addAlias("OH", "orderDate", null, null, null, true, null);
itemEntity.addAlias("OI", "orderItemCount", "quantity", null, null, false, "sum");
itemEntity.addAlias("OI", "orderItemValue", "unitPrice", null, null, false, "sum");
itemEntity.addViewLink("OI", "OH", Boolean.FALSE, ModelKeyMap.makeKeyMapList("orderId", "orderId"));
List<EntityCondition> exprListStatus = new ArrayList<>();
exprListStatus.add(EntityCondition.makeCondition("orderId", EntityOperator.IN, orderIds));
if(UtilValidate.isNotEmpty(includedOrderItemStatusIds)){
exprListStatus.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, includedOrderItemStatusIds));
}
EntityCondition andCond = EntityCondition.makeCondition(exprListStatus, EntityOperator.AND);
EntityListIterator customerOrderStats;
try{
customerOrderStats = delegator.findListIteratorByCondition(itemEntity,andCond,null,null,UtilMisc.toList("-orderDate"),null);
Timestamp lastOrderDate;
if (customerOrderStats != null) {
int cIndex = 0;
List<GenericValue> orderStatsList = customerOrderStats.getCompleteList();
for(GenericValue n : orderStatsList){
if(cIndex==0){
lastOrderDate = n.getTimestamp("orderDate");
rfmRecency = Math.toIntExact( (System.currentTimeMillis() - lastOrderDate.getTime() )/ (1000 * 60 * 60 * 24));
}
BigDecimal nv = n.getBigDecimal("orderItemValue");
orderItemValue = orderItemValue.add(nv.multiply(n.getBigDecimal("orderItemCount")));
orderItemCount = orderItemCount.add(n.getBigDecimal("orderItemCount"));
cIndex+=1;
}
}
customerOrderStats.close();
}catch(Exception e){
Debug.logError("Error while fetching orderItems "+e.getMessage(),module);
}
DynamicViewEntity retEntity = new DynamicViewEntity();
retEntity.addMemberEntity("RI", "ReturnItem");
retEntity.addAlias("RI", "orderId", null, null, null, true, null);
retEntity.addAlias("RI", "returnId", null, null, null, true, null);
retEntity.addAlias("RI", "statusId", null, null, null, true, null);
retEntity.addAlias("RI", "returnTypeId", null, null, null, true, null);
retEntity.addAlias("RI", "returnItemCount", "returnQuantity", null, null, false, "sum");
retEntity.addAlias("RI", "returnItemValue", "returnPrice", null, null, false, "sum");
try{
List<EntityCondition> returnExpL = new ArrayList<>();
returnExpL.add(EntityCondition.makeCondition("orderId", EntityOperator.IN, orderIds));
if(UtilValidate.isNotEmpty(excludedReturnItemStatusIds))returnExpL.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_IN, excludedReturnItemStatusIds));
EntityListIterator returnStats = delegator.findListIteratorByCondition(retEntity,EntityCondition.makeCondition(returnExpL, EntityOperator.AND),null,null,null,null);
if (returnStats != null) {
List<GenericValue> returnStatsList = returnStats.getCompleteList();
returnCount = returnStatsList.size();
for(GenericValue n : returnStatsList){
BigDecimal nv = n.getBigDecimal("returnItemValue");
returnItemValue = returnItemValue.add(nv.multiply(n.getBigDecimal("returnItemCount")));
returnItemCount = returnItemCount.add(n.getBigDecimal("returnItemCount"));
}
}
returnStats.close();
}catch(Exception e){
Debug.logError("Error while fetching returnItems "+e.getMessage(),module);
}
resultMap.put("orderCount",orderCount);
resultMap.put("orderItemValue",orderItemValue);
resultMap.put("orderItemCount",orderItemCount.setScale(0,BigDecimal.ROUND_HALF_UP));
resultMap.put("returnCount",returnCount);
resultMap.put("returnItemValue",returnItemValue);
resultMap.put("returnItemCount",returnItemCount.setScale(0,BigDecimal.ROUND_HALF_UP));
if(BigDecimal.ZERO.compareTo(returnItemCount) == 0 || BigDecimal.ZERO.compareTo(orderItemCount) == 0){
resultMap.put("returnItemRatio",BigDecimal.ZERO);
}else{
resultMap.put("returnItemRatio",(returnItemCount.divide(orderItemCount,2,BigDecimal.ROUND_HALF_UP)));
}
//rfm values
resultMap.put("rfmRecency",rfmRecency);
Integer rfmFrequency = orderCount;
resultMap.put("rfmFrequency",rfmFrequency);
BigDecimal rfmMonetary = orderItemValue.subtract(returnItemValue);
resultMap.put("rfmMonetary",rfmMonetary);
int rfmRecencyScore = 0;
int rfmFrequencyScore = 0;
int rfmMonetaryScore = 0;
if(rfmRecency <= UtilProperties.getPropertyAsInteger("order","order.rfm.recency.1",30)){
rfmRecencyScore = 1;
}else if(rfmRecency <= UtilProperties.getPropertyAsInteger("order","order.rfm.recency.2",90)){
rfmRecencyScore = 2;
}else if(rfmRecency <= UtilProperties.getPropertyAsInteger("order","order.rfm.recency.3",375)){
rfmRecencyScore = 3;
}else{
rfmRecencyScore = 4;
}
if(rfmFrequency >= UtilProperties.getPropertyAsInteger("order","order.rfm.frequency.1",10)){
rfmFrequencyScore = 1;
}else if(rfmFrequency >= UtilProperties.getPropertyAsInteger("order","order.rfm.frequency.2",5)){
rfmFrequencyScore = 2;
}else if(rfmFrequency >= UtilProperties.getPropertyAsInteger("order","order.rfm.frequency.3",3)){
rfmFrequencyScore = 3;
}else{
rfmFrequencyScore = 4;
}
if(rfmMonetary.compareTo(new BigDecimal(UtilProperties.getPropertyAsInteger("order","order.rfm.monetary.1",250))) == 1){
rfmMonetaryScore = 1;
}else if(rfmMonetary.compareTo(new BigDecimal(UtilProperties.getPropertyAsInteger("order","order.rfm.monetary.2",100))) == 1){
rfmMonetaryScore = 2;
}else if(rfmMonetary.compareTo(new BigDecimal(UtilProperties.getPropertyAsInteger("order","order.rfm.monetary.3",50))) == 1){
rfmMonetaryScore = 3;
}else{
rfmMonetaryScore = 4;
}
resultMap.put("rfmRecencyScore",rfmRecencyScore);
resultMap.put("rfmFrequencyScore",rfmFrequencyScore);
resultMap.put("rfmMonetaryScore",rfmMonetaryScore);
return resultMap;
}
/**
* SCIPIO: Helper map cache that keeps an OrderReadHelper for each orderId
* and automatically returns a new OrderReadHelper on {@link #get(Object)} calls
* if there is not already one for the given orderId.
*/
public static class Cache implements Map<String, OrderReadHelper> {
private final Map<String, OrderReadHelper> orderIdMap = new HashMap<>();
private final Delegator delegator;
private final LocalDispatcher dispatcher; // SCIPIO: Optional dispatcher
private final Locale locale; // SCIPIO: Optional locale
protected Cache(Delegator delegator, LocalDispatcher dispatcher, Locale locale) {
this.delegator = delegator;
this.dispatcher = dispatcher;
this.locale = locale;
}
public static Cache create(Delegator delegator, LocalDispatcher dispatcher, Locale locale, OrderReadHelper... initialHelpers) {
Cache cache = new Cache(delegator, dispatcher, locale);
for(OrderReadHelper helper : initialHelpers) {
cache.put(helper.getOrderId(), helper);
}
return cache;
}
public static Cache create(LocalDispatcher dispatcher, Locale locale, OrderReadHelper... initialHelpers) {
return create(dispatcher.getDelegator(), dispatcher, locale, initialHelpers);
}
public static Cache create(Delegator delegator, LocalDispatcher dispatcher, Locale locale) {
return new Cache(delegator, dispatcher, locale);
}
public static Cache create(LocalDispatcher dispatcher, Locale locale) {
return new Cache(dispatcher.getDelegator(), dispatcher, locale);
}
public Delegator getDelegator() {
return delegator;
}
public LocalDispatcher getDispatcher() {
return dispatcher;
}
public Locale getLocale() {
return locale;
}
// Map interface methods
@Override
public OrderReadHelper get(Object key) {
OrderReadHelper orh = getIfExists(key);
if (orh == null) {
orh = new OrderReadHelper(getDelegator(), getDispatcher(), getLocale(), (String) key);
put((String) key, orh);
}
return orh;
}
public OrderReadHelper getIfExists(Object key) {
return orderIdMap.get(key);
}
@Override
public int size() {
return orderIdMap.size();
}
@Override
public boolean isEmpty() {
return orderIdMap.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return orderIdMap.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return orderIdMap.containsValue(value);
}
@Override
public OrderReadHelper put(String key, OrderReadHelper value) {
return orderIdMap.put(key, value);
}
@Override
public OrderReadHelper remove(Object key) {
return orderIdMap.remove(key);
}
@Override
public void putAll(Map<? extends String, ? extends OrderReadHelper> m) {
orderIdMap.putAll(m);
}
@Override
public void clear() {
orderIdMap.clear();
}
@Override
public Set<String> keySet() {
return orderIdMap.keySet();
}
@Override
public Collection<OrderReadHelper> values() {
return orderIdMap.values();
}
@Override
public Set<Entry<String, OrderReadHelper>> entrySet() {
return orderIdMap.entrySet();
}
@Override
public boolean equals(Object o) {
return orderIdMap.equals(o);
}
@Override
public int hashCode() {
return orderIdMap.hashCode();
}
}
}
| applications/order/src/org/ofbiz/order/order/OrderReadHelper.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.ofbiz.order.order;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilFormatOut;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilNumber;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.common.DataModelConstants;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntity;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityConditionList;
import org.ofbiz.entity.condition.EntityExpr;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.model.DynamicViewEntity;
import org.ofbiz.entity.model.ModelKeyMap;
import org.ofbiz.entity.util.EntityListIterator;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.product.config.ProductConfigWorker;
import org.ofbiz.product.config.ProductConfigWrapper;
import org.ofbiz.product.product.ProductWorker;
import org.ofbiz.product.store.ProductStoreWorker;
import org.ofbiz.security.Security;
import org.ofbiz.service.LocalDispatcher;
import sun.net.www.content.text.Generic;
/**
* Utility class for easily extracting important information from orders
*
* <p>NOTE: in the current scheme order adjustments are never included in tax or shipping,
* but order item adjustments ARE included in tax and shipping calcs unless they are
* tax or shipping adjustments or the includeInTax or includeInShipping are set to N.</p>
*/
public class OrderReadHelper {
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
// scales and rounding modes for BigDecimal math
public static final int scale = UtilNumber.getBigDecimalScale("order.decimals");
public static final RoundingMode rounding = UtilNumber.getRoundingMode("order.rounding");
public static final int taxCalcScale = UtilNumber.getBigDecimalScale("salestax.calc.decimals");
public static final int taxFinalScale = UtilNumber.getBigDecimalScale("salestax.final.decimals");
public static final RoundingMode taxRounding = UtilNumber.getRoundingMode("salestax.rounding");
public static final BigDecimal ZERO = (BigDecimal.ZERO).setScale(scale, rounding);
public static final BigDecimal percentage = (new BigDecimal("0.01")).setScale(scale, rounding);
/**
* SCIPIO: Custom flag used to determine whether only one subscription is allowed per order or not.
*/
public static final boolean subscriptionSingleOrderItem = UtilProperties.getPropertyAsBoolean("order", "order.item.subscription.singleOrderItem", false);
/**
* SCIPIO: Sales channels which only fully work with a webSiteId on OrderHeader.
* @see #getWebSiteSalesChannelIds
*/
private static final Set<String> webSiteSalesChannelIds = Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(
UtilProperties.getPropertyValue("order", "order.webSiteSalesChannelIds").split(","))));
protected GenericValue orderHeader = null;
protected List<GenericValue> orderItemAndShipGrp = null;
protected List<GenericValue> orderItems = null;
protected List<GenericValue> adjustments = null;
protected List<GenericValue> paymentPrefs = null;
protected List<GenericValue> orderStatuses = null;
protected List<GenericValue> orderItemPriceInfos = null;
protected List<GenericValue> orderItemShipGrpInvResList = null;
protected List<GenericValue> orderItemIssuances = null;
protected List<GenericValue> orderReturnItems = null;
protected Map<GenericValue, List<GenericValue>> orderSubscriptionItems = null; // SCIPIO
protected BigDecimal totalPrice = null;
protected LocalDispatcher dispatcher; // SCIPIO: Optional dispatcher
protected Locale locale; // SCIPIO: Optional locale
protected OrderReadHelper() {}
// SCIPIO: Added dispatcher overload
public OrderReadHelper(LocalDispatcher dispatcher, Locale locale, GenericValue orderHeader, List<GenericValue> adjustments, List<GenericValue> orderItems) {
this.dispatcher = dispatcher; // SCIPIO
this.locale = locale;
this.orderHeader = orderHeader;
this.adjustments = adjustments;
this.orderItems = orderItems;
if (this.orderHeader != null && !"OrderHeader".equals(this.orderHeader.getEntityName())) {
try {
this.orderHeader = orderHeader.getDelegator().findOne("OrderHeader", UtilMisc.toMap("orderId",
orderHeader.getString("orderId")), false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
this.orderHeader = null;
}
} else if (this.orderHeader == null && orderItems != null) {
GenericValue firstItem = EntityUtil.getFirst(orderItems);
try {
this.orderHeader = firstItem.getRelatedOne("OrderHeader", false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
this.orderHeader = null;
}
}
if (this.orderHeader == null) {
if (orderHeader == null) {
throw new IllegalArgumentException("Order header passed is null, or is otherwise invalid");
}
throw new IllegalArgumentException("Order header passed in is not valid for orderId [" + orderHeader.getString("orderId") + "]");
}
}
public OrderReadHelper(GenericValue orderHeader, List<GenericValue> adjustments, List<GenericValue> orderItems) {
this(null, null, orderHeader, adjustments, orderItems); // SCIPIO: delegating
}
public OrderReadHelper(LocalDispatcher dispatcher, Locale locale, GenericValue orderHeader) { // SCIPIO: Added dispatcher overload
this(dispatcher, locale, orderHeader, null, null);
}
public OrderReadHelper(GenericValue orderHeader) {
this(orderHeader, null, null);
}
public OrderReadHelper(LocalDispatcher dispatcher, Locale locale, List<GenericValue> adjustments, List<GenericValue> orderItems) { // SCIPIO: Added dispatcher overload
this.dispatcher = dispatcher;
this.locale = locale;
this.adjustments = adjustments;
this.orderItems = orderItems;
}
public OrderReadHelper(List<GenericValue> adjustments, List<GenericValue> orderItems) {
this((LocalDispatcher) null, (Locale) null, adjustments, orderItems); // SCIPIO: delegating
}
public OrderReadHelper(Delegator delegator, LocalDispatcher dispatcher, Locale locale, String orderId) { // SCIPIO: Added dispatcher overload
this.dispatcher = dispatcher;
this.locale = locale;
try {
this.orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
} catch (GenericEntityException e) {
String errMsg = "Error finding order with ID [" + orderId + "]: " + e.toString();
Debug.logError(e, errMsg, module);
throw new IllegalArgumentException(errMsg);
}
if (this.orderHeader == null) {
throw new IllegalArgumentException("Order not found with orderId [" + orderId + "]");
}
}
public OrderReadHelper(Delegator delegator, String orderId) {
this(delegator, null, null, orderId); // SCIPIO: delegating
}
// ==========================================
// ========== Generic Methods (SCIPIO) ======
// ==========================================
/**
* SCIPIO: Returns the delegator (for the order header).
*/
protected Delegator getDelegator() {
return orderHeader.getDelegator();
}
/**
* SCIPIO: Returns the dispatcher IF present (may be null!).
*/
protected LocalDispatcher getDispatcher() {
return dispatcher;
}
/**
* SCIPIO: Returns the "current" display locale IF present (may be null!).
*/
protected Locale getLocale() {
return locale;
}
// ==========================================
// ========== Order Header Methods ==========
// ==========================================
public String getOrderId() {
return orderHeader.getString("orderId");
}
public String getWebSiteId() {
return orderHeader.getString("webSiteId");
}
/**
* SCIPIO: Returns the OrderHeader.webSiteId field if set;
* otherwise returns the default website associated with the
* ProductStore pointed to by OrderHeader.productStoreId.
* <p>
* The default website is the one marked with WebSite.isStoreDefault Y
* OR if the store only has one website, that website is returned.
* <p>
* <strong>NOTE:</strong> If there are multiple WebSites but none is marked with isStoreDefault Y,
* logs a warning and returns null - by design - in a frontend environment there must be no ambiguity as to which
* store should be used by default! (Otherwise, if ambiguous, could be picking a WebSite
* intended for backend usage only, e.g. cms preview!)
* <p>
* Added 2018-10-02.
*/
public String getWebSiteIdOrStoreDefault() {
String webSiteId = getWebSiteId();
if (webSiteId == null) {
String productStoreId = getProductStoreId();
if (productStoreId != null) {
webSiteId = ProductStoreWorker.getStoreDefaultWebSiteId(orderHeader.getDelegator(),
productStoreId, true);
}
}
return webSiteId;
}
public String getProductStoreId() {
return orderHeader.getString("productStoreId");
}
/**
* Returns the ProductStore of this Order or null in case of Exception
*/
public GenericValue getProductStore() {
String productStoreId = orderHeader.getString("productStoreId");
try {
Delegator delegator = orderHeader.getDelegator();
GenericValue productStore = EntityQuery.use(delegator).from("ProductStore").where("productStoreId", productStoreId).cache().queryOne();
return productStore;
} catch (GenericEntityException ex) {
Debug.logError(ex, "Failed to get product store for order header [" + orderHeader + "] due to exception " + ex.getMessage(), module);
return null;
}
}
public String getOrderTypeId() {
return orderHeader.getString("orderTypeId");
}
public String getCurrency() {
return orderHeader.getString("currencyUom");
}
public String getOrderName() {
return orderHeader.getString("orderName");
}
public List<GenericValue> getAdjustments() {
if (adjustments == null) {
try {
adjustments = orderHeader.getRelated("OrderAdjustment", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (adjustments == null) {
adjustments = new ArrayList<>();
}
}
return adjustments;
}
public List<GenericValue> getPaymentPreferences() {
if (paymentPrefs == null) {
try {
paymentPrefs = orderHeader.getRelated("OrderPaymentPreference", null, UtilMisc.toList("orderPaymentPreferenceId"), false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
return paymentPrefs;
}
/**
* Returns a Map of paymentMethodId -> amount charged (BigDecimal) based on PaymentGatewayResponse.
* @return returns a Map of paymentMethodId -> amount charged (BigDecimal) based on PaymentGatewayResponse.
*/
public Map<String, BigDecimal> getReceivedPaymentTotalsByPaymentMethod() {
Map<String, BigDecimal> paymentMethodAmounts = new HashMap<>();
List<GenericValue> paymentPrefs = getPaymentPreferences();
for (GenericValue paymentPref : paymentPrefs) {
List<GenericValue> payments = new ArrayList<>();
try {
List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PMNT_RECEIVED"),
EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PMNT_CONFIRMED"));
payments = paymentPref.getRelated("Payment", null, null, false);
payments = EntityUtil.filterByOr(payments, exprs);
List<EntityExpr> conds = UtilMisc.toList(EntityCondition.makeCondition("paymentTypeId", EntityOperator.EQUALS, "CUSTOMER_PAYMENT"),
EntityCondition.makeCondition("paymentTypeId", EntityOperator.EQUALS, "CUSTOMER_DEPOSIT"),
EntityCondition.makeCondition("paymentTypeId", EntityOperator.EQUALS, "INTEREST_RECEIPT"),
EntityCondition.makeCondition("paymentTypeId", EntityOperator.EQUALS, "GC_DEPOSIT"),
EntityCondition.makeCondition("paymentTypeId", EntityOperator.EQUALS, "POS_PAID_IN"));
payments = EntityUtil.filterByOr(payments, conds);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
BigDecimal chargedToPaymentPref = ZERO;
for (GenericValue payment : payments) {
if (payment.get("amount") != null) {
chargedToPaymentPref = chargedToPaymentPref.add(payment.getBigDecimal("amount")).setScale(scale+1, rounding);
}
}
if (chargedToPaymentPref.compareTo(ZERO) > 0) {
// key of the resulting map is paymentMethodId or paymentMethodTypeId if the paymentMethodId is not available
String paymentMethodKey = paymentPref.getString("paymentMethodId") != null ? paymentPref.getString("paymentMethodId") : paymentPref.getString("paymentMethodTypeId");
if (paymentMethodAmounts.containsKey(paymentMethodKey)) {
BigDecimal value = paymentMethodAmounts.get(paymentMethodKey);
if (value != null) {
chargedToPaymentPref = chargedToPaymentPref.add(value);
}
}
paymentMethodAmounts.put(paymentMethodKey, chargedToPaymentPref.setScale(scale, rounding));
}
}
return paymentMethodAmounts;
}
/**
* Returns a Map of paymentMethodId -> amount refunded
* @return returns a Map of paymentMethodId -> amount refunded
*/
public Map<String, BigDecimal> getReturnedTotalsByPaymentMethod() {
Map<String, BigDecimal> paymentMethodAmounts = new HashMap<>();
List<GenericValue> paymentPrefs = getPaymentPreferences();
for (GenericValue paymentPref : paymentPrefs) {
List<GenericValue> returnItemResponses = new ArrayList<>();
try {
returnItemResponses = orderHeader.getDelegator().findByAnd("ReturnItemResponse", UtilMisc.toMap("orderPaymentPreferenceId", paymentPref.getString("orderPaymentPreferenceId")), null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
BigDecimal refundedToPaymentPref = ZERO;
for (GenericValue returnItemResponse : returnItemResponses) {
refundedToPaymentPref = refundedToPaymentPref.add(returnItemResponse.getBigDecimal("responseAmount")).setScale(scale+1, rounding);
}
if (refundedToPaymentPref.compareTo(ZERO) == 1) {
String paymentMethodId = paymentPref.getString("paymentMethodId") != null ? paymentPref.getString("paymentMethodId") : paymentPref.getString("paymentMethodTypeId");
paymentMethodAmounts.put(paymentMethodId, refundedToPaymentPref.setScale(scale, rounding));
}
}
return paymentMethodAmounts;
}
public List<GenericValue> getOrderPayments() {
return getOrderPayments(null);
}
public List<GenericValue> getOrderPayments(GenericValue orderPaymentPreference) {
List<GenericValue> orderPayments = new ArrayList<>();
List<GenericValue> prefs = null;
if (orderPaymentPreference == null) {
prefs = getPaymentPreferences();
} else {
prefs = UtilMisc.toList(orderPaymentPreference);
}
if (prefs != null) {
for (GenericValue payPref : prefs) {
try {
orderPayments.addAll(payPref.getRelated("Payment", null, null, false));
} catch (GenericEntityException e) {
Debug.logError(e, module);
return null;
}
}
}
return orderPayments;
}
public List<GenericValue> getOrderStatuses() {
if (orderStatuses == null) {
try {
orderStatuses = orderHeader.getRelated("OrderStatus", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
return orderStatuses;
}
public List<GenericValue> getOrderTerms() {
try {
return orderHeader.getRelated("OrderTerm", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return null;
}
}
/**
* Return the number of days from termDays of first FIN_PAYMENT_TERM
* @return number of days from termDays of first FIN_PAYMENT_TERM
*/
public Long getOrderTermNetDays() {
List<GenericValue> orderTerms = EntityUtil.filterByAnd(getOrderTerms(), UtilMisc.toMap("termTypeId", "FIN_PAYMENT_TERM"));
if (UtilValidate.isEmpty(orderTerms)) {
return null;
} else if (orderTerms.size() > 1) {
Debug.logWarning("Found " + orderTerms.size() + " FIN_PAYMENT_TERM order terms for orderId [" + getOrderId() + "], using the first one ", module);
}
return orderTerms.get(0).getLong("termDays");
}
public String getShippingMethod(String shipGroupSeqId) {
try {
GenericValue shipGroup = orderHeader.getDelegator().findOne("OrderItemShipGroup",
UtilMisc.toMap("orderId", orderHeader.getString("orderId"), "shipGroupSeqId", shipGroupSeqId), false);
if (shipGroup != null) {
GenericValue carrierShipmentMethod = shipGroup.getRelatedOne("CarrierShipmentMethod", false);
if (carrierShipmentMethod != null) {
GenericValue shipmentMethodType = carrierShipmentMethod.getRelatedOne("ShipmentMethodType", false);
if (shipmentMethodType != null) {
return UtilFormatOut.checkNull(shipGroup.getString("carrierPartyId")) + " " +
UtilFormatOut.checkNull(shipmentMethodType.getString("description"));
}
}
return UtilFormatOut.checkNull(shipGroup.getString("carrierPartyId"));
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return "";
}
public String getShippingMethodCode(String shipGroupSeqId) {
try {
GenericValue shipGroup = orderHeader.getDelegator().findOne("OrderItemShipGroup",
UtilMisc.toMap("orderId", orderHeader.getString("orderId"), "shipGroupSeqId", shipGroupSeqId), false);
if (shipGroup != null) {
GenericValue carrierShipmentMethod = shipGroup.getRelatedOne("CarrierShipmentMethod", false);
if (carrierShipmentMethod != null) {
GenericValue shipmentMethodType = carrierShipmentMethod.getRelatedOne("ShipmentMethodType", false);
if (shipmentMethodType != null) {
return UtilFormatOut.checkNull(shipmentMethodType.getString("shipmentMethodTypeId")) + "@" + UtilFormatOut.checkNull(shipGroup.getString("carrierPartyId"));
}
}
return UtilFormatOut.checkNull(shipGroup.getString("carrierPartyId"));
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return "";
}
public boolean hasShippingAddress() {
if (UtilValidate.isNotEmpty(this.getShippingLocations())) {
return true;
}
return false;
}
public boolean hasPhysicalProductItems() throws GenericEntityException {
for (GenericValue orderItem : this.getOrderItems()) {
GenericValue product = orderItem.getRelatedOne("Product", true);
if (product != null) {
GenericValue productType = product.getRelatedOne("ProductType", true);
if ("Y".equals(productType.getString("isPhysical"))) {
return true;
}
}
}
return false;
}
public GenericValue getOrderItemShipGroup(String shipGroupSeqId) {
try {
return orderHeader.getDelegator().findOne("OrderItemShipGroup",
UtilMisc.toMap("orderId", orderHeader.getString("orderId"), "shipGroupSeqId", shipGroupSeqId), false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public List<GenericValue> getOrderItemShipGroups() {
try {
return orderHeader.getRelated("OrderItemShipGroup", null, UtilMisc.toList("shipGroupSeqId"), false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public List<GenericValue> getShippingLocations() {
List<GenericValue> shippingLocations = new ArrayList<>();
List<GenericValue> shippingCms = this.getOrderContactMechs("SHIPPING_LOCATION");
if (shippingCms != null) {
for (GenericValue ocm : shippingCms) {
if (ocm != null) {
try {
GenericValue addr = ocm.getDelegator().findOne("PostalAddress",
UtilMisc.toMap("contactMechId", ocm.getString("contactMechId")), false);
if (addr != null) {
shippingLocations.add(addr);
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
}
}
}
return shippingLocations;
}
public GenericValue getShippingAddress(String shipGroupSeqId) {
try {
GenericValue shipGroup = orderHeader.getDelegator().findOne("OrderItemShipGroup",
UtilMisc.toMap("orderId", orderHeader.getString("orderId"), "shipGroupSeqId", shipGroupSeqId), false);
if (shipGroup != null) {
return shipGroup.getRelatedOne("PostalAddress", false);
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
/** @deprecated */
@Deprecated
public GenericValue getShippingAddress() {
try {
GenericValue orderContactMech = EntityUtil.getFirst(orderHeader.getRelated("OrderContactMech", UtilMisc.toMap("contactMechPurposeTypeId", "SHIPPING_LOCATION"), null, false));
if (orderContactMech != null) {
GenericValue contactMech = orderContactMech.getRelatedOne("ContactMech", false);
if (contactMech != null) {
return contactMech.getRelatedOne("PostalAddress", false);
}
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public List<GenericValue> getBillingLocations() {
List<GenericValue> billingLocations = new ArrayList<>();
List<GenericValue> billingCms = this.getOrderContactMechs("BILLING_LOCATION");
if (billingCms != null) {
for (GenericValue ocm : billingCms) {
if (ocm != null) {
try {
GenericValue addr = ocm.getDelegator().findOne("PostalAddress",
UtilMisc.toMap("contactMechId", ocm.getString("contactMechId")), false);
if (addr != null) {
billingLocations.add(addr);
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
}
}
}
return billingLocations;
}
/** @deprecated */
@Deprecated
public GenericValue getBillingAddress() {
GenericValue billingAddress = null;
try {
GenericValue orderContactMech = EntityUtil.getFirst(orderHeader.getRelated("OrderContactMech", UtilMisc.toMap("contactMechPurposeTypeId", "BILLING_LOCATION"), null, false));
if (orderContactMech != null) {
GenericValue contactMech = orderContactMech.getRelatedOne("ContactMech", false);
if (contactMech != null) {
billingAddress = contactMech.getRelatedOne("PostalAddress", false);
}
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
if (billingAddress == null) {
// get the address from the billing account
GenericValue billingAccount = getBillingAccount();
if (billingAccount != null) {
try {
billingAddress = billingAccount.getRelatedOne("PostalAddress", false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
} else {
// get the address from the first payment method
GenericValue paymentPreference = EntityUtil.getFirst(getPaymentPreferences());
if (paymentPreference != null) {
try {
GenericValue paymentMethod = paymentPreference.getRelatedOne("PaymentMethod", false);
if (paymentMethod != null) {
GenericValue creditCard = paymentMethod.getRelatedOne("CreditCard", false);
if (creditCard != null) {
billingAddress = creditCard.getRelatedOne("PostalAddress", false);
} else {
GenericValue eftAccount = paymentMethod.getRelatedOne("EftAccount", false);
if (eftAccount != null) {
billingAddress = eftAccount.getRelatedOne("PostalAddress", false);
}
}
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
}
}
}
return billingAddress;
}
public List<GenericValue> getOrderContactMechs(String purposeTypeId) {
try {
return orderHeader.getRelated("OrderContactMech", UtilMisc.toMap("contactMechPurposeTypeId", purposeTypeId), null, false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public Timestamp getEarliestShipByDate() {
try {
List<GenericValue> groups = orderHeader.getRelated("OrderItemShipGroup", null, UtilMisc.toList("shipByDate"), false);
if (groups.size() > 0) {
GenericValue group = groups.get(0);
return group.getTimestamp("shipByDate");
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public Timestamp getLatestShipAfterDate() {
try {
List<GenericValue> groups = orderHeader.getRelated("OrderItemShipGroup", null, UtilMisc.toList("shipAfterDate DESC"), false);
if (groups.size() > 0) {
GenericValue group = groups.get(0);
return group.getTimestamp("shipAfterDate");
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public String getCurrentStatusString() {
GenericValue statusItem = null;
try {
statusItem = orderHeader.getRelatedOne("StatusItem", true);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (statusItem != null) {
return statusItem.getString("description");
}
return orderHeader.getString("statusId");
}
public String getStatusString(Locale locale) {
List<GenericValue> orderStatusList = this.getOrderHeaderStatuses();
if (UtilValidate.isEmpty(orderStatusList)) {
return "";
}
Iterator<GenericValue> orderStatusIter = orderStatusList.iterator();
StringBuilder orderStatusString = new StringBuilder(50);
try {
boolean isCurrent = true;
while (orderStatusIter.hasNext()) {
GenericValue orderStatus = orderStatusIter.next();
GenericValue statusItem = orderStatus.getRelatedOne("StatusItem", true);
if (statusItem != null) {
orderStatusString.append(statusItem.get("description", locale));
} else {
orderStatusString.append(orderStatus.getString("statusId"));
}
if (isCurrent && orderStatusIter.hasNext()) {
orderStatusString.append(" (");
isCurrent = false;
} else {
if (orderStatusIter.hasNext()) {
orderStatusString.append("/");
} else {
if (!isCurrent) {
orderStatusString.append(")");
}
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Error getting Order Status information: " + e.toString(), module);
}
return orderStatusString.toString();
}
public GenericValue getBillingAccount() {
GenericValue billingAccount = null;
try {
billingAccount = orderHeader.getRelatedOne("BillingAccount", false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return billingAccount;
}
/**
* Returns the OrderPaymentPreference.maxAmount for the billing account associated with the order, or 0 if there is no
* billing account or no max amount set
*/
public BigDecimal getBillingAccountMaxAmount() {
if (getBillingAccount() == null) {
return BigDecimal.ZERO;
}
List<GenericValue> paymentPreferences = null;
try {
Delegator delegator = orderHeader.getDelegator();
paymentPreferences = EntityQuery.use(delegator).from("OrderPurchasePaymentSummary")
.where("orderId", orderHeader.get("orderId")).queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
List<EntityExpr> exprs = UtilMisc.toList(
EntityCondition.makeCondition("paymentMethodTypeId", "EXT_BILLACT"),
EntityCondition.makeCondition("preferenceStatusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED"));
GenericValue billingAccountPaymentPreference = EntityUtil.getFirst(EntityUtil.filterByAnd(paymentPreferences, exprs));
if ((billingAccountPaymentPreference != null) && (billingAccountPaymentPreference.getBigDecimal("maxAmount") != null)) {
return billingAccountPaymentPreference.getBigDecimal("maxAmount");
}
return BigDecimal.ZERO;
}
/**
* Returns party from OrderRole of BILL_TO_CUSTOMER
*/
public GenericValue getBillToParty() {
return this.getPartyFromRole("BILL_TO_CUSTOMER");
}
/**
* Returns party from OrderRole of BILL_FROM_VENDOR
*/
public GenericValue getBillFromParty() {
return this.getPartyFromRole("BILL_FROM_VENDOR");
}
/**
* Returns party from OrderRole of SHIP_TO_CUSTOMER
*/
public GenericValue getShipToParty() {
return this.getPartyFromRole("SHIP_TO_CUSTOMER");
}
/**
* Returns party from OrderRole of PLACING_CUSTOMER
*/
public GenericValue getPlacingParty() {
return this.getPartyFromRole("PLACING_CUSTOMER");
}
/**
* Returns party from OrderRole of END_USER_CUSTOMER
*/
public GenericValue getEndUserParty() {
return this.getPartyFromRole("END_USER_CUSTOMER");
}
/**
* Returns party from OrderRole of SUPPLIER_AGENT
*/
public GenericValue getSupplierAgent() {
return this.getPartyFromRole("SUPPLIER_AGENT");
}
/**
* SCIPIO: Returns party from OrderRole of BILL_TO_CUSTOMER.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getBillToPartyId() {
return this.getPartyIdFromRole("BILL_TO_CUSTOMER");
}
/**
* SCIPIO: Returns partyId from OrderRole of BILL_FROM_VENDOR.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getBillFromPartyId() {
return this.getPartyIdFromRole("BILL_FROM_VENDOR");
}
/**
* SCIPIO: Returns partyId from OrderRole of SHIP_TO_CUSTOMER.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getShipToPartyId() {
return this.getPartyIdFromRole("SHIP_TO_CUSTOMER");
}
/**
* SCIPIO: Returns partyId from OrderRole of PLACING_CUSTOMER.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getPlacingPartyId() {
return this.getPartyIdFromRole("PLACING_CUSTOMER");
}
/**
* SCIPIO: Returns partyId from OrderRole of END_USER_CUSTOMER.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getEndUserPartyId() {
return this.getPartyIdFromRole("END_USER_CUSTOMER");
}
/**
* SCIPIO: Returns partyId from OrderRole of SUPPLIER_AGENT.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getSupplierAgentPartyId() {
return this.getPartyIdFromRole("SUPPLIER_AGENT");
}
public GenericValue getPartyFromRole(String roleTypeId) {
Delegator delegator = orderHeader.getDelegator();
GenericValue partyObject = null;
try {
GenericValue orderRole = EntityUtil.getFirst(orderHeader.getRelated("OrderRole", UtilMisc.toMap("roleTypeId", roleTypeId), null, false));
if (orderRole != null) {
partyObject = EntityQuery.use(delegator).from("Person").where("partyId", orderRole.getString("partyId")).queryOne();
if (partyObject == null) {
partyObject = EntityQuery.use(delegator).from("PartyGroup").where("partyId", orderRole.getString("partyId")).queryOne();
// SCIPIO: 2019-02-27: WARN: when no Person or PartyGroup, most likely the entity data is not appropriate
// for use by (callers of) this method; alternatively, the data may be incomplete.
// This is clear due to some templates unconditionally falling back to PartyGroup.groupName when no Person record.
if (partyObject == null) {
GenericValue party = EntityQuery.use(delegator).from("Party").where("partyId", orderRole.getString("partyId")).queryOne();
if (party != null) {
Debug.logWarning("getPartyFromRole: Party '" + orderRole.getString("partyId")
+ "' (from orderId '" + getOrderId() + "', roleTypeId '" + roleTypeId + "', partyTypeId '"
+ party.get("partyTypeId") + "') has no Person or PartyGroup"
+ " (unsupported configuration); returning null", module);
} else {
Debug.logError("getPartyFromRole: Party '" + orderRole.getString("partyId")
+ "' (from orderId '" + getOrderId() + "', roleTypeId '" + roleTypeId + "') does not exist (bad partyId)"
+ "; returning null", module);
}
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return partyObject;
}
/**
* SCIPIO: Returns the partyId from the specified OrderRole for the order.
* NOTE: Unlike {@link #getPartyFromRole}, this will return a partyId regardless of party type.
*/
public String getPartyIdFromRole(String roleTypeId) { // SCIPIO: Added 2019-02
try {
GenericValue orderRole = EntityUtil.getFirst(orderHeader.getRelated("OrderRole", UtilMisc.toMap("roleTypeId", roleTypeId), null, false));
if (orderRole != null) {
return orderRole.getString("partyId");
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return null;
}
public String getDistributorId() {
try {
GenericEntity distributorRole = EntityUtil.getFirst(orderHeader.getRelated("OrderRole", UtilMisc.toMap("roleTypeId", "DISTRIBUTOR"), null, false));
return distributorRole == null ? null : distributorRole.getString("partyId");
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public String getAffiliateId() {
try {
GenericEntity distributorRole = EntityUtil.getFirst(orderHeader.getRelated("OrderRole", UtilMisc.toMap("roleTypeId", "AFFILIATE"), null, false));
return distributorRole == null ? null : distributorRole.getString("partyId");
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public BigDecimal getShippingTotal() {
return OrderReadHelper.calcOrderAdjustments(getOrderHeaderAdjustments(), getOrderItemsSubTotal(), false, false, true);
}
public BigDecimal getHeaderTaxTotal() {
return OrderReadHelper.calcOrderAdjustments(getOrderHeaderAdjustments(), getOrderItemsSubTotal(), false, true, false);
}
public BigDecimal getTaxTotal() {
return OrderReadHelper.calcOrderAdjustments(getAdjustments(), getOrderItemsSubTotal(), false, true, false);
}
public Set<String> getItemFeatureSet(GenericValue item) {
Set<String> featureSet = new LinkedHashSet<>();
List<GenericValue> featureAppls = null;
if (item.get("productId") != null) {
try {
featureAppls = item.getDelegator().findByAnd("ProductFeatureAppl", UtilMisc.toMap("productId", item.getString("productId")), null, true);
List<EntityExpr> filterExprs = UtilMisc.toList(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "STANDARD_FEATURE"));
filterExprs.add(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "REQUIRED_FEATURE"));
featureAppls = EntityUtil.filterByOr(featureAppls, filterExprs);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get ProductFeatureAppl for item : " + item, module);
}
if (featureAppls != null) {
for (GenericValue appl : featureAppls) {
featureSet.add(appl.getString("productFeatureId"));
}
}
}
// get the ADDITIONAL_FEATURE adjustments
List<GenericValue> additionalFeatures = null;
try {
additionalFeatures = item.getRelated("OrderAdjustment", UtilMisc.toMap("orderAdjustmentTypeId", "ADDITIONAL_FEATURE"), null, false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get OrderAdjustment from item : " + item, module);
}
if (additionalFeatures != null) {
for (GenericValue adj : additionalFeatures) {
String featureId = adj.getString("productFeatureId");
if (featureId != null) {
featureSet.add(featureId);
}
}
}
return featureSet;
}
public Map<String, BigDecimal> getFeatureIdQtyMap(String shipGroupSeqId) {
Map<String, BigDecimal> featureMap = new HashMap<>();
List<GenericValue> validItems = getValidOrderItems(shipGroupSeqId);
if (validItems != null) {
for (GenericValue item : validItems) {
List<GenericValue> featureAppls = null;
if (item.get("productId") != null) {
try {
featureAppls = item.getDelegator().findByAnd("ProductFeatureAppl", UtilMisc.toMap("productId", item.getString("productId")), null, true);
List<EntityExpr> filterExprs = UtilMisc.toList(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "STANDARD_FEATURE"));
filterExprs.add(EntityCondition.makeCondition("productFeatureApplTypeId", EntityOperator.EQUALS, "REQUIRED_FEATURE"));
featureAppls = EntityUtil.filterByOr(featureAppls, filterExprs);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get ProductFeatureAppl for item : " + item, module);
}
if (featureAppls != null) {
for (GenericValue appl : featureAppls) {
BigDecimal lastQuantity = featureMap.get(appl.getString("productFeatureId"));
if (lastQuantity == null) {
lastQuantity = BigDecimal.ZERO;
}
BigDecimal newQuantity = lastQuantity.add(getOrderItemQuantity(item));
featureMap.put(appl.getString("productFeatureId"), newQuantity);
}
}
}
// get the ADDITIONAL_FEATURE adjustments
List<GenericValue> additionalFeatures = null;
try {
additionalFeatures = item.getRelated("OrderAdjustment", UtilMisc.toMap("orderAdjustmentTypeId", "ADDITIONAL_FEATURE"), null, false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get OrderAdjustment from item : " + item, module);
}
if (additionalFeatures != null) {
for (GenericValue adj : additionalFeatures) {
String featureId = adj.getString("productFeatureId");
if (featureId != null) {
BigDecimal lastQuantity = featureMap.get(featureId);
if (lastQuantity == null) {
lastQuantity = BigDecimal.ZERO;
}
BigDecimal newQuantity = lastQuantity.add(getOrderItemQuantity(item));
featureMap.put(featureId, newQuantity);
}
}
}
}
}
return featureMap;
}
public boolean shippingApplies() {
boolean shippingApplies = false;
List<GenericValue> validItems = this.getValidOrderItems();
if (validItems != null) {
for (GenericValue item : validItems) {
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
shippingApplies = true;
break;
}
}
}
}
return shippingApplies;
}
public boolean taxApplies() {
boolean taxApplies = false;
List<GenericValue> validItems = this.getValidOrderItems();
if (validItems != null) {
for (GenericValue item : validItems) {
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
}
if (product != null) {
if (ProductWorker.taxApplies(product)) {
taxApplies = true;
break;
}
}
}
}
return taxApplies;
}
public BigDecimal getShippableTotal(String shipGroupSeqId) {
BigDecimal shippableTotal = ZERO;
List<GenericValue> validItems = getValidOrderItems(shipGroupSeqId);
if (validItems != null) {
for (GenericValue item : validItems) {
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
return ZERO;
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
shippableTotal = shippableTotal.add(OrderReadHelper.getOrderItemSubTotal(item, getAdjustments(), false, true)).setScale(scale, rounding);
}
}
}
}
return shippableTotal.setScale(scale, rounding);
}
public BigDecimal getShippableQuantity() {
BigDecimal shippableQuantity = ZERO;
List<GenericValue> shipGroups = getOrderItemShipGroups();
if (UtilValidate.isNotEmpty(shipGroups)) {
for (GenericValue shipGroup : shipGroups) {
shippableQuantity = shippableQuantity.add(getShippableQuantity(shipGroup.getString("shipGroupSeqId")));
}
}
return shippableQuantity.setScale(scale, rounding);
}
public BigDecimal getShippableQuantity(String shipGroupSeqId) {
BigDecimal shippableQuantity = ZERO;
List<GenericValue> validItems = getValidOrderItems(shipGroupSeqId);
if (validItems != null) {
for (GenericValue item : validItems) {
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
return ZERO;
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
shippableQuantity = shippableQuantity.add(getOrderItemQuantity(item)).setScale(scale, rounding);
}
}
}
}
return shippableQuantity.setScale(scale, rounding);
}
public BigDecimal getShippableWeight(String shipGroupSeqId) {
BigDecimal shippableWeight = ZERO;
List<GenericValue> validItems = getValidOrderItems(shipGroupSeqId);
if (validItems != null) {
for (GenericValue item : validItems) {
shippableWeight = shippableWeight.add(this.getItemWeight(item).multiply(getOrderItemQuantity(item))).setScale(scale, rounding);
}
}
return shippableWeight.setScale(scale, rounding);
}
public BigDecimal getItemWeight(GenericValue item) {
Delegator delegator = orderHeader.getDelegator();
BigDecimal itemWeight = ZERO;
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem; returning 0", module);
return BigDecimal.ZERO;
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
BigDecimal weight = product.getBigDecimal("weight");
String isVariant = product.getString("isVariant");
if (weight == null && "Y".equals(isVariant)) {
// get the virtual product and check its weight
try {
String virtualId = ProductWorker.getVariantVirtualId(product);
if (UtilValidate.isNotEmpty(virtualId)) {
GenericValue virtual = EntityQuery.use(delegator).from("Product").where("productId", virtualId).cache().queryOne();
if (virtual != null) {
weight = virtual.getBigDecimal("weight");
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting virtual product");
}
}
if (weight != null) {
itemWeight = weight;
}
}
}
return itemWeight;
}
/**
* SCIPIO: Returns a map containing "weight" and "weightUomId" keys, or null.
* NOTE: This follows {@link #getItemWeight(GenericValue)} and returns null if
* shipping does not apply to the product.
*/
public Map<String, Object> getItemWeightInfo(GenericValue item) {
Delegator delegator = orderHeader.getDelegator();
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem", module);
return null;
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
BigDecimal weight = product.getBigDecimal("weight");
String isVariant = product.getString("isVariant");
if (weight == null && "Y".equals(isVariant)) {
// get the virtual product and check its weight
try {
String virtualId = ProductWorker.getVariantVirtualId(product);
if (UtilValidate.isNotEmpty(virtualId)) {
GenericValue virtual = EntityQuery.use(delegator).from("Product").where("productId", virtualId).cache().queryOne();
if (virtual != null) {
weight = virtual.getBigDecimal("weight");
product = virtual;
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting virtual product");
}
}
return product;
}
}
return null;
}
public List<BigDecimal> getShippableSizes() {
List<BigDecimal> shippableSizes = new ArrayList<>();
List<GenericValue> validItems = getValidOrderItems();
if (validItems != null) {
for (GenericValue item : validItems) {
shippableSizes.add(this.getItemSize(item));
}
}
return shippableSizes;
}
/**
* Get the total payment preference amount by payment type. Specify null to get amount
* for all preference types. TODO: filter by status as well?
*/
public BigDecimal getOrderPaymentPreferenceTotalByType(String paymentMethodTypeId) {
BigDecimal total = ZERO;
for (GenericValue preference : getPaymentPreferences()) {
if (preference.get("maxAmount") == null) {
continue;
}
if (paymentMethodTypeId == null || paymentMethodTypeId.equals(preference.get("paymentMethodTypeId"))) {
total = total.add(preference.getBigDecimal("maxAmount")).setScale(scale, rounding);
}
}
return total;
}
/**
* SCIPIO: Get the total payment preference amount for each payment method
* or type.
*/
public Map<String, BigDecimal> getOrderPaymentPreferenceTotalsByIdOrType() {
Map<String, BigDecimal> totals = new HashMap<>();
for (GenericValue preference : getPaymentPreferences()) {
if (preference.get("maxAmount") == null)
continue;
if (UtilValidate.isNotEmpty(preference.getString("paymentMethodId"))) {
BigDecimal total = totals.get(preference.getString("paymentMethodId"));
if (total == null) {
total = BigDecimal.ZERO;
}
total = total.add(preference.getBigDecimal("maxAmount")).setScale(scale, rounding);
totals.put(preference.getString("paymentMethodId"), total);
} else if (UtilValidate.isNotEmpty(preference.getString("paymentMethodTypeId"))) {
BigDecimal total = totals.get(preference.getString("paymentMethodTypeId"));
if (total == null) {
total = BigDecimal.ZERO;
}
total = total.add(preference.getBigDecimal("maxAmount")).setScale(scale, rounding);
totals.put(preference.getString("paymentMethodTypeId"), total);
}
}
return totals;
}
public BigDecimal getCreditCardPaymentPreferenceTotal() {
return getOrderPaymentPreferenceTotalByType("CREDIT_CARD");
}
public BigDecimal getBillingAccountPaymentPreferenceTotal() {
return getOrderPaymentPreferenceTotalByType("EXT_BILLACT");
}
public BigDecimal getGiftCardPaymentPreferenceTotal() {
return getOrderPaymentPreferenceTotalByType("GIFT_CARD");
}
/**
* Get the total payment received amount by payment type. Specify null to get amount
* over all types. This method works by going through all the PaymentAndApplications
* for all order Invoices that have status PMNT_RECEIVED.
*/
public BigDecimal getOrderPaymentReceivedTotalByType(String paymentMethodTypeId) {
BigDecimal total = ZERO;
try {
// get a set of invoice IDs that belong to the order
List<GenericValue> orderItemBillings = orderHeader.getRelated("OrderItemBilling", null, null, false);
Set<String> invoiceIds = new HashSet<>();
for (GenericValue orderItemBilling : orderItemBillings) {
invoiceIds.add(orderItemBilling.getString("invoiceId"));
}
// get the payments of the desired type for these invoices TODO: in models where invoices can have many orders, this needs to be refined
List<EntityExpr> conditions = UtilMisc.toList(
EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PMNT_RECEIVED"),
EntityCondition.makeCondition("invoiceId", EntityOperator.IN, invoiceIds));
if (paymentMethodTypeId != null) {
conditions.add(EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, paymentMethodTypeId));
}
EntityConditionList<EntityExpr> ecl = EntityCondition.makeCondition(conditions, EntityOperator.AND);
List<GenericValue> payments = orderHeader.getDelegator().findList("PaymentAndApplication", ecl, null, null, null, true);
for (GenericValue payment : payments) {
if (payment.get("amountApplied") == null) {
continue;
}
total = total.add(payment.getBigDecimal("amountApplied")).setScale(scale, rounding);
}
} catch (GenericEntityException e) {
Debug.logError(e, e.getMessage(), module);
}
return total;
}
public BigDecimal getItemSize(GenericValue item) {
Delegator delegator = orderHeader.getDelegator();
BigDecimal size = BigDecimal.ZERO;
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem", module);
return BigDecimal.ZERO;
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
BigDecimal height = product.getBigDecimal("shippingHeight");
BigDecimal width = product.getBigDecimal("shippingWidth");
BigDecimal depth = product.getBigDecimal("shippingDepth");
String isVariant = product.getString("isVariant");
if ((height == null || width == null || depth == null) && "Y".equals(isVariant)) {
// get the virtual product and check its values
try {
String virtualId = ProductWorker.getVariantVirtualId(product);
if (UtilValidate.isNotEmpty(virtualId)) {
GenericValue virtual = EntityQuery.use(delegator).from("Product").where("productId", virtualId).cache().queryOne();
if (virtual != null) {
if (height == null) {
height = virtual.getBigDecimal("shippingHeight");
}
if (width == null) {
width = virtual.getBigDecimal("shippingWidth");
}
if (depth == null) {
depth = virtual.getBigDecimal("shippingDepth");
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting virtual product");
}
}
if (height == null) {
height = BigDecimal.ZERO;
}
if (width == null) {
width = BigDecimal.ZERO;
}
if (depth == null) {
depth = BigDecimal.ZERO;
}
// determine girth (longest field is length)
BigDecimal[] sizeInfo = { height, width, depth };
Arrays.sort(sizeInfo);
size = sizeInfo[0].multiply(new BigDecimal("2")).add(sizeInfo[1].multiply(new BigDecimal("2"))).add(sizeInfo[2]);
}
}
return size;
}
public long getItemPiecesIncluded(GenericValue item) {
Delegator delegator = orderHeader.getDelegator();
long piecesIncluded = 1;
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting Product from OrderItem; returning 1", module);
return 1;
}
if (product != null) {
if (ProductWorker.shippingApplies(product)) {
Long pieces = product.getLong("piecesIncluded");
String isVariant = product.getString("isVariant");
if (pieces == null && isVariant != null && "Y".equals(isVariant)) {
// get the virtual product and check its weight
GenericValue virtual = null;
try {
virtual = EntityQuery.use(delegator).from("ProductAssoc")
.where("productIdTo", product.get("productId"),
"productAssocTypeId", "PRODUCT_VARIANT")
.orderBy("-fromDate")
.filterByDate().queryFirst();
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting virtual product");
}
if (virtual != null) {
try {
GenericValue virtualProduct = virtual.getRelatedOne("MainProduct", false);
pieces = virtualProduct.getLong("piecesIncluded");
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting virtual product");
}
}
}
if (pieces != null) {
piecesIncluded = pieces;
}
}
}
return piecesIncluded;
}
public List<Map<String, Object>> getShippableItemInfo(String shipGroupSeqId) {
List<Map<String, Object>> shippableInfo = new ArrayList<>();
List<GenericValue> validItems = getValidOrderItems(shipGroupSeqId);
if (validItems != null) {
for (GenericValue item : validItems) {
shippableInfo.add(this.getItemInfoMap(item));
}
}
return shippableInfo;
}
public Map<String, Object> getItemInfoMap(GenericValue item) {
Map<String, Object> itemInfo = new HashMap<>();
itemInfo.put("productId", item.getString("productId"));
itemInfo.put("quantity", getOrderItemQuantity(item));
// SCIPIO: 2019-03-01: included weight uom ID
//itemInfo.put("weight", this.getItemWeight(item));
BigDecimal weight = null;
String weightUomId = null;
Map<String, Object> weightInfo = this.getItemWeightInfo(item);
if (weightInfo != null) {
weight = (BigDecimal) weightInfo.get("weight");
weightUomId = (String) weightInfo.get("weightUomId");
}
itemInfo.put("weight", weight != null ? weight : BigDecimal.ZERO);
itemInfo.put("weightUomId", weightUomId);
itemInfo.put("size", this.getItemSize(item));
itemInfo.put("piecesIncluded", this.getItemPiecesIncluded(item));
itemInfo.put("featureSet", this.getItemFeatureSet(item));
return itemInfo;
}
public String getOrderEmailString() {
Delegator delegator = orderHeader.getDelegator();
// get the email addresses from the order contact mech(s)
List<GenericValue> orderContactMechs = null;
try {
orderContactMechs = EntityQuery.use(delegator).from("OrderContactMech")
.where("orderId", orderHeader.get("orderId"),
"contactMechPurposeTypeId", "ORDER_EMAIL")
.queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problems getting order contact mechs", module);
}
StringBuilder emails = new StringBuilder();
if (orderContactMechs != null) {
for (GenericValue orderContactMech : orderContactMechs) {
try {
GenericValue contactMech = orderContactMech.getRelatedOne("ContactMech", false);
emails.append(emails.length() > 0 ? "," : "").append(contactMech.getString("infoString"));
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problems getting contact mech from order contact mech", module);
}
}
}
return emails.toString();
}
/**
* SCIPIO: Alternate to getOrderEmailString that returns as a list.
*/
public List<String> getOrderEmailList() {
Delegator delegator = orderHeader.getDelegator();
// get the email addresses from the order contact mech(s)
List<GenericValue> orderContactMechs = null;
try {
orderContactMechs = EntityQuery.use(delegator).from("OrderContactMech")
.where("orderId", orderHeader.get("orderId"), "contactMechPurposeTypeId", "ORDER_EMAIL").queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problems getting order contact mechs", module);
}
List<String> emails = new ArrayList<>();
if (orderContactMechs != null) {
for (GenericValue orderContactMech : orderContactMechs) {
try {
GenericValue contactMech = orderContactMech.getRelatedOne("ContactMech", false);
emails.add(contactMech.getString("infoString"));
} catch (GenericEntityException e) {
Debug.logWarning(e, "Problems getting contact mech from order contact mech", module);
}
}
}
return emails;
}
/**
* SCIPIO: return all OrderIds that match the current email address and that are not rejected or cancelled
*/
public List getAllCustomerOrderIdsFromOrderEmail() {
return getAllCustomerOrderIdsFromEmail(getOrderEmailString(),new ArrayList<String>());
}
public List getAllCustomerOrderIdsFromOrderEmail(List<String>filteredStatusIds) {
return getAllCustomerOrderIdsFromEmail(getOrderEmailString(),filteredStatusIds);
}
/**
* SCIPIO: return all OrderIds that match the email address
*/
public List<String> getAllCustomerOrderIdsFromEmail(String emailAddress,List<String>filteredStatusIds) {
List<String> orderList = new ArrayList<>();
try {
List<GenericValue> vl = getAllCustomerOrderIdsFromEmailGenericValue(emailAddress,filteredStatusIds);
for (GenericValue n : vl) {
String orderId = n.getString("orderId");
orderList.add(orderId);
}
} catch (Exception e) {
Debug.logError(e,module);
}
return orderList;
}
public List<GenericValue> getAllCustomerOrderIdsFromEmailGenericValue(String emailAddress, List<String>filteredStatusIds) {
Delegator delegator = orderHeader.getDelegator();
List<GenericValue> orderList = new ArrayList<GenericValue>();
int rfmDays = UtilProperties.getPropertyAsInteger("order.properties","order.rfm.days",730);
DynamicViewEntity dve = new DynamicViewEntity();
dve.addMemberEntity("OH", "OrderHeader");
dve.addMemberEntity("OHR", "OrderRole");
dve.addMemberEntity("OCM", "OrderContactMech");
dve.addMemberEntity("CM", "ContactMech");
dve.addAlias("OH", "orderDate",null,null,null,true,null);
dve.addAlias("OH", "statusId",null,null,null,false,null);
dve.addAlias("OHR", "orderId", null, null, null, false, null);
dve.addAlias("OHR", "partyId", null, null, null, false, null);
dve.addAlias("OHR", "roleTypeId", null, null, null, false, null);
dve.addAlias("OCM", "contactMechPurposeTypeId", null, null, null, true, null);
dve.addAlias("CM", "emailAddress", "infoString", null, null, true, null);
dve.addViewLink("OH", "OHR", Boolean.FALSE, ModelKeyMap.makeKeyMapList("orderId", "orderId"));
dve.addViewLink("OH", "OCM", Boolean.FALSE, ModelKeyMap.makeKeyMapList("orderId", "orderId"));
dve.addViewLink("OCM", "CM", Boolean.FALSE, ModelKeyMap.makeKeyMapList("contactMechId", "contactMechId"));
List<EntityCondition> exprListStatus = new ArrayList<>();
EntityCondition expr = EntityCondition.makeCondition("emailAddress", EntityOperator.EQUALS, emailAddress);
exprListStatus.add(expr);
expr = EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "PLACING_CUSTOMER");
exprListStatus.add(expr);
expr = EntityCondition.makeCondition("contactMechPurposeTypeId", EntityOperator.EQUALS, "ORDER_EMAIL");
exprListStatus.add(expr);
if(UtilValidate.isNotEmpty(filteredStatusIds)){
expr = EntityCondition.makeCondition("statusId", EntityOperator.NOT_IN, filteredStatusIds);
exprListStatus.add(expr);
}
if(rfmDays>0){
Calendar currentDayCal = Calendar.getInstance();
currentDayCal.set(Calendar.DATE, -rfmDays);
exprListStatus.add(EntityCondition.makeCondition("orderDate", EntityOperator.GREATER_THAN_EQUAL_TO, UtilDateTime.toTimestamp(currentDayCal.getTime())));
}
EntityCondition andCond = EntityCondition.makeCondition(exprListStatus, EntityOperator.AND);
try {
EntityListIterator customerOrdersIterator = delegator.findListIteratorByCondition(dve,andCond,null,UtilMisc.toList("orderId"),UtilMisc.toList("-orderDate"),null);
orderList = customerOrdersIterator.getCompleteList();
} catch (GenericEntityException e) {
Debug.logError(e,module);
}
return orderList.stream().distinct()
.collect(Collectors.toList());
}
public BigDecimal getOrderGrandTotal() {
if (totalPrice == null) {
totalPrice = getOrderGrandTotal(getValidOrderItems(), getAdjustments());
} // else already set
return totalPrice;
}
/**
* Gets the amount open on the order that is not covered by the relevant OrderPaymentPreferences.
* This works by adding up the amount allocated to each unprocessed OrderPaymentPreference and the
* amounts received and refunded as payments for the settled ones.
*/
public BigDecimal getOrderOpenAmount() throws GenericEntityException {
BigDecimal total = getOrderGrandTotal();
BigDecimal openAmount = BigDecimal.ZERO;
List<GenericValue> prefs = getPaymentPreferences();
// add up the covered amount, but skip preferences which are declined or cancelled
for (GenericValue pref : prefs) {
if ("PAYMENT_CANCELLED".equals(pref.get("statusId")) || "PAYMENT_DECLINED".equals(pref.get("statusId"))) {
continue;
} else if ("PAYMENT_SETTLED".equals(pref.get("statusId"))) {
List<GenericValue> responses = pref.getRelated("PaymentGatewayResponse", UtilMisc.toMap("transCodeEnumId", "PGT_CAPTURE"), null, false);
for (GenericValue response : responses) {
BigDecimal amount = response.getBigDecimal("amount");
if (amount != null) {
openAmount = openAmount.add(amount);
}
}
responses = pref.getRelated("PaymentGatewayResponse", UtilMisc.toMap("transCodeEnumId", "PGT_REFUND"), null, false);
for (GenericValue response : responses) {
BigDecimal amount = response.getBigDecimal("amount");
if (amount != null) {
openAmount = openAmount.subtract(amount);
}
}
} else {
// all others are currently "unprocessed" payment preferences
BigDecimal maxAmount = pref.getBigDecimal("maxAmount");
if (maxAmount != null) {
openAmount = openAmount.add(maxAmount);
}
}
}
openAmount = total.subtract(openAmount).setScale(scale, rounding);
// return either a positive amount or positive zero
return openAmount.compareTo(BigDecimal.ZERO) > 0 ? openAmount : BigDecimal.ZERO;
}
public List<GenericValue> getOrderHeaderAdjustments() {
return getOrderHeaderAdjustments(getAdjustments(), null);
}
public List<GenericValue> getOrderHeaderAdjustments(String shipGroupSeqId) {
return getOrderHeaderAdjustments(getAdjustments(), shipGroupSeqId);
}
public List<GenericValue> getOrderHeaderAdjustmentsTax(String shipGroupSeqId) {
return filterOrderAdjustments(getOrderHeaderAdjustments(getAdjustments(), shipGroupSeqId), false, true, false, false, false);
}
public List<GenericValue> getOrderHeaderAdjustmentsToShow() {
return filterOrderAdjustments(getOrderHeaderAdjustments(), true, false, false, false, false);
}
public List<GenericValue> getOrderHeaderStatuses() {
return getOrderHeaderStatuses(getOrderStatuses());
}
public BigDecimal getOrderAdjustmentsTotal() {
return getOrderAdjustmentsTotal(getValidOrderItems(), getAdjustments());
}
public BigDecimal getOrderAdjustmentTotal(GenericValue adjustment) {
return calcOrderAdjustment(adjustment, getOrderItemsSubTotal());
}
public int hasSurvey() {
Delegator delegator = orderHeader.getDelegator();
List<GenericValue> surveys = null;
try {
surveys = EntityQuery.use(delegator).from("SurveyResponse")
.where("orderId", orderHeader.get("orderId")).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
int size = 0;
if (surveys != null) {
size = surveys.size();
}
return size;
}
// ========================================
// ========== Order Item Methods ==========
// ========================================
public List<GenericValue> getOrderItems() {
if (orderItems == null) {
try {
orderItems = orderHeader.getRelated("OrderItem", null, UtilMisc.toList("orderItemSeqId"), false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
}
return orderItems;
}
public List<GenericValue> getOrderItemAndShipGroupAssoc() {
if (orderItemAndShipGrp == null) {
try {
orderItemAndShipGrp = orderHeader.getDelegator().findByAnd("OrderItemAndShipGroupAssoc",
UtilMisc.toMap("orderId", orderHeader.getString("orderId")), null, false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
}
return orderItemAndShipGrp;
}
public List<GenericValue> getOrderItemAndShipGroupAssoc(String shipGroupSeqId) {
List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("shipGroupSeqId", EntityOperator.EQUALS, shipGroupSeqId));
return EntityUtil.filterByAnd(getOrderItemAndShipGroupAssoc(), exprs);
}
public List<GenericValue> getValidOrderItems() {
List<EntityExpr> exprs = UtilMisc.toList(
EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"),
EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED"));
return EntityUtil.filterByAnd(getOrderItems(), exprs);
}
public boolean getPastEtaOrderItems(String orderId) {
Delegator delegator = orderHeader.getDelegator();
GenericValue orderDeliverySchedule = null;
try {
orderDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", "_NA_").queryOne();
} catch (GenericEntityException e) {
if (Debug.infoOn()) {
Debug.logInfo(" OrderDeliverySchedule not found for order " + orderId, module);
}
return false;
}
if (orderDeliverySchedule == null) {
return false;
}
Timestamp estimatedShipDate = orderDeliverySchedule.getTimestamp("estimatedReadyDate");
return estimatedShipDate != null && UtilDateTime.nowTimestamp().after(estimatedShipDate);
}
public boolean getRejectedOrderItems() {
List<GenericValue> items = getOrderItems();
for (GenericValue item : items) {
List<GenericValue> receipts = null;
try {
receipts = item.getRelated("ShipmentReceipt", null, null, false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
if (UtilValidate.isNotEmpty(receipts)) {
for (GenericValue rec : receipts) {
BigDecimal rejected = rec.getBigDecimal("quantityRejected");
if (rejected != null && rejected.compareTo(BigDecimal.ZERO) > 0) {
return true;
}
}
}
}
return false;
}
public boolean getPartiallyReceivedItems() {
List<GenericValue> items = getOrderItems();
for (GenericValue item : items) {
List<GenericValue> receipts = null;
try {
receipts = item.getRelated("ShipmentReceipt", null, null, false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
if (UtilValidate.isNotEmpty(receipts)) {
for (GenericValue rec : receipts) {
BigDecimal acceptedQuantity = rec.getBigDecimal("quantityAccepted");
BigDecimal orderedQuantity = (BigDecimal) item.get("quantity");
if (acceptedQuantity.intValue() != orderedQuantity.intValue() && acceptedQuantity.intValue() > 0) {
return true;
}
}
}
}
return false;
}
public List<GenericValue> getValidOrderItems(String shipGroupSeqId) {
if (shipGroupSeqId == null) {
return getValidOrderItems();
}
List<EntityExpr> exprs = UtilMisc.toList(
EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"),
EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED"),
EntityCondition.makeCondition("shipGroupSeqId", EntityOperator.EQUALS, shipGroupSeqId));
return EntityUtil.filterByAnd(getOrderItemAndShipGroupAssoc(), exprs);
}
public GenericValue getOrderItem(String orderItemSeqId) {
List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItemSeqId));
return EntityUtil.getFirst(EntityUtil.filterByAnd(getOrderItems(), exprs));
}
public List<GenericValue> getValidDigitalItems() {
List<GenericValue> digitalItems = new ArrayList<>();
// only approved or complete items apply
List<EntityExpr> exprs = UtilMisc.toList(
EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ITEM_APPROVED"),
EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ITEM_COMPLETED"));
List<GenericValue> items = EntityUtil.filterByOr(getOrderItems(), exprs);
for (GenericValue item : items) {
if (item.get("productId") != null) {
GenericValue product = null;
try {
product = item.getRelatedOne("Product", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get Product from OrderItem", module);
}
if (product != null) {
GenericValue productType = null;
try {
productType = product.getRelatedOne("ProductType", false);
} catch (GenericEntityException e) {
Debug.logError(e, "ERROR: Unable to get ProductType from Product", module);
}
if (productType != null) {
String isDigital = productType.getString("isDigital");
if (isDigital != null && "Y".equalsIgnoreCase(isDigital)) {
// make sure we have an OrderItemBilling record
List<GenericValue> orderItemBillings = null;
try {
orderItemBillings = item.getRelated("OrderItemBilling", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get OrderItemBilling from OrderItem");
}
if (UtilValidate.isNotEmpty(orderItemBillings)) {
// get the ProductContent records
List<GenericValue> productContents = null;
try {
productContents = product.getRelated("ProductContent", null, null, false);
} catch (GenericEntityException e) {
Debug.logError("Unable to get ProductContent from Product", module);
}
List<EntityExpr> cExprs = UtilMisc.toList(
EntityCondition.makeCondition("productContentTypeId", EntityOperator.EQUALS, "DIGITAL_DOWNLOAD"),
EntityCondition.makeCondition("productContentTypeId", EntityOperator.EQUALS, "FULFILLMENT_EMAIL"),
EntityCondition.makeCondition("productContentTypeId", EntityOperator.EQUALS, "FULFILLMENT_EXTERNAL"));
// add more as needed
productContents = EntityUtil.filterByDate(productContents);
productContents = EntityUtil.filterByOr(productContents, cExprs);
if (UtilValidate.isNotEmpty(productContents)) {
// make sure we are still within the allowed timeframe and use limits
for (GenericValue productContent : productContents) {
Timestamp fromDate = productContent.getTimestamp("purchaseFromDate");
Timestamp thruDate = productContent.getTimestamp("purchaseThruDate");
if (fromDate == null || item.getTimestamp("orderDate").after(fromDate)) {
if (thruDate == null || item.getTimestamp("orderDate").before(thruDate)) {
// TODO: Implement use count and days
digitalItems.add(item);
}
}
}
}
}
}
}
}
}
}
return digitalItems;
}
public List<GenericValue> getOrderItemAdjustments(GenericValue orderItem) {
return getOrderItemAdjustmentList(orderItem, getAdjustments());
}
public String getCurrentOrderItemWorkEffort(GenericValue orderItem) {
String orderItemSeqId = orderItem.getString("orderItemSeqId");
String orderId = orderItem.getString("orderId");
Delegator delegator = orderItem.getDelegator();
GenericValue workOrderItemFulFillment = null;
GenericValue workEffort = null;
try {
workOrderItemFulFillment = EntityQuery.use(delegator).from("WorkOrderItemFulfillment")
.where("orderId", orderId, "orderItemSeqId", orderItemSeqId)
.cache().queryFirst();
if (workOrderItemFulFillment != null) {
workEffort = workOrderItemFulFillment.getRelatedOne("WorkEffort", false);
}
} catch (GenericEntityException e) {
return null;
}
if (workEffort != null) {
return workEffort.getString("workEffortId");
}
return null;
}
public String getCurrentItemStatus(GenericValue orderItem) {
GenericValue statusItem = null;
try {
statusItem = orderItem.getRelatedOne("StatusItem", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Trouble getting StatusItem : " + orderItem, module);
}
if (statusItem == null || statusItem.get("description") == null) {
return "Not Available";
}
return statusItem.getString("description");
}
public List<GenericValue> getOrderItemPriceInfos(GenericValue orderItem) {
if (orderItem == null) {
return null;
}
if (this.orderItemPriceInfos == null) {
Delegator delegator = orderHeader.getDelegator();
try {
orderItemPriceInfos = EntityQuery.use(delegator).from("OrderItemPriceInfo")
.where("orderId", orderHeader.get("orderId")).queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
}
String orderItemSeqId = (String) orderItem.get("orderItemSeqId");
return EntityUtil.filterByAnd(this.orderItemPriceInfos, UtilMisc.toMap("orderItemSeqId", orderItemSeqId));
}
public List<GenericValue> getOrderItemShipGroupAssocs(GenericValue orderItem) {
if (orderItem == null) {
return null;
}
try {
return orderHeader.getDelegator().findByAnd("OrderItemShipGroupAssoc",
UtilMisc.toMap("orderId", orderItem.getString("orderId"), "orderItemSeqId", orderItem.getString("orderItemSeqId")), UtilMisc.toList("shipGroupSeqId"), false);
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
}
return null;
}
public List<GenericValue> getOrderItemShipGrpInvResList(GenericValue orderItem) {
if (orderItem == null) {
return null;
}
if (this.orderItemShipGrpInvResList == null) {
Delegator delegator = orderItem.getDelegator();
try {
orderItemShipGrpInvResList = EntityQuery.use(delegator).from("OrderItemShipGrpInvRes")
.where("orderId", orderItem.get("orderId")).queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Trouble getting OrderItemShipGrpInvRes List", module);
}
}
return EntityUtil.filterByAnd(orderItemShipGrpInvResList, UtilMisc.toMap("orderItemSeqId", orderItem.getString("orderItemSeqId")));
}
public List<GenericValue> getOrderItemIssuances(GenericValue orderItem) {
return this.getOrderItemIssuances(orderItem, null);
}
public List<GenericValue> getOrderItemIssuances(GenericValue orderItem, String shipmentId) {
if (orderItem == null) {
return null;
}
if (this.orderItemIssuances == null) {
Delegator delegator = orderItem.getDelegator();
try {
orderItemIssuances = EntityQuery.use(delegator).from("ItemIssuance")
.where("orderId", orderItem.get("orderId")).queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Trouble getting ItemIssuance(s)", module);
}
}
// filter the issuances
Map<String, Object> filter = UtilMisc.toMap("orderItemSeqId", orderItem.get("orderItemSeqId"));
if (shipmentId != null) {
filter.put("shipmentId", shipmentId);
}
return EntityUtil.filterByAnd(orderItemIssuances, filter);
}
/** Get a set of productIds in the order. */
public Collection<String> getOrderProductIds() {
Set<String> productIds = new HashSet<>();
for (GenericValue orderItem : getOrderItems()) {
if (orderItem.get("productId") != null) {
productIds.add(orderItem.getString("productId"));
}
}
return productIds;
}
public List<GenericValue> getOrderReturnItems() {
Delegator delegator = orderHeader.getDelegator();
if (this.orderReturnItems == null) {
try {
this.orderReturnItems = EntityQuery.use(delegator).from("ReturnItem").where("orderId", orderHeader.get("orderId")).orderBy("returnItemSeqId").queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Problem getting ReturnItem from order", module);
return null;
}
}
return this.orderReturnItems;
}
/**
* Get the quantity returned per order item.
* In other words, this method will count the ReturnItems
* related to each OrderItem.
*
* @return Map of returned quantities as BigDecimals keyed to the orderItemSeqId
*/
public Map<String, BigDecimal> getOrderItemReturnedQuantities() {
List<GenericValue> returnItems = getOrderReturnItems();
// since we don't have a handy grouped view entity, we'll have to group the return items by hand
Map<String, BigDecimal> returnMap = new HashMap<>();
for (GenericValue orderItem : this.getValidOrderItems()) {
List<GenericValue> group = EntityUtil.filterByAnd(returnItems, UtilMisc.toList(
EntityCondition.makeCondition("orderId", orderItem.get("orderId")),
EntityCondition.makeCondition("orderItemSeqId", orderItem.get("orderItemSeqId")),
EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "RETURN_CANCELLED")));
// add up the returned quantities for this group TODO: received quantity should be used eventually
BigDecimal returned = BigDecimal.ZERO;
for (GenericValue returnItem : group) {
if (returnItem.getBigDecimal("returnQuantity") != null) {
returned = returned.add(returnItem.getBigDecimal("returnQuantity"));
}
}
// the quantity returned per order item
returnMap.put(orderItem.getString("orderItemSeqId"), returned);
}
return returnMap;
}
/**
* Get the total quantity of returned items for an order. This will count
* only the ReturnItems that are directly correlated to an OrderItem.
*/
public BigDecimal getOrderReturnedQuantity() {
List<GenericValue> returnedItemsBase = getOrderReturnItems();
List<GenericValue> returnedItems = new ArrayList<>(returnedItemsBase.size());
// filter just order items
List<EntityExpr> orderItemExprs = UtilMisc.toList(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_PROD_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_FPROD_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_DPROD_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_FDPROD_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_PROD_FEATR_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_SPROD_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_WE_ITEM"));
orderItemExprs.add(EntityCondition.makeCondition("returnItemTypeId", EntityOperator.EQUALS, "RET_TE_ITEM"));
returnedItemsBase = EntityUtil.filterByOr(returnedItemsBase, orderItemExprs);
// get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
BigDecimal returnedQuantity = ZERO;
for (GenericValue returnedItem : returnedItems) {
if (returnedItem.get("returnQuantity") != null) {
returnedQuantity = returnedQuantity.add(returnedItem.getBigDecimal("returnQuantity")).setScale(scale, rounding);
}
}
return returnedQuantity.setScale(scale, rounding);
}
/**
* Get the returned total by return type (credit, refund, etc.). Specify returnTypeId = null to get sum over all
* return types. Specify includeAll = true to sum up over all return statuses except cancelled. Specify includeAll
* = false to sum up over ACCEPTED,RECEIVED And COMPLETED returns.
*/
public BigDecimal getOrderReturnedTotalByTypeBd(String returnTypeId, boolean includeAll) {
List<GenericValue> returnedItemsBase = getOrderReturnItems();
if (returnTypeId != null) {
returnedItemsBase = EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("returnTypeId", returnTypeId));
}
List<GenericValue> returnedItems = new ArrayList<>(returnedItemsBase.size());
// get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
if (!includeAll) {
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_ACCEPTED")));
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
} else {
// otherwise get all of them except cancelled ones
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase,
UtilMisc.toList(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "RETURN_CANCELLED"))));
}
BigDecimal returnedAmount = ZERO;
String orderId = orderHeader.getString("orderId");
List<String> returnHeaderList = new ArrayList<>();
for (GenericValue returnedItem : returnedItems) {
if ((returnedItem.get("returnPrice") != null) && (returnedItem.get("returnQuantity") != null)) {
returnedAmount = returnedAmount.add(returnedItem.getBigDecimal("returnPrice").multiply(returnedItem.getBigDecimal("returnQuantity")).setScale(scale, rounding));
}
Map<String, Object> itemAdjustmentCondition = UtilMisc.toMap("returnId", returnedItem.get("returnId"), "returnItemSeqId", returnedItem.get("returnItemSeqId"));
if (UtilValidate.isNotEmpty(returnTypeId)) {
itemAdjustmentCondition.put("returnTypeId", returnTypeId);
}
returnedAmount = returnedAmount.add(getReturnAdjustmentTotal(orderHeader.getDelegator(), itemAdjustmentCondition));
if (orderId.equals(returnedItem.getString("orderId")) && (!returnHeaderList.contains(returnedItem.getString("returnId")))) {
returnHeaderList.add(returnedItem.getString("returnId"));
}
}
// get returnedAmount from returnHeader adjustments whose orderId must equals to current orderHeader.orderId
for (String returnId : returnHeaderList) {
Map<String, Object> returnHeaderAdjFilter = UtilMisc.<String, Object>toMap("returnId", returnId, "returnItemSeqId", "_NA_", "returnTypeId", returnTypeId);
returnedAmount = returnedAmount.add(getReturnAdjustmentTotal(orderHeader.getDelegator(), returnHeaderAdjFilter)).setScale(scale, rounding);
}
return returnedAmount.setScale(scale, rounding);
}
/** Gets the total return credit for COMPLETED and RECEIVED returns. */
public BigDecimal getOrderReturnedCreditTotalBd() {
return getOrderReturnedTotalByTypeBd("RTN_CREDIT", false);
}
/** Gets the total return refunded for COMPLETED and RECEIVED returns. */
public BigDecimal getOrderReturnedRefundTotalBd() {
return getOrderReturnedTotalByTypeBd("RTN_REFUND", false);
}
/** Gets the total return amount (all return types) for COMPLETED and RECEIVED returns. */
public BigDecimal getOrderReturnedTotal() {
return getOrderReturnedTotalByTypeBd(null, false);
}
/**
* Gets the total returned over all return types. Specify true to include all return statuses
* except cancelled. Specify false to include only COMPLETED and RECEIVED returns.
*/
public BigDecimal getOrderReturnedTotal(boolean includeAll) {
return getOrderReturnedTotalByTypeBd(null, includeAll);
}
public BigDecimal getOrderNonReturnedTaxAndShipping() {
// first make a Map of orderItemSeqId key, returnQuantity value
List<GenericValue> returnedItemsBase = getOrderReturnItems();
List<GenericValue> returnedItems = new ArrayList<>(returnedItemsBase.size());
// get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
Map<String, BigDecimal> itemReturnedQuantities = new HashMap<>();
for (GenericValue returnedItem : returnedItems) {
String orderItemSeqId = returnedItem.getString("orderItemSeqId");
BigDecimal returnedQuantity = returnedItem.getBigDecimal("returnQuantity");
if (orderItemSeqId != null && returnedQuantity != null) {
BigDecimal existingQuantity = itemReturnedQuantities.get(orderItemSeqId);
if (existingQuantity == null) {
itemReturnedQuantities.put(orderItemSeqId, returnedQuantity);
} else {
itemReturnedQuantities.put(orderItemSeqId, returnedQuantity.add(existingQuantity));
}
}
}
// then go through all order items and for the quantity not returned calculate it's portion of the item, and of the entire order
BigDecimal totalSubTotalNotReturned = ZERO;
BigDecimal totalTaxNotReturned = ZERO;
BigDecimal totalShippingNotReturned = ZERO;
for (GenericValue orderItem : this.getValidOrderItems()) {
BigDecimal itemQuantityDbl = orderItem.getBigDecimal("quantity");
if (itemQuantityDbl == null || itemQuantityDbl.compareTo(ZERO) == 0) {
continue;
}
BigDecimal itemQuantity = itemQuantityDbl;
BigDecimal itemSubTotal = this.getOrderItemSubTotal(orderItem);
BigDecimal itemTaxes = this.getOrderItemTax(orderItem);
BigDecimal itemShipping = this.getOrderItemShipping(orderItem);
BigDecimal quantityReturned = itemReturnedQuantities.get(orderItem.get("orderItemSeqId"));
if (quantityReturned == null) {
quantityReturned = BigDecimal.ZERO;
}
BigDecimal quantityNotReturned = itemQuantity.subtract(quantityReturned);
// pro-rated factor (quantity not returned / total items ordered), which shouldn't be rounded to 2 decimals
BigDecimal factorNotReturned = quantityNotReturned.divide(itemQuantity, 100, rounding);
BigDecimal subTotalNotReturned = itemSubTotal.multiply(factorNotReturned).setScale(scale, rounding);
// calculate tax and shipping adjustments for each item, add to accumulators
BigDecimal itemTaxNotReturned = itemTaxes.multiply(factorNotReturned).setScale(scale, rounding);
BigDecimal itemShippingNotReturned = itemShipping.multiply(factorNotReturned).setScale(scale, rounding);
totalSubTotalNotReturned = totalSubTotalNotReturned.add(subTotalNotReturned);
totalTaxNotReturned = totalTaxNotReturned.add(itemTaxNotReturned);
totalShippingNotReturned = totalShippingNotReturned.add(itemShippingNotReturned);
}
// calculate tax and shipping adjustments for entire order, add to result
BigDecimal orderItemsSubTotal = this.getOrderItemsSubTotal();
BigDecimal orderFactorNotReturned = ZERO;
if (orderItemsSubTotal.signum() != 0) {
// pro-rated factor (subtotal not returned / item subtotal), which shouldn't be rounded to 2 decimals
orderFactorNotReturned = totalSubTotalNotReturned.divide(orderItemsSubTotal, 100, rounding);
}
BigDecimal orderTaxNotReturned = this.getHeaderTaxTotal().multiply(orderFactorNotReturned).setScale(scale, rounding);
BigDecimal orderShippingNotReturned = this.getShippingTotal().multiply(orderFactorNotReturned).setScale(scale, rounding);
return totalTaxNotReturned.add(totalShippingNotReturned).add(orderTaxNotReturned).add(orderShippingNotReturned).setScale(scale, rounding);
}
/** Gets the total refunded to the order billing account by type. Specify null to get total over all types. */
public BigDecimal getBillingAccountReturnedTotalByTypeBd(String returnTypeId) {
BigDecimal returnedAmount = ZERO;
List<GenericValue> returnedItemsBase = getOrderReturnItems();
if (returnTypeId != null) {
returnedItemsBase = EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("returnTypeId", returnTypeId));
}
List<GenericValue> returnedItems = new ArrayList<>(returnedItemsBase.size());
// get only the RETURN_RECEIVED and RETURN_COMPLETED statusIds
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_RECEIVED")));
returnedItems.addAll(EntityUtil.filterByAnd(returnedItemsBase, UtilMisc.toMap("statusId", "RETURN_COMPLETED")));
// sum up the return items that have a return item response with a billing account defined
try {
for (GenericValue returnItem : returnedItems) {
GenericValue returnItemResponse = returnItem.getRelatedOne("ReturnItemResponse", false);
if (returnItemResponse == null) {
continue;
}
if (returnItemResponse.get("billingAccountId") == null) {
continue;
}
// we can just add the response amounts
returnedAmount = returnedAmount.add(returnItemResponse.getBigDecimal("responseAmount")).setScale(scale, rounding);
}
} catch (GenericEntityException e) {
Debug.logError(e, e.getMessage(), module);
}
return returnedAmount;
}
/** Get the total return credited to the order billing accounts */
public BigDecimal getBillingAccountReturnedCreditTotalBd() {
return getBillingAccountReturnedTotalByTypeBd("RTN_CREDIT");
}
/** Get the total return refunded to the order billing accounts */
public BigDecimal getBillingAccountReturnedRefundTotalBd() {
return getBillingAccountReturnedTotalByTypeBd("RTN_REFUND");
}
/** Gets the total return credited amount with refunds and credits to the billing account figured in */
public BigDecimal getReturnedCreditTotalWithBillingAccountBd() {
return getOrderReturnedCreditTotalBd().add(getBillingAccountReturnedRefundTotalBd()).subtract(getBillingAccountReturnedCreditTotalBd());
}
/** Gets the total return refund amount with refunds and credits to the billing account figured in */
public BigDecimal getReturnedRefundTotalWithBillingAccountBd() {
return getOrderReturnedRefundTotalBd().add(getBillingAccountReturnedCreditTotalBd()).subtract(getBillingAccountReturnedRefundTotalBd());
}
public BigDecimal getOrderBackorderQuantity() {
BigDecimal backorder = ZERO;
List<GenericValue> items = this.getValidOrderItems();
if (items != null) {
for (GenericValue item : items) {
List<GenericValue> reses = this.getOrderItemShipGrpInvResList(item);
if (reses != null) {
for (GenericValue res : reses) {
BigDecimal nav = res.getBigDecimal("quantityNotAvailable");
if (nav != null) {
backorder = backorder.add(nav).setScale(scale, rounding);
}
}
}
}
}
return backorder.setScale(scale, rounding);
}
public BigDecimal getItemPickedQuantityBd(GenericValue orderItem) {
BigDecimal quantityPicked = ZERO;
EntityConditionList<EntityExpr> pickedConditions = EntityCondition.makeCondition(UtilMisc.toList(
EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderItem.get("orderId")),
EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItem.getString("orderItemSeqId")),
EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PICKLIST_CANCELLED")),
EntityOperator.AND);
List<GenericValue> picked = null;
try {
picked = orderHeader.getDelegator().findList("PicklistAndBinAndItem", pickedConditions, null, null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
this.orderHeader = null;
}
if (picked != null) {
for (GenericValue pickedItem : picked) {
BigDecimal issueQty = pickedItem.getBigDecimal("quantity");
if (issueQty != null) {
quantityPicked = quantityPicked.add(issueQty).setScale(scale, rounding);
}
}
}
return quantityPicked.setScale(scale, rounding);
}
public BigDecimal getItemShippedQuantity(GenericValue orderItem) {
BigDecimal quantityShipped = ZERO;
List<GenericValue> issuance = getOrderItemIssuances(orderItem);
if (issuance != null) {
for (GenericValue issue : issuance) {
BigDecimal issueQty = issue.getBigDecimal("quantity");
BigDecimal cancelQty = issue.getBigDecimal("cancelQuantity");
if (cancelQty == null) {
cancelQty = ZERO;
}
if (issueQty == null) {
issueQty = ZERO;
}
quantityShipped = quantityShipped.add(issueQty.subtract(cancelQty)).setScale(scale, rounding);
}
}
return quantityShipped.setScale(scale, rounding);
}
public BigDecimal getItemShipGroupAssocShippedQuantity(GenericValue orderItem, String shipGroupSeqId) {
BigDecimal quantityShipped = ZERO;
if (orderItem == null) {
return null;
}
if (this.orderItemIssuances == null) {
Delegator delegator = orderItem.getDelegator();
try {
orderItemIssuances = EntityQuery.use(delegator).from("ItemIssuance").where("orderId", orderItem.get("orderId"), "shipGroupSeqId", shipGroupSeqId).queryList();
} catch (GenericEntityException e) {
Debug.logWarning(e, "Trouble getting ItemIssuance(s)", module);
}
}
// filter the issuance
Map<String, Object> filter = UtilMisc.toMap("orderItemSeqId", orderItem.get("orderItemSeqId"), "shipGroupSeqId", shipGroupSeqId);
List<GenericValue> issuances = EntityUtil.filterByAnd(orderItemIssuances, filter);
if (UtilValidate.isNotEmpty(issuances)) {
for (GenericValue issue : issuances) {
BigDecimal issueQty = issue.getBigDecimal("quantity");
BigDecimal cancelQty = issue.getBigDecimal("cancelQuantity");
if (cancelQty == null) {
cancelQty = ZERO;
}
if (issueQty == null) {
issueQty = ZERO;
}
quantityShipped = quantityShipped.add(issueQty.subtract(cancelQty)).setScale(scale, rounding);
}
}
return quantityShipped.setScale(scale, rounding);
}
public BigDecimal getItemReservedQuantity(GenericValue orderItem) {
BigDecimal reserved = ZERO;
List<GenericValue> reses = getOrderItemShipGrpInvResList(orderItem);
if (reses != null) {
for (GenericValue res : reses) {
BigDecimal quantity = res.getBigDecimal("quantity");
if (quantity != null) {
reserved = reserved.add(quantity).setScale(scale, rounding);
}
}
}
return reserved.setScale(scale, rounding);
}
public BigDecimal getItemBackorderedQuantity(GenericValue orderItem) {
BigDecimal backOrdered = ZERO;
Timestamp shipDate = orderItem.getTimestamp("estimatedShipDate");
Timestamp autoCancel = orderItem.getTimestamp("autoCancelDate");
List<GenericValue> reses = getOrderItemShipGrpInvResList(orderItem);
if (reses != null) {
for (GenericValue res : reses) {
Timestamp promised = res.getTimestamp("currentPromisedDate");
if (promised == null) {
promised = res.getTimestamp("promisedDatetime");
}
if (autoCancel != null || (shipDate != null && shipDate.after(promised))) {
BigDecimal resQty = res.getBigDecimal("quantity");
if (resQty != null) {
backOrdered = backOrdered.add(resQty).setScale(scale, rounding);
}
}
}
}
return backOrdered;
}
public BigDecimal getItemPendingShipmentQuantity(GenericValue orderItem) {
BigDecimal reservedQty = getItemReservedQuantity(orderItem);
BigDecimal backordered = getItemBackorderedQuantity(orderItem);
return reservedQty.subtract(backordered).setScale(scale, rounding);
}
public BigDecimal getItemCanceledQuantity(GenericValue orderItem) {
BigDecimal cancelQty = orderItem.getBigDecimal("cancelQuantity");
if (cancelQty == null) {
cancelQty = BigDecimal.ZERO;
}
return cancelQty;
}
public BigDecimal getTotalOrderItemsQuantity() {
List<GenericValue> orderItems = getValidOrderItems();
BigDecimal totalItems = ZERO;
for (int i = 0; i < orderItems.size(); i++) {
GenericValue oi = orderItems.get(i);
totalItems = totalItems.add(getOrderItemQuantity(oi)).setScale(scale, rounding);
}
return totalItems.setScale(scale, rounding);
}
public BigDecimal getTotalOrderItemsOrderedQuantity() {
List<GenericValue> orderItems = getValidOrderItems();
BigDecimal totalItems = ZERO;
for (int i = 0; i < orderItems.size(); i++) {
GenericValue oi = orderItems.get(i);
totalItems = totalItems.add(oi.getBigDecimal("quantity")).setScale(scale, rounding);
}
return totalItems;
}
public BigDecimal getOrderItemsSubTotal() {
return getOrderItemsSubTotal(getValidOrderItems(), getAdjustments());
}
public BigDecimal getOrderItemSubTotal(GenericValue orderItem) {
return getOrderItemSubTotal(orderItem, getAdjustments());
}
public BigDecimal getOrderItemsTotal() {
return getOrderItemsTotal(getValidOrderItems(), getAdjustments());
}
public BigDecimal getOrderItemTotal(GenericValue orderItem) {
return getOrderItemTotal(orderItem, getAdjustments());
}
public BigDecimal getOrderItemTax(GenericValue orderItem) {
return getOrderItemAdjustmentsTotal(orderItem, false, true, false);
}
public BigDecimal getOrderItemShipping(GenericValue orderItem) {
return getOrderItemAdjustmentsTotal(orderItem, false, false, true);
}
public BigDecimal getOrderItemAdjustmentsTotal(GenericValue orderItem, boolean includeOther, boolean includeTax, boolean includeShipping) {
return getOrderItemAdjustmentsTotal(orderItem, getAdjustments(), includeOther, includeTax, includeShipping);
}
public BigDecimal getOrderItemAdjustmentsTotal(GenericValue orderItem) {
return getOrderItemAdjustmentsTotal(orderItem, true, false, false);
}
public BigDecimal getOrderItemAdjustmentTotal(GenericValue orderItem, GenericValue adjustment) {
return calcItemAdjustment(adjustment, orderItem);
}
public String getAdjustmentType(GenericValue adjustment) {
GenericValue adjustmentType = null;
try {
adjustmentType = adjustment.getRelatedOne("OrderAdjustmentType", false);
} catch (GenericEntityException e) {
Debug.logError(e, "Problems with order adjustment", module);
}
if (adjustmentType == null || adjustmentType.get("description") == null) {
return "";
}
return adjustmentType.getString("description");
}
public List<GenericValue> getOrderItemStatuses(GenericValue orderItem) {
return getOrderItemStatuses(orderItem, getOrderStatuses());
}
public String getCurrentItemStatusString(GenericValue orderItem) {
GenericValue statusItem = null;
try {
statusItem = orderItem.getRelatedOne("StatusItem", true);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (statusItem != null) {
return statusItem.getString("description");
}
return orderHeader.getString("statusId");
}
/** Fetches the set of order items with the given EntityCondition. */
public List<GenericValue> getOrderItemsByCondition(EntityCondition entityCondition) {
return EntityUtil.filterByCondition(getOrderItems(), entityCondition);
}
public Set<String> getProductPromoCodesEntered() {
Delegator delegator = orderHeader.getDelegator();
Set<String> productPromoCodesEntered = new HashSet<>();
try {
for (GenericValue orderProductPromoCode : EntityQuery.use(delegator).from("OrderProductPromoCode").where("orderId", orderHeader.get("orderId")).cache().queryList()) {
productPromoCodesEntered.add(orderProductPromoCode.getString("productPromoCodeId"));
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return productPromoCodesEntered;
}
public List<GenericValue> getProductPromoUse() {
Delegator delegator = orderHeader.getDelegator();
try {
return EntityQuery.use(delegator).from("ProductPromoUse").where("orderId", orderHeader.get("orderId")).cache().queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return new ArrayList<>();
}
/**
* Checks to see if this user has read permission on this order
* @param userLogin The UserLogin value object to check
* @return boolean True if we have read permission
*/
public boolean hasPermission(Security security, GenericValue userLogin) {
return OrderReadHelper.hasPermission(security, userLogin, orderHeader);
}
/**
* Getter for property orderHeader.
* @return Value of property orderHeader.
*/
public GenericValue getOrderHeader() {
return orderHeader;
}
// ======================================================
// =================== Static Methods ===================
// ======================================================
public static GenericValue getOrderHeader(Delegator delegator, String orderId) {
GenericValue orderHeader = null;
if (orderId != null && delegator != null) {
try {
orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Cannot get order header for orderId [" + orderId + "]", module); // SCIPIO: Improved logging
}
}
return orderHeader;
}
public static BigDecimal getOrderItemQuantity(GenericValue orderItem) {
BigDecimal cancelQty = orderItem.getBigDecimal("cancelQuantity");
BigDecimal orderQty = orderItem.getBigDecimal("quantity");
if (cancelQty == null) {
cancelQty = ZERO;
}
if (orderQty == null) {
orderQty = ZERO;
}
return orderQty.subtract(cancelQty);
}
public static BigDecimal getOrderItemShipGroupQuantity(GenericValue shipGroupAssoc) {
BigDecimal cancelQty = shipGroupAssoc.getBigDecimal("cancelQuantity");
BigDecimal orderQty = shipGroupAssoc.getBigDecimal("quantity");
if (cancelQty == null) {
cancelQty = BigDecimal.ZERO;
}
if (orderQty == null) {
orderQty = BigDecimal.ZERO;
}
return orderQty.subtract(cancelQty);
}
public static GenericValue getProductStoreFromOrder(Delegator delegator, String orderId) {
GenericValue orderHeader = getOrderHeader(delegator, orderId);
if (orderHeader == null) {
Debug.logError("Could not find OrderHeader for orderId [" + orderId + "] in getProductStoreFromOrder, returning null", module); // SCIPIO: Changed to error, why ever?
}
return getProductStoreFromOrder(orderHeader);
}
public static GenericValue getProductStoreFromOrder(GenericValue orderHeader) {
if (orderHeader == null) {
return null;
}
Delegator delegator = orderHeader.getDelegator();
GenericValue productStore = null;
if (orderHeader.get("productStoreId") != null) {
try {
productStore = EntityQuery.use(delegator).from("ProductStore").where("productStoreId", orderHeader.getString("productStoreId")).cache().queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Cannot locate ProductStore from OrderHeader for orderId [" + orderHeader.get("orderId") + "]", module);
}
} else {
Debug.logError("Null header or productStoreId for orderId [" + orderHeader.get("orderId") + "]", module);
}
return productStore;
}
public static BigDecimal getOrderGrandTotal(List<GenericValue> orderItems, List<GenericValue> adjustments) {
Map<String, Object> orderTaxByTaxAuthGeoAndParty = getOrderTaxByTaxAuthGeoAndParty(adjustments);
BigDecimal taxGrandTotal = (BigDecimal) orderTaxByTaxAuthGeoAndParty.get("taxGrandTotal");
adjustments = EntityUtil.filterByAnd(adjustments, UtilMisc.toList(EntityCondition.makeCondition("orderAdjustmentTypeId", EntityOperator.NOT_EQUAL, "SALES_TAX")));
BigDecimal total = getOrderItemsTotal(orderItems, adjustments);
BigDecimal adj = getOrderAdjustmentsTotal(orderItems, adjustments);
total = ((total.add(taxGrandTotal)).add(adj)).setScale(scale, rounding);
return total;
}
public static List<GenericValue> getOrderHeaderAdjustments(List<GenericValue> adjustments, String shipGroupSeqId) {
List<EntityExpr> contraints1 = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, null));
List<EntityExpr> contraints2 = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, DataModelConstants.SEQ_ID_NA));
List<EntityExpr> contraints3 = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, ""));
List<EntityExpr> contraints4 = new ArrayList<>();
if (shipGroupSeqId != null) {
contraints4.add(EntityCondition.makeCondition("shipGroupSeqId", EntityOperator.EQUALS, shipGroupSeqId));
}
List<GenericValue> toFilter = null;
List<GenericValue> adj = new ArrayList<>();
if (shipGroupSeqId != null) {
toFilter = EntityUtil.filterByAnd(adjustments, contraints4);
} else {
toFilter = adjustments;
}
adj.addAll(EntityUtil.filterByAnd(toFilter, contraints1));
adj.addAll(EntityUtil.filterByAnd(toFilter, contraints2));
adj.addAll(EntityUtil.filterByAnd(toFilter, contraints3));
return adj;
}
public static List<GenericValue> getOrderHeaderStatuses(List<GenericValue> orderStatuses) {
List<EntityExpr> contraints1 = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, null));
contraints1.add(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, DataModelConstants.SEQ_ID_NA));
contraints1.add(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, ""));
List<EntityExpr> contraints2 = UtilMisc.toList(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.EQUALS, null));
contraints2.add(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.EQUALS, DataModelConstants.SEQ_ID_NA));
contraints2.add(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.EQUALS, ""));
List<GenericValue> newOrderStatuses = new ArrayList<>();
newOrderStatuses.addAll(EntityUtil.filterByOr(orderStatuses, contraints1));
return EntityUtil.orderBy(EntityUtil.filterByOr(newOrderStatuses, contraints2), UtilMisc.toList("-statusDatetime"));
}
public static BigDecimal getOrderAdjustmentsTotal(List<GenericValue> orderItems, List<GenericValue> adjustments) {
return calcOrderAdjustments(getOrderHeaderAdjustments(adjustments, null), getOrderItemsSubTotal(orderItems, adjustments), true, true, true);
}
public static List<GenericValue> getOrderSurveyResponses(GenericValue orderHeader) {
Delegator delegator = orderHeader.getDelegator();
String orderId = orderHeader.getString("orderId");
List<GenericValue> responses = null;
try {
responses = EntityQuery.use(delegator).from("SurveyResponse").where("orderId", orderId, "orderItemSeqId", "_NA_").queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (responses == null) {
responses = new ArrayList<>();
}
return responses;
}
public static List<GenericValue> getOrderItemSurveyResponse(GenericValue orderItem) {
Delegator delegator = orderItem.getDelegator();
String orderItemSeqId = orderItem.getString("orderItemSeqId");
String orderId = orderItem.getString("orderId");
List<GenericValue> responses = null;
try {
responses = EntityQuery.use(delegator).from("SurveyResponse").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (responses == null) {
responses = new ArrayList<>();
}
return responses;
}
// ================= Order Adjustments =================
public static BigDecimal calcOrderAdjustments(List<GenericValue> orderHeaderAdjustments, BigDecimal subTotal, boolean includeOther, boolean includeTax, boolean includeShipping) {
BigDecimal adjTotal = ZERO;
if (UtilValidate.isNotEmpty(orderHeaderAdjustments)) {
List<GenericValue> filteredAdjs = filterOrderAdjustments(orderHeaderAdjustments, includeOther, includeTax, includeShipping, false, false);
for (GenericValue orderAdjustment : filteredAdjs) {
adjTotal = adjTotal.add(OrderReadHelper.calcOrderAdjustment(orderAdjustment, subTotal)).setScale(scale, rounding);
}
}
return adjTotal.setScale(scale, rounding);
}
public static BigDecimal calcOrderAdjustment(GenericValue orderAdjustment, BigDecimal orderSubTotal) {
BigDecimal adjustment = ZERO;
if (orderAdjustment.get("amount") != null) {
BigDecimal amount = orderAdjustment.getBigDecimal("amount");
adjustment = adjustment.add(amount);
} else if (orderAdjustment.get("sourcePercentage") != null) {
BigDecimal percent = orderAdjustment.getBigDecimal("sourcePercentage");
BigDecimal amount = orderSubTotal.multiply(percent).multiply(percentage);
adjustment = adjustment.add(amount);
}
if ("SALES_TAX".equals(orderAdjustment.get("orderAdjustmentTypeId"))) {
return adjustment.setScale(taxCalcScale, taxRounding);
}
return adjustment.setScale(scale, rounding);
}
// ================= Order Item Adjustments =================
public static BigDecimal getOrderItemsSubTotal(List<GenericValue> orderItems, List<GenericValue> adjustments) {
return getOrderItemsSubTotal(orderItems, adjustments, null);
}
public static BigDecimal getOrderItemsSubTotal(List<GenericValue> orderItems, List<GenericValue> adjustments, List<GenericValue> workEfforts) {
BigDecimal result = ZERO;
Iterator<GenericValue> itemIter = UtilMisc.toIterator(orderItems);
while (itemIter != null && itemIter.hasNext()) {
GenericValue orderItem = itemIter.next();
BigDecimal itemTotal = getOrderItemSubTotal(orderItem, adjustments);
if (workEfforts != null && orderItem.getString("orderItemTypeId").compareTo("RENTAL_ORDER_ITEM") == 0) {
Iterator<GenericValue> weIter = UtilMisc.toIterator(workEfforts);
while (weIter != null && weIter.hasNext()) {
GenericValue workEffort = weIter.next();
if (workEffort.getString("workEffortId").compareTo(orderItem.getString("orderItemSeqId")) == 0) {
itemTotal = itemTotal.multiply(getWorkEffortRentalQuantity(workEffort)).setScale(scale, rounding);
break;
}
}
}
result = result.add(itemTotal).setScale(scale, rounding);
}
return result.setScale(scale, rounding);
}
/** The passed adjustments can be all adjustments for the order, ie for all line items */
public static BigDecimal getOrderItemSubTotal(GenericValue orderItem, List<GenericValue> adjustments) {
return getOrderItemSubTotal(orderItem, adjustments, false, false);
}
/** The passed adjustments can be all adjustments for the order, ie for all line items */
public static BigDecimal getOrderItemSubTotal(GenericValue orderItem, List<GenericValue> adjustments, boolean forTax, boolean forShipping) {
BigDecimal unitPrice = orderItem.getBigDecimal("unitPrice");
BigDecimal quantity = getOrderItemQuantity(orderItem);
BigDecimal result = ZERO;
if (unitPrice == null || quantity == null) {
Debug.logWarning("[getOrderItemTotal] unitPrice or quantity are null, using 0 for the item base price", module);
} else {
if (Debug.verboseOn()) {
Debug.logVerbose("Unit Price : " + unitPrice + " / " + "Quantity : " + quantity, module);
}
result = unitPrice.multiply(quantity);
if ("RENTAL_ORDER_ITEM".equals(orderItem.getString("orderItemTypeId"))) {
// retrieve related work effort when required.
List<GenericValue> workOrderItemFulfillments = null;
try {
workOrderItemFulfillments = orderItem.getDelegator().findByAnd("WorkOrderItemFulfillment", UtilMisc.toMap("orderId", orderItem.getString("orderId"), "orderItemSeqId", orderItem.getString("orderItemSeqId")), null, true);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (workOrderItemFulfillments != null) {
Iterator<GenericValue> iter = workOrderItemFulfillments.iterator();
if (iter.hasNext()) {
GenericValue WorkOrderItemFulfillment = iter.next();
GenericValue workEffort = null;
try {
workEffort = WorkOrderItemFulfillment.getRelatedOne("WorkEffort", true);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
result = result.multiply(getWorkEffortRentalQuantity(workEffort));
}
}
}
}
// subtotal also includes non tax and shipping adjustments; tax and shipping will be calculated using this adjusted value
result = result.add(getOrderItemAdjustmentsTotal(orderItem, adjustments, true, false, false, forTax, forShipping));
return result.setScale(scale, rounding);
}
public static BigDecimal getOrderItemsTotal(List<GenericValue> orderItems, List<GenericValue> adjustments) {
BigDecimal result = ZERO;
Iterator<GenericValue> itemIter = UtilMisc.toIterator(orderItems);
while (itemIter != null && itemIter.hasNext()) {
result = result.add(getOrderItemTotal(itemIter.next(), adjustments));
}
return result.setScale(scale, rounding);
}
public static BigDecimal getOrderItemTotal(GenericValue orderItem, List<GenericValue> adjustments) {
// add tax and shipping to subtotal
return getOrderItemSubTotal(orderItem, adjustments).add(getOrderItemAdjustmentsTotal(orderItem, adjustments, false, true, true));
}
public static BigDecimal calcOrderPromoAdjustmentsBd(List<GenericValue> allOrderAdjustments) {
BigDecimal promoAdjTotal = ZERO;
List<GenericValue> promoAdjustments = EntityUtil.filterByAnd(allOrderAdjustments, UtilMisc.toMap("orderAdjustmentTypeId", "PROMOTION_ADJUSTMENT"));
if (UtilValidate.isNotEmpty(promoAdjustments)) {
Iterator<GenericValue> promoAdjIter = promoAdjustments.iterator();
while (promoAdjIter.hasNext()) {
GenericValue promoAdjustment = promoAdjIter.next();
if (promoAdjustment != null) {
BigDecimal amount = promoAdjustment.getBigDecimal("amount").setScale(taxCalcScale, taxRounding);
promoAdjTotal = promoAdjTotal.add(amount);
}
}
}
return promoAdjTotal.setScale(scale, rounding);
}
public static BigDecimal getWorkEffortRentalLength(GenericValue workEffort) {
BigDecimal length = null;
if (workEffort.get("estimatedStartDate") != null && workEffort.get("estimatedCompletionDate") != null) {
length = new BigDecimal(UtilDateTime.getInterval(workEffort.getTimestamp("estimatedStartDate"), workEffort.getTimestamp("estimatedCompletionDate")) / 86400000);
}
return length;
}
public static BigDecimal getWorkEffortRentalQuantity(GenericValue workEffort) {
BigDecimal persons = BigDecimal.ONE;
if (workEffort.get("reservPersons") != null) {
persons = workEffort.getBigDecimal("reservPersons");
}
BigDecimal secondPersonPerc = ZERO;
if (workEffort.get("reserv2ndPPPerc") != null) {
secondPersonPerc = workEffort.getBigDecimal("reserv2ndPPPerc");
}
BigDecimal nthPersonPerc = ZERO;
if (workEffort.get("reservNthPPPerc") != null) {
nthPersonPerc = workEffort.getBigDecimal("reservNthPPPerc");
}
long length = 1;
if (workEffort.get("estimatedStartDate") != null && workEffort.get("estimatedCompletionDate") != null) {
length = (workEffort.getTimestamp("estimatedCompletionDate").getTime() - workEffort.getTimestamp("estimatedStartDate").getTime()) / 86400000;
}
BigDecimal rentalAdjustment = ZERO;
if (persons.compareTo(BigDecimal.ONE) == 1) {
if (persons.compareTo(new BigDecimal(2)) == 1) {
persons = persons.subtract(new BigDecimal(2));
if (nthPersonPerc.signum() == 1) {
rentalAdjustment = persons.multiply(nthPersonPerc);
} else {
rentalAdjustment = persons.multiply(secondPersonPerc);
}
persons = new BigDecimal("2");
}
if (persons.compareTo(new BigDecimal("2")) == 0) {
rentalAdjustment = rentalAdjustment.add(secondPersonPerc);
}
}
rentalAdjustment = rentalAdjustment.add(new BigDecimal(100)); // add final 100 percent for first person
rentalAdjustment = rentalAdjustment.divide(new BigDecimal(100), scale, rounding).multiply(new BigDecimal(String.valueOf(length)));
return rentalAdjustment; // return total rental adjustment
}
public static BigDecimal getAllOrderItemsAdjustmentsTotal(List<GenericValue> orderItems, List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping) {
BigDecimal result = ZERO;
Iterator<GenericValue> itemIter = UtilMisc.toIterator(orderItems);
while (itemIter != null && itemIter.hasNext()) {
result = result.add(getOrderItemAdjustmentsTotal(itemIter.next(), adjustments, includeOther, includeTax, includeShipping));
}
return result.setScale(scale, rounding);
}
/** The passed adjustments can be all adjustments for the order, ie for all line items */
public static BigDecimal getOrderItemAdjustmentsTotal(GenericValue orderItem, List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping) {
return getOrderItemAdjustmentsTotal(orderItem, adjustments, includeOther, includeTax, includeShipping, false, false);
}
/** The passed adjustments can be all adjustments for the order, ie for all line items */
public static BigDecimal getOrderItemAdjustmentsTotal(GenericValue orderItem, List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
return calcItemAdjustments(getOrderItemQuantity(orderItem), orderItem.getBigDecimal("unitPrice"),
getOrderItemAdjustmentList(orderItem, adjustments),
includeOther, includeTax, includeShipping, forTax, forShipping);
}
public static List<GenericValue> getOrderItemAdjustmentList(GenericValue orderItem, List<GenericValue> adjustments) {
return EntityUtil.filterByAnd(adjustments, UtilMisc.toMap("orderItemSeqId", orderItem.get("orderItemSeqId")));
}
public static List<GenericValue> getOrderItemStatuses(GenericValue orderItem, List<GenericValue> orderStatuses) {
List<EntityExpr> contraints1 = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItem.get("orderItemSeqId")));
List<EntityExpr> contraints2 = UtilMisc.toList(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.EQUALS, null));
contraints2.add(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.EQUALS, DataModelConstants.SEQ_ID_NA));
contraints2.add(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.EQUALS, ""));
List<GenericValue> newOrderStatuses = new ArrayList<>();
newOrderStatuses.addAll(EntityUtil.filterByAnd(orderStatuses, contraints1));
return EntityUtil.orderBy(EntityUtil.filterByOr(newOrderStatuses, contraints2), UtilMisc.toList("-statusDatetime"));
}
// Order Item Adjs Utility Methods
public static BigDecimal calcItemAdjustments(BigDecimal quantity, BigDecimal unitPrice, List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
BigDecimal adjTotal = ZERO;
if (UtilValidate.isNotEmpty(adjustments)) {
List<GenericValue> filteredAdjs = filterOrderAdjustments(adjustments, includeOther, includeTax, includeShipping, forTax, forShipping);
for (GenericValue orderAdjustment : filteredAdjs) {
adjTotal = adjTotal.add(OrderReadHelper.calcItemAdjustment(orderAdjustment, quantity, unitPrice));
}
}
return adjTotal;
}
public static BigDecimal calcItemAdjustmentsRecurringBd(BigDecimal quantity, BigDecimal unitPrice, List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
BigDecimal adjTotal = ZERO;
if (UtilValidate.isNotEmpty(adjustments)) {
List<GenericValue> filteredAdjs = filterOrderAdjustments(adjustments, includeOther, includeTax, includeShipping, forTax, forShipping);
for (GenericValue orderAdjustment : filteredAdjs) {
adjTotal = adjTotal.add(OrderReadHelper.calcItemAdjustmentRecurringBd(orderAdjustment, quantity, unitPrice)).setScale(scale, rounding);
}
}
return adjTotal;
}
public static BigDecimal calcItemAdjustment(GenericValue itemAdjustment, GenericValue item) {
return calcItemAdjustment(itemAdjustment, getOrderItemQuantity(item), item.getBigDecimal("unitPrice"));
}
public static BigDecimal calcItemAdjustment(GenericValue itemAdjustment, BigDecimal quantity, BigDecimal unitPrice) {
BigDecimal adjustment = ZERO;
if (itemAdjustment.get("amount") != null) {
// shouldn't round amounts here, wait until item total is added up otherwise incremental errors are introduced, and there is code that calls this method that does that already:
//adjustment = adjustment.add(setScaleByType("SALES_TAX".equals(itemAdjustment.get("orderAdjustmentTypeId")), itemAdjustment.getBigDecimal("amount")));
adjustment = adjustment.add(itemAdjustment.getBigDecimal("amount"));
} else if (itemAdjustment.get("sourcePercentage") != null) {
// see comment above about rounding:
//adjustment = adjustment.add(setScaleByType("SALES_TAX".equals(itemAdjustment.get("orderAdjustmentTypeId")), itemAdjustment.getBigDecimal("sourcePercentage").multiply(quantity).multiply(unitPrice).multiply(percentage)));
adjustment = adjustment.add(itemAdjustment.getBigDecimal("sourcePercentage").multiply(quantity).multiply(unitPrice).multiply(percentage));
}
if (Debug.verboseOn()) {
Debug.logVerbose("calcItemAdjustment: " + itemAdjustment + ", quantity=" + quantity + ", unitPrice=" + unitPrice + ", adjustment=" + adjustment, module);
}
return adjustment;
}
public static BigDecimal calcItemAdjustmentRecurringBd(GenericValue itemAdjustment, BigDecimal quantity, BigDecimal unitPrice) {
BigDecimal adjustmentRecurring = ZERO;
if (itemAdjustment.get("recurringAmount") != null) {
adjustmentRecurring = adjustmentRecurring.add(setScaleByType("SALES_TAX".equals(itemAdjustment.get("orderAdjustmentTypeId")), itemAdjustment.getBigDecimal("recurringAmount")));
}
if (Debug.verboseOn()) {
Debug.logVerbose("calcItemAdjustmentRecurring: " + itemAdjustment + ", quantity=" + quantity + ", unitPrice=" + unitPrice + ", adjustmentRecurring=" + adjustmentRecurring, module);
}
return adjustmentRecurring.setScale(scale, rounding);
}
public static List<GenericValue> filterOrderAdjustments(List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) {
List<GenericValue> newOrderAdjustmentsList = new ArrayList<>();
if (UtilValidate.isNotEmpty(adjustments)) {
for (GenericValue orderAdjustment : adjustments) {
boolean includeAdjustment = false;
if ("SALES_TAX".equals(orderAdjustment.getString("orderAdjustmentTypeId")) ||
"VAT_TAX".equals(orderAdjustment.getString("orderAdjustmentTypeId")) ||
"VAT_PRICE_CORRECT".equals(orderAdjustment.getString("orderAdjustmentTypeId"))) {
if (includeTax) {
includeAdjustment = true;
}
} else if ("SHIPPING_CHARGES".equals(orderAdjustment.getString("orderAdjustmentTypeId"))) {
if (includeShipping) {
includeAdjustment = true;
}
} else {
if (includeOther) {
includeAdjustment = true;
}
}
// default to yes, include for shipping; so only exclude if includeInShipping is N, or false; if Y or null or anything else it will be included
if (forTax && "N".equals(orderAdjustment.getString("includeInTax"))) {
includeAdjustment = false;
}
// default to yes, include for shipping; so only exclude if includeInShipping is N, or false; if Y or null or anything else it will be included
if (forShipping && "N".equals(orderAdjustment.getString("includeInShipping"))) {
includeAdjustment = false;
}
if (includeAdjustment) {
newOrderAdjustmentsList.add(orderAdjustment);
}
}
}
return newOrderAdjustmentsList;
}
public static BigDecimal getQuantityOnOrder(Delegator delegator, String productId) {
BigDecimal quantity = BigDecimal.ZERO;
// first find all open purchase orders
List<GenericValue> openOrders = null;
try {
openOrders = EntityQuery.use(delegator).from("OrderHeaderAndItems")
.where(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "PURCHASE_ORDER"),
EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_CANCELLED"),
EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED"),
EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_COMPLETED"),
EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId))
.queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (UtilValidate.isNotEmpty(openOrders)) {
for (GenericValue order : openOrders) {
BigDecimal thisQty = order.getBigDecimal("quantity");
if (thisQty == null) {
thisQty = BigDecimal.ZERO;
}
quantity = quantity.add(thisQty);
}
}
return quantity;
}
/**
* Checks to see if this user has read permission on the specified order
* @param userLogin The UserLogin value object to check
* @param orderHeader The OrderHeader for the specified order
* @return boolean True if we have read permission
*/
public static boolean hasPermission(Security security, GenericValue userLogin, GenericValue orderHeader) {
if (userLogin == null || orderHeader == null) {
return false;
}
if (security.hasEntityPermission("ORDERMGR", "_VIEW", userLogin)) {
return true;
} else if (security.hasEntityPermission("ORDERMGR", "_ROLEVIEW", userLogin)) {
List<GenericValue> orderRoles = null;
try {
orderRoles = orderHeader.getRelated("OrderRole", UtilMisc.toMap("partyId", userLogin.getString("partyId")), null, false);
} catch (GenericEntityException e) {
Debug.logError(e, "Cannot get OrderRole from OrderHeader", module);
}
if (UtilValidate.isNotEmpty(orderRoles)) {
// we are in at least one role
return true;
}
}
return false;
}
public static OrderReadHelper getHelper(GenericValue orderHeader) {
return new OrderReadHelper(orderHeader);
}
/**
* Get orderAdjustments that have no corresponding returnAdjustment
* @return return the order adjustments that have no corresponding with return adjustment
*/
public List<GenericValue> getAvailableOrderHeaderAdjustments() {
List<GenericValue> orderHeaderAdjustments = this.getOrderHeaderAdjustments();
List<GenericValue> filteredAdjustments = new ArrayList<>();
for (GenericValue orderAdjustment : orderHeaderAdjustments) {
long count = 0;
try {
count = orderHeader.getDelegator().findCountByCondition("ReturnAdjustment",
EntityCondition.makeCondition("orderAdjustmentId", EntityOperator.EQUALS, orderAdjustment.get("orderAdjustmentId")), null, null);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (count == 0) {
filteredAdjustments.add(orderAdjustment);
}
}
return filteredAdjustments;
}
/**
* Get the total return adjustments for a set of key -> value condition pairs. Done for code efficiency.
* @param delegator the delegator
* @param condition a map of the conditions to use
* @return Get the total return adjustments
*/
public static BigDecimal getReturnAdjustmentTotal(Delegator delegator, Map<String, Object> condition) {
BigDecimal total = ZERO;
List<GenericValue> adjustments;
try {
// TODO: find on a view-entity with a sum is probably more efficient
adjustments = EntityQuery.use(delegator).from("ReturnAdjustment").where(condition).queryList();
if (adjustments != null) {
for (GenericValue returnAdjustment : adjustments) {
total = total.add(setScaleByType("RET_SALES_TAX_ADJ".equals(returnAdjustment.get("returnAdjustmentTypeId")), returnAdjustment.getBigDecimal("amount")));
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return total;
}
// little helper method to set the scale according to tax type
public static BigDecimal setScaleByType(boolean isTax, BigDecimal value) {
return isTax ? value.setScale(taxCalcScale, taxRounding) : value.setScale(scale, rounding);
}
/** Get the quantity of order items that have been invoiced */
public static BigDecimal getOrderItemInvoicedQuantity(GenericValue orderItem) {
BigDecimal invoiced = BigDecimal.ZERO;
try {
// this is simply the sum of quantity billed in all related OrderItemBillings
List<GenericValue> billings = orderItem.getRelated("OrderItemBilling", null, null, false);
for (GenericValue billing : billings) {
BigDecimal quantity = billing.getBigDecimal("quantity");
if (quantity != null) {
invoiced = invoiced.add(quantity);
}
}
} catch (GenericEntityException e) {
Debug.logError(e, e.getMessage(), module);
}
return invoiced;
}
public List<GenericValue> getOrderPaymentStatuses() {
return getOrderPaymentStatuses(getOrderStatuses());
}
public static List<GenericValue> getOrderPaymentStatuses(List<GenericValue> orderStatuses) {
List<EntityExpr> contraints1 = UtilMisc.toList(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, null));
contraints1.add(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, DataModelConstants.SEQ_ID_NA));
contraints1.add(EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, ""));
List<EntityExpr> contraints2 = UtilMisc.toList(EntityCondition.makeCondition("orderPaymentPreferenceId", EntityOperator.NOT_EQUAL, null));
List<GenericValue> newOrderStatuses = new ArrayList<>();
newOrderStatuses.addAll(EntityUtil.filterByOr(orderStatuses, contraints1));
return EntityUtil.orderBy(EntityUtil.filterByAnd(newOrderStatuses, contraints2), UtilMisc.toList("-statusDatetime"));
}
public static String getOrderItemAttribute(GenericValue orderItem, String attributeName) {
String attributeValue = null;
if (orderItem != null) {
try {
GenericValue orderItemAttribute = EntityUtil.getFirst(orderItem.getRelated("OrderItemAttribute", UtilMisc.toMap("attrName", attributeName), null, false));
if (orderItemAttribute != null) {
attributeValue = orderItemAttribute.getString("attrValue");
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
return attributeValue;
}
public String getOrderAttribute(String attributeName) {
String attributeValue = null;
if (orderHeader != null) {
try {
GenericValue orderAttribute = EntityUtil.getFirst(orderHeader.getRelated("OrderAttribute", UtilMisc.toMap("attrName", attributeName), null, false));
if (orderAttribute != null) {
attributeValue = orderAttribute.getString("attrValue");
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
return attributeValue;
}
/** SCIPIO: generalized the tax calculation */
public static Map<String, Object> getCommonOrderTaxByTaxAuthGeoAndParty(List<GenericValue> orderAdjustmentsOriginal) {
BigDecimal taxGrandTotal = BigDecimal.ZERO;
List<Map<String, Object>> taxByTaxAuthGeoAndPartyList = new ArrayList<>();
List<GenericValue> orderAdjustmentsToUse = new ArrayList<>();
if (UtilValidate.isNotEmpty(orderAdjustmentsOriginal)) {
orderAdjustmentsToUse.addAll(orderAdjustmentsOriginal);
// get orderAdjustment where orderAdjustmentTypeId is SALES_TAX.
orderAdjustmentsToUse = EntityUtil.orderBy(orderAdjustmentsToUse, UtilMisc.toList("taxAuthGeoId", "taxAuthPartyId"));
// get the list of all distinct taxAuthGeoId and taxAuthPartyId. It is for getting the number of taxAuthGeo and taxAuthPartyId in adjustments.
List<String> distinctTaxAuthGeoIdList = EntityUtil.getFieldListFromEntityList(orderAdjustmentsToUse, "taxAuthGeoId", true);
List<String> distinctTaxAuthPartyIdList = EntityUtil.getFieldListFromEntityList(orderAdjustmentsToUse, "taxAuthPartyId", true);
// Keep a list of amount that have been added to make sure none are missed (if taxAuth* information is missing)
List<GenericValue> processedAdjustments = new ArrayList<>();
// For each taxAuthGeoId get and add amount from orderAdjustment
for (String taxAuthGeoId : distinctTaxAuthGeoIdList) {
for (String taxAuthPartyId : distinctTaxAuthPartyIdList) {
// get all records for orderAdjustments filtered by taxAuthGeoId and taxAuthPartyId
List<GenericValue> orderAdjByTaxAuthGeoAndPartyIds = EntityUtil.filterByAnd(orderAdjustmentsToUse, UtilMisc.toMap("taxAuthGeoId", taxAuthGeoId, "taxAuthPartyId", taxAuthPartyId));
if (UtilValidate.isNotEmpty(orderAdjByTaxAuthGeoAndPartyIds)) {
BigDecimal totalAmount = BigDecimal.ZERO;
// Now for each orderAdjustment record get and add amount.
for (GenericValue orderAdjustment : orderAdjByTaxAuthGeoAndPartyIds) {
BigDecimal amount = orderAdjustment.getBigDecimal("amount");
if (amount != null) {
totalAmount = totalAmount.add(amount);
}
if ("VAT_TAX".equals(orderAdjustment.getString("orderAdjustmentTypeId")) &&
orderAdjustment.get("amountAlreadyIncluded") != null) {
// this is the only case where the VAT_TAX amountAlreadyIncluded should be added in, and should just be for display and not to calculate the order grandTotal
totalAmount = totalAmount.add(orderAdjustment.getBigDecimal("amountAlreadyIncluded"));
}
totalAmount = totalAmount.setScale(taxCalcScale, taxRounding);
processedAdjustments.add(orderAdjustment);
}
totalAmount = totalAmount.setScale(taxFinalScale, taxRounding);
taxByTaxAuthGeoAndPartyList.add(UtilMisc.<String, Object>toMap("taxAuthPartyId", taxAuthPartyId, "taxAuthGeoId", taxAuthGeoId, "totalAmount", totalAmount));
taxGrandTotal = taxGrandTotal.add(totalAmount);
}
}
}
// Process any adjustments that got missed
List<GenericValue> missedAdjustments = new ArrayList<>();
missedAdjustments.addAll(orderAdjustmentsToUse);
missedAdjustments.removeAll(processedAdjustments);
for (GenericValue orderAdjustment : missedAdjustments) {
taxGrandTotal = taxGrandTotal.add(orderAdjustment.getBigDecimal("amount").setScale(taxCalcScale, taxRounding));
}
taxGrandTotal = taxGrandTotal.setScale(taxFinalScale, taxRounding);
}
Map<String, Object> result = new HashMap<>();
result.put("taxByTaxAuthGeoAndPartyList", taxByTaxAuthGeoAndPartyList);
result.put("taxGrandTotal", taxGrandTotal);
return result;
}
public static Map<String, Object> getOrderSalesTaxByTaxAuthGeoAndParty(List<GenericValue> orderAdjustments) {
orderAdjustments = EntityUtil.filterByAnd(orderAdjustments, UtilMisc.toMap("orderAdjustmentTypeId", "SALES_TAX"));
return getCommonOrderTaxByTaxAuthGeoAndParty(orderAdjustments);
}
/** SCIPIO: Added VAT calculation */
public static Map<String, Object> getOrderVATTaxByTaxAuthGeoAndParty(List<GenericValue> orderAdjustments) {
orderAdjustments = EntityUtil.filterByAnd(orderAdjustments, UtilMisc.toMap("orderAdjustmentTypeId", "VAT_TAX"));
return getCommonOrderTaxByTaxAuthGeoAndParty(orderAdjustments);
}
public static Map<String, Object> getOrderTaxByTaxAuthGeoAndParty(List<GenericValue> orderAdjustments) {
orderAdjustments = EntityUtil.filterByAnd(orderAdjustments, UtilMisc.toMap("orderAdjustmentTypeId", "SALES_TAX"));
return getCommonOrderTaxByTaxAuthGeoAndParty(orderAdjustments);
}
public static Map<String, Object> getOrderTaxByTaxAuthGeoAndPartyForDisplay(List<GenericValue> orderAdjustmentsOriginal) {
orderAdjustmentsOriginal.addAll(EntityUtil.filterByAnd(orderAdjustmentsOriginal, UtilMisc.toMap("orderAdjustmentTypeId", "SALES_TAX")));
orderAdjustmentsOriginal.addAll(EntityUtil.filterByAnd(orderAdjustmentsOriginal, UtilMisc.toMap("orderAdjustmentTypeId", "VAT_TAX")));
return getCommonOrderTaxByTaxAuthGeoAndParty(orderAdjustmentsOriginal);
}
public static Map<String, Object> getOrderItemTaxByTaxAuthGeoAndPartyForDisplay(GenericValue orderItem, List<GenericValue> orderAdjustmentsOriginal) {
return getOrderTaxByTaxAuthGeoAndPartyForDisplay(getOrderItemAdjustmentList(orderItem, orderAdjustmentsOriginal));
}
public BigDecimal getTotalTax(List<GenericValue> taxAdjustments) {
Map<String, Object> taxByAuthority = OrderReadHelper.getOrderTaxByTaxAuthGeoAndParty(taxAdjustments);
BigDecimal taxTotal = (BigDecimal) taxByAuthority.get("taxGrandTotal");
return taxTotal;
}
/** SCIPIO: Added VAT Tax calculation */
public BigDecimal getTotalVATTax(List<GenericValue> taxAdjustments) {
Map<String, Object> taxByAuthority = OrderReadHelper.getOrderVATTaxByTaxAuthGeoAndParty(taxAdjustments);
BigDecimal taxTotal = (BigDecimal) taxByAuthority.get("taxGrandTotal");
return taxTotal;
}
/**
* Calculates the "available" balance of a billing account, which is the
* net balance minus amount of pending (not cancelled, rejected, or received) order payments.
* When looking at using a billing account for a new order, you should use this method.
* @param billingAccount the billing account record
* @return return the "available" balance of a billing account
* @throws GenericEntityException
*/
public static BigDecimal getBillingAccountBalance(GenericValue billingAccount) throws GenericEntityException {
Delegator delegator = billingAccount.getDelegator();
String billingAccountId = billingAccount.getString("billingAccountId");
BigDecimal balance = ZERO;
BigDecimal accountLimit = getAccountLimit(billingAccount);
balance = balance.add(accountLimit);
// pending (not cancelled, rejected, or received) order payments
List<GenericValue> orderPaymentPreferenceSums = EntityQuery.use(delegator)
.select("maxAmount")
.from("OrderPurchasePaymentSummary")
.where(EntityCondition.makeCondition("billingAccountId", EntityOperator.EQUALS, billingAccountId),
EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "EXT_BILLACT"),
EntityCondition.makeCondition("statusId", EntityOperator.NOT_IN, UtilMisc.toList("ORDER_CANCELLED", "ORDER_REJECTED")),
EntityCondition.makeCondition("preferenceStatusId", EntityOperator.NOT_IN, UtilMisc.toList("PAYMENT_SETTLED", "PAYMENT_RECEIVED", "PAYMENT_DECLINED", "PAYMENT_CANCELLED"))) // PAYMENT_NOT_AUTH
.queryList();
for (GenericValue orderPaymentPreferenceSum : orderPaymentPreferenceSums) {
BigDecimal maxAmount = orderPaymentPreferenceSum.getBigDecimal("maxAmount");
balance = maxAmount != null ? balance.subtract(maxAmount) : balance;
}
List<GenericValue> paymentAppls = EntityQuery.use(delegator).from("PaymentApplication").where("billingAccountId", billingAccountId).queryList();
// TODO: cancelled payments?
for (GenericValue paymentAppl : paymentAppls) {
if (paymentAppl.getString("invoiceId") == null) {
BigDecimal amountApplied = paymentAppl.getBigDecimal("amountApplied");
balance = balance.add(amountApplied);
}
}
balance = balance.setScale(scale, rounding);
return balance;
}
/**
* Returns the accountLimit of the BillingAccount or BigDecimal ZERO if it is null
* @param billingAccount
* @throws GenericEntityException
*/
public static BigDecimal getAccountLimit(GenericValue billingAccount) throws GenericEntityException {
if (billingAccount.getBigDecimal("accountLimit") != null) {
return billingAccount.getBigDecimal("accountLimit");
}
Debug.logWarning("Billing Account [" + billingAccount.getString("billingAccountId") + "] does not have an account limit defined, assuming zero.", module);
return ZERO;
}
public List<BigDecimal> getShippableSizes(String shipGrouSeqId) {
List<BigDecimal> shippableSizes = new ArrayList<>();
List<GenericValue> validItems = getValidOrderItems(shipGrouSeqId);
if (validItems != null) {
Iterator<GenericValue> i = validItems.iterator();
while (i.hasNext()) {
GenericValue item = i.next();
shippableSizes.add(this.getItemSize(item));
}
}
return shippableSizes;
}
public BigDecimal getItemReceivedQuantity(GenericValue orderItem) {
BigDecimal totalReceived = BigDecimal.ZERO;
try {
if (orderItem != null) {
EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(
EntityCondition.makeCondition("orderId", orderItem.getString("orderId")),
EntityCondition.makeCondition("quantityAccepted", EntityOperator.GREATER_THAN, BigDecimal.ZERO),
EntityCondition.makeCondition("orderItemSeqId", orderItem.getString("orderItemSeqId"))));
Delegator delegator = orderItem.getDelegator();
List<GenericValue> shipmentReceipts = EntityQuery.use(delegator).select("quantityAccepted", "quantityRejected").from("ShipmentReceiptAndItem").where(cond).queryList();
for (GenericValue shipmentReceipt : shipmentReceipts) {
if (shipmentReceipt.getBigDecimal("quantityAccepted") != null) {
totalReceived = totalReceived.add(shipmentReceipt.getBigDecimal("quantityAccepted"));
}
if (shipmentReceipt.getBigDecimal("quantityRejected") != null) {
totalReceived = totalReceived.add(shipmentReceipt.getBigDecimal("quantityRejected"));
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return totalReceived;
}
// ================= Order Subscriptions (SCIPIO) =================
/**
* SCIPIO: Retrieve all subscription of the entire order
*/
public Map<GenericValue, List<GenericValue>> getItemSubscriptions() throws GenericEntityException {
if (orderItems == null) {
getValidOrderItems();
}
if (orderItems != null) {
for (GenericValue orderItem : orderItems) {
List<GenericValue> productSubscriptions = getItemSubscriptions(orderItem);
for (GenericValue productSubscription : productSubscriptions) {
Debug.log("Found orderItem [" + orderItem.getString("orderItemSeqId") + "#" + orderItem.getString("productId") + "] with subscription id ["
+ productSubscription.getString("subscriptionResourceId") + "]");
}
}
return this.orderSubscriptionItems;
}
return null;
}
/**
* SCIPIO: Retrieve all subscriptions associated to an orderItem
*/
public List<GenericValue> getItemSubscriptions(GenericValue orderItem) throws GenericEntityException {
Delegator delegator = orderItem.getDelegator();
if (this.orderSubscriptionItems == null) {
this.orderSubscriptionItems = new HashMap<>();
}
List<GenericValue> productSubscriptionResources = EntityQuery.use(delegator).from("ProductSubscriptionResource")
.where("productId", orderItem.getString("productId")).cache(true).filterByDate().queryList();
if (UtilValidate.isNotEmpty(productSubscriptionResources)) {
this.orderSubscriptionItems.put(orderItem, productSubscriptionResources);
}
return productSubscriptionResources;
}
/**
* SCIPIO: Checks if any order item has an underlying subscription/s bound to it.
*/
public boolean hasSubscriptions() {
return UtilValidate.isNotEmpty(this.orderSubscriptionItems);
}
/**
* SCIPIO: Checks if an order item has an underlying subscription/s bound to it.
*/
public boolean hasSubscriptions(GenericValue orderItem) {
return UtilValidate.isNotEmpty(this.orderSubscriptionItems) && this.orderSubscriptionItems.containsKey(orderItem);
}
/**
* SCIPIO: Check if the order contains only subscription items
*/
public boolean orderContainsSubscriptionItemsOnly() {
if (orderItems != null && orderSubscriptionItems != null) {
for (GenericValue orderItem : orderItems) {
if (!orderSubscriptionItems.containsKey(orderItem)) {
return false;
}
}
return true;
}
return false;
}
public BigDecimal getSubscriptionItemsSubTotal() {
BigDecimal subscriptionItemsSubTotal = BigDecimal.ZERO;
if (UtilValidate.isNotEmpty(orderSubscriptionItems)) {
List<GenericValue> subscriptionItems = new ArrayList<>(orderSubscriptionItems.keySet());
subscriptionItemsSubTotal = getOrderItemsSubTotal(subscriptionItems, getAdjustments());
}
return subscriptionItemsSubTotal;
}
public BigDecimal getSubscriptionItemSubTotal(GenericValue orderItem) {
return getOrderItemSubTotal(orderItem, getAdjustments());
}
public BigDecimal getSubscriptionItemsTotal() {
BigDecimal subscriptionItemsTotal = BigDecimal.ZERO;
if (UtilValidate.isNotEmpty(orderSubscriptionItems)) {
List<GenericValue> subscriptionItems = new ArrayList<>(orderSubscriptionItems.keySet());
subscriptionItemsTotal = getOrderItemsTotal(subscriptionItems, getAdjustments());
}
return subscriptionItemsTotal;
}
public BigDecimal getSubscriptionItemTotal(GenericValue orderItem) {
return getOrderItemTotal(orderItem, getAdjustments());
}
public BigDecimal getSubscriptionItemTax(GenericValue orderItem) {
return getOrderItemAdjustmentsTotal(orderItem, false, true, false);
}
/**
* SCIPIO: Returns the salesChannelEnumIds of the channels which can be considered "web" channels
* or in other words require a webSiteId to work properly.
*/
public static Set<String> getWebSiteSalesChannelIds(Delegator delegator) {
return webSiteSalesChannelIds;
}
public ProductConfigWrapper getProductConfigWrapperForOrderItem(GenericValue orderItem) { // SCIPIO
try {
GenericValue product = orderItem.getRelatedOne("Product");
if (ProductWorker.isConfigProductConfig(product)) {
String configurableProductId = ProductWorker.getInstanceAggregatedId(getDelegator(), product.getString("productId"));
if (configurableProductId != null) {
return ProductConfigWorker.loadProductConfigWrapper(getDelegator(), getDispatcher(), product.getString("configId"),
configurableProductId, getOrderHeader().getString("productStoreId"), orderItem.getString("prodCatalogId"),
getOrderHeader().getString("webSiteId"), getOrderHeader().getString("currencyUom"), locale, null);
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return null;
}
public ProductConfigWrapper getProductConfigWrapperForOrderItem(String orderItemSeqId) { // SCIPIO
GenericValue orderItem = getOrderItem(orderItemSeqId);
return (orderItem != null) ? getProductConfigWrapperForOrderItem(orderItem) : null;
}
public Map<String, ProductConfigWrapper> getProductConfigWrappersByOrderItemSeqId(Collection<GenericValue> orderItems) { // SCIPIO
Map<String, ProductConfigWrapper> pcwMap = new HashMap<>();
if (orderItems != null) {
for(GenericValue orderItem : orderItems) {
ProductConfigWrapper pcw = getProductConfigWrapperForOrderItem(orderItem);
if (pcw != null) {
pcwMap.put(orderItem.getString("orderItemSeqId"), pcw);
}
}
}
return pcwMap;
}
public Map<String, ProductConfigWrapper> getProductConfigWrappersByOrderItemSeqId() { // SCIPIO
return getProductConfigWrappersByOrderItemSeqId(getOrderItems());
}
public Map<String, ProductConfigWrapper> getProductConfigWrappersByProductId() { // SCIPIO
Map<String, ProductConfigWrapper> pcwMap = new HashMap<>();
if (orderItems != null) {
for(GenericValue orderItem : orderItems) {
String productId = orderItem.getString("productId");
if (pcwMap.get(productId) != null) {
continue;
}
ProductConfigWrapper pcw = getProductConfigWrapperForOrderItem(orderItem);
if (pcw != null) {
pcwMap.put(productId, pcw);
}
}
}
return pcwMap;
}
public Map<String, String> getOrderAdjustmentReturnItemTypeMap(String returnHeaderTypeId) { // SCIPIO
return getOrderAdjustmentReturnItemTypeMap(getDelegator(), returnHeaderTypeId);
}
public static Map<String, String> getOrderAdjustmentReturnItemTypeMap(Delegator delegator, String returnHeaderTypeId) { // SCIPIO
Map<String, String> typeMap = new HashMap<>();
try {
List<GenericValue> valueList = delegator.from("ReturnItemTypeMap").where("returnHeaderTypeId", returnHeaderTypeId).cache().queryList();
if (valueList != null) {
for (GenericValue value : valueList) {
typeMap.put(value.getString("returnItemMapKey"), value.getString("returnItemTypeId"));
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return typeMap;
}
/**
* SCIPIO: Returns the adjustments for the specified item from the returnableItems map returned by the getReturnableItems service using orderItemSeqId.
*/
public static List<GenericValue> getOrderItemAdjustmentsFromReturnableItems(Map<GenericValue, Map<String, Object>> returnableItems, String orderItemSeqId) {
Map<String, Object> info = getReturnableItemInfo(returnableItems, orderItemSeqId);
return (info != null) ? UtilGenerics.cast(info.get("adjustments")) : null;
}
/**
* SCIPIO: Keys into the returnableItems map returned by the getReturnableItems service using orderItemSeqId.
*/
public static Map<String, Object> getReturnableItemInfo(Map<GenericValue, Map<String, Object>> returnableItems, String orderItemSeqId) {
if (returnableItems == null || orderItemSeqId == null) {
return null;
}
for(Map.Entry<GenericValue, Map<String, Object>> entry : returnableItems.entrySet()) {
if ("OrderItem".equals(entry.getKey().getEntityName()) && orderItemSeqId.equals(entry.getKey().get("orderItemSeqId"))) {
return entry.getValue();
}
}
return null;
}
/**
* SCIPIO: returns a map of valuable order and return stats for a customer
*/
public Map<String, Object> getCustomerOrderMktgStats(List<String> orderIds, Boolean removeEmptyOrders, List<String>includedOrderItemStatusIds, List<String>excludedReturnItemStatusIds) {
Map<String,Object> resultMap = new HashMap<>();
Delegator delegator = getDelegator();
//Remove orders from list that are "replacements" or "empty"
if(removeEmptyOrders){
List<EntityCondition> exl = new ArrayList<>();
exl.add(EntityCondition.makeCondition("orderId", EntityOperator.IN, orderIds));
exl.add(EntityCondition.makeCondition("grandTotal", EntityOperator.EQUALS, BigDecimal.ZERO));
try{
List<GenericValue> negativeOrders = delegator.findList("OrderHeader", EntityCondition.makeCondition(exl, EntityOperator.AND),
UtilMisc.toSet("orderId"),
null,
null,
true);
for(GenericValue n : negativeOrders){
orderIds.remove(n.getString("orderId"));
}
}catch(Exception e){
Debug.logWarning("Could not fetch results from ",module);
}
}
Integer orderCount = orderIds.size();
Integer returnCount = 0;
BigDecimal orderItemValue = BigDecimal.ZERO;
BigDecimal returnItemValue = BigDecimal.ZERO;
BigDecimal orderItemCount = BigDecimal.ZERO;
BigDecimal returnItemCount = BigDecimal.ZERO;
int rfmRecency = 0;
DynamicViewEntity itemEntity = new DynamicViewEntity();
itemEntity.addMemberEntity("OI", "OrderItem");
itemEntity.addMemberEntity("OH", "OrderHeader");
itemEntity.addAlias("OI", "orderId", null, null, null, true, null);
itemEntity.addAlias("OI", "statusId", null, null, null, true, null);
itemEntity.addAlias("OH", "orderDate", null, null, null, true, null);
itemEntity.addAlias("OI", "orderItemCount", "quantity", null, null, false, "sum");
itemEntity.addAlias("OI", "orderItemValue", "unitPrice", null, null, false, "sum");
itemEntity.addViewLink("OI", "OH", Boolean.FALSE, ModelKeyMap.makeKeyMapList("orderId", "orderId"));
List<EntityCondition> exprListStatus = new ArrayList<>();
exprListStatus.add(EntityCondition.makeCondition("orderId", EntityOperator.IN, orderIds));
if(UtilValidate.isNotEmpty(includedOrderItemStatusIds)){
exprListStatus.add(EntityCondition.makeCondition("statusId", EntityOperator.IN, includedOrderItemStatusIds));
}
EntityCondition andCond = EntityCondition.makeCondition(exprListStatus, EntityOperator.AND);
EntityListIterator customerOrderStats;
try{
customerOrderStats = delegator.findListIteratorByCondition(itemEntity,andCond,null,null,UtilMisc.toList("-orderDate"),null);
Timestamp lastOrderDate;
if (customerOrderStats != null) {
int cIndex = 0;
List<GenericValue> orderStatsList = customerOrderStats.getCompleteList();
for(GenericValue n : orderStatsList){
if(cIndex==0){
lastOrderDate = n.getTimestamp("orderDate");
rfmRecency = Math.toIntExact( (System.currentTimeMillis() - lastOrderDate.getTime() )/ (1000 * 60 * 60 * 24));
}
BigDecimal nv = n.getBigDecimal("orderItemValue");
orderItemValue = orderItemValue.add(nv);
orderItemCount = orderItemCount.add(n.getBigDecimal("orderItemCount"));
cIndex+=1;
}
}
customerOrderStats.close();
}catch(Exception e){
Debug.logError("Error while fetching orderItems "+e.getMessage(),module);
}
DynamicViewEntity retEntity = new DynamicViewEntity();
retEntity.addMemberEntity("RI", "ReturnItem");
retEntity.addAlias("RI", "orderId", null, null, null, true, null);
retEntity.addAlias("RI", "returnId", null, null, null, true, null);
retEntity.addAlias("RI", "statusId", null, null, null, true, null);
retEntity.addAlias("RI", "returnTypeId", null, null, null, true, null);
retEntity.addAlias("RI", "returnItemCount", "returnQuantity", null, null, false, "sum");
retEntity.addAlias("RI", "returnItemValue", "returnPrice", null, null, false, "sum");
try{
List<EntityCondition> returnExpL = new ArrayList<>();
returnExpL.add(EntityCondition.makeCondition("orderId", EntityOperator.IN, orderIds));
if(UtilValidate.isNotEmpty(excludedReturnItemStatusIds))returnExpL.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_IN, excludedReturnItemStatusIds));
EntityListIterator returnStats = delegator.findListIteratorByCondition(retEntity,EntityCondition.makeCondition(returnExpL, EntityOperator.AND),null,null,null,null);
if (returnStats != null) {
List<GenericValue> returnStatsList = returnStats.getCompleteList();
returnCount = returnStatsList.size();
for(GenericValue n : returnStatsList){
BigDecimal nv = n.getBigDecimal("returnItemValue");
returnItemValue = returnItemValue.add(nv);
returnItemCount = returnItemCount.add(n.getBigDecimal("returnItemCount"));
}
}
returnStats.close();
}catch(Exception e){
Debug.logError("Error while fetching returnItems "+e.getMessage(),module);
}
resultMap.put("orderCount",orderCount);
resultMap.put("orderItemValue",orderItemValue);
resultMap.put("orderItemCount",orderItemCount.setScale(0,BigDecimal.ROUND_HALF_UP));
resultMap.put("returnCount",returnCount);
resultMap.put("returnItemValue",returnItemValue);
resultMap.put("returnItemCount",returnItemCount.setScale(0,BigDecimal.ROUND_HALF_UP));
if(BigDecimal.ZERO.compareTo(returnItemCount) == 0 || BigDecimal.ZERO.compareTo(orderItemCount) == 0){
resultMap.put("returnItemRatio",BigDecimal.ZERO);
}else{
resultMap.put("returnItemRatio",(returnItemCount.divide(orderItemCount,2,BigDecimal.ROUND_HALF_UP)));
}
//rfm values
resultMap.put("rfmRecency",rfmRecency);
Integer rfmFrequency = orderCount;
resultMap.put("rfmFrequency",rfmFrequency);
BigDecimal rfmMonetary = orderItemValue.subtract(returnItemValue);
resultMap.put("rfmMonetary",rfmMonetary);
int rfmRecencyScore = 0;
int rfmFrequencyScore = 0;
int rfmMonetaryScore = 0;
if(rfmRecency <= UtilProperties.getPropertyAsInteger("order","order.rfm.recency.1",30)){
rfmRecencyScore = 1;
}else if(rfmRecency <= UtilProperties.getPropertyAsInteger("order","order.rfm.recency.2",90)){
rfmRecencyScore = 2;
}else if(rfmRecency <= UtilProperties.getPropertyAsInteger("order","order.rfm.recency.3",375)){
rfmRecencyScore = 3;
}else{
rfmRecencyScore = 4;
}
if(rfmFrequency >= UtilProperties.getPropertyAsInteger("order","order.rfm.frequency.1",10)){
rfmFrequencyScore = 1;
}else if(rfmFrequency >= UtilProperties.getPropertyAsInteger("order","order.rfm.frequency.2",5)){
rfmFrequencyScore = 2;
}else if(rfmFrequency >= UtilProperties.getPropertyAsInteger("order","order.rfm.frequency.3",3)){
rfmFrequencyScore = 3;
}else{
rfmFrequencyScore = 4;
}
if(rfmMonetary.compareTo(new BigDecimal(UtilProperties.getPropertyAsInteger("order","order.rfm.monetary.1",250))) == 1){
rfmMonetaryScore = 1;
}else if(rfmMonetary.compareTo(new BigDecimal(UtilProperties.getPropertyAsInteger("order","order.rfm.monetary.2",100))) == 1){
rfmMonetaryScore = 2;
}else if(rfmMonetary.compareTo(new BigDecimal(UtilProperties.getPropertyAsInteger("order","order.rfm.monetary.3",50))) == 1){
rfmMonetaryScore = 3;
}else{
rfmMonetaryScore = 4;
}
resultMap.put("rfmRecencyScore",rfmRecencyScore);
resultMap.put("rfmFrequencyScore",rfmFrequencyScore);
resultMap.put("rfmMonetaryScore",rfmMonetaryScore);
return resultMap;
}
/**
* SCIPIO: Helper map cache that keeps an OrderReadHelper for each orderId
* and automatically returns a new OrderReadHelper on {@link #get(Object)} calls
* if there is not already one for the given orderId.
*/
public static class Cache implements Map<String, OrderReadHelper> {
private final Map<String, OrderReadHelper> orderIdMap = new HashMap<>();
private final Delegator delegator;
private final LocalDispatcher dispatcher; // SCIPIO: Optional dispatcher
private final Locale locale; // SCIPIO: Optional locale
protected Cache(Delegator delegator, LocalDispatcher dispatcher, Locale locale) {
this.delegator = delegator;
this.dispatcher = dispatcher;
this.locale = locale;
}
public static Cache create(Delegator delegator, LocalDispatcher dispatcher, Locale locale, OrderReadHelper... initialHelpers) {
Cache cache = new Cache(delegator, dispatcher, locale);
for(OrderReadHelper helper : initialHelpers) {
cache.put(helper.getOrderId(), helper);
}
return cache;
}
public static Cache create(LocalDispatcher dispatcher, Locale locale, OrderReadHelper... initialHelpers) {
return create(dispatcher.getDelegator(), dispatcher, locale, initialHelpers);
}
public static Cache create(Delegator delegator, LocalDispatcher dispatcher, Locale locale) {
return new Cache(delegator, dispatcher, locale);
}
public static Cache create(LocalDispatcher dispatcher, Locale locale) {
return new Cache(dispatcher.getDelegator(), dispatcher, locale);
}
public Delegator getDelegator() {
return delegator;
}
public LocalDispatcher getDispatcher() {
return dispatcher;
}
public Locale getLocale() {
return locale;
}
// Map interface methods
@Override
public OrderReadHelper get(Object key) {
OrderReadHelper orh = getIfExists(key);
if (orh == null) {
orh = new OrderReadHelper(getDelegator(), getDispatcher(), getLocale(), (String) key);
put((String) key, orh);
}
return orh;
}
public OrderReadHelper getIfExists(Object key) {
return orderIdMap.get(key);
}
@Override
public int size() {
return orderIdMap.size();
}
@Override
public boolean isEmpty() {
return orderIdMap.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return orderIdMap.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return orderIdMap.containsValue(value);
}
@Override
public OrderReadHelper put(String key, OrderReadHelper value) {
return orderIdMap.put(key, value);
}
@Override
public OrderReadHelper remove(Object key) {
return orderIdMap.remove(key);
}
@Override
public void putAll(Map<? extends String, ? extends OrderReadHelper> m) {
orderIdMap.putAll(m);
}
@Override
public void clear() {
orderIdMap.clear();
}
@Override
public Set<String> keySet() {
return orderIdMap.keySet();
}
@Override
public Collection<OrderReadHelper> values() {
return orderIdMap.values();
}
@Override
public Set<Entry<String, OrderReadHelper>> entrySet() {
return orderIdMap.entrySet();
}
@Override
public boolean equals(Object o) {
return orderIdMap.equals(o);
}
@Override
public int hashCode() {
return orderIdMap.hashCode();
}
}
}
| Fixed a bug in the order value - was missing multiplication by orderItem- and returnItem quantity
| applications/order/src/org/ofbiz/order/order/OrderReadHelper.java | Fixed a bug in the order value - was missing multiplication by orderItem- and returnItem quantity | <ide><path>pplications/order/src/org/ofbiz/order/order/OrderReadHelper.java
<ide> rfmRecency = Math.toIntExact( (System.currentTimeMillis() - lastOrderDate.getTime() )/ (1000 * 60 * 60 * 24));
<ide> }
<ide> BigDecimal nv = n.getBigDecimal("orderItemValue");
<del> orderItemValue = orderItemValue.add(nv);
<add> orderItemValue = orderItemValue.add(nv.multiply(n.getBigDecimal("orderItemCount")));
<ide> orderItemCount = orderItemCount.add(n.getBigDecimal("orderItemCount"));
<ide> cIndex+=1;
<ide> }
<ide> returnCount = returnStatsList.size();
<ide> for(GenericValue n : returnStatsList){
<ide> BigDecimal nv = n.getBigDecimal("returnItemValue");
<del> returnItemValue = returnItemValue.add(nv);
<add> returnItemValue = returnItemValue.add(nv.multiply(n.getBigDecimal("returnItemCount")));
<ide> returnItemCount = returnItemCount.add(n.getBigDecimal("returnItemCount"));
<ide> }
<ide> } |
|
JavaScript | apache-2.0 | 04a47e91108c5b40d48a7cf11c43ac4ef08a2088 | 0 | IMAGINARY/snapshot-slider,IMAGINARY/snapshot-slider,IMAGINARY/snapshot-slider | 'use strict';
const { WritableStreamBuffer } = require('stream-buffers');
const hummus = require('hummus');
const printer = require('printer');
const path = require('path');
module.exports = class SnapshotPrinter {
static async print(pdfFilename) {
await new Promise((resolve, reject) => {
const docName = path.basename(pdfFilename);
console.log('printing ' + path.basename(pdfFilename));
const streamBuffer = new WritableStreamBuffer({
initialSize: (1000 * 1024), // start at 100 kilobytes.
incrementAmount: (100 * 1024) // grow by 10 kilobytes each time buffer overflows.
});
createPDFBooklet(pdfFilename, streamBuffer);
printer.printDirect({
data: streamBuffer.getContents(),
docname: docName,
type: 'PDF',
options: {
landscape: true,
PageSize: 'A4',
Duplex: 'DuplexTumble'
},
success: resolve,
error: reject
});
});
}
};
function createPDF2On1(infile, outfileOrStream, pagesNumbers) {
console.log(`Creating 2-on-1 version of ${infile} at ${outfileOrStream}`);
if (typeof outfileOrStream !== 'string')
outfileOrStream = new hummus.PDFStreamForResponse(outfileOrStream);
const pdfWriter = hummus.createWriter(outfileOrStream, {
version: eval("hummus.ePDFVersion" + hummus.createReader(infile).getPDFLevel() * 10)
});
const copyingContext = pdfWriter.createPDFCopyingContext(infile);
const numPages = copyingContext.getSourceDocumentParser().getPagesCount();
pagesNumbers = (typeof pagesNumbers !== 'undefined') ? pagesNumbers : Array.from(Array(numPages), (_, i) => i);
for(let i = 0; i < pagesNumbers.length;) {
const page = pdfWriter.createPage(0, 0, 842, 595);
const pageContent = pdfWriter.startPageContentContext(page);
if (pagesNumbers[i] >= 0) {
pageContent.q().cm(1, 0, 0, 1, 0, 0);
copyingContext.mergePDFPageToPage(page, pagesNumbers[i]);
pageContent.Q();
}
++i;
if (i < pagesNumbers.length && pagesNumbers[i] >= 0) {
pageContent.q().cm(1, 0, 0, 1, 421, 0);
copyingContext.mergePDFPageToPage(page, pagesNumbers[i]);
pageContent.Q();
}
++i;
pdfWriter.writePage(page);
}
pdfWriter.end();
}
function createPDFBooklet(infile, outfileOrStream, shiftLastPageToBackCover = true) {
console.log(`Creating booklet version of ${infile} at ${outfileOrStream}`);
const numPages = hummus.createReader(infile).getPagesCount();
const numBookletPages = Math.ceil(numPages / 4) * 4;
// compute bookelt page numbers
let pageNumbers = Array(0);
let segment = [numBookletPages - 1, 0, 1, numBookletPages - 2];
for (let i = 0; i < numBookletPages / 4; ++i) {
pageNumbers = pageNumbers.concat(segment);
segment = [segment[0] - 2, segment[1] + 2, segment[2] + 2, segment[3] - 2];
}
// move last page of input to last page of booklet if required
if (shiftLastPageToBackCover) {
pageNumbers = pageNumbers.map(i => i >= numPages - 1 ? -1 : i);
pageNumbers[0] = numPages - 1;
} else {
pageNumbers = pageNumbers.map(i => i > numPages - 1 ? -1 : i);
}
createPDF2On1(infile, outfileOrStream, pageNumbers);
} | src/js/renderer/SnapshotPrinter.js | 'use strict';
const { WritableStreamBuffer } = require('stream-buffers');
const hummus = require('hummus');
const printer = require('printer');
module.exports = class SnapshotPrinter {
static async print(pdfFilename) {
await new Promise((resolve, reject) => {
const docName = path.basename(pdfFilename);
console.log('printing ' + path.basename(pdfFilename));
const streamBuffer = new WritableStreamBuffer({
initialSize: (1000 * 1024), // start at 100 kilobytes.
incrementAmount: (100 * 1024) // grow by 10 kilobytes each time buffer overflows.
});
createPDFBooklet(pdfFilename, streamBuffer);
printer.printDirect({
data: streamBuffer.getContents(),
docname: docName,
type: 'PDF',
options: {
landscape: true,
PageSize: 'A4',
Duplex: 'DuplexTumble'
},
success: resolve,
error: reject
});
});
}
};
function createPDF2On1(infile, outfileOrStream, pagesNumbers) {
console.log(`Creating 2-on-1 version of ${infile} at ${outfileOrStream}`);
if (typeof outfileOrStream !== 'string')
outfileOrStream = new hummus.PDFStreamForResponse(outfileOrStream);
const pdfWriter = hummus.createWriter(outfileOrStream, {
version: eval("hummus.ePDFVersion" + hummus.createReader(infile).getPDFLevel() * 10)
});
const copyingContext = pdfWriter.createPDFCopyingContext(infile);
const numPages = copyingContext.getSourceDocumentParser().getPagesCount();
pagesNumbers = (typeof pagesNumbers !== 'undefined') ? pagesNumbers : Array.from(Array(numPages), (_, i) => i);
for(let i = 0; i < pagesNumbers.length;) {
const page = pdfWriter.createPage(0, 0, 842, 595);
const pageContent = pdfWriter.startPageContentContext(page);
if (pagesNumbers[i] >= 0) {
pageContent.q().cm(1, 0, 0, 1, 0, 0);
copyingContext.mergePDFPageToPage(page, pagesNumbers[i]);
pageContent.Q();
}
++i;
if (i < pagesNumbers.length && pagesNumbers[i] >= 0) {
pageContent.q().cm(1, 0, 0, 1, 421, 0);
copyingContext.mergePDFPageToPage(page, pagesNumbers[i]);
pageContent.Q();
}
++i;
pdfWriter.writePage(page);
}
pdfWriter.end();
}
function createPDFBooklet(infile, outfileOrStream, shiftLastPageToBackCover = true) {
console.log(`Creating booklet version of ${infile} at ${outfileOrStream}`);
const numPages = hummus.createReader(infile).getPagesCount();
const numBookletPages = Math.ceil(numPages / 4) * 4;
// compute bookelt page numbers
let pageNumbers = Array(0);
let segment = [numBookletPages - 1, 0, 1, numBookletPages - 2];
for (let i = 0; i < numBookletPages / 4; ++i) {
pageNumbers = pageNumbers.concat(segment);
segment = [segment[0] - 2, segment[1] + 2, segment[2] + 2, segment[3] - 2];
}
// move last page of input to last page of booklet if required
if (shiftLastPageToBackCover) {
pageNumbers = pageNumbers.map(i => i >= numPages - 1 ? -1 : i);
pageNumbers[0] = numPages - 1;
} else {
pageNumbers = pageNumbers.map(i => i > numPages - 1 ? -1 : i);
}
createPDF2On1(infile, outfileOrStream, pageNumbers);
} | Fix missing import in SnapshotPrinter module
| src/js/renderer/SnapshotPrinter.js | Fix missing import in SnapshotPrinter module | <ide><path>rc/js/renderer/SnapshotPrinter.js
<ide> const { WritableStreamBuffer } = require('stream-buffers');
<ide> const hummus = require('hummus');
<ide> const printer = require('printer');
<add>const path = require('path');
<ide>
<ide> module.exports = class SnapshotPrinter {
<ide> |
|
Java | apache-2.0 | 156a956e01813dddffa1852c5076240773f29a38 | 0 | lucastheisen/apache-directory-server,apache/directory-server,drankye/directory-server,lucastheisen/apache-directory-server,darranl/directory-server,darranl/directory-server,drankye/directory-server,apache/directory-server | /*
* 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.directory.server.core.schema;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchResult;
import org.apache.directory.server.constants.MetaSchemaConstants;
import org.apache.directory.server.core.interceptor.context.LookupServiceContext;
import org.apache.directory.server.core.partition.Partition;
import org.apache.directory.server.schema.bootstrap.Schema;
import org.apache.directory.server.schema.registries.AbstractSchemaLoader;
import org.apache.directory.server.schema.registries.AttributeTypeRegistry;
import org.apache.directory.server.schema.registries.Registries;
import org.apache.directory.server.schema.registries.SchemaLoader;
import org.apache.directory.shared.ldap.constants.SchemaConstants;
import org.apache.directory.shared.ldap.name.LdapDN;
import org.apache.directory.shared.ldap.schema.AttributeType;
import org.apache.directory.shared.ldap.schema.Normalizer;
import org.apache.directory.shared.ldap.schema.ObjectClass;
import org.apache.directory.shared.ldap.schema.Syntax;
import org.apache.directory.shared.ldap.schema.MatchingRule;
import org.apache.directory.shared.ldap.schema.syntax.ComparatorDescription;
import org.apache.directory.shared.ldap.schema.syntax.NormalizerDescription;
import org.apache.directory.shared.ldap.schema.syntax.SyntaxChecker;
import org.apache.directory.shared.ldap.schema.syntax.SyntaxCheckerDescription;
import org.apache.directory.shared.ldap.util.AttributeUtils;
import org.apache.directory.shared.ldap.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A class that loads schemas from a partition.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$
*/
public class PartitionSchemaLoader extends AbstractSchemaLoader
{
/** static class logger */
private final static Logger log = LoggerFactory.getLogger( PartitionSchemaLoader.class );
private final SchemaPartitionDao dao;
private SchemaEntityFactory factory;
private Partition partition;
private AttributeTypeRegistry attrRegistry;
private final AttributeType mOidAT;
private final AttributeType mNameAT;
private final AttributeType cnAT;
private final AttributeType byteCodeAT;
private final AttributeType descAT;
private final AttributeType fqcnAT;
private static Map<String, LdapDN> staticAttributeTypeDNs = new HashMap<String, LdapDN>();
private static Map<String, LdapDN> staticMatchingRulesDNs = new HashMap<String, LdapDN>();
private static Map<String, LdapDN> staticObjectClassesDNs = new HashMap<String, LdapDN>();
private static Map<String, LdapDN> staticComparatorsDNs = new HashMap<String, LdapDN>();
private static Map<String, LdapDN> staticNormalizersDNs = new HashMap<String, LdapDN>();
private static Map<String, LdapDN> staticSyntaxCheckersDNs = new HashMap<String, LdapDN>();
private static Map<String, LdapDN> staticSyntaxesDNs = new HashMap<String, LdapDN>();
public PartitionSchemaLoader( Partition partition, Registries bootstrapRegistries ) throws NamingException
{
this.factory = new SchemaEntityFactory( bootstrapRegistries );
this.partition = partition;
this.attrRegistry = bootstrapRegistries.getAttributeTypeRegistry();
this.dao = new SchemaPartitionDao( this.partition, bootstrapRegistries );
this.mOidAT = bootstrapRegistries.getAttributeTypeRegistry().lookup( MetaSchemaConstants.M_OID_AT );
this.mNameAT = bootstrapRegistries.getAttributeTypeRegistry().lookup( MetaSchemaConstants.M_NAME_AT );
this.cnAT = bootstrapRegistries.getAttributeTypeRegistry().lookup( SchemaConstants.CN_AT );
this.byteCodeAT = bootstrapRegistries.getAttributeTypeRegistry().lookup( MetaSchemaConstants.M_BYTECODE_AT );
this.descAT = bootstrapRegistries.getAttributeTypeRegistry().lookup( MetaSchemaConstants.M_DESCRIPTION_AT );
this.fqcnAT = bootstrapRegistries.getAttributeTypeRegistry().lookup( MetaSchemaConstants.M_FQCN_AT );
initStaticDNs( "system" );
initStaticDNs( "core" );
initStaticDNs( "apache" );
initStaticDNs( "apachemeta" );
initStaticDNs( "other" );
initStaticDNs( "collective" );
initStaticDNs( "java" );
initStaticDNs( "cosine" );
initStaticDNs( "inetorgperson" );
}
private void initStaticDNs( String schemaName ) throws NamingException
{
// Initialize AttributeType Dns
LdapDN dn = new LdapDN( "ou=attributeTypes,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticAttributeTypeDNs.put( schemaName, dn );
// Initialize ObjectClasses Dns
dn = new LdapDN( "ou=objectClasses,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticObjectClassesDNs.put( schemaName, dn );
// Initialize MatchingRules Dns
dn = new LdapDN( "ou=matchingRules,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticMatchingRulesDNs.put( schemaName, dn );
// Initialize Comparators Dns
dn = new LdapDN( "ou=comparators,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticComparatorsDNs.put( schemaName, dn );
// Initialize Normalizers Dns
dn = new LdapDN( "ou=normalizers,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticNormalizersDNs.put( schemaName, dn );
// Initialize SyntaxCheckers Dns
dn = new LdapDN( "ou=syntaxCheckers,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticSyntaxCheckersDNs.put( schemaName, dn );
// Initialize Syntaxes Dns
dn = new LdapDN( "ou=syntaxes,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticSyntaxesDNs.put( schemaName, dn );
}
/**
* Utility method to load all enabled schemas into this registry.
*
* @param targetRegistries
* @throws NamingException
*/
public void loadEnabled( Registries targetRegistries ) throws NamingException
{
/*
* We need to load all names and oids into the oid registry regardless of
* the entity being in an enabled schema. This is necessary because we
* search for values in the schema partition that represent matchingRules
* and other entities that are not loaded. While searching these values
* in disabled schemas normalizers will attempt to equate names with oids
* and if there is an unrecognized value by a normalizer then the search
* will fail.
*
* For example there is a NameOrNumericOidNormalizer that will reduce a
* numeric OID or a non-numeric OID to it's numeric form using the OID
* registry. While searching the schema partition for attributeTypes we
* might find values of matchingRules in the m-ordering, m-equality, and
* m-substr attributes of metaAttributeType definitions. Now if an entry
* references a matchingRule that has not been loaded then the
* NameOrNumericOidNormalizer will bomb out when it tries to resolve
* names of matchingRules in unloaded schemas to OID values using the
* OID registry. To prevent this we need to load all the OID's in advance
* regardless of whether they are used or not.
*/
NamingEnumeration ne = dao.listAllNames();
while ( ne.hasMore() )
{
Attributes attrs = ( ( SearchResult ) ne.next() ).getAttributes();
String oid = ( String ) AttributeUtils.getAttribute( attrs, mOidAT ).get();
Attribute names = AttributeUtils.getAttribute( attrs, mNameAT );
targetRegistries.getOidRegistry().register( oid, oid );
for ( int ii = 0; ii < names.size(); ii++ )
{
targetRegistries.getOidRegistry().register( ( String ) names.get( ii ), oid );
}
}
ne.close();
Map<String, Schema> allSchemaMap = getSchemas();
Set<Schema> enabledSchemaSet = new HashSet<Schema>();
for ( Schema schema: allSchemaMap.values() )
{
if ( ! schema.isDisabled() )
{
log.debug( "will attempt to load enabled schema: {}", schema.getSchemaName() );
enabledSchemaSet.add( schema );
}
else
{
log.debug( "will NOT attempt to load disabled schema: {}", schema.getSchemaName() );
}
}
loadWithDependencies( enabledSchemaSet, targetRegistries );
}
/**
* Lists the names of the schemas that depend on the schema name provided.
*
* @param schemaName the name of the schema to find dependents for
* @return a set of schemas (String names) that depend on the schema
* @throws NamingException if there are problems searching the schema partition
*/
public Set<String> listDependentSchemaNames( String schemaName ) throws NamingException
{
Set<String> dependees = new HashSet<String>();
Set<SearchResult> results = dao.listSchemaDependents( schemaName );
if ( results.isEmpty() )
{
return dependees;
}
for ( SearchResult sr: results )
{
Attribute cn = AttributeUtils.getAttribute( sr.getAttributes(), cnAT );
dependees.add( ( String ) cn.get() );
}
return dependees;
}
/**
* Lists the names of the enabled schemas that depend on the schema name
* provided.
*
* @param schemaName the name of the schema to find dependents for
* @return a set of enabled schemas (String names) that depend on the schema
* @throws NamingException if there are problems searching the schema partition
*/
public Set<String> listEnabledDependentSchemaNames( String schemaName ) throws NamingException
{
Set<String> dependees = new HashSet<String>();
Set<SearchResult> results = dao.listEnabledSchemaDependents( schemaName );
if ( results.isEmpty() )
{
return dependees;
}
for ( SearchResult sr: results )
{
Attribute cn = AttributeUtils.getAttribute( sr.getAttributes(), cnAT );
dependees.add( ( String ) cn.get() );
}
return dependees;
}
public Map<String,Schema> getSchemas() throws NamingException
{
return dao.getSchemas();
}
public Set<String> getSchemaNames() throws NamingException
{
return dao.getSchemaNames();
}
public Schema getSchema( String schemaName ) throws NamingException
{
return dao.getSchema( schemaName );
}
public Schema getSchema( String schemaName, Properties schemaProperties ) throws NamingException
{
return getSchema( schemaName );
}
public final void loadWithDependencies( Collection<Schema> schemas, Registries targetRegistries ) throws NamingException
{
HashMap<String,Schema> notLoaded = new HashMap<String,Schema>();
Iterator<Schema> list = schemas.iterator();
while ( list.hasNext() )
{
Schema schema = list.next();
notLoaded.put( schema.getSchemaName(), schema );
}
list = notLoaded.values().iterator();
while ( list.hasNext() )
{
Schema schema = ( Schema ) list.next();
loadDepsFirst( schema, new Stack<String>(), notLoaded, schema, targetRegistries, null );
list = notLoaded.values().iterator();
}
}
/**
* {@link SchemaLoader#load(Schema, Registries, boolean)}
*/
public final void load( Schema schema, Registries targetRegistries, boolean isDepLoad ) throws NamingException
{
// if we're loading a dependency and it has not been enabled on
// disk then enable it on disk before we proceed to load it
if ( schema.isDisabled() && isDepLoad )
{
dao.enableSchema( schema.getSchemaName() );
}
if ( targetRegistries.getLoadedSchemas().containsKey( schema.getSchemaName() ) )
{
log.debug( "schema {} already seems to be loaded", schema.getSchemaName() );
return;
}
log.debug( "loading {} schema ...", schema.getSchemaName() );
loadComparators( schema, targetRegistries );
loadNormalizers( schema, targetRegistries );
loadSyntaxCheckers( schema, targetRegistries );
loadSyntaxes( schema, targetRegistries );
loadMatchingRules( schema, targetRegistries );
loadAttributeTypes( schema, targetRegistries );
loadObjectClasses( schema, targetRegistries );
loadMatchingRuleUses( schema, targetRegistries );
loadDitContentRules( schema, targetRegistries );
loadNameForms( schema, targetRegistries );
// order does matter here so some special trickery is needed
// we cannot load a DSR before the DSRs it depends on are loaded?
// TODO need ot confirm this ( or we must make the class for this and use deferred
// resolution until everything is available?
loadDitStructureRules( schema, targetRegistries );
notifyListenerOrRegistries( schema, targetRegistries );
}
private void loadMatchingRuleUses( Schema schema, Registries targetRegistries )
{
// TODO Auto-generated method stub
}
private void loadDitStructureRules( Schema schema, Registries targetRegistries ) throws NamingException
{
// TODO Auto-generated method stub
}
private void loadNameForms( Schema schema, Registries targetRegistries ) throws NamingException
{
// TODO Auto-generated method stub
}
private void loadDitContentRules( Schema schema, Registries targetRegistries ) throws NamingException
{
// TODO Auto-generated method stub
}
private void loadObjectClasses( Schema schema, Registries targetRegistries ) throws NamingException
{
/**
* Sometimes search may return child objectClasses before their superiors have
* been registered like with attributeTypes. To prevent this from bombing out
* the loader we will defer the registration of elements until later.
*/
LinkedList<ObjectClass> deferred = new LinkedList<ObjectClass>();
LdapDN dn = staticObjectClassesDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=objectClasses,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticObjectClassesDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading objectClasses", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
ObjectClass oc = factory.getObjectClass( attrs, targetRegistries, schema.getSchemaName() );
try
{
targetRegistries.getObjectClassRegistry().register( oc );
}
catch ( NamingException ne )
{
deferred.add( oc );
}
}
log.debug( "Deferred queue size = {}", deferred.size() );
if ( log.isDebugEnabled() )
{
StringBuffer buf = new StringBuffer();
buf.append( "Deferred queue contains: " );
for ( ObjectClass extra : deferred )
{
buf.append( extra.getName() );
buf.append( '[' );
buf.append( extra.getOid() );
buf.append( "]" );
buf.append( "\n" );
}
}
int lastCount = deferred.size();
while ( ! deferred.isEmpty() )
{
log.debug( "Deferred queue size = {}", deferred.size() );
ObjectClass oc = deferred.removeFirst();
NamingException lastException = null;
try
{
targetRegistries.getObjectClassRegistry().register( oc );
}
catch ( NamingException ne )
{
deferred.addLast( oc );
lastException = ne;
}
// if we shrank the deferred list we're doing good and can continue
if ( deferred.size() < lastCount )
{
lastCount = deferred.size();
}
else
{
StringBuffer buf = new StringBuffer();
buf.append( "A cycle must exist somewhere within the objectClasses of the " );
buf.append( schema.getSchemaName() );
buf.append( " schema. We cannot seem to register the following objectClasses:\n" );
for ( ObjectClass extra : deferred )
{
buf.append( extra.getName() );
buf.append( '[' );
buf.append( extra.getOid() );
buf.append( "]" );
buf.append( "\n" );
}
NamingException ne = new NamingException( buf.toString() );
ne.setRootCause( lastException );
}
}
}
private void loadAttributeTypes( Schema schema, Registries targetRegistries ) throws NamingException
{
LinkedList<AttributeType> deferred = new LinkedList<AttributeType>();
LdapDN dn = staticAttributeTypeDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=attributeTypes,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticAttributeTypeDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading attributeTypes", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
AttributeType at = factory.getAttributeType( attrs, targetRegistries, schema.getSchemaName() );
try
{
targetRegistries.getAttributeTypeRegistry().register( at );
}
catch ( NamingException ne )
{
deferred.add( at );
}
}
log.debug( "Deferred queue size = {}", deferred.size() );
if ( log.isDebugEnabled() )
{
StringBuffer buf = new StringBuffer();
buf.append( "Deferred queue contains: " );
for ( AttributeType extra : deferred )
{
buf.append( extra.getName() );
buf.append( '[' );
buf.append( extra.getOid() );
buf.append( "]" );
buf.append( "\n" );
}
}
int lastCount = deferred.size();
while ( ! deferred.isEmpty() )
{
log.debug( "Deferred queue size = {}", deferred.size() );
AttributeType at = deferred.removeFirst();
NamingException lastException = null;
try
{
targetRegistries.getAttributeTypeRegistry().register( at );
}
catch ( NamingException ne )
{
deferred.addLast( at );
lastException = ne;
}
// if we shrank the deferred list we're doing good and can continue
if ( deferred.size() < lastCount )
{
lastCount = deferred.size();
}
else
{
StringBuffer buf = new StringBuffer();
buf.append( "A cycle must exist somewhere within the attributeTypes of the " );
buf.append( schema.getSchemaName() );
buf.append( " schema. We cannot seem to register the following attributeTypes:\n" );
for ( AttributeType extra : deferred )
{
buf.append( extra.getName() );
buf.append( '[' );
buf.append( extra.getOid() );
buf.append( "]" );
buf.append( "\n" );
}
NamingException ne = new NamingException( buf.toString() );
ne.setRootCause( lastException );
}
}
}
private void loadMatchingRules( Schema schema, Registries targetRegistries ) throws NamingException
{
LdapDN dn = staticMatchingRulesDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=matchingRules,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticMatchingRulesDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading matchingRules", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
MatchingRule mrule = factory.getMatchingRule( attrs, targetRegistries, schema.getSchemaName() );
targetRegistries.getMatchingRuleRegistry().register( mrule );
}
}
private void loadSyntaxes( Schema schema, Registries targetRegistries ) throws NamingException
{
LdapDN dn = staticSyntaxesDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=syntaxes,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticSyntaxesDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading syntaxes", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
Syntax syntax = factory.getSyntax( attrs, targetRegistries, schema.getSchemaName() );
targetRegistries.getSyntaxRegistry().register( syntax );
}
}
private void loadSyntaxCheckers( Schema schema, Registries targetRegistries ) throws NamingException
{
LdapDN dn = staticSyntaxCheckersDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=syntaxCheckers,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticSyntaxCheckersDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading syntaxCheckers", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
SyntaxChecker sc = factory.getSyntaxChecker( attrs, targetRegistries );
SyntaxCheckerDescription syntaxCheckerDescription =
getSyntaxCheckerDescription( schema.getSchemaName(), attrs );
targetRegistries.getSyntaxCheckerRegistry().register( syntaxCheckerDescription, sc );
}
}
private void loadNormalizers( Schema schema, Registries targetRegistries ) throws NamingException
{
LdapDN dn = staticNormalizersDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=normalizers,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticNormalizersDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading normalizers", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
Normalizer normalizer = factory.getNormalizer( attrs, targetRegistries );
NormalizerDescription normalizerDescription = getNormalizerDescription( schema.getSchemaName(), attrs );
targetRegistries.getNormalizerRegistry().register( normalizerDescription, normalizer );
}
}
private String getOid( Attributes entry ) throws NamingException
{
Attribute oid = AttributeUtils.getAttribute( entry, mOidAT );
if ( oid == null )
{
return null;
}
return ( String ) oid.get();
}
private NormalizerDescription getNormalizerDescription( String schemaName, Attributes entry ) throws NamingException
{
NormalizerDescription description = new NormalizerDescription();
description.setNumericOid( getOid( entry ) );
List<String> values = new ArrayList<String>();
values.add( schemaName );
description.addExtension( MetaSchemaConstants.X_SCHEMA, values );
description.setFqcn( ( String ) AttributeUtils.getAttribute( entry, fqcnAT ).get() );
Attribute desc = AttributeUtils.getAttribute( entry, descAT );
if ( desc != null && desc.size() > 0 )
{
description.setDescription( ( String ) desc.get() );
}
Attribute bytecode = AttributeUtils.getAttribute( entry, byteCodeAT );
if ( bytecode != null && bytecode.size() > 0 )
{
byte[] bytes = ( byte[] ) bytecode.get();
description.setBytecode( new String( Base64.encode( bytes ) ) );
}
return description;
}
private void loadComparators( Schema schema, Registries targetRegistries ) throws NamingException
{
LdapDN dn = staticComparatorsDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=comparators,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticComparatorsDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading comparators", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
Comparator comparator = factory.getComparator( attrs, targetRegistries );
ComparatorDescription comparatorDescription = getComparatorDescription( schema.getSchemaName(), attrs );
targetRegistries.getComparatorRegistry().register( comparatorDescription, comparator );
}
}
private ComparatorDescription getComparatorDescription( String schemaName, Attributes entry ) throws NamingException
{
ComparatorDescription description = new ComparatorDescription();
description.setNumericOid( getOid( entry ) );
List<String> values = new ArrayList<String>();
values.add( schemaName );
description.addExtension( MetaSchemaConstants.X_SCHEMA, values );
description.setFqcn( ( String ) AttributeUtils.getAttribute( entry, fqcnAT ).get() );
Attribute desc = AttributeUtils.getAttribute( entry, descAT );
if ( desc != null && desc.size() > 0 )
{
description.setDescription( ( String ) desc.get() );
}
Attribute bytecode = AttributeUtils.getAttribute( entry, byteCodeAT );
if ( bytecode != null && bytecode.size() > 0 )
{
byte[] bytes = ( byte[] ) bytecode.get();
description.setBytecode( new String( Base64.encode( bytes ) ) );
}
return description;
}
private SyntaxCheckerDescription getSyntaxCheckerDescription( String schemaName, Attributes entry )
throws NamingException
{
SyntaxCheckerDescription description = new SyntaxCheckerDescription();
description.setNumericOid( getOid( entry ) );
List<String> values = new ArrayList<String>();
values.add( schemaName );
description.addExtension( MetaSchemaConstants.X_SCHEMA, values );
description.setFqcn( ( String ) AttributeUtils.getAttribute( entry, fqcnAT ).get() );
Attribute desc = AttributeUtils.getAttribute( entry, descAT );
if ( desc != null && desc.size() > 0 )
{
description.setDescription( ( String ) desc.get() );
}
Attribute bytecode = AttributeUtils.getAttribute( entry, byteCodeAT );
if ( bytecode != null && bytecode.size() > 0 )
{
byte[] bytes = ( byte[] ) bytecode.get();
description.setBytecode( new String( Base64.encode( bytes ) ) );
}
return description;
}
public void loadWithDependencies( Schema schema, Registries registries ) throws NamingException
{
HashMap<String,Schema> notLoaded = new HashMap<String,Schema>();
notLoaded.put( schema.getSchemaName(), schema );
Properties props = new Properties();
loadDepsFirst( schema, new Stack<String>(), notLoaded, schema, registries, props );
}
}
| core/src/main/java/org/apache/directory/server/core/schema/PartitionSchemaLoader.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.directory.server.core.schema;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchResult;
import org.apache.directory.server.constants.MetaSchemaConstants;
import org.apache.directory.server.core.partition.Partition;
import org.apache.directory.server.schema.bootstrap.Schema;
import org.apache.directory.server.schema.registries.AbstractSchemaLoader;
import org.apache.directory.server.schema.registries.AttributeTypeRegistry;
import org.apache.directory.server.schema.registries.Registries;
import org.apache.directory.server.schema.registries.SchemaLoader;
import org.apache.directory.shared.ldap.constants.SchemaConstants;
import org.apache.directory.shared.ldap.name.LdapDN;
import org.apache.directory.shared.ldap.schema.AttributeType;
import org.apache.directory.shared.ldap.schema.Normalizer;
import org.apache.directory.shared.ldap.schema.ObjectClass;
import org.apache.directory.shared.ldap.schema.Syntax;
import org.apache.directory.shared.ldap.schema.MatchingRule;
import org.apache.directory.shared.ldap.schema.syntax.ComparatorDescription;
import org.apache.directory.shared.ldap.schema.syntax.NormalizerDescription;
import org.apache.directory.shared.ldap.schema.syntax.SyntaxChecker;
import org.apache.directory.shared.ldap.schema.syntax.SyntaxCheckerDescription;
import org.apache.directory.shared.ldap.util.AttributeUtils;
import org.apache.directory.shared.ldap.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A class that loads schemas from a partition.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$
*/
public class PartitionSchemaLoader extends AbstractSchemaLoader
{
/** static class logger */
private final static Logger log = LoggerFactory.getLogger( PartitionSchemaLoader.class );
private final SchemaPartitionDao dao;
private SchemaEntityFactory factory;
private Partition partition;
private AttributeTypeRegistry attrRegistry;
private final AttributeType mOidAT;
private final AttributeType mNameAT;
private final AttributeType cnAT;
private final AttributeType byteCodeAT;
private final AttributeType descAT;
private final AttributeType fqcnAT;
private static Map<String, LdapDN> staticAttributeTypeDNs = new HashMap<String, LdapDN>();
private static Map<String, LdapDN> staticMatchingRulesDNs = new HashMap<String, LdapDN>();
private static Map<String, LdapDN> staticObjectClassesDNs = new HashMap<String, LdapDN>();
private static Map<String, LdapDN> staticComparatorsDNs = new HashMap<String, LdapDN>();
private static Map<String, LdapDN> staticNormalizersDNs = new HashMap<String, LdapDN>();
private static Map<String, LdapDN> staticSyntaxCheckersDNs = new HashMap<String, LdapDN>();
private static Map<String, LdapDN> staticSyntaxesDNs = new HashMap<String, LdapDN>();
public PartitionSchemaLoader( Partition partition, Registries bootstrapRegistries ) throws NamingException
{
this.factory = new SchemaEntityFactory( bootstrapRegistries );
this.partition = partition;
this.attrRegistry = bootstrapRegistries.getAttributeTypeRegistry();
this.dao = new SchemaPartitionDao( this.partition, bootstrapRegistries );
this.mOidAT = bootstrapRegistries.getAttributeTypeRegistry().lookup( MetaSchemaConstants.M_OID_AT );
this.mNameAT = bootstrapRegistries.getAttributeTypeRegistry().lookup( MetaSchemaConstants.M_NAME_AT );
this.cnAT = bootstrapRegistries.getAttributeTypeRegistry().lookup( SchemaConstants.CN_AT );
this.byteCodeAT = bootstrapRegistries.getAttributeTypeRegistry().lookup( MetaSchemaConstants.M_BYTECODE_AT );
this.descAT = bootstrapRegistries.getAttributeTypeRegistry().lookup( MetaSchemaConstants.M_DESCRIPTION_AT );
this.fqcnAT = bootstrapRegistries.getAttributeTypeRegistry().lookup( MetaSchemaConstants.M_FQCN_AT );
initStaticDNs( "system" );
initStaticDNs( "core" );
initStaticDNs( "apache" );
initStaticDNs( "apachemeta" );
initStaticDNs( "other" );
initStaticDNs( "collective" );
initStaticDNs( "java" );
initStaticDNs( "cosine" );
initStaticDNs( "inetorgperson" );
}
private void initStaticDNs( String schemaName ) throws NamingException
{
// Initialize AttributeType Dns
LdapDN dn = new LdapDN( "ou=attributeTypes,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticAttributeTypeDNs.put( schemaName, dn );
// Initialize ObjectClasses Dns
dn = new LdapDN( "ou=objectClasses,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticObjectClassesDNs.put( schemaName, dn );
// Initialize MatchingRules Dns
dn = new LdapDN( "ou=matchingRules,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticMatchingRulesDNs.put( schemaName, dn );
// Initialize Comparators Dns
dn = new LdapDN( "ou=comparators,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticComparatorsDNs.put( schemaName, dn );
// Initialize Normalizers Dns
dn = new LdapDN( "ou=normalizers,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticNormalizersDNs.put( schemaName, dn );
// Initialize SyntaxCheckers Dns
dn = new LdapDN( "ou=syntaxCheckers,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticSyntaxCheckersDNs.put( schemaName, dn );
// Initialize Syntaxes Dns
dn = new LdapDN( "ou=syntaxes,cn=" + schemaName + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticSyntaxesDNs.put( schemaName, dn );
}
/**
* Utility method to load all enabled schemas into this registry.
*
* @param targetRegistries
* @throws NamingException
*/
public void loadEnabled( Registries targetRegistries ) throws NamingException
{
/*
* We need to load all names and oids into the oid registry regardless of
* the entity being in an enabled schema. This is necessary because we
* search for values in the schema partition that represent matchingRules
* and other entities that are not loaded. While searching these values
* in disabled schemas normalizers will attempt to equate names with oids
* and if there is an unrecognized value by a normalizer then the search
* will fail.
*
* For example there is a NameOrNumericOidNormalizer that will reduce a
* numeric OID or a non-numeric OID to it's numeric form using the OID
* registry. While searching the schema partition for attributeTypes we
* might find values of matchingRules in the m-ordering, m-equality, and
* m-substr attributes of metaAttributeType definitions. Now if an entry
* references a matchingRule that has not been loaded then the
* NameOrNumericOidNormalizer will bomb out when it tries to resolve
* names of matchingRules in unloaded schemas to OID values using the
* OID registry. To prevent this we need to load all the OID's in advance
* regardless of whether they are used or not.
*/
NamingEnumeration ne = dao.listAllNames();
while ( ne.hasMore() )
{
Attributes attrs = ( ( SearchResult ) ne.next() ).getAttributes();
String oid = ( String ) AttributeUtils.getAttribute( attrs, mOidAT ).get();
Attribute names = AttributeUtils.getAttribute( attrs, mNameAT );
targetRegistries.getOidRegistry().register( oid, oid );
for ( int ii = 0; ii < names.size(); ii++ )
{
targetRegistries.getOidRegistry().register( ( String ) names.get( ii ), oid );
}
}
ne.close();
Map<String, Schema> allSchemaMap = getSchemas();
Set<Schema> enabledSchemaSet = new HashSet<Schema>();
for ( Schema schema: allSchemaMap.values() )
{
if ( ! schema.isDisabled() )
{
log.debug( "will attempt to load enabled schema: {}", schema.getSchemaName() );
enabledSchemaSet.add( schema );
}
else
{
log.debug( "will NOT attempt to load disabled schema: {}", schema.getSchemaName() );
}
}
loadWithDependencies( enabledSchemaSet, targetRegistries );
}
/**
* Lists the names of the schemas that depend on the schema name provided.
*
* @param schemaName the name of the schema to find dependents for
* @return a set of schemas (String names) that depend on the schema
* @throws NamingException if there are problems searching the schema partition
*/
public Set<String> listDependentSchemaNames( String schemaName ) throws NamingException
{
Set<String> dependees = new HashSet<String>();
Set<SearchResult> results = dao.listSchemaDependents( schemaName );
if ( results.isEmpty() )
{
return dependees;
}
for ( SearchResult sr: results )
{
Attribute cn = AttributeUtils.getAttribute( sr.getAttributes(), cnAT );
dependees.add( ( String ) cn.get() );
}
return dependees;
}
/**
* Lists the names of the enabled schemas that depend on the schema name
* provided.
*
* @param schemaName the name of the schema to find dependents for
* @return a set of enabled schemas (String names) that depend on the schema
* @throws NamingException if there are problems searching the schema partition
*/
public Set<String> listEnabledDependentSchemaNames( String schemaName ) throws NamingException
{
Set<String> dependees = new HashSet<String>();
Set<SearchResult> results = dao.listEnabledSchemaDependents( schemaName );
if ( results.isEmpty() )
{
return dependees;
}
for ( SearchResult sr: results )
{
Attribute cn = AttributeUtils.getAttribute( sr.getAttributes(), cnAT );
dependees.add( ( String ) cn.get() );
}
return dependees;
}
public Map<String,Schema> getSchemas() throws NamingException
{
return dao.getSchemas();
}
public Set<String> getSchemaNames() throws NamingException
{
return dao.getSchemaNames();
}
public Schema getSchema( String schemaName ) throws NamingException
{
return dao.getSchema( schemaName );
}
public Schema getSchema( String schemaName, Properties schemaProperties ) throws NamingException
{
return getSchema( schemaName );
}
public final void loadWithDependencies( Collection<Schema> schemas, Registries targetRegistries ) throws NamingException
{
HashMap<String,Schema> notLoaded = new HashMap<String,Schema>();
Iterator<Schema> list = schemas.iterator();
while ( list.hasNext() )
{
Schema schema = list.next();
notLoaded.put( schema.getSchemaName(), schema );
}
list = notLoaded.values().iterator();
while ( list.hasNext() )
{
Schema schema = ( Schema ) list.next();
loadDepsFirst( schema, new Stack<String>(), notLoaded, schema, targetRegistries, null );
list = notLoaded.values().iterator();
}
}
/**
* {@link SchemaLoader#load(Schema, Registries, boolean)}
*/
public final void load( Schema schema, Registries targetRegistries, boolean isDepLoad ) throws NamingException
{
// if we're loading a dependency and it has not been enabled on
// disk then enable it on disk before we proceed to load it
if ( schema.isDisabled() && isDepLoad )
{
dao.enableSchema( schema.getSchemaName() );
}
if ( targetRegistries.getLoadedSchemas().containsKey( schema.getSchemaName() ) )
{
log.debug( "schema {} already seems to be loaded", schema.getSchemaName() );
return;
}
log.debug( "loading {} schema ...", schema.getSchemaName() );
loadComparators( schema, targetRegistries );
loadNormalizers( schema, targetRegistries );
loadSyntaxCheckers( schema, targetRegistries );
loadSyntaxes( schema, targetRegistries );
loadMatchingRules( schema, targetRegistries );
loadAttributeTypes( schema, targetRegistries );
loadObjectClasses( schema, targetRegistries );
loadMatchingRuleUses( schema, targetRegistries );
loadDitContentRules( schema, targetRegistries );
loadNameForms( schema, targetRegistries );
// order does matter here so some special trickery is needed
// we cannot load a DSR before the DSRs it depends on are loaded?
// TODO need ot confirm this ( or we must make the class for this and use deferred
// resolution until everything is available?
loadDitStructureRules( schema, targetRegistries );
notifyListenerOrRegistries( schema, targetRegistries );
}
private void loadMatchingRuleUses( Schema schema, Registries targetRegistries )
{
// TODO Auto-generated method stub
}
private void loadDitStructureRules( Schema schema, Registries targetRegistries ) throws NamingException
{
// TODO Auto-generated method stub
}
private void loadNameForms( Schema schema, Registries targetRegistries ) throws NamingException
{
// TODO Auto-generated method stub
}
private void loadDitContentRules( Schema schema, Registries targetRegistries ) throws NamingException
{
// TODO Auto-generated method stub
}
private void loadObjectClasses( Schema schema, Registries targetRegistries ) throws NamingException
{
/**
* Sometimes search may return child objectClasses before their superiors have
* been registered like with attributeTypes. To prevent this from bombing out
* the loader we will defer the registration of elements until later.
*/
LinkedList<ObjectClass> deferred = new LinkedList<ObjectClass>();
LdapDN dn = staticObjectClassesDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=objectClasses,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticObjectClassesDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading objectClasses", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( resultDN );
ObjectClass oc = factory.getObjectClass( attrs, targetRegistries, schema.getSchemaName() );
try
{
targetRegistries.getObjectClassRegistry().register( oc );
}
catch ( NamingException ne )
{
deferred.add( oc );
}
}
log.debug( "Deferred queue size = {}", deferred.size() );
if ( log.isDebugEnabled() )
{
StringBuffer buf = new StringBuffer();
buf.append( "Deferred queue contains: " );
for ( ObjectClass extra : deferred )
{
buf.append( extra.getName() );
buf.append( '[' );
buf.append( extra.getOid() );
buf.append( "]" );
buf.append( "\n" );
}
}
int lastCount = deferred.size();
while ( ! deferred.isEmpty() )
{
log.debug( "Deferred queue size = {}", deferred.size() );
ObjectClass oc = deferred.removeFirst();
NamingException lastException = null;
try
{
targetRegistries.getObjectClassRegistry().register( oc );
}
catch ( NamingException ne )
{
deferred.addLast( oc );
lastException = ne;
}
// if we shrank the deferred list we're doing good and can continue
if ( deferred.size() < lastCount )
{
lastCount = deferred.size();
}
else
{
StringBuffer buf = new StringBuffer();
buf.append( "A cycle must exist somewhere within the objectClasses of the " );
buf.append( schema.getSchemaName() );
buf.append( " schema. We cannot seem to register the following objectClasses:\n" );
for ( ObjectClass extra : deferred )
{
buf.append( extra.getName() );
buf.append( '[' );
buf.append( extra.getOid() );
buf.append( "]" );
buf.append( "\n" );
}
NamingException ne = new NamingException( buf.toString() );
ne.setRootCause( lastException );
}
}
}
private void loadAttributeTypes( Schema schema, Registries targetRegistries ) throws NamingException
{
LinkedList<AttributeType> deferred = new LinkedList<AttributeType>();
LdapDN dn = staticAttributeTypeDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=attributeTypes,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticAttributeTypeDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading attributeTypes", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( resultDN );
AttributeType at = factory.getAttributeType( attrs, targetRegistries, schema.getSchemaName() );
try
{
targetRegistries.getAttributeTypeRegistry().register( at );
}
catch ( NamingException ne )
{
deferred.add( at );
}
}
log.debug( "Deferred queue size = {}", deferred.size() );
if ( log.isDebugEnabled() )
{
StringBuffer buf = new StringBuffer();
buf.append( "Deferred queue contains: " );
for ( AttributeType extra : deferred )
{
buf.append( extra.getName() );
buf.append( '[' );
buf.append( extra.getOid() );
buf.append( "]" );
buf.append( "\n" );
}
}
int lastCount = deferred.size();
while ( ! deferred.isEmpty() )
{
log.debug( "Deferred queue size = {}", deferred.size() );
AttributeType at = deferred.removeFirst();
NamingException lastException = null;
try
{
targetRegistries.getAttributeTypeRegistry().register( at );
}
catch ( NamingException ne )
{
deferred.addLast( at );
lastException = ne;
}
// if we shrank the deferred list we're doing good and can continue
if ( deferred.size() < lastCount )
{
lastCount = deferred.size();
}
else
{
StringBuffer buf = new StringBuffer();
buf.append( "A cycle must exist somewhere within the attributeTypes of the " );
buf.append( schema.getSchemaName() );
buf.append( " schema. We cannot seem to register the following attributeTypes:\n" );
for ( AttributeType extra : deferred )
{
buf.append( extra.getName() );
buf.append( '[' );
buf.append( extra.getOid() );
buf.append( "]" );
buf.append( "\n" );
}
NamingException ne = new NamingException( buf.toString() );
ne.setRootCause( lastException );
}
}
}
private void loadMatchingRules( Schema schema, Registries targetRegistries ) throws NamingException
{
LdapDN dn = staticMatchingRulesDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=matchingRules,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticMatchingRulesDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading matchingRules", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( resultDN );
MatchingRule mrule = factory.getMatchingRule( attrs, targetRegistries, schema.getSchemaName() );
targetRegistries.getMatchingRuleRegistry().register( mrule );
}
}
private void loadSyntaxes( Schema schema, Registries targetRegistries ) throws NamingException
{
LdapDN dn = staticSyntaxesDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=syntaxes,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticSyntaxesDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading syntaxes", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( resultDN );
Syntax syntax = factory.getSyntax( attrs, targetRegistries, schema.getSchemaName() );
targetRegistries.getSyntaxRegistry().register( syntax );
}
}
private void loadSyntaxCheckers( Schema schema, Registries targetRegistries ) throws NamingException
{
LdapDN dn = staticSyntaxCheckersDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=syntaxCheckers,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticSyntaxCheckersDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading syntaxCheckers", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( resultDN );
SyntaxChecker sc = factory.getSyntaxChecker( attrs, targetRegistries );
SyntaxCheckerDescription syntaxCheckerDescription =
getSyntaxCheckerDescription( schema.getSchemaName(), attrs );
targetRegistries.getSyntaxCheckerRegistry().register( syntaxCheckerDescription, sc );
}
}
private void loadNormalizers( Schema schema, Registries targetRegistries ) throws NamingException
{
LdapDN dn = staticNormalizersDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=normalizers,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticNormalizersDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading normalizers", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( resultDN );
Normalizer normalizer = factory.getNormalizer( attrs, targetRegistries );
NormalizerDescription normalizerDescription = getNormalizerDescription( schema.getSchemaName(), attrs );
targetRegistries.getNormalizerRegistry().register( normalizerDescription, normalizer );
}
}
private String getOid( Attributes entry ) throws NamingException
{
Attribute oid = AttributeUtils.getAttribute( entry, mOidAT );
if ( oid == null )
{
return null;
}
return ( String ) oid.get();
}
private NormalizerDescription getNormalizerDescription( String schemaName, Attributes entry ) throws NamingException
{
NormalizerDescription description = new NormalizerDescription();
description.setNumericOid( getOid( entry ) );
List<String> values = new ArrayList<String>();
values.add( schemaName );
description.addExtension( MetaSchemaConstants.X_SCHEMA, values );
description.setFqcn( ( String ) AttributeUtils.getAttribute( entry, fqcnAT ).get() );
Attribute desc = AttributeUtils.getAttribute( entry, descAT );
if ( desc != null && desc.size() > 0 )
{
description.setDescription( ( String ) desc.get() );
}
Attribute bytecode = AttributeUtils.getAttribute( entry, byteCodeAT );
if ( bytecode != null && bytecode.size() > 0 )
{
byte[] bytes = ( byte[] ) bytecode.get();
description.setBytecode( new String( Base64.encode( bytes ) ) );
}
return description;
}
private void loadComparators( Schema schema, Registries targetRegistries ) throws NamingException
{
LdapDN dn = staticComparatorsDNs.get( schema.getSchemaName() );
if ( dn == null )
{
dn = new LdapDN( "ou=comparators,cn=" + schema.getSchemaName() + ",ou=schema" );
dn.normalize( this.attrRegistry.getNormalizerMapping() );
staticComparatorsDNs.put( schema.getSchemaName(), dn );
}
if ( ! partition.hasEntry( dn ) )
{
return;
}
log.debug( "{} schema: loading comparators", schema.getSchemaName() );
NamingEnumeration list = partition.list( dn );
while ( list.hasMore() )
{
SearchResult result = ( SearchResult ) list.next();
LdapDN resultDN = new LdapDN( result.getName() );
resultDN.normalize( attrRegistry.getNormalizerMapping() );
Attributes attrs = partition.lookup( resultDN );
Comparator comparator = factory.getComparator( attrs, targetRegistries );
ComparatorDescription comparatorDescription = getComparatorDescription( schema.getSchemaName(), attrs );
targetRegistries.getComparatorRegistry().register( comparatorDescription, comparator );
}
}
private ComparatorDescription getComparatorDescription( String schemaName, Attributes entry ) throws NamingException
{
ComparatorDescription description = new ComparatorDescription();
description.setNumericOid( getOid( entry ) );
List<String> values = new ArrayList<String>();
values.add( schemaName );
description.addExtension( MetaSchemaConstants.X_SCHEMA, values );
description.setFqcn( ( String ) AttributeUtils.getAttribute( entry, fqcnAT ).get() );
Attribute desc = AttributeUtils.getAttribute( entry, descAT );
if ( desc != null && desc.size() > 0 )
{
description.setDescription( ( String ) desc.get() );
}
Attribute bytecode = AttributeUtils.getAttribute( entry, byteCodeAT );
if ( bytecode != null && bytecode.size() > 0 )
{
byte[] bytes = ( byte[] ) bytecode.get();
description.setBytecode( new String( Base64.encode( bytes ) ) );
}
return description;
}
private SyntaxCheckerDescription getSyntaxCheckerDescription( String schemaName, Attributes entry )
throws NamingException
{
SyntaxCheckerDescription description = new SyntaxCheckerDescription();
description.setNumericOid( getOid( entry ) );
List<String> values = new ArrayList<String>();
values.add( schemaName );
description.addExtension( MetaSchemaConstants.X_SCHEMA, values );
description.setFqcn( ( String ) AttributeUtils.getAttribute( entry, fqcnAT ).get() );
Attribute desc = AttributeUtils.getAttribute( entry, descAT );
if ( desc != null && desc.size() > 0 )
{
description.setDescription( ( String ) desc.get() );
}
Attribute bytecode = AttributeUtils.getAttribute( entry, byteCodeAT );
if ( bytecode != null && bytecode.size() > 0 )
{
byte[] bytes = ( byte[] ) bytecode.get();
description.setBytecode( new String( Base64.encode( bytes ) ) );
}
return description;
}
public void loadWithDependencies( Schema schema, Registries registries ) throws NamingException
{
HashMap<String,Schema> notLoaded = new HashMap<String,Schema>();
notLoaded.put( schema.getSchemaName(), schema );
Properties props = new Properties();
loadDepsFirst( schema, new Stack<String>(), notLoaded, schema, registries, props );
}
}
| Now use the new lookup( ServiceContext ) method
git-svn-id: 90776817adfbd895fc5cfa90f675377e0a62e745@525884 13f79535-47bb-0310-9956-ffa450edef68
| core/src/main/java/org/apache/directory/server/core/schema/PartitionSchemaLoader.java | Now use the new lookup( ServiceContext ) method | <ide><path>ore/src/main/java/org/apache/directory/server/core/schema/PartitionSchemaLoader.java
<ide> import javax.naming.directory.SearchResult;
<ide>
<ide> import org.apache.directory.server.constants.MetaSchemaConstants;
<add>import org.apache.directory.server.core.interceptor.context.LookupServiceContext;
<ide> import org.apache.directory.server.core.partition.Partition;
<ide> import org.apache.directory.server.schema.bootstrap.Schema;
<ide> import org.apache.directory.server.schema.registries.AbstractSchemaLoader;
<ide> SearchResult result = ( SearchResult ) list.next();
<ide> LdapDN resultDN = new LdapDN( result.getName() );
<ide> resultDN.normalize( attrRegistry.getNormalizerMapping() );
<del> Attributes attrs = partition.lookup( resultDN );
<add> Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
<ide> ObjectClass oc = factory.getObjectClass( attrs, targetRegistries, schema.getSchemaName() );
<ide>
<ide> try
<ide> SearchResult result = ( SearchResult ) list.next();
<ide> LdapDN resultDN = new LdapDN( result.getName() );
<ide> resultDN.normalize( attrRegistry.getNormalizerMapping() );
<del> Attributes attrs = partition.lookup( resultDN );
<add> Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
<ide> AttributeType at = factory.getAttributeType( attrs, targetRegistries, schema.getSchemaName() );
<ide> try
<ide> {
<ide> SearchResult result = ( SearchResult ) list.next();
<ide> LdapDN resultDN = new LdapDN( result.getName() );
<ide> resultDN.normalize( attrRegistry.getNormalizerMapping() );
<del> Attributes attrs = partition.lookup( resultDN );
<add> Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
<ide> MatchingRule mrule = factory.getMatchingRule( attrs, targetRegistries, schema.getSchemaName() );
<ide> targetRegistries.getMatchingRuleRegistry().register( mrule );
<ide>
<ide> SearchResult result = ( SearchResult ) list.next();
<ide> LdapDN resultDN = new LdapDN( result.getName() );
<ide> resultDN.normalize( attrRegistry.getNormalizerMapping() );
<del> Attributes attrs = partition.lookup( resultDN );
<add> Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
<ide> Syntax syntax = factory.getSyntax( attrs, targetRegistries, schema.getSchemaName() );
<ide> targetRegistries.getSyntaxRegistry().register( syntax );
<ide> }
<ide> SearchResult result = ( SearchResult ) list.next();
<ide> LdapDN resultDN = new LdapDN( result.getName() );
<ide> resultDN.normalize( attrRegistry.getNormalizerMapping() );
<del> Attributes attrs = partition.lookup( resultDN );
<add> Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
<ide> SyntaxChecker sc = factory.getSyntaxChecker( attrs, targetRegistries );
<ide> SyntaxCheckerDescription syntaxCheckerDescription =
<ide> getSyntaxCheckerDescription( schema.getSchemaName(), attrs );
<ide> SearchResult result = ( SearchResult ) list.next();
<ide> LdapDN resultDN = new LdapDN( result.getName() );
<ide> resultDN.normalize( attrRegistry.getNormalizerMapping() );
<del> Attributes attrs = partition.lookup( resultDN );
<add> Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
<ide> Normalizer normalizer = factory.getNormalizer( attrs, targetRegistries );
<ide> NormalizerDescription normalizerDescription = getNormalizerDescription( schema.getSchemaName(), attrs );
<ide> targetRegistries.getNormalizerRegistry().register( normalizerDescription, normalizer );
<ide> SearchResult result = ( SearchResult ) list.next();
<ide> LdapDN resultDN = new LdapDN( result.getName() );
<ide> resultDN.normalize( attrRegistry.getNormalizerMapping() );
<del> Attributes attrs = partition.lookup( resultDN );
<add> Attributes attrs = partition.lookup( new LookupServiceContext( resultDN ) );
<ide> Comparator comparator = factory.getComparator( attrs, targetRegistries );
<ide> ComparatorDescription comparatorDescription = getComparatorDescription( schema.getSchemaName(), attrs );
<ide> targetRegistries.getComparatorRegistry().register( comparatorDescription, comparator ); |
|
Java | apache-2.0 | 0542f18274a5ebb012bb73644b354cc261c247ae | 0 | cheetah100/jackrabbit-ocm,Yavin/ocm | /*
* 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.jackrabbit.ocm.mapper.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jackrabbit.ocm.exception.JcrMappingException;
import org.apache.jackrabbit.ocm.reflection.ReflectionUtils;
/**
*
* ClassDescriptor is used by the mapper to read general information on a class
*
* @author <a href="mailto:[email protected]">Lombart Christophe </a>
* @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>
*/
public class ClassDescriptor {
private static final Log log = LogFactory.getLog(ClassDescriptor.class);
private static final String NODETYPE_PER_HIERARCHY = "nodetypeperhierarchy";
private static final String NODETYPE_PER_CONCRETECLASS = "nodetypeperconcreteclass";
private MappingDescriptor mappingDescriptor;
private ClassDescriptor superClassDescriptor;
private Collection descendantClassDescriptors = new ArrayList();
private String className;
private String jcrType;
private String jcrSuperTypes;
private String[] jcrMixinTypes = new String[0];
private FieldDescriptor idFieldDescriptor;
private FieldDescriptor pathFieldDescriptor;
private FieldDescriptor uuidFieldDescriptor;
private Map fieldDescriptors = new HashMap();
private Map beanDescriptors = new HashMap();
private Map collectionDescriptors = new HashMap();
private Map fieldNames = new HashMap();
private String superClassName;
private String extendsStrategy;
private boolean isAbstract = false;
private boolean hasDescendant = false;
private boolean hasDiscriminator = true;
private boolean isInterface=false;
private List interfaces = new ArrayList();
public void setAbstract(boolean flag) {
this.isAbstract = flag;
}
public boolean isAbstract() {
return this.isAbstract;
}
public void setInterface(boolean flag) {
this.isInterface = flag;
}
public boolean isInterface() {
return isInterface;
}
public boolean hasInterfaces()
{
return this.interfaces.size() > 0;
}
public void setDiscriminator(boolean flag)
{
this.hasDiscriminator = flag;
}
public boolean hasDiscriminator() {
return this.hasDiscriminator;
}
public boolean usesNodeTypePerHierarchyStrategy() {
return NODETYPE_PER_HIERARCHY.equals(this.extendsStrategy);
}
public boolean usesNodeTypePerConcreteClassStrategy() {
return NODETYPE_PER_CONCRETECLASS.equals(this.extendsStrategy);
}
/**
* @return Returns the className.
*/
public String getClassName() {
return className;
}
/**
* @param className The className to set.
*/
public void setClassName(String className) {
this.className = className;
}
/**
* @return Returns the jcrType.
*/
public String getJcrType() {
return jcrType;
}
/**
* @param jcrType The jcrType to set.
*/
public void setJcrType(String jcrType) {
if (jcrType != null && ! jcrType.equals(""))
{
this.jcrType = jcrType;
}
}
/**
* Add a new FielDescriptor
* @param fieldDescriptor the new field descriptor to add
*/
public void addFieldDescriptor(FieldDescriptor fieldDescriptor) {
fieldDescriptor.setClassDescriptor(this);
if (fieldDescriptor.isId()) {
this.idFieldDescriptor = fieldDescriptor;
}
if (fieldDescriptor.isPath()) {
this.pathFieldDescriptor = fieldDescriptor;
}
if (fieldDescriptor.isUuid()) {
this.uuidFieldDescriptor = fieldDescriptor;
}
fieldDescriptors.put(fieldDescriptor.getFieldName(), fieldDescriptor);
fieldNames.put(fieldDescriptor.getFieldName(), fieldDescriptor.getJcrName());
}
public void addImplementDescriptor(ImplementDescriptor implementDescriptor)
{
interfaces.add(implementDescriptor.getInterfaceName());
}
/**
* Get the FieldDescriptor to used for a specific java bean attribute
* @param fieldName The java bean attribute name
*
* @return the {@link FieldDescriptor} found or null
*/
public FieldDescriptor getFieldDescriptor(String fieldName) {
return (FieldDescriptor) this.fieldDescriptors.get(fieldName);
}
/**
*
* @return all {@link FieldDescriptor} defined in this ClassDescriptor
*/
public Collection getFieldDescriptors() {
return this.fieldDescriptors.values();
}
/**
* Add a new BeanDescriptor
* @param beanDescriptor the new bean descriptor to add
*/
public void addBeanDescriptor(BeanDescriptor beanDescriptor) {
beanDescriptor.setClassDescriptor(this);
beanDescriptors.put(beanDescriptor.getFieldName(), beanDescriptor);
fieldNames.put(beanDescriptor.getFieldName(), beanDescriptor.getJcrName());
}
/**
* Get the BeanDescriptor to used for a specific java bean attribute
* @param fieldName The java bean attribute name
*
* @return the {@link BeanDescriptor} found or null
*/
public BeanDescriptor getBeanDescriptor(String fieldName) {
return (BeanDescriptor) this.beanDescriptors.get(fieldName);
}
/**
* @return all {@link BeanDescriptor} defined in this ClassDescriptor
*/
public Collection getBeanDescriptors() {
return this.beanDescriptors.values();
}
/**
* Add a new CollectionDescriptor
* @param collectionDescriptor the new collection descriptor to add
*/
public void addCollectionDescriptor(CollectionDescriptor collectionDescriptor) {
collectionDescriptor.setClassDescriptor(this);
collectionDescriptors.put(collectionDescriptor.getFieldName(), collectionDescriptor);
fieldNames.put(collectionDescriptor.getFieldName(), collectionDescriptor.getJcrName());
}
/**
* Get the CollectionDescriptor to used for a specific java bean attribute
* @param fieldName The java bean attribute name
*
* @return the {@link CollectionDescriptor} found or null
*/
public CollectionDescriptor getCollectionDescriptor(String fieldName) {
return (CollectionDescriptor) this.collectionDescriptors.get(fieldName);
}
/**
* @return all {@link BeanDescriptor} defined in this ClassDescriptor
*/
public Collection getCollectionDescriptors() {
return this.collectionDescriptors.values();
}
/**
* @return the fieldDescriptor ID
*/
public FieldDescriptor getIdFieldDescriptor() {
if (null != this.idFieldDescriptor) {
return this.idFieldDescriptor;
}
if (null != this.superClassDescriptor) {
return this.superClassDescriptor.getIdFieldDescriptor();
}
return null;
}
/**
* @return the fieldDescriptor path
*/
public FieldDescriptor getPathFieldDescriptor() {
if (null != this.pathFieldDescriptor) {
return this.pathFieldDescriptor;
}
if (null != this.superClassDescriptor) {
return this.superClassDescriptor.getPathFieldDescriptor();
}
return null;
}
/**
* @return the fieldDescriptor path
*/
public FieldDescriptor getUuidFieldDescriptor() {
if (null != this.uuidFieldDescriptor) {
return this.uuidFieldDescriptor;
}
if (null != this.superClassDescriptor) {
return this.superClassDescriptor.getUuidFieldDescriptor();
}
return null;
}
/**
* Check if this class has an ID
* @return true if the class has an ID
*/
public boolean hasIdField() {
return (this.idFieldDescriptor != null && ! this.idFieldDescriptor.equals(""));
}
/**
* Get the JCR name used for one of the object attributes
* @param fieldName the object attribute name (can be an atomic field, bean field or a collection field)
* @return the JCR name found
*/
public String getJcrName(String fieldName) {
String jcrName = (String) this.fieldNames.get(fieldName);
if (this.isInterface && jcrName == null)
{
return this.getJcrNameFromDescendants(this, fieldName);
}
return jcrName;
}
private String getJcrNameFromDescendants(ClassDescriptor classDescriptor, String fieldName )
{
Iterator descendants = classDescriptor.getDescendantClassDescriptors().iterator();
while (descendants.hasNext())
{
ClassDescriptor descendant = (ClassDescriptor) descendants.next();
String jcrName = (String) descendant.fieldNames.get(fieldName);
if(jcrName != null)
{
return jcrName;
}
return this.getJcrNameFromDescendants(descendant, fieldName);
}
return null;
}
public Map getFieldNames() {
return this.fieldNames;
}
/** Get the JCR node super types.
*
* @return jcrSuperTypes
*/
public String getJcrSuperTypes() {
return jcrSuperTypes;
}
/** Setter for JCR super types.
*
* @param superTypes Comma separated list of JCR node super types
*/
public void setJcrSuperTypes(String superTypes) {
if (superTypes != null && ! superTypes.equals(""))
{
this.jcrSuperTypes = superTypes;
}
}
/**
* Retrieve the mixin types.
*
* @return array of mixin types
*/
public String[] getJcrMixinTypes() {
return this.jcrMixinTypes;
}
/**
* Sets a comma separated list of mixin types.
*
* @param mixinTypes command separated list of mixins
*/
public void setJcrMixinTypes(String[] mixinTypes) {
if (null != mixinTypes && mixinTypes.length == 1) {
jcrMixinTypes = mixinTypes[0].split(" *, *");
}
}
public void setJcrMixinTypes(String mixinTypes) {
if (mixinTypes != null && ! mixinTypes.equals(""))
{
jcrMixinTypes = mixinTypes.split(" *, *");
}
}
/**
* @return Returns the mappingDescriptor.
*/
public MappingDescriptor getMappingDescriptor() {
return mappingDescriptor;
}
/**
* @param mappingDescriptor The mappingDescriptor to set.
*/
public void setMappingDescriptor(MappingDescriptor mappingDescriptor) {
this.mappingDescriptor = mappingDescriptor;
}
/**
* Revisit information in this descriptor and fills in more.
*/
public void afterPropertiesSet() {
validateClassName();
lookupSuperDescriptor();
lookupInheritanceSettings();
}
private void validateClassName() {
try {
ReflectionUtils.forName(this.className);
} catch (JcrMappingException e) {
throw new JcrMappingException("Class used in descriptor not found : " + className);
}
}
private void lookupSuperDescriptor() {
if (null != superClassDescriptor) {
this.hasDiscriminator = superClassDescriptor.hasDiscriminator();
if (! this.isInterface)
{
this.fieldDescriptors = mergeFields(this.fieldDescriptors, this.superClassDescriptor.getFieldDescriptors());
this.beanDescriptors = mergeBeans(this.beanDescriptors, this.superClassDescriptor.getBeanDescriptors());
this.collectionDescriptors = mergeCollections(this.collectionDescriptors, this.superClassDescriptor.getCollectionDescriptors());
this.fieldNames.putAll(this.superClassDescriptor.getFieldNames());
}
}
}
private void lookupInheritanceSettings() {
if ((null != this.superClassDescriptor) || (this.hasDescendants()) || this.hasInterfaces()) {
if (this.hasDiscriminator()) {
this.extendsStrategy = NODETYPE_PER_HIERARCHY;
}
else {
this.extendsStrategy = NODETYPE_PER_CONCRETECLASS;
}
}
}
/**
* @return return the super class name if defined in mapping, or
* <tt>null</tt> if not set
*/
public String getExtend() {
return this.superClassName;
}
/**
* @param className
*/
public void setExtend(String className) {
if (className != null && className.length() == 0) {
className = null;
}
this.superClassName = className;
}
/**
* @return Returns the superClassDescriptor.
*/
public ClassDescriptor getSuperClassDescriptor() {
return superClassDescriptor;
}
public Collection getDescendantClassDescriptors() {
return this.descendantClassDescriptors;
}
/**
* If the node type per concrete class strategy is used, we need to find a descendant class descriptor assigned to a node type
* This method is not used in other situation.
*
* @param nodeType the node type for which the classdescriptor is required
* @return the classdescriptor found or null
*
* @todo : maybe we have to review this implementation to have better performance.
*/
public ClassDescriptor getDescendantClassDescriptor(String nodeType) {
Iterator iterator = this.descendantClassDescriptors.iterator();
while (iterator.hasNext()) {
ClassDescriptor descendantClassDescriptor = (ClassDescriptor) iterator.next();
if (nodeType.equals(descendantClassDescriptor.getJcrType())) {
return descendantClassDescriptor;
}
if (descendantClassDescriptor.hasDescendants()) {
ClassDescriptor classDescriptor = descendantClassDescriptor.getDescendantClassDescriptor(nodeType);
if (classDescriptor != null) {
return classDescriptor;
}
}
}
return null;
}
public void addDescendantClassDescriptor(ClassDescriptor classDescriptor) {
this.descendantClassDescriptors.add(classDescriptor);
this.hasDescendant = true;
}
public boolean hasDescendants() {
return this.hasDescendant;
}
/**
* @param superClassDescriptor The superClassDescriptor to set.
*/
public void setSuperClassDescriptor(ClassDescriptor superClassDescriptor) {
this.superClassDescriptor= superClassDescriptor;
superClassDescriptor.addDescendantClassDescriptor(this);
}
public Collection getImplements()
{
return interfaces;
}
private Map mergeFields(Map existing, Collection superSource) {
if (null == superSource) {
return existing;
}
Map merged = new HashMap(existing);
for(Iterator it = superSource.iterator(); it.hasNext();) {
FieldDescriptor fieldDescriptor = (FieldDescriptor) it.next();
if (!merged.containsKey(fieldDescriptor.getFieldName())) {
merged.put(fieldDescriptor.getFieldName(), fieldDescriptor);
}
// else {
// log.warn("Field name conflict in " + this.className + " - field : " +fieldDescriptor.getFieldName() + " - this field name is also defined in the ancestor class : " + this.getExtend());
// }
}
return merged;
}
private Map mergeBeans(Map existing, Collection superSource) {
if (null == superSource) {
return existing;
}
Map merged = new HashMap(existing);
for(Iterator it = superSource.iterator(); it.hasNext();) {
BeanDescriptor beanDescriptor = (BeanDescriptor) it.next();
if (!merged.containsKey(beanDescriptor.getFieldName())) {
merged.put(beanDescriptor.getFieldName(), beanDescriptor);
}
// else {
// log.warn("Bean name conflict in " + this.className + " - field : " +beanDescriptor.getFieldName() + " - this field name is also defined in the ancestor class : " + this.getExtend());
// }
}
return merged;
}
private Map mergeCollections(Map existing, Collection superSource) {
if (null == superSource) {
return existing;
}
Map merged = new HashMap(existing);
for(Iterator it = superSource.iterator(); it.hasNext();) {
CollectionDescriptor collectionDescriptor = (CollectionDescriptor) it.next();
if (!merged.containsKey(collectionDescriptor.getFieldName())) {
merged.put(collectionDescriptor.getFieldName(), collectionDescriptor);
}
}
return merged;
}
public String toString() {
return "Class Descriptor : " + this.getClassName();
}
} | src/main/java/org/apache/jackrabbit/ocm/mapper/model/ClassDescriptor.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.jackrabbit.ocm.mapper.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jackrabbit.ocm.exception.JcrMappingException;
import org.apache.jackrabbit.ocm.reflection.ReflectionUtils;
/**
*
* ClassDescriptor is used by the mapper to read general information on a class
*
* @author <a href="mailto:[email protected]">Lombart Christophe </a>
* @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>
*/
public class ClassDescriptor {
private static final Log log = LogFactory.getLog(ClassDescriptor.class);
private static final String NODETYPE_PER_HIERARCHY = "nodetypeperhierarchy";
private static final String NODETYPE_PER_CONCRETECLASS = "nodetypeperconcreteclass";
private MappingDescriptor mappingDescriptor;
private ClassDescriptor superClassDescriptor;
private Collection descendantClassDescriptors = new ArrayList();
private String className;
private String jcrType;
private String jcrSuperTypes;
private String[] jcrMixinTypes = new String[0];
private FieldDescriptor idFieldDescriptor;
private FieldDescriptor pathFieldDescriptor;
private FieldDescriptor uuidFieldDescriptor;
private Map fieldDescriptors = new HashMap();
private Map beanDescriptors = new HashMap();
private Map collectionDescriptors = new HashMap();
private Map fieldNames = new HashMap();
private String superClassName;
private String extendsStrategy;
private boolean isAbstract = false;
private boolean hasDescendant = false;
private boolean hasDiscriminator = true;
private boolean isInterface=false;
private List interfaces = new ArrayList();
public void setAbstract(boolean flag) {
this.isAbstract = flag;
}
public boolean isAbstract() {
return this.isAbstract;
}
public void setInterface(boolean flag) {
this.isInterface = flag;
}
public boolean isInterface() {
return isInterface;
}
public boolean hasInterfaces()
{
return this.interfaces.size() > 0;
}
public void setDiscriminator(boolean flag)
{
this.hasDiscriminator = flag;
}
public boolean hasDiscriminator() {
return this.hasDiscriminator;
}
public boolean usesNodeTypePerHierarchyStrategy() {
return NODETYPE_PER_HIERARCHY.equals(this.extendsStrategy);
}
public boolean usesNodeTypePerConcreteClassStrategy() {
return NODETYPE_PER_CONCRETECLASS.equals(this.extendsStrategy);
}
/**
* @return Returns the className.
*/
public String getClassName() {
return className;
}
/**
* @param className The className to set.
*/
public void setClassName(String className) {
this.className = className;
}
/**
* @return Returns the jcrType.
*/
public String getJcrType() {
return jcrType;
}
/**
* @param jcrType The jcrType to set.
*/
public void setJcrType(String jcrType) {
if (jcrType != null && ! jcrType.equals(""))
{
this.jcrType = jcrType;
}
}
/**
* Add a new FielDescriptor
* @param fieldDescriptor the new field descriptor to add
*/
public void addFieldDescriptor(FieldDescriptor fieldDescriptor) {
fieldDescriptor.setClassDescriptor(this);
if (fieldDescriptor.isId()) {
this.idFieldDescriptor = fieldDescriptor;
}
if (fieldDescriptor.isPath()) {
this.pathFieldDescriptor = fieldDescriptor;
}
if (fieldDescriptor.isUuid()) {
this.uuidFieldDescriptor = fieldDescriptor;
}
fieldDescriptors.put(fieldDescriptor.getFieldName(), fieldDescriptor);
fieldNames.put(fieldDescriptor.getFieldName(), fieldDescriptor.getJcrName());
}
public void addImplementDescriptor(ImplementDescriptor implementDescriptor)
{
interfaces.add(implementDescriptor.getInterfaceName());
}
/**
* Get the FieldDescriptor to used for a specific java bean attribute
* @param fieldName The java bean attribute name
*
* @return the {@link FieldDescriptor} found or null
*/
public FieldDescriptor getFieldDescriptor(String fieldName) {
return (FieldDescriptor) this.fieldDescriptors.get(fieldName);
}
/**
*
* @return all {@link FieldDescriptor} defined in this ClassDescriptor
*/
public Collection getFieldDescriptors() {
return this.fieldDescriptors.values();
}
/**
* Add a new BeanDescriptor
* @param beanDescriptor the new bean descriptor to add
*/
public void addBeanDescriptor(BeanDescriptor beanDescriptor) {
beanDescriptor.setClassDescriptor(this);
beanDescriptors.put(beanDescriptor.getFieldName(), beanDescriptor);
fieldNames.put(beanDescriptor.getFieldName(), beanDescriptor.getJcrName());
}
/**
* Get the BeanDescriptor to used for a specific java bean attribute
* @param fieldName The java bean attribute name
*
* @return the {@link BeanDescriptor} found or null
*/
public BeanDescriptor getBeanDescriptor(String fieldName) {
return (BeanDescriptor) this.beanDescriptors.get(fieldName);
}
/**
* @return all {@link BeanDescriptor} defined in this ClassDescriptor
*/
public Collection getBeanDescriptors() {
return this.beanDescriptors.values();
}
/**
* Add a new CollectionDescriptor
* @param collectionDescriptor the new collection descriptor to add
*/
public void addCollectionDescriptor(CollectionDescriptor collectionDescriptor) {
collectionDescriptor.setClassDescriptor(this);
collectionDescriptors.put(collectionDescriptor.getFieldName(), collectionDescriptor);
fieldNames.put(collectionDescriptor.getFieldName(), collectionDescriptor.getJcrName());
}
/**
* Get the CollectionDescriptor to used for a specific java bean attribute
* @param fieldName The java bean attribute name
*
* @return the {@link CollectionDescriptor} found or null
*/
public CollectionDescriptor getCollectionDescriptor(String fieldName) {
return (CollectionDescriptor) this.collectionDescriptors.get(fieldName);
}
/**
* @return all {@link BeanDescriptor} defined in this ClassDescriptor
*/
public Collection getCollectionDescriptors() {
return this.collectionDescriptors.values();
}
/**
* @return the fieldDescriptor ID
*/
public FieldDescriptor getIdFieldDescriptor() {
return idFieldDescriptor;
}
/**
* @return the fieldDescriptor path
*/
public FieldDescriptor getPathFieldDescriptor() {
if (null != this.pathFieldDescriptor) {
return this.pathFieldDescriptor;
}
if (null != this.superClassDescriptor) {
return this.superClassDescriptor.getPathFieldDescriptor();
}
return null;
}
/**
* @return the fieldDescriptor path
*/
public FieldDescriptor getUuidFieldDescriptor() {
if (null != this.uuidFieldDescriptor) {
return this.uuidFieldDescriptor;
}
if (null != this.superClassDescriptor) {
return this.superClassDescriptor.getUuidFieldDescriptor();
}
return null;
}
/**
* Check if this class has an ID
* @return true if the class has an ID
*/
public boolean hasIdField() {
return (this.idFieldDescriptor != null && ! this.idFieldDescriptor.equals(""));
}
/**
* Get the JCR name used for one of the object attributes
* @param fieldName the object attribute name (can be an atomic field, bean field or a collection field)
* @return the JCR name found
*/
public String getJcrName(String fieldName) {
String jcrName = (String) this.fieldNames.get(fieldName);
if (this.isInterface && jcrName == null)
{
return this.getJcrNameFromDescendants(this, fieldName);
}
return jcrName;
}
private String getJcrNameFromDescendants(ClassDescriptor classDescriptor, String fieldName )
{
Iterator descendants = classDescriptor.getDescendantClassDescriptors().iterator();
while (descendants.hasNext())
{
ClassDescriptor descendant = (ClassDescriptor) descendants.next();
String jcrName = (String) descendant.fieldNames.get(fieldName);
if(jcrName != null)
{
return jcrName;
}
return this.getJcrNameFromDescendants(descendant, fieldName);
}
return null;
}
public Map getFieldNames() {
return this.fieldNames;
}
/** Get the JCR node super types.
*
* @return jcrSuperTypes
*/
public String getJcrSuperTypes() {
return jcrSuperTypes;
}
/** Setter for JCR super types.
*
* @param superTypes Comma separated list of JCR node super types
*/
public void setJcrSuperTypes(String superTypes) {
if (superTypes != null && ! superTypes.equals(""))
{
this.jcrSuperTypes = superTypes;
}
}
/**
* Retrieve the mixin types.
*
* @return array of mixin types
*/
public String[] getJcrMixinTypes() {
return this.jcrMixinTypes;
}
/**
* Sets a comma separated list of mixin types.
*
* @param mixinTypes command separated list of mixins
*/
public void setJcrMixinTypes(String[] mixinTypes) {
if (null != mixinTypes && mixinTypes.length == 1) {
jcrMixinTypes = mixinTypes[0].split(" *, *");
}
}
public void setJcrMixinTypes(String mixinTypes) {
if (mixinTypes != null && ! mixinTypes.equals(""))
{
jcrMixinTypes = mixinTypes.split(" *, *");
}
}
/**
* @return Returns the mappingDescriptor.
*/
public MappingDescriptor getMappingDescriptor() {
return mappingDescriptor;
}
/**
* @param mappingDescriptor The mappingDescriptor to set.
*/
public void setMappingDescriptor(MappingDescriptor mappingDescriptor) {
this.mappingDescriptor = mappingDescriptor;
}
/**
* Revisit information in this descriptor and fills in more.
*/
public void afterPropertiesSet() {
validateClassName();
lookupSuperDescriptor();
lookupInheritanceSettings();
}
private void validateClassName() {
try {
ReflectionUtils.forName(this.className);
} catch (JcrMappingException e) {
throw new JcrMappingException("Class used in descriptor not found : " + className);
}
}
private void lookupSuperDescriptor() {
if (null != superClassDescriptor) {
this.hasDiscriminator = superClassDescriptor.hasDiscriminator();
if (! this.isInterface)
{
this.fieldDescriptors = mergeFields(this.fieldDescriptors, this.superClassDescriptor.getFieldDescriptors());
this.beanDescriptors = mergeBeans(this.beanDescriptors, this.superClassDescriptor.getBeanDescriptors());
this.collectionDescriptors = mergeCollections(this.collectionDescriptors, this.superClassDescriptor.getCollectionDescriptors());
this.fieldNames.putAll(this.superClassDescriptor.getFieldNames());
}
}
}
private void lookupInheritanceSettings() {
if ((null != this.superClassDescriptor) || (this.hasDescendants()) || this.hasInterfaces()) {
if (this.hasDiscriminator()) {
this.extendsStrategy = NODETYPE_PER_HIERARCHY;
}
else {
this.extendsStrategy = NODETYPE_PER_CONCRETECLASS;
}
}
}
/**
* @return return the super class name if defined in mapping, or
* <tt>null</tt> if not set
*/
public String getExtend() {
return this.superClassName;
}
/**
* @param className
*/
public void setExtend(String className) {
if (className != null && className.length() == 0) {
className = null;
}
this.superClassName = className;
}
/**
* @return Returns the superClassDescriptor.
*/
public ClassDescriptor getSuperClassDescriptor() {
return superClassDescriptor;
}
public Collection getDescendantClassDescriptors() {
return this.descendantClassDescriptors;
}
/**
* If the node type per concrete class strategy is used, we need to find a descendant class descriptor assigned to a node type
* This method is not used in other situation.
*
* @param nodeType the node type for which the classdescriptor is required
* @return the classdescriptor found or null
*
* @todo : maybe we have to review this implementation to have better performance.
*/
public ClassDescriptor getDescendantClassDescriptor(String nodeType) {
Iterator iterator = this.descendantClassDescriptors.iterator();
while (iterator.hasNext()) {
ClassDescriptor descendantClassDescriptor = (ClassDescriptor) iterator.next();
if (nodeType.equals(descendantClassDescriptor.getJcrType())) {
return descendantClassDescriptor;
}
if (descendantClassDescriptor.hasDescendants()) {
ClassDescriptor classDescriptor = descendantClassDescriptor.getDescendantClassDescriptor(nodeType);
if (classDescriptor != null) {
return classDescriptor;
}
}
}
return null;
}
public void addDescendantClassDescriptor(ClassDescriptor classDescriptor) {
this.descendantClassDescriptors.add(classDescriptor);
this.hasDescendant = true;
}
public boolean hasDescendants() {
return this.hasDescendant;
}
/**
* @param superClassDescriptor The superClassDescriptor to set.
*/
public void setSuperClassDescriptor(ClassDescriptor superClassDescriptor) {
this.superClassDescriptor= superClassDescriptor;
superClassDescriptor.addDescendantClassDescriptor(this);
}
public Collection getImplements()
{
return interfaces;
}
private Map mergeFields(Map existing, Collection superSource) {
if (null == superSource) {
return existing;
}
Map merged = new HashMap(existing);
for(Iterator it = superSource.iterator(); it.hasNext();) {
FieldDescriptor fieldDescriptor = (FieldDescriptor) it.next();
if (!merged.containsKey(fieldDescriptor.getFieldName())) {
merged.put(fieldDescriptor.getFieldName(), fieldDescriptor);
}
// else {
// log.warn("Field name conflict in " + this.className + " - field : " +fieldDescriptor.getFieldName() + " - this field name is also defined in the ancestor class : " + this.getExtend());
// }
}
return merged;
}
private Map mergeBeans(Map existing, Collection superSource) {
if (null == superSource) {
return existing;
}
Map merged = new HashMap(existing);
for(Iterator it = superSource.iterator(); it.hasNext();) {
BeanDescriptor beanDescriptor = (BeanDescriptor) it.next();
if (!merged.containsKey(beanDescriptor.getFieldName())) {
merged.put(beanDescriptor.getFieldName(), beanDescriptor);
}
// else {
// log.warn("Bean name conflict in " + this.className + " - field : " +beanDescriptor.getFieldName() + " - this field name is also defined in the ancestor class : " + this.getExtend());
// }
}
return merged;
}
private Map mergeCollections(Map existing, Collection superSource) {
if (null == superSource) {
return existing;
}
Map merged = new HashMap(existing);
for(Iterator it = superSource.iterator(); it.hasNext();) {
CollectionDescriptor collectionDescriptor = (CollectionDescriptor) it.next();
if (!merged.containsKey(collectionDescriptor.getFieldName())) {
merged.put(collectionDescriptor.getFieldName(), collectionDescriptor);
}
}
return merged;
}
public String toString() {
return "Class Descriptor : " + this.getClassName();
}
} | Patch applied for JCR-1316
git-svn-id: 93a7552841ba555a21ad5dc8739eae854af6e0ca@616083 13f79535-47bb-0310-9956-ffa450edef68
| src/main/java/org/apache/jackrabbit/ocm/mapper/model/ClassDescriptor.java | Patch applied for JCR-1316 | <ide><path>rc/main/java/org/apache/jackrabbit/ocm/mapper/model/ClassDescriptor.java
<ide> * @return the fieldDescriptor ID
<ide> */
<ide> public FieldDescriptor getIdFieldDescriptor() {
<del> return idFieldDescriptor;
<add> if (null != this.idFieldDescriptor) {
<add> return this.idFieldDescriptor;
<add> }
<add>
<add> if (null != this.superClassDescriptor) {
<add> return this.superClassDescriptor.getIdFieldDescriptor();
<add> }
<add>
<add> return null;
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | 1fdfaa36b67f3573592d4e5d0794ae581f6fd218 | 0 | streamsets/datacollector,SandishKumarHN/datacollector,kunickiaj/datacollector,SandishKumarHN/datacollector,SandishKumarHN/datacollector,streamsets/datacollector,rockmkd/datacollector,rockmkd/datacollector,kunickiaj/datacollector,kunickiaj/datacollector,rockmkd/datacollector,streamsets/datacollector,SandishKumarHN/datacollector,rockmkd/datacollector,rockmkd/datacollector,streamsets/datacollector,kunickiaj/datacollector,kunickiaj/datacollector,streamsets/datacollector,SandishKumarHN/datacollector | /*
* Copyright 2017 StreamSets 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.streamsets.pipeline.kafka.api;
import com.google.common.collect.ImmutableSet;
import com.streamsets.pipeline.api.impl.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ServiceLoader;
import java.util.Set;
public abstract class FactoriesBean {
private static final Logger LOG = LoggerFactory.getLogger(FactoriesBean.class);
public abstract SdcKafkaProducerFactory createSdcKafkaProducerFactory();
public abstract SdcKafkaValidationUtilFactory createSdcKafkaValidationUtilFactory();
public abstract SdcKafkaConsumerFactory createSdcKafkaConsumerFactory();
public abstract SdcKafkaLowLevelConsumerFactory createSdcKafkaLowLevelConsumerFactory();
private static ServiceLoader<FactoriesBean> factoriesBeanLoader = ServiceLoader.load(FactoriesBean.class);
private static FactoriesBean factoriesBean;
private final static Set<String> subclassNames = ImmutableSet.of(
"com.streamsets.pipeline.kafka.impl.Kafka10FactoriesBean",
"com.streamsets.pipeline.kafka.impl.Kafka11FactoriesBean",
"com.streamsets.pipeline.kafka.impl.Kafka1_0FactoriesBean"
);
static {
int serviceCount = 0;
FactoriesBean subclassBean = null;
for (FactoriesBean bean : factoriesBeanLoader) {
LOG.info("Found FactoriesBean loader {}", bean.getClass().getName());
factoriesBean = bean;
serviceCount++;
if(subclassNames.contains(bean.getClass().getName())) {
if(subclassBean != null) {
throw new RuntimeException(Utils.format("More then one subclass beans found: {}, {}", subclassBean, bean.getClass().getName()));
}
subclassBean = bean;
}
}
if(subclassBean != null) {
factoriesBean = subclassBean;
serviceCount--;
}
if (serviceCount != 1) {
throw new RuntimeException(Utils.format("Unexpected number of FactoriesBean: {} instead of 1", serviceCount));
}
}
public static SdcKafkaProducerFactory getKafkaProducerFactory() {
return factoriesBean.createSdcKafkaProducerFactory();
}
public static SdcKafkaValidationUtilFactory getKafkaValidationUtilFactory() {
return factoriesBean.createSdcKafkaValidationUtilFactory();
}
public static SdcKafkaConsumerFactory getKafkaConsumerFactory() {
return factoriesBean.createSdcKafkaConsumerFactory();
}
public static SdcKafkaLowLevelConsumerFactory getKafkaLowLevelConsumerFactory() {
return factoriesBean.createSdcKafkaLowLevelConsumerFactory();
}
}
| sdc-kafka-api/src/main/java/com/streamsets/pipeline/kafka/api/FactoriesBean.java | /*
* Copyright 2017 StreamSets 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.streamsets.pipeline.kafka.api;
import com.google.common.collect.ImmutableSet;
import com.streamsets.pipeline.api.impl.Utils;
import java.util.ServiceLoader;
import java.util.Set;
public abstract class FactoriesBean {
public abstract SdcKafkaProducerFactory createSdcKafkaProducerFactory();
public abstract SdcKafkaValidationUtilFactory createSdcKafkaValidationUtilFactory();
public abstract SdcKafkaConsumerFactory createSdcKafkaConsumerFactory();
public abstract SdcKafkaLowLevelConsumerFactory createSdcKafkaLowLevelConsumerFactory();
private static ServiceLoader<FactoriesBean> factoriesBeanLoader = ServiceLoader.load(FactoriesBean.class);
private static FactoriesBean factoriesBean;
private final static Set<String> subclassNames = ImmutableSet.of(
"com.streamsets.pipeline.kafka.impl.MapRStreams09FactoriesBean",
"com.streamsets.pipeline.kafka.impl.Kafka10FactoriesBean",
"com.streamsets.pipeline.kafka.impl.Kafka11FactoriesBean",
"com.streamsets.pipeline.kafka.impl.Kafka1_0FactoriesBean"
);
static {
int serviceCount = 0;
FactoriesBean subclassBean = null;
for (FactoriesBean bean : factoriesBeanLoader) {
factoriesBean = bean;
serviceCount++;
if(subclassNames.contains(bean.getClass().getName())) {
if(subclassBean != null) {
throw new RuntimeException(Utils.format("More then one subclass beans found: {}, {}", subclassBean, bean.getClass().getName()));
}
subclassBean = bean;
}
}
if(subclassBean != null) {
factoriesBean = subclassBean;
serviceCount--;
}
if (serviceCount != 1) {
throw new RuntimeException(Utils.format("Unexpected number of FactoriesBean: {} instead of 1", serviceCount));
}
}
public static SdcKafkaProducerFactory getKafkaProducerFactory() {
return factoriesBean.createSdcKafkaProducerFactory();
}
public static SdcKafkaValidationUtilFactory getKafkaValidationUtilFactory() {
return factoriesBean.createSdcKafkaValidationUtilFactory();
}
public static SdcKafkaConsumerFactory getKafkaConsumerFactory() {
return factoriesBean.createSdcKafkaConsumerFactory();
}
public static SdcKafkaLowLevelConsumerFactory getKafkaLowLevelConsumerFactory() {
return factoriesBean.createSdcKafkaLowLevelConsumerFactory();
}
}
| SDC-7871: Increase logging of kafka.FactoriesBean
Adding additional logging for logging what providers were found, extra
helpful when there is more then one. Also removed the MapR specific
class from subclasses this one is not subclass of Kafka09 and hence
doesn't belong to the list.
Change-Id: I736de649321d1a123ddb1445cbc70c1e9d3ddca7
Reviewed-on: https://review.streamsets.net/11370
Reviewed-by: Bob Plotts <[email protected]>
Tested-by: StreamSets CI <[email protected]>
| sdc-kafka-api/src/main/java/com/streamsets/pipeline/kafka/api/FactoriesBean.java | SDC-7871: Increase logging of kafka.FactoriesBean | <ide><path>dc-kafka-api/src/main/java/com/streamsets/pipeline/kafka/api/FactoriesBean.java
<ide>
<ide> import com.google.common.collect.ImmutableSet;
<ide> import com.streamsets.pipeline.api.impl.Utils;
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<add>
<ide> import java.util.ServiceLoader;
<ide> import java.util.Set;
<ide>
<ide> public abstract class FactoriesBean {
<add>
<add> private static final Logger LOG = LoggerFactory.getLogger(FactoriesBean.class);
<ide>
<ide> public abstract SdcKafkaProducerFactory createSdcKafkaProducerFactory();
<ide>
<ide> private static FactoriesBean factoriesBean;
<ide>
<ide> private final static Set<String> subclassNames = ImmutableSet.of(
<del> "com.streamsets.pipeline.kafka.impl.MapRStreams09FactoriesBean",
<ide> "com.streamsets.pipeline.kafka.impl.Kafka10FactoriesBean",
<ide> "com.streamsets.pipeline.kafka.impl.Kafka11FactoriesBean",
<ide> "com.streamsets.pipeline.kafka.impl.Kafka1_0FactoriesBean"
<ide> int serviceCount = 0;
<ide> FactoriesBean subclassBean = null;
<ide> for (FactoriesBean bean : factoriesBeanLoader) {
<add> LOG.info("Found FactoriesBean loader {}", bean.getClass().getName());
<ide> factoriesBean = bean;
<ide> serviceCount++;
<ide> |
|
Java | apache-2.0 | fe2075180635e138e29cc13f7f13ab29afc26dbd | 0 | matyb/roman-numerals | package com.pillar.conversions.romannumerals;
import static org.junit.Assert.assertEquals;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Before;
import org.junit.Test;
import com.pillar.conversions.romannumerals.RomanNumeralsConverter;
public class RomanNumeralsConverterTest {
private Map<String, Integer> cases;
@Before
public void setup() throws Exception {
this.cases = new LinkedHashMap<>();
cases.put("I", 1);
cases.put("III", 3);
cases.put("IX", 9);
cases.put("MLXVI", 1066);
cases.put("CMLXXXIX", 989);
cases.put("MCMLXXXIX", 1989);
}
// TODO: enforce symmetry without testing more than one thing in a method!
@Test
public void testNumberToNumeral() throws Exception {
RomanNumeralsConverter romanNumerals = new RomanNumeralsConverter();
for(Entry<String, Integer> entry : cases.entrySet()){
assertEquals("Converting ARABIC -> ROMAN failed.",
entry.getKey(), romanNumerals.from(entry.getValue()));
}
}
// TODO: enforce symmetry without testing more than one thing in a method!
@Test
public void testNumeralToNumber() throws Exception {
RomanNumeralsConverter romanNumerals = new RomanNumeralsConverter();
for(Entry<String, Integer> entry : cases.entrySet()){
assertEquals("Converting ROMAN -> ARABIC failed.",
entry.getValue(), romanNumerals.to(entry.getKey()));
}
}
}
| src/test/java/com/pillar/conversions/romannumerals/RomanNumeralsConverterTest.java | package com.pillar.conversions.romannumerals;
import static org.junit.Assert.assertEquals;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Before;
import org.junit.Test;
import com.pillar.conversions.romannumerals.RomanNumeralsConverter;
public class RomanNumeralsConverterTest {
private Map<String, Integer> cases;
@Before
public void setup() throws Exception {
this.cases = new LinkedHashMap<>();
cases.put("I", 1);
cases.put("III", 3);
cases.put("IX", 9);
cases.put("MLXVI", 1066);
cases.put("CMLXXXIX", 989);
cases.put("MCMLXXXIX", 1989);
}
/**
* <b>TODO: I KNOW THIS IS GENERALLY A BAD IDEA TO TEST > 1 THING IN ONE
* UNIT TEST! but enforcing symmetry between conversions felt more valuable.<b>
* oh and comments in tests are usually a code smell, but - i wanted to explain.
*/
@Test
public void testNumberToNumeral() throws Exception {
RomanNumeralsConverter romanNumerals = new RomanNumeralsConverter();
for(Entry<String, Integer> entry : cases.entrySet()){
assertEquals(entry.getKey(), romanNumerals.from(entry.getValue()));
}
}
/**
* <b>TODO: I KNOW THIS IS GENERALLY A BAD IDEA TO TEST > 1 THING IN ONE
* UNIT TEST! but enforcing symmetry between conversions felt more valuable.<b>
* oh and comments in tests are usually a code smell, but - i wanted to explain.
*/
@Test
public void testNumeralToNumber() throws Exception {
RomanNumeralsConverter romanNumerals = new RomanNumeralsConverter();
for(Entry<String, Integer> entry : cases.entrySet()){
assertEquals(entry.getValue(), romanNumerals.to(entry.getKey()));
}
}
}
| making comment less dramatic
| src/test/java/com/pillar/conversions/romannumerals/RomanNumeralsConverterTest.java | making comment less dramatic | <ide><path>rc/test/java/com/pillar/conversions/romannumerals/RomanNumeralsConverterTest.java
<ide> cases.put("MCMLXXXIX", 1989);
<ide> }
<ide>
<del> /**
<del> * <b>TODO: I KNOW THIS IS GENERALLY A BAD IDEA TO TEST > 1 THING IN ONE
<del> * UNIT TEST! but enforcing symmetry between conversions felt more valuable.<b>
<del> * oh and comments in tests are usually a code smell, but - i wanted to explain.
<del> */
<add> // TODO: enforce symmetry without testing more than one thing in a method!
<ide> @Test
<ide> public void testNumberToNumeral() throws Exception {
<ide> RomanNumeralsConverter romanNumerals = new RomanNumeralsConverter();
<ide> for(Entry<String, Integer> entry : cases.entrySet()){
<del> assertEquals(entry.getKey(), romanNumerals.from(entry.getValue()));
<add> assertEquals("Converting ARABIC -> ROMAN failed.",
<add> entry.getKey(), romanNumerals.from(entry.getValue()));
<ide> }
<ide> }
<ide>
<del> /**
<del> * <b>TODO: I KNOW THIS IS GENERALLY A BAD IDEA TO TEST > 1 THING IN ONE
<del> * UNIT TEST! but enforcing symmetry between conversions felt more valuable.<b>
<del> * oh and comments in tests are usually a code smell, but - i wanted to explain.
<del> */
<add> // TODO: enforce symmetry without testing more than one thing in a method!
<ide> @Test
<ide> public void testNumeralToNumber() throws Exception {
<ide> RomanNumeralsConverter romanNumerals = new RomanNumeralsConverter();
<ide> for(Entry<String, Integer> entry : cases.entrySet()){
<del> assertEquals(entry.getValue(), romanNumerals.to(entry.getKey()));
<add> assertEquals("Converting ROMAN -> ARABIC failed.",
<add> entry.getValue(), romanNumerals.to(entry.getKey()));
<ide> }
<ide> }
<ide> |
|
JavaScript | artistic-2.0 | e1cc2886a25ae2e4e6aeeefc3c595dfbe40e7fd2 | 0 | cygx/nqp,cygx/nqp,cygx/nqp,cygx/nqp,cygx/nqp,cygx/nqp,cygx/nqp,cygx/nqp | var SerializationContext = require('./serialization-context.js');
var reprs = require('./reprs.js');
var Hash = require('./hash.js');
var STable = require('./sixmodel.js').STable;
var repr = new reprs.KnowHOWREPR();
var core = new SerializationContext('__6MODEL_CORE__');
core.description = 'core SC';
function add_to_sc_with_st(obj) {
core.root_objects.push(obj);
core.root_stables.push(obj._STable);
obj._SC = core;
obj._STable._SC = core;
}
function add_to_sc_with_st_and_mo() {
throw "...";
}
/* Creates and installs the KnowHOWAttribute type. */
function create_KnowHOWAttribute() {
var meta_obj = KnowHOW_HOW._STable.REPR.allocate(KnowHOW_HOW._STable);
var r = new reprs.KnowHOWAttribute();
var type_obj = r.type_object_for(meta_obj);
var methods = {};
methods.name = function() {
return this.__name;
};
methods['new'] = function(ctx, _NAMED) {
var attr = r.allocate(this._STable);
//TODO convert to string
attr.__name = _NAMED.name;
attr.__type = _NAMED.type;
//TODO convert to int
attr.__box_target = _NAMED.box_target ? _NAMED.box_target : 0;
return attr;
};
for (var method in methods) {
type_obj._STable.obj_constructor.prototype[method] = methods[method];
}
return type_obj;
}
/* Create our KnowHOW type object. Note we don't have a HOW just yet, so
* pass in null. */
var KnowHOW = repr.type_object_for(null);
add_to_sc_with_st(KnowHOW);
var st = new STable(repr, null);
var KnowHOW_HOW = repr.allocate(st);
add_to_sc_with_st(KnowHOW_HOW);
KnowHOW_HOW.id = "KnowHOW_HOW";
KnowHOW._STable.id = "KnowHOW";
KnowHOW._STable.HOW = KnowHOW_HOW;
function add_knowhow_how_method(name, method) {
/* TODO - think if setting the object cache would be better */
KnowHOW_HOW._STable.obj_constructor.prototype[name] = method;
KnowHOW._STable.obj_constructor.prototype[name] = method;
}
add_knowhow_how_method("name", function() {
return this.__name;
});
add_knowhow_how_method("attributes", function() {
return this.__attributes;
});
add_knowhow_how_method("methods", function() {
return this.__methods;
});
add_knowhow_how_method("new_type", function(ctx, _NAMED) {
/* We first create a new HOW instance. */
var HOW = this._STable.REPR.allocate(this._STable);
/* See if we have a representation name; if not default to P6opaque. */
var repr_name = _NAMED['repr'] || 'P6opaque';
/* Create a new type object of the desired REPR. (Note that we can't
* default to KnowHOWREPR here, since it doesn't know how to actually
* store attributes, it's just for bootstrapping knowhow's. */
var type_object = (new reprs[repr_name]).type_object_for(HOW);
/* See if we were given a name; put it into the meta-object if so. */
if (_NAMED['name']) {
HOW.__name = _NAMED['name'];
} else {
HOW.__name = null;
}
/* Set .WHO to an empty hash. */
type_object._STable.WHO = new Hash();
return type_object;
});
add_knowhow_how_method("compose", function(ctx, _NAMED, type_object) {
/* Set method cache */
type_object._STable.setMethodCache(this.__methods.content);
/* Set type check cache. */
type_object._STable.type_check_cache = [type_object];
/* Use any attribute information to produce attribute protocol
* data. The protocol consists of an array... */
var repr_info = [];
/* ...which contains an array per MRO entry... */
var type_info = [];
repr_info.push(type_info);
/* ...which in turn contains this type... */
type_info.push(type_object);
/* ...then an array of hashes per attribute... */
var attr_info_list = [];
type_info.push(attr_info_list);
/* ...then an array of hashes per attribute... */
for (var i = 0; i < this.__attributes.length; i++) {
var attr_info = new Hash();
var attr = this.__attributes[i];
attr_info.content.name = attr.__name;
attr_info.content.type = attr.__type;
if (attr.__box_target) {
attr_info.content.box_target = attr.__box_target;
}
attr_info_list.push(attr_info);
}
/* ...followed by a list of parents (none). */
var parent_info = [];
type_info.push(parent_info);
/* All of this goes in a hash. */
var repr_info_hash = new Hash();
repr_info_hash.content.attribute = repr_info;
/* Compose the representation using it. */
type_object._STable.REPR.compose(type_object._STable, repr_info_hash);
return type_info;
});
module.exports.knowhow = KnowHOW;
/* KnowHOW.HOW */
//add_to_sc_with_st(STABLE(tc->instance->KnowHOW)->HOW);
var KnowHOWAttribute = create_KnowHOWAttribute();
module.exports.knowhowattr = KnowHOWAttribute;
/* KnowHOWAttribute */
add_to_sc_with_st(KnowHOWAttribute);
/* BOOT* */
/*add_to_sc_with_st_and_mo(BOOTArray);
add_to_sc_with_st_and_mo(BOOTHash);
add_to_sc_with_st_and_mo(BOOTIter);
add_to_sc_with_st_and_mo(BOOTInt);
add_to_sc_with_st_and_mo(BOOTNum);
add_to_sc_with_st_and_mo(BOOTStr);
add_to_sc_with_st_and_mo(BOOTCode);*/
module.exports.core = core;
| src/vm/js/nqp-runtime/bootstrap.js | var SerializationContext = require('./serialization-context.js');
var reprs = require('./reprs.js');
var Hash = require('./hash.js');
var STable = require('./sixmodel.js').STable;
var repr = new reprs.KnowHOWREPR();
var core = new SerializationContext('__6MODEL_CORE__');
core.description = 'core SC';
function add_to_sc_with_st(obj) {
core.root_objects.push(obj);
core.root_stables.push(obj._STable);
obj._SC = core;
}
function add_to_sc_with_st_and_mo() {
throw "...";
}
/* Creates and installs the KnowHOWAttribute type. */
function create_KnowHOWAttribute() {
var meta_obj = KnowHOW_HOW._STable.REPR.allocate(KnowHOW_HOW._STable);
var r = new reprs.KnowHOWAttribute();
var type_obj = r.type_object_for(meta_obj);
var methods = {};
methods.name = function() {
return this.__name;
};
methods['new'] = function(ctx, _NAMED) {
var attr = r.allocate(this._STable);
//TODO convert to string
attr.__name = _NAMED.name;
attr.__type = _NAMED.type;
//TODO convert to int
attr.__box_target = _NAMED.box_target ? _NAMED.box_target : 0;
return attr;
};
for (var method in methods) {
type_obj._STable.obj_constructor.prototype[method] = methods[method];
}
return type_obj;
}
/* Create our KnowHOW type object. Note we don't have a HOW just yet, so
* pass in null. */
var KnowHOW = repr.type_object_for(null);
add_to_sc_with_st(KnowHOW);
var st = new STable(repr, null);
var KnowHOW_HOW = repr.allocate(st);
add_to_sc_with_st(KnowHOW_HOW);
KnowHOW_HOW.id = "KnowHOW_HOW";
KnowHOW._STable.id = "KnowHOW";
KnowHOW._STable.HOW = KnowHOW_HOW;
function add_knowhow_how_method(name, method) {
/* TODO - think if setting the object cache would be better */
KnowHOW_HOW._STable.obj_constructor.prototype[name] = method;
KnowHOW._STable.obj_constructor.prototype[name] = method;
}
add_knowhow_how_method("name", function() {
return this.__name;
});
add_knowhow_how_method("attributes", function() {
return this.__attributes;
});
add_knowhow_how_method("methods", function() {
return this.__methods;
});
add_knowhow_how_method("new_type", function(ctx, _NAMED) {
/* We first create a new HOW instance. */
var HOW = this._STable.REPR.allocate(this._STable);
/* See if we have a representation name; if not default to P6opaque. */
var repr_name = _NAMED['repr'] || 'P6opaque';
/* Create a new type object of the desired REPR. (Note that we can't
* default to KnowHOWREPR here, since it doesn't know how to actually
* store attributes, it's just for bootstrapping knowhow's. */
var type_object = (new reprs[repr_name]).type_object_for(HOW);
/* See if we were given a name; put it into the meta-object if so. */
if (_NAMED['name']) {
HOW.__name = _NAMED['name'];
} else {
HOW.__name = null;
}
/* Set .WHO to an empty hash. */
type_object._STable.WHO = new Hash();
return type_object;
});
add_knowhow_how_method("compose", function(ctx, _NAMED, type_object) {
/* Set method cache */
type_object._STable.setMethodCache(this.__methods.content);
/* Set type check cache. */
type_object._STable.type_check_cache = [type_object];
/* Use any attribute information to produce attribute protocol
* data. The protocol consists of an array... */
var repr_info = [];
/* ...which contains an array per MRO entry... */
var type_info = [];
repr_info.push(type_info);
/* ...which in turn contains this type... */
type_info.push(type_object);
/* ...then an array of hashes per attribute... */
var attr_info_list = [];
type_info.push(attr_info_list);
/* ...then an array of hashes per attribute... */
for (var i = 0; i < this.__attributes.length; i++) {
var attr_info = new Hash();
var attr = this.__attributes[i];
attr_info.content.name = attr.__name;
attr_info.content.type = attr.__type;
if (attr.__box_target) {
attr_info.content.box_target = attr.__box_target;
}
attr_info_list.push(attr_info);
}
/* ...followed by a list of parents (none). */
var parent_info = [];
type_info.push(parent_info);
/* All of this goes in a hash. */
var repr_info_hash = new Hash();
repr_info_hash.content.attribute = repr_info;
/* Compose the representation using it. */
type_object._STable.REPR.compose(type_object._STable, repr_info_hash);
return type_info;
});
module.exports.knowhow = KnowHOW;
/* KnowHOW.HOW */
//add_to_sc_with_st(STABLE(tc->instance->KnowHOW)->HOW);
var KnowHOWAttribute = create_KnowHOWAttribute();
module.exports.knowhowattr = KnowHOWAttribute;
/* KnowHOWAttribute */
add_to_sc_with_st(KnowHOWAttribute);
/* BOOT* */
/*add_to_sc_with_st_and_mo(BOOTArray);
add_to_sc_with_st_and_mo(BOOTHash);
add_to_sc_with_st_and_mo(BOOTIter);
add_to_sc_with_st_and_mo(BOOTInt);
add_to_sc_with_st_and_mo(BOOTNum);
add_to_sc_with_st_and_mo(BOOTStr);
add_to_sc_with_st_and_mo(BOOTCode);*/
module.exports.core = core;
| [js] fix bootstraping bug
| src/vm/js/nqp-runtime/bootstrap.js | [js] fix bootstraping bug | <ide><path>rc/vm/js/nqp-runtime/bootstrap.js
<ide> core.root_objects.push(obj);
<ide> core.root_stables.push(obj._STable);
<ide> obj._SC = core;
<add> obj._STable._SC = core;
<ide> }
<ide>
<ide> function add_to_sc_with_st_and_mo() { |
|
Java | apache-2.0 | 23b490c1c25088977925a592736e843d366b1398 | 0 | apache/empire-db,apache/empire-db,apache/empire-db,apache/empire-db | /*
* 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.empire.jsf2.pages;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.application.NavigationHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.apache.empire.commons.StringUtils;
import org.apache.empire.db.DBDatabase;
import org.apache.empire.db.DBRowSet;
import org.apache.empire.exceptions.EmpireException;
import org.apache.empire.exceptions.InternalException;
import org.apache.empire.exceptions.ItemNotFoundException;
import org.apache.empire.exceptions.MiscellaneousErrorException;
import org.apache.empire.jsf2.app.FacesApplication;
import org.apache.empire.jsf2.app.FacesUtils;
import org.apache.empire.jsf2.app.TextResolver;
import org.apache.empire.jsf2.utils.ParameterMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class Page implements Serializable
{
private static final long serialVersionUID = 1L;
public static final String SESSION_MESSAGE = "PAGE_SESSION_MESSAGE";
// private static final String INVALID_ACTION = "XXXXXXXXXXXX";
private static final Logger log = LoggerFactory.getLogger(Page.class);
private String action = null;
private boolean initialized = false;
private PageDefinition pageDefinition = null;
private List<PageElement> pageElements = null;
protected Page()
{
if (log.isDebugEnabled())
{ String name = this.getClass().getSimpleName();
Page.log.debug("PageBean {} created.", name);
}
}
public String getPageName()
{
return (pageDefinition != null ? pageDefinition.getPageBeanName() : "{" + getClass().getSimpleName() + "}");
}
public String getName()
{
String className = pageDefinition.getPageBeanClass().getName();
int lastDot = className.lastIndexOf(".");
String name = className.substring(lastDot + 1);
return name;
}
public boolean isInitialized()
{
return initialized;
}
public String getAction()
{
if (this.action==null)
return null;
// if (this.action==INVALID_ACTION)
// return null;
// Generate key
ParameterMap pm = FacesUtils.getParameterMap(FacesUtils.getContext());
String actionParam = (pm!=null ? pm.encodeString(action) : action);
return actionParam;
}
public void setAction(String actionParam)
{
if (!initialized)
Page.log.debug("Setting PageBean action {} for bean {}.", action, getPageName());
else
Page.log.trace("Re-setting PageBeanAction {} for bean {}.", action, getPageName());
// actionParam
if (StringUtils.isEmpty(actionParam))
return;
// Set action from param
this.action = PageDefinition.decodeActionParam(actionParam);
if (this.action==null)
throw new ItemNotFoundException(actionParam);
}
public PageDefinition getPageDefinition()
{
return pageDefinition;
}
public void setPageDefinition(PageDefinition pageDefinition)
{
this.pageDefinition = pageDefinition;
}
public PageDefinition getParentPage()
{
return pageDefinition.getParent();
}
public void preRenderPage(FacesContext context)
{
if (this.initialized)
{
// PageBean.log.error("PageBean {} is already initialized.", name());
try
{
Page.log.debug("PageBean {} is already initialized. Calling doRefresh().", getPageName());
doRefresh();
}
catch (Throwable e)
{
logAndHandleActionException("doRefresh", e);
}
return; // already Initialized
}
// Check access
try
{
checkPageAccess();
}
catch (Throwable e)
{
logAndHandleActionException("checkAccess", e);
// redirected?
if (context.getResponseComplete())
return;
// Oops, not redirected yet?
if (getParentPage()!=null)
navigateTo(getParentOutcome(true));
// Done
return;
}
// Initialize
this.initialized = true;
// String value of "null"?
if (this.action!=null && "null".equals(this.action))
{ log.warn("Invalid action name 'null' for {}", getClass().getName());
this.action = null;
}
// Execute Action
if (this.action != null)
{
/*
if (this.action.equals(Page.INVALID_ACTION))
{
Page.log.error("Action probably executed twice. Ignoring action.");
return;
}
*/
try
{
Page.log.debug("Executing action {} on {}.", String.valueOf(action), getPageName());
Method method = getClass().getMethod(action);
Object result = method.invoke(this);
if (result != null)
{
String outcome = result.toString();
// Retrieve the NavigationHandler instance..
NavigationHandler navHandler = context.getApplication().getNavigationHandler();
// Invoke nav handling..
navHandler.handleNavigation(context, action, outcome);
// Trigger a switch to Render Response if needed
context.renderResponse();
return;
}
restoreSessionMessage();
}
catch (NoSuchMethodException nsme)
{
logAndHandleActionException(action, nsme);
}
catch (Exception e)
{
logAndHandleActionException(action, e.getCause());
}
finally
{
// Clear action
this.action = null; // Page.INVALID_ACTION;
}
}
else
{ // call default Action
try
{
Page.log.debug("Initializing PageBean {}. Calling doInit()", getPageName());
doInit();
restoreSessionMessage();
}
catch (Throwable e)
{
logAndHandleActionException("doInit", e);
}
}
}
protected void checkPageAccess()
{
/* Throw exception if User has no Access */
}
private void restoreSessionMessage()
{
// Restore Session Error Message
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> map = ec.getSessionMap();
if (map.containsKey(SESSION_MESSAGE))
{
FacesMessage errorMsg = (FacesMessage) map.get(SESSION_MESSAGE);
FacesContext.getCurrentInstance().addMessage(getPageName(), errorMsg);
map.remove(SESSION_MESSAGE);
}
}
private void logAndHandleActionException(String action, Throwable e)
{
String msg = "Failed to perform action " + action + " on " + getPageName();
// Message
Page.log.error(msg, e);
if (!handleActionError(action, e))
{ // Not handled. Throw again
if (e instanceof EmpireException)
throw ((EmpireException)e);
else
throw new InternalException(e);
}
}
protected void setSessionMessage(FacesMessage facesMsg)
{
// Set Session Message
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.getSessionMap().put(SESSION_MESSAGE, facesMsg);
}
protected boolean handleActionError(String action, Throwable e)
{
// Set Faces Message
String msg = getErrorMessage(e);
String detail = extractErrorMessageDetail(action, e, 1);
log.error(msg + "\r\n" + detail);
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detail);
setSessionMessage(facesMsg);
// Return to parent page
PageDefinition parentPage = getParentPage();
if (parentPage == null)
{ FacesContext.getCurrentInstance().addMessage(getPageName(), facesMsg);
return false;
}
// redirect
navigateTo(parentPage.getRedirect());
return true;
}
protected void setErrorMessage(Throwable e)
{
String msg = getErrorMessage(e);
String detail = extractErrorMessageDetail(action, e, 1);
if (log.isDebugEnabled())
log.debug(msg + "\r\n" + detail, e);
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detail);
FacesContext.getCurrentInstance().addMessage(getPageName(), facesMsg);
}
protected String getErrorMessage(Throwable e)
{ // Wrap Exception
if (!(e instanceof EmpireException))
e = new InternalException(e);
// get message
return getTextResolver().getExceptionMessage((Exception)e);
}
protected String extractErrorMessageDetail(String action, Throwable e, int stackTraceElements)
{
StringBuilder b = new StringBuilder();
b.append("Error performing action '");
b.append(action);
b.append("' on page ");
b.append(getPageName());
b.append(": ");
b.append(e.toString());
b.append("\r\nat:");
StackTraceElement[] stack = e.getStackTrace();
int len = (stack.length>stackTraceElements) ? stackTraceElements : stack.length;
for (int i=0; i<len; i++)
{
b.append(stack[i].toString());
b.append("\r\n");
}
return b.toString();
}
/**
* navigates to the desired page. Depending on the page outcome provided this is either a forward or a redirect.
* @param outcome the destination page to navigate to
*/
protected void navigateTo(PageOutcome outcome)
{
if (log.isDebugEnabled())
log.debug("Redirecting from page {} to page {}.", getPageName(), outcome.toString());
// Return to Parent
FacesContext context = FacesContext.getCurrentInstance();
// Retrieve the NavigationHandler instance..
NavigationHandler navHandler = context.getApplication().getNavigationHandler();
// Invoke nav handling..
navHandler.handleNavigation(context, action, outcome.toString());
// Trigger a switch to Render Response if needed
context.renderResponse();
}
/**
* adds a page element to this page
* DO NOT CALL yourself, this method is called from the PageElement constructor!
*
* @param element
*/
protected void registerPageElement(PageElement element)
{
if (pageElements == null)
pageElements = new ArrayList<PageElement>(1);
// register now
if (pageElements.contains(element) == false)
pageElements.add(element);
else
log.warn("PageElement {} was registered twice!", element.getPropertyName());
}
/**
* Helper methods for parent outcome
*
* @param action
* @param redirect
* @return the parent outcome string
*/
protected PageOutcome getParentOutcome(String action, boolean redirect)
{
PageDefinition parentPage = getParentPage();
if (parentPage == null)
throw new MiscellaneousErrorException("No Parent Page defined for " + getPageName());
if (redirect)
return parentPage.getRedirect(action);
else
return parentPage.getOutcome(action);
}
protected PageOutcome getParentOutcome(boolean redirect)
{
return getParentOutcome(null, redirect);
}
/**
* return a connection for a particular database
* @param db the database for which to obtain a connection
* @return the connection for the given database
*/
public Connection getConnection(DBDatabase db)
{
FacesApplication app = FacesUtils.getFacesApplication();
return app.getConnectionForRequest(FacesUtils.getContext(), db);
}
public Object[] getKeyFromParam(DBRowSet rowset, String idParam)
{
FacesContext fc = FacesUtils.getContext();
return FacesUtils.getParameterMap(fc).get(rowset, idParam);
}
public String getIdParamForKey(DBRowSet rowset, Object[] key)
{
FacesContext fc = FacesUtils.getContext();
return FacesUtils.getParameterMap(fc).put(rowset, key);
}
public void addJavascriptCall(String function)
{
if (!function.endsWith(";"))
{ // Add a semicolon (important!)
function += ";";
}
// Add Call
FacesContext fc = FacesUtils.getContext();
FacesApplication app = FacesUtils.getFacesApplication();
app.addJavascriptCall(fc, function);
}
/* Page Resources */
/**
* Adds an object required for resource handling, to the page resource map.
* <pre>
* Since resource requests are not attached to a view, they cannot access page properties via expression language like this
* #{page.someProperty}
* Instead, the page should add properties that are required to the "pageResources"-map. This map is held on the session, and cleared when the page changes.
* In order to access such page resources via expression language use
* #{pageResources.someProperty}
* </pre>
* @param name the name of the resource
* @param resource the resource
*/
public void addPageResource(String name, Object resource)
{
Map<String, Object> prm = FacesUtils.getPageResourceMap(FacesUtils.getContext());
prm.put(name, this);
}
/**
* Returns the page resource object previously added by addPageResource(...)
* @param name the name of the resource
* @return resource the resource
*/
public Object getPageResource(String name)
{
Map<String, Object> prm = FacesUtils.getPageResourceMap(FacesUtils.getContext());
return prm.get(name);
}
/* Default Init Method */
public void doInit()
{
if (pageElements != null)
{ // Init Page Elements
for (PageElement pe : pageElements)
doInitElement(pe);
}
}
public void doRefresh()
{
if (pageElements != null)
{ // Refresh Page Elements
for (PageElement pe : pageElements)
doRefreshElement(pe);
}
}
/**
* called by doInit() to initialize a particular page element
* @param pe the page element to initialize
*/
protected void doInitElement(PageElement pe)
{
pe.onInitPage();
}
/**
* called by doRefresh() to refresh a particular page element
* @param pe the page element to refresh
*/
protected void doRefreshElement(PageElement pe)
{
pe.onRefreshPage();
}
/* Helpers */
protected final TextResolver getTextResolver()
{
FacesContext fc = FacesUtils.getContext();
return FacesUtils.getFacesApplication().getTextResolver(fc);
}
}
| empire-db-jsf2/src/main/java/org/apache/empire/jsf2/pages/Page.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.empire.jsf2.pages;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.application.NavigationHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.apache.empire.commons.StringUtils;
import org.apache.empire.db.DBDatabase;
import org.apache.empire.db.DBRowSet;
import org.apache.empire.exceptions.EmpireException;
import org.apache.empire.exceptions.InternalException;
import org.apache.empire.exceptions.ItemNotFoundException;
import org.apache.empire.exceptions.MiscellaneousErrorException;
import org.apache.empire.jsf2.app.FacesApplication;
import org.apache.empire.jsf2.app.FacesUtils;
import org.apache.empire.jsf2.app.TextResolver;
import org.apache.empire.jsf2.utils.ParameterMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class Page implements Serializable
{
private static final long serialVersionUID = 1L;
public static final String SESSION_MESSAGE = "PAGE_SESSION_MESSAGE";
// private static final String INVALID_ACTION = "XXXXXXXXXXXX";
private static final Logger log = LoggerFactory.getLogger(Page.class);
private String action = null;
private boolean initialized = false;
private PageDefinition pageDefinition = null;
private List<PageElement> pageElements = null;
protected Page()
{
if (log.isDebugEnabled())
{ String name = this.getClass().getSimpleName();
Page.log.debug("PageBean {} created.", name);
}
}
public String getPageName()
{
return (pageDefinition != null ? pageDefinition.getPageBeanName() : "{" + getClass().getSimpleName() + "}");
}
public String getName()
{
String className = pageDefinition.getPageBeanClass().getName();
int lastDot = className.lastIndexOf(".");
String name = className.substring(lastDot + 1);
return name;
}
public boolean isInitialized()
{
return initialized;
}
public String getAction()
{
if (this.action==null)
return null;
// if (this.action==INVALID_ACTION)
// return null;
// Generate key
ParameterMap pm = FacesUtils.getParameterMap(FacesUtils.getContext());
String actionParam = (pm!=null ? pm.encodeString(action) : action);
return actionParam;
}
public void setAction(String actionParam)
{
if (!initialized)
Page.log.debug("Setting PageBean action {} for bean {}.", action, getPageName());
else
Page.log.trace("Re-setting PageBeanAction {} for bean {}.", action, getPageName());
// actionParam
if (StringUtils.isEmpty(actionParam))
return;
// Set action from param
this.action = PageDefinition.decodeActionParam(actionParam);
if (this.action==null)
throw new ItemNotFoundException(actionParam);
}
public PageDefinition getPageDefinition()
{
return pageDefinition;
}
public void setPageDefinition(PageDefinition pageDefinition)
{
this.pageDefinition = pageDefinition;
}
public PageDefinition getParentPage()
{
return pageDefinition.getParent();
}
public void preRenderPage(FacesContext context)
{
if (this.initialized)
{
// PageBean.log.error("PageBean {} is already initialized.", name());
try
{
Page.log.debug("PageBean {} is already initialized. Calling doRefresh().", getPageName());
doRefresh();
}
catch (Throwable e)
{
logAndHandleActionException("doRefresh", e);
}
return; // already Initialized
}
// Check access
try
{
checkPageAccess();
}
catch (Throwable e)
{
logAndHandleActionException("checkAccess", e);
// redirected?
if (context.getResponseComplete())
return;
// Oops, not redirected yet?
if (getParentPage()!=null)
redirectTo(getParentOutcome(true));
// Done
return;
}
// Initialize
this.initialized = true;
// String value of "null"?
if (this.action!=null && "null".equals(this.action))
{ log.warn("Invalid action name 'null' for {}", getClass().getName());
this.action = null;
}
// Execute Action
if (this.action != null)
{
/*
if (this.action.equals(Page.INVALID_ACTION))
{
Page.log.error("Action probably executed twice. Ignoring action.");
return;
}
*/
try
{
Page.log.debug("Executing action {} on {}.", String.valueOf(action), getPageName());
Method method = getClass().getMethod(action);
Object result = method.invoke(this);
if (result != null)
{
String outcome = result.toString();
// Retrieve the NavigationHandler instance..
NavigationHandler navHandler = context.getApplication().getNavigationHandler();
// Invoke nav handling..
navHandler.handleNavigation(context, action, outcome);
// Trigger a switch to Render Response if needed
context.renderResponse();
return;
}
restoreSessionMessage();
}
catch (NoSuchMethodException nsme)
{
logAndHandleActionException(action, nsme);
}
catch (Exception e)
{
logAndHandleActionException(action, e.getCause());
}
finally
{
// Clear action
this.action = null; // Page.INVALID_ACTION;
}
}
else
{ // call default Action
try
{
Page.log.debug("Initializing PageBean {}. Calling doInit()", getPageName());
doInit();
restoreSessionMessage();
}
catch (Throwable e)
{
logAndHandleActionException("doInit", e);
}
}
}
protected void checkPageAccess()
{
/* Throw exception if User has no Access */
}
private void restoreSessionMessage()
{
// Restore Session Error Message
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> map = ec.getSessionMap();
if (map.containsKey(SESSION_MESSAGE))
{
FacesMessage errorMsg = (FacesMessage) map.get(SESSION_MESSAGE);
FacesContext.getCurrentInstance().addMessage(getPageName(), errorMsg);
map.remove(SESSION_MESSAGE);
}
}
private void logAndHandleActionException(String action, Throwable e)
{
String msg = "Failed to perform action " + action + " on " + getPageName();
// Message
Page.log.error(msg, e);
if (!handleActionError(action, e))
{ // Not handled. Throw again
if (e instanceof EmpireException)
throw ((EmpireException)e);
else
throw new InternalException(e);
}
}
protected void setSessionMessage(FacesMessage facesMsg)
{
// Set Session Message
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.getSessionMap().put(SESSION_MESSAGE, facesMsg);
}
protected boolean handleActionError(String action, Throwable e)
{
// Set Faces Message
String msg = getErrorMessage(e);
String detail = extractErrorMessageDetail(action, e, 1);
log.error(msg + "\r\n" + detail);
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detail);
setSessionMessage(facesMsg);
// Return to parent page
PageDefinition parentPage = getParentPage();
if (parentPage == null)
{ FacesContext.getCurrentInstance().addMessage(getPageName(), facesMsg);
return false;
}
// redirect
redirectTo(parentPage.getRedirect());
return true;
}
protected void setErrorMessage(Throwable e)
{
String msg = getErrorMessage(e);
String detail = extractErrorMessageDetail(action, e, 1);
if (log.isDebugEnabled())
log.debug(msg + "\r\n" + detail, e);
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detail);
FacesContext.getCurrentInstance().addMessage(getPageName(), facesMsg);
}
protected String getErrorMessage(Throwable e)
{ // Wrap Exception
if (!(e instanceof EmpireException))
e = new InternalException(e);
// get message
return getTextResolver().getExceptionMessage((Exception)e);
}
protected String extractErrorMessageDetail(String action, Throwable e, int stackTraceElements)
{
StringBuilder b = new StringBuilder();
b.append("Error performing action '");
b.append(action);
b.append("' on page ");
b.append(getPageName());
b.append(": ");
b.append(e.toString());
b.append("\r\nat:");
StackTraceElement[] stack = e.getStackTrace();
int len = (stack.length>stackTraceElements) ? stackTraceElements : stack.length;
for (int i=0; i<len; i++)
{
b.append(stack[i].toString());
b.append("\r\n");
}
return b.toString();
}
protected void redirectTo(PageOutcome outcome)
{
if (log.isDebugEnabled())
log.debug("Redirecting from page {} to page {}.", getPageName(), outcome.toString());
// Return to Parent
FacesContext context = FacesContext.getCurrentInstance();
// Retrieve the NavigationHandler instance..
NavigationHandler navHandler = context.getApplication().getNavigationHandler();
// Invoke nav handling..
navHandler.handleNavigation(context, action, outcome.toString());
// Trigger a switch to Render Response if needed
context.renderResponse();
}
/**
* adds a page element to this page
* DO NOT CALL yourself, this method is called from the PageElement constructor!
*
* @param element
*/
protected void registerPageElement(PageElement element)
{
if (pageElements == null)
pageElements = new ArrayList<PageElement>(1);
// register now
if (pageElements.contains(element) == false)
pageElements.add(element);
else
log.warn("PageElement {} was registered twice!", element.getPropertyName());
}
/**
* Helper methods for parent outcome
*
* @param action
* @param redirect
* @return the parent outcome string
*/
protected PageOutcome getParentOutcome(String action, boolean redirect)
{
PageDefinition parentPage = getParentPage();
if (parentPage == null)
throw new MiscellaneousErrorException("No Parent Page defined for " + getPageName());
if (redirect)
return parentPage.getRedirect(action);
else
return parentPage.getOutcome(action);
}
protected PageOutcome getParentOutcome(boolean redirect)
{
return getParentOutcome(null, redirect);
}
/**
* return a connection for a particular database
* @param db the database for which to obtain a connection
* @return the connection for the given database
*/
public Connection getConnection(DBDatabase db)
{
FacesApplication app = FacesUtils.getFacesApplication();
return app.getConnectionForRequest(FacesUtils.getContext(), db);
}
public Object[] getKeyFromParam(DBRowSet rowset, String idParam)
{
FacesContext fc = FacesUtils.getContext();
return FacesUtils.getParameterMap(fc).get(rowset, idParam);
}
public String getIdParamForKey(DBRowSet rowset, Object[] key)
{
FacesContext fc = FacesUtils.getContext();
return FacesUtils.getParameterMap(fc).put(rowset, key);
}
public void addJavascriptCall(String function)
{
if (!function.endsWith(";"))
{ // Add a semicolon (important!)
function += ";";
}
// Add Call
FacesContext fc = FacesUtils.getContext();
FacesApplication app = FacesUtils.getFacesApplication();
app.addJavascriptCall(fc, function);
}
/* Page Resources */
/**
* Adds an object required for resource handling, to the page resource map.
* <pre>
* Since resource requests are not attached to a view, they cannot access page properties via expression language like this
* #{page.someProperty}
* Instead, the page should add properties that are required to the "pageResources"-map. This map is held on the session, and cleared when the page changes.
* In order to access such page resources via expression language use
* #{pageResources.someProperty}
* </pre>
* @param name the name of the resource
* @param resource the resource
*/
public void addPageResource(String name, Object resource)
{
Map<String, Object> prm = FacesUtils.getPageResourceMap(FacesUtils.getContext());
prm.put(name, this);
}
/**
* Returns the page resource object previously added by addPageResource(...)
* @param name the name of the resource
* @return resource the resource
*/
public Object getPageResource(String name)
{
Map<String, Object> prm = FacesUtils.getPageResourceMap(FacesUtils.getContext());
return prm.get(name);
}
/* Default Init Method */
public void doInit()
{
if (pageElements != null)
{ // Init Page Elements
for (PageElement pe : pageElements)
doInitElement(pe);
}
}
public void doRefresh()
{
if (pageElements != null)
{ // Refresh Page Elements
for (PageElement pe : pageElements)
doRefreshElement(pe);
}
}
/**
* called by doInit() to initialize a particular page element
* @param pe the page element to initialize
*/
protected void doInitElement(PageElement pe)
{
pe.onInitPage();
}
/**
* called by doRefresh() to refresh a particular page element
* @param pe the page element to refresh
*/
protected void doRefreshElement(PageElement pe)
{
pe.onRefreshPage();
}
/* Helpers */
protected final TextResolver getTextResolver()
{
FacesContext fc = FacesUtils.getContext();
return FacesUtils.getFacesApplication().getTextResolver(fc);
}
}
| EMPIREDB-175
rename misleading method name redirectTo() to navigateTo()
git-svn-id: b3b0da0efb1e558805af38d819c06f711288435d@1448948 13f79535-47bb-0310-9956-ffa450edef68
| empire-db-jsf2/src/main/java/org/apache/empire/jsf2/pages/Page.java | EMPIREDB-175 rename misleading method name redirectTo() to navigateTo() | <ide><path>mpire-db-jsf2/src/main/java/org/apache/empire/jsf2/pages/Page.java
<ide> return;
<ide> // Oops, not redirected yet?
<ide> if (getParentPage()!=null)
<del> redirectTo(getParentOutcome(true));
<add> navigateTo(getParentOutcome(true));
<ide> // Done
<ide> return;
<ide> }
<ide> return false;
<ide> }
<ide> // redirect
<del> redirectTo(parentPage.getRedirect());
<add> navigateTo(parentPage.getRedirect());
<ide> return true;
<ide> }
<ide>
<ide> return b.toString();
<ide> }
<ide>
<del> protected void redirectTo(PageOutcome outcome)
<add> /**
<add> * navigates to the desired page. Depending on the page outcome provided this is either a forward or a redirect.
<add> * @param outcome the destination page to navigate to
<add> */
<add> protected void navigateTo(PageOutcome outcome)
<ide> {
<ide> if (log.isDebugEnabled())
<ide> log.debug("Redirecting from page {} to page {}.", getPageName(), outcome.toString()); |
|
Java | bsd-3-clause | 8d7369f891d6dc429a35b7ae763f73ad5e8670dd | 0 | muloem/xins,muloem/xins,muloem/xins | /*
* $Id$
*/
package org.xins.util.collections;
import org.xins.util.MandatoryArgumentChecker;
import org.xins.util.text.FastStringBuffer;
/**
* Exception thrown to indicate the property of a value is invalid. This
* exception applies to both bootstrapping
* ({@link Manageable#bootstrap(PropertyReader)}) and initialization
* ({@link Manageable#init(PropertyReader)}).
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*/
public final class InvalidPropertyValueException
extends Exception {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* Creates message based on the specified constructor arguments.
*
* @param propertyName
* the name of the property, cannot be <code>null</code>.
*
* @param propertyValue
* the (invalid) value set for the property, cannot be
* <code>null</code>.
*
* @return
* the message, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>propertyName == null || propertyValue == null</code>.
*/
private static final String createMessage(String propertyName,
String propertyValue,
String reason)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("propertyName", propertyName,
"propertyValue", propertyValue);
// Construct the message
FastStringBuffer buffer = new FastStringBuffer(150);
buffer.append("The value \"");
buffer.append(propertyValue);
buffer.append("\" is invalid for property \"");
buffer.append(propertyName);
if (reason == null) {
buffer.append("\".");
} else {
buffer.append("\": ");
buffer.append(reason);
}
return buffer.toString();
}
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>InvalidPropertyValueException</code>.
*
* @param propertyName
* the name of the property, cannot be <code>null</code>.
*
* @param propertyValue
* the (invalid) value set for the property, cannot be
* <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>propertyName == null || propertyValue == null</code>.
*/
public InvalidPropertyValueException(String propertyName,
String propertyValue)
throws IllegalArgumentException {
this(propertyName, propertyValue, null);
}
/**
* Constructs a new <code>InvalidPropertyValueException</code> with the
* specified reason.
*
* @param propertyName
* the name of the property, cannot be <code>null</code>.
*
* @param propertyValue
* the (invalid) value set for the property, cannot be
* <code>null</code>.
*
* @param reason
* additional description of the problem, or <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>propertyName == null || propertyValue == null</code>.
*
* @since XINS 0.150
*/
public InvalidPropertyValueException(String propertyName,
String propertyValue,
String reason)
throws IllegalArgumentException {
// Construct message and call superclass constructor
super(createMessage(propertyName, propertyValue, reason));
// Store data
_propertyName = propertyName;
_propertyValue = propertyValue;
_reason = reason;
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* The name of the property. Cannot be <code>null</code>.
*/
private final String _propertyName;
/**
* The (invalid) value of the property. Cannot be <code>null</code>.
*/
private final String _propertyValue;
/**
* The detailed reason. Can be <code>null</code>.
*/
private final String _reason;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Returns the name of the property.
*
* @return
* the name of the property, never <code>null</code>.
*/
public String getPropertyName() {
return _propertyName;
}
/**
* Returns the (invalid) value of the property.
*
* @return
* the value of the property, never <code>null</code>.
*/
public String getPropertyValue() {
return _propertyValue;
}
/**
* Returns the description of the reason.
*
* @return
* the reason, or <code>null</code>.
*
* @since XINS 0.150
*/
public String getReason() {
return _reason;
}
}
| src/java-common/org/xins/util/collections/InvalidPropertyValueException.java | /*
* $Id$
*/
package org.xins.util.collections;
import org.xins.util.MandatoryArgumentChecker;
import org.xins.util.text.FastStringBuffer;
/**
* Exception thrown to indicate the property of a value is invalid. This
* exception applies to both bootstrapping
* ({@link Manageable#bootstrap(PropertyReader)}) and initialization
* ({@link Manageable#init(PropertyReader)}).
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*/
public final class InvalidPropertyValueException
extends Exception {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* Creates message based on the specified constructor arguments.
*
* @param propertyName
* the name of the property, cannot be <code>null</code>.
*
* @param propertyValue
* the (invalid) value set for the property, cannot be
* <code>null</code>.
*
* @return
* the message, never <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>propertyName == null || propertyValue == null</code>.
*/
private static final String createMessage(String propertyName, String propertyValue)
throws IllegalArgumentException {
// Check preconditions
MandatoryArgumentChecker.check("propertyName", propertyName,
"propertyValue", propertyValue);
// Construct the message
FastStringBuffer buffer = new FastStringBuffer(150);
buffer.append("The value \"");
buffer.append(propertyValue);
buffer.append("\" is invalid for property \"");
buffer.append(propertyName);
buffer.append("\".");
return buffer.toString();
}
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>InvalidPropertyValueException</code>.
*
* @param propertyName
* the name of the property, cannot be <code>null</code>.
*
* @param propertyValue
* the (invalid) value set for the property, cannot be
* <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>propertyName == null || propertyValue == null</code>.
*/
public InvalidPropertyValueException(String propertyName, String propertyValue)
throws IllegalArgumentException {
// Construct message and call superclass constructor
super(createMessage(propertyName, propertyValue));
// Store data
_propertyName = propertyName;
_propertyValue = propertyValue;
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* The name of the property.
*/
private final String _propertyName;
/**
* The (invalid) value of the property.
*/
private final String _propertyValue;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
/**
* Returns the name of the property.
*
* @return
* the name of the property, never <code>null</code>.
*/
public String getPropertyName() {
return _propertyName;
}
/**
* Returns the (invalid) value of the property.
*
* @return
* the value of the property, never <code>null</code>.
*/
public String getPropertyValue() {
return _propertyValue;
}
}
| Added support for 'reason' property.
| src/java-common/org/xins/util/collections/InvalidPropertyValueException.java | Added support for 'reason' property. | <ide><path>rc/java-common/org/xins/util/collections/InvalidPropertyValueException.java
<ide> * @throws IllegalArgumentException
<ide> * if <code>propertyName == null || propertyValue == null</code>.
<ide> */
<del> private static final String createMessage(String propertyName, String propertyValue)
<add> private static final String createMessage(String propertyName,
<add> String propertyValue,
<add> String reason)
<ide> throws IllegalArgumentException {
<ide>
<ide> // Check preconditions
<ide> buffer.append(propertyValue);
<ide> buffer.append("\" is invalid for property \"");
<ide> buffer.append(propertyName);
<del> buffer.append("\".");
<add> if (reason == null) {
<add> buffer.append("\".");
<add> } else {
<add> buffer.append("\": ");
<add> buffer.append(reason);
<add> }
<ide>
<ide> return buffer.toString();
<ide> }
<ide> * @throws IllegalArgumentException
<ide> * if <code>propertyName == null || propertyValue == null</code>.
<ide> */
<del> public InvalidPropertyValueException(String propertyName, String propertyValue)
<add> public InvalidPropertyValueException(String propertyName,
<add> String propertyValue)
<add> throws IllegalArgumentException {
<add>
<add> this(propertyName, propertyValue, null);
<add> }
<add>
<add> /**
<add> * Constructs a new <code>InvalidPropertyValueException</code> with the
<add> * specified reason.
<add> *
<add> * @param propertyName
<add> * the name of the property, cannot be <code>null</code>.
<add> *
<add> * @param propertyValue
<add> * the (invalid) value set for the property, cannot be
<add> * <code>null</code>.
<add> *
<add> * @param reason
<add> * additional description of the problem, or <code>null</code>.
<add> *
<add> * @throws IllegalArgumentException
<add> * if <code>propertyName == null || propertyValue == null</code>.
<add> *
<add> * @since XINS 0.150
<add> */
<add> public InvalidPropertyValueException(String propertyName,
<add> String propertyValue,
<add> String reason)
<ide> throws IllegalArgumentException {
<ide>
<ide> // Construct message and call superclass constructor
<del> super(createMessage(propertyName, propertyValue));
<add> super(createMessage(propertyName, propertyValue, reason));
<ide>
<ide> // Store data
<ide> _propertyName = propertyName;
<ide> _propertyValue = propertyValue;
<add> _reason = reason;
<ide> }
<ide>
<ide>
<ide> //-------------------------------------------------------------------------
<ide>
<ide> /**
<del> * The name of the property.
<add> * The name of the property. Cannot be <code>null</code>.
<ide> */
<ide> private final String _propertyName;
<ide>
<ide> /**
<del> * The (invalid) value of the property.
<add> * The (invalid) value of the property. Cannot be <code>null</code>.
<ide> */
<ide> private final String _propertyValue;
<add>
<add> /**
<add> * The detailed reason. Can be <code>null</code>.
<add> */
<add> private final String _reason;
<ide>
<ide>
<ide> //-------------------------------------------------------------------------
<ide> public String getPropertyValue() {
<ide> return _propertyValue;
<ide> }
<add>
<add> /**
<add> * Returns the description of the reason.
<add> *
<add> * @return
<add> * the reason, or <code>null</code>.
<add> *
<add> * @since XINS 0.150
<add> */
<add> public String getReason() {
<add> return _reason;
<add> }
<ide> } |
|
Java | apache-2.0 | 1d97ba62ef8a04f40a7dcbe2a869bb5e852f18f6 | 0 | rquast/esindexer,rquast/esindexer,rquast/esindexer | package com.esindexer;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.log4j.Logger;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.esindexer.preferences.IPreferences;
import com.esindexer.xstream.model.ProcessedIndex;
import com.esindexer.xstream.model.ProcessedPage;
/**
* @author Roland Quast ([email protected])
*
*/
class FileWatcher implements Runnable {
private static Logger LOG = Logger.getLogger(FileWatcher.class);
private WatchService myWatcher;
private ProcessedIndex index;
private IPreferences preferences;
public FileWatcher(WatchService myWatcher) {
this.myWatcher = myWatcher;
}
@Override
public void run() {
try {
WatchKey key = myWatcher.take();
while(key != null) {
for (WatchEvent<?> event : key.pollEvents()) {
final Path changed = (Path) event.context();
LOG.info("File updated: " + changed);
if ( !(index.getPath().endsWith(changed.toString())) ) {
continue;
}
try {
processFile();
} catch (FileNotFoundException e) {
LOG.error(e, e);
} catch (IOException e) {
LOG.error(e, e);
} catch (ParseException e) {
LOG.error(e, e);
} catch (java.text.ParseException e) {
LOG.error(e, e);
}
}
key.reset();
key = myWatcher.take();
}
} catch (InterruptedException e) {
LOG.info(e, e);
}
}
// TODO: run this as a file watcher thread.
private void processFile() throws FileNotFoundException,
IOException, ParseException, java.text.ParseException {
TransportClient client = new TransportClient();
for ( String node: preferences.getApplicationPreferences().getNodes() ) {
client.addTransportAddress(new InetSocketTransportAddress(node, 9300));
}
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(index.getPath()));
JSONArray pageList = (JSONArray) obj;
for (Object pageObj : pageList.toArray()) {
JSONObject pageJObj = (JSONObject) pageObj;
String modifiedStr = (String) pageJObj.get("modified");
String url = (String) pageJObj.get("url");
String title = (String) pageJObj.get("title");
String content = (String) pageJObj.get("content");
String path = (String) pageJObj.get("path");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.ENGLISH);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date newModified = format.parse(modifiedStr);
ProcessedPage processedPage = null;
if ( index.getProcessedPages().containsKey(url) ) {
processedPage = index.getProcessedPages().get(url);
Date lastModified = processedPage.getModified();
if ( newModified.after(lastModified) ) {
processedPage = new ProcessedPage();
processedPage.setUrl(url);
processedPage.setModified(newModified);
processedPage.setTitle(title);
processedPage.setContent(content);
processedPage.setPath(path);
if ( updateIndex(client, processedPage) ) {
index.getProcessedPages().put(url, processedPage);
preferences.save();
}
}
} else {
processedPage = new ProcessedPage();
processedPage.setUrl(url);
processedPage.setModified(newModified);
processedPage.setTitle(title);
processedPage.setContent(content);
processedPage.setPath(path);
if ( updateIndex(client, processedPage) ) {
index.getProcessedPages().put(url, processedPage);
preferences.save();
}
}
}
client.close();
}
private boolean updateIndex(Client client, ProcessedPage processedPage) {
JSONObject obj = new JSONObject();
obj.put("url", processedPage.getUrl());
obj.put("title", processedPage.getTitle());
obj.put("content", processedPage.getContent());
obj.put("modified", processedPage.getModified());
String json = null;
try {
json = obj.toJSONString();
} catch ( Exception ex ) {
LOG.error(ex, ex);
}
if ( json == null ) {
return false;
}
LOG.info(json);
try {
IndexResponse response = client.prepareIndex("helpindex", "page")
.setSource(json)
.execute()
.actionGet();
} catch ( Exception ex ) {
LOG.error(ex, ex);
}
return true; // TODO: return false if elasticsearch didn't like doing and update.
}
public void setProcessedIndex(ProcessedIndex index) {
this.index = index;
}
public void setPreferences(IPreferences preferences) {
this.preferences = preferences;
}
}
| src/main/java/com/esindexer/FileWatcher.java | package com.esindexer;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.log4j.Logger;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.esindexer.preferences.IPreferences;
import com.esindexer.xstream.model.ProcessedIndex;
import com.esindexer.xstream.model.ProcessedPage;
/**
* @author Roland Quast ([email protected])
*
*/
class FileWatcher implements Runnable {
private static Logger LOG = Logger.getLogger(FileWatcher.class);
private WatchService myWatcher;
private ProcessedIndex index;
private IPreferences preferences;
public FileWatcher(WatchService myWatcher) {
this.myWatcher = myWatcher;
}
@Override
public void run() {
try {
WatchKey key = myWatcher.take();
while(key != null) {
for (WatchEvent<?> event : key.pollEvents()) {
final Path changed = (Path) event.context();
LOG.info("File updated: " + changed);
if ( !(index.getPath().endsWith(changed.toString())) ) {
continue;
}
try {
processFile();
} catch (FileNotFoundException e) {
LOG.error(e, e);
} catch (IOException e) {
LOG.error(e, e);
} catch (ParseException e) {
LOG.error(e, e);
} catch (java.text.ParseException e) {
LOG.error(e, e);
}
}
key.reset();
key = myWatcher.take();
}
} catch (InterruptedException e) {
LOG.info(e, e);
}
}
// TODO: run this as a file watcher thread.
private void processFile() throws FileNotFoundException,
IOException, ParseException, java.text.ParseException {
TransportClient client = new TransportClient();
for ( String node: preferences.getApplicationPreferences().getNodes() ) {
client.addTransportAddress(new InetSocketTransportAddress(node, 9300));
}
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(index.getPath()));
JSONArray pageList = (JSONArray) obj;
for (Object pageObj : pageList.toArray()) {
JSONObject pageJObj = (JSONObject) pageObj;
String modifiedStr = (String) pageJObj.get("modified");
String url = (String) pageJObj.get("url");
String title = (String) pageJObj.get("title");
String content = (String) pageJObj.get("content");
String path = (String) pageJObj.get("path");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.ENGLISH);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date newModified = format.parse(modifiedStr);
ProcessedPage processedPage = null;
if ( index.getProcessedPages().containsKey(url) ) {
processedPage = index.getProcessedPages().get(url);
Date lastModified = processedPage.getModified();
if ( newModified.after(lastModified) ) {
processedPage = new ProcessedPage();
processedPage.setUrl(url);
processedPage.setModified(newModified);
processedPage.setTitle(title);
processedPage.setContent(content);
processedPage.setPath(path);
if ( updateIndex(client, processedPage) ) {
index.getProcessedPages().put(url, processedPage);
preferences.save();
}
}
} else {
processedPage = new ProcessedPage();
processedPage.setUrl(url);
processedPage.setModified(newModified);
processedPage.setTitle(title);
processedPage.setContent(content);
processedPage.setPath(path);
if ( updateIndex(client, processedPage) ) {
index.getProcessedPages().put(url, processedPage);
preferences.save();
}
}
}
client.close();
}
private boolean updateIndex(Client client, ProcessedPage processedPage) {
JSONObject obj = new JSONObject();
obj.put("url", processedPage.getUrl());
obj.put("title", processedPage.getTitle());
obj.put("content", processedPage.getContent());
obj.put("modified", processedPage.getModified());
String json = obj.toJSONString();
IndexResponse response = client.prepareIndex("helpindex", "page")
.setSource(json)
.execute()
.actionGet();
return true; // TODO: return false if elasticsearch didn't like doing and update.
}
public void setProcessedIndex(ProcessedIndex index) {
this.index = index;
}
public void setPreferences(IPreferences preferences) {
this.preferences = preferences;
}
}
| Added error checking for json creation. | src/main/java/com/esindexer/FileWatcher.java | Added error checking for json creation. | <ide><path>rc/main/java/com/esindexer/FileWatcher.java
<ide> obj.put("title", processedPage.getTitle());
<ide> obj.put("content", processedPage.getContent());
<ide> obj.put("modified", processedPage.getModified());
<del> String json = obj.toJSONString();
<add> String json = null;
<add> try {
<add> json = obj.toJSONString();
<add> } catch ( Exception ex ) {
<add> LOG.error(ex, ex);
<add> }
<add>
<add> if ( json == null ) {
<add> return false;
<add> }
<add>
<add> LOG.info(json);
<add>
<add> try {
<ide> IndexResponse response = client.prepareIndex("helpindex", "page")
<ide> .setSource(json)
<ide> .execute()
<ide> .actionGet();
<add> } catch ( Exception ex ) {
<add> LOG.error(ex, ex);
<add> }
<add>
<ide> return true; // TODO: return false if elasticsearch didn't like doing and update.
<ide> }
<ide> |
|
Java | apache-2.0 | 917730e7a46107918059778c95083ea2d1b677d0 | 0 | ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp | package com.ilscipio.scipio.solr;
import java.io.IOException;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Collation;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Suggestion;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.CommonParams;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericDelegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.transaction.TransactionUtil;
import org.ofbiz.entity.util.EntityFindOptions;
import org.ofbiz.entity.util.EntityListIterator;
import org.ofbiz.product.product.ProductWorker;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceSyncRegistrations;
import org.ofbiz.service.ServiceSyncRegistrations.ServiceSyncRegistration;
import org.ofbiz.service.ServiceUtil;
import com.ilscipio.scipio.solr.util.DirectJsonRequest;
/**
* Base class for OFBiz Test Tools test case implementations.
*/
public abstract class SolrProductSearch {
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
private static final boolean rebuildClearAndUseCacheDefault = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName,
"solr.index.rebuild.clearAndUseCache", false);
private static final String defaultRegisterUpdateToSolrUpdateSrv = UtilProperties.getPropertyValue(SolrUtil.solrConfigName,
"solr.service.registerUpdateToSolr.updateSrv", "updateToSolr");
private static boolean reindexAutoForceRan = false;
private static final String reindexStartupForceSysProp = "scipio.solr.reindex.startup.force";
private static final String reindexStartupForceConfigProp = "solr.index.rebuild.startup.force";
public static Map<String, Object> addToSolr(DispatchContext dctx, Map<String, Object> context) {
return updateToSolrCommon(dctx, context, Boolean.TRUE, true);
}
private static Map<String, Object> addToSolrCore(DispatchContext dctx, Map<String, Object> context, GenericValue product, String productId) {
Map<String, Object> result;
if (Debug.verboseOn()) Debug.logVerbose("Solr: addToSolr: Running indexing for productId '" + productId + "'", module);
try {
Map<String, Object> dispatchContext = SolrProductUtil.getProductContent(product, dctx, context);
dispatchContext.put("treatConnectErrorNonFatal", SolrUtil.isEcaTreatConnectErrorNonFatal());
copyStdServiceFieldsNotSet(context, dispatchContext);
Map<String, Object> runResult = dctx.getDispatcher().runSync("addToSolrIndex", dispatchContext);
String runMsg = ServiceUtil.getErrorMessage(runResult);
if (UtilValidate.isEmpty(runMsg)) {
runMsg = null;
}
if (ServiceUtil.isError(runResult)) {
result = ServiceUtil.returnError(runMsg);
} else if (ServiceUtil.isFailure(runResult)) {
result = ServiceUtil.returnFailure(runMsg);
} else {
result = ServiceUtil.returnSuccess();
}
} catch (Exception e) {
Debug.logError(e, "Solr: addToSolr: Error adding product '" + productId + "' to solr index: " + e.getMessage(), module);
result = ServiceUtil.returnError("Error adding product '" + productId + "' to solr index: " + e.toString());
}
return result;
}
public static Map<String, Object> removeFromSolr(DispatchContext dctx, Map<String, Object> context) {
return updateToSolrCommon(dctx, context, Boolean.FALSE, true);
}
private static Map<String, Object> removeFromSolrCore(DispatchContext dctx, Map<String, Object> context, String productId) {
Map<String, Object> result;
// NOTE: log this as info because it's the only log line
Debug.logInfo("Solr: removeFromSolr: Removing productId '" + productId + "' from index", module);
try {
HttpSolrClient client = SolrUtil.getUpdateHttpSolrClient((String) context.get("core"));
client.deleteByQuery("productId:" + SolrExprUtil.escapeTermFull(productId));
client.commit();
result = ServiceUtil.returnSuccess();
} catch (Exception e) {
Debug.logError(e, "Solr: removeFromSolr: Error removing product '" + productId + "' from solr index: " + e.getMessage(), module);
result = ServiceUtil.returnError("Error removing product '" + productId + "' from solr index: " + e.toString());
}
return result;
}
public static final Map<String, Boolean> updateToSolrActionMap = UtilMisc.toMap("add", true, "remove", false); // default: "auto" -> null
private static final String getUpdateToSolrAction(Boolean forceAdd) {
if (forceAdd == null) return null;
else return forceAdd ? "add" : "remove";
}
public static Map<String, Object> updateToSolr(DispatchContext dctx, Map<String, Object> context) {
return updateToSolrCommon(dctx, context, updateToSolrActionMap.get(context.get("action")), true);
}
public static Map<String, Object> registerUpdateToSolr(DispatchContext dctx, Map<String, Object> context) {
return updateToSolrCommon(dctx, context, updateToSolrActionMap.get(context.get("action")), false);
}
/**
* Core implementation for the updateToSolr, addToSolr, removeFromSolr, and registerUpdateToSolr services.
* <p>
* Upon error, unless instructed otherwise (manual flag or config), this marks the Solr data as dirty.
*/
private static Map<String, Object> updateToSolrCommon(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd, boolean immediate) {
Map<String, Object> result;
// DEV NOTE: BOILERPLATE ECA ENABLE CHECKING PATTERN, KEEP SAME FOR SERVICES ABOVE/BELOW
boolean manual = Boolean.TRUE.equals(context.get("manual"));
boolean indexed = false;
Boolean webappInitPassed = null;
boolean skippedDueToWebappInit = false;
if (manual || SolrUtil.isSolrEcaEnabled()) {
webappInitPassed = SolrUtil.isSolrEcaWebappInitCheckPassed();
if (webappInitPassed) {
String productId;
// NOTE: 2017-04-13: type may be org.ofbiz.entity.GenericValue or GenericPk, so use common parent GenericEntity (even better: Map)
//GenericValue productInstance = (GenericValue) context.get("instance");
@SuppressWarnings("unchecked")
Map<String, Object> productInst = (Map<String, Object>) context.get("instance");
if (productInst != null) productId = (String) productInst.get("productId");
else productId = (String) context.get("productId");
@SuppressWarnings("unchecked")
Map<String, Map<String, Object>> productIds = (Map<String, Map<String, Object>>) context.get("productIds");
if (immediate) {
if (productId == null && productIds == null) {
Debug.logError("Solr: updateToSolr: Missing product instance, productId or productIds map", module);
return ServiceUtil.returnError("Missing product instance, productId or productIds map");
}
result = updateToSolrCore(dctx, context, forceAdd, productId, productInst, productIds);
if (ServiceUtil.isSuccess(result)) indexed = true;
} else {
if (TransactionUtil.isTransactionInPlaceSafe()) {
if (productId == null) {
Debug.logError("Solr: registerUpdateToSolr: Missing product instance or productId", module);
// DEV NOTE: This *should* be okay to return error, without interfering with running transaction,
// because default ECA flags are: rollback-on-error="false" abort-on-error="false"
return ServiceUtil.returnError("Missing product instance or productId");
}
result = registerUpdateToSolrForTxCore(dctx, context, forceAdd, productId, productInst);
if (ServiceUtil.isSuccess(result)) indexed = true; // NOTE: not really indexed; this is just to skip the mark-dirty below
} else {
final String reason = "No transaction in place";
if ("update".equals(context.get("noTransMode"))) {
if (productId == null && productIds == null) {
Debug.logError("Solr: updateToSolr: Missing product instance, productId or productIds map", module);
return ServiceUtil.returnError("Missing product instance, productId or productIds map");
}
Debug.logInfo("Solr: registerUpdateToSolr: " + reason + "; running immediate index update", module);
result = updateToSolrCore(dctx, context, forceAdd, productId, productInst, productIds);
if (ServiceUtil.isSuccess(result)) indexed = true;
} else { // "mark-dirty"
result = ServiceUtil.returnSuccess();
if (manual) {
Debug.logInfo("Solr: registerUpdateToSolr: " + reason + "; skipping solr indexing completely (manual mode; not marking dirty)", module);
} else {
Debug.logInfo("Solr: registerUpdateToSolr: " + reason + "; skipping solr indexing, will mark dirty", module);
indexed = false;
}
}
}
}
} else {
if (Debug.verboseOn()) Debug.logVerbose("Solr: updateToSolr: Solr webapp not available; skipping indexing for product", module);
result = ServiceUtil.returnSuccess();
skippedDueToWebappInit = true;
}
} else {
if (Debug.verboseOn()) Debug.logVerbose("Solr: updateToSolr: Solr ECA indexing disabled; skipping indexing for product", module);
result = ServiceUtil.returnSuccess();
}
if (!manual && !indexed && UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.eca.markDirty.enabled", false)) {
boolean markDirtyNoWebappCheck = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.eca.markDirty.noWebappCheck", false);
if (!(markDirtyNoWebappCheck && skippedDueToWebappInit)) {
if (Debug.verboseOn()) Debug.logVerbose("Solr: updateToSolr: Did not update index for product; marking SOLR data as dirty (old)", module);
SolrUtil.setSolrDataStatusIdSepTxSafe(dctx.getDelegator(), "SOLR_DATA_OLD", false);
}
}
return result;
}
/**
* Multi-product core update.
* <p>
* WARN: this edits the products map in-place. We're assuming this isn't an issue...
* Added 2018-07-23.
* <p>
* DEV NOTE: 2018-07-26: For updateToSolr(Core), the global commit hook ignores the returned error message
* from this, so logError statements are essential.
*/
private static Map<String, Object> updateToSolrCore(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd, String productId, Map<String, Object> productInst,
Map<String, Map<String, Object>> products) {
// WARN: this edits the products map in-place. We're assuming this isn't an issue...
if (productId != null) {
if (products == null) products = new HashMap<>(); // SPECIAL: here no need for LinkedHashMap, but other cases should be LinkedHashMap
Map<String, Object> productProps;
try {
productProps = dctx.getModelService("updateToSolrSingleInterface").makeValid(context, ModelService.IN_PARAM, false, null);
} catch (GenericServiceException e) {
Debug.logError(e, "Solr: updateToSolr: Error parsing service parameters for updateToSolrSingleInterface: " + e.getMessage() , module);
return ServiceUtil.returnError("Error parsing service parameters for updateToSolrSingleInterface: " + e.toString());
}
productProps.put("instance", productInst);
productProps.put("action", getUpdateToSolrAction(forceAdd));
products.put(productId, productProps);
}
return updateToSolrCore(dctx, context, products);
}
/**
* Multi-product core update.
* Added 2018-07-19.
* <p>
* DEV NOTE: 2018-07-26: For updateToSolr(Core), the global commit hook ignores the returned error message
* from this, so logError statements are essential.
*/
private static Map<String, Object> updateToSolrCore(DispatchContext dctx, Map<String, Object> context, Map<String, Map<String, Object>> products) {
// SPECIAL: 2018-01-03: do not update to Solr if the current transaction marked as rollback,
// because the rollbacked data may be (even likely to be) product data that we don't want in index
// FIXME?: this cannot handle transaction rollbacks triggered after us! Some client diligence still needed for that...
try {
if (TransactionUtil.isTransactionInPlace() && TransactionUtil.getStatus() == TransactionUtil.STATUS_MARKED_ROLLBACK) {
Debug.logWarning("Solr: updateToSolr: Current transaction is marked for rollback; aborting solr index update", module);
return ServiceUtil.returnFailure("Current transaction is marked for rollback; aborting solr index update");
}
} catch (Exception e) {
Debug.logError("Solr: updateToSolr: Failed to check transaction status; aborting solr index update: " + e.toString(), module);
return ServiceUtil.returnError("Failed to check transaction status; aborting solr index update: " + e.toString());
}
// pre-process for variants
// NOTE: products should be a LinkedHashMap;
// expandedProducts doesn't need to be LinkedHashMap, but do it anyway
// to keep more readable order of indexing operations in the log
Map<String, Map<String, Object>> expandedProducts = new LinkedHashMap<>();
for(Map.Entry<String, Map<String, Object>> entry : products.entrySet()) {
String productId = entry.getKey();
Map<String, Object> props = entry.getValue();
Map<String, Object> productInst = UtilGenerics.checkMap(props.get("instance"));
Boolean forceAdd = updateToSolrActionMap.get(props.get("action"));
boolean updateVariantsDeep = Boolean.TRUE.equals(props.get("updateVariantsDeep"));
boolean updateVariants = updateVariantsDeep || Boolean.TRUE.equals(props.get("updateVariants"));
boolean updateVirtualDeep = Boolean.TRUE.equals(props.get("updateVirtualDeep"));
boolean updateVirtual = updateVirtualDeep || Boolean.TRUE.equals(props.get("updateVirtual"));
expandedProducts.put(productId, props);
if (updateVariants || updateVirtual) {
if (Boolean.FALSE.equals(forceAdd)) {
// Here the Product will already have been removed so we can't determine its
// variants; but that's ok because it makes no sense for virtual to have been
// removed without its variants removed, which should have come through an ECA
// either in the same transaction or another before it.
if (Debug.verboseOn()) {
Debug.logVerbose("Solr: updateToSolr: Ignoring updateVariants/updateVirtual request for (forced) removal of product '"
+ productId + "' (the variants/virtual should be scheduled for removal through separate invocation)", module);
}
} else {
GenericValue product;
if (productInst instanceof GenericValue) {
product = (GenericValue) productInst;
} else {
try {
product = dctx.getDelegator().findOne("Product", UtilMisc.toMap("productId", productId), false);
} catch (Exception e) {
Debug.logError(e, "Solr: updateToSolr: Could not lookup product '" + productId + "': " + e.getMessage(), module);
return ServiceUtil.returnError("Could not lookup product '" + productId + "': " + e.toString());
}
if (Boolean.TRUE.equals(forceAdd) && product == null) {
return ServiceUtil.returnError("Product not found for productId: " + productId);
}
// update the props with the instance to prevent double lookup in updateToSolrCore below
// NOTE: SPECIAL MARKER for null
props = new HashMap<>(props);
props.put("instance", (product != null) ? product : Collections.emptyMap());
expandedProducts.put(productId, props);
}
if (product == null) {
if (Debug.verboseOn()) {
Debug.logVerbose("Solr: updateToSolr: Ignoring updateVariants/updateVirtual request for (forced) removal of product '"
+ productId + "' (the variants/virtual should be scheduled for removal through separate invocation)", module);
}
} else {
if (updateVariants && Boolean.TRUE.equals(product.getBoolean("isVirtual"))) {
if (Debug.verboseOn()) {
Debug.logVerbose("Solr: updateToSolr: Product '" + productId + "' is virtual for add operation"
+ " and updateVariants true; looking up variants for update", module);
}
List<GenericValue> variantProducts;
try {
if (updateVariantsDeep) {
variantProducts = ProductWorker.getVariantProductsDeepDfs(dctx.getDelegator(), dctx.getDispatcher(),
product, null, null, false);
} else {
variantProducts = ProductWorker.getVariantProducts(dctx.getDelegator(), dctx.getDispatcher(),
product, null, null, false);
}
} catch (GeneralException e) {
Debug.logError(e, "Solr: updateToSolr: Could not lookup product variants for '"
+ productId + "' for updateVariants: " + e.getMessage(), module);
return ServiceUtil.returnError("Could not lookup product variants for '"
+ productId + "' for updateVariants: " + e.toString());
}
for(GenericValue variantProduct : variantProducts) {
// NOTE: we crush any prior entry for same product;
// chronological last update request in transaction has priority
Map<String, Object> variantProps = new HashMap<>();
variantProps.put("instance", variantProduct);
variantProps.put("forceAdd", forceAdd); // no need: getUpdateToSolrAction(forceAdd)
String variantProductId = variantProduct.getString("productId");
// re-add the key to LinkedHashMap keep a readable order in log
expandedProducts.remove(variantProductId);
expandedProducts.put(variantProductId, variantProps);
}
}
if (updateVirtual && Boolean.TRUE.equals(product.getBoolean("isVariant"))) {
if (Debug.verboseOn()) {
Debug.logVerbose("Solr: updateToSolr: Product '" + productId + "' is variant for add operation"
+ " and updateVirtual true; looking up virtual for update", module);
}
List<GenericValue> virtualProducts;
try {
// TODO: REVIEW: in most stock code these would be "-fromDate" and maxPerLevel=1,
// but I see no good reason to limit it here (needless ordering)...
final List<String> orderBy = null;
final Integer maxPerLevel = null;
if (updateVirtualDeep) {
virtualProducts = ProductWorker.getVirtualProductsDeepDfs(dctx.getDelegator(), dctx.getDispatcher(),
product, orderBy, maxPerLevel, null, false);
} else {
virtualProducts = ProductWorker.getVirtualProducts(dctx.getDelegator(), dctx.getDispatcher(),
product, orderBy, maxPerLevel, null, false);
}
} catch(Exception e) {
Debug.logError(e, "Solr: updateToSolr: Could not lookup virtual product for variant product '"
+ productId + "': " + e.getMessage(), module);
return ServiceUtil.returnError("Could not lookup virtual product for variant product '"
+ productId + "': " + e.toString());
}
// This can be a valid state for ALTERNATIVE_PACKAGE products
//if (virtualProducts.isEmpty()) {
// Debug.logWarning("Solr: updateToSolr: Product '"
// + productId + "' is variant but found no parent product (either the association is being"
// + " removed, or data error)", module);
//} else {
for(GenericValue virtualProduct : virtualProducts) {
Map<String, Object> variantProps = new HashMap<>();
variantProps.put("instance", virtualProduct);
variantProps.put("forceAdd", forceAdd); // no need: getUpdateToSolrAction(forceAdd)
String virtualProductId = virtualProduct.getString("productId");
// re-add the key to LinkedHashMap keep a readable order in log
expandedProducts.remove(virtualProductId);
expandedProducts.put(virtualProductId, variantProps);
}
//}
}
}
}
}
}
Map<String, String> productIndexErrorMsgs = new HashMap<>();
for(Map.Entry<String, Map<String, Object>> entry : expandedProducts.entrySet()) {
String productId = entry.getKey();
Map<String, Object> props = entry.getValue();
Map<String, Object> productInst = UtilGenerics.checkMap(props.get("instance"));
Object actionObj = props.get("action");
Boolean forceAdd = (actionObj instanceof Boolean) ? (Boolean) actionObj : updateToSolrActionMap.get(actionObj);
Map<String, Object> updateSingleResult = updateToSolrCoreSingleImpl(dctx, context, forceAdd, productId, productInst);
if (!ServiceUtil.isSuccess(updateSingleResult)) {
productIndexErrorMsgs.put(productId, ServiceUtil.getErrorMessage(updateSingleResult));
}
}
if (productIndexErrorMsgs.size() == 0) {
return ServiceUtil.returnSuccess();
} else {
List<String> errorMsgs = new ArrayList<>();
for(Map.Entry<String, String> entry : productIndexErrorMsgs.entrySet()) {
errorMsgs.add("Error updating index for product '" + entry.getKey() + "': " + entry.getValue());
}
Map<String, Object> result = ServiceUtil.returnError(errorMsgs);
// DEV NOTE: this log statement is _probably_ redundant, but do it just in case
Debug.logError("Solr: registerUpdateToSolr: Error(s) indexing product(s): " + errorMsgs, module);
return result;
}
}
private static Map<String, Object> updateToSolrCoreSingleImpl(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd,
String productId, Map<String, Object> productInst) {
Map<String, Object> result;
if (Boolean.FALSE.equals(forceAdd)) {
result = removeFromSolrCore(dctx, context, productId);
} else {
GenericValue product;
if (productInst instanceof GenericValue) {
product = (GenericValue) productInst;
} else if (productInst != null && productInst.isEmpty()) { // SPECIAL MARKER to prevent double-lookup when null
product = null;
} else { // SPECIAL MARKER to prevent re-lookup
try {
product = dctx.getDelegator().findOne("Product", UtilMisc.toMap("productId", productId), false);
} catch (Exception e) {
Debug.logError(e, "Solr: updateToSolr: Could not lookup product '" + productId + "': " + e.getMessage(), module);
return ServiceUtil.returnError("Could not lookup product '" + productId + "': " + e.toString());
}
}
if (Boolean.TRUE.equals(forceAdd)) {
if (product == null) {
Debug.logError("Solr: updateToSolr: Explicit add action requested, but product not found for productId: " + productId, module);
return ServiceUtil.returnError("Explicit add action requested, but product not found for productId: " + productId);
}
result = addToSolrCore(dctx, context, product, productId);
} else {
if (product != null) {
if (Debug.verboseOn()) Debug.logVerbose("Solr: updateToSolr: productId '" + productId + "' found in system; running solr add", module);
result = addToSolrCore(dctx, context, product, productId);
} else {
if (Debug.verboseOn()) Debug.logVerbose("Solr: updateToSolr: productId '" + productId + "' not found in system; running solr remove", module);
result = removeFromSolrCore(dctx, context, productId);
}
}
}
return result;
}
/**
* Registers an updateToSolr call at the end of the transaction using global-commit event.
* <p>
* NOTE: the checking loop below may not currently handle all possible cases imaginable,
* but should cover the ones we're using.
* <p>
* UPDATE: 2018-07-24: We now use a single update service call with a map of productIds,
* to minimize overhead.
* WARN: DEV NOTE: This now edits the update service productIds context map in-place
* in the already-registered service; this is not "proper" but there is no known current case
* where it should cause an issue and it removes more overhead.
* <p>
* DEV NOTE: This *should* be okay to return error, without interfering with running transaction,
* because default ECA flags are: rollback-on-error="false" abort-on-error="false"
*/
private static Map<String, Object> registerUpdateToSolrForTxCore(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd, String productId, Map<String, Object> productInst) {
String updateSrv = (String) context.get("updateSrv");
if (updateSrv == null) updateSrv = defaultRegisterUpdateToSolrUpdateSrv;
try {
LocalDispatcher dispatcher = dctx.getDispatcher();
ServiceSyncRegistrations regs = dispatcher.getServiceSyncRegistrations();
Map<String, Object> productProps = dctx.getModelService("updateToSolrSingleInterface")
.makeValid(context, ModelService.IN_PARAM, false, null);
// IMPORTANT: DO NOT PASS AN INSTANCE; use productId to force updateToSolr to re-query the Product
// after transaction committed (by the time updateSrv is called, this instance may be invalid)
productProps.remove("instance");
productProps.put("action", getUpdateToSolrAction(forceAdd));
Collection<ServiceSyncRegistration> updateSrvRegs = regs.getCommitRegistrationsForService(updateSrv);
if (updateSrvRegs.size() >= 1) {
if (updateSrvRegs.size() >= 2) {
Debug.logError("Solr: registerUpdateToSolr: Found more than one transaction commit registration"
+ " for update service '" + updateSrv + "'; should not happen! (coding or ECA config error)", module);
}
ServiceSyncRegistration reg = updateSrvRegs.iterator().next();
// WARN: editing existing registration's service context in-place
@SuppressWarnings("unchecked")
Map<String, Map<String, Object>> productIds = (Map<String, Map<String, Object>>) reg.getContext().get("productIds");
productIds.remove(productId); // this is a LinkedHashMap, so remove existing first so we keep the "real" order
productIds.put(productId, productProps);
return ServiceUtil.returnSuccess("Updated transaction global-commit registration for " + updateSrv + " to include productId '" + productId + ")");
} else {
// register the service
Map<String, Object> servCtx = new HashMap<>();
// NOTE: this ditches the "manual" boolean (updateToSolrControlInterface), because can't support it here with only one updateSrv call
servCtx.put("locale", context.get("locale"));
servCtx.put("userLogin", context.get("userLogin"));
servCtx.put("timeZone", context.get("timeZone"));
// IMPORTANT: LinkedHashMap keeps order of changes across transaction
Map<String, Map<String, Object>> productIds = new LinkedHashMap<>();
productIds.put(productId, productProps);
servCtx.put("productIds", productIds);
regs.addCommitService(dctx, updateSrv, null, servCtx, false, false);
return ServiceUtil.returnSuccess("Registered " + updateSrv + " to run at transaction global-commit for productId '" + productId + ")");
}
} catch (Exception e) {
final String errMsg = "Could not register " + updateSrv + " to run at transaction global-commit for product '" + productId + "'";
Debug.logError(e, "Solr: registerUpdateToSolr: " + errMsg, module);
return ServiceUtil.returnError(errMsg + ": " + e.toString());
}
}
/**
* Adds product to solr index.
*/
public static Map<String, Object> addToSolrIndex(DispatchContext dctx, Map<String, Object> context) {
HttpSolrClient client = null;
Map<String, Object> result;
String productId = (String) context.get("productId");
// connectErrorNonFatal is a necessary option because in some cases it
// may be considered normal that solr server is unavailable;
// don't want to return error and abort transactions in these cases.
Boolean treatConnectErrorNonFatal = (Boolean) context.get("treatConnectErrorNonFatal");
boolean useCache = Boolean.TRUE.equals(context.get("useCache"));
try {
Debug.logInfo("Solr: Indexing product '" + productId + "'", module);
client = SolrUtil.getUpdateHttpSolrClient((String) context.get("core"));
// Construct Documents
SolrInputDocument doc1 = SolrProductUtil.generateSolrProductDocument(dctx.getDelegator(), dctx.getDispatcher(), context, useCache);
Collection<SolrInputDocument> docs = new ArrayList<>();
if (Debug.verboseOn()) Debug.logVerbose("Solr: Indexing document: " + doc1.toString(), module);
docs.add(doc1);
// push Documents to server
client.add(docs);
client.commit();
final String statusStr = "Product '" + productId + "' indexed";
if (Debug.verboseOn()) Debug.logVerbose("Solr: " + statusStr, module);
result = ServiceUtil.returnSuccess(statusStr);
} catch (MalformedURLException e) {
Debug.logError(e, "Solr: addToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "urlError");
} catch (SolrServerException e) {
if (e.getCause() != null && e.getCause() instanceof ConnectException) {
final String statusStr = "Failure connecting to solr server to commit productId " + context.get("productId") + "; product not updated";
if (Boolean.TRUE.equals(treatConnectErrorNonFatal)) {
Debug.logWarning(e, "Solr: " + statusStr, module);
result = ServiceUtil.returnFailure(statusStr);
} else {
Debug.logError(e, "Solr: " + statusStr, module);
result = ServiceUtil.returnError(statusStr);
}
result.put("errorType", "connectError");
} else {
Debug.logError(e, "Solr: addToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "solrServerError");
}
} catch (IOException e) {
Debug.logError(e, "Solr: addToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "ioError");
} catch (Exception e) {
Debug.logError(e, "Solr: addToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "general");
} finally {
try {
if (UtilValidate.isNotEmpty(client))
client.close();
} catch (IOException e) {
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "ioError");
}
}
return result;
}
/**
* Adds a List of products to the solr index.
* <p>
* This is faster than reflushing the index each time.
*/
public static Map<String, Object> addListToSolrIndex(DispatchContext dctx, Map<String, Object> context) {
HttpSolrClient client = null;
Map<String, Object> result;
Boolean treatConnectErrorNonFatal = (Boolean) context.get("treatConnectErrorNonFatal");
boolean useCache = Boolean.TRUE.equals(context.get("useCache"));
try {
Collection<SolrInputDocument> docs = new ArrayList<>();
List<Map<String, Object>> fieldList = UtilGenerics.<Map<String, Object>> checkList(context.get("fieldList"));
if (fieldList.size() > 0) {
Debug.logInfo("Solr: addListToSolrIndex: Generating and adding " + fieldList.size() + " documents to solr index", module);
// Construct Documents
for (Map<String, Object> productContent : fieldList) {
SolrInputDocument doc1 = SolrProductUtil.generateSolrProductDocument(dctx.getDelegator(), dctx.getDispatcher(), productContent, useCache);
if (Debug.verboseOn()) Debug.logVerbose("Solr: addListToSolrIndex: Processed document for indexing: " + doc1.toString(), module);
docs.add(doc1);
}
// push Documents to server
client = SolrUtil.getUpdateHttpSolrClient((String) context.get("core"));
client.add(docs);
client.commit();
}
final String statusStr = "Added " + fieldList.size() + " documents to solr index";
Debug.logInfo("Solr: addListToSolrIndex: " + statusStr, module);
result = ServiceUtil.returnSuccess(statusStr);
} catch (MalformedURLException e) {
Debug.logError(e, "Solr: addListToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "urlError");
} catch (SolrServerException e) {
if (e.getCause() != null && e.getCause() instanceof ConnectException) {
final String statusStr = "Failure connecting to solr server to commit product list; products not updated";
if (Boolean.TRUE.equals(treatConnectErrorNonFatal)) {
Debug.logWarning(e, "Solr: addListToSolrIndex: " + statusStr, module);
result = ServiceUtil.returnFailure(statusStr);
} else {
Debug.logError(e, "Solr: addListToSolrIndex: " + statusStr, module);
result = ServiceUtil.returnError(statusStr);
}
result.put("errorType", "connectError");
} else {
Debug.logError(e, "Solr: addListToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "solrServerError");
}
} catch (IOException e) {
Debug.logError(e, "Solr: addListToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "ioError");
} catch (Exception e) {
Debug.logError(e, "Solr: addListToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "general");
} finally {
try {
if (client != null) client.close();
} catch (IOException e) {
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "ioError");
}
}
return result;
}
/**
* Runs a query on the Solr Search Engine and returns the results.
* <p>
* This function only returns an object of type QueryResponse, so it is
* probably not a good idea to call it directly from within the groovy files
* (As a decent example on how to use it, however, use keywordSearch
* instead).
*/
public static Map<String, Object> runSolrQuery(DispatchContext dctx, Map<String, Object> context) {
// get Connection
HttpSolrClient client = null;
Map<String, Object> result;
try {
// DEV NOTE: WARN: 2017-08-22: BEWARE PARSING FIELDS HERE - should be avoided here
// the passed values may not be simple fields names, they require complex expressions containing spaces and special chars
// (for example the old "queryFilter" parameter was unusable, so now have "queryFilters" list in addition).
String solrUsername = (String) context.get("solrUsername");
String solrPassword = (String) context.get("solrPassword");
client = SolrUtil.getQueryHttpSolrClient((String) context.get("core"), solrUsername, solrPassword);
// create Query Object
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery((String) context.get("query"));
String queryType = (String) context.get("queryType");
if (UtilValidate.isNotEmpty(queryType)) {
solrQuery.setRequestHandler(queryType);
}
String defType = (String) context.get("defType");
if (UtilValidate.isNotEmpty(defType)) {
solrQuery.set("defType", defType);
}
Boolean faceted = (Boolean) context.get("facet");
if (Boolean.TRUE.equals(faceted)) {
solrQuery.setFacet(faceted);
solrQuery.addFacetField("manu");
solrQuery.addFacetField("cat");
solrQuery.setFacetMinCount(1);
solrQuery.setFacetLimit(8);
solrQuery.addFacetQuery("listPrice:[0 TO 50]");
solrQuery.addFacetQuery("listPrice:[50 TO 100]");
solrQuery.addFacetQuery("listPrice:[100 TO 250]");
solrQuery.addFacetQuery("listPrice:[250 TO 500]");
solrQuery.addFacetQuery("listPrice:[500 TO 1000]");
solrQuery.addFacetQuery("listPrice:[1000 TO 2500]");
solrQuery.addFacetQuery("listPrice:[2500 TO 5000]");
solrQuery.addFacetQuery("listPrice:[5000 TO 10000]");
solrQuery.addFacetQuery("listPrice:[10000 TO 50000]");
solrQuery.addFacetQuery("listPrice:[50000 TO *]");
}
Boolean spellCheck = (Boolean) context.get("spellcheck");
if (Boolean.TRUE.equals(spellCheck)) {
solrQuery.setParam("spellcheck", true);
solrQuery.setParam("spellcheck.collate", true);
Object spellDictObj = context.get("spellDict");
if (spellDictObj instanceof String) {
if (UtilValidate.isNotEmpty((String) spellDictObj)) {
solrQuery.setParam("spellcheck.dictionary", (String) spellDictObj);
}
} else if (spellDictObj instanceof Collection) {
for(String spellDict : UtilGenerics.<String>checkCollection(spellDictObj)) {
solrQuery.add("spellcheck.dictionary", spellDict);
}
}
}
Boolean highlight = (Boolean) context.get("highlight");
if (Boolean.TRUE.equals(highlight)) {
// FIXME: unhardcode markup
solrQuery.setHighlight(highlight);
solrQuery.setHighlightSimplePre("<span class=\"highlight\">");
solrQuery.addHighlightField("description");
solrQuery.setHighlightSimplePost("</span>");
solrQuery.setHighlightSnippets(2);
}
// Set additional Parameter
// SolrQuery.ORDER order = SolrQuery.ORDER.desc;
// 2016-04-01: start must be calculated
//if (context.get("viewIndex") != null && (Integer) context.get("viewIndex") > 0) {
// solrQuery.setStart((Integer) context.get("viewIndex"));
//}
//if (context.get("viewSize") != null && (Integer) context.get("viewSize") > 0) {
// solrQuery.setRows((Integer) context.get("viewSize"));
//}
Integer start = (Integer) context.get("start");
Integer viewIndex = (Integer) context.get("viewIndex");
Integer viewSize = (Integer) context.get("viewSize");
if (viewSize != null && viewSize > 0) {
solrQuery.setRows(viewSize);
}
if (start != null) {
if (start > 0) {
solrQuery.setStart(start);
}
} else if (viewIndex != null) {
if (viewIndex > 0 && viewSize != null && viewSize > 0) {
solrQuery.setStart(viewIndex * viewSize);
}
}
String queryFilter = (String) context.get("queryFilter");
if (UtilValidate.isNotEmpty((String) queryFilter)) {
// WARN: 2017-08-17: we don't really want splitting on whitespace anymore, because it
// slaughters complex queries and ignores escaping; callers should use queryFilters list instead.
// However, we can at least fix a bug here where we can do better and split on \\s+ instead
//solrQuery.addFilterQuery(((String) queryFilter).split(" "));
solrQuery.addFilterQuery(((String) queryFilter).trim().split("\\s+"));
}
Collection<String> queryFilters = UtilGenerics.checkCollection(context.get("queryFilters"));
SolrQueryUtil.addFilterQueries(solrQuery, queryFilters);
if ((String) context.get("returnFields") != null) {
solrQuery.setFields((String) context.get("returnFields"));
}
String defaultOp = (String) context.get("defaultOp");
if (UtilValidate.isNotEmpty(defaultOp)) {
solrQuery.set("q.op", defaultOp);
}
String queryFields = (String) context.get("queryFields");
if (UtilValidate.isNotEmpty(queryFields)) {
solrQuery.set("qf", queryFields);
}
Map<String, ?> queryParams = UtilGenerics.checkMap(context.get("queryParams"));
if (queryParams != null) {
for(Map.Entry<String, ?> entry : queryParams.entrySet()) {
String name = entry.getKey();
Object value = entry.getValue();
if (value == null) {
// NOTE: this removes the param when null
solrQuery.set(name, (String) value);
} else if (value instanceof String) {
solrQuery.set(name, (String) value);
} else if (value instanceof Integer) {
solrQuery.set(name, (Integer) value);
} else if (value instanceof Long) {
solrQuery.set(name, ((Long) value).intValue());
} else if (value instanceof Boolean) {
solrQuery.set(name, (Boolean) value);
} else {
throw new IllegalArgumentException("queryParams entry '" + name
+ "' value unsupported type (supported: String, Integer, Long, Boolean): " + value.getClass().getName());
}
}
}
// if((Boolean)context.get("sortByReverse"))order.reverse();
String sortBy = (String) context.get("sortBy");
if (UtilValidate.isNotEmpty(sortBy)) {
SolrQuery.ORDER order = null;
Boolean sortByReverse = (Boolean) context.get("sortByReverse");
if (sortByReverse != null) {
order = sortByReverse ? SolrQuery.ORDER.desc : SolrQuery.ORDER.asc;
}
// TODO?: REVIEW?: 2017-08-22: this parsing poses a problem and may interfere with queries.
// I have restricted it to only remove the first "-" if it's preceeded by whitespace, but
// there's no guarantee it still might not interfere with query too...
//sortBy = sortBy.replaceFirst("-", "");
// TODO: REVIEW: trim would probably be fine & simplify check, but I don't know for sure
//sortBy = sortBy.trim();
int dashIndex = sortBy.indexOf('-');
if (dashIndex >= 0 && sortBy.substring(0, dashIndex).trim().isEmpty()) { // this checks if dash is first char or preceeded by space only
if (order == null) {
order = SolrQuery.ORDER.desc;
}
sortBy = sortBy.substring(dashIndex + 1);
}
if (order == null) {
order = SolrQuery.ORDER.asc;
}
solrQuery.setSort(sortBy, order);
}
if ((String) context.get("facetQuery") != null) {
solrQuery.addFacetQuery((String) context.get("facetQuery"));
}
//QueryResponse rsp = client.query(solrQuery, METHOD.POST); // old way (can't configure the request)
QueryRequest req = new QueryRequest(solrQuery, METHOD.POST);
if (solrUsername != null) {
// This will override the credentials stored in (Scipio)HttpSolrClient, if any
req.setBasicAuthCredentials(solrUsername, solrPassword);
}
QueryResponse rsp = req.process(client);
result = ServiceUtil.returnSuccess();
result.put("queryResult", rsp);
} catch (Exception e) {
Debug.logError(e, "Solr: runSolrQuery: Error: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
if (SolrQueryUtil.isSolrQuerySyntaxError(e)) {
result.put("errorType", "query-syntax");
} else {
result.put("errorType", "general");
}
// TODO? nestedErrorMessage: did not succeed extracting this reliably
}
return result;
}
/**
* Performs solr products search.
*/
public static Map<String, Object> productsSearch(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result;
LocalDispatcher dispatcher = dctx.getDispatcher();
try {
Map<String, Object> dispatchMap = dctx.makeValidContext("runSolrQuery", ModelService.IN_PARAM, context);
if (UtilValidate.isNotEmpty(context.get("productCategoryId"))) {
String productCategoryId = (String) context.get("productCategoryId");
// causes erroneous results for similar-name categories
//dispatchMap.put("query", "cat:*" + SolrUtil.escapeTermFull(productCategoryId) + "*");
boolean includeSubCategories = !Boolean.FALSE.equals(context.get("includeSubCategories"));
dispatchMap.put("query", SolrExprUtil.makeCategoryIdFieldQueryEscape("cat", productCategoryId, includeSubCategories));
} else {
return ServiceUtil.returnError("Missing productCategoryId"); // TODO: localize
}
Integer viewSize = (Integer) dispatchMap.get("viewSize");
//Integer viewIndex = (Integer) dispatchMap.get("viewIndex");
dispatchMap.put("facet", false); // (always false)
dispatchMap.put("spellcheck", false); // 2017-09: changed to false (always false)
if (dispatchMap.get("highlight") == null) dispatchMap.put("highlight", false); // 2017-09: default changed to false
List<String> queryFilters = getEnsureQueryFiltersModifiable(dispatchMap);
SolrQueryUtil.addDefaultQueryFilters(queryFilters, context); // 2018-05-25
Map<String, Object> searchResult = dispatcher.runSync("runSolrQuery", dispatchMap);
if (ServiceUtil.isFailure(searchResult)) {
return copySolrQueryExtraOutParams(searchResult, ServiceUtil.returnFailure(ServiceUtil.getErrorMessage(searchResult)));
} else if (ServiceUtil.isError(searchResult)) {
return copySolrQueryExtraOutParams(searchResult, ServiceUtil.returnError(ServiceUtil.getErrorMessage(searchResult)));
}
QueryResponse queryResult = (QueryResponse) searchResult.get("queryResult");
result = ServiceUtil.returnSuccess();
result.put("results", queryResult.getResults());
result.put("listSize", queryResult.getResults().getNumFound());
// 2016-04-01: Need to translate this
//result.put("viewIndex", queryResult.getResults().getStart());
result.put("start", queryResult.getResults().getStart());
result.put("viewIndex", SolrQueryUtil.calcResultViewIndex(queryResult.getResults(), viewSize));
result.put("viewSize", viewSize);
} catch (Exception e) {
Debug.logError(e, "Solr: productsSearch: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
}
return result;
}
private static Map<String, Object> copySolrQueryExtraOutParams(Map<String, Object> src, Map<String, Object> dest) {
if (src.containsKey("errorType")) dest.put("errorType", src.get("errorType"));
if (src.containsKey("nestedErrorMessage")) dest.put("nestedErrorMessage", src.get("nestedErrorMessage"));
return dest;
}
private static List<String> getEnsureQueryFiltersModifiable(Map<String, Object> context) {
List<String> queryFilters = UtilGenerics.checkList(context.get("queryFilters"));
if (queryFilters != null) queryFilters = new ArrayList<>(queryFilters);
else queryFilters = new ArrayList<>();
context.put("queryFilters", queryFilters);
return queryFilters;
}
/**
* Performs keyword search.
* <p>
* The search form requires the result to be in a specific layout, so this
* will generate the proper results.
*/
public static Map<String, Object> keywordSearch(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result;
LocalDispatcher dispatcher = dctx.getDispatcher();
try {
Map<String, Object> dispatchMap = dctx.makeValidContext("runSolrQuery", ModelService.IN_PARAM, context);
if (UtilValidate.isEmpty((String) dispatchMap.get("query"))) {
dispatchMap.put("dispatchMap", "*:*");
}
Integer viewSize = (Integer) dispatchMap.get("viewSize");
//Integer viewIndex = (Integer) dispatchMap.get("viewIndex");
if (dispatchMap.get("facet") == null) dispatchMap.put("facet", false); // 2017-09: default changed to false
if (dispatchMap.get("spellcheck") == null) dispatchMap.put("spellcheck", false); // 2017-09: default changed to false
if (dispatchMap.get("highlight") == null) dispatchMap.put("highlight", false); // 2017-09: default changed to false
List<String> queryFilters = getEnsureQueryFiltersModifiable(dispatchMap);
SolrQueryUtil.addDefaultQueryFilters(queryFilters, context); // 2018-05-25
Map<String, Object> searchResult = dispatcher.runSync("runSolrQuery", dispatchMap);
if (ServiceUtil.isFailure(searchResult)) {
return copySolrQueryExtraOutParams(searchResult, ServiceUtil.returnFailure(ServiceUtil.getErrorMessage(searchResult)));
} else if (ServiceUtil.isError(searchResult)) {
return copySolrQueryExtraOutParams(searchResult, ServiceUtil.returnError(ServiceUtil.getErrorMessage(searchResult)));
}
QueryResponse queryResult = (QueryResponse) searchResult.get("queryResult");
Boolean isCorrectlySpelled = Boolean.TRUE.equals(dispatchMap.get("spellcheck")) ? Boolean.TRUE : null;
Map<String, List<String>> tokenSuggestions = null;
List<String> fullSuggestions = null;
SpellCheckResponse spellResp = queryResult.getSpellCheckResponse();
if (spellResp != null) {
isCorrectlySpelled = spellResp.isCorrectlySpelled();
if (spellResp.getSuggestions() != null) {
tokenSuggestions = new LinkedHashMap<>();
for(Suggestion suggestion : spellResp.getSuggestions()) {
tokenSuggestions.put(suggestion.getToken(), suggestion.getAlternatives());
}
if (Debug.verboseOn()) Debug.logVerbose("Solr: Spelling: Token suggestions: " + tokenSuggestions, module);
}
// collations 2017-09-14, much more useful than the individual word suggestions
if (spellResp.getCollatedResults() != null) {
fullSuggestions = new ArrayList<>();
for(Collation collation : spellResp.getCollatedResults()) {
fullSuggestions.add(collation.getCollationQueryString());
}
if (Debug.verboseOn()) Debug.logVerbose("Solr: Spelling: Collations: " + fullSuggestions, module);
}
}
result = ServiceUtil.returnSuccess();
result.put("isCorrectlySpelled", isCorrectlySpelled);
Map<String, Integer> facetQuery = queryResult.getFacetQuery();
Map<String, String> facetQueries = null;
if (facetQuery != null) {
facetQueries = new HashMap<>();
for (String fq : facetQuery.keySet()) {
if (facetQuery.get(fq).intValue() > 0)
facetQueries.put(fq, fq.replaceAll("^.*\\u005B(.*)\\u005D", "$1") + " (" + facetQuery.get(fq).intValue() + ")");
}
}
List<FacetField> facets = queryResult.getFacetFields();
Map<String, Map<String, Long>> facetFields = null;
if (facets != null) {
facetFields = new HashMap<>();
for (FacetField facet : facets) {
Map<String, Long> facetEntry = new HashMap<>();
List<FacetField.Count> facetEntries = facet.getValues();
if (UtilValidate.isNotEmpty(facetEntries)) {
for (FacetField.Count fcount : facetEntries)
facetEntry.put(fcount.getName(), fcount.getCount());
facetFields.put(facet.getName(), facetEntry);
}
}
}
result.put("results", queryResult.getResults());
result.put("facetFields", facetFields);
result.put("facetQueries", facetQueries);
result.put("queryTime", queryResult.getElapsedTime());
result.put("listSize", queryResult.getResults().getNumFound());
// 2016-04-01: Need to translate this
//result.put("viewIndex", queryResult.getResults().getStart());
result.put("start", queryResult.getResults().getStart());
result.put("viewIndex", SolrQueryUtil.calcResultViewIndex(queryResult.getResults(), viewSize));
result.put("viewSize", viewSize);
result.put("tokenSuggestions", tokenSuggestions);
result.put("fullSuggestions", fullSuggestions);
} catch (Exception e) {
Debug.logError(e, "Solr: keywordSearch: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
}
return result;
}
/**
* Returns a map of the categories currently available under the root
* element.
*/
public static Map<String, Object> getAvailableCategories(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result;
try {
boolean displayProducts = Boolean.TRUE.equals(context.get("displayProducts"));
int viewIndex = 0;
int viewSize = 9;
if (displayProducts) {
viewIndex = (Integer) context.get("viewIndex");
viewSize = (Integer) context.get("viewSize");
}
String catalogId = (String) context.get("catalogId");
if (catalogId != null && catalogId.isEmpty()) catalogId = null; // TODO: REVIEW: is this necessary?
List<String> currentTrail = UtilGenerics.checkList(context.get("currentTrail"));
String productCategoryId = SolrCategoryUtil.getCategoryNameWithTrail((String) context.get("productCategoryId"),
catalogId, dctx, currentTrail);
String productId = (String) context.get("productId");
if (Debug.verboseOn()) Debug.logVerbose("Solr: getAvailableCategories: productCategoryId: " + productCategoryId, module);
Map<String, Object> query = getAvailableCategories(dctx, context, catalogId, productCategoryId, productId, null,
displayProducts, viewIndex, viewSize);
if (ServiceUtil.isError(query)) {
throw new Exception(ServiceUtil.getErrorMessage(query));
}
QueryResponse cat = (QueryResponse) query.get("rows");
result = ServiceUtil.returnSuccess();
result.put("numFound", (long) 0);
Map<String, Object> categories = new HashMap<>();
List<FacetField> catList = (List<FacetField>) cat.getFacetFields();
for (Iterator<FacetField> catIterator = catList.iterator(); catIterator.hasNext();) {
FacetField field = (FacetField) catIterator.next();
List<Count> catL = (List<Count>) field.getValues();
if (catL != null) {
// log.info("FacetFields = "+catL);
for (Iterator<Count> catIter = catL.iterator(); catIter.hasNext();) {
FacetField.Count f = (FacetField.Count) catIter.next();
if (f.getCount() > 0) {
categories.put(f.getName(), Long.toString(f.getCount()));
}
}
result.put("categories", categories);
result.put("numFound", cat.getResults().getNumFound());
// log.info("The returned map is this:"+result);
}
}
} catch (Exception e) {
result = ServiceUtil.returnError(e.toString());
result.put("numFound", (long) 0);
return result;
}
return result;
}
/**
* NOTE: This method is package-private for backward compat only and should not be made public; its interface is subject to change.
* Client code should call the solrAvailableCategories or solrSideDeepCategory service instead.
*/
static Map<String, Object> getAvailableCategories(DispatchContext dctx, Map<String, Object> context,
String catalogId, String categoryId, String productId, String facetPrefix, boolean displayProducts, int viewIndex, int viewSize) {
Map<String, Object> result;
try {
HttpSolrClient client = SolrUtil.getQueryHttpSolrClient((String) context.get("core"));
SolrQuery solrQuery = new SolrQuery();
String query;
if (categoryId != null) {
query = "+cat:"+ SolrExprUtil.escapeTermFull(categoryId);
} else if (productId != null) {
query = "+productId:" + SolrExprUtil.escapeTermFull(productId);
} else {
query = "*:*";
}
solrQuery.setQuery(query);
if (catalogId != null) {
solrQuery.addFilterQuery("+catalog:" + SolrExprUtil.escapeTermFull(catalogId));
}
SolrQueryUtil.addDefaultQueryFilters(solrQuery, context);
SolrQueryUtil.addFilterQueries(solrQuery, UtilGenerics.<String>checkList(context.get("queryFilters")));
if (displayProducts) {
if (viewSize > -1) {
solrQuery.setRows(viewSize);
} else
solrQuery.setRows(50000);
if (viewIndex > -1) {
// 2016-04-01: This must be calculated
//solrQuery.setStart(viewIndex);
if (viewSize > 0) {
solrQuery.setStart(viewSize * viewIndex);
}
}
} else {
solrQuery.setFields("cat");
solrQuery.setRows(0);
}
if(UtilValidate.isNotEmpty(facetPrefix)){
solrQuery.setFacetPrefix(facetPrefix);
}
solrQuery.setFacetMinCount(0);
solrQuery.setFacet(true);
solrQuery.addFacetField("cat");
solrQuery.setFacetLimit(-1);
if (Debug.verboseOn()) Debug.logVerbose("solr: solrQuery: " + solrQuery, module);
QueryResponse returnMap = client.query(solrQuery, METHOD.POST);
result = ServiceUtil.returnSuccess();
result.put("rows", returnMap);
result.put("numFound", returnMap.getResults().getNumFound());
} catch (Exception e) {
Debug.logError(e.getMessage(), module);
return ServiceUtil.returnError(e.getMessage());
}
return result;
}
/**
* Return a map of the side deep categories.
*/
public static Map<String, Object> getSideDeepCategories(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result;
try {
String catalogId = (String) context.get("catalogId");
if (catalogId != null && catalogId.isEmpty()) catalogId = null; // TODO: REVIEW: is this necessary?
List<String> currentTrail = UtilGenerics.checkList(context.get("currentTrail"));
// 2016-03-22: FIXME?: I think we could call getCategoryNameWithTrail with showDepth=false,
// instead of check in loop...
String productCategoryId = SolrCategoryUtil.getCategoryNameWithTrail((String) context.get("productCategoryId"), catalogId, dctx, currentTrail);
result = ServiceUtil.returnSuccess();
Map<String, List<Map<String, Object>>> catLevel = new HashMap<>();
if (Debug.verboseOn()) Debug.logVerbose("Solr: getSideDeepCategories: productCategoryId: " + productCategoryId, module);
// Add toplevel categories
String[] trailElements = productCategoryId.split("/");
long numFound = 0;
boolean isFirstElement = true;
// iterate over actual results
for (String element : trailElements) {
if (Debug.verboseOn()) Debug.logVerbose("Solr: getSideDeepCategories: iterating element: " + element, module);
List<Map<String, Object>> categories = new ArrayList<>();
int level;
// 2016-03-22: Don't make a query for the first element, which is the count,
// but for compatibility, still make a map entry for it
// NOTE: I think this could be skipped entirely because level 0 is replaced/taken by the
// first category, but leaving in to play it safe
if (isFirstElement) {
level = 0;
isFirstElement = false;
} else {
String categoryPath = SolrCategoryUtil.getCategoryNameWithTrail(element, catalogId, dctx, currentTrail);
String[] categoryPathArray = categoryPath.split("/");
level = Integer.parseInt(categoryPathArray[0]);
String facetPrefix = SolrCategoryUtil.getFacetFilterForCategory(categoryPath, dctx);
// 2016-03-22: IMPORTANT: the facetPrefix MUST end with / otherwise it will return unrelated categories!
// solr facetPrefix is not aware of our path delimiters
if (!facetPrefix.endsWith("/")) {
facetPrefix += "/";
}
// Debug.logInfo("categoryPath: "+categoryPath + "
// facetPrefix: "+facetPrefix,module);
Map<String, Object> query = getAvailableCategories(dctx, context, catalogId, categoryPath, null, facetPrefix, false, 0, 0);
if (ServiceUtil.isError(query)) {
throw new Exception(ServiceUtil.getErrorMessage(query));
}
QueryResponse cat = (QueryResponse) query.get("rows");
Long subNumFound = (Long) query.get("numFound");
if (subNumFound != null) {
numFound += subNumFound;
}
List<FacetField> catList = (List<FacetField>) cat.getFacetFields();
for (Iterator<FacetField> catIterator = catList.iterator(); catIterator.hasNext();) {
FacetField field = (FacetField) catIterator.next();
List<Count> catL = (List<Count>) field.getValues();
if (catL != null) {
for (Iterator<Count> catIter = catL.iterator(); catIter.hasNext();) {
FacetField.Count facet = (FacetField.Count) catIter.next();
if (facet.getCount() > 0) {
Map<String, Object> catMap = new HashMap<>();
List<String> iName = new LinkedList<>();
iName.addAll(Arrays.asList(facet.getName().split("/")));
// Debug.logInfo("topLevel "+topLevel,"");
// int l = Integer.parseInt((String)
// iName.getFirst());
catMap.put("catId", iName.get(iName.size() - 1)); // get last
iName.remove(0); // remove first
String path = facet.getName();
catMap.put("path", path);
if (level > 0) {
iName.remove(iName.size() - 1); // remove last
catMap.put("parentCategory", StringUtils.join(iName, "/"));
} else {
catMap.put("parentCategory", null);
}
catMap.put("count", Long.toString(facet.getCount()));
categories.add(catMap);
}
}
}
}
}
catLevel.put("menu-" + level, categories);
}
result.put("categories", catLevel);
result.put("numFound", numFound);
} catch (Exception e) {
result = ServiceUtil.returnError(e.toString());
result.put("numFound", (long) 0);
return result;
}
return result;
}
/**
* Rebuilds the solr index.
*/
public static Map<String, Object> rebuildSolrIndex(DispatchContext dctx, Map<String, Object> context) {
HttpSolrClient client = null;
Map<String, Object> result = null;
GenericDelegator delegator = (GenericDelegator) dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
//GenericValue userLogin = (GenericValue) context.get("userLogin");
//Locale locale = new Locale("de_DE");
// 2016-03-29: Only if dirty (or unknown)
Boolean onlyIfDirty = (Boolean) context.get("onlyIfDirty");
if (onlyIfDirty == null) onlyIfDirty = false;
// 2017-08-23: Only if effective Solr config version changed
Boolean ifConfigChange = (Boolean) context.get("ifConfigChange");
if (ifConfigChange == null) ifConfigChange = false;
if (onlyIfDirty || ifConfigChange) {
GenericValue solrStatus = SolrUtil.getSolrStatus(delegator);
String cfgVersion = SolrUtil.getSolrConfigVersionStatic();
String dataStatusId = solrStatus != null ? solrStatus.getString("dataStatusId") : null;
String dataCfgVersion = solrStatus != null ? solrStatus.getString("dataCfgVersion") : null;
boolean dataStatusOk = "SOLR_DATA_OK".equals(dataStatusId);
boolean dataCfgVerOk = cfgVersion.equals(dataCfgVersion);
// TODO: simplify this code structure (one more bool and it will be unmaintainable)
if (onlyIfDirty && ifConfigChange) {
if (dataStatusOk && dataCfgVerOk) {
result = ServiceUtil.returnSuccess("SOLR data is already marked OK; SOLR data is already at config version " + cfgVersion + "; not rebuilding");
result.put("numDocs", (int) 0);
result.put("executed", Boolean.FALSE);
return result;
}
} else if (onlyIfDirty) {
if (dataStatusOk) {
result = ServiceUtil.returnSuccess("SOLR data is already marked OK; not rebuilding");
result.put("numDocs", (int) 0);
result.put("executed", Boolean.FALSE);
return result;
}
} else if (ifConfigChange) {
if (dataCfgVerOk) {
result = ServiceUtil.returnSuccess("SOLR data is already at config version " + cfgVersion + "; not rebuilding");
result.put("numDocs", (int) 0);
result.put("executed", Boolean.FALSE);
return result;
}
}
if (onlyIfDirty && !dataStatusOk) {
Debug.logInfo("Solr: rebuildSolrIndex: [onlyIfDirty] Data is marked dirty (status: " + dataStatusId + "); reindexing proceeding...", module);
}
if (ifConfigChange && !dataCfgVerOk) {
Debug.logInfo("Solr: rebuildSolrIndex: [ifConfigChange] Data config version has changed (current: " + cfgVersion + ", previous: " + dataCfgVersion + "); reindexing proceeding...", module);
}
}
Boolean treatConnectErrorNonFatal = (Boolean) context.get("treatConnectErrorNonFatal");
Boolean clearAndUseCache = (Boolean) context.get("clearAndUseCache");
if (clearAndUseCache == null) clearAndUseCache = rebuildClearAndUseCacheDefault;
int numDocs = 0;
int numDocsIndexed = 0; // 2018-02: needed for accurate stats in case a client edit filters out products within loop
EntityListIterator prodIt = null;
boolean executed = false;
try {
client = SolrUtil.getUpdateHttpSolrClient((String) context.get("core"));
// 2018-02-20: new ability to wait for Solr to load
if (Boolean.TRUE.equals(context.get("waitSolrReady"))) {
// NOTE: skipping runSync for speed; we know the implementation...
Map<String, Object> waitCtx = new HashMap<>();
waitCtx.put("client", client);
Map<String, Object> waitResult = waitSolrReady(dctx, waitCtx); // params will be null
if (!ServiceUtil.isSuccess(waitResult)) {
throw new ScipioSolrException(ServiceUtil.getErrorMessage(waitResult)).setLightweight(true);
}
}
executed = true;
Debug.logInfo("Solr: rebuildSolrIndex: Clearing solr index", module);
// this removes everything from the index
client.deleteByQuery("*:*");
client.commit();
// NEW 2017-09-14: clear all entity caches at beginning, and then enable caching during
// the product reading - this should significantly speed up the process
// NOTE: we also clear it again at the end to avoid filling up entity cache with rarely-accessed records
if (clearAndUseCache) {
SolrProductUtil.clearProductEntityCaches(delegator, dispatcher);
}
Integer bufSize = (Integer) context.get("bufSize");
if (bufSize == null) {
bufSize = UtilProperties.getPropertyAsInteger(SolrUtil.solrConfigName, "solr.index.rebuild.record.buffer.size", 1000);
}
// now lets fetch all products
EntityFindOptions findOptions = new EntityFindOptions();
//findOptions.setResultSetType(EntityFindOptions.TYPE_SCROLL_INSENSITIVE); // not needed anymore, only for getPartialList (done manual instead)
prodIt = delegator.find("Product", null, null, null, null, findOptions);
numDocs = prodIt.getResultsSizeAfterPartialList();
int startIndex = 1;
int bufNumDocs = 0;
// NOTE: use ArrayList instead of LinkedList (EntityListIterator) in buffered mode because it will use less total memory
List<Map<String, Object>> solrDocs = (bufSize > 0) ? new ArrayList<>(Math.min(bufSize, numDocs)) : new LinkedList<>();
Map<String, Object> productContext = new HashMap<>(context);
productContext.put("useCache", clearAndUseCache);
boolean lastReached = false;
while (!lastReached) {
startIndex = startIndex + bufNumDocs;
// NOTE: the endIndex is actually a prediction, but if it's ever false, there is a serious DB problem
int endIndex;
if (bufSize > 0) endIndex = startIndex + Math.min(bufSize, numDocs-(startIndex-1)) - 1;
else endIndex = numDocs;
Debug.logInfo("Solr: rebuildSolrIndex: Reading products " + startIndex + "-" + endIndex + " / " + numDocs + " for indexing", module);
solrDocs.clear();
int numLeft = bufSize;
while ((bufSize <= 0 || numLeft > 0) && !lastReached) {
GenericValue product = prodIt.next();
if (product != null) {
Map<String, Object> dispatchContext = SolrProductUtil.getProductContent(product, dctx, productContext);
solrDocs.add(dispatchContext);
numDocsIndexed++;
numLeft--;
} else {
lastReached = true;
}
}
bufNumDocs = solrDocs.size();
if (bufNumDocs == 0) {
break;
}
// This adds all products to the Index (instantly)
Map<String, Object> servCtx = UtilMisc.toMap("fieldList", solrDocs, "treatConnectErrorNonFatal", treatConnectErrorNonFatal);
servCtx.put("useCache", clearAndUseCache);
copyStdServiceFieldsNotSet(context, servCtx);
Map<String, Object> runResult = dispatcher.runSync("addListToSolrIndex", servCtx);
if (ServiceUtil.isError(runResult) || ServiceUtil.isFailure(runResult)) {
String runMsg = ServiceUtil.getErrorMessage(runResult);
if (UtilValidate.isEmpty(runMsg)) {
runMsg = null;
}
if (ServiceUtil.isFailure(runResult)) result = ServiceUtil.returnFailure(runMsg);
else result = ServiceUtil.returnError(runMsg);
break;
}
}
if (result == null) {
Debug.logInfo("Solr: rebuildSolrIndex: Finished with " + numDocsIndexed + " documents indexed", module);
final String statusMsg = "Cleared solr index and reindexed " + numDocsIndexed + " documents";
result = ServiceUtil.returnSuccess(statusMsg);
}
} catch (SolrServerException e) {
if (e.getCause() != null && e.getCause() instanceof ConnectException) {
final String statusStr = "Failure connecting to solr server to rebuild index; index not updated";
if (Boolean.TRUE.equals(treatConnectErrorNonFatal)) {
Debug.logWarning(e, "Solr: rebuildSolrIndex: " + statusStr, module);
result = ServiceUtil.returnFailure(statusStr);
} else {
Debug.logError(e, "Solr: rebuildSolrIndex: " + statusStr, module);
result = ServiceUtil.returnError(statusStr);
}
} else {
Debug.logError(e, "Solr: rebuildSolrIndex: Server error: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
}
} catch (Exception e) {
if (e instanceof ScipioSolrException && ((ScipioSolrException) e).isLightweight()) {
// don't print the error itself, too verbose
Debug.logError("Solr: rebuildSolrIndex: Error: " + e.getMessage(), module);
} else {
Debug.logError(e, "Solr: rebuildSolrIndex: Error: " + e.getMessage(), module);
}
result = ServiceUtil.returnError(e.toString());
} finally {
if (prodIt != null) {
try {
prodIt.close();
} catch(Exception e) {
}
}
if (clearAndUseCache) {
SolrProductUtil.clearProductEntityCaches(delegator, dispatcher);
}
}
// If success, mark data as good
if (result != null && ServiceUtil.isSuccess(result)) {
// TODO?: REVIEW?: 2018-01-03: for this method, for now, unlike updateToSolr,
// we will leave the status update in the same transaction as parent service,
// because it is technically possible that there was an error in the parent transaction
// prior to this service call that modified product data, or a transaction snafu
// that causes a modification in the product data being indexed to be rolled back,
// and in that case we don't want to mark the data as OK because another reindex
// will be needed as soon as possible.
// NOTE: in such case, we should even explicitly mark data as dirty, but I'm not
// certain we can do that reliably from here.
//SolrUtil.setSolrDataStatusIdSepTxSafe(delegator, "SOLR_DATA_OK", true);
SolrUtil.setSolrDataStatusIdSafe(delegator, "SOLR_DATA_OK", true);
}
result.put("numDocs", numDocs);
result.put("executed", executed);
return result;
}
/**
* Rebuilds the solr index - auto run.
*/
public static Map<String, Object> rebuildSolrIndexAuto(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result;
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
boolean startupForce = isReindexStartupForce(delegator, dispatcher);
if (startupForce) {
Debug.logInfo("Solr: rebuildSolrIndexAuto: Execution forced by force-startup system or config property", module);
}
boolean force = startupForce;
boolean autoRunEnabled = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.index.rebuild.autoRun.enabled", false);
if (force || autoRunEnabled) {
Boolean onlyIfDirty = (Boolean) context.get("onlyIfDirty");
if (onlyIfDirty == null) {
onlyIfDirty = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.index.rebuild.autoRun.onlyIfDirty", false);
}
Boolean ifConfigChange = (Boolean) context.get("ifConfigChange");
if (ifConfigChange == null) {
ifConfigChange = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.index.rebuild.autoRun.ifConfigChange", false);
}
if (force) {
onlyIfDirty = false;
ifConfigChange = false;
}
Boolean waitSolrReady = (Boolean) context.get("waitSolrReady");
if (waitSolrReady == null) {
waitSolrReady = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.index.rebuild.autoRun.waitSolrReady", true);
}
Debug.logInfo("Solr: rebuildSolrIndexAuto: Launching index check/rebuild (onlyIfDirty: " + onlyIfDirty
+ ", ifConfigChange: " + ifConfigChange + ", waitSolrReady: " + waitSolrReady + ")", module);
Map<String, Object> servCtx;
try {
servCtx = dctx.makeValidContext("rebuildSolrIndex", ModelService.IN_PARAM, context);
servCtx.put("onlyIfDirty", onlyIfDirty);
servCtx.put("ifConfigChange", ifConfigChange);
servCtx.put("waitSolrReady", waitSolrReady);
Map<String, Object> servResult = dispatcher.runSync("rebuildSolrIndex", servCtx);
if (ServiceUtil.isSuccess(servResult)) {
String respMsg = (String) servResult.get(ModelService.SUCCESS_MESSAGE);
if (UtilValidate.isNotEmpty(respMsg)) {
Debug.logInfo("Solr: rebuildSolrIndexAuto: rebuildSolrIndex returned success: " + respMsg, module);
} else {
Debug.logInfo("Solr: rebuildSolrIndexAuto: rebuildSolrIndex returned success", module);
}
} else {
Debug.logError("Solr: rebuildSolrIndexAuto: rebuildSolrIndex returned an error: " +
ServiceUtil.getErrorMessage(servResult), module);
}
// Just pass it all back, hackish but should work
result = new HashMap<>();
result.putAll(servResult);
} catch (Exception e) {
Debug.logError(e, "Solr: rebuildSolrIndexAuto: Error: " + e.getMessage(), module);
return ServiceUtil.returnError(e.getMessage());
}
} else {
Debug.logInfo("Solr: rebuildSolrIndexAuto: not running - disabled", module);
result = ServiceUtil.returnSuccess();
}
return result;
}
private static boolean isReindexStartupForce(Delegator delegator, LocalDispatcher dispatcher) {
if (reindexAutoForceRan) return false;
synchronized(SolrProductSearch.class) {
if (reindexAutoForceRan) return false;
reindexAutoForceRan = true;
return getReindexStartupForceProperty(delegator, dispatcher, false);
}
}
private static Boolean getReindexStartupForceProperty(Delegator delegator, LocalDispatcher dispatcher, Boolean defaultValue) {
Boolean force = UtilMisc.booleanValueVersatile(System.getProperty(reindexStartupForceSysProp));
if (force != null) return force;
return UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, reindexStartupForceConfigProp, defaultValue);
}
/**
* Rebuilds the solr index - only if dirty.
*/
public static Map<String, Object> rebuildSolrIndexIfDirty(DispatchContext dctx, Map<String, Object> context) {
return rebuildSolrIndex(dctx, context);
}
/**
* Marks SOLR data as dirty.
*/
public static Map<String, Object> setSolrDataStatus(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result;
GenericDelegator delegator = (GenericDelegator) dctx.getDelegator();
try {
SolrUtil.setSolrDataStatusId(delegator, (String) context.get("dataStatusId"), false);
result = ServiceUtil.returnSuccess();
} catch (Exception e) {
result = ServiceUtil.returnError("Unable to set SOLR data status: " + e.getMessage());
}
return result;
}
static void copyStdServiceFieldsNotSet(Map<String, Object> srcCtx, Map<String, Object> destCtx) {
copyServiceFieldsNotSet(srcCtx, destCtx, "locale", "userLogin", "timeZone");
}
static void copyServiceFieldsNotSet(Map<String, Object> srcCtx, Map<String, Object> destCtx, String... fieldNames) {
for(String fieldName : fieldNames) {
if (!destCtx.containsKey(fieldName)) destCtx.put(fieldName, srcCtx.get(fieldName));
}
}
public static Map<String, Object> checkSolrReady(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result = ServiceUtil.returnSuccess();
boolean enabled = SolrUtil.isSystemInitialized(); // NOTE: this must NOT use SolrUtil.isSolrLocalWebappPresent() anymore
result.put("enabled", enabled);
if (enabled) {
try {
HttpSolrClient client = (HttpSolrClient) context.get("client");
if (client == null) client = SolrUtil.getQueryHttpSolrClient((String) context.get("core"));
result.put("ready", SolrUtil.isSolrWebappReady(client));
} catch (Exception e) {
Debug.logWarning(e, "Solr: checkSolrReady: error trying to check if Solr ready: " + e.getMessage(), module);
result = ServiceUtil.returnFailure("Error while checking if Solr ready");
result.put("enabled", enabled);
result.put("ready", false);
return result;
}
} else {
result.put("ready", false);
}
return result;
}
public static Map<String, Object> waitSolrReady(DispatchContext dctx, Map<String, Object> context) {
if (!SolrUtil.isSolrEnabled()) { // NOTE: this must NOT use SolrUtil.isSolrLocalWebappPresent() anymore
return ServiceUtil.returnFailure("Solr not enabled");
}
HttpSolrClient client = null;
try {
client = (HttpSolrClient) context.get("client");
if (client == null) client = SolrUtil.getQueryHttpSolrClient((String) context.get("core"));
if (SolrUtil.isSystemInitializedAssumeEnabled() && SolrUtil.isSolrWebappReady(client)) {
if (Debug.verboseOn()) Debug.logInfo("Solr: waitSolrReady: Solr is ready, continuing", module);
return ServiceUtil.returnSuccess();
}
} catch (Exception e) {
Debug.logWarning(e, "Solr: waitSolrReady: error trying to check if Solr ready: " + e.getMessage(), module);
return ServiceUtil.returnFailure("Error while checking if Solr ready");
}
Integer maxChecks = (Integer) context.get("maxChecks");
if (maxChecks == null) maxChecks = UtilProperties.getPropertyAsInteger(SolrUtil.solrConfigName, "solr.service.waitSolrReady.maxChecks", null);
if (maxChecks != null && maxChecks < 0) maxChecks = null;
Integer sleepTime = (Integer) context.get("sleepTime");
if (sleepTime == null) sleepTime = UtilProperties.getPropertyAsInteger(SolrUtil.solrConfigName, "solr.service.waitSolrReady.sleepTime", null);
if (sleepTime == null || sleepTime < 0) sleepTime = 3000;
int checkNum = 2; // first already done above
while((maxChecks == null || checkNum <= maxChecks)) {
Debug.logInfo("Solr: waitSolrReady: Solr not ready, waiting " + sleepTime + "ms (check " + checkNum + (maxChecks != null ? "/" + maxChecks : "") + ")", module);
try {
Thread.sleep(sleepTime);
} catch (Exception e) {
Debug.logWarning("Solr: waitSolrReady: interrupted while waiting for Solr: " + e.getMessage(), module);
return ServiceUtil.returnFailure("Solr not ready, interrupted while waiting");
}
try {
if (SolrUtil.isSystemInitializedAssumeEnabled() && SolrUtil.isSolrWebappReady(client)) {
Debug.logInfo("Solr: waitSolrReady: Solr is ready, continuing", module);
return ServiceUtil.returnSuccess();
}
} catch (Exception e) {
Debug.logWarning(e, "Solr: waitSolrReady: error trying to check if Solr ready: " + e.getMessage(), module);
return ServiceUtil.returnFailure("Error while checking if Solr ready");
}
checkNum++;
}
return ServiceUtil.returnFailure("Solr not ready, reached max wait time");
}
public static Map<String, Object> reloadSolrSecurityAuthorizations(DispatchContext dctx, Map<String, Object> context) {
if (!SolrUtil.isSystemInitialized()) { // NOTE: this must NOT use SolrUtil.isSolrLocalWebappPresent() anymore
return ServiceUtil.returnFailure("Solr not enabled or system not ready");
}
try {
HttpSolrClient client = SolrUtil.getAdminHttpSolrClientFromUrl(SolrUtil.getSolrWebappUrl());
//ModifiableSolrParams params = new ModifiableSolrParams();
//// this is very sketchy, I don't think ModifiableSolrParams were meant for this
//params.set("set-user-role", (String) null);
//SolrRequest<?> request = new GenericSolrRequest(METHOD.POST, CommonParams.AUTHZ_PATH, params);
SolrRequest<?> request = new DirectJsonRequest(CommonParams.AUTHZ_PATH,
"{\"set-user-role\":{}}"); // "{\"set-user-role\":{\"dummy\":\"dummy\"}}"
client.request(request);
Debug.logInfo("Solr: reloadSolrSecurityAuthorizations: invoked reload", module);
return ServiceUtil.returnSuccess();
} catch (Exception e) {
Debug.logError("Solr: reloadSolrSecurityAuthorizations: error: " + e.getMessage(), module);
return ServiceUtil.returnError("Error reloading Solr security authorizations");
}
}
}
| applications/solr/src/com/ilscipio/scipio/solr/SolrProductSearch.java | package com.ilscipio.scipio.solr;
import java.io.IOException;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Collation;
import org.apache.solr.client.solrj.response.SpellCheckResponse.Suggestion;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.CommonParams;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericDelegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.transaction.TransactionUtil;
import org.ofbiz.entity.util.EntityFindOptions;
import org.ofbiz.entity.util.EntityListIterator;
import org.ofbiz.product.product.ProductWorker;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceSyncRegistrations;
import org.ofbiz.service.ServiceSyncRegistrations.ServiceSyncRegistration;
import org.ofbiz.service.ServiceUtil;
import com.ilscipio.scipio.solr.util.DirectJsonRequest;
/**
* Base class for OFBiz Test Tools test case implementations.
*/
public abstract class SolrProductSearch {
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
private static final boolean rebuildClearAndUseCacheDefault = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName,
"solr.index.rebuild.clearAndUseCache", false);
private static final String defaultRegisterUpdateToSolrUpdateSrv = UtilProperties.getPropertyValue(SolrUtil.solrConfigName,
"solr.service.registerUpdateToSolr.updateSrv", "updateToSolr");
private static boolean reindexAutoForceRan = false;
private static final String reindexStartupForceSysProp = "scipio.solr.reindex.startup.force";
private static final String reindexStartupForceConfigProp = "solr.index.rebuild.startup.force";
public static Map<String, Object> addToSolr(DispatchContext dctx, Map<String, Object> context) {
return updateToSolrCommon(dctx, context, Boolean.TRUE, true);
}
private static Map<String, Object> addToSolrCore(DispatchContext dctx, Map<String, Object> context, GenericValue product, String productId) {
Map<String, Object> result;
if (Debug.verboseOn()) Debug.logVerbose("Solr: addToSolr: Running indexing for productId '" + productId + "'", module);
try {
Map<String, Object> dispatchContext = SolrProductUtil.getProductContent(product, dctx, context);
dispatchContext.put("treatConnectErrorNonFatal", SolrUtil.isEcaTreatConnectErrorNonFatal());
copyStdServiceFieldsNotSet(context, dispatchContext);
Map<String, Object> runResult = dctx.getDispatcher().runSync("addToSolrIndex", dispatchContext);
String runMsg = ServiceUtil.getErrorMessage(runResult);
if (UtilValidate.isEmpty(runMsg)) {
runMsg = null;
}
if (ServiceUtil.isError(runResult)) {
result = ServiceUtil.returnError(runMsg);
} else if (ServiceUtil.isFailure(runResult)) {
result = ServiceUtil.returnFailure(runMsg);
} else {
result = ServiceUtil.returnSuccess();
}
} catch (Exception e) {
Debug.logError(e, "Solr: addToSolr: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
}
return result;
}
public static Map<String, Object> removeFromSolr(DispatchContext dctx, Map<String, Object> context) {
return updateToSolrCommon(dctx, context, Boolean.FALSE, true);
}
private static Map<String, Object> removeFromSolrCore(DispatchContext dctx, Map<String, Object> context, String productId) {
Map<String, Object> result;
// NOTE: log this as info because it's the only log line
Debug.logInfo("Solr: removeFromSolr: Removing productId '" + productId + "' from index", module);
try {
HttpSolrClient client = SolrUtil.getUpdateHttpSolrClient((String) context.get("core"));
client.deleteByQuery("productId:" + SolrExprUtil.escapeTermFull(productId));
client.commit();
result = ServiceUtil.returnSuccess();
} catch (Exception e) {
Debug.logError(e, "Solr: removeFromSolr: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
}
return result;
}
public static final Map<String, Boolean> updateToSolrActionMap = UtilMisc.toMap("add", true, "remove", false); // default: "auto" -> null
private static final String getUpdateToSolrAction(Boolean forceAdd) {
if (forceAdd == null) return null;
else return forceAdd ? "add" : "remove";
}
public static Map<String, Object> updateToSolr(DispatchContext dctx, Map<String, Object> context) {
return updateToSolrCommon(dctx, context, updateToSolrActionMap.get(context.get("action")), true);
}
public static Map<String, Object> registerUpdateToSolr(DispatchContext dctx, Map<String, Object> context) {
return updateToSolrCommon(dctx, context, updateToSolrActionMap.get(context.get("action")), false);
}
/**
* Core implementation for the updateToSolr, addToSolr, removeFromSolr, and registerUpdateToSolr services.
* <p>
* Upon error, unless instructed otherwise, this marks the Solr data as dirty.
*/
private static Map<String, Object> updateToSolrCommon(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd, boolean immediate) {
Map<String, Object> result;
// DEV NOTE: BOILERPLATE ECA ENABLE CHECKING PATTERN, KEEP SAME FOR SERVICES ABOVE/BELOW
boolean manual = Boolean.TRUE.equals(context.get("manual"));
boolean indexed = false;
Boolean webappInitPassed = null;
boolean skippedDueToWebappInit = false;
if (manual || SolrUtil.isSolrEcaEnabled()) {
webappInitPassed = SolrUtil.isSolrEcaWebappInitCheckPassed();
if (webappInitPassed) {
String productId;
// NOTE: 2017-04-13: type may be org.ofbiz.entity.GenericValue or GenericPk, so use common parent GenericEntity (even better: Map)
//GenericValue productInstance = (GenericValue) context.get("instance");
@SuppressWarnings("unchecked")
Map<String, Object> productInst = (Map<String, Object>) context.get("instance");
if (productInst != null) productId = (String) productInst.get("productId");
else productId = (String) context.get("productId");
@SuppressWarnings("unchecked")
Map<String, Map<String, Object>> productIds = (Map<String, Map<String, Object>>) context.get("productIds");
if (immediate) {
if (productId == null && productIds == null) return ServiceUtil.returnError("missing product instance, productId or productIds map");
result = updateToSolrCore(dctx, context, forceAdd, productId, productInst, productIds);
if (ServiceUtil.isSuccess(result)) indexed = true;
} else {
if (TransactionUtil.isTransactionInPlaceSafe()) {
if (productId == null) return ServiceUtil.returnError("missing product instance or productId");
result = registerUpdateToSolrForTxCore(dctx, context, forceAdd, productId, productInst);
if (ServiceUtil.isSuccess(result)) indexed = true; // NOTE: not really indexed; this is just to skip the mark-dirty below
} else {
final String reason = "No transaction in place";
if ("update".equals(context.get("noTransMode"))) {
if (productId == null && productIds == null) return ServiceUtil.returnError("missing product instance, productId or productIds map");
Debug.logInfo("Solr: registerUpdateToSolr: " + reason + "; running immediate index update", module);
result = updateToSolrCore(dctx, context, forceAdd, productId, productInst, productIds);
if (ServiceUtil.isSuccess(result)) indexed = true;
} else { // "mark-dirty"
result = ServiceUtil.returnSuccess();
if (manual) {
Debug.logInfo("Solr: registerUpdateToSolr: " + reason + "; skipping solr indexing completely (manual mode; not marking dirty)", module);
} else {
Debug.logInfo("Solr: registerUpdateToSolr: " + reason + "; skipping solr indexing, will mark dirty", module);
indexed = false;
}
}
}
}
} else {
if (Debug.verboseOn()) Debug.logVerbose("Solr: updateToSolr: Solr webapp not available; skipping indexing for product", module);
result = ServiceUtil.returnSuccess();
skippedDueToWebappInit = true;
}
} else {
if (Debug.verboseOn()) Debug.logVerbose("Solr: updateToSolr: Solr ECA indexing disabled; skipping indexing for product", module);
result = ServiceUtil.returnSuccess();
}
if (!manual && !indexed && UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.eca.markDirty.enabled", false)) {
boolean markDirtyNoWebappCheck = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.eca.markDirty.noWebappCheck", false);
if (!(markDirtyNoWebappCheck && skippedDueToWebappInit)) {
if (Debug.verboseOn()) Debug.logVerbose("Solr: updateToSolr: Did not update index for product; marking SOLR data as dirty (old)", module);
SolrUtil.setSolrDataStatusIdSepTxSafe(dctx.getDelegator(), "SOLR_DATA_OLD", false);
}
}
return result;
}
/**
* Multi-product core update.
* <p>
* WARN: this edits the products map in-place. We're assuming this isn't an issue...
* Added 2018-07-23.
*/
private static Map<String, Object> updateToSolrCore(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd, String productId, Map<String, Object> productInst,
Map<String, Map<String, Object>> products) {
// WARN: this edits the products map in-place. We're assuming this isn't an issue...
if (productId != null) {
if (products == null) products = new HashMap<>(); // SPECIAL: here no need for LinkedHashMap, but other cases should be LinkedHashMap
Map<String, Object> productProps;
try {
productProps = dctx.getModelService("updateToSolrSingleInterface")
.makeValid(context, ModelService.IN_PARAM, false, null);
} catch (GenericServiceException e) {
Debug.logError(e, "Solr: updateToSolr: Error parsing service parameters for updateToSolrSingleInterface: " + e.getMessage() , module);
return ServiceUtil.returnError(e.getMessage());
}
productProps.put("instance", productInst);
productProps.put("action", getUpdateToSolrAction(forceAdd));
products.put(productId, productProps);
}
return updateToSolrCore(dctx, context, products);
}
/**
* Multi-product core update.
* Added 2018-07-19.
*/
private static Map<String, Object> updateToSolrCore(DispatchContext dctx, Map<String, Object> context, Map<String, Map<String, Object>> products) {
// SPECIAL: 2018-01-03: do not update to Solr if the current transaction marked as rollback,
// because the rollbacked data may be (even likely to be) product data that we don't want in index
// FIXME?: this cannot handle transaction rollbacks triggered after us! Some client diligence still needed for that...
try {
if (TransactionUtil.isTransactionInPlace() && TransactionUtil.getStatus() == TransactionUtil.STATUS_MARKED_ROLLBACK) {
Debug.logWarning("Solr: updateToSolr: Current transaction is marked for rollback; aborting solr index update", module);
return ServiceUtil.returnFailure("Current transaction is marked for rollback; aborting solr index update");
}
} catch (Exception e) {
Debug.logError("Solr: updateToSolr: Failed to check transaction status; aborting solr index update: " + e.getMessage(), module);
return ServiceUtil.returnError("Failed to check transaction status; aborting solr index update");
}
List<String> errorMessageList = new ArrayList<>();
// pre-process for variants
// NOTE: products should be a LinkedHashMap;
// expandedProducts doesn't need to be LinkedHashMap, but do it anyway
// to keep more readable order of indexing operations in the log
Map<String, Map<String, Object>> expandedProducts = new LinkedHashMap<>();
for(Map.Entry<String, Map<String, Object>> entry : products.entrySet()) {
String productId = entry.getKey();
Map<String, Object> props = entry.getValue();
Map<String, Object> productInst = UtilGenerics.checkMap(props.get("instance"));
Boolean forceAdd = updateToSolrActionMap.get(props.get("action"));
boolean updateVariantsDeep = Boolean.TRUE.equals(props.get("updateVariantsDeep"));
boolean updateVariants = updateVariantsDeep || Boolean.TRUE.equals(props.get("updateVariants"));
boolean updateVirtualDeep = Boolean.TRUE.equals(props.get("updateVirtualDeep"));
boolean updateVirtual = updateVirtualDeep || Boolean.TRUE.equals(props.get("updateVirtual"));
expandedProducts.put(productId, props);
if (updateVariants || updateVirtual) {
if (Boolean.FALSE.equals(forceAdd)) {
// Here the Product will already have been removed so we can't determine its
// variants; but that's ok because it makes no sense for virtual to have been
// removed without its variants removed, which should have come through an ECA
// either in the same transaction or another before it.
if (Debug.verboseOn()) {
Debug.logVerbose("Solr: updateToSolr: Ignoring updateVariants/updateVirtual request for (forced) removal of product '"
+ productId + "'; the variants should already be scheduled for removal (logically) through another mechanism", module);
}
} else {
GenericValue product;
if (productInst instanceof GenericValue) {
product = (GenericValue) productInst;
} else {
try {
product = dctx.getDelegator().findOne("Product", UtilMisc.toMap("productId", productId), false);
} catch (Exception e) {
Debug.logError(e, "Solr: updateToSolr: Could not lookup product '" + productId + "': " + e.getMessage(), module);
return ServiceUtil.returnError(e.toString());
}
if (Boolean.TRUE.equals(forceAdd) && product == null) {
return ServiceUtil.returnError("Product not found for productId: " + productId);
}
// update the props with the instance to prevent double lookup in updateToSolrCore below
// NOTE: SPECIAL MARKER for null
props = new HashMap<>(props);
props.put("instance", (product != null) ? product : Collections.emptyMap());
expandedProducts.put(productId, props);
}
if (product == null) {
if (Debug.verboseOn()) {
Debug.logVerbose("Solr: updateToSolr: Ignoring updateVariants/updateVirtual request for (forced) removal of product '"
+ productId + "'; the variants should already be scheduled for removal (logically) through another mechanism", module);
}
} else {
if (updateVariants && Boolean.TRUE.equals(product.getBoolean("isVirtual"))) {
if (Debug.verboseOn()) {
Debug.logVerbose("Solr: updateToSolr: Product '" + productId + "' is virtual for add operation"
+ " and updateVariants true; looking up variants for update", module);
}
List<GenericValue> variantProducts;
try {
if (updateVariantsDeep) {
variantProducts = ProductWorker.getVariantProductsDeepDfs(dctx.getDelegator(), dctx.getDispatcher(),
product, null, null, false);
} else {
variantProducts = ProductWorker.getVariantProducts(dctx.getDelegator(), dctx.getDispatcher(),
product, null, null, false);
}
} catch (GeneralException e) {
Debug.logError(e, "Solr: updateToSolr: Could not lookup product variants for '"
+ productId + "' for updateVariants: " + e.getMessage(), module);
return ServiceUtil.returnError(e.toString());
}
for(GenericValue variantProduct : variantProducts) {
// NOTE: we crush any prior entry for same product;
// chronological last update request in transaction has priority
Map<String, Object> variantProps = new HashMap<>();
variantProps.put("instance", variantProduct);
variantProps.put("forceAdd", forceAdd); // no need: getUpdateToSolrAction(forceAdd)
String variantProductId = variantProduct.getString("productId");
// re-add the key to LinkedHashMap keep a readable order in log
expandedProducts.remove(variantProductId);
expandedProducts.put(variantProductId, variantProps);
}
}
if (updateVirtual && Boolean.TRUE.equals(product.getBoolean("isVariant"))) {
if (Debug.verboseOn()) {
Debug.logVerbose("Solr: updateToSolr: Product '" + productId + "' is variant for add operation"
+ " and updateVirtual true; looking up virtual for update", module);
}
List<GenericValue> virtualProducts;
try {
// TODO: REVIEW: in most stock code these would be "-fromDate" and maxPerLevel=1,
// but I see no good reason to limit it...
final List<String> orderBy = null;
final Integer maxPerLevel = null;
if (updateVirtualDeep) {
virtualProducts = ProductWorker.getVirtualProductsDeepDfs(dctx.getDelegator(), dctx.getDispatcher(),
product, orderBy, maxPerLevel, null, false);
} else {
virtualProducts = ProductWorker.getVirtualProducts(dctx.getDelegator(), dctx.getDispatcher(),
product, orderBy, maxPerLevel, null, false);
}
} catch(Exception e) {
Debug.logError(e, "Solr: updateToSolr: Could not lookup virtual product for variant product '" + productId + "'", module);
return ServiceUtil.returnError("Could not lookup virtual product for variant product '" + productId + "'");
}
if (virtualProducts.isEmpty()) {
Debug.logWarning("Solr: updateToSolr: Product '"
+ productId + "' is variant but found no parent product (either the association is being removed, or data error)", module);
} else {
for(GenericValue virtualProduct : virtualProducts) {
Map<String, Object> variantProps = new HashMap<>();
variantProps.put("instance", virtualProduct);
variantProps.put("forceAdd", forceAdd); // no need: getUpdateToSolrAction(forceAdd)
String virtualProductId = virtualProduct.getString("productId");
// re-add the key to LinkedHashMap keep a readable order in log
expandedProducts.remove(virtualProductId);
expandedProducts.put(virtualProductId, variantProps);
}
}
}
}
}
}
}
for(Map.Entry<String, Map<String, Object>> entry : expandedProducts.entrySet()) {
String productId = entry.getKey();
Map<String, Object> props = entry.getValue();
Map<String, Object> productInst = UtilGenerics.checkMap(props.get("instance"));
Object actionObj = props.get("action");
Boolean forceAdd = (actionObj instanceof Boolean) ? (Boolean) actionObj : updateToSolrActionMap.get(actionObj);
Map<String, Object> updateSingleResult = updateToSolrCore(dctx, context, forceAdd, productId, productInst);
if (!ServiceUtil.isSuccess(updateSingleResult)) {
errorMessageList.add(ServiceUtil.getErrorMessage(updateSingleResult));
}
}
Map<String, Object> result = (errorMessageList.size() > 0) ?
ServiceUtil.returnError(errorMessageList) :
ServiceUtil.returnSuccess();
return result;
}
private static Map<String, Object> updateToSolrCore(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd, String productId, Map<String, Object> productInst) {
Map<String, Object> result;
if (Boolean.FALSE.equals(forceAdd)) {
result = removeFromSolrCore(dctx, context, productId);
} else {
GenericValue product;
if (productInst instanceof GenericValue) {
product = (GenericValue) productInst;
} else if (productInst != null && productInst.isEmpty()) { // SPECIAL MARKER to prevent double-lookup when null
product = null;
} else { // SPECIAL MARKER to prevent re-lookup
try {
product = dctx.getDelegator().findOne("Product", UtilMisc.toMap("productId", productId), false);
} catch (Exception e) {
Debug.logError(e, "Solr: updateToSolr: Could not lookup product '" + productId + "': " + e.getMessage(), module);
return ServiceUtil.returnError(e.toString());
}
}
if (Boolean.TRUE.equals(forceAdd)) {
if (product == null) {
return ServiceUtil.returnError("Product not found for productId: " + productId);
}
result = addToSolrCore(dctx, context, product, productId);
} else {
if (product != null) {
if (Debug.verboseOn()) Debug.logVerbose("Solr: updateToSolr: productId '" + productId + "' found in system; running solr add", module);
result = addToSolrCore(dctx, context, product, productId);
} else {
if (Debug.verboseOn()) Debug.logVerbose("Solr: updateToSolr: productId '" + productId + "' not found in system; running solr remove", module);
result = removeFromSolrCore(dctx, context, productId);
}
}
}
return result;
}
/**
* Registers an updateToSolr call at the end of the transaction using global-commit event.
* <p>
* NOTE: the checking loop below may not currently handle all possible cases imaginable,
* but should cover the ones we're using.
* <p>
* UPDATE: 2018-07-24: We now use a single update service call with a map of productIds,
* to minimize overhead.
* WARN: DEV NOTE: This now edits the update service productIds context map in-place
* in the already-registered service; this is not "proper" but there is no known current case
* where it should cause an issue and it removes more overhead.
*/
private static Map<String, Object> registerUpdateToSolrForTxCore(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd, String productId, Map<String, Object> productInst) {
String updateSrv = (String) context.get("updateSrv");
if (updateSrv == null) updateSrv = defaultRegisterUpdateToSolrUpdateSrv;
try {
LocalDispatcher dispatcher = dctx.getDispatcher();
ServiceSyncRegistrations regs = dispatcher.getServiceSyncRegistrations();
Map<String, Object> productProps = dctx.getModelService("updateToSolrSingleInterface")
.makeValid(context, ModelService.IN_PARAM, false, null);
// IMPORTANT: DO NOT PASS AN INSTANCE; use productId to force updateToSolr to re-query the Product
// after transaction committed (by the time updateSrv is called, this instance may be invalid)
productProps.remove("instance");
productProps.put("action", getUpdateToSolrAction(forceAdd));
Collection<ServiceSyncRegistration> updateSrvRegs = regs.getCommitRegistrationsForService(updateSrv);
if (updateSrvRegs.size() >= 1) {
if (updateSrvRegs.size() >= 2) {
Debug.logError("Solr: registerUpdateToSolr: Found more than one transaction commit registration"
+ " for update service '" + updateSrv + "'; should not happen! (coding or ECA config error)", module);
}
ServiceSyncRegistration reg = updateSrvRegs.iterator().next();
// WARN: editing existing registration's service context in-place
@SuppressWarnings("unchecked")
Map<String, Map<String, Object>> productIds = (Map<String, Map<String, Object>>) reg.getContext().get("productIds");
productIds.remove(productId); // this is a LinkedHashMap, so remove existing first so we keep the "real" order
productIds.put(productId, productProps);
return ServiceUtil.returnSuccess("Updated transaction global-commit registration for " + updateSrv + " to include productId '" + productId + ")");
} else {
// register the service
Map<String, Object> servCtx = new HashMap<>();
// NOTE: this ditches the "manual" boolean (updateToSolrControlInterface), because can't support it here with only one updateSrv call
servCtx.put("locale", context.get("locale"));
servCtx.put("userLogin", context.get("userLogin"));
servCtx.put("timeZone", context.get("timeZone"));
// IMPORTANT: LinkedHashMap keeps order of changes across transaction
Map<String, Map<String, Object>> productIds = new LinkedHashMap<>();
productIds.put(productId, productProps);
servCtx.put("productIds", productIds);
regs.addCommitService(dctx, updateSrv, null, servCtx, false, false);
return ServiceUtil.returnSuccess("Registered " + updateSrv + " to run at transaction global-commit for productId '" + productId + ")");
}
} catch (Exception e) {
final String errMsg = "Could not register " + updateSrv + " to run at transaction global-commit for product '" + productId + "'";
Debug.logError(e, "Solr: registerUpdateToSolr: " + productId, module);
return ServiceUtil.returnError(errMsg);
}
}
/**
* Adds product to solr index.
*/
public static Map<String, Object> addToSolrIndex(DispatchContext dctx, Map<String, Object> context) {
HttpSolrClient client = null;
Map<String, Object> result;
String productId = (String) context.get("productId");
// connectErrorNonFatal is a necessary option because in some cases it
// may be considered normal that solr server is unavailable;
// don't want to return error and abort transactions in these cases.
Boolean treatConnectErrorNonFatal = (Boolean) context.get("treatConnectErrorNonFatal");
boolean useCache = Boolean.TRUE.equals(context.get("useCache"));
try {
Debug.logInfo("Solr: Indexing product '" + productId + "'", module);
client = SolrUtil.getUpdateHttpSolrClient((String) context.get("core"));
// Debug.log(server.ping().toString());
// Construct Documents
SolrInputDocument doc1 = SolrProductUtil.generateSolrProductDocument(dctx.getDelegator(), dctx.getDispatcher(), context, useCache);
Collection<SolrInputDocument> docs = new ArrayList<>();
if (Debug.verboseOn()) Debug.logVerbose("Solr: Indexing document: " + doc1.toString(), module);
docs.add(doc1);
// push Documents to server
client.add(docs);
client.commit();
final String statusStr = "Product '" + productId + "' indexed";
if (Debug.verboseOn()) Debug.logVerbose("Solr: " + statusStr, module);
result = ServiceUtil.returnSuccess(statusStr);
} catch (MalformedURLException e) {
Debug.logError(e, "Solr: addToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "urlError");
} catch (SolrServerException e) {
if (e.getCause() != null && e.getCause() instanceof ConnectException) {
final String statusStr = "Failure connecting to solr server to commit productId " + context.get("productId") + "; product not updated";
if (Boolean.TRUE.equals(treatConnectErrorNonFatal)) {
Debug.logWarning(e, "Solr: " + statusStr, module);
result = ServiceUtil.returnFailure(statusStr);
} else {
Debug.logError(e, "Solr: " + statusStr, module);
result = ServiceUtil.returnError(statusStr);
}
result.put("errorType", "connectError");
} else {
Debug.logError(e, "Solr: addToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "solrServerError");
}
} catch (IOException e) {
Debug.logError(e, "Solr: addToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "ioError");
} catch (Exception e) {
Debug.logError(e, "Solr: addToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "general");
} finally {
try {
if (UtilValidate.isNotEmpty(client))
client.close();
} catch (IOException e) {
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "ioError");
}
}
return result;
}
/**
* Adds a List of products to the solr index.
* <p>
* This is faster than reflushing the index each time.
*/
public static Map<String, Object> addListToSolrIndex(DispatchContext dctx, Map<String, Object> context) {
HttpSolrClient client = null;
Map<String, Object> result;
Boolean treatConnectErrorNonFatal = (Boolean) context.get("treatConnectErrorNonFatal");
boolean useCache = Boolean.TRUE.equals(context.get("useCache"));
try {
Collection<SolrInputDocument> docs = new ArrayList<>();
List<Map<String, Object>> fieldList = UtilGenerics.<Map<String, Object>> checkList(context.get("fieldList"));
if (fieldList.size() > 0) {
Debug.logInfo("Solr: addListToSolrIndex: Generating and adding " + fieldList.size() + " documents to solr index", module);
// Construct Documents
for (Map<String, Object> productContent : fieldList) {
SolrInputDocument doc1 = SolrProductUtil.generateSolrProductDocument(dctx.getDelegator(), dctx.getDispatcher(), productContent, useCache);
if (Debug.verboseOn()) Debug.logVerbose("Solr: addListToSolrIndex: Processed document for indexing: " + doc1.toString(), module);
docs.add(doc1);
}
// push Documents to server
client = SolrUtil.getUpdateHttpSolrClient((String) context.get("core"));
client.add(docs);
client.commit();
}
final String statusStr = "Added " + fieldList.size() + " documents to solr index";
Debug.logInfo("Solr: addListToSolrIndex: " + statusStr, module);
result = ServiceUtil.returnSuccess(statusStr);
} catch (MalformedURLException e) {
Debug.logError(e, "Solr: addListToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "urlError");
} catch (SolrServerException e) {
if (e.getCause() != null && e.getCause() instanceof ConnectException) {
final String statusStr = "Failure connecting to solr server to commit product list; products not updated";
if (Boolean.TRUE.equals(treatConnectErrorNonFatal)) {
Debug.logWarning(e, "Solr: addListToSolrIndex: " + statusStr, module);
result = ServiceUtil.returnFailure(statusStr);
} else {
Debug.logError(e, "Solr: addListToSolrIndex: " + statusStr, module);
result = ServiceUtil.returnError(statusStr);
}
result.put("errorType", "connectError");
} else {
Debug.logError(e, "Solr: addListToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "solrServerError");
}
} catch (IOException e) {
Debug.logError(e, "Solr: addListToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "ioError");
} catch (Exception e) {
Debug.logError(e, "Solr: addListToSolrIndex: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "general");
} finally {
try {
if (client != null) client.close();
} catch (IOException e) {
result = ServiceUtil.returnError(e.toString());
result.put("errorType", "ioError");
}
}
return result;
}
/**
* Runs a query on the Solr Search Engine and returns the results.
* <p>
* This function only returns an object of type QueryResponse, so it is
* probably not a good idea to call it directly from within the groovy files
* (As a decent example on how to use it, however, use keywordSearch
* instead).
*/
public static Map<String, Object> runSolrQuery(DispatchContext dctx, Map<String, Object> context) {
// get Connection
HttpSolrClient client = null;
Map<String, Object> result;
try {
// DEV NOTE: WARN: 2017-08-22: BEWARE PARSING FIELDS HERE - should be avoided here
// the passed values may not be simple fields names, they require complex expressions containing spaces and special chars
// (for example the old "queryFilter" parameter was unusable, so now have "queryFilters" list in addition).
String solrUsername = (String) context.get("solrUsername");
String solrPassword = (String) context.get("solrPassword");
client = SolrUtil.getQueryHttpSolrClient((String) context.get("core"), solrUsername, solrPassword);
// create Query Object
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery((String) context.get("query"));
String queryType = (String) context.get("queryType");
if (UtilValidate.isNotEmpty(queryType)) {
solrQuery.setRequestHandler(queryType);
}
String defType = (String) context.get("defType");
if (UtilValidate.isNotEmpty(defType)) {
solrQuery.set("defType", defType);
}
Boolean faceted = (Boolean) context.get("facet");
if (Boolean.TRUE.equals(faceted)) {
solrQuery.setFacet(faceted);
solrQuery.addFacetField("manu");
solrQuery.addFacetField("cat");
solrQuery.setFacetMinCount(1);
solrQuery.setFacetLimit(8);
solrQuery.addFacetQuery("listPrice:[0 TO 50]");
solrQuery.addFacetQuery("listPrice:[50 TO 100]");
solrQuery.addFacetQuery("listPrice:[100 TO 250]");
solrQuery.addFacetQuery("listPrice:[250 TO 500]");
solrQuery.addFacetQuery("listPrice:[500 TO 1000]");
solrQuery.addFacetQuery("listPrice:[1000 TO 2500]");
solrQuery.addFacetQuery("listPrice:[2500 TO 5000]");
solrQuery.addFacetQuery("listPrice:[5000 TO 10000]");
solrQuery.addFacetQuery("listPrice:[10000 TO 50000]");
solrQuery.addFacetQuery("listPrice:[50000 TO *]");
}
Boolean spellCheck = (Boolean) context.get("spellcheck");
if (Boolean.TRUE.equals(spellCheck)) {
solrQuery.setParam("spellcheck", true);
solrQuery.setParam("spellcheck.collate", true);
Object spellDictObj = context.get("spellDict");
if (spellDictObj instanceof String) {
if (UtilValidate.isNotEmpty((String) spellDictObj)) {
solrQuery.setParam("spellcheck.dictionary", (String) spellDictObj);
}
} else if (spellDictObj instanceof Collection) {
for(String spellDict : UtilGenerics.<String>checkCollection(spellDictObj)) {
solrQuery.add("spellcheck.dictionary", spellDict);
}
}
}
Boolean highlight = (Boolean) context.get("highlight");
if (Boolean.TRUE.equals(highlight)) {
// FIXME: unhardcode markup
solrQuery.setHighlight(highlight);
solrQuery.setHighlightSimplePre("<span class=\"highlight\">");
solrQuery.addHighlightField("description");
solrQuery.setHighlightSimplePost("</span>");
solrQuery.setHighlightSnippets(2);
}
// Set additional Parameter
// SolrQuery.ORDER order = SolrQuery.ORDER.desc;
// 2016-04-01: start must be calculated
//if (context.get("viewIndex") != null && (Integer) context.get("viewIndex") > 0) {
// solrQuery.setStart((Integer) context.get("viewIndex"));
//}
//if (context.get("viewSize") != null && (Integer) context.get("viewSize") > 0) {
// solrQuery.setRows((Integer) context.get("viewSize"));
//}
Integer start = (Integer) context.get("start");
Integer viewIndex = (Integer) context.get("viewIndex");
Integer viewSize = (Integer) context.get("viewSize");
if (viewSize != null && viewSize > 0) {
solrQuery.setRows(viewSize);
}
if (start != null) {
if (start > 0) {
solrQuery.setStart(start);
}
} else if (viewIndex != null) {
if (viewIndex > 0 && viewSize != null && viewSize > 0) {
solrQuery.setStart(viewIndex * viewSize);
}
}
String queryFilter = (String) context.get("queryFilter");
if (UtilValidate.isNotEmpty((String) queryFilter)) {
// WARN: 2017-08-17: we don't really want splitting on whitespace anymore, because it
// slaughters complex queries and ignores escaping; callers should use queryFilters list instead.
// However, we can at least fix a bug here where we can do better and split on \\s+ instead
//solrQuery.addFilterQuery(((String) queryFilter).split(" "));
solrQuery.addFilterQuery(((String) queryFilter).trim().split("\\s+"));
}
Collection<String> queryFilters = UtilGenerics.checkCollection(context.get("queryFilters"));
SolrQueryUtil.addFilterQueries(solrQuery, queryFilters);
if ((String) context.get("returnFields") != null) {
solrQuery.setFields((String) context.get("returnFields"));
}
String defaultOp = (String) context.get("defaultOp");
if (UtilValidate.isNotEmpty(defaultOp)) {
solrQuery.set("q.op", defaultOp);
}
String queryFields = (String) context.get("queryFields");
if (UtilValidate.isNotEmpty(queryFields)) {
solrQuery.set("qf", queryFields);
}
Map<String, ?> queryParams = UtilGenerics.checkMap(context.get("queryParams"));
if (queryParams != null) {
for(Map.Entry<String, ?> entry : queryParams.entrySet()) {
String name = entry.getKey();
Object value = entry.getValue();
if (value == null) {
// NOTE: this removes the param when null
solrQuery.set(name, (String) value);
} else if (value instanceof String) {
solrQuery.set(name, (String) value);
} else if (value instanceof Integer) {
solrQuery.set(name, (Integer) value);
} else if (value instanceof Long) {
solrQuery.set(name, ((Long) value).intValue());
} else if (value instanceof Boolean) {
solrQuery.set(name, (Boolean) value);
} else {
throw new IllegalArgumentException("queryParams entry '" + name
+ "' value unsupported type (supported: String, Integer, Long, Boolean): " + value.getClass().getName());
}
}
}
// if((Boolean)context.get("sortByReverse"))order.reverse();
String sortBy = (String) context.get("sortBy");
if (UtilValidate.isNotEmpty(sortBy)) {
SolrQuery.ORDER order = null;
Boolean sortByReverse = (Boolean) context.get("sortByReverse");
if (sortByReverse != null) {
order = sortByReverse ? SolrQuery.ORDER.desc : SolrQuery.ORDER.asc;
}
// TODO?: REVIEW?: 2017-08-22: this parsing poses a problem and may interfere with queries.
// I have restricted it to only remove the first "-" if it's preceeded by whitespace, but
// there's no guarantee it still might not interfere with query too...
//sortBy = sortBy.replaceFirst("-", "");
// TODO: REVIEW: trim would probably be fine & simplify check, but I don't know for sure
//sortBy = sortBy.trim();
int dashIndex = sortBy.indexOf('-');
if (dashIndex >= 0 && sortBy.substring(0, dashIndex).trim().isEmpty()) { // this checks if dash is first char or preceeded by space only
if (order == null) {
order = SolrQuery.ORDER.desc;
}
sortBy = sortBy.substring(dashIndex + 1);
}
if (order == null) {
order = SolrQuery.ORDER.asc;
}
solrQuery.setSort(sortBy, order);
}
if ((String) context.get("facetQuery") != null) {
solrQuery.addFacetQuery((String) context.get("facetQuery"));
}
//QueryResponse rsp = client.query(solrQuery, METHOD.POST); // old way (can't configure the request)
QueryRequest req = new QueryRequest(solrQuery, METHOD.POST);
if (solrUsername != null) {
// This will override the credentials stored in (Scipio)HttpSolrClient, if any
req.setBasicAuthCredentials(solrUsername, solrPassword);
}
QueryResponse rsp = req.process(client);
result = ServiceUtil.returnSuccess();
result.put("queryResult", rsp);
} catch (Exception e) {
Debug.logError(e, "Solr: runSolrQuery: Error: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
if (SolrQueryUtil.isSolrQuerySyntaxError(e)) {
result.put("errorType", "query-syntax");
} else {
result.put("errorType", "general");
}
// TODO? nestedErrorMessage: did not succeed extracting this reliably
}
return result;
}
/**
* Performs solr products search.
*/
public static Map<String, Object> productsSearch(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result;
LocalDispatcher dispatcher = dctx.getDispatcher();
try {
Map<String, Object> dispatchMap = dctx.makeValidContext("runSolrQuery", ModelService.IN_PARAM, context);
if (UtilValidate.isNotEmpty(context.get("productCategoryId"))) {
String productCategoryId = (String) context.get("productCategoryId");
// causes erroneous results for similar-name categories
//dispatchMap.put("query", "cat:*" + SolrUtil.escapeTermFull(productCategoryId) + "*");
boolean includeSubCategories = !Boolean.FALSE.equals(context.get("includeSubCategories"));
dispatchMap.put("query", SolrExprUtil.makeCategoryIdFieldQueryEscape("cat", productCategoryId, includeSubCategories));
} else {
return ServiceUtil.returnError("Missing productCategoryId"); // TODO: localize
}
Integer viewSize = (Integer) dispatchMap.get("viewSize");
//Integer viewIndex = (Integer) dispatchMap.get("viewIndex");
dispatchMap.put("facet", false); // (always false)
dispatchMap.put("spellcheck", false); // 2017-09: changed to false (always false)
if (dispatchMap.get("highlight") == null) dispatchMap.put("highlight", false); // 2017-09: default changed to false
List<String> queryFilters = getEnsureQueryFiltersModifiable(dispatchMap);
SolrQueryUtil.addDefaultQueryFilters(queryFilters, context); // 2018-05-25
Map<String, Object> searchResult = dispatcher.runSync("runSolrQuery", dispatchMap);
if (ServiceUtil.isFailure(searchResult)) {
return copySolrQueryExtraOutParams(searchResult, ServiceUtil.returnFailure(ServiceUtil.getErrorMessage(searchResult)));
} else if (ServiceUtil.isError(searchResult)) {
return copySolrQueryExtraOutParams(searchResult, ServiceUtil.returnError(ServiceUtil.getErrorMessage(searchResult)));
}
QueryResponse queryResult = (QueryResponse) searchResult.get("queryResult");
result = ServiceUtil.returnSuccess();
result.put("results", queryResult.getResults());
result.put("listSize", queryResult.getResults().getNumFound());
// 2016-04-01: Need to translate this
//result.put("viewIndex", queryResult.getResults().getStart());
result.put("start", queryResult.getResults().getStart());
result.put("viewIndex", SolrQueryUtil.calcResultViewIndex(queryResult.getResults(), viewSize));
result.put("viewSize", viewSize);
} catch (Exception e) {
Debug.logError(e, "Solr: productsSearch: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
}
return result;
}
private static Map<String, Object> copySolrQueryExtraOutParams(Map<String, Object> src, Map<String, Object> dest) {
if (src.containsKey("errorType")) dest.put("errorType", src.get("errorType"));
if (src.containsKey("nestedErrorMessage")) dest.put("nestedErrorMessage", src.get("nestedErrorMessage"));
return dest;
}
private static List<String> getEnsureQueryFiltersModifiable(Map<String, Object> context) {
List<String> queryFilters = UtilGenerics.checkList(context.get("queryFilters"));
if (queryFilters != null) queryFilters = new ArrayList<>(queryFilters);
else queryFilters = new ArrayList<>();
context.put("queryFilters", queryFilters);
return queryFilters;
}
/**
* Performs keyword search.
* <p>
* The search form requires the result to be in a specific layout, so this
* will generate the proper results.
*/
public static Map<String, Object> keywordSearch(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result;
LocalDispatcher dispatcher = dctx.getDispatcher();
try {
Map<String, Object> dispatchMap = dctx.makeValidContext("runSolrQuery", ModelService.IN_PARAM, context);
if (UtilValidate.isEmpty((String) dispatchMap.get("query"))) {
dispatchMap.put("dispatchMap", "*:*");
}
Integer viewSize = (Integer) dispatchMap.get("viewSize");
//Integer viewIndex = (Integer) dispatchMap.get("viewIndex");
if (dispatchMap.get("facet") == null) dispatchMap.put("facet", false); // 2017-09: default changed to false
if (dispatchMap.get("spellcheck") == null) dispatchMap.put("spellcheck", false); // 2017-09: default changed to false
if (dispatchMap.get("highlight") == null) dispatchMap.put("highlight", false); // 2017-09: default changed to false
List<String> queryFilters = getEnsureQueryFiltersModifiable(dispatchMap);
SolrQueryUtil.addDefaultQueryFilters(queryFilters, context); // 2018-05-25
Map<String, Object> searchResult = dispatcher.runSync("runSolrQuery", dispatchMap);
if (ServiceUtil.isFailure(searchResult)) {
return copySolrQueryExtraOutParams(searchResult, ServiceUtil.returnFailure(ServiceUtil.getErrorMessage(searchResult)));
} else if (ServiceUtil.isError(searchResult)) {
return copySolrQueryExtraOutParams(searchResult, ServiceUtil.returnError(ServiceUtil.getErrorMessage(searchResult)));
}
QueryResponse queryResult = (QueryResponse) searchResult.get("queryResult");
Boolean isCorrectlySpelled = Boolean.TRUE.equals(dispatchMap.get("spellcheck")) ? Boolean.TRUE : null;
Map<String, List<String>> tokenSuggestions = null;
List<String> fullSuggestions = null;
SpellCheckResponse spellResp = queryResult.getSpellCheckResponse();
if (spellResp != null) {
isCorrectlySpelled = spellResp.isCorrectlySpelled();
if (spellResp.getSuggestions() != null) {
tokenSuggestions = new LinkedHashMap<>();
for(Suggestion suggestion : spellResp.getSuggestions()) {
tokenSuggestions.put(suggestion.getToken(), suggestion.getAlternatives());
}
if (Debug.verboseOn()) Debug.logVerbose("Solr: Spelling: Token suggestions: " + tokenSuggestions, module);
}
// collations 2017-09-14, much more useful than the individual word suggestions
if (spellResp.getCollatedResults() != null) {
fullSuggestions = new ArrayList<>();
for(Collation collation : spellResp.getCollatedResults()) {
fullSuggestions.add(collation.getCollationQueryString());
}
if (Debug.verboseOn()) Debug.logVerbose("Solr: Spelling: Collations: " + fullSuggestions, module);
}
}
result = ServiceUtil.returnSuccess();
result.put("isCorrectlySpelled", isCorrectlySpelled);
Map<String, Integer> facetQuery = queryResult.getFacetQuery();
Map<String, String> facetQueries = null;
if (facetQuery != null) {
facetQueries = new HashMap<>();
for (String fq : facetQuery.keySet()) {
if (facetQuery.get(fq).intValue() > 0)
facetQueries.put(fq, fq.replaceAll("^.*\\u005B(.*)\\u005D", "$1") + " (" + facetQuery.get(fq).intValue() + ")");
}
}
List<FacetField> facets = queryResult.getFacetFields();
Map<String, Map<String, Long>> facetFields = null;
if (facets != null) {
facetFields = new HashMap<>();
for (FacetField facet : facets) {
Map<String, Long> facetEntry = new HashMap<>();
List<FacetField.Count> facetEntries = facet.getValues();
if (UtilValidate.isNotEmpty(facetEntries)) {
for (FacetField.Count fcount : facetEntries)
facetEntry.put(fcount.getName(), fcount.getCount());
facetFields.put(facet.getName(), facetEntry);
}
}
}
result.put("results", queryResult.getResults());
result.put("facetFields", facetFields);
result.put("facetQueries", facetQueries);
result.put("queryTime", queryResult.getElapsedTime());
result.put("listSize", queryResult.getResults().getNumFound());
// 2016-04-01: Need to translate this
//result.put("viewIndex", queryResult.getResults().getStart());
result.put("start", queryResult.getResults().getStart());
result.put("viewIndex", SolrQueryUtil.calcResultViewIndex(queryResult.getResults(), viewSize));
result.put("viewSize", viewSize);
result.put("tokenSuggestions", tokenSuggestions);
result.put("fullSuggestions", fullSuggestions);
} catch (Exception e) {
Debug.logError(e, "Solr: keywordSearch: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
}
return result;
}
/**
* Returns a map of the categories currently available under the root
* element.
*/
public static Map<String, Object> getAvailableCategories(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result;
try {
boolean displayProducts = Boolean.TRUE.equals(context.get("displayProducts"));
int viewIndex = 0;
int viewSize = 9;
if (displayProducts) {
viewIndex = (Integer) context.get("viewIndex");
viewSize = (Integer) context.get("viewSize");
}
String catalogId = (String) context.get("catalogId");
if (catalogId != null && catalogId.isEmpty()) catalogId = null; // TODO: REVIEW: is this necessary?
List<String> currentTrail = UtilGenerics.checkList(context.get("currentTrail"));
String productCategoryId = SolrCategoryUtil.getCategoryNameWithTrail((String) context.get("productCategoryId"),
catalogId, dctx, currentTrail);
String productId = (String) context.get("productId");
if (Debug.verboseOn()) Debug.logVerbose("Solr: getAvailableCategories: productCategoryId: " + productCategoryId, module);
Map<String, Object> query = getAvailableCategories(dctx, context, catalogId, productCategoryId, productId, null,
displayProducts, viewIndex, viewSize);
if (ServiceUtil.isError(query)) {
throw new Exception(ServiceUtil.getErrorMessage(query));
}
QueryResponse cat = (QueryResponse) query.get("rows");
result = ServiceUtil.returnSuccess();
result.put("numFound", (long) 0);
Map<String, Object> categories = new HashMap<>();
List<FacetField> catList = (List<FacetField>) cat.getFacetFields();
for (Iterator<FacetField> catIterator = catList.iterator(); catIterator.hasNext();) {
FacetField field = (FacetField) catIterator.next();
List<Count> catL = (List<Count>) field.getValues();
if (catL != null) {
// log.info("FacetFields = "+catL);
for (Iterator<Count> catIter = catL.iterator(); catIter.hasNext();) {
FacetField.Count f = (FacetField.Count) catIter.next();
if (f.getCount() > 0) {
categories.put(f.getName(), Long.toString(f.getCount()));
}
}
result.put("categories", categories);
result.put("numFound", cat.getResults().getNumFound());
// log.info("The returned map is this:"+result);
}
}
} catch (Exception e) {
result = ServiceUtil.returnError(e.toString());
result.put("numFound", (long) 0);
return result;
}
return result;
}
/**
* NOTE: This method is package-private for backward compat only and should not be made public; its interface is subject to change.
* Client code should call the solrAvailableCategories or solrSideDeepCategory service instead.
*/
static Map<String, Object> getAvailableCategories(DispatchContext dctx, Map<String, Object> context,
String catalogId, String categoryId, String productId, String facetPrefix, boolean displayProducts, int viewIndex, int viewSize) {
Map<String, Object> result;
try {
HttpSolrClient client = SolrUtil.getQueryHttpSolrClient((String) context.get("core"));
SolrQuery solrQuery = new SolrQuery();
String query;
if (categoryId != null) {
query = "+cat:"+ SolrExprUtil.escapeTermFull(categoryId);
} else if (productId != null) {
query = "+productId:" + SolrExprUtil.escapeTermFull(productId);
} else {
query = "*:*";
}
solrQuery.setQuery(query);
if (catalogId != null) {
solrQuery.addFilterQuery("+catalog:" + SolrExprUtil.escapeTermFull(catalogId));
}
SolrQueryUtil.addDefaultQueryFilters(solrQuery, context);
SolrQueryUtil.addFilterQueries(solrQuery, UtilGenerics.<String>checkList(context.get("queryFilters")));
if (displayProducts) {
if (viewSize > -1) {
solrQuery.setRows(viewSize);
} else
solrQuery.setRows(50000);
if (viewIndex > -1) {
// 2016-04-01: This must be calculated
//solrQuery.setStart(viewIndex);
if (viewSize > 0) {
solrQuery.setStart(viewSize * viewIndex);
}
}
} else {
solrQuery.setFields("cat");
solrQuery.setRows(0);
}
if(UtilValidate.isNotEmpty(facetPrefix)){
solrQuery.setFacetPrefix(facetPrefix);
}
solrQuery.setFacetMinCount(0);
solrQuery.setFacet(true);
solrQuery.addFacetField("cat");
solrQuery.setFacetLimit(-1);
if (Debug.verboseOn()) Debug.logVerbose("solr: solrQuery: " + solrQuery, module);
QueryResponse returnMap = client.query(solrQuery, METHOD.POST);
result = ServiceUtil.returnSuccess();
result.put("rows", returnMap);
result.put("numFound", returnMap.getResults().getNumFound());
} catch (Exception e) {
Debug.logError(e.getMessage(), module);
return ServiceUtil.returnError(e.getMessage());
}
return result;
}
/**
* Return a map of the side deep categories.
*/
public static Map<String, Object> getSideDeepCategories(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result;
try {
String catalogId = (String) context.get("catalogId");
if (catalogId != null && catalogId.isEmpty()) catalogId = null; // TODO: REVIEW: is this necessary?
List<String> currentTrail = UtilGenerics.checkList(context.get("currentTrail"));
// 2016-03-22: FIXME?: I think we could call getCategoryNameWithTrail with showDepth=false,
// instead of check in loop...
String productCategoryId = SolrCategoryUtil.getCategoryNameWithTrail((String) context.get("productCategoryId"), catalogId, dctx, currentTrail);
result = ServiceUtil.returnSuccess();
Map<String, List<Map<String, Object>>> catLevel = new HashMap<>();
if (Debug.verboseOn()) Debug.logVerbose("Solr: getSideDeepCategories: productCategoryId: " + productCategoryId, module);
// Add toplevel categories
String[] trailElements = productCategoryId.split("/");
long numFound = 0;
boolean isFirstElement = true;
// iterate over actual results
for (String element : trailElements) {
if (Debug.verboseOn()) Debug.logVerbose("Solr: getSideDeepCategories: iterating element: " + element, module);
List<Map<String, Object>> categories = new ArrayList<>();
int level;
// 2016-03-22: Don't make a query for the first element, which is the count,
// but for compatibility, still make a map entry for it
// NOTE: I think this could be skipped entirely because level 0 is replaced/taken by the
// first category, but leaving in to play it safe
if (isFirstElement) {
level = 0;
isFirstElement = false;
} else {
String categoryPath = SolrCategoryUtil.getCategoryNameWithTrail(element, catalogId, dctx, currentTrail);
String[] categoryPathArray = categoryPath.split("/");
level = Integer.parseInt(categoryPathArray[0]);
String facetPrefix = SolrCategoryUtil.getFacetFilterForCategory(categoryPath, dctx);
// 2016-03-22: IMPORTANT: the facetPrefix MUST end with / otherwise it will return unrelated categories!
// solr facetPrefix is not aware of our path delimiters
if (!facetPrefix.endsWith("/")) {
facetPrefix += "/";
}
// Debug.logInfo("categoryPath: "+categoryPath + "
// facetPrefix: "+facetPrefix,module);
Map<String, Object> query = getAvailableCategories(dctx, context, catalogId, categoryPath, null, facetPrefix, false, 0, 0);
if (ServiceUtil.isError(query)) {
throw new Exception(ServiceUtil.getErrorMessage(query));
}
QueryResponse cat = (QueryResponse) query.get("rows");
Long subNumFound = (Long) query.get("numFound");
if (subNumFound != null) {
numFound += subNumFound;
}
List<FacetField> catList = (List<FacetField>) cat.getFacetFields();
for (Iterator<FacetField> catIterator = catList.iterator(); catIterator.hasNext();) {
FacetField field = (FacetField) catIterator.next();
List<Count> catL = (List<Count>) field.getValues();
if (catL != null) {
for (Iterator<Count> catIter = catL.iterator(); catIter.hasNext();) {
FacetField.Count facet = (FacetField.Count) catIter.next();
if (facet.getCount() > 0) {
Map<String, Object> catMap = new HashMap<>();
List<String> iName = new LinkedList<>();
iName.addAll(Arrays.asList(facet.getName().split("/")));
// Debug.logInfo("topLevel "+topLevel,"");
// int l = Integer.parseInt((String)
// iName.getFirst());
catMap.put("catId", iName.get(iName.size() - 1)); // get last
iName.remove(0); // remove first
String path = facet.getName();
catMap.put("path", path);
if (level > 0) {
iName.remove(iName.size() - 1); // remove last
catMap.put("parentCategory", StringUtils.join(iName, "/"));
} else {
catMap.put("parentCategory", null);
}
catMap.put("count", Long.toString(facet.getCount()));
categories.add(catMap);
}
}
}
}
}
catLevel.put("menu-" + level, categories);
}
result.put("categories", catLevel);
result.put("numFound", numFound);
} catch (Exception e) {
result = ServiceUtil.returnError(e.toString());
result.put("numFound", (long) 0);
return result;
}
return result;
}
/**
* Rebuilds the solr index.
*/
public static Map<String, Object> rebuildSolrIndex(DispatchContext dctx, Map<String, Object> context) {
HttpSolrClient client = null;
Map<String, Object> result = null;
GenericDelegator delegator = (GenericDelegator) dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
//GenericValue userLogin = (GenericValue) context.get("userLogin");
//Locale locale = new Locale("de_DE");
// 2016-03-29: Only if dirty (or unknown)
Boolean onlyIfDirty = (Boolean) context.get("onlyIfDirty");
if (onlyIfDirty == null) onlyIfDirty = false;
// 2017-08-23: Only if effective Solr config version changed
Boolean ifConfigChange = (Boolean) context.get("ifConfigChange");
if (ifConfigChange == null) ifConfigChange = false;
if (onlyIfDirty || ifConfigChange) {
GenericValue solrStatus = SolrUtil.getSolrStatus(delegator);
String cfgVersion = SolrUtil.getSolrConfigVersionStatic();
String dataStatusId = solrStatus != null ? solrStatus.getString("dataStatusId") : null;
String dataCfgVersion = solrStatus != null ? solrStatus.getString("dataCfgVersion") : null;
boolean dataStatusOk = "SOLR_DATA_OK".equals(dataStatusId);
boolean dataCfgVerOk = cfgVersion.equals(dataCfgVersion);
// TODO: simplify this code structure (one more bool and it will be unmaintainable)
if (onlyIfDirty && ifConfigChange) {
if (dataStatusOk && dataCfgVerOk) {
result = ServiceUtil.returnSuccess("SOLR data is already marked OK; SOLR data is already at config version " + cfgVersion + "; not rebuilding");
result.put("numDocs", (int) 0);
result.put("executed", Boolean.FALSE);
return result;
}
} else if (onlyIfDirty) {
if (dataStatusOk) {
result = ServiceUtil.returnSuccess("SOLR data is already marked OK; not rebuilding");
result.put("numDocs", (int) 0);
result.put("executed", Boolean.FALSE);
return result;
}
} else if (ifConfigChange) {
if (dataCfgVerOk) {
result = ServiceUtil.returnSuccess("SOLR data is already at config version " + cfgVersion + "; not rebuilding");
result.put("numDocs", (int) 0);
result.put("executed", Boolean.FALSE);
return result;
}
}
if (onlyIfDirty && !dataStatusOk) {
Debug.logInfo("Solr: rebuildSolrIndex: [onlyIfDirty] Data is marked dirty (status: " + dataStatusId + "); reindexing proceeding...", module);
}
if (ifConfigChange && !dataCfgVerOk) {
Debug.logInfo("Solr: rebuildSolrIndex: [ifConfigChange] Data config version has changed (current: " + cfgVersion + ", previous: " + dataCfgVersion + "); reindexing proceeding...", module);
}
}
Boolean treatConnectErrorNonFatal = (Boolean) context.get("treatConnectErrorNonFatal");
Boolean clearAndUseCache = (Boolean) context.get("clearAndUseCache");
if (clearAndUseCache == null) clearAndUseCache = rebuildClearAndUseCacheDefault;
int numDocs = 0;
int numDocsIndexed = 0; // 2018-02: needed for accurate stats in case a client edit filters out products within loop
EntityListIterator prodIt = null;
boolean executed = false;
try {
client = SolrUtil.getUpdateHttpSolrClient((String) context.get("core"));
// 2018-02-20: new ability to wait for Solr to load
if (Boolean.TRUE.equals(context.get("waitSolrReady"))) {
// NOTE: skipping runSync for speed; we know the implementation...
Map<String, Object> waitCtx = new HashMap<>();
waitCtx.put("client", client);
Map<String, Object> waitResult = waitSolrReady(dctx, waitCtx); // params will be null
if (!ServiceUtil.isSuccess(waitResult)) {
throw new ScipioSolrException(ServiceUtil.getErrorMessage(waitResult)).setLightweight(true);
}
}
executed = true;
Debug.logInfo("Solr: rebuildSolrIndex: Clearing solr index", module);
// this removes everything from the index
client.deleteByQuery("*:*");
client.commit();
// NEW 2017-09-14: clear all entity caches at beginning, and then enable caching during
// the product reading - this should significantly speed up the process
// NOTE: we also clear it again at the end to avoid filling up entity cache with rarely-accessed records
if (clearAndUseCache) {
SolrProductUtil.clearProductEntityCaches(delegator, dispatcher);
}
Integer bufSize = (Integer) context.get("bufSize");
if (bufSize == null) {
bufSize = UtilProperties.getPropertyAsInteger(SolrUtil.solrConfigName, "solr.index.rebuild.record.buffer.size", 1000);
}
// now lets fetch all products
EntityFindOptions findOptions = new EntityFindOptions();
//findOptions.setResultSetType(EntityFindOptions.TYPE_SCROLL_INSENSITIVE); // not needed anymore, only for getPartialList (done manual instead)
prodIt = delegator.find("Product", null, null, null, null, findOptions);
numDocs = prodIt.getResultsSizeAfterPartialList();
int startIndex = 1;
int bufNumDocs = 0;
// NOTE: use ArrayList instead of LinkedList (EntityListIterator) in buffered mode because it will use less total memory
List<Map<String, Object>> solrDocs = (bufSize > 0) ? new ArrayList<>(Math.min(bufSize, numDocs)) : new LinkedList<>();
Map<String, Object> productContext = new HashMap<>(context);
productContext.put("useCache", clearAndUseCache);
boolean lastReached = false;
while (!lastReached) {
startIndex = startIndex + bufNumDocs;
// NOTE: the endIndex is actually a prediction, but if it's ever false, there is a serious DB problem
int endIndex;
if (bufSize > 0) endIndex = startIndex + Math.min(bufSize, numDocs-(startIndex-1)) - 1;
else endIndex = numDocs;
Debug.logInfo("Solr: rebuildSolrIndex: Reading products " + startIndex + "-" + endIndex + " / " + numDocs + " for indexing", module);
solrDocs.clear();
int numLeft = bufSize;
while ((bufSize <= 0 || numLeft > 0) && !lastReached) {
GenericValue product = prodIt.next();
if (product != null) {
Map<String, Object> dispatchContext = SolrProductUtil.getProductContent(product, dctx, productContext);
solrDocs.add(dispatchContext);
numDocsIndexed++;
numLeft--;
} else {
lastReached = true;
}
}
bufNumDocs = solrDocs.size();
if (bufNumDocs == 0) {
break;
}
// This adds all products to the Index (instantly)
Map<String, Object> servCtx = UtilMisc.toMap("fieldList", solrDocs, "treatConnectErrorNonFatal", treatConnectErrorNonFatal);
servCtx.put("useCache", clearAndUseCache);
copyStdServiceFieldsNotSet(context, servCtx);
Map<String, Object> runResult = dispatcher.runSync("addListToSolrIndex", servCtx);
if (ServiceUtil.isError(runResult) || ServiceUtil.isFailure(runResult)) {
String runMsg = ServiceUtil.getErrorMessage(runResult);
if (UtilValidate.isEmpty(runMsg)) {
runMsg = null;
}
if (ServiceUtil.isFailure(runResult)) result = ServiceUtil.returnFailure(runMsg);
else result = ServiceUtil.returnError(runMsg);
break;
}
}
if (result == null) {
Debug.logInfo("Solr: rebuildSolrIndex: Finished with " + numDocsIndexed + " documents indexed", module);
final String statusMsg = "Cleared solr index and reindexed " + numDocsIndexed + " documents";
result = ServiceUtil.returnSuccess(statusMsg);
}
} catch (SolrServerException e) {
if (e.getCause() != null && e.getCause() instanceof ConnectException) {
final String statusStr = "Failure connecting to solr server to rebuild index; index not updated";
if (Boolean.TRUE.equals(treatConnectErrorNonFatal)) {
Debug.logWarning(e, "Solr: rebuildSolrIndex: " + statusStr, module);
result = ServiceUtil.returnFailure(statusStr);
} else {
Debug.logError(e, "Solr: rebuildSolrIndex: " + statusStr, module);
result = ServiceUtil.returnError(statusStr);
}
} else {
Debug.logError(e, "Solr: rebuildSolrIndex: Server error: " + e.getMessage(), module);
result = ServiceUtil.returnError(e.toString());
}
} catch (Exception e) {
if (e instanceof ScipioSolrException && ((ScipioSolrException) e).isLightweight()) {
// don't print the error itself, too verbose
Debug.logError("Solr: rebuildSolrIndex: Error: " + e.getMessage(), module);
} else {
Debug.logError(e, "Solr: rebuildSolrIndex: Error: " + e.getMessage(), module);
}
result = ServiceUtil.returnError(e.toString());
} finally {
if (prodIt != null) {
try {
prodIt.close();
} catch(Exception e) {
}
}
if (clearAndUseCache) {
SolrProductUtil.clearProductEntityCaches(delegator, dispatcher);
}
}
// If success, mark data as good
if (result != null && ServiceUtil.isSuccess(result)) {
// TODO?: REVIEW?: 2018-01-03: for this method, for now, unlike updateToSolr,
// we will leave the status update in the same transaction as parent service,
// because it is technically possible that there was an error in the parent transaction
// prior to this service call that modified product data, or a transaction snafu
// that causes a modification in the product data being indexed to be rolled back,
// and in that case we don't want to mark the data as OK because another reindex
// will be needed as soon as possible.
// NOTE: in such case, we should even explicitly mark data as dirty, but I'm not
// certain we can do that reliably from here.
//SolrUtil.setSolrDataStatusIdSepTxSafe(delegator, "SOLR_DATA_OK", true);
SolrUtil.setSolrDataStatusIdSafe(delegator, "SOLR_DATA_OK", true);
}
result.put("numDocs", numDocs);
result.put("executed", executed);
return result;
}
/**
* Rebuilds the solr index - auto run.
*/
public static Map<String, Object> rebuildSolrIndexAuto(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result;
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
boolean startupForce = isReindexStartupForce(delegator, dispatcher);
if (startupForce) {
Debug.logInfo("Solr: rebuildSolrIndexAuto: Execution forced by force-startup system or config property", module);
}
boolean force = startupForce;
boolean autoRunEnabled = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.index.rebuild.autoRun.enabled", false);
if (force || autoRunEnabled) {
Boolean onlyIfDirty = (Boolean) context.get("onlyIfDirty");
if (onlyIfDirty == null) {
onlyIfDirty = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.index.rebuild.autoRun.onlyIfDirty", false);
}
Boolean ifConfigChange = (Boolean) context.get("ifConfigChange");
if (ifConfigChange == null) {
ifConfigChange = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.index.rebuild.autoRun.ifConfigChange", false);
}
if (force) {
onlyIfDirty = false;
ifConfigChange = false;
}
Boolean waitSolrReady = (Boolean) context.get("waitSolrReady");
if (waitSolrReady == null) {
waitSolrReady = UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, "solr.index.rebuild.autoRun.waitSolrReady", true);
}
Debug.logInfo("Solr: rebuildSolrIndexAuto: Launching index check/rebuild (onlyIfDirty: " + onlyIfDirty
+ ", ifConfigChange: " + ifConfigChange + ", waitSolrReady: " + waitSolrReady + ")", module);
Map<String, Object> servCtx;
try {
servCtx = dctx.makeValidContext("rebuildSolrIndex", ModelService.IN_PARAM, context);
servCtx.put("onlyIfDirty", onlyIfDirty);
servCtx.put("ifConfigChange", ifConfigChange);
servCtx.put("waitSolrReady", waitSolrReady);
Map<String, Object> servResult = dispatcher.runSync("rebuildSolrIndex", servCtx);
if (ServiceUtil.isSuccess(servResult)) {
String respMsg = (String) servResult.get(ModelService.SUCCESS_MESSAGE);
if (UtilValidate.isNotEmpty(respMsg)) {
Debug.logInfo("Solr: rebuildSolrIndexAuto: rebuildSolrIndex returned success: " + respMsg, module);
} else {
Debug.logInfo("Solr: rebuildSolrIndexAuto: rebuildSolrIndex returned success", module);
}
} else {
Debug.logError("Solr: rebuildSolrIndexAuto: rebuildSolrIndex returned an error: " +
ServiceUtil.getErrorMessage(servResult), module);
}
// Just pass it all back, hackish but should work
result = new HashMap<>();
result.putAll(servResult);
} catch (Exception e) {
Debug.logError(e, "Solr: rebuildSolrIndexAuto: Error: " + e.getMessage(), module);
return ServiceUtil.returnError(e.getMessage());
}
} else {
Debug.logInfo("Solr: rebuildSolrIndexAuto: not running - disabled", module);
result = ServiceUtil.returnSuccess();
}
return result;
}
private static boolean isReindexStartupForce(Delegator delegator, LocalDispatcher dispatcher) {
if (reindexAutoForceRan) return false;
synchronized(SolrProductSearch.class) {
if (reindexAutoForceRan) return false;
reindexAutoForceRan = true;
return getReindexStartupForceProperty(delegator, dispatcher, false);
}
}
private static Boolean getReindexStartupForceProperty(Delegator delegator, LocalDispatcher dispatcher, Boolean defaultValue) {
Boolean force = UtilMisc.booleanValueVersatile(System.getProperty(reindexStartupForceSysProp));
if (force != null) return force;
return UtilProperties.getPropertyAsBoolean(SolrUtil.solrConfigName, reindexStartupForceConfigProp, defaultValue);
}
/**
* Rebuilds the solr index - only if dirty.
*/
public static Map<String, Object> rebuildSolrIndexIfDirty(DispatchContext dctx, Map<String, Object> context) {
return rebuildSolrIndex(dctx, context);
}
/**
* Marks SOLR data as dirty.
*/
public static Map<String, Object> setSolrDataStatus(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result;
GenericDelegator delegator = (GenericDelegator) dctx.getDelegator();
try {
SolrUtil.setSolrDataStatusId(delegator, (String) context.get("dataStatusId"), false);
result = ServiceUtil.returnSuccess();
} catch (Exception e) {
result = ServiceUtil.returnError("Unable to set SOLR data status: " + e.getMessage());
}
return result;
}
static void copyStdServiceFieldsNotSet(Map<String, Object> srcCtx, Map<String, Object> destCtx) {
copyServiceFieldsNotSet(srcCtx, destCtx, "locale", "userLogin", "timeZone");
}
static void copyServiceFieldsNotSet(Map<String, Object> srcCtx, Map<String, Object> destCtx, String... fieldNames) {
for(String fieldName : fieldNames) {
if (!destCtx.containsKey(fieldName)) destCtx.put(fieldName, srcCtx.get(fieldName));
}
}
public static Map<String, Object> checkSolrReady(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result = ServiceUtil.returnSuccess();
boolean enabled = SolrUtil.isSystemInitialized(); // NOTE: this must NOT use SolrUtil.isSolrLocalWebappPresent() anymore
result.put("enabled", enabled);
if (enabled) {
try {
HttpSolrClient client = (HttpSolrClient) context.get("client");
if (client == null) client = SolrUtil.getQueryHttpSolrClient((String) context.get("core"));
result.put("ready", SolrUtil.isSolrWebappReady(client));
} catch (Exception e) {
Debug.logWarning(e, "Solr: checkSolrReady: error trying to check if Solr ready: " + e.getMessage(), module);
result = ServiceUtil.returnFailure("Error while checking if Solr ready");
result.put("enabled", enabled);
result.put("ready", false);
return result;
}
} else {
result.put("ready", false);
}
return result;
}
public static Map<String, Object> waitSolrReady(DispatchContext dctx, Map<String, Object> context) {
if (!SolrUtil.isSolrEnabled()) { // NOTE: this must NOT use SolrUtil.isSolrLocalWebappPresent() anymore
return ServiceUtil.returnFailure("Solr not enabled");
}
HttpSolrClient client = null;
try {
client = (HttpSolrClient) context.get("client");
if (client == null) client = SolrUtil.getQueryHttpSolrClient((String) context.get("core"));
if (SolrUtil.isSystemInitializedAssumeEnabled() && SolrUtil.isSolrWebappReady(client)) {
if (Debug.verboseOn()) Debug.logInfo("Solr: waitSolrReady: Solr is ready, continuing", module);
return ServiceUtil.returnSuccess();
}
} catch (Exception e) {
Debug.logWarning(e, "Solr: waitSolrReady: error trying to check if Solr ready: " + e.getMessage(), module);
return ServiceUtil.returnFailure("Error while checking if Solr ready");
}
Integer maxChecks = (Integer) context.get("maxChecks");
if (maxChecks == null) maxChecks = UtilProperties.getPropertyAsInteger(SolrUtil.solrConfigName, "solr.service.waitSolrReady.maxChecks", null);
if (maxChecks != null && maxChecks < 0) maxChecks = null;
Integer sleepTime = (Integer) context.get("sleepTime");
if (sleepTime == null) sleepTime = UtilProperties.getPropertyAsInteger(SolrUtil.solrConfigName, "solr.service.waitSolrReady.sleepTime", null);
if (sleepTime == null || sleepTime < 0) sleepTime = 3000;
int checkNum = 2; // first already done above
while((maxChecks == null || checkNum <= maxChecks)) {
Debug.logInfo("Solr: waitSolrReady: Solr not ready, waiting " + sleepTime + "ms (check " + checkNum + (maxChecks != null ? "/" + maxChecks : "") + ")", module);
try {
Thread.sleep(sleepTime);
} catch (Exception e) {
Debug.logWarning("Solr: waitSolrReady: interrupted while waiting for Solr: " + e.getMessage(), module);
return ServiceUtil.returnFailure("Solr not ready, interrupted while waiting");
}
try {
if (SolrUtil.isSystemInitializedAssumeEnabled() && SolrUtil.isSolrWebappReady(client)) {
Debug.logInfo("Solr: waitSolrReady: Solr is ready, continuing", module);
return ServiceUtil.returnSuccess();
}
} catch (Exception e) {
Debug.logWarning(e, "Solr: waitSolrReady: error trying to check if Solr ready: " + e.getMessage(), module);
return ServiceUtil.returnFailure("Error while checking if Solr ready");
}
checkNum++;
}
return ServiceUtil.returnFailure("Solr not ready, reached max wait time");
}
public static Map<String, Object> reloadSolrSecurityAuthorizations(DispatchContext dctx, Map<String, Object> context) {
if (!SolrUtil.isSystemInitialized()) { // NOTE: this must NOT use SolrUtil.isSolrLocalWebappPresent() anymore
return ServiceUtil.returnFailure("Solr not enabled or system not ready");
}
try {
HttpSolrClient client = SolrUtil.getAdminHttpSolrClientFromUrl(SolrUtil.getSolrWebappUrl());
//ModifiableSolrParams params = new ModifiableSolrParams();
//// this is very sketchy, I don't think ModifiableSolrParams were meant for this
//params.set("set-user-role", (String) null);
//SolrRequest<?> request = new GenericSolrRequest(METHOD.POST, CommonParams.AUTHZ_PATH, params);
SolrRequest<?> request = new DirectJsonRequest(CommonParams.AUTHZ_PATH,
"{\"set-user-role\":{}}"); // "{\"set-user-role\":{\"dummy\":\"dummy\"}}"
client.request(request);
Debug.logInfo("Solr: reloadSolrSecurityAuthorizations: invoked reload", module);
return ServiceUtil.returnSuccess();
} catch (Exception e) {
Debug.logError("Solr: reloadSolrSecurityAuthorizations: error: " + e.getMessage(), module);
return ServiceUtil.returnError("Error reloading Solr security authorizations");
}
}
}
| solr: eca: fix error/logging
service errors messages may be discarded by the global-commit handler,
so must handle them explicit.
also, do not log when virtual product is missing, sometimes valid. | applications/solr/src/com/ilscipio/scipio/solr/SolrProductSearch.java | solr: eca: fix error/logging | <ide><path>pplications/solr/src/com/ilscipio/scipio/solr/SolrProductSearch.java
<ide> result = ServiceUtil.returnSuccess();
<ide> }
<ide> } catch (Exception e) {
<del> Debug.logError(e, "Solr: addToSolr: " + e.getMessage(), module);
<del> result = ServiceUtil.returnError(e.toString());
<add> Debug.logError(e, "Solr: addToSolr: Error adding product '" + productId + "' to solr index: " + e.getMessage(), module);
<add> result = ServiceUtil.returnError("Error adding product '" + productId + "' to solr index: " + e.toString());
<ide> }
<ide> return result;
<ide> }
<ide> client.commit();
<ide> result = ServiceUtil.returnSuccess();
<ide> } catch (Exception e) {
<del> Debug.logError(e, "Solr: removeFromSolr: " + e.getMessage(), module);
<del> result = ServiceUtil.returnError(e.toString());
<add> Debug.logError(e, "Solr: removeFromSolr: Error removing product '" + productId + "' from solr index: " + e.getMessage(), module);
<add> result = ServiceUtil.returnError("Error removing product '" + productId + "' from solr index: " + e.toString());
<ide> }
<ide> return result;
<ide> }
<ide> /**
<ide> * Core implementation for the updateToSolr, addToSolr, removeFromSolr, and registerUpdateToSolr services.
<ide> * <p>
<del> * Upon error, unless instructed otherwise, this marks the Solr data as dirty.
<add> * Upon error, unless instructed otherwise (manual flag or config), this marks the Solr data as dirty.
<ide> */
<ide> private static Map<String, Object> updateToSolrCommon(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd, boolean immediate) {
<ide> Map<String, Object> result;
<ide> Map<String, Map<String, Object>> productIds = (Map<String, Map<String, Object>>) context.get("productIds");
<ide>
<ide> if (immediate) {
<del> if (productId == null && productIds == null) return ServiceUtil.returnError("missing product instance, productId or productIds map");
<add> if (productId == null && productIds == null) {
<add> Debug.logError("Solr: updateToSolr: Missing product instance, productId or productIds map", module);
<add> return ServiceUtil.returnError("Missing product instance, productId or productIds map");
<add> }
<ide> result = updateToSolrCore(dctx, context, forceAdd, productId, productInst, productIds);
<ide> if (ServiceUtil.isSuccess(result)) indexed = true;
<ide> } else {
<ide> if (TransactionUtil.isTransactionInPlaceSafe()) {
<del> if (productId == null) return ServiceUtil.returnError("missing product instance or productId");
<add> if (productId == null) {
<add> Debug.logError("Solr: registerUpdateToSolr: Missing product instance or productId", module);
<add> // DEV NOTE: This *should* be okay to return error, without interfering with running transaction,
<add> // because default ECA flags are: rollback-on-error="false" abort-on-error="false"
<add> return ServiceUtil.returnError("Missing product instance or productId");
<add> }
<ide> result = registerUpdateToSolrForTxCore(dctx, context, forceAdd, productId, productInst);
<ide> if (ServiceUtil.isSuccess(result)) indexed = true; // NOTE: not really indexed; this is just to skip the mark-dirty below
<ide> } else {
<ide> final String reason = "No transaction in place";
<ide> if ("update".equals(context.get("noTransMode"))) {
<del> if (productId == null && productIds == null) return ServiceUtil.returnError("missing product instance, productId or productIds map");
<add> if (productId == null && productIds == null) {
<add> Debug.logError("Solr: updateToSolr: Missing product instance, productId or productIds map", module);
<add> return ServiceUtil.returnError("Missing product instance, productId or productIds map");
<add> }
<ide> Debug.logInfo("Solr: registerUpdateToSolr: " + reason + "; running immediate index update", module);
<ide> result = updateToSolrCore(dctx, context, forceAdd, productId, productInst, productIds);
<ide> if (ServiceUtil.isSuccess(result)) indexed = true;
<ide> * <p>
<ide> * WARN: this edits the products map in-place. We're assuming this isn't an issue...
<ide> * Added 2018-07-23.
<add> * <p>
<add> * DEV NOTE: 2018-07-26: For updateToSolr(Core), the global commit hook ignores the returned error message
<add> * from this, so logError statements are essential.
<ide> */
<ide> private static Map<String, Object> updateToSolrCore(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd, String productId, Map<String, Object> productInst,
<ide> Map<String, Map<String, Object>> products) {
<ide> if (products == null) products = new HashMap<>(); // SPECIAL: here no need for LinkedHashMap, but other cases should be LinkedHashMap
<ide> Map<String, Object> productProps;
<ide> try {
<del> productProps = dctx.getModelService("updateToSolrSingleInterface")
<del> .makeValid(context, ModelService.IN_PARAM, false, null);
<add> productProps = dctx.getModelService("updateToSolrSingleInterface").makeValid(context, ModelService.IN_PARAM, false, null);
<ide> } catch (GenericServiceException e) {
<ide> Debug.logError(e, "Solr: updateToSolr: Error parsing service parameters for updateToSolrSingleInterface: " + e.getMessage() , module);
<del> return ServiceUtil.returnError(e.getMessage());
<add> return ServiceUtil.returnError("Error parsing service parameters for updateToSolrSingleInterface: " + e.toString());
<ide> }
<ide> productProps.put("instance", productInst);
<ide> productProps.put("action", getUpdateToSolrAction(forceAdd));
<ide> /**
<ide> * Multi-product core update.
<ide> * Added 2018-07-19.
<add> * <p>
<add> * DEV NOTE: 2018-07-26: For updateToSolr(Core), the global commit hook ignores the returned error message
<add> * from this, so logError statements are essential.
<ide> */
<ide> private static Map<String, Object> updateToSolrCore(DispatchContext dctx, Map<String, Object> context, Map<String, Map<String, Object>> products) {
<ide> // SPECIAL: 2018-01-03: do not update to Solr if the current transaction marked as rollback,
<ide> return ServiceUtil.returnFailure("Current transaction is marked for rollback; aborting solr index update");
<ide> }
<ide> } catch (Exception e) {
<del> Debug.logError("Solr: updateToSolr: Failed to check transaction status; aborting solr index update: " + e.getMessage(), module);
<del> return ServiceUtil.returnError("Failed to check transaction status; aborting solr index update");
<del> }
<del>
<del> List<String> errorMessageList = new ArrayList<>();
<del>
<add> Debug.logError("Solr: updateToSolr: Failed to check transaction status; aborting solr index update: " + e.toString(), module);
<add> return ServiceUtil.returnError("Failed to check transaction status; aborting solr index update: " + e.toString());
<add> }
<add>
<ide> // pre-process for variants
<ide> // NOTE: products should be a LinkedHashMap;
<ide> // expandedProducts doesn't need to be LinkedHashMap, but do it anyway
<ide> // either in the same transaction or another before it.
<ide> if (Debug.verboseOn()) {
<ide> Debug.logVerbose("Solr: updateToSolr: Ignoring updateVariants/updateVirtual request for (forced) removal of product '"
<del> + productId + "'; the variants should already be scheduled for removal (logically) through another mechanism", module);
<add> + productId + "' (the variants/virtual should be scheduled for removal through separate invocation)", module);
<ide> }
<ide> } else {
<ide> GenericValue product;
<ide> product = dctx.getDelegator().findOne("Product", UtilMisc.toMap("productId", productId), false);
<ide> } catch (Exception e) {
<ide> Debug.logError(e, "Solr: updateToSolr: Could not lookup product '" + productId + "': " + e.getMessage(), module);
<del> return ServiceUtil.returnError(e.toString());
<add> return ServiceUtil.returnError("Could not lookup product '" + productId + "': " + e.toString());
<ide> }
<ide> if (Boolean.TRUE.equals(forceAdd) && product == null) {
<ide> return ServiceUtil.returnError("Product not found for productId: " + productId);
<ide> if (product == null) {
<ide> if (Debug.verboseOn()) {
<ide> Debug.logVerbose("Solr: updateToSolr: Ignoring updateVariants/updateVirtual request for (forced) removal of product '"
<del> + productId + "'; the variants should already be scheduled for removal (logically) through another mechanism", module);
<add> + productId + "' (the variants/virtual should be scheduled for removal through separate invocation)", module);
<ide> }
<ide> } else {
<ide> if (updateVariants && Boolean.TRUE.equals(product.getBoolean("isVirtual"))) {
<ide> } catch (GeneralException e) {
<ide> Debug.logError(e, "Solr: updateToSolr: Could not lookup product variants for '"
<ide> + productId + "' for updateVariants: " + e.getMessage(), module);
<del> return ServiceUtil.returnError(e.toString());
<add> return ServiceUtil.returnError("Could not lookup product variants for '"
<add> + productId + "' for updateVariants: " + e.toString());
<ide> }
<ide> for(GenericValue variantProduct : variantProducts) {
<ide> // NOTE: we crush any prior entry for same product;
<ide> List<GenericValue> virtualProducts;
<ide> try {
<ide> // TODO: REVIEW: in most stock code these would be "-fromDate" and maxPerLevel=1,
<del> // but I see no good reason to limit it...
<add> // but I see no good reason to limit it here (needless ordering)...
<ide> final List<String> orderBy = null;
<ide> final Integer maxPerLevel = null;
<ide> if (updateVirtualDeep) {
<ide> product, orderBy, maxPerLevel, null, false);
<ide> }
<ide> } catch(Exception e) {
<del> Debug.logError(e, "Solr: updateToSolr: Could not lookup virtual product for variant product '" + productId + "'", module);
<del> return ServiceUtil.returnError("Could not lookup virtual product for variant product '" + productId + "'");
<add> Debug.logError(e, "Solr: updateToSolr: Could not lookup virtual product for variant product '"
<add> + productId + "': " + e.getMessage(), module);
<add> return ServiceUtil.returnError("Could not lookup virtual product for variant product '"
<add> + productId + "': " + e.toString());
<ide> }
<del> if (virtualProducts.isEmpty()) {
<del> Debug.logWarning("Solr: updateToSolr: Product '"
<del> + productId + "' is variant but found no parent product (either the association is being removed, or data error)", module);
<del> } else {
<del> for(GenericValue virtualProduct : virtualProducts) {
<del> Map<String, Object> variantProps = new HashMap<>();
<del> variantProps.put("instance", virtualProduct);
<del> variantProps.put("forceAdd", forceAdd); // no need: getUpdateToSolrAction(forceAdd)
<del> String virtualProductId = virtualProduct.getString("productId");
<del> // re-add the key to LinkedHashMap keep a readable order in log
<del> expandedProducts.remove(virtualProductId);
<del> expandedProducts.put(virtualProductId, variantProps);
<del> }
<add> // This can be a valid state for ALTERNATIVE_PACKAGE products
<add> //if (virtualProducts.isEmpty()) {
<add> // Debug.logWarning("Solr: updateToSolr: Product '"
<add> // + productId + "' is variant but found no parent product (either the association is being"
<add> // + " removed, or data error)", module);
<add> //} else {
<add> for(GenericValue virtualProduct : virtualProducts) {
<add> Map<String, Object> variantProps = new HashMap<>();
<add> variantProps.put("instance", virtualProduct);
<add> variantProps.put("forceAdd", forceAdd); // no need: getUpdateToSolrAction(forceAdd)
<add> String virtualProductId = virtualProduct.getString("productId");
<add> // re-add the key to LinkedHashMap keep a readable order in log
<add> expandedProducts.remove(virtualProductId);
<add> expandedProducts.put(virtualProductId, variantProps);
<ide> }
<add> //}
<ide> }
<ide> }
<ide> }
<ide> }
<ide> }
<del>
<add>
<add> Map<String, String> productIndexErrorMsgs = new HashMap<>();
<add>
<ide> for(Map.Entry<String, Map<String, Object>> entry : expandedProducts.entrySet()) {
<ide> String productId = entry.getKey();
<ide> Map<String, Object> props = entry.getValue();
<ide> Object actionObj = props.get("action");
<ide> Boolean forceAdd = (actionObj instanceof Boolean) ? (Boolean) actionObj : updateToSolrActionMap.get(actionObj);
<ide>
<del> Map<String, Object> updateSingleResult = updateToSolrCore(dctx, context, forceAdd, productId, productInst);
<add> Map<String, Object> updateSingleResult = updateToSolrCoreSingleImpl(dctx, context, forceAdd, productId, productInst);
<ide> if (!ServiceUtil.isSuccess(updateSingleResult)) {
<del> errorMessageList.add(ServiceUtil.getErrorMessage(updateSingleResult));
<del> }
<del> }
<del>
<del> Map<String, Object> result = (errorMessageList.size() > 0) ?
<del> ServiceUtil.returnError(errorMessageList) :
<del> ServiceUtil.returnSuccess();
<del>
<del> return result;
<del> }
<del>
<del> private static Map<String, Object> updateToSolrCore(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd, String productId, Map<String, Object> productInst) {
<add> productIndexErrorMsgs.put(productId, ServiceUtil.getErrorMessage(updateSingleResult));
<add> }
<add> }
<add>
<add> if (productIndexErrorMsgs.size() == 0) {
<add> return ServiceUtil.returnSuccess();
<add> } else {
<add> List<String> errorMsgs = new ArrayList<>();
<add> for(Map.Entry<String, String> entry : productIndexErrorMsgs.entrySet()) {
<add> errorMsgs.add("Error updating index for product '" + entry.getKey() + "': " + entry.getValue());
<add> }
<add> Map<String, Object> result = ServiceUtil.returnError(errorMsgs);
<add> // DEV NOTE: this log statement is _probably_ redundant, but do it just in case
<add> Debug.logError("Solr: registerUpdateToSolr: Error(s) indexing product(s): " + errorMsgs, module);
<add> return result;
<add> }
<add> }
<add>
<add> private static Map<String, Object> updateToSolrCoreSingleImpl(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd,
<add> String productId, Map<String, Object> productInst) {
<ide> Map<String, Object> result;
<ide> if (Boolean.FALSE.equals(forceAdd)) {
<ide> result = removeFromSolrCore(dctx, context, productId);
<ide> product = dctx.getDelegator().findOne("Product", UtilMisc.toMap("productId", productId), false);
<ide> } catch (Exception e) {
<ide> Debug.logError(e, "Solr: updateToSolr: Could not lookup product '" + productId + "': " + e.getMessage(), module);
<del> return ServiceUtil.returnError(e.toString());
<add> return ServiceUtil.returnError("Could not lookup product '" + productId + "': " + e.toString());
<ide> }
<ide> }
<ide> if (Boolean.TRUE.equals(forceAdd)) {
<ide> if (product == null) {
<del> return ServiceUtil.returnError("Product not found for productId: " + productId);
<add> Debug.logError("Solr: updateToSolr: Explicit add action requested, but product not found for productId: " + productId, module);
<add> return ServiceUtil.returnError("Explicit add action requested, but product not found for productId: " + productId);
<ide> }
<ide> result = addToSolrCore(dctx, context, product, productId);
<ide> } else {
<ide> * WARN: DEV NOTE: This now edits the update service productIds context map in-place
<ide> * in the already-registered service; this is not "proper" but there is no known current case
<ide> * where it should cause an issue and it removes more overhead.
<add> * <p>
<add> * DEV NOTE: This *should* be okay to return error, without interfering with running transaction,
<add> * because default ECA flags are: rollback-on-error="false" abort-on-error="false"
<ide> */
<ide> private static Map<String, Object> registerUpdateToSolrForTxCore(DispatchContext dctx, Map<String, Object> context, Boolean forceAdd, String productId, Map<String, Object> productInst) {
<ide> String updateSrv = (String) context.get("updateSrv");
<ide> }
<ide> } catch (Exception e) {
<ide> final String errMsg = "Could not register " + updateSrv + " to run at transaction global-commit for product '" + productId + "'";
<del> Debug.logError(e, "Solr: registerUpdateToSolr: " + productId, module);
<del> return ServiceUtil.returnError(errMsg);
<add> Debug.logError(e, "Solr: registerUpdateToSolr: " + errMsg, module);
<add> return ServiceUtil.returnError(errMsg + ": " + e.toString());
<ide> }
<ide> }
<ide>
<ide> Debug.logInfo("Solr: Indexing product '" + productId + "'", module);
<ide>
<ide> client = SolrUtil.getUpdateHttpSolrClient((String) context.get("core"));
<del> // Debug.log(server.ping().toString());
<ide>
<ide> // Construct Documents
<ide> SolrInputDocument doc1 = SolrProductUtil.generateSolrProductDocument(dctx.getDelegator(), dctx.getDispatcher(), context, useCache); |
|
Java | lgpl-2.1 | ea79b8fa0e4f962b364dc387bd040af196166ad4 | 0 | hibernate/hibernate-ogm,ZJaffee/hibernate-ogm,DavideD/hibernate-ogm-cassandra,Sanne/hibernate-ogm,Sanne/hibernate-ogm,mp911de/hibernate-ogm,tempbottle/hibernate-ogm,DavideD/hibernate-ogm,tempbottle/hibernate-ogm,gunnarmorling/hibernate-ogm,schernolyas/hibernate-ogm,DavideD/hibernate-ogm-contrib,gunnarmorling/hibernate-ogm,DavideD/hibernate-ogm,ZJaffee/hibernate-ogm,mp911de/hibernate-ogm,schernolyas/hibernate-ogm,uugaa/hibernate-ogm,mp911de/hibernate-ogm,jhalliday/hibernate-ogm,DavideD/hibernate-ogm,hibernate/hibernate-ogm,DavideD/hibernate-ogm-cassandra,hibernate/hibernate-ogm,hibernate/hibernate-ogm,DavideD/hibernate-ogm-contrib,DavideD/hibernate-ogm,gunnarmorling/hibernate-ogm,uugaa/hibernate-ogm,uugaa/hibernate-ogm,schernolyas/hibernate-ogm,ZJaffee/hibernate-ogm,hferentschik/hibernate-ogm,jhalliday/hibernate-ogm,DavideD/hibernate-ogm-cassandra,Sanne/hibernate-ogm,DavideD/hibernate-ogm-contrib,emmanuelbernard/hibernate-ogm,tempbottle/hibernate-ogm,Sanne/hibernate-ogm,jhalliday/hibernate-ogm | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* JBoss, Home of Professional Open Source
* Copyright 2010-2012 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.hibernate.ogm.dialect.mongodb;
import java.util.Collections;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.annotations.common.AssertionFailure;
import org.hibernate.dialect.lock.LockingStrategy;
import org.hibernate.id.IntegralDataTypeHolder;
import org.hibernate.ogm.datastore.impl.EmptyTupleSnapshot;
import org.hibernate.ogm.datastore.mongodb.Environment;
import org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider;
import org.hibernate.ogm.datastore.spi.Association;
import org.hibernate.ogm.datastore.spi.AssociationOperation;
import org.hibernate.ogm.datastore.spi.Tuple;
import org.hibernate.ogm.datastore.spi.TupleOperation;
import org.hibernate.ogm.dialect.GridDialect;
import org.hibernate.ogm.grid.AssociationKey;
import org.hibernate.ogm.grid.EntityKey;
import org.hibernate.ogm.grid.RowKey;
import org.hibernate.ogm.logging.mongodb.impl.Log;
import org.hibernate.ogm.logging.mongodb.impl.LoggerFactory;
import org.hibernate.ogm.type.GridType;
import org.hibernate.ogm.type.StringCalendarDateType;
import org.hibernate.persister.entity.Lockable;
import org.hibernate.ogm.type.ByteStringType;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import static org.hibernate.ogm.dialect.mongodb.MongoHelpers.addEmptyAssociationField;
import static org.hibernate.ogm.dialect.mongodb.MongoHelpers.getAssociationFieldOrNull;
import static org.hibernate.ogm.dialect.mongodb.MongoHelpers.isEmbedded;
/**
* Each Tuple entry is stored as a property in a MongoDB document.
*
* Each association is stored in an association document containing three properties:
* - the association table name (optionally)
* - the RowKey column names and values
* - the tuples as an array of elements
*
* Associations can be stored as:
* - one MongoDB collection per association class. The collection name is prefixed.
* - one MongoDB collection for all associations (the association table name property in then used)
* - embed the collection info in the owning entity document is planned but not supported at the moment (OGM-177)
*
* Collection of embeddable are stored within the owning entity document under the
* unqualified collection role
*
* @author Guillaume Scheibel <[email protected]>
* @author Alan Fitton <alan at eth0.org.uk>
* @author Emmanuel Bernard <[email protected]>
*/
public class MongoDBDialect implements GridDialect {
private static final Log log = LoggerFactory.getLogger();
private static final Integer ONE = Integer.valueOf( 1 );
public static final String ID_FIELDNAME = "_id";
public static final String DOT_SEPARATOR = ".";
public static final String SEQUENCE_VALUE = "sequence_value";
public static final String ASSOCIATIONS_FIELDNAME = "associations";
public static final String TUPLE_FIELDNAME = "tuple";
public static final String COLUMNS_FIELDNAME = "columns";
public static final String ROWS_FIELDNAME = "rows";
public static final String TABLE_FIELDNAME = "table";
public static final String ASSOCIATIONS_COLLECTION_PREFIX = "associations_";
private final MongoDBDatastoreProvider provider;
private final DB currentDB;
public MongoDBDialect(MongoDBDatastoreProvider provider) {
this.provider = provider;
this.currentDB = this.provider.getDatabase();
}
@Override
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
throw new UnsupportedOperationException( "The MongoDB GridDialect does not support locking" );
}
@Override
public Tuple getTuple(EntityKey key) {
DBObject found = this.getObject( key );
return found != null ? new Tuple( new MongoDBTupleSnapshot( found ) ) : null;
}
@Override
public Tuple createTuple(EntityKey key) {
DBObject toSave = this.prepareIdObject( key );
return new Tuple( new MongoDBTupleSnapshot( toSave, key.getColumnNames() ) );
}
private DBObject getObject(EntityKey key) {
DBCollection collection = this.getCollection( key );
DBObject searchObject = this.prepareIdObject( key );
return collection.findOne( searchObject );
}
/**
* Create a DBObject which represents the _id field.
* In case of simple id objects the json representation will look like {_id: "theIdValue"}
* In case of composite id objects the json representation will look like {_id: {author: "Guillaume", title: "What this method is used for?"}}
*
* @param key
*
* @return the DBObject which represents the id field
*/
private BasicDBObject prepareIdObject(EntityKey key) {
return this.prepareIdObject( key.getColumnNames(), key.getColumnValues() );
}
private BasicDBObject prepareIdObject(AssociationKey key){
return this.prepareIdObject( key.getColumnNames(), key.getColumnValues() );
}
private BasicDBObject prepareIdObject(String[] columnNames, Object[] columnValues){
BasicDBObject object = null;
if ( columnNames.length == 1 ) {
object = new BasicDBObject( ID_FIELDNAME, columnValues[0] );
}
else {
object = new BasicDBObject();
DBObject idObject = new BasicDBObject();
for ( int i = 0; i < columnNames.length; i++ ) {
String columnName = columnNames[i];
Object columnValue = columnValues[i];
if ( columnName.contains( DOT_SEPARATOR ) ) {
int dotIndex = columnName.indexOf( DOT_SEPARATOR );
String shortColumnName = columnName.substring( dotIndex + 1 );
idObject.put( shortColumnName, columnValue );
}
else {
idObject.put( columnNames[i], columnValue );
}
}
object.put( ID_FIELDNAME, idObject );
}
return object;
}
private DBCollection getCollection(String table) {
return this.currentDB.getCollection( table );
}
private DBCollection getCollection(EntityKey key) {
return getCollection( key.getTable() );
}
private DBCollection getAssociationCollection(AssociationKey key) {
switch ( provider.getAssociationStorage() ) {
case GLOBAL_COLLECTION:
return getCollection( Environment.MONGODB_DEFAULT_ASSOCIATION_STORE );
case COLLECTION:
return getCollection( ASSOCIATIONS_COLLECTION_PREFIX + key.getTable() );
default:
throw new AssertionFailure( "Unknown AssociationStorage: " + provider.getAssociationStorage() );
}
}
private BasicDBObject getSubQuery(String operator, BasicDBObject query) {
return query.get( operator ) != null ? (BasicDBObject) query.get( operator ) : new BasicDBObject();
}
private void addSubQuery(String operator, BasicDBObject query, String column, Object value) {
BasicDBObject subQuery = this.getSubQuery( operator, query );
query.append( operator, subQuery.append( column, value ) );
}
@Override
public void updateTuple(Tuple tuple, EntityKey key) {
MongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();
BasicDBObject updater = new BasicDBObject();
for ( TupleOperation operation : tuple.getOperations() ) {
String column = operation.getColumn();
if ( !column.equals( ID_FIELDNAME ) && !column.endsWith( DOT_SEPARATOR + ID_FIELDNAME ) && !snapshot.columnInIdField(
column
) ) {
switch ( operation.getType() ) {
case PUT_NULL:
case PUT:
this.addSubQuery( "$set", updater, column, operation.getValue() );
break;
case REMOVE:
this.addSubQuery( "$unset", updater, column, ONE );
break;
}
}
}
/*Needed because in case of object with only an ID field
the "_id" won't be persisted properly.
With this adjustment, it will work like this:
if the object (from snapshot) doesn't exist so create the one represented by updater
so if at this moment the "_id" is not enforce properly an ObjectID will be crated by the server instead
of the custom id
*/
if ( updater.size() == 0 ) {
updater = this.prepareIdObject( key );
}
this.getCollection( key ).update( snapshot.getDbObject(), updater, true, false );
}
@Override
public void removeTuple(EntityKey key) {
DBCollection collection = this.getCollection( key );
DBObject toDelete = this.getObject( key );
if ( toDelete != null ) {
collection.remove( toDelete );
}
else {
if ( log.isDebugEnabled() ) {
log.debugf( "Unable to remove %1$s (object not found)", key.getColumnValues()[0] );
}
}
}
//not for embedded
private DBObject findAssociation(AssociationKey key) {
final DBObject associationKeyObject = MongoHelpers.associationKeyToObject( provider.getAssociationStorage(), key );
return this.getAssociationCollection( key ).findOne( associationKeyObject );
}
@Override
public Association getAssociation(AssociationKey key) {
if ( isEmbedded( key ) ) {
DBObject entity = getObject( key.getEntityKey() );
if ( getAssociationFieldOrNull( key, entity ) != null ) {
return new Association( new MongoDBAssociationSnapshot( entity, key ) );
}
else {
return null;
}
}
final DBObject result = findAssociation( key );
if ( result == null ) {
return null;
} else {
return new Association( new MongoDBAssociationSnapshot( result, key ) );
}
}
@Override
public Association createAssociation(AssociationKey key) {
if ( isEmbedded( key ) ) {
DBObject entity = getObject( key.getEntityKey() );
boolean insert = false;
if ( entity == null ) {
insert = true;
entity = this.prepareIdObject( key );
}
if ( getAssociationFieldOrNull( key, entity ) == null ) {
if ( insert ) {
//adding assoc before insert
addEmptyAssociationField( key, entity );
getCollection( key.getEntityKey() ).insert( entity );
}
else {
BasicDBObject updater = new BasicDBObject();
this.addSubQuery( "$set", updater, key.getCollectionRole(), Collections.EMPTY_LIST );
//TODO use entity filter with only the ids
this.getCollection( key.getEntityKey() ).update( entity, updater, true, false );
//adding assoc after update because the query takes the whole object today
addEmptyAssociationField( key, entity );
}
}
return new Association( new MongoDBAssociationSnapshot( entity, key ) );
}
DBCollection associations = getAssociationCollection( key );
DBObject assoc = MongoHelpers.associationKeyToObject( provider.getAssociationStorage(), key );
assoc.put( ROWS_FIELDNAME, Collections.EMPTY_LIST );
associations.insert( assoc );
return new Association( new MongoDBAssociationSnapshot( assoc, key ) );
}
private DBObject removeAssociationRowKey(MongoDBAssociationSnapshot snapshot, RowKey rowKey, String associationField) {
DBObject pull = new BasicDBObject( associationField, snapshot.getRowKeyDBObject( rowKey ) );
return new BasicDBObject( "$pull", pull );
}
//non embedded only
private static DBObject createBaseRowKey(RowKey rowKey) {
DBObject row = new BasicDBObject();
DBObject rowColumnMap = new BasicDBObject();
Object[] columnValues = rowKey.getColumnValues();
int i = 0;
for ( String rowKeyColumnName : rowKey.getColumnNames() )
rowColumnMap.put( rowKeyColumnName, columnValues[i++] );
row.put( TABLE_FIELDNAME, rowKey.getTable() );
row.put( COLUMNS_FIELDNAME, rowColumnMap );
return row;
}
private DBObject putAssociationRowKey(RowKey rowKey, Tuple value, String associationField, AssociationKey associationKey) {
boolean embedded = isEmbedded( associationKey );
DBObject rowTupleMap = new BasicDBObject();
for ( String valueKeyName : value.getColumnNames() ) {
boolean add = true;
if ( embedded ) {
//exclude columns from the associationKey
for ( String assocColumn : associationKey.getColumnNames() ) {
if ( valueKeyName.equals( assocColumn ) ) {
add = false;
break;
}
}
}
if (add) {
rowTupleMap.put( valueKeyName, value.get( valueKeyName ) );
}
}
DBObject row;
if ( embedded ) {
row = rowTupleMap;
}
else {
row = createBaseRowKey(rowKey);
row.put( TUPLE_FIELDNAME, rowTupleMap );
}
return new BasicDBObject( "$push", new BasicDBObject( associationField, row ) );
}
@Override
public void updateAssociation(Association association, AssociationKey key) {
DBCollection collection;
DBObject query;
MongoDBAssociationSnapshot assocSnapshot = (MongoDBAssociationSnapshot)association.getSnapshot();
String associationField;
if ( isEmbedded( key ) ) {
collection = this.getCollection( key.getEntityKey() );
query = this.prepareIdObject( key );
associationField = key.getCollectionRole();
}
else {
collection = getAssociationCollection( key );
query = assocSnapshot.getQueryObject();
associationField = ROWS_FIELDNAME;
}
for ( AssociationOperation action : association.getOperations() ) {
RowKey rowKey = action.getKey();
Tuple rowValue = action.getValue();
DBObject update = null;
switch ( action.getType() ) {
case CLEAR:
update = new BasicDBObject( "$set", new BasicDBObject (associationField, Collections.EMPTY_LIST ) );
break;
case PUT_NULL:
case PUT:
update = putAssociationRowKey( rowKey, rowValue, associationField, key );
break;
case REMOVE:
update = removeAssociationRowKey( assocSnapshot, rowKey, associationField );
break;
}
if ( update != null )
collection.update( query, update, true, false );
}
}
@Override
public void removeAssociation(AssociationKey key) {
if ( isEmbedded( key ) ) {
DBObject entity = getObject( key.getEntityKey() );
if ( entity != null ) {
BasicDBObject updater = new BasicDBObject();
this.addSubQuery( "$unset", updater, key.getCollectionRole(), ONE );
this.getCollection( key.getEntityKey() ).update( entity, updater, true, false );
}
}
DBCollection collection = getAssociationCollection( key );
DBObject query = MongoHelpers.associationKeyToObject( provider.getAssociationStorage(), key );
int nAffected = collection.remove( query ).getN();
log.removedAssociation( nAffected );
}
@Override
public Tuple createTupleAssociation(AssociationKey associationKey, RowKey rowKey) {
return new Tuple( EmptyTupleSnapshot.SINGLETON );
}
@Override
public void nextValue(RowKey key, IntegralDataTypeHolder value, int increment, int initialValue) {
DBCollection currentCollection = this.currentDB.getCollection( key.getTable() );
DBObject query = new BasicDBObject();
int size = key.getColumnNames().length;
//all columns should match to find the value
for ( int index = 0; index < size; index++ ) {
query.put( key.getColumnNames()[index], key.getColumnValues()[index] );
}
BasicDBObject update = new BasicDBObject();
//FIXME should "value" be hardcoded?
//FIXME how to set the initialValue if the document is not present? It seems the inc value is used as initial new value
Integer incrementObject = increment == 1 ? ONE : Integer.valueOf( increment );
this.addSubQuery( "$inc", update, SEQUENCE_VALUE, incrementObject );
DBObject result = currentCollection.findAndModify( query, null, null, false, update, false, true );
Object idFromDB;
idFromDB = result == null ? null : result.get( SEQUENCE_VALUE );
if ( idFromDB == null ) {
//not inserted yet so we need to add initial value to increment to have the right next value in the DB
//FIXME that means there is a small hole as when there was not value in the DB, we do add initial value in a non atomic way
BasicDBObject updateForInitial = new BasicDBObject();
this.addSubQuery( "$inc", updateForInitial, SEQUENCE_VALUE, initialValue );
currentCollection.findAndModify( query, null, null, false, updateForInitial, false, true );
idFromDB = initialValue; //first time we ask this value
}
else {
idFromDB = result.get( SEQUENCE_VALUE );
}
if ( idFromDB.getClass().equals( Integer.class ) || idFromDB.getClass().equals( Long.class ) ) {
Number id = (Number) idFromDB;
//idFromDB is the one used and the BD contains the next available value to use
value.initialize( id.longValue() );
}
else {
throw new HibernateException( "Cannot increment a non numeric field" );
}
}
@Override
public GridType overrideType(Type type) {
// Override handling of calendar types
if ( type == StandardBasicTypes.CALENDAR || type == StandardBasicTypes.CALENDAR_DATE ) {
return StringCalendarDateType.INSTANCE;
}
else if ( type == StandardBasicTypes.BYTE ) {
return ByteStringType.INSTANCE;
}
return null; // all other types handled as in hibernate-ogm-core
}
}
| hibernate-ogm-mongodb/src/main/java/org/hibernate/ogm/dialect/mongodb/MongoDBDialect.java | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* JBoss, Home of Professional Open Source
* Copyright 2010-2012 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.hibernate.ogm.dialect.mongodb;
import java.util.Collections;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.annotations.common.AssertionFailure;
import org.hibernate.dialect.lock.LockingStrategy;
import org.hibernate.id.IntegralDataTypeHolder;
import org.hibernate.ogm.datastore.impl.EmptyTupleSnapshot;
import org.hibernate.ogm.datastore.mongodb.Environment;
import org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider;
import org.hibernate.ogm.datastore.spi.Association;
import org.hibernate.ogm.datastore.spi.AssociationOperation;
import org.hibernate.ogm.datastore.spi.Tuple;
import org.hibernate.ogm.datastore.spi.TupleOperation;
import org.hibernate.ogm.dialect.GridDialect;
import org.hibernate.ogm.grid.AssociationKey;
import org.hibernate.ogm.grid.EntityKey;
import org.hibernate.ogm.grid.RowKey;
import org.hibernate.ogm.logging.mongodb.impl.Log;
import org.hibernate.ogm.logging.mongodb.impl.LoggerFactory;
import org.hibernate.ogm.type.GridType;
import org.hibernate.ogm.type.StringCalendarDateType;
import org.hibernate.persister.entity.Lockable;
import org.hibernate.ogm.type.ByteStringType;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import static org.hibernate.ogm.dialect.mongodb.MongoHelpers.addEmptyAssociationField;
import static org.hibernate.ogm.dialect.mongodb.MongoHelpers.getAssociationFieldOrNull;
import static org.hibernate.ogm.dialect.mongodb.MongoHelpers.isEmbedded;
/**
* Each Tuple entry is stored as a property in a MongoDB document.
*
* Each association is stored in an association document containing three properties:
* - the association table name (optionally)
* - the RowKey column names and values
* - the tuples as an array of elements
*
* Associations can be stored as:
* - one MongoDB collection per association class. The collection name is prefixed.
* - one MongoDB collection for all associations (the association table name property in then used)
* - embed the collection info in the owning entity document is planned but not supported at the moment (OGM-177)
*
* Collection of embeddable are stored within the owning entity document under the
* unqualified collection role
*
* @author Guillaume Scheibel <[email protected]>
* @author Alan Fitton <alan at eth0.org.uk>
* @author Emmanuel Bernard <[email protected]>
*/
public class MongoDBDialect implements GridDialect {
private static final Log log = LoggerFactory.getLogger();
private static final Integer ONE = Integer.valueOf( 1 );
public static final String ID_FIELDNAME = "_id";
public static final String DOT_SEPARATOR = ".";
public static final String SEQUENCE_VALUE = "sequence_value";
public static final String ASSOCIATIONS_FIELDNAME = "associations";
public static final String TUPLE_FIELDNAME = "tuple";
public static final String COLUMNS_FIELDNAME = "columns";
public static final String ROWS_FIELDNAME = "rows";
public static final String TABLE_FIELDNAME = "table";
public static final String ASSOCIATIONS_COLLECTION_PREFIX = "associations_";
private final MongoDBDatastoreProvider provider;
private final DB currentDB;
public MongoDBDialect(MongoDBDatastoreProvider provider) {
this.provider = provider;
this.currentDB = this.provider.getDatabase();
}
@Override
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
throw new UnsupportedOperationException( "The MongoDB GridDialect does not support locking" );
}
@Override
public Tuple getTuple(EntityKey key) {
DBObject found = this.getObject( key );
return found != null ? new Tuple( new MongoDBTupleSnapshot( found ) ) : null;
}
@Override
public Tuple createTuple(EntityKey key) {
DBObject toSave = this.preprareIdObject( key );
return new Tuple( new MongoDBTupleSnapshot( toSave, key.getColumnNames() ) );
}
private DBObject getObject(EntityKey key) {
DBCollection collection = this.getCollection( key );
DBObject searchObject = this.preprareIdObject( key );
return collection.findOne( searchObject );
}
/**
* Create a DBObject which represents the _id field.
* In case of simple id objects the json representation will look like {_id: "theIdValue"}
* In case of composite id objects the json representation will look like {_id: {author: "Guillaume", title: "What this method is used for?"}}
*
* @param key
*
* @return the DBObject which represents the id field
*/
private BasicDBObject preprareIdObject(EntityKey key) {
BasicDBObject object = null;
if ( key.getColumnNames().length == 1 ) {
object = new BasicDBObject( ID_FIELDNAME, key.getColumnValues()[0] );
}
else {
object = new BasicDBObject();
DBObject idObject = new BasicDBObject();
for ( int i = 0; i < key.getColumnNames().length; i++ ) {
String columnName = key.getColumnNames()[i];
Object columnValue = key.getColumnValues()[i];
if ( columnName.contains( DOT_SEPARATOR ) ) {
int dotIndex = columnName.indexOf( DOT_SEPARATOR );
String shortColumnName = columnName.substring( dotIndex + 1 );
idObject.put( shortColumnName, columnValue );
}
else {
idObject.put( key.getColumnNames()[i], columnValue );
}
}
object.put( ID_FIELDNAME, idObject );
}
return object;
}
private DBCollection getCollection(String table) {
return this.currentDB.getCollection( table );
}
private DBCollection getCollection(EntityKey key) {
return getCollection( key.getTable() );
}
private DBCollection getAssociationCollection(AssociationKey key) {
switch ( provider.getAssociationStorage() ) {
case GLOBAL_COLLECTION:
return getCollection( Environment.MONGODB_DEFAULT_ASSOCIATION_STORE );
case COLLECTION:
return getCollection( ASSOCIATIONS_COLLECTION_PREFIX + key.getTable() );
default:
throw new AssertionFailure( "Unknown AssociationStorage: " + provider.getAssociationStorage() );
}
}
private BasicDBObject getSubQuery(String operator, BasicDBObject query) {
return query.get( operator ) != null ? (BasicDBObject) query.get( operator ) : new BasicDBObject();
}
private void addSubQuery(String operator, BasicDBObject query, String column, Object value) {
BasicDBObject subQuery = this.getSubQuery( operator, query );
query.append( operator, subQuery.append( column, value ) );
}
@Override
public void updateTuple(Tuple tuple, EntityKey key) {
MongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();
BasicDBObject updater = new BasicDBObject();
for ( TupleOperation operation : tuple.getOperations() ) {
String column = operation.getColumn();
if ( !column.equals( ID_FIELDNAME ) && !column.endsWith( DOT_SEPARATOR + ID_FIELDNAME ) && !snapshot.columnInIdField(
column
) ) {
switch ( operation.getType() ) {
case PUT_NULL:
case PUT:
this.addSubQuery( "$set", updater, column, operation.getValue() );
break;
case REMOVE:
this.addSubQuery( "$unset", updater, column, ONE );
break;
}
}
}
if ( updater.size() == 0 ) {
updater = this.preprareIdObject( key );
}
this.getCollection( key ).update( snapshot.getDbObject(), updater, true, false );
}
@Override
public void removeTuple(EntityKey key) {
DBCollection collection = this.getCollection( key );
DBObject toDelete = this.getObject( key );
if ( toDelete != null ) {
collection.remove( toDelete );
}
else {
if ( log.isDebugEnabled() ) {
log.debugf( "Unable to remove %1$s (object not found)", key.getColumnValues()[0] );
}
}
}
//not for embedded
private DBObject findAssociation(AssociationKey key) {
final DBObject associationKeyObject = MongoHelpers.associationKeyToObject( provider.getAssociationStorage(), key );
return this.getAssociationCollection( key ).findOne( associationKeyObject );
}
@Override
public Association getAssociation(AssociationKey key) {
if ( isEmbedded( key ) ) {
DBObject entity = getObject( key.getEntityKey() );
if ( getAssociationFieldOrNull( key, entity ) != null ) {
return new Association( new MongoDBAssociationSnapshot( entity, key ) );
}
else {
return null;
}
}
final DBObject result = findAssociation( key );
if ( result == null ) {
return null;
} else {
return new Association( new MongoDBAssociationSnapshot( result, key ) );
}
}
@Override
public Association createAssociation(AssociationKey key) {
if ( isEmbedded( key ) ) {
DBObject entity = getObject( key.getEntityKey() );
boolean insert = false;
if ( entity == null ) {
insert = true;
entity = new BasicDBObject( ID_FIELDNAME, key.getEntityKey().getColumnValues()[0] );
}
if ( getAssociationFieldOrNull( key, entity ) == null ) {
if ( insert ) {
//adding assoc before insert
addEmptyAssociationField( key, entity );
getCollection( key.getEntityKey() ).insert( entity );
}
else {
BasicDBObject updater = new BasicDBObject();
this.addSubQuery( "$set", updater, key.getCollectionRole(), Collections.EMPTY_LIST );
//TODO use entity filter with only the ids
this.getCollection( key.getEntityKey() ).update( entity, updater, true, false );
//adding assoc after update because the query takes the whole object today
addEmptyAssociationField( key, entity );
}
}
return new Association( new MongoDBAssociationSnapshot( entity, key ) );
}
DBCollection associations = getAssociationCollection( key );
DBObject assoc = MongoHelpers.associationKeyToObject( provider.getAssociationStorage(), key );
assoc.put( ROWS_FIELDNAME, Collections.EMPTY_LIST );
associations.insert( assoc );
return new Association( new MongoDBAssociationSnapshot( assoc, key ) );
}
private DBObject removeAssociationRowKey(MongoDBAssociationSnapshot snapshot, RowKey rowKey, String associationField) {
DBObject pull = new BasicDBObject( associationField, snapshot.getRowKeyDBObject( rowKey ) );
return new BasicDBObject( "$pull", pull );
}
//non embedded only
private static DBObject createBaseRowKey(RowKey rowKey) {
DBObject row = new BasicDBObject();
DBObject rowColumnMap = new BasicDBObject();
Object[] columnValues = rowKey.getColumnValues();
int i = 0;
for ( String rowKeyColumnName : rowKey.getColumnNames() )
rowColumnMap.put( rowKeyColumnName, columnValues[i++] );
row.put( TABLE_FIELDNAME, rowKey.getTable() );
row.put( COLUMNS_FIELDNAME, rowColumnMap );
return row;
}
private DBObject putAssociationRowKey(RowKey rowKey, Tuple value, String associationField, AssociationKey associationKey) {
boolean embedded = isEmbedded( associationKey );
DBObject rowTupleMap = new BasicDBObject();
for ( String valueKeyName : value.getColumnNames() ) {
boolean add = true;
if ( embedded ) {
//exclude columns from the associationKey
for ( String assocColumn : associationKey.getColumnNames() ) {
if ( valueKeyName.equals( assocColumn ) ) {
add = false;
break;
}
}
}
if (add) {
rowTupleMap.put( valueKeyName, value.get( valueKeyName ) );
}
}
DBObject row;
if ( embedded ) {
row = rowTupleMap;
}
else {
row = createBaseRowKey(rowKey);
row.put( TUPLE_FIELDNAME, rowTupleMap );
}
return new BasicDBObject( "$push", new BasicDBObject( associationField, row ) );
}
@Override
public void updateAssociation(Association association, AssociationKey key) {
DBCollection collection;
DBObject query;
MongoDBAssociationSnapshot assocSnapshot = (MongoDBAssociationSnapshot)association.getSnapshot();
String associationField;
if ( isEmbedded( key ) ) {
collection = this.getCollection( key.getEntityKey() );
query = new BasicDBObject( ID_FIELDNAME, key.getEntityKey().getColumnValues()[0] );
associationField = key.getCollectionRole();
}
else {
collection = getAssociationCollection( key );
query = assocSnapshot.getQueryObject();
associationField = ROWS_FIELDNAME;
}
for ( AssociationOperation action : association.getOperations() ) {
RowKey rowKey = action.getKey();
Tuple rowValue = action.getValue();
DBObject update = null;
switch ( action.getType() ) {
case CLEAR:
update = new BasicDBObject( "$set", new BasicDBObject (associationField, Collections.EMPTY_LIST ) );
break;
case PUT_NULL:
case PUT:
update = putAssociationRowKey( rowKey, rowValue, associationField, key );
break;
case REMOVE:
update = removeAssociationRowKey( assocSnapshot, rowKey, associationField );
break;
}
if ( update != null )
collection.update( query, update, true, false );
}
}
@Override
public void removeAssociation(AssociationKey key) {
if ( isEmbedded( key ) ) {
DBObject entity = getObject( key.getEntityKey() );
if ( entity != null ) {
BasicDBObject updater = new BasicDBObject();
this.addSubQuery( "$unset", updater, key.getCollectionRole(), ONE );
this.getCollection( key.getEntityKey() ).update( entity, updater, true, false );
}
}
DBCollection collection = getAssociationCollection( key );
DBObject query = MongoHelpers.associationKeyToObject( provider.getAssociationStorage(), key );
int nAffected = collection.remove( query ).getN();
log.removedAssociation( nAffected );
}
@Override
public Tuple createTupleAssociation(AssociationKey associationKey, RowKey rowKey) {
return new Tuple( EmptyTupleSnapshot.SINGLETON );
}
@Override
public void nextValue(RowKey key, IntegralDataTypeHolder value, int increment, int initialValue) {
DBCollection currentCollection = this.currentDB.getCollection( key.getTable() );
DBObject query = new BasicDBObject();
int size = key.getColumnNames().length;
//all columns should match to find the value
for ( int index = 0; index < size; index++ ) {
query.put( key.getColumnNames()[index], key.getColumnValues()[index] );
}
BasicDBObject update = new BasicDBObject();
//FIXME should "value" be hardcoded?
//FIXME how to set the initialValue if the document is not present? It seems the inc value is used as initial new value
Integer incrementObject = increment == 1 ? ONE : Integer.valueOf( increment );
this.addSubQuery( "$inc", update, SEQUENCE_VALUE, incrementObject );
DBObject result = currentCollection.findAndModify( query, null, null, false, update, false, true );
Object idFromDB;
idFromDB = result == null ? null : result.get( SEQUENCE_VALUE );
if ( idFromDB == null ) {
//not inserted yet so we need to add initial value to increment to have the right next value in the DB
//FIXME that means there is a small hole as when there was not value in the DB, we do add initial value in a non atomic way
BasicDBObject updateForInitial = new BasicDBObject();
this.addSubQuery( "$inc", updateForInitial, SEQUENCE_VALUE, initialValue );
currentCollection.findAndModify( query, null, null, false, updateForInitial, false, true );
idFromDB = initialValue; //first time we ask this value
}
else {
idFromDB = result.get( SEQUENCE_VALUE );
}
if ( idFromDB.getClass().equals( Integer.class ) || idFromDB.getClass().equals( Long.class ) ) {
Number id = (Number) idFromDB;
//idFromDB is the one used and the BD contains the next available value to use
value.initialize( id.longValue() );
}
else {
throw new HibernateException( "Cannot increment a non numeric field" );
}
}
@Override
public GridType overrideType(Type type) {
// Override handling of calendar types
if ( type == StandardBasicTypes.CALENDAR || type == StandardBasicTypes.CALENDAR_DATE ) {
return StringCalendarDateType.INSTANCE;
}
else if ( type == StandardBasicTypes.BYTE ) {
return ByteStringType.INSTANCE;
}
return null; // all other types handled as in hibernate-ogm-core
}
}
| OGM-174 update the object id preparation (fix typo, and add some comments)
| hibernate-ogm-mongodb/src/main/java/org/hibernate/ogm/dialect/mongodb/MongoDBDialect.java | OGM-174 update the object id preparation (fix typo, and add some comments) | <ide><path>ibernate-ogm-mongodb/src/main/java/org/hibernate/ogm/dialect/mongodb/MongoDBDialect.java
<ide>
<ide> @Override
<ide> public Tuple createTuple(EntityKey key) {
<del> DBObject toSave = this.preprareIdObject( key );
<add> DBObject toSave = this.prepareIdObject( key );
<ide> return new Tuple( new MongoDBTupleSnapshot( toSave, key.getColumnNames() ) );
<ide> }
<ide>
<ide> private DBObject getObject(EntityKey key) {
<ide> DBCollection collection = this.getCollection( key );
<del> DBObject searchObject = this.preprareIdObject( key );
<add> DBObject searchObject = this.prepareIdObject( key );
<ide> return collection.findOne( searchObject );
<ide> }
<ide>
<ide> *
<ide> * @return the DBObject which represents the id field
<ide> */
<del> private BasicDBObject preprareIdObject(EntityKey key) {
<add> private BasicDBObject prepareIdObject(EntityKey key) {
<add> return this.prepareIdObject( key.getColumnNames(), key.getColumnValues() );
<add> }
<add>
<add> private BasicDBObject prepareIdObject(AssociationKey key){
<add> return this.prepareIdObject( key.getColumnNames(), key.getColumnValues() );
<add> }
<add>
<add> private BasicDBObject prepareIdObject(String[] columnNames, Object[] columnValues){
<ide> BasicDBObject object = null;
<del> if ( key.getColumnNames().length == 1 ) {
<del> object = new BasicDBObject( ID_FIELDNAME, key.getColumnValues()[0] );
<add> if ( columnNames.length == 1 ) {
<add> object = new BasicDBObject( ID_FIELDNAME, columnValues[0] );
<ide> }
<ide> else {
<ide> object = new BasicDBObject();
<ide> DBObject idObject = new BasicDBObject();
<del> for ( int i = 0; i < key.getColumnNames().length; i++ ) {
<del> String columnName = key.getColumnNames()[i];
<del> Object columnValue = key.getColumnValues()[i];
<add> for ( int i = 0; i < columnNames.length; i++ ) {
<add> String columnName = columnNames[i];
<add> Object columnValue = columnValues[i];
<ide>
<ide> if ( columnName.contains( DOT_SEPARATOR ) ) {
<ide> int dotIndex = columnName.indexOf( DOT_SEPARATOR );
<ide> idObject.put( shortColumnName, columnValue );
<ide> }
<ide> else {
<del> idObject.put( key.getColumnNames()[i], columnValue );
<add> idObject.put( columnNames[i], columnValue );
<ide> }
<ide>
<ide> }
<ide> }
<ide> }
<ide>
<add> /*Needed because in case of object with only an ID field
<add> the "_id" won't be persisted properly.
<add> With this adjustment, it will work like this:
<add> if the object (from snapshot) doesn't exist so create the one represented by updater
<add> so if at this moment the "_id" is not enforce properly an ObjectID will be crated by the server instead
<add> of the custom id
<add> */
<ide> if ( updater.size() == 0 ) {
<del> updater = this.preprareIdObject( key );
<add> updater = this.prepareIdObject( key );
<ide> }
<ide> this.getCollection( key ).update( snapshot.getDbObject(), updater, true, false );
<ide> }
<ide> boolean insert = false;
<ide> if ( entity == null ) {
<ide> insert = true;
<del> entity = new BasicDBObject( ID_FIELDNAME, key.getEntityKey().getColumnValues()[0] );
<add> entity = this.prepareIdObject( key );
<ide> }
<ide> if ( getAssociationFieldOrNull( key, entity ) == null ) {
<ide> if ( insert ) {
<ide>
<ide> if ( isEmbedded( key ) ) {
<ide> collection = this.getCollection( key.getEntityKey() );
<del> query = new BasicDBObject( ID_FIELDNAME, key.getEntityKey().getColumnValues()[0] );
<add> query = this.prepareIdObject( key );
<ide> associationField = key.getCollectionRole();
<ide> }
<ide> else { |
|
Java | apache-2.0 | 47c78e7650d9079c17f4a5eb2197083a9d6091c8 | 0 | wyzssw/orientdb,orientechnologies/orientdb,wyzssw/orientdb,wouterv/orientdb,allanmoso/orientdb,intfrr/orientdb,wouterv/orientdb,tempbottle/orientdb,alonsod86/orientdb,mmacfadden/orientdb,joansmith/orientdb,jdillon/orientdb,joansmith/orientdb,allanmoso/orientdb,intfrr/orientdb,cstamas/orientdb,alonsod86/orientdb,tempbottle/orientdb,sanyaade-g2g-repos/orientdb,intfrr/orientdb,tempbottle/orientdb,wyzssw/orientdb,sanyaade-g2g-repos/orientdb,joansmith/orientdb,orientechnologies/orientdb,cstamas/orientdb,wouterv/orientdb,sanyaade-g2g-repos/orientdb,wouterv/orientdb,mmacfadden/orientdb,giastfader/orientdb,cstamas/orientdb,joansmith/orientdb,giastfader/orientdb,jdillon/orientdb,mbhulin/orientdb,rprabhat/orientdb,wyzssw/orientdb,mmacfadden/orientdb,orientechnologies/orientdb,rprabhat/orientdb,alonsod86/orientdb,intfrr/orientdb,rprabhat/orientdb,alonsod86/orientdb,allanmoso/orientdb,cstamas/orientdb,mbhulin/orientdb,giastfader/orientdb,tempbottle/orientdb,mbhulin/orientdb,rprabhat/orientdb,giastfader/orientdb,mmacfadden/orientdb,allanmoso/orientdb,mbhulin/orientdb,orientechnologies/orientdb,sanyaade-g2g-repos/orientdb,jdillon/orientdb | /*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.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.orientechnologies.orient.server.hazelcast;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import com.hazelcast.core.IMap;
import com.hazelcast.core.IQueue;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.OScenarioThreadLocal;
import com.orientechnologies.orient.core.db.OScenarioThreadLocal.RUN_MODE;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.server.config.OServerUserConfiguration;
import com.orientechnologies.orient.server.distributed.ODistributedAbstractPlugin;
import com.orientechnologies.orient.server.distributed.ODistributedConfiguration;
import com.orientechnologies.orient.server.distributed.ODistributedException;
import com.orientechnologies.orient.server.distributed.ODistributedMessageService;
import com.orientechnologies.orient.server.distributed.ODistributedPartition;
import com.orientechnologies.orient.server.distributed.ODistributedPartitioningStrategy;
import com.orientechnologies.orient.server.distributed.ODistributedRequest;
import com.orientechnologies.orient.server.distributed.ODistributedRequest.EXECUTION_MODE;
import com.orientechnologies.orient.server.distributed.ODistributedResponse;
import com.orientechnologies.orient.server.distributed.ODistributedResponseManager;
import com.orientechnologies.orient.server.distributed.ODistributedServerLog;
import com.orientechnologies.orient.server.distributed.ODistributedServerLog.DIRECTION;
/**
* Hazelcast implementation of distributed peer. There is one instance per database. Each node creates own instance to talk with
* each others.
*
* @author Luca Garulli (l.garulli--at--orientechnologies.com)
*
*/
public class OHazelcastDistributedMessageService implements ODistributedMessageService {
protected final OHazelcastPlugin manager;
protected final String databaseName;
protected final static Map<String, IQueue<?>> queues = new HashMap<String, IQueue<?>>();
protected final Lock requestLock;
protected final IQueue<ODistributedResponse> nodeResponseQueue;
protected final ConcurrentHashMap<Long, ArrayBlockingQueue<ODistributedResponse>> internalThreadQueues;
protected final ConcurrentHashMap<Long, ODistributedResponseManager> responsesByRequestIds;
protected final TimerTask asynchMessageManager;
protected ODatabaseDocumentTx database;
public static final String NODE_QUEUE_PREFIX = "orientdb.node.";
public static final String NODE_QUEUE_REQUEST_POSTFIX = ".request";
public static final String NODE_QUEUE_RESPONSE_POSTFIX = ".response";
public static final String NODE_QUEUE_UNDO_POSTFIX = ".undo";
private static final String NODE_LOCK_PREFIX = "orientdb.reqlock.";
public OHazelcastDistributedMessageService(final OHazelcastPlugin manager, final String iDatabaseName) {
this.manager = manager;
this.databaseName = iDatabaseName;
this.requestLock = manager.getHazelcastInstance().getLock(NODE_LOCK_PREFIX + iDatabaseName);
this.internalThreadQueues = new ConcurrentHashMap<Long, ArrayBlockingQueue<ODistributedResponse>>();
this.responsesByRequestIds = new ConcurrentHashMap<Long, ODistributedResponseManager>();
// CREATE TASK THAT CHECK ASYNCHRONOUS MESSAGE RECEIVED
asynchMessageManager = new TimerTask() {
@Override
public void run() {
purgePendingMessages();
}
};
Orient
.instance()
.getTimer()
.schedule(asynchMessageManager, OGlobalConfiguration.DISTRIBUTED_PURGE_RESPONSES_TIMER_DELAY.getValueAsLong(),
OGlobalConfiguration.DISTRIBUTED_PURGE_RESPONSES_TIMER_DELAY.getValueAsLong());
// CREAT THE QUEUE
final String queueName = getResponseQueueName(manager.getLocalNodeName());
nodeResponseQueue = getQueue(queueName);
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), null, DIRECTION.NONE,
"listening for incoming responses on queue: %s", queueName);
checkForPendingMessages(nodeResponseQueue, queueName);
// CREATE THREAD LISTENER AGAINST orientdb.node.<node>.response, ONE PER NODE, THEN DISPATCH THE MESSAGE INTERNALLY USING THE
// THREAD ID
new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()) {
String senderNode = null;
ODistributedResponse message = null;
try {
message = nodeResponseQueue.take();
if (message != null) {
senderNode = message.getSenderNodeName();
dispatchResponseToThread(message);
}
} catch (InterruptedException e) {
// EXIT CURRENT THREAD
Thread.interrupted();
break;
} catch (Throwable e) {
ODistributedServerLog.error(this, manager.getLocalNodeName(), senderNode, DIRECTION.IN,
"error on reading distributed response", e, message != null ? message.getPayload() : "-");
}
}
}
}).start();
}
@Override
public ODistributedRequest createRequest() {
return new OHazelcastDistributedRequest();
}
@Override
public ODistributedResponse send(final ODistributedRequest iRequest) {
final Thread currentThread = Thread.currentThread();
final long threadId = currentThread.getId();
final String databaseName = iRequest.getDatabaseName();
final String clusterName = iRequest.getClusterName();
final ODistributedConfiguration cfg = manager.getDatabaseConfiguration(databaseName);
final ODistributedPartitioningStrategy strategy = manager.getPartitioningStrategy(cfg.getPartitionStrategy(clusterName));
final ODistributedPartition partition = strategy.getPartition(manager, databaseName, clusterName);
final Set<String> nodes = partition.getNodes();
final IQueue<ODistributedRequest>[] reqQueues = getRequestQueues(databaseName, nodes);
final int queueSize = nodes.size();
final int quorum = iRequest.getPayload().isWriteOperation() ? cfg.getWriteQuorum(clusterName) : queueSize;
iRequest.setSenderNodeName(manager.getLocalNodeName());
iRequest.setSenderThreadId(threadId);
int availableNodes = 0;
for (String node : nodes) {
if (manager.isNodeAvailable(node))
availableNodes++;
else {
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), node, DIRECTION.OUT,
"skip listening of response because node '%s' is not online", node);
}
}
final int expectedSynchronousResponses = Math.min(availableNodes, quorum);
final boolean executeOnLocalNode = nodes.contains(manager.getLocalNodeName());
// CREATE THE RESPONSE MANAGER
final ODistributedResponseManager currentResponseMgr = new ODistributedResponseManager(iRequest.getId(), nodes,
expectedSynchronousResponses, quorum, executeOnLocalNode, iRequest.getPayload().getTotalTimeout(queueSize));
responsesByRequestIds.put(iRequest.getId(), currentResponseMgr);
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), nodes.toString(), DIRECTION.OUT, "request %s",
iRequest.getPayload());
final long timeout = OGlobalConfiguration.DISTRIBUTED_QUEUE_TIMEOUT.getValueAsLong();
try {
requestLock.lock();
try {
// LOCK = ASSURE MESSAGES IN THE QUEUE ARE INSERTED SEQUENTIALLY AT CLUSTER LEVEL
// BROADCAST THE REQUEST TO ALL THE NODE QUEUES
for (IQueue<ODistributedRequest> queue : reqQueues) {
queue.offer(iRequest, timeout, TimeUnit.MILLISECONDS);
}
} finally {
requestLock.unlock();
}
Orient.instance().getProfiler()
.updateCounter("distributed.replication.msgSent", "Number of replication messages sent from current node", +1);
return collectResponses(iRequest, currentResponseMgr);
} catch (Throwable e) {
throw new ODistributedException("Error on sending distributed request against " + databaseName
+ (clusterName != null ? ":" + clusterName : ""), e);
}
}
protected ODistributedResponse collectResponses(final ODistributedRequest iRequest,
final ODistributedResponseManager currentResponseMgr) throws InterruptedException {
if (iRequest.getExecutionMode() == EXECUTION_MODE.NO_RESPONSE)
return null;
final long beginTime = System.currentTimeMillis();
int expectedSynchronousResponses = currentResponseMgr.getExpectedSynchronousResponses();
final long synchTimeout = iRequest.getPayload().getSynchronousTimeout(expectedSynchronousResponses);
final ArrayBlockingQueue<ODistributedResponse> responseQueue = getInternalThreadQueue(iRequest.getSenderThreadId());
// WAIT FOR THE MINIMUM SYNCHRONOUS RESPONSES (WRITE QUORUM)
ODistributedResponse firstResponse = null;
while (currentResponseMgr.waitForSynchronousResponses()) {
long elapsed = System.currentTimeMillis() - beginTime;
final ODistributedResponse currentResponse = responseQueue.poll(synchTimeout - elapsed, TimeUnit.MILLISECONDS);
if (currentResponse != null) {
// RESPONSE RECEIVED
if (currentResponse.getRequestId() != iRequest.getId()) {
// IT REFERS TO ANOTHER REQUEST, DISCARD IT
continue;
}
// PROCESS IT AS SYNCHRONOUS
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), currentResponse.getSenderNodeName(), DIRECTION.IN,
"received response: %s", currentResponse);
if (firstResponse == null)
firstResponse = currentResponse;
} else {
elapsed = System.currentTimeMillis() - beginTime;
ODistributedServerLog.warn(this, getLocalNodeNameAndThread(), null, DIRECTION.IN,
"timeout (%dms) on waiting for synchronous responses from nodes=%s responsesSoFar=%s request=%s", elapsed,
currentResponseMgr.getExpectedNodes(), currentResponseMgr.getRespondingNodes(), iRequest);
break;
}
}
if (currentResponseMgr.isExecuteOnLocalNode() && !currentResponseMgr.isReceivedCurrentNode())
ODistributedServerLog.warn(this, getLocalNodeNameAndThread(), manager.getLocalNodeName(), DIRECTION.IN,
"no response received from local node about message %d", iRequest.getId());
if (currentResponseMgr.getReceivedResponses() < currentResponseMgr.getQuorum()) {
// UNDO REQUEST
// TODO: UNDO
iRequest.undo();
}
if (firstResponse == null)
throw new ODistributedException("No response received from any of nodes " + currentResponseMgr.getExpectedNodes()
+ " for request " + iRequest + " after the timeout " + synchTimeout);
return currentResponseMgr.getResponse(iRequest.getPayload().getResultStrategy());
}
protected ArrayBlockingQueue<ODistributedResponse> getInternalThreadQueue(final long threadId) {
ArrayBlockingQueue<ODistributedResponse> responseQueue = internalThreadQueues.get(threadId);
if (responseQueue == null) {
// REGISTER THE INTERNAL THREAD'S RESPONSE QUEUE
responseQueue = new ArrayBlockingQueue<ODistributedResponse>(
OGlobalConfiguration.DISTRIBUTED_THREAD_QUEUE_SIZE.getValueAsInteger(), true);
internalThreadQueues.put(threadId, responseQueue);
}
return responseQueue;
}
public void configureDatabase(final String iDatabaseName) {
// TODO: USE THE POOL!
final OServerUserConfiguration replicatorUser = manager.getServerInstance().getUser(ODistributedAbstractPlugin.REPLICATOR_USER);
database = (ODatabaseDocumentTx) manager.getServerInstance().openDatabase("document", databaseName, replicatorUser.name,
replicatorUser.password);
// CREATE A QUEUE PER DATABASE
final String queueName = getRequestQueueName(manager.getLocalNodeName(), iDatabaseName);
final IQueue<ODistributedRequest> requestQueue = getQueue(queueName);
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), null, DIRECTION.NONE,
"listening for incoming requests on queue: %s", queueName);
// UNDO PREVIOUS MESSAGE IF ANY
final IMap<Object, Object> undoMap = restoreMessagesBeforeFailure(iDatabaseName);
checkForPendingMessages(requestQueue, queueName);
// CREATE THREAD LISTENER AGAINST orientdb.node.<node>.<db>.request, ONE PER NODE, THEN DISPATCH THE MESSAGE INTERNALLY USING
// THE THREAD ID
new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()) {
String senderNode = null;
ODistributedRequest message = null;
try {
// TODO: ASSURE WE DON'T LOOSE THE MSG AT THIS POINT. HAZELCAST TX? OR PEEK? ARE NOT BLOCKING :-(
message = requestQueue.take();
// SAVE THE MESSAGE IN THE UNDO MAP IN CASE OF FAILURE
undoMap.put(iDatabaseName, message);
if (message != null) {
senderNode = message.getSenderNodeName();
onMessage(message);
}
// OK: REMOVE THE UNDO BUFFER
undoMap.remove(iDatabaseName);
} catch (InterruptedException e) {
// EXIT CURRENT THREAD
Thread.interrupted();
break;
} catch (Throwable e) {
ODistributedServerLog.error(this, getLocalNodeNameAndThread(), senderNode, DIRECTION.IN,
"error on reading distributed request: %s", e, message != null ? message.getPayload() : "-");
}
}
}
}).start();
}
/**
* Execute the remote call on the local node and send back the result
*/
protected void onMessage(final ODistributedRequest iRequest) {
OScenarioThreadLocal.INSTANCE.set(RUN_MODE.RUNNING_DISTRIBUTED);
try {
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, manager.getLocalNodeName(),
iRequest.getSenderNodeName() + ":" + iRequest.getSenderThreadId(), DIRECTION.IN, "request %s", iRequest.getPayload());
// EXECUTE IT LOCALLY
final Serializable responsePayload;
try {
ODatabaseRecordThreadLocal.INSTANCE.set(database);
iRequest.getPayload().setNodeSource(iRequest.getSenderNodeName());
responsePayload = manager.executeOnLocalNode(iRequest, database);
} finally {
database.getLevel1Cache().clear();
}
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, manager.getLocalNodeName(),
iRequest.getSenderNodeName() + ":" + iRequest.getSenderThreadId(), DIRECTION.OUT,
"sending back response %s to request %s", responsePayload, iRequest.getPayload());
final OHazelcastDistributedResponse response = new OHazelcastDistributedResponse(iRequest.getId(),
manager.getLocalNodeName(), iRequest.getSenderNodeName(), iRequest.getSenderThreadId(), responsePayload);
try {
// GET THE SENDER'S RESPONSE QUEUE
final IQueue<ODistributedResponse> queue = getQueue(getResponseQueueName(iRequest.getSenderNodeName()));
if (!queue.offer(response, OGlobalConfiguration.DISTRIBUTED_QUEUE_TIMEOUT.getValueAsLong(), TimeUnit.MILLISECONDS))
throw new ODistributedException("Timeout on dispatching response to the thread queue " + iRequest.getSenderNodeName()
+ ":" + iRequest.getSenderThreadId());
} catch (Exception e) {
throw new ODistributedException("Cannot dispatch response to the thread queue " + iRequest.getSenderNodeName() + ":"
+ iRequest.getSenderThreadId(), e);
}
} finally {
OScenarioThreadLocal.INSTANCE.set(RUN_MODE.DEFAULT);
}
}
protected void dispatchResponseToThread(final ODistributedResponse response) {
Orient.instance().getProfiler()
.updateCounter("distributed.replication.msgReceived", "Number of replication messages received in current node", +1);
final long threadId = response.getSenderThreadId();
final String targetLocalNodeThread = manager.getLocalNodeName() + ":" + threadId;
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, manager.getLocalNodeName(), targetLocalNodeThread, DIRECTION.OUT,
"- forward response to the internal thread");
final ArrayBlockingQueue<ODistributedResponse> responseQueue = internalThreadQueues.get(threadId);
if (responseQueue == null) {
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, manager.getLocalNodeName(), targetLocalNodeThread, DIRECTION.OUT,
"cannot dispatch response to the internal thread because the thread queue %d was not found: %s", threadId,
response.getPayload());
return;
}
if (processAsynchResponse(response))
// DISPATCH THE RESPONSE TO THE INTERNAL THREAD TO BE WORKED SYNCHRONOUSLY
try {
if (!responseQueue.offer(response, OGlobalConfiguration.DISTRIBUTED_QUEUE_TIMEOUT.getValueAsLong(), TimeUnit.MILLISECONDS))
ODistributedServerLog.debug(this, manager.getLocalNodeName(), targetLocalNodeThread, DIRECTION.OUT,
"timeout on dispatching response of message %d to the internal thread queue", response.getRequestId());
} catch (Exception e) {
ODistributedServerLog.error(this, manager.getLocalNodeName(), targetLocalNodeThread, DIRECTION.OUT,
"error on dispatching response to the internal thread queue", e);
}
}
@SuppressWarnings("unchecked")
protected IQueue<ODistributedRequest>[] getRequestQueues(final String iDatabaseName, final Set<String> nodes) {
final IQueue<ODistributedRequest>[] queues = new IQueue[nodes.size()];
int i = 0;
for (String node : nodes)
queues[i++] = getQueue(getRequestQueueName(node, iDatabaseName));
return queues;
}
public void shutdown() {
try {
database.close();
} catch (Exception e) {
}
internalThreadQueues.clear();
asynchMessageManager.cancel();
responsesByRequestIds.clear();
if (nodeResponseQueue != null) {
nodeResponseQueue.clear();
nodeResponseQueue.destroy();
}
}
/**
* Composes the request queue name based on node name and database.
*/
protected static String getRequestQueueName(final String iNodeName, final String iDatabaseName) {
final StringBuilder buffer = new StringBuilder();
buffer.append(NODE_QUEUE_PREFIX);
buffer.append(iNodeName);
if (iDatabaseName != null) {
buffer.append('.');
buffer.append(iDatabaseName);
}
buffer.append(NODE_QUEUE_REQUEST_POSTFIX);
return buffer.toString();
}
/**
* Composes the response queue name based on node name.
*/
protected static String getResponseQueueName(final String iNodeName) {
final StringBuilder buffer = new StringBuilder();
buffer.append(NODE_QUEUE_PREFIX);
buffer.append(iNodeName);
buffer.append(NODE_QUEUE_RESPONSE_POSTFIX);
return buffer.toString();
}
/**
* Composes the undo queue name based on node name.
*/
protected String getUndoMapName() {
final StringBuilder buffer = new StringBuilder();
buffer.append(NODE_QUEUE_PREFIX);
buffer.append(manager.getLocalNodeName());
buffer.append(NODE_QUEUE_UNDO_POSTFIX);
return buffer.toString();
}
protected String getLocalNodeNameAndThread() {
return manager.getLocalNodeName() + ":" + Thread.currentThread().getId();
}
protected void purgePendingMessages() {
final long now = System.currentTimeMillis();
final long timeout = OGlobalConfiguration.DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT.getValueAsLong();
for (Iterator<Entry<Long, ODistributedResponseManager>> it = responsesByRequestIds.entrySet().iterator(); it.hasNext();) {
final Entry<Long, ODistributedResponseManager> item = it.next();
final ODistributedResponseManager resp = item.getValue();
final long timeElapsed = now - resp.getSentOn();
if (timeElapsed > timeout) {
// EXPIRED, FREE IT!
final List<String> missingNodes = resp.getMissingNodes();
if (missingNodes.size() > 0) {
ODistributedServerLog.warn(this, manager.getLocalNodeName(), null, DIRECTION.IN,
"%d missed response(s) for message %d by nodes %s after %dms when timeout is %dms", missingNodes.size(),
resp.getMessageId(), missingNodes, timeElapsed, timeout);
}
Orient.instance().getProfiler()
.updateCounter("distributed.replication.timeouts", "Number of timeouts on replication messages responses", +1);
it.remove();
}
}
}
protected IMap<Object, Object> restoreMessagesBeforeFailure(final String iDatabaseName) {
final IMap<Object, Object> undoMap = manager.getHazelcastInstance().getMap(getUndoMapName());
final ODistributedRequest undoRequest = (ODistributedRequest) undoMap.remove(iDatabaseName);
if (undoRequest != null) {
ODistributedServerLog.warn(this, getLocalNodeNameAndThread(), null, DIRECTION.NONE,
"restore last replication message before the crash for database %s: %s", iDatabaseName, undoRequest);
try {
onMessage(undoRequest);
} catch (Throwable t) {
ODistributedServerLog.error(this, getLocalNodeNameAndThread(), null, DIRECTION.NONE,
"error on executing restored message for database %s", t, iDatabaseName);
}
}
return undoMap;
}
protected void checkForPendingMessages(final IQueue<?> iQueue, final String iQueueName) {
final int queueSize = iQueue.size();
if (queueSize > 0)
ODistributedServerLog.warn(this, manager.getLocalNodeName(), null, DIRECTION.NONE,
"found %d previous messages in queue %s, aligning the database...", queueSize, iQueueName);
}
/**
* Processes the response asynchronously.
*
* @return true if the response should be sent to the internal thread queue, otherwise no
*/
protected boolean processAsynchResponse(final ODistributedResponse response) {
final long reqId = response.getRequestId();
// GET ASYNCHRONOUS MSG MANAGER IF ANY
final ODistributedResponseManager asynchMgr = responsesByRequestIds.get(reqId);
if (asynchMgr == null) {
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), response.getSenderNodeName(), DIRECTION.OUT,
"received response for message %d after the timeout", reqId);
return false;
}
boolean processSynchronously = asynchMgr.waitForSynchronousResponses();
if (asynchMgr.addResponse(response))
// ALL RESPONSE RECEIVED, REMOVE THE RESPONSE MANAGER
responsesByRequestIds.remove(reqId);
return processSynchronously;
}
/**
* Return the queue. If not exists create and register it.
*/
@SuppressWarnings("unchecked")
protected <T> IQueue<T> getQueue(final String iQueueName) {
synchronized (queues) {
IQueue<T> queue = (IQueue<T>) queues.get(iQueueName);
if (queue == null) {
queue = manager.getHazelcastInstance().getQueue(iQueueName);
queues.put(iQueueName, queue);
}
return manager.getHazelcastInstance().getQueue(iQueueName);
}
}
public ODatabaseDocumentTx getDatabase() {
return database;
}
}
| distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastDistributedMessageService.java | /*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.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.orientechnologies.orient.server.hazelcast;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import com.hazelcast.core.IMap;
import com.hazelcast.core.IQueue;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.OScenarioThreadLocal;
import com.orientechnologies.orient.core.db.OScenarioThreadLocal.RUN_MODE;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.server.config.OServerUserConfiguration;
import com.orientechnologies.orient.server.distributed.ODistributedAbstractPlugin;
import com.orientechnologies.orient.server.distributed.ODistributedConfiguration;
import com.orientechnologies.orient.server.distributed.ODistributedException;
import com.orientechnologies.orient.server.distributed.ODistributedMessageService;
import com.orientechnologies.orient.server.distributed.ODistributedPartition;
import com.orientechnologies.orient.server.distributed.ODistributedPartitioningStrategy;
import com.orientechnologies.orient.server.distributed.ODistributedRequest;
import com.orientechnologies.orient.server.distributed.ODistributedRequest.EXECUTION_MODE;
import com.orientechnologies.orient.server.distributed.ODistributedResponse;
import com.orientechnologies.orient.server.distributed.ODistributedResponseManager;
import com.orientechnologies.orient.server.distributed.ODistributedServerLog;
import com.orientechnologies.orient.server.distributed.ODistributedServerLog.DIRECTION;
/**
* Hazelcast implementation of distributed peer. There is one instance per database. Each node creates own instance to talk with
* each others.
*
* @author Luca Garulli (l.garulli--at--orientechnologies.com)
*
*/
public class OHazelcastDistributedMessageService implements ODistributedMessageService {
protected final OHazelcastPlugin manager;
protected final String databaseName;
protected final static Map<String, IQueue<?>> queues = new HashMap<String, IQueue<?>>();
protected final Lock requestLock;
protected final IQueue<ODistributedResponse> nodeResponseQueue;
protected final ConcurrentHashMap<Long, ArrayBlockingQueue<ODistributedResponse>> internalThreadQueues;
protected final ConcurrentHashMap<Long, ODistributedResponseManager> responsesByRequestIds;
protected final TimerTask asynchMessageManager;
protected ODatabaseDocumentTx database;
public static final String NODE_QUEUE_PREFIX = "orientdb.node.";
public static final String NODE_QUEUE_REQUEST_POSTFIX = ".request";
public static final String NODE_QUEUE_RESPONSE_POSTFIX = ".response";
public static final String NODE_QUEUE_UNDO_POSTFIX = ".undo";
private static final String NODE_LOCK_PREFIX = "orientdb.reqlock.";
public OHazelcastDistributedMessageService(final OHazelcastPlugin manager, final String iDatabaseName) {
this.manager = manager;
this.databaseName = iDatabaseName;
this.requestLock = manager.getHazelcastInstance().getLock(NODE_LOCK_PREFIX + iDatabaseName);
this.internalThreadQueues = new ConcurrentHashMap<Long, ArrayBlockingQueue<ODistributedResponse>>();
this.responsesByRequestIds = new ConcurrentHashMap<Long, ODistributedResponseManager>();
// CREATE TASK THAT CHECK ASYNCHRONOUS MESSAGE RECEIVED
asynchMessageManager = new TimerTask() {
@Override
public void run() {
purgePendingMessages();
}
};
Orient
.instance()
.getTimer()
.schedule(asynchMessageManager, OGlobalConfiguration.DISTRIBUTED_PURGE_RESPONSES_TIMER_DELAY.getValueAsLong(),
OGlobalConfiguration.DISTRIBUTED_PURGE_RESPONSES_TIMER_DELAY.getValueAsLong());
// CREAT THE QUEUE
final String queueName = getResponseQueueName(manager.getLocalNodeName());
nodeResponseQueue = getQueue(queueName);
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), null, DIRECTION.NONE,
"listening for incoming responses on queue: %s", queueName);
checkForPendingMessages(nodeResponseQueue, queueName);
// CREATE THREAD LISTENER AGAINST orientdb.node.<node>.response, ONE PER NODE, THEN DISPATCH THE MESSAGE INTERNALLY USING THE
// THREAD ID
new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()) {
String senderNode = null;
ODistributedResponse message = null;
try {
message = nodeResponseQueue.take();
if (message != null) {
senderNode = message.getSenderNodeName();
dispatchResponseToThread(message);
}
} catch (InterruptedException e) {
// EXIT CURRENT THREAD
Thread.interrupted();
break;
} catch (Throwable e) {
ODistributedServerLog.error(this, manager.getLocalNodeName(), senderNode, DIRECTION.IN,
"error on reading distributed response", e, message != null ? message.getPayload() : "-");
}
}
}
}).start();
}
@Override
public ODistributedRequest createRequest() {
return new OHazelcastDistributedRequest();
}
@Override
public ODistributedResponse send(final ODistributedRequest iRequest) {
final Thread currentThread = Thread.currentThread();
final long threadId = currentThread.getId();
final String databaseName = iRequest.getDatabaseName();
final String clusterName = iRequest.getClusterName();
final ODistributedConfiguration cfg = manager.getDatabaseConfiguration(databaseName);
final ODistributedPartitioningStrategy strategy = manager.getPartitioningStrategy(cfg.getPartitionStrategy(clusterName));
final ODistributedPartition partition = strategy.getPartition(manager, databaseName, clusterName);
final Set<String> nodes = partition.getNodes();
final IQueue<ODistributedRequest>[] reqQueues = getRequestQueues(databaseName, nodes);
final int queueSize = nodes.size();
final int quorum = iRequest.getPayload().isWriteOperation() ? cfg.getWriteQuorum(clusterName) : queueSize;
iRequest.setSenderNodeName(manager.getLocalNodeName());
iRequest.setSenderThreadId(threadId);
int availableNodes = 0;
for (String node : nodes) {
if (manager.isNodeAvailable(node))
availableNodes++;
else {
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), node, DIRECTION.OUT,
"skip listening of response because node '%s' is not online", node);
}
}
final int expectedSynchronousResponses = Math.min(availableNodes, quorum);
final boolean executeOnLocalNode = nodes.contains(manager.getLocalNodeName());
// CREATE THE RESPONSE MANAGER
final ODistributedResponseManager currentResponseMgr = new ODistributedResponseManager(iRequest.getId(), nodes,
expectedSynchronousResponses, quorum, executeOnLocalNode, iRequest.getPayload().getTotalTimeout(queueSize));
responsesByRequestIds.put(iRequest.getId(), currentResponseMgr);
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), nodes.toString(), DIRECTION.OUT, "request %s",
iRequest.getPayload());
final long timeout = OGlobalConfiguration.DISTRIBUTED_QUEUE_TIMEOUT.getValueAsLong();
try {
requestLock.lock();
try {
// LOCK = ASSURE MESSAGES IN THE QUEUE ARE INSERTED SEQUENTIALLY AT CLUSTER LEVEL
// BROADCAST THE REQUEST TO ALL THE NODE QUEUES
for (IQueue<ODistributedRequest> queue : reqQueues) {
queue.offer(iRequest, timeout, TimeUnit.MILLISECONDS);
}
} finally {
requestLock.unlock();
}
Orient.instance().getProfiler()
.updateCounter("distributed.replication.msgSent", "Number of replication messages sent from current node", +1);
return collectResponses(iRequest, currentResponseMgr);
} catch (Throwable e) {
throw new ODistributedException("Error on sending distributed request against " + databaseName
+ (clusterName != null ? ":" + clusterName : ""), e);
}
}
protected ODistributedResponse collectResponses(final ODistributedRequest iRequest,
final ODistributedResponseManager currentResponseMgr) throws InterruptedException {
if (iRequest.getExecutionMode() == EXECUTION_MODE.NO_RESPONSE)
return null;
final long beginTime = System.currentTimeMillis();
int expectedSynchronousResponses = currentResponseMgr.getExpectedSynchronousResponses();
final long synchTimeout = iRequest.getPayload().getSynchronousTimeout(expectedSynchronousResponses);
final ArrayBlockingQueue<ODistributedResponse> responseQueue = getInternalThreadQueue(iRequest.getSenderThreadId());
// WAIT FOR THE MINIMUM SYNCHRONOUS RESPONSES (WRITE QUORUM)
ODistributedResponse firstResponse = null;
while (currentResponseMgr.waitForSynchronousResponses()) {
long elapsed = System.currentTimeMillis() - beginTime;
final ODistributedResponse currentResponse = responseQueue.poll(synchTimeout - elapsed, TimeUnit.MILLISECONDS);
if (currentResponse != null) {
// RESPONSE RECEIVED
if (currentResponse.getRequestId() != iRequest.getId()) {
// IT REFERS TO ANOTHER REQUEST, DISCARD IT
continue;
}
// PROCESS IT AS SYNCHRONOUS
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), currentResponse.getSenderNodeName(), DIRECTION.IN,
"received response: %s", currentResponse);
if (firstResponse == null)
firstResponse = currentResponse;
} else {
elapsed = System.currentTimeMillis() - beginTime;
ODistributedServerLog.warn(this, getLocalNodeNameAndThread(), null, DIRECTION.IN,
"timeout (%dms) on waiting for synchronous responses from nodes=%s responsesSoFar=%s request=%s", elapsed,
currentResponseMgr.getExpectedNodes(), currentResponseMgr.getRespondingNodes(), iRequest);
break;
}
}
if (currentResponseMgr.isExecuteOnLocalNode() && !currentResponseMgr.isReceivedCurrentNode())
ODistributedServerLog.warn(this, getLocalNodeNameAndThread(), manager.getLocalNodeName(), DIRECTION.IN,
"no response received from local node about message %d", iRequest.getId());
if (currentResponseMgr.getReceivedResponses() < currentResponseMgr.getQuorum()) {
// UNDO REQUEST
// TODO: UNDO
iRequest.undo();
}
if (firstResponse == null)
throw new ODistributedException("No response received from any of nodes " + currentResponseMgr.getExpectedNodes()
+ " for request " + iRequest);
return currentResponseMgr.getResponse(iRequest.getPayload().getResultStrategy());
}
protected ArrayBlockingQueue<ODistributedResponse> getInternalThreadQueue(final long threadId) {
ArrayBlockingQueue<ODistributedResponse> responseQueue = internalThreadQueues.get(threadId);
if (responseQueue == null) {
// REGISTER THE INTERNAL THREAD'S RESPONSE QUEUE
responseQueue = new ArrayBlockingQueue<ODistributedResponse>(
OGlobalConfiguration.DISTRIBUTED_THREAD_QUEUE_SIZE.getValueAsInteger(), true);
internalThreadQueues.put(threadId, responseQueue);
}
return responseQueue;
}
public void configureDatabase(final String iDatabaseName) {
// TODO: USE THE POOL!
final OServerUserConfiguration replicatorUser = manager.getServerInstance().getUser(ODistributedAbstractPlugin.REPLICATOR_USER);
database = (ODatabaseDocumentTx) manager.getServerInstance().openDatabase("document", databaseName, replicatorUser.name,
replicatorUser.password);
// CREATE A QUEUE PER DATABASE
final String queueName = getRequestQueueName(manager.getLocalNodeName(), iDatabaseName);
final IQueue<ODistributedRequest> requestQueue = getQueue(queueName);
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), null, DIRECTION.NONE,
"listening for incoming requests on queue: %s", queueName);
// UNDO PREVIOUS MESSAGE IF ANY
final IMap<Object, Object> undoMap = restoreMessagesBeforeFailure(iDatabaseName);
checkForPendingMessages(requestQueue, queueName);
// CREATE THREAD LISTENER AGAINST orientdb.node.<node>.<db>.request, ONE PER NODE, THEN DISPATCH THE MESSAGE INTERNALLY USING
// THE THREAD ID
new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()) {
String senderNode = null;
ODistributedRequest message = null;
try {
// TODO: ASSURE WE DON'T LOOSE THE MSG AT THIS POINT. HAZELCAST TX? OR PEEK? ARE NOT BLOCKING :-(
message = requestQueue.take();
// SAVE THE MESSAGE IN THE UNDO MAP IN CASE OF FAILURE
undoMap.put(iDatabaseName, message);
if (message != null) {
senderNode = message.getSenderNodeName();
onMessage(message);
}
// OK: REMOVE THE UNDO BUFFER
undoMap.remove(iDatabaseName);
} catch (InterruptedException e) {
// EXIT CURRENT THREAD
Thread.interrupted();
break;
} catch (Throwable e) {
ODistributedServerLog.error(this, getLocalNodeNameAndThread(), senderNode, DIRECTION.IN,
"error on reading distributed request: %s", e, message != null ? message.getPayload() : "-");
}
}
}
}).start();
}
/**
* Execute the remote call on the local node and send back the result
*/
protected void onMessage(final ODistributedRequest iRequest) {
OScenarioThreadLocal.INSTANCE.set(RUN_MODE.RUNNING_DISTRIBUTED);
try {
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, manager.getLocalNodeName(),
iRequest.getSenderNodeName() + ":" + iRequest.getSenderThreadId(), DIRECTION.IN, "request %s", iRequest.getPayload());
// EXECUTE IT LOCALLY
final Serializable responsePayload;
try {
ODatabaseRecordThreadLocal.INSTANCE.set(database);
iRequest.getPayload().setNodeSource(iRequest.getSenderNodeName());
responsePayload = manager.executeOnLocalNode(iRequest, database);
} finally {
database.getLevel1Cache().clear();
}
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, manager.getLocalNodeName(),
iRequest.getSenderNodeName() + ":" + iRequest.getSenderThreadId(), DIRECTION.OUT,
"sending back response %s to request %s", responsePayload, iRequest.getPayload());
final OHazelcastDistributedResponse response = new OHazelcastDistributedResponse(iRequest.getId(),
manager.getLocalNodeName(), iRequest.getSenderNodeName(), iRequest.getSenderThreadId(), responsePayload);
try {
// GET THE SENDER'S RESPONSE QUEUE
final IQueue<ODistributedResponse> queue = getQueue(getResponseQueueName(iRequest.getSenderNodeName()));
if (!queue.offer(response, OGlobalConfiguration.DISTRIBUTED_QUEUE_TIMEOUT.getValueAsLong(), TimeUnit.MILLISECONDS))
throw new ODistributedException("Timeout on dispatching response to the thread queue " + iRequest.getSenderNodeName()
+ ":" + iRequest.getSenderThreadId());
} catch (Exception e) {
throw new ODistributedException("Cannot dispatch response to the thread queue " + iRequest.getSenderNodeName() + ":"
+ iRequest.getSenderThreadId(), e);
}
} finally {
OScenarioThreadLocal.INSTANCE.set(RUN_MODE.DEFAULT);
}
}
protected void dispatchResponseToThread(final ODistributedResponse response) {
Orient.instance().getProfiler()
.updateCounter("distributed.replication.msgReceived", "Number of replication messages received in current node", +1);
final long threadId = response.getSenderThreadId();
final String targetLocalNodeThread = manager.getLocalNodeName() + ":" + threadId;
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, manager.getLocalNodeName(), targetLocalNodeThread, DIRECTION.OUT,
"- forward response to the internal thread");
final ArrayBlockingQueue<ODistributedResponse> responseQueue = internalThreadQueues.get(threadId);
if (responseQueue == null) {
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, manager.getLocalNodeName(), targetLocalNodeThread, DIRECTION.OUT,
"cannot dispatch response to the internal thread because the thread queue %d was not found: %s", threadId,
response.getPayload());
return;
}
if (processAsynchResponse(response))
// DISPATCH THE RESPONSE TO THE INTERNAL THREAD TO BE WORKED SYNCHRONOUSLY
try {
if (!responseQueue.offer(response, OGlobalConfiguration.DISTRIBUTED_QUEUE_TIMEOUT.getValueAsLong(), TimeUnit.MILLISECONDS))
ODistributedServerLog.debug(this, manager.getLocalNodeName(), targetLocalNodeThread, DIRECTION.OUT,
"timeout on dispatching response of message %d to the internal thread queue", response.getRequestId());
} catch (Exception e) {
ODistributedServerLog.error(this, manager.getLocalNodeName(), targetLocalNodeThread, DIRECTION.OUT,
"error on dispatching response to the internal thread queue", e);
}
}
@SuppressWarnings("unchecked")
protected IQueue<ODistributedRequest>[] getRequestQueues(final String iDatabaseName, final Set<String> nodes) {
final IQueue<ODistributedRequest>[] queues = new IQueue[nodes.size()];
int i = 0;
for (String node : nodes)
queues[i++] = getQueue(getRequestQueueName(node, iDatabaseName));
return queues;
}
public void shutdown() {
try {
database.close();
} catch (Exception e) {
}
internalThreadQueues.clear();
asynchMessageManager.cancel();
responsesByRequestIds.clear();
if (nodeResponseQueue != null) {
nodeResponseQueue.clear();
nodeResponseQueue.destroy();
}
}
/**
* Composes the request queue name based on node name and database.
*/
protected static String getRequestQueueName(final String iNodeName, final String iDatabaseName) {
final StringBuilder buffer = new StringBuilder();
buffer.append(NODE_QUEUE_PREFIX);
buffer.append(iNodeName);
if (iDatabaseName != null) {
buffer.append('.');
buffer.append(iDatabaseName);
}
buffer.append(NODE_QUEUE_REQUEST_POSTFIX);
return buffer.toString();
}
/**
* Composes the response queue name based on node name.
*/
protected static String getResponseQueueName(final String iNodeName) {
final StringBuilder buffer = new StringBuilder();
buffer.append(NODE_QUEUE_PREFIX);
buffer.append(iNodeName);
buffer.append(NODE_QUEUE_RESPONSE_POSTFIX);
return buffer.toString();
}
/**
* Composes the undo queue name based on node name.
*/
protected String getUndoMapName() {
final StringBuilder buffer = new StringBuilder();
buffer.append(NODE_QUEUE_PREFIX);
buffer.append(manager.getLocalNodeName());
buffer.append(NODE_QUEUE_UNDO_POSTFIX);
return buffer.toString();
}
protected String getLocalNodeNameAndThread() {
return manager.getLocalNodeName() + ":" + Thread.currentThread().getId();
}
protected void purgePendingMessages() {
final long now = System.currentTimeMillis();
for (Iterator<Entry<Long, ODistributedResponseManager>> it = responsesByRequestIds.entrySet().iterator(); it.hasNext();) {
final Entry<Long, ODistributedResponseManager> item = it.next();
final ODistributedResponseManager resp = item.getValue();
final long timeElapsed = now - resp.getSentOn();
if (timeElapsed > OGlobalConfiguration.DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT.getValueAsLong()) {
// EXPIRED, FREE IT!
final List<String> missingNodes = resp.getMissingNodes();
if (missingNodes.size() > 0) {
ODistributedServerLog.warn(this, manager.getLocalNodeName(), null, DIRECTION.IN,
"%d missed response(s) for message %d by nodes %s after %dms when timeout is %dms", missingNodes.size(),
resp.getMessageId(), missingNodes, timeElapsed, resp.getTotalTimeout());
}
Orient.instance().getProfiler()
.updateCounter("distributed.replication.timeouts", "Number of timeouts on replication messages responses", +1);
it.remove();
}
}
}
protected IMap<Object, Object> restoreMessagesBeforeFailure(final String iDatabaseName) {
final IMap<Object, Object> undoMap = manager.getHazelcastInstance().getMap(getUndoMapName());
final ODistributedRequest undoRequest = (ODistributedRequest) undoMap.remove(iDatabaseName);
if (undoRequest != null) {
ODistributedServerLog.warn(this, getLocalNodeNameAndThread(), null, DIRECTION.NONE,
"restore last replication message before the crash for database %s: %s", iDatabaseName, undoRequest);
try {
onMessage(undoRequest);
} catch (Throwable t) {
ODistributedServerLog.error(this, getLocalNodeNameAndThread(), null, DIRECTION.NONE,
"error on executing restored message for database %s", t, iDatabaseName);
}
}
return undoMap;
}
protected void checkForPendingMessages(final IQueue<?> iQueue, final String iQueueName) {
final int queueSize = iQueue.size();
if (queueSize > 0)
ODistributedServerLog.warn(this, manager.getLocalNodeName(), null, DIRECTION.NONE,
"found %d previous messages in queue %s, aligning the database...", queueSize, iQueueName);
}
/**
* Processes the response asynchronously.
*
* @return true if the response should be sent to the internal thread queue, otherwise no
*/
protected boolean processAsynchResponse(final ODistributedResponse response) {
final long reqId = response.getRequestId();
// GET ASYNCHRONOUS MSG MANAGER IF ANY
final ODistributedResponseManager asynchMgr = responsesByRequestIds.get(reqId);
if (asynchMgr == null) {
if (ODistributedServerLog.isDebugEnabled())
ODistributedServerLog.debug(this, getLocalNodeNameAndThread(), response.getSenderNodeName(), DIRECTION.OUT,
"received response for message %d after the timeout", reqId);
return false;
}
boolean processSynchronously = asynchMgr.waitForSynchronousResponses();
if (asynchMgr.addResponse(response))
// ALL RESPONSE RECEIVED, REMOVE THE RESPONSE MANAGER
responsesByRequestIds.remove(reqId);
return processSynchronously;
}
/**
* Return the queue. If not exists create and register it.
*/
@SuppressWarnings("unchecked")
protected <T> IQueue<T> getQueue(final String iQueueName) {
synchronized (queues) {
IQueue<T> queue = (IQueue<T>) queues.get(iQueueName);
if (queue == null) {
queue = manager.getHazelcastInstance().getQueue(iQueueName);
queues.put(iQueueName, queue);
}
return manager.getHazelcastInstance().getQueue(iQueueName);
}
}
public ODatabaseDocumentTx getDatabase() {
return database;
}
}
| Distributed: improved timeout messages and fixed asynch timeout value
| distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastDistributedMessageService.java | Distributed: improved timeout messages and fixed asynch timeout value | <ide><path>istributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastDistributedMessageService.java
<ide>
<ide> if (firstResponse == null)
<ide> throw new ODistributedException("No response received from any of nodes " + currentResponseMgr.getExpectedNodes()
<del> + " for request " + iRequest);
<add> + " for request " + iRequest + " after the timeout " + synchTimeout);
<ide>
<ide> return currentResponseMgr.getResponse(iRequest.getPayload().getResultStrategy());
<ide> }
<ide> protected void purgePendingMessages() {
<ide> final long now = System.currentTimeMillis();
<ide>
<add> final long timeout = OGlobalConfiguration.DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT.getValueAsLong();
<add>
<ide> for (Iterator<Entry<Long, ODistributedResponseManager>> it = responsesByRequestIds.entrySet().iterator(); it.hasNext();) {
<ide> final Entry<Long, ODistributedResponseManager> item = it.next();
<ide>
<ide>
<ide> final long timeElapsed = now - resp.getSentOn();
<ide>
<del> if (timeElapsed > OGlobalConfiguration.DISTRIBUTED_ASYNCH_RESPONSES_TIMEOUT.getValueAsLong()) {
<add> if (timeElapsed > timeout) {
<ide> // EXPIRED, FREE IT!
<ide> final List<String> missingNodes = resp.getMissingNodes();
<ide> if (missingNodes.size() > 0) {
<ide> ODistributedServerLog.warn(this, manager.getLocalNodeName(), null, DIRECTION.IN,
<ide> "%d missed response(s) for message %d by nodes %s after %dms when timeout is %dms", missingNodes.size(),
<del> resp.getMessageId(), missingNodes, timeElapsed, resp.getTotalTimeout());
<add> resp.getMessageId(), missingNodes, timeElapsed, timeout);
<ide> }
<ide>
<ide> Orient.instance().getProfiler() |
|
Java | mit | 56f33b373d8133e443f6847bbeb3293475f24f6e | 0 | MightyPirates/OC-LuaJ,MightyPirates/OC-LuaJ | package lua;
/**
* Constants for lua limits and opcodes
*
* @author jim_roseborough
*
*/
public class Lua {
// from llimits.h
/** maximum stack for a Lua function */
public static final int MAXSTACK = 250;
/** minimum size for the string table (must be power of 2) */
public static final int MINSTRTABSIZE = 32;
/** minimum size for string buffer */
public static final int LUA_MINBUFFER = 32;
/** use return values from previous op */
public static final int LUA_MULTRET = -1;
// from lopcodes.h
/*===========================================================================
We assume that instructions are unsigned numbers.
All instructions have an opcode in the first 6 bits.
Instructions can have the following fields:
`A' : 8 bits
`B' : 9 bits
`C' : 9 bits
`Bx' : 18 bits (`B' and `C' together)
`sBx' : signed Bx
A signed argument is represented in excess K; that is, the number
value is the unsigned value minus K. K is exactly the maximum value
for that argument (so that -max is represented by 0, and +max is
represented by 2*max), which is half the maximum for the corresponding
unsigned argument.
===========================================================================*/
/* basic instruction format */
public static final int iABC = 0;
public static final int iABx = 1;
public static final int iAsBx = 2;
/*
** size and position of opcode arguments.
*/
public static final int SIZE_C = 9;
public static final int SIZE_B = 9;
public static final int SIZE_Bx = (SIZE_C + SIZE_B);
public static final int SIZE_A = 8;
public static final int SIZE_OP = 6;
public static final int POS_OP = 0;
public static final int POS_A = (POS_OP + SIZE_OP);
public static final int POS_C = (POS_A + SIZE_A);
public static final int POS_B = (POS_C + SIZE_C);
public static final int POS_Bx = POS_C;
public static final int MAX_OP = ((1<<SIZE_OP)-1);
public static final int MAXARG_A = ((1<<SIZE_A)-1);
public static final int MAXARG_B = ((1<<SIZE_B)-1);
public static final int MAXARG_C = ((1<<SIZE_C)-1);
public static final int MAXARG_Bx = ((1<<SIZE_Bx)-1);
public static final int MAXARG_sBx = (MAXARG_Bx>>1); /* `sBx' is signed */
public static final int MASK_OP = ((1<<SIZE_OP)-1)<<POS_OP;
public static final int MASK_A = ((1<<SIZE_A)-1)<<POS_A;
public static final int MASK_B = ((1<<SIZE_B)-1)<<POS_B;
public static final int MASK_C = ((1<<SIZE_C)-1)<<POS_C;
public static final int MASK_Bx = ((1<<SIZE_Bx)-1)<<POS_Bx;
public static final int MASK_NOT_OP = ~MASK_OP;
public static final int MASK_NOT_A = ~MASK_A;
public static final int MASK_NOT_B = ~MASK_B;
public static final int MASK_NOT_C = ~MASK_C;
public static final int MASK_NOT_Bx = ~MASK_Bx;
/*
** the following macros help to manipulate instructions
*/
public static int GET_OPCODE(int i) {
return (i >> POS_OP) & MAX_OP;
}
public static int SET_OPCODE(int i,int o) {
return (i & (MASK_NOT_OP)) | ((o & MAX_OP) << POS_OP);
}
public static int GETARG_A(int i) {
return (i >> POS_A) & MAXARG_A;
}
public static int SETARG_A(int i,int u) {
return (i & (MASK_NOT_A)) | ((u & MAXARG_A) << POS_A);
}
public static int GETARG_B(int i) {
return (i >> POS_B) & MAXARG_B;
}
public static int SETARG_B(int i,int u) {
return (i & (MASK_NOT_B)) | ((u & MAXARG_B) << POS_B);
}
public static int GETARG_C(int i) {
return (i >> POS_C) & MAXARG_C;
}
public static int SETARG_C(int i,int u) {
return (i & (MASK_NOT_C)) | ((u & MAXARG_C) << POS_C);
}
public static int GETARG_Bx(int i) {
return (i >> POS_Bx) & MAXARG_Bx;
}
public static int SETARG_Bx(int i,int u) {
return (i & (MASK_NOT_Bx)) | ((u & MAXARG_Bx) << POS_Bx);
}
public static int GETARG_sBx(int i) {
return ((i >> POS_Bx) & MAXARG_Bx) - MAXARG_sBx;
}
public static int SETARG_sBx(int i,int u) {
return (i & (MASK_NOT_Bx)) | ((u + MAXARG_sBx) << POS_Bx);
}
public static int CREATE_ABC(int o, int a, int b, int c) {
return (o<<POS_OP) | (a<<POS_A) | (b<<POS_B) | (c<<POS_C);
}
public static int CREATE_ABx(int o, int a, int bc) {
return (o<<POS_OP) | (a<<POS_A) | (bc<<POS_Bx);
}
/*
** Macros to operate RK indices
*/
/** this bit 1 means constant (0 means register) */
public static final int BITRK = (1 << (SIZE_B - 1));
/** test whether value is a constant */
public static boolean ISK(int x) {
return 0 != ((x) & BITRK);
}
/** gets the index of the constant */
public static int INDEXK(int r) {
return ((int)(r) & ~BITRK);
}
public static final int MAXINDEXRK = (BITRK - 1);
/** code a constant index as a RK value */
public static int RKASK(int x) {
return ((x) | BITRK);
}
/**
** invalid register that fits in 8 bits
*/
public static final int NO_REG = MAXARG_A;
/*
** R(x) - register
** Kst(x) - constant (in constant table)
** RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x)
*/
/*
** grep "ORDER OP" if you change these enums
*/
/*----------------------------------------------------------------------
name args description
------------------------------------------------------------------------*/
public static final int OP_MOVE = 0;/* A B R(A) := R(B) */
public static final int OP_LOADK = 1;/* A Bx R(A) := Kst(Bx) */
public static final int OP_LOADBOOL = 2;/* A B C R(A) := (Bool)B; if (C) pc++ */
public static final int OP_LOADNIL = 3; /* A B R(A) := ... := R(B) := nil */
public static final int OP_GETUPVAL = 4; /* A B R(A) := UpValue[B] */
public static final int OP_GETGLOBAL = 5; /* A Bx R(A) := Gbl[Kst(Bx)] */
public static final int OP_GETTABLE = 6; /* A B C R(A) := R(B)[RK(C)] */
public static final int OP_SETGLOBAL = 7; /* A Bx Gbl[Kst(Bx)] := R(A) */
public static final int OP_SETUPVAL = 8; /* A B UpValue[B] := R(A) */
public static final int OP_SETTABLE = 9; /* A B C R(A)[RK(B)] := RK(C) */
public static final int OP_NEWTABLE = 10; /* A B C R(A) := {} (size = B,C) */
public static final int OP_SELF = 11; /* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */
public static final int OP_ADD = 12; /* A B C R(A) := RK(B) + RK(C) */
public static final int OP_SUB = 13; /* A B C R(A) := RK(B) - RK(C) */
public static final int OP_MUL = 14; /* A B C R(A) := RK(B) * RK(C) */
public static final int OP_DIV = 15; /* A B C R(A) := RK(B) / RK(C) */
public static final int OP_MOD = 16; /* A B C R(A) := RK(B) % RK(C) */
public static final int OP_POW = 17; /* A B C R(A) := RK(B) ^ RK(C) */
public static final int OP_UNM = 18; /* A B R(A) := -R(B) */
public static final int OP_NOT = 19; /* A B R(A) := not R(B) */
public static final int OP_LEN = 20; /* A B R(A) := length of R(B) */
public static final int OP_CONCAT = 21; /* A B C R(A) := R(B).. ... ..R(C) */
public static final int OP_JMP = 22; /* sBx pc+=sBx */
public static final int OP_EQ = 23; /* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */
public static final int OP_LT = 24; /* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */
public static final int OP_LE = 25; /* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */
public static final int OP_TEST = 26; /* A C if not (R(A) <=> C) then pc++ */
public static final int OP_TESTSET = 27; /* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */
public static final int OP_CALL = 28; /* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */
public static final int OP_TAILCALL = 29; /* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */
public static final int OP_RETURN = 30; /* A B return R(A), ... ,R(A+B-2) (see note) */
public static final int OP_FORLOOP = 31; /* A sBx R(A)+=R(A+2);
if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/
public static final int OP_FORPREP = 32; /* A sBx R(A)-=R(A+2); pc+=sBx */
public static final int OP_TFORLOOP = 33; /* A C R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2));
if R(A+3) ~= nil then R(A+2)=R(A+3) else pc++ */
public static final int OP_SETLIST = 34; /* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */
public static final int OP_CLOSE = 35; /* A close all variables in the stack up to (>=) R(A)*/
public static final int OP_CLOSURE = 36; /* A Bx R(A) := closure(KPROTO[Bx], R(A), ... ,R(A+n)) */
public static final int OP_VARARG = 37; /* A B R(A), R(A+1), ..., R(A+B-1) = vararg */
public static final int NUM_OPCODES = OP_VARARG + 1;
/*===========================================================================
Notes:
(*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1,
and can be 0: OP_CALL then sets `top' to last_result+1, so
next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use `top'.
(*) In OP_VARARG, if (B == 0) then use actual number of varargs and
set top (like in OP_CALL with C == 0).
(*) In OP_RETURN, if (B == 0) then return up to `top'
(*) In OP_SETLIST, if (B == 0) then B = `top';
if (C == 0) then next `instruction' is real C
(*) For comparisons, A specifies what condition the test should accept
(true or false).
(*) All `skips' (pc++) assume that next instruction is a jump
===========================================================================*/
/*
** masks for instruction properties. The format is:
** bits 0-1: op mode
** bits 2-3: C arg mode
** bits 4-5: B arg mode
** bit 6: instruction set register A
** bit 7: operator is a test
*/
public static final int OpArgN = 0; /* argument is not used */
public static final int OpArgU = 1; /* argument is used */
public static final int OpArgR = 2; /* argument is a register or a jump offset */
public static final int OpArgK = 3; /* argument is a constant or register/constant */
public static final int[] luaP_opmodes = {
/* T A B C mode opcode */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_MOVE */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgN<<2) | (iABx), /* OP_LOADK */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_LOADBOOL */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_LOADNIL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_GETUPVAL */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgN<<2) | (iABx), /* OP_GETGLOBAL */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgK<<2) | (iABC), /* OP_GETTABLE */
(0<<7) | (0<<6) | (OpArgK<<4) | (OpArgN<<2) | (iABx), /* OP_SETGLOBAL */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_SETUPVAL */
(0<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SETTABLE */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_NEWTABLE */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgK<<2) | (iABC), /* OP_SELF */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_ADD */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SUB */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_MUL */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_DIV */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_MOD */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_POW */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_UNM */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_NOT */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_LEN */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgR<<2) | (iABC), /* OP_CONCAT */
(0<<7) | (0<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_JMP */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_EQ */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_LT */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_LE */
(1<<7) | (1<<6) | (OpArgR<<4) | (OpArgU<<2) | (iABC), /* OP_TEST */
(1<<7) | (1<<6) | (OpArgR<<4) | (OpArgU<<2) | (iABC), /* OP_TESTSET */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_CALL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_TAILCALL */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_RETURN */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_FORLOOP */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_FORPREP */
(1<<7) | (0<<6) | (OpArgN<<4) | (OpArgU<<2) | (iABC), /* OP_TFORLOOP */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_SETLIST */
(0<<7) | (0<<6) | (OpArgN<<4) | (OpArgN<<2) | (iABC), /* OP_CLOSE */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABx), /* OP_CLOSURE */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_VARARG */
};
public static int getOpMode(int m) {
return luaP_opmodes[m] & 3;
}
public static int getBMode(int m) {
return (luaP_opmodes[m] >> 4) & 3;
}
public static int getCMode(int m) {
return (luaP_opmodes[m] >> 2) & 3;
}
public static boolean testAMode(int m) {
return 0 != (luaP_opmodes[m] & (1 << 6));
}
public static boolean testTMode(int m) {
return 0 != (luaP_opmodes[m] & (1 << 7));
}
/** opcode names */
public static final String[] luaP_opnames = {
"MOVE",
"LOADK",
"LOADBOOL",
"LOADNIL",
"GETUPVAL",
"GETGLOBAL",
"GETTABLE",
"SETGLOBAL",
"SETUPVAL",
"SETTABLE",
"NEWTABLE",
"SELF",
"ADD",
"SUB",
"MUL",
"DIV",
"MOD",
"POW",
"UNM",
"NOT",
"LEN",
"CONCAT",
"JMP",
"EQ",
"LT",
"LE",
"TEST",
"TESTSET",
"CALL",
"TAILCALL",
"RETURN",
"FORLOOP",
"FORPREP",
"TFORLOOP",
"SETLIST",
"CLOSE",
"CLOSURE",
"VARARG",
null,
};
}
| src/main/java/lua/Lua.java | package lua;
/**
* Constants for lua limits and opcodes
*
* @author jim_roseborough
*
*/
public class Lua {
// from llimits.h
/** maximum stack for a Lua function */
public static final int MAXSTACK = 250;
/** minimum size for the string table (must be power of 2) */
public static final int MINSTRTABSIZE = 32;
/** minimum size for string buffer */
public static final int LUA_MINBUFFER = 32;
// from lopcodes.h
/*===========================================================================
We assume that instructions are unsigned numbers.
All instructions have an opcode in the first 6 bits.
Instructions can have the following fields:
`A' : 8 bits
`B' : 9 bits
`C' : 9 bits
`Bx' : 18 bits (`B' and `C' together)
`sBx' : signed Bx
A signed argument is represented in excess K; that is, the number
value is the unsigned value minus K. K is exactly the maximum value
for that argument (so that -max is represented by 0, and +max is
represented by 2*max), which is half the maximum for the corresponding
unsigned argument.
===========================================================================*/
/* basic instruction format */
public static final int iABC = 0;
public static final int iABx = 1;
public static final int iAsBx = 2;
/*
** size and position of opcode arguments.
*/
public static final int SIZE_C = 9;
public static final int SIZE_B = 9;
public static final int SIZE_Bx = (SIZE_C + SIZE_B);
public static final int SIZE_A = 8;
public static final int SIZE_OP = 6;
public static final int POS_OP = 0;
public static final int POS_A = (POS_OP + SIZE_OP);
public static final int POS_C = (POS_A + SIZE_A);
public static final int POS_B = (POS_C + SIZE_C);
public static final int POS_Bx = POS_C;
public static final int MAX_OP = ((1<<SIZE_OP)-1);
public static final int MAXARG_A = ((1<<SIZE_A)-1);
public static final int MAXARG_B = ((1<<SIZE_B)-1);
public static final int MAXARG_C = ((1<<SIZE_C)-1);
public static final int MAXARG_Bx = ((1<<SIZE_Bx)-1);
public static final int MAXARG_sBx = (MAXARG_Bx>>1); /* `sBx' is signed */
public static final int MASK_OP = ((1<<SIZE_OP)-1)<<POS_OP;
public static final int MASK_A = ((1<<SIZE_A)-1)<<POS_A;
public static final int MASK_B = ((1<<SIZE_B)-1)<<POS_B;
public static final int MASK_C = ((1<<SIZE_C)-1)<<POS_C;
public static final int MASK_Bx = ((1<<SIZE_Bx)-1)<<POS_Bx;
public static final int MASK_NOT_OP = ~MASK_OP;
public static final int MASK_NOT_A = ~MASK_A;
public static final int MASK_NOT_B = ~MASK_B;
public static final int MASK_NOT_C = ~MASK_C;
public static final int MASK_NOT_Bx = ~MASK_Bx;
/*
** the following macros help to manipulate instructions
*/
public static int GET_OPCODE(int i) {
return (i >> POS_OP) & MAX_OP;
}
public static int SET_OPCODE(int i,int o) {
return (i & (MASK_NOT_OP)) | ((o & MAX_OP) << POS_OP);
}
public static int GETARG_A(int i) {
return (i >> POS_A) & MAXARG_A;
}
public static int SETARG_A(int i,int u) {
return (i & (MASK_NOT_A)) | ((u & MAXARG_A) << POS_A);
}
public static int GETARG_B(int i) {
return (i >> POS_B) & MAXARG_B;
}
public static int SETARG_B(int i,int u) {
return (i & (MASK_NOT_B)) | ((u & MAXARG_B) << POS_B);
}
public static int GETARG_C(int i) {
return (i >> POS_C) & MAXARG_C;
}
public static int SETARG_C(int i,int u) {
return (i & (MASK_NOT_C)) | ((u & MAXARG_C) << POS_C);
}
public static int GETARG_Bx(int i) {
return (i >> POS_Bx) & MAXARG_Bx;
}
public static int SETARG_Bx(int i,int u) {
return (i & (MASK_NOT_Bx)) | ((u & MAXARG_Bx) << POS_Bx);
}
public static int GETARG_sBx(int i) {
return ((i >> POS_Bx) & MAXARG_Bx) - MAXARG_sBx;
}
public static int SETARG_sBx(int i,int u) {
return (i & (MASK_NOT_Bx)) | ((u + MAXARG_sBx) << POS_Bx);
}
public static int CREATE_ABC(int o, int a, int b, int c) {
return (o<<POS_OP) | (a<<POS_A) | (b<<POS_B) | (c<<POS_C);
}
public static int CREATE_ABx(int o, int a, int bc) {
return (o<<POS_OP) | (a<<POS_A) | (bc<<POS_Bx);
}
/*
** Macros to operate RK indices
*/
/** this bit 1 means constant (0 means register) */
public static final int BITRK = (1 << (SIZE_B - 1));
/** test whether value is a constant */
public static boolean ISK(int x) {
return 0 != ((x) & BITRK);
}
/** gets the index of the constant */
public static int INDEXK(int r) {
return ((int)(r) & ~BITRK);
}
public static final int MAXINDEXRK = (BITRK - 1);
/** code a constant index as a RK value */
public static int RKASK(int x) {
return ((x) | BITRK);
}
/**
** invalid register that fits in 8 bits
*/
public static final int NO_REG = MAXARG_A;
/*
** R(x) - register
** Kst(x) - constant (in constant table)
** RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x)
*/
/*
** grep "ORDER OP" if you change these enums
*/
/*----------------------------------------------------------------------
name args description
------------------------------------------------------------------------*/
public static final int OP_MOVE = 0;/* A B R(A) := R(B) */
public static final int OP_LOADK = 1;/* A Bx R(A) := Kst(Bx) */
public static final int OP_LOADBOOL = 2;/* A B C R(A) := (Bool)B; if (C) pc++ */
public static final int OP_LOADNIL = 3; /* A B R(A) := ... := R(B) := nil */
public static final int OP_GETUPVAL = 4; /* A B R(A) := UpValue[B] */
public static final int OP_GETGLOBAL = 5; /* A Bx R(A) := Gbl[Kst(Bx)] */
public static final int OP_GETTABLE = 6; /* A B C R(A) := R(B)[RK(C)] */
public static final int OP_SETGLOBAL = 7; /* A Bx Gbl[Kst(Bx)] := R(A) */
public static final int OP_SETUPVAL = 8; /* A B UpValue[B] := R(A) */
public static final int OP_SETTABLE = 9; /* A B C R(A)[RK(B)] := RK(C) */
public static final int OP_NEWTABLE = 10; /* A B C R(A) := {} (size = B,C) */
public static final int OP_SELF = 11; /* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */
public static final int OP_ADD = 12; /* A B C R(A) := RK(B) + RK(C) */
public static final int OP_SUB = 13; /* A B C R(A) := RK(B) - RK(C) */
public static final int OP_MUL = 14; /* A B C R(A) := RK(B) * RK(C) */
public static final int OP_DIV = 15; /* A B C R(A) := RK(B) / RK(C) */
public static final int OP_MOD = 16; /* A B C R(A) := RK(B) % RK(C) */
public static final int OP_POW = 17; /* A B C R(A) := RK(B) ^ RK(C) */
public static final int OP_UNM = 18; /* A B R(A) := -R(B) */
public static final int OP_NOT = 19; /* A B R(A) := not R(B) */
public static final int OP_LEN = 20; /* A B R(A) := length of R(B) */
public static final int OP_CONCAT = 21; /* A B C R(A) := R(B).. ... ..R(C) */
public static final int OP_JMP = 22; /* sBx pc+=sBx */
public static final int OP_EQ = 23; /* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */
public static final int OP_LT = 24; /* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */
public static final int OP_LE = 25; /* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */
public static final int OP_TEST = 26; /* A C if not (R(A) <=> C) then pc++ */
public static final int OP_TESTSET = 27; /* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */
public static final int OP_CALL = 28; /* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */
public static final int OP_TAILCALL = 29; /* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */
public static final int OP_RETURN = 30; /* A B return R(A), ... ,R(A+B-2) (see note) */
public static final int OP_FORLOOP = 31; /* A sBx R(A)+=R(A+2);
if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/
public static final int OP_FORPREP = 32; /* A sBx R(A)-=R(A+2); pc+=sBx */
public static final int OP_TFORLOOP = 33; /* A C R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2));
if R(A+3) ~= nil then R(A+2)=R(A+3) else pc++ */
public static final int OP_SETLIST = 34; /* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */
public static final int OP_CLOSE = 35; /* A close all variables in the stack up to (>=) R(A)*/
public static final int OP_CLOSURE = 36; /* A Bx R(A) := closure(KPROTO[Bx], R(A), ... ,R(A+n)) */
public static final int OP_VARARG = 37; /* A B R(A), R(A+1), ..., R(A+B-1) = vararg */
public static final int NUM_OPCODES = OP_VARARG + 1;
/*===========================================================================
Notes:
(*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1,
and can be 0: OP_CALL then sets `top' to last_result+1, so
next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use `top'.
(*) In OP_VARARG, if (B == 0) then use actual number of varargs and
set top (like in OP_CALL with C == 0).
(*) In OP_RETURN, if (B == 0) then return up to `top'
(*) In OP_SETLIST, if (B == 0) then B = `top';
if (C == 0) then next `instruction' is real C
(*) For comparisons, A specifies what condition the test should accept
(true or false).
(*) All `skips' (pc++) assume that next instruction is a jump
===========================================================================*/
/*
** masks for instruction properties. The format is:
** bits 0-1: op mode
** bits 2-3: C arg mode
** bits 4-5: B arg mode
** bit 6: instruction set register A
** bit 7: operator is a test
*/
public static final int OpArgN = 0; /* argument is not used */
public static final int OpArgU = 1; /* argument is used */
public static final int OpArgR = 2; /* argument is a register or a jump offset */
public static final int OpArgK = 3; /* argument is a constant or register/constant */
public static final int[] luaP_opmodes = {
/* T A B C mode opcode */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_MOVE */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgN<<2) | (iABx), /* OP_LOADK */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_LOADBOOL */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_LOADNIL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_GETUPVAL */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgN<<2) | (iABx), /* OP_GETGLOBAL */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgK<<2) | (iABC), /* OP_GETTABLE */
(0<<7) | (0<<6) | (OpArgK<<4) | (OpArgN<<2) | (iABx), /* OP_SETGLOBAL */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_SETUPVAL */
(0<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SETTABLE */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_NEWTABLE */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgK<<2) | (iABC), /* OP_SELF */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_ADD */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_SUB */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_MUL */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_DIV */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_MOD */
(0<<7) | (1<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_POW */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_UNM */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_NOT */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iABC), /* OP_LEN */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgR<<2) | (iABC), /* OP_CONCAT */
(0<<7) | (0<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_JMP */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_EQ */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_LT */
(1<<7) | (0<<6) | (OpArgK<<4) | (OpArgK<<2) | (iABC), /* OP_LE */
(1<<7) | (1<<6) | (OpArgR<<4) | (OpArgU<<2) | (iABC), /* OP_TEST */
(1<<7) | (1<<6) | (OpArgR<<4) | (OpArgU<<2) | (iABC), /* OP_TESTSET */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_CALL */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_TAILCALL */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_RETURN */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_FORLOOP */
(0<<7) | (1<<6) | (OpArgR<<4) | (OpArgN<<2) | (iAsBx), /* OP_FORPREP */
(1<<7) | (0<<6) | (OpArgN<<4) | (OpArgU<<2) | (iABC), /* OP_TFORLOOP */
(0<<7) | (0<<6) | (OpArgU<<4) | (OpArgU<<2) | (iABC), /* OP_SETLIST */
(0<<7) | (0<<6) | (OpArgN<<4) | (OpArgN<<2) | (iABC), /* OP_CLOSE */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABx), /* OP_CLOSURE */
(0<<7) | (1<<6) | (OpArgU<<4) | (OpArgN<<2) | (iABC), /* OP_VARARG */
};
public static int getOpMode(int m) {
return luaP_opmodes[m] & 3;
}
public static int getBMode(int m) {
return (luaP_opmodes[m] >> 4) & 3;
}
public static int getCMode(int m) {
return (luaP_opmodes[m] >> 2) & 3;
}
public static boolean testAMode(int m) {
return 0 != (luaP_opmodes[m] & (1 << 6));
}
public static boolean testTMode(int m) {
return 0 != (luaP_opmodes[m] & (1 << 7));
}
/** opcode names */
public static final String[] luaP_opnames = {
"MOVE",
"LOADK",
"LOADBOOL",
"LOADNIL",
"GETUPVAL",
"GETGLOBAL",
"GETTABLE",
"SETGLOBAL",
"SETUPVAL",
"SETTABLE",
"NEWTABLE",
"SELF",
"ADD",
"SUB",
"MUL",
"DIV",
"MOD",
"POW",
"UNM",
"NOT",
"LEN",
"CONCAT",
"JMP",
"EQ",
"LT",
"LE",
"TEST",
"TESTSET",
"CALL",
"TAILCALL",
"RETURN",
"FORLOOP",
"FORPREP",
"TFORLOOP",
"SETLIST",
"CLOSE",
"CLOSURE",
"VARARG",
null,
};
/** number of list items to accumulate before a SETLIST instruction */
public static final int LFIELDS_PER_FLUSH = 50;
}
| Move LUA_MULTRET def to Lua.java
| src/main/java/lua/Lua.java | Move LUA_MULTRET def to Lua.java | <ide><path>rc/main/java/lua/Lua.java
<ide>
<ide> /** minimum size for string buffer */
<ide> public static final int LUA_MINBUFFER = 32;
<add>
<add> /** use return values from previous op */
<add> public static final int LUA_MULTRET = -1;
<ide>
<ide>
<ide> // from lopcodes.h
<ide> null,
<ide> };
<ide>
<del>
<del> /** number of list items to accumulate before a SETLIST instruction */
<del> public static final int LFIELDS_PER_FLUSH = 50;
<del>
<ide> } |
|
Java | mit | 7f2ab8ac4a47ab22db0a0e9bee6bf81a42faf859 | 0 | nking/curvature-scale-space-corners-and-transformations,nking/curvature-scale-space-corners-and-transformations | package algorithms.imageProcessing;
import algorithms.compGeometry.clustering.KMeansPlusPlus;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
*
* @author nichole
*/
public class ImageProcesser {
protected Logger log = Logger.getLogger(this.getClass().getName());
public void applySobelKernel(Image input) {
IKernel kernel = new SobelX();
Kernel kernelX = kernel.getKernel();
float normX = kernel.getNormalizationFactor();
kernel = new SobelY();
Kernel kernelY = kernel.getKernel();
float normY = kernel.getNormalizationFactor();
applyKernels(input, kernelX, kernelY, normX, normY);
}
protected void applyKernels(Image input, Kernel kernelX, Kernel kernelY,
float normFactorX, float normFactorY) {
/*
assumes that kernelX is applied to a copy of the img
and kernelY is applied to a separate copy of the img and
then they are added in quadrature for the final result.
*/
Image imgX = input.copyImage();
Image imgY = input.copyImage();
applyKernel(imgX, kernelX, normFactorX);
applyKernel(imgY, kernelY, normFactorY);
Image img2 = combineConvolvedImages(imgX, imgY);
input.resetTo(img2);
}
public Image combineConvolvedImages(Image imageX, Image imageY) {
Image img2 = new Image(imageX.getWidth(), imageX.getHeight());
for (int i = 0; i < imageX.getWidth(); i++) {
for (int j = 0; j < imageX.getHeight(); j++) {
int rX = imageX.getR(i, j);
int gX = imageX.getG(i, j);
int bX = imageX.getB(i, j);
int rY = imageY.getR(i, j);
int gY = imageY.getG(i, j);
int bY = imageY.getB(i, j);
double r = Math.sqrt(rX*rX + rY*rY);
double g = Math.sqrt(gX*gX + gY*gY);
double b = Math.sqrt(bX*bX + bY*bY);
r = (r > 255) ? 255 : r;
g = (g > 255) ? 255 : g;
b = (b > 255) ? 255 : b;
//int rgb = (int)(((rSum & 0x0ff) << 16)
// | ((gSum & 0x0ff) << 8) | (bSum & 0x0ff));
img2.setRGB(i, j, (int)r, (int)g, (int)b);
}
}
return img2;
}
/**
* process only the green channel and set red and blue to zero
* @param imageX
* @param imageY
* @return
*/
public GreyscaleImage combineConvolvedImages(final GreyscaleImage imageX,
final GreyscaleImage imageY) {
GreyscaleImage img2 = new GreyscaleImage(imageX.getWidth(), imageX.getHeight());
for (int i = 0; i < imageX.getWidth(); i++) {
for (int j = 0; j < imageX.getHeight(); j++) {
int gX = imageX.getValue(i, j);
int gY = imageY.getValue(i, j);
//double g = Math.sqrt(0.5*(gX*gX + gY*gY));
//g = (g > 255) ? 255 : g;
double g = Math.sqrt(gX*gX + gY*gY);
if (g > 255) {
g = 255;
}
//int rgb = (int)(((rSum & 0x0ff) << 16)
// | ((gSum & 0x0ff) << 8) | (bSum & 0x0ff));
img2.setValue(i, j, (int)g);
}
}
return img2;
}
/**
* apply kernel to input. NOTE, that because the image is composed of vectors
* that should have values between 0 and 255, inclusive, if the kernel application
* results in a value outside of that range, the value is reset to 0 or
* 255.
* @param input
* @param kernel
* @param normFactor
*/
protected void applyKernel(Image input, Kernel kernel, float normFactor) {
int h = (kernel.getWidth() - 1) >> 1;
Image output = new Image(input.getWidth(), input.getHeight());
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
long rValue = 0;
long gValue = 0;
long bValue = 0;
// apply the kernel to pixels centered in (i, j)
for (int col = 0; col < kernel.getWidth(); col++) {
int x = col - h;
int imgX = i + x;
// edge corrections. use replication
if (imgX < 0) {
imgX = -1 * imgX - 1;
} else if (imgX >= input.getWidth()) {
int diff = imgX - input.getWidth();
imgX = input.getWidth() - diff - 1;
}
for (int row = 0; row < kernel.getHeight(); row++) {
int y = row - h;
int imgY = j + y;
// edge corrections. use replication
if (imgY < 0) {
imgY = -1 * imgY - 1;
} else if (imgY >= input.getHeight()) {
int diff = imgY - input.getHeight();
imgY = input.getHeight() - diff - 1;
}
int rPixel = input.getR(imgX, imgY);
int gPixel = input.getG(imgX, imgY);
int bPixel = input.getB(imgX, imgY);
int k = kernel.getValue(col, row);
rValue += k * rPixel;
gValue += k * gPixel;
bValue += k * bPixel;
}
}
rValue *= normFactor;
gValue *= normFactor;
bValue *= normFactor;
/*
if ((rValue > 255) || (rValue < 0)) {
throw new IllegalStateException("rValue is " + rValue);
}
if ((gValue > 255) || (gValue < 0)) {
throw new IllegalStateException("gValue is " + gValue);
}
if ((bValue > 255) || (bValue < 0)) {
throw new IllegalStateException("bValue is " + bValue);
}*/
if (rValue < 0) {
rValue = 0;
}
if (rValue > 255) {
rValue = 255;
}
if (gValue < 0) {
gValue = 0;
}
if (gValue > 255) {
gValue = 255;
}
if (bValue < 0) {
bValue = 0;
}
if (bValue > 255) {
bValue = 255;
}
output.setRGB(i, j, (int)rValue, (int)gValue, (int)bValue);
}
}
input.resetTo(output);
}
public Image computeTheta(Image convolvedX, Image convolvedY) {
Image output = new Image(convolvedX.getWidth(), convolvedX.getHeight());
for (int i = 0; i < convolvedX.getWidth(); i++) {
for (int j = 0; j < convolvedX.getHeight(); j++) {
double rX = convolvedX.getR(i, j);
double gX = convolvedX.getG(i, j);
double bX = convolvedX.getB(i, j);
double rY = convolvedY.getR(i, j);
double gY = convolvedY.getG(i, j);
double bY = convolvedY.getB(i, j);
int thetaR = calculateTheta(rX, rY);
int thetaG = calculateTheta(gX, gY);
int thetaB = calculateTheta(bX, bY);
output.setRGB(i, j, thetaR, thetaG, thetaB);
}
}
return output;
}
public GreyscaleImage computeTheta(final GreyscaleImage convolvedX,
final GreyscaleImage convolvedY) {
GreyscaleImage output = new GreyscaleImage(convolvedX.getWidth(),
convolvedX.getHeight());
for (int i = 0; i < convolvedX.getWidth(); i++) {
for (int j = 0; j < convolvedX.getHeight(); j++) {
double gX = convolvedX.getValue(i, j);
double gY = convolvedY.getValue(i, j);
int thetaG = calculateTheta(gX, gY);
output.setValue(i, j, thetaG);
}
}
return output;
}
public GreyscaleImage subtractImages(final GreyscaleImage image,
final GreyscaleImage subtrImage) {
if (image.getWidth() != subtrImage.getWidth()) {
throw new IllegalArgumentException("image widths must be the same");
}
if (image.getHeight() != subtrImage.getHeight()) {
throw new IllegalArgumentException("image heights must be the same");
}
GreyscaleImage output = new GreyscaleImage(image.getWidth(), image.getHeight());
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
int diff = image.getValue(i, j) - subtrImage.getValue(i, j);
output.setValue(i, j, diff);
}
}
return output;
}
protected int calculateTheta(double gradientX, double gradientY) {
/* -45 90 45 y/x
- | +
0 -----|----- 0
+ | -
45 90 -45
when X is 0: if Y > 0, theta is 90
when Y is 0: if X >= 0, theta is 0
*/
if (gradientX == 0 && (gradientY != 0)) {
return 90;
}
if (gradientY == 0) {
return 0;
}
double div = gradientY/gradientX;
double theta = Math.atan(div)*180./Math.PI;
int angle = (int)theta;
// +x, +y -> +
// -x, +y -> -
// -x, -y -> +
// +x, -y -> -
if (!(gradientX < 0) && !(gradientY < 0)) {
if (angle < 0) {
// make it positive if negative
angle *= -1;
}
} else if ((gradientX < 0) && !(gradientY < 0)) {
if (!(angle < 0)) {
// make it negative if it's not
angle *= -1;
}
} else if ((gradientX < 0) && (gradientY < 0)) {
if (angle < 0) {
// make it positive if negative
angle *= -1;
}
} else if (!(gradientX < 0) && (gradientY < 0)) {
if (!(angle < 0)) {
// make it negative if it's not
angle *= -1;
}
}
return angle;
}
/**
* images bounded by zero's have to be shrunk to the columns and rows
* of the first non-zeroes in order to keep the lines that should be
* attached to the image edges from eroding completely.
*
* @param input
* @return
*/
public int[] shrinkImageToFirstNonZeros(final GreyscaleImage input) {
int xNZFirst = -1;
int xNZLast = -1;
int yNZFirst = -1;
int yNZLast = -1;
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
int pixValue = input.getValue(i, j);
if (pixValue > 0) {
xNZFirst = i;
break;
}
}
if (xNZFirst > -1) {
break;
}
}
for (int j = 0; j < input.getHeight(); j++) {
for (int i = 0; i < input.getWidth(); i++) {
int pixValue = input.getValue(i, j);
if (pixValue > 0) {
yNZFirst = j;
break;
}
}
if (yNZFirst > -1) {
break;
}
}
for (int i = (input.getWidth() - 1); i > -1; i--) {
for (int j = (input.getHeight() - 1); j > -1; j--) {
if (input.getValue(i, j) > 0) {
xNZLast = i;
break;
}
}
if (xNZLast > -1) {
break;
}
}
for (int j = (input.getHeight() - 1); j > -1; j--) {
for (int i = (input.getWidth() - 1); i > -1; i--) {
int pixValue = input.getValue(i, j);
if (pixValue > 0) {
yNZLast = j;
break;
}
}
if (yNZLast > -1) {
break;
}
}
if ((xNZFirst > 0) || (xNZLast < (input.getWidth() - 1))
|| (yNZFirst > 0) || (yNZLast < (input.getHeight() - 1))) {
//add a 2 pix border
xNZFirst -= 2;
yNZFirst -= 2;
if (xNZFirst < 0) {
xNZFirst = 0;
}
if (yNZFirst < 0) {
yNZFirst = 0;
}
if (xNZLast == -1) {
xNZLast = input.getWidth() - 1;
} else if (xNZLast < (input.getWidth() - 2)) {
// add a 1 pix border
xNZLast += 2;
} else if (xNZLast < (input.getWidth() - 1)) {
// add a 1 pix border
xNZLast++;
}
if (yNZLast == -1) {
yNZLast = input.getHeight() - 1;
} else if (yNZLast < (input.getHeight() - 2)) {
// add a 1 pix border
yNZLast += 2;
} else if (yNZLast < (input.getHeight() - 1)) {
// add a 1 pix border
yNZLast++;
}
int xLen = xNZLast - xNZFirst + 1;
int yLen = yNZLast - yNZFirst + 1;
GreyscaleImage output = new GreyscaleImage(xLen, yLen);
for (int i = xNZFirst; i <= xNZLast; i++) {
int iIdx = i - xNZFirst;
for (int j = yNZFirst; j <= yNZLast; j++) {
int jIdx = j - yNZFirst;
output.setValue(iIdx, jIdx, input.getValue(i, j));
}
}
input.resetTo(output);
return new int[]{xNZFirst, yNZFirst};
}
return new int[]{0, 0};
}
public void applyImageSegmentation(GreyscaleImage input, int kBands)
throws IOException, NoSuchAlgorithmException {
KMeansPlusPlus instance = new KMeansPlusPlus();
instance.computeMeans(kBands, input);
int[] binCenters = instance.getCenters();
for (int col = 0; col < input.getWidth(); col++) {
for (int row = 0; row < input.getHeight(); row++) {
int v = input.getValue(col, row);
for (int i = 0; i < binCenters.length; i++) {
int vc = binCenters[i];
int bisectorBelow = ((i - 1) > -1) ?
((binCenters[i - 1] + vc) / 2) : 0;
int bisectorAbove = ((i + 1) > (binCenters.length - 1)) ?
255 : ((binCenters[i + 1] + vc) / 2);
if ((v >= bisectorBelow) && (v <= bisectorAbove)) {
input.setValue(col, row, vc);
break;
}
}
}
}
}
public void applyImageSegmentationForSky(GreyscaleImage input,
GreyscaleImage theta) throws IOException, NoSuchAlgorithmException {
/*
this needs a dfs type algorithm to find contiguous '0' pixels in
the theta image, determine bounds of the region, and set all pixels
within the bounds to '0's too.
for the DFS portion I wrote group finding code in another project:
https://two-point-correlation.googlecode.com/git/docs/dfs.png
https://code.google.com/p/two-point-correlation/source/browse/src/main/java/algorithms/compGeometry/clustering/twopointcorrelation/DFSGroupFinder.java
----------------------------------------------------------------
the algorithm:
responsibilities:
the algorithm should determine sky in the input image and turn all
pixels within the sky to zero in the input image. the theta image
should be the gradient theta image created by the canny edge filter
used in 'outdoorMode' for best results.
(when a blur is not used, the gradient theta image has alot of
structure in sky, but too much blur will move the boundary of the
sky.)
rough design:
N is the number of pixels in input.
N_groups is the number of groups of contiguous pixels of values '0'.
N_0 is number of pixels within largest '0' group.
N_H is the number of points in the largest group '0' hull.
-- ~O(N^2)
from theta, return all groups of contiguous regions
that have value 0. (might change that to allow a given value).
This is a DFS style algorithm that should be similar to the
DFSGroupFinder mentioned above.
The data structures for the 'group' and the index information
will be re-written here for use with GreyScaleImage.
-- O(N_groups) or O(N_groups * lg(N_groups).
given groups of contiguous '0' value pixels,
choose the largest group or largest groups if the sizes of the
top are very close.
for all points within the boundaries of the largest '0' group(s)
we want to set those to '0's too.
(this is easily done by the erosion filter I have, except
that it's setup to only work on an entire image).
so to make the image to apply the erosion filter to:
convex hull is fast approx of the '0' group(s) boundaries,
but the convexity means that it may include positive pixels
from non-sky areas between hull points.
-- O(N) + O(N_0 lg(N_0)) + O(N)*O(N_H)
create an empty image and turn all points outside
of the convex hull to '1's.
then copy all pixels of input image from within the bounds of
the convex hull into the new image.
(making the values binary, that is, anything > 0 gets a '1')
** for points that are within the hull between 2 points'
bounds specifically, do not copy those points. that should
help exclude copying the positive features under the sky
(those would subsequently be eroded away)
-- O(estimate the runtime for ErosionFilter.java...).
then can apply the erosion filter to the new image.
--> assert that the result is a binary image of sky as '0's
and all else is '1's
this is now a mask for the sky.
-- O(N)
one can multiply the input image by the new mask. subsequent
operations such as an edge detection should find horizon
features more easily afterwards.
data structures:
need to decide whether to use the smaller memory data structures of
the code in the other project or use java structures here.
The number of pixels in images may be very large, so it's worth the
effort to use small memory structures here.
the dfs zero pixel finder:
*/
throw new UnsupportedOperationException("not implemented yet");
}
public void multiply(GreyscaleImage input, float m) throws IOException,
NoSuchAlgorithmException {
for (int col = 0; col < input.getWidth(); col++) {
for (int row = 0; row < input.getHeight(); row++) {
int v = input.getValue(col, row);
int f = (int)(m * v);
input.setValue(col, row, f);
}
}
}
public void blur(GreyscaleImage input, float sigma) {
float[] kernel = Gaussian1D.getKernel(sigma);
Kernel1DHelper kernel1DHelper = new Kernel1DHelper();
GreyscaleImage output = new GreyscaleImage(input.getWidth(),
input.getHeight());
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
double conv = kernel1DHelper.convolvePointWithKernel(
input, i, j, kernel, true);
int g = (int) conv;
output.setValue(i, j, g);
}
}
input.resetTo(output);
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
double conv = kernel1DHelper.convolvePointWithKernel(
input, i, j, kernel, false);
int g = (int) conv;
output.setValue(i, j, g);
}
}
input.resetTo(output);
}
public void divideByBlurredSelf(GreyscaleImage input, float sigma) {
GreyscaleImage input2 = input.copyImage();
blur(input, sigma);
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
int v = input.getValue(i, j);
int vorig = input2.getValue(i, j);
if (v != 0) {
float r = (float)vorig/(float)v;
if ((i==250) && (j >= 50) && (j <= 150)) {
log.info(Float.toString(r));
}
input.setValue(i, j, (int)(100*r));
}
}
}
}
}
| src/algorithms/imageProcessing/ImageProcesser.java | package algorithms.imageProcessing;
import algorithms.compGeometry.clustering.KMeansPlusPlus;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
*
* @author nichole
*/
public class ImageProcesser {
protected Logger log = Logger.getLogger(this.getClass().getName());
public void applySobelKernel(Image input) {
IKernel kernel = new SobelX();
Kernel kernelX = kernel.getKernel();
float normX = kernel.getNormalizationFactor();
kernel = new SobelY();
Kernel kernelY = kernel.getKernel();
float normY = kernel.getNormalizationFactor();
applyKernels(input, kernelX, kernelY, normX, normY);
}
protected void applyKernels(Image input, Kernel kernelX, Kernel kernelY,
float normFactorX, float normFactorY) {
/*
assumes that kernelX is applied to a copy of the img
and kernelY is applied to a separate copy of the img and
then they are added in quadrature for the final result.
*/
Image imgX = input.copyImage();
Image imgY = input.copyImage();
applyKernel(imgX, kernelX, normFactorX);
applyKernel(imgY, kernelY, normFactorY);
Image img2 = combineConvolvedImages(imgX, imgY);
input.resetTo(img2);
}
public Image combineConvolvedImages(Image imageX, Image imageY) {
Image img2 = new Image(imageX.getWidth(), imageX.getHeight());
for (int i = 0; i < imageX.getWidth(); i++) {
for (int j = 0; j < imageX.getHeight(); j++) {
int rX = imageX.getR(i, j);
int gX = imageX.getG(i, j);
int bX = imageX.getB(i, j);
int rY = imageY.getR(i, j);
int gY = imageY.getG(i, j);
int bY = imageY.getB(i, j);
double r = Math.sqrt(rX*rX + rY*rY);
double g = Math.sqrt(gX*gX + gY*gY);
double b = Math.sqrt(bX*bX + bY*bY);
r = (r > 255) ? 255 : r;
g = (g > 255) ? 255 : g;
b = (b > 255) ? 255 : b;
//int rgb = (int)(((rSum & 0x0ff) << 16)
// | ((gSum & 0x0ff) << 8) | (bSum & 0x0ff));
img2.setRGB(i, j, (int)r, (int)g, (int)b);
}
}
return img2;
}
/**
* process only the green channel and set red and blue to zero
* @param imageX
* @param imageY
* @return
*/
public GreyscaleImage combineConvolvedImages(final GreyscaleImage imageX,
final GreyscaleImage imageY) {
GreyscaleImage img2 = new GreyscaleImage(imageX.getWidth(), imageX.getHeight());
for (int i = 0; i < imageX.getWidth(); i++) {
for (int j = 0; j < imageX.getHeight(); j++) {
int gX = imageX.getValue(i, j);
int gY = imageY.getValue(i, j);
//double g = Math.sqrt(0.5*(gX*gX + gY*gY));
//g = (g > 255) ? 255 : g;
double g = Math.sqrt(gX*gX + gY*gY);
if (g > 255) {
g = 255;
}
//int rgb = (int)(((rSum & 0x0ff) << 16)
// | ((gSum & 0x0ff) << 8) | (bSum & 0x0ff));
img2.setValue(i, j, (int)g);
}
}
return img2;
}
/**
* apply kernel to input. NOTE, that because the image is composed of vectors
* that should have values between 0 and 255, inclusive, if the kernel application
* results in a value outside of that range, the value is reset to 0 or
* 255.
* @param input
* @param kernel
* @param normFactor
*/
protected void applyKernel(Image input, Kernel kernel, float normFactor) {
int h = (kernel.getWidth() - 1) >> 1;
Image output = new Image(input.getWidth(), input.getHeight());
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
long rValue = 0;
long gValue = 0;
long bValue = 0;
// apply the kernel to pixels centered in (i, j)
for (int col = 0; col < kernel.getWidth(); col++) {
int x = col - h;
int imgX = i + x;
// edge corrections. use replication
if (imgX < 0) {
imgX = -1 * imgX - 1;
} else if (imgX >= input.getWidth()) {
int diff = imgX - input.getWidth();
imgX = input.getWidth() - diff - 1;
}
for (int row = 0; row < kernel.getHeight(); row++) {
int y = row - h;
int imgY = j + y;
// edge corrections. use replication
if (imgY < 0) {
imgY = -1 * imgY - 1;
} else if (imgY >= input.getHeight()) {
int diff = imgY - input.getHeight();
imgY = input.getHeight() - diff - 1;
}
int rPixel = input.getR(imgX, imgY);
int gPixel = input.getG(imgX, imgY);
int bPixel = input.getB(imgX, imgY);
int k = kernel.getValue(col, row);
rValue += k * rPixel;
gValue += k * gPixel;
bValue += k * bPixel;
}
}
rValue *= normFactor;
gValue *= normFactor;
bValue *= normFactor;
/*
if ((rValue > 255) || (rValue < 0)) {
throw new IllegalStateException("rValue is " + rValue);
}
if ((gValue > 255) || (gValue < 0)) {
throw new IllegalStateException("gValue is " + gValue);
}
if ((bValue > 255) || (bValue < 0)) {
throw new IllegalStateException("bValue is " + bValue);
}*/
if (rValue < 0) {
rValue = 0;
}
if (rValue > 255) {
rValue = 255;
}
if (gValue < 0) {
gValue = 0;
}
if (gValue > 255) {
gValue = 255;
}
if (bValue < 0) {
bValue = 0;
}
if (bValue > 255) {
bValue = 255;
}
output.setRGB(i, j, (int)rValue, (int)gValue, (int)bValue);
}
}
input.resetTo(output);
}
public Image computeTheta(Image convolvedX, Image convolvedY) {
Image output = new Image(convolvedX.getWidth(), convolvedX.getHeight());
for (int i = 0; i < convolvedX.getWidth(); i++) {
for (int j = 0; j < convolvedX.getHeight(); j++) {
double rX = convolvedX.getR(i, j);
double gX = convolvedX.getG(i, j);
double bX = convolvedX.getB(i, j);
double rY = convolvedY.getR(i, j);
double gY = convolvedY.getG(i, j);
double bY = convolvedY.getB(i, j);
int thetaR = calculateTheta(rX, rY);
int thetaG = calculateTheta(gX, gY);
int thetaB = calculateTheta(bX, bY);
output.setRGB(i, j, thetaR, thetaG, thetaB);
}
}
return output;
}
public GreyscaleImage computeTheta(final GreyscaleImage convolvedX,
final GreyscaleImage convolvedY) {
GreyscaleImage output = new GreyscaleImage(convolvedX.getWidth(),
convolvedX.getHeight());
for (int i = 0; i < convolvedX.getWidth(); i++) {
for (int j = 0; j < convolvedX.getHeight(); j++) {
double gX = convolvedX.getValue(i, j);
double gY = convolvedY.getValue(i, j);
int thetaG = calculateTheta(gX, gY);
output.setValue(i, j, thetaG);
}
}
return output;
}
public GreyscaleImage subtractImages(final GreyscaleImage image,
final GreyscaleImage subtrImage) {
if (image.getWidth() != subtrImage.getWidth()) {
throw new IllegalArgumentException("image widths must be the same");
}
if (image.getHeight() != subtrImage.getHeight()) {
throw new IllegalArgumentException("image heights must be the same");
}
GreyscaleImage output = new GreyscaleImage(image.getWidth(), image.getHeight());
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
int diff = image.getValue(i, j) - subtrImage.getValue(i, j);
output.setValue(i, j, diff);
}
}
return output;
}
protected int calculateTheta(double gradientX, double gradientY) {
/* -45 90 45 y/x
- | +
0 -----|----- 0
+ | -
45 90 -45
when X is 0: if Y > 0, theta is 90
when Y is 0: if X >= 0, theta is 0
*/
if (gradientX == 0 && (gradientY != 0)) {
return 90;
}
if (gradientY == 0) {
return 0;
}
double div = gradientY/gradientX;
double theta = Math.atan(div)*180./Math.PI;
int angle = (int)theta;
// +x, +y -> +
// -x, +y -> -
// -x, -y -> +
// +x, -y -> -
if (!(gradientX < 0) && !(gradientY < 0)) {
if (angle < 0) {
// make it positive if negative
angle *= -1;
}
} else if ((gradientX < 0) && !(gradientY < 0)) {
if (!(angle < 0)) {
// make it negative if it's not
angle *= -1;
}
} else if ((gradientX < 0) && (gradientY < 0)) {
if (angle < 0) {
// make it positive if negative
angle *= -1;
}
} else if (!(gradientX < 0) && (gradientY < 0)) {
if (!(angle < 0)) {
// make it negative if it's not
angle *= -1;
}
}
return angle;
}
/**
* images bounded by zero's have to be shrunk to the columns and rows
* of the first non-zeroes in order to keep the lines that should be
* attached to the image edges from eroding completely.
*
* @param input
* @return
*/
public int[] shrinkImageToFirstNonZeros(final GreyscaleImage input) {
int xNZFirst = -1;
int xNZLast = -1;
int yNZFirst = -1;
int yNZLast = -1;
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
int pixValue = input.getValue(i, j);
if (pixValue > 0) {
xNZFirst = i;
break;
}
}
if (xNZFirst > -1) {
break;
}
}
for (int j = 0; j < input.getHeight(); j++) {
for (int i = 0; i < input.getWidth(); i++) {
int pixValue = input.getValue(i, j);
if (pixValue > 0) {
yNZFirst = j;
break;
}
}
if (yNZFirst > -1) {
break;
}
}
for (int i = (input.getWidth() - 1); i > -1; i--) {
for (int j = (input.getHeight() - 1); j > -1; j--) {
if (input.getValue(i, j) > 0) {
xNZLast = i;
break;
}
}
if (xNZLast > -1) {
break;
}
}
for (int j = (input.getHeight() - 1); j > -1; j--) {
for (int i = (input.getWidth() - 1); i > -1; i--) {
int pixValue = input.getValue(i, j);
if (pixValue > 0) {
yNZLast = j;
break;
}
}
if (yNZLast > -1) {
break;
}
}
if ((xNZFirst > 0) || (xNZLast < (input.getWidth() - 1))
|| (yNZFirst > 0) || (yNZLast < (input.getHeight() - 1))) {
//add a 2 pix border
xNZFirst -= 2;
yNZFirst -= 2;
if (xNZFirst < 0) {
xNZFirst = 0;
}
if (yNZFirst < 0) {
yNZFirst = 0;
}
if (xNZLast == -1) {
xNZLast = input.getWidth() - 1;
} else if (xNZLast < (input.getWidth() - 2)) {
// add a 1 pix border
xNZLast += 2;
} else if (xNZLast < (input.getWidth() - 1)) {
// add a 1 pix border
xNZLast++;
}
if (yNZLast == -1) {
yNZLast = input.getHeight() - 1;
} else if (yNZLast < (input.getHeight() - 2)) {
// add a 1 pix border
yNZLast += 2;
} else if (yNZLast < (input.getHeight() - 1)) {
// add a 1 pix border
yNZLast++;
}
int xLen = xNZLast - xNZFirst + 1;
int yLen = yNZLast - yNZFirst + 1;
GreyscaleImage output = new GreyscaleImage(xLen, yLen);
for (int i = xNZFirst; i <= xNZLast; i++) {
int iIdx = i - xNZFirst;
for (int j = yNZFirst; j <= yNZLast; j++) {
int jIdx = j - yNZFirst;
output.setValue(iIdx, jIdx, input.getValue(i, j));
}
}
input.resetTo(output);
return new int[]{xNZFirst, yNZFirst};
}
return new int[]{0, 0};
}
public void applyImageSegmentation(GreyscaleImage input, int kBands)
throws IOException, NoSuchAlgorithmException {
KMeansPlusPlus instance = new KMeansPlusPlus();
instance.computeMeans(kBands, input);
int[] binCenters = instance.getCenters();
for (int col = 0; col < input.getWidth(); col++) {
for (int row = 0; row < input.getHeight(); row++) {
int v = input.getValue(col, row);
for (int i = 0; i < binCenters.length; i++) {
int vc = binCenters[i];
int bisectorBelow = ((i - 1) > -1) ?
((binCenters[i - 1] + vc) / 2) : 0;
int bisectorAbove = ((i + 1) > (binCenters.length - 1)) ?
255 : ((binCenters[i + 1] + vc) / 2);
if ((v >= bisectorBelow) && (v <= bisectorAbove)) {
input.setValue(col, row, vc);
break;
}
}
}
}
}
public void applyImageSegmentationForSky(GreyscaleImage input,
GreyscaleImage theta) throws IOException, NoSuchAlgorithmException {
/*
this needs a dfs type algorithm to find contiguous '0' pixels in
the theta image, determine bounds of the region, and set all pixels
within the bounds to '0's too.
for the DFS portion I wrote group finding code in another project:
https://two-point-correlation.googlecode.com/git/docs/dfs.png
https://code.google.com/p/two-point-correlation/source/browse/src/main/java/algorithms/compGeometry/clustering/twopointcorrelation/DFSGroupFinder.java
----------------------------------------------------------------
the algorithm:
responsibilities:
the algorithm should determine sky and turn all pixels within the sky
to zero in the input image. the input theta image should be the
gradient theta image created by the canny edge filter used in
'outdoorMode' for best results.
(when a blur is not used, the gradient theta image has alot of structure
in sky, but too much blur will move the boundary of the sky.)
rough design:
N is the number of pixels in input. N_0 is number of pixels within
largest '0' group. N_H is the number of points in the group '0' hull.
-- O(N)
copy the image theta to theta2
-- ~O(N^2)
on theta2, return all groups of contiguous regions
that have value 0. (might change that to allow a given value).
This is a DFS style algorithm that should be similar to the
DFSGroupFinder mentioned above.
The data structures for the 'group' and the index information
will be re-written here for use with GreyScaleImage.
-- given groups of contiguous '0' value pixels,
choose the largest group or largest groups if the sizes of the
top are very close.
for all points within the boundaries of the largest '0' group(s)
we want to set those to '0's too.
(this is easily done by the erosion filter I have, except
that it's setup to only work on an entire image).
so to make the image to apply the erosion filter to:
-- convex hull is fast approx of the '0' group(s) boundaries,
but the convexity
means that it may include positive pixels from non-sky areas
between hull points.
-- O(N) + O(N_0 lg(N_0)) + O(N)*O(N_H)
so to make an image that is the input to an erosion filter
would need to create an empty image and turn all points outside
of the convex hull to '1's.
then copy all pixels from within the bounds of
the convex hull into the new image.
(keep the values as binary, anything > 0 gets a '1')
** for points that are within the hull between 2 points
bounds specifically, do not copy those points. that should
help exclude copying the positive features under the sky
(those would subsequently be eroded away)
-- then can apply the erosion filter to the image.
--> assert that the result is a binary image of sky as '0's
and all else is '1's
-- this is now a mask for the sky.
-- O(N)
one can multiply the input image by the new mask. subsequent
operations such as an edge detector should find horizon
features more easily afterwards.
data structures:
need to decide whether to use the smaller memory data structures of the
code in the other project, or use java structures here.
The number of pixels in images may be very large, so it's worth the
effort to use small memory structures here.
the dfs zero pixel finder:
*/
throw new UnsupportedOperationException("not implemented yet");
}
public void multiply(GreyscaleImage input, float m) throws IOException,
NoSuchAlgorithmException {
for (int col = 0; col < input.getWidth(); col++) {
for (int row = 0; row < input.getHeight(); row++) {
int v = input.getValue(col, row);
int f = (int)(m * v);
input.setValue(col, row, f);
}
}
}
public void blur(GreyscaleImage input, float sigma) {
float[] kernel = Gaussian1D.getKernel(sigma);
Kernel1DHelper kernel1DHelper = new Kernel1DHelper();
GreyscaleImage output = new GreyscaleImage(input.getWidth(),
input.getHeight());
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
double conv = kernel1DHelper.convolvePointWithKernel(
input, i, j, kernel, true);
int g = (int) conv;
output.setValue(i, j, g);
}
}
input.resetTo(output);
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
double conv = kernel1DHelper.convolvePointWithKernel(
input, i, j, kernel, false);
int g = (int) conv;
output.setValue(i, j, g);
}
}
input.resetTo(output);
}
public void divideByBlurredSelf(GreyscaleImage input, float sigma) {
GreyscaleImage input2 = input.copyImage();
blur(input, sigma);
for (int i = 0; i < input.getWidth(); i++) {
for (int j = 0; j < input.getHeight(); j++) {
int v = input.getValue(i, j);
int vorig = input2.getValue(i, j);
if (v != 0) {
float r = (float)vorig/(float)v;
if ((i==250) && (j >= 50) && (j <= 150)) {
log.info(Float.toString(r));
}
input.setValue(i, j, (int)(100*r));
}
}
}
}
}
| more towards outline of the sky mask algorithm. | src/algorithms/imageProcessing/ImageProcesser.java | more towards outline of the sky mask algorithm. | <ide><path>rc/algorithms/imageProcessing/ImageProcesser.java
<ide>
<ide> responsibilities:
<ide>
<del> the algorithm should determine sky and turn all pixels within the sky
<del> to zero in the input image. the input theta image should be the
<del> gradient theta image created by the canny edge filter used in
<del> 'outdoorMode' for best results.
<del> (when a blur is not used, the gradient theta image has alot of structure
<del> in sky, but too much blur will move the boundary of the sky.)
<add> the algorithm should determine sky in the input image and turn all
<add> pixels within the sky to zero in the input image. the theta image
<add> should be the gradient theta image created by the canny edge filter
<add> used in 'outdoorMode' for best results.
<add> (when a blur is not used, the gradient theta image has alot of
<add> structure in sky, but too much blur will move the boundary of the
<add> sky.)
<ide>
<ide> rough design:
<del> N is the number of pixels in input. N_0 is number of pixels within
<del> largest '0' group. N_H is the number of points in the group '0' hull.
<del> -- O(N)
<del> copy the image theta to theta2
<add> N is the number of pixels in input.
<add> N_groups is the number of groups of contiguous pixels of values '0'.
<add> N_0 is number of pixels within largest '0' group.
<add> N_H is the number of points in the largest group '0' hull.
<ide> -- ~O(N^2)
<del> on theta2, return all groups of contiguous regions
<add> from theta, return all groups of contiguous regions
<ide> that have value 0. (might change that to allow a given value).
<ide> This is a DFS style algorithm that should be similar to the
<ide> DFSGroupFinder mentioned above.
<ide> The data structures for the 'group' and the index information
<ide> will be re-written here for use with GreyScaleImage.
<del> -- given groups of contiguous '0' value pixels,
<add> -- O(N_groups) or O(N_groups * lg(N_groups).
<add> given groups of contiguous '0' value pixels,
<ide> choose the largest group or largest groups if the sizes of the
<ide> top are very close.
<ide>
<ide> that it's setup to only work on an entire image).
<ide>
<ide> so to make the image to apply the erosion filter to:
<del> -- convex hull is fast approx of the '0' group(s) boundaries,
<del> but the convexity
<del> means that it may include positive pixels from non-sky areas
<del> between hull points.
<add> convex hull is fast approx of the '0' group(s) boundaries,
<add> but the convexity means that it may include positive pixels
<add> from non-sky areas between hull points.
<ide>
<ide> -- O(N) + O(N_0 lg(N_0)) + O(N)*O(N_H)
<del> so to make an image that is the input to an erosion filter
<del> would need to create an empty image and turn all points outside
<add> create an empty image and turn all points outside
<ide> of the convex hull to '1's.
<del> then copy all pixels from within the bounds of
<del> the convex hull into the new image.
<del> (keep the values as binary, anything > 0 gets a '1')
<del> ** for points that are within the hull between 2 points
<add> then copy all pixels of input image from within the bounds of
<add> the convex hull into the new image.
<add> (making the values binary, that is, anything > 0 gets a '1')
<add> ** for points that are within the hull between 2 points'
<ide> bounds specifically, do not copy those points. that should
<ide> help exclude copying the positive features under the sky
<ide> (those would subsequently be eroded away)
<ide>
<del> -- then can apply the erosion filter to the image.
<add> -- O(estimate the runtime for ErosionFilter.java...).
<add> then can apply the erosion filter to the new image.
<ide> --> assert that the result is a binary image of sky as '0's
<ide> and all else is '1's
<ide>
<del> -- this is now a mask for the sky.
<add> this is now a mask for the sky.
<ide>
<ide> -- O(N)
<ide> one can multiply the input image by the new mask. subsequent
<del> operations such as an edge detector should find horizon
<add> operations such as an edge detection should find horizon
<ide> features more easily afterwards.
<ide>
<ide> data structures:
<del> need to decide whether to use the smaller memory data structures of the
<del> code in the other project, or use java structures here.
<add> need to decide whether to use the smaller memory data structures of
<add> the code in the other project or use java structures here.
<ide> The number of pixels in images may be very large, so it's worth the
<ide> effort to use small memory structures here.
<ide> |
|
JavaScript | mit | b4d684fb56bc1877ef37bde06d2de142ca333a76 | 0 | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | import client from '@sanity/client'
import getUserConfig from './getUserConfig'
/**
* Creates a wrapper/getter function to retrieve a Sanity API client.
* Instead of spreading the error checking logic around the project,
* we call it here when (and only when) a command needs to use the API
*/
const defaults = {
requireUser: true,
requireProject: true
}
export default function clientWrapper(manifest, path) {
return function (opts = {}) {
const {requireUser, requireProject, api} = {...defaults, ...opts}
const userConfig = getUserConfig()
const userApiConf = userConfig.get('api')
const token = userConfig.get('authToken')
const apiConfig = api || (manifest && manifest.api) || userApiConf || {}
if (requireUser && !token) {
throw new Error('You must login first - run "sanity login"')
}
if (requireProject && !apiConfig.projectId) {
throw new Error(
`"${path}" does not contain a project identifier ("api.projectId"), `
+ 'which is required for the Sanity CLI to communicate with the Sanity API'
)
}
return client({
...apiConfig,
dataset: apiConfig.dataset || 'dummy',
token: token,
useProjectHostname: requireProject
})
}
}
| packages/@sanity/cli/src/util/clientWrapper.js | import client from '@sanity/client'
import getUserConfig from './getUserConfig'
/**
* Creates a wrapper/getter function to retrieve a Sanity API client.
* Instead of spreading the error checking logic around the project,
* we call it here when (and only when) a command needs to use the API
*/
const defaults = {
requireUser: true,
requireProject: true
}
export default function clientWrapper(manifest, path) {
return function (opts = {}) {
const {requireUser, requireProject, api} = {...defaults, ...opts}
const userConfig = getUserConfig()
const userApiConf = userConfig.get('api')
const token = userConfig.get('authToken')
const apiConfig = api || (manifest && manifest.api) || userApiConf || {}
if (requireUser && !token) {
throw new Error('You must login first')
}
if (requireProject && !apiConfig.projectId) {
throw new Error(
`"${path}" does not contain a project identifier ("api.projectId"), `
+ 'which is required for the Sanity CLI to communicate with the Sanity API'
)
}
return client({
...apiConfig,
dataset: apiConfig.dataset || 'dummy',
token: token,
useProjectHostname: requireProject
})
}
}
| Add a more helpful error when the user needs to login to perform an operation
| packages/@sanity/cli/src/util/clientWrapper.js | Add a more helpful error when the user needs to login to perform an operation | <ide><path>ackages/@sanity/cli/src/util/clientWrapper.js
<ide> const apiConfig = api || (manifest && manifest.api) || userApiConf || {}
<ide>
<ide> if (requireUser && !token) {
<del> throw new Error('You must login first')
<add> throw new Error('You must login first - run "sanity login"')
<ide> }
<ide>
<ide> if (requireProject && !apiConfig.projectId) { |
|
Java | epl-1.0 | error: pathspec 'src/main/java/com/kyloth/serleenacloud/persistence/IUserDao.java' did not match any file(s) known to git
| b9080fe3adf5bfd4362361ce1f4af12ee5eb82af | 1 | kyloth/serleena-cloud | /******************************************************************************
* Copyright (c) 2015 Nicola Mometto
* 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:
* Nicola Mometto
* Antonio Cavestro
* Sebastiano Valle
* Gabriele Pozzan
******************************************************************************/
package com.kyloth.serleenacloud.persistence;
import com.kyloth.serleenacloud.datamodel.auth.User;
public interface IUserDao {
public void persist(User token);
public User find(String email);
}
| src/main/java/com/kyloth/serleenacloud/persistence/IUserDao.java | PERSISTENCE: Aggiungi IWeatherDao
Related to: SHCLOUD-10
| src/main/java/com/kyloth/serleenacloud/persistence/IUserDao.java | PERSISTENCE: Aggiungi IWeatherDao | <ide><path>rc/main/java/com/kyloth/serleenacloud/persistence/IUserDao.java
<add>/******************************************************************************
<add>* Copyright (c) 2015 Nicola Mometto
<add>* All rights reserved. This program and the accompanying materials
<add>* are made available under the terms of the Eclipse Public License v1.0
<add>* which accompanies this distribution, and is available at
<add>* http://www.eclipse.org/legal/epl-v10.html
<add>*
<add>* Contributors:
<add>* Nicola Mometto
<add>* Antonio Cavestro
<add>* Sebastiano Valle
<add>* Gabriele Pozzan
<add>******************************************************************************/
<add>
<add>
<add>package com.kyloth.serleenacloud.persistence;
<add>
<add>import com.kyloth.serleenacloud.datamodel.auth.User;
<add>
<add>public interface IUserDao {
<add> public void persist(User token);
<add> public User find(String email);
<add>} |
|
Java | apache-2.0 | 2836c0e20a4269913d45ab35bb4ed6865fb63080 | 0 | prmsheriff/log4j,sreekanthpulagam/log4j,sreekanthpulagam/log4j,smathieu/librarian_sample_repo_java,MuShiiii/log4j,prmsheriff/log4j,sreekanthpulagam/log4j,qos-ch/reload4j,qos-ch/reload4j,prmsheriff/log4j,MuShiiii/log4j,MuShiiii/log4j,MuShiiii/log4j,qos-ch/reload4j,sreekanthpulagam/log4j,smathieu/librarian_sample_repo_java,prmsheriff/log4j,prmsheriff/log4j,MuShiiii/log4j,sreekanthpulagam/log4j | /*
* Copyright 1999,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.log4j.chainsaw;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StringReader;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.text.Document;
import org.apache.log4j.Layout;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.chainsaw.color.ColorPanel;
import org.apache.log4j.chainsaw.color.RuleColorizer;
import org.apache.log4j.chainsaw.filter.FilterModel;
import org.apache.log4j.chainsaw.icons.ChainsawIcons;
import org.apache.log4j.chainsaw.icons.LineIconFactory;
import org.apache.log4j.chainsaw.layout.DefaultLayoutFactory;
import org.apache.log4j.chainsaw.layout.EventDetailLayout;
import org.apache.log4j.chainsaw.layout.LayoutEditorPane;
import org.apache.log4j.chainsaw.messages.MessageCenter;
import org.apache.log4j.chainsaw.prefs.LoadSettingsEvent;
import org.apache.log4j.chainsaw.prefs.Profileable;
import org.apache.log4j.chainsaw.prefs.SaveSettingsEvent;
import org.apache.log4j.chainsaw.prefs.SettingsManager;
import org.apache.log4j.helpers.Constants;
import org.apache.log4j.helpers.ISO8601DateFormat;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.rule.ExpressionRule;
import org.apache.log4j.rule.ExpressionRuleContext;
import org.apache.log4j.rule.Rule;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.LoggingEventFieldResolver;
/**
* A LogPanel provides a view to a collection of LoggingEvents.<br>
* <br>
* As events are received, the keywords in the 'tab identifier' application
* preference are replaced with the values from the received event. The
* main application uses this expression to route received LoggingEvents to
* individual LogPanels which match each event's resolved expression.<br>
* <br>
* The LogPanel's capabilities can be broken up into four areas:<br>
* <ul><li> toolbar - provides 'find' and 'refine focus' features
* <li> logger tree - displays a tree of the logger hierarchy, which can be used
* to filter the display
* <li> table - displays the events which pass the filtering rules
* <li>detail panel - displays information about the currently selected event
* </ul>
* Here is a complete list of LogPanel's capabilities:<br>
* <ul><li>display selected LoggingEvent row number and total LoggingEvent count
* <li>pause or unpause reception of LoggingEvents
* <li>configure, load and save column settings (displayed columns, order, width)
* <li>configure, load and save color rules
* filter displayed LoggingEvents based on the logger tree settings
* <li>filter displayed LoggingEvents based on a 'refine focus' expression
* (evaluates only those LoggingEvents which pass the logger tree filter
* <li>colorize LoggingEvents based on expressions
* <li>hide, show and configure the detail pane and tooltip
* <li>configure the formatting of the logger, level and timestamp fields
* <li>dock or undock
* <li>table displays first line of exception, but when cell is clicked, a
* popup opens to display the full stack trace
* <li>find
* <li>scroll to bottom
* <li>sort
* <li>provide a context menu which can be used to build color or display expressions
* <li>hide or show the logger tree
* <li>toggle the container storing the LoggingEvents to use either a
* CyclicBuffer (defaults to max size of 5000, but configurable through
* CHAINSAW_CAPACITY system property) or ArrayList (no max size)
* <li>use the mouse context menu to 'best-fit' columns, define display
* expression filters based on mouse location and access other capabilities
*</ul>
*
*@see org.apache.log4j.chainsaw.color.ColorPanel
*@see org.apache.log4j.rule.ExpressionRule
*@see org.apache.log4j.spi.LoggingEventFieldResolver
*
*@author Scott Deboy (sdeboy at apache.org)
*@author Paul Smith (psmith at apache.org)
*@author Stephen Pain
*
*/
public class LogPanel extends DockablePanel implements EventBatchListener,
Profileable {
private static final double DEFAULT_DETAIL_SPLIT_LOCATION = .5;
private static final double DEFAULT_LOG_TREE_SPLIT_LOCATION = .25;
private final String identifier;
private final ChainsawStatusBar statusBar;
private final JFrame preferencesFrame = new JFrame();
private final JFrame colorFrame = new JFrame();
private final JFrame undockedFrame;
private final DockablePanel externalPanel;
private final Action dockingAction;
private final JToolBar undockedToolbar;
private final JSortTable table;
private final TableColorizingRenderer renderer;
private final EventContainer tableModel;
private final ThrowableRenderPanel throwableRenderPanel;
private final JEditorPane detail;
private final JSplitPane lowerPanel;
private final DetailPaneUpdater detailPaneUpdater;
private final JPanel detailPanel = new JPanel(new BorderLayout());
private final JSplitPane nameTreeAndMainPanelSplit;
private final LoggerNameTreePanel logTreePanel;
private final LogPanelPreferenceModel preferenceModel =
new LogPanelPreferenceModel();
private final LogPanelPreferencePanel preferencesPanel =
new LogPanelPreferencePanel(preferenceModel);
private final FilterModel filterModel = new FilterModel();
private final RuleColorizer colorizer = new RuleColorizer();
private final RuleMediator ruleMediator = new RuleMediator();
private Layout detailLayout = new EventDetailLayout();
private double lastDetailPanelSplitLocation = DEFAULT_DETAIL_SPLIT_LOCATION;
private double lastLogTreePanelSplitLocation =
DEFAULT_LOG_TREE_SPLIT_LOCATION;
private boolean bypassScrollFind;
private Point currentPoint;
private boolean scroll;
private boolean paused = false;
private Rule findRule;
private final JPanel findPanel;
private JTextField findField;
private int dividerSize;
static final String TABLE_COLUMN_ORDER = "table.columns.order";
static final String TABLE_COLUMN_WIDTHS = "table.columns.widths";
static final String COLUMNS_EXTENSION = ".columns";
static final String COLORS_EXTENSION = ".colors";
private int previousLastIndex = -1;
private final DateFormat timestampExpressionFormat = new SimpleDateFormat(Constants.TIMESTAMP_RULE_FORMAT);
/**
* Creates a new LogPanel object. If a LogPanel with this identifier has
* been loaded previously, reload settings saved on last exit.
*
* @param statusBar shared status bar, provided by main application
* @param identifier used to load and save settings
*/
public LogPanel(final ChainsawStatusBar statusBar, final String identifier, int cyclicBufferSize) {
this.identifier = identifier;
this.statusBar = statusBar;
setLayout(new BorderLayout());
scroll = true;
findPanel = new JPanel();
final Map columnNameKeywordMap = new HashMap();
columnNameKeywordMap.put(
ChainsawConstants.CLASS_COL_NAME, LoggingEventFieldResolver.CLASS_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.FILE_COL_NAME, LoggingEventFieldResolver.FILE_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.LEVEL_COL_NAME, LoggingEventFieldResolver.LEVEL_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.LINE_COL_NAME, LoggingEventFieldResolver.LINE_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.LOGGER_COL_NAME, LoggingEventFieldResolver.LOGGER_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.NDC_COL_NAME, LoggingEventFieldResolver.NDC_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.MESSAGE_COL_NAME, LoggingEventFieldResolver.MSG_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.THREAD_COL_NAME, LoggingEventFieldResolver.THREAD_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.THROWABLE_COL_NAME,
LoggingEventFieldResolver.EXCEPTION_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.TIMESTAMP_COL_NAME,
LoggingEventFieldResolver.TIMESTAMP_FIELD);
preferencesFrame.setTitle("'" + identifier + "' Log Panel Preferences");
preferencesFrame.setIconImage(
((ImageIcon) ChainsawIcons.ICON_PREFERENCES).getImage());
preferencesFrame.getContentPane().add(preferencesPanel);
preferencesFrame.setSize(640, 480);
preferencesPanel.setOkCancelActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
preferencesFrame.setVisible(false);
}
});
setDetailPaneConversionPattern(
DefaultLayoutFactory.getDefaultPatternLayout());
((EventDetailLayout) detailLayout).setConversionPattern(
DefaultLayoutFactory.getDefaultPatternLayout());
undockedFrame = new JFrame(identifier);
undockedFrame.setDefaultCloseOperation(
WindowConstants.DO_NOTHING_ON_CLOSE);
if (ChainsawIcons.UNDOCKED_ICON != null) {
undockedFrame.setIconImage(
new ImageIcon(ChainsawIcons.UNDOCKED_ICON).getImage());
}
externalPanel = new DockablePanel();
externalPanel.setLayout(new BorderLayout());
undockedFrame.getContentPane().add(externalPanel);
undockedFrame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dock();
}
});
undockedToolbar = createDockwindowToolbar();
externalPanel.add(undockedToolbar, BorderLayout.NORTH);
undockedFrame.pack();
/*
* Menus on which the preferencemodels rely
*/
/**
* Setup a popup menu triggered for Timestamp column to allow time stamp
* format changes
*/
final JPopupMenu dateFormatChangePopup = new JPopupMenu();
final JRadioButtonMenuItem isoButton =
new JRadioButtonMenuItem(
new AbstractAction("Use ISO8601Format") {
public void actionPerformed(ActionEvent e) {
preferenceModel.setDateFormatPattern("ISO8601");
}
});
final JRadioButtonMenuItem simpleTimeButton =
new JRadioButtonMenuItem(
new AbstractAction("Use simple time") {
public void actionPerformed(ActionEvent e) {
preferenceModel.setDateFormatPattern("HH:mm:ss");
}
});
ButtonGroup dfBG = new ButtonGroup();
dfBG.add(isoButton);
dfBG.add(simpleTimeButton);
isoButton.setSelected(true);
dateFormatChangePopup.add(isoButton);
dateFormatChangePopup.add(simpleTimeButton);
final JCheckBoxMenuItem menuItemToggleToolTips =
new JCheckBoxMenuItem("Show ToolTips");
menuItemToggleToolTips.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
preferenceModel.setToolTips(menuItemToggleToolTips.isSelected());
}
});
menuItemToggleToolTips.setIcon(new ImageIcon(ChainsawIcons.TOOL_TIP));
final JCheckBoxMenuItem menuItemLoggerTree =
new JCheckBoxMenuItem("Show Logger Tree panel");
menuItemLoggerTree.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
preferenceModel.setLogTreePanelVisible(
menuItemLoggerTree.isSelected());
}
});
menuItemLoggerTree.setIcon(new ImageIcon(ChainsawIcons.WINDOW_ICON));
final JCheckBoxMenuItem menuItemScrollBottom =
new JCheckBoxMenuItem("Scroll to bottom");
menuItemScrollBottom.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
preferenceModel.setScrollToBottom(menuItemScrollBottom.isSelected());
}
});
menuItemScrollBottom.setIcon(
new ImageIcon(ChainsawIcons.SCROLL_TO_BOTTOM));
final JCheckBoxMenuItem menuItemToggleDetails =
new JCheckBoxMenuItem("Show Detail Pane");
menuItemToggleDetails.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
preferenceModel.setDetailPaneVisible(
menuItemToggleDetails.isSelected());
}
});
menuItemToggleDetails.setIcon(new ImageIcon(ChainsawIcons.INFO));
/*
* add preferencemodel listeners
*/
preferenceModel.addPropertyChangeListener(
"levelIcons",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
renderer.setLevelUseIcons(
((Boolean) evt.getNewValue()).booleanValue());
table.tableChanged(new TableModelEvent(tableModel));
}
});
preferenceModel.addPropertyChangeListener(
"detailPaneVisible",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean newValue = ((Boolean) evt.getNewValue()).booleanValue();
if (newValue) {
showDetailPane();
} else {
hideDetailPane();
}
}
});
preferenceModel.addPropertyChangeListener(
"logTreePanelVisible",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean newValue = ((Boolean) evt.getNewValue()).booleanValue();
if (newValue) {
showLogTreePanel();
} else {
hideLogTreePanel();
}
}
});
preferenceModel.addPropertyChangeListener(
"toolTips",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
renderer.setToolTipsVisible(
((Boolean) evt.getNewValue()).booleanValue());
}
});
preferenceModel.addPropertyChangeListener(
"visibleColumns",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
TableColumnModel columnModel = table.getColumnModel();
for (int i = 0; i < columnModel.getColumnCount(); i++) {
TableColumn column = columnModel.getColumn(i);
if (
!preferenceModel.isColumnVisible(
column.getHeaderValue().toString())) {
columnModel.removeColumn(column);
}
}
Set columnSet = new HashSet();
Enumeration enumeration = columnModel.getColumns();
while (enumeration.hasMoreElements()) {
TableColumn column = (TableColumn) enumeration.nextElement();
columnSet.add(column.getHeaderValue());
}
for (
Iterator iter = ChainsawColumns.getColumnsNames().iterator();
iter.hasNext();) {
String column = (String) iter.next();
if (
preferenceModel.isColumnVisible(column)
&& !columnSet.contains(column)) {
TableColumn newCol =
new TableColumn(
ChainsawColumns.getColumnsNames().indexOf(column));
newCol.setHeaderValue(column);
columnModel.addColumn(newCol);
}
}
}
});
PropertyChangeListener datePrefsChangeListener =
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
LogPanelPreferenceModel model =
(LogPanelPreferenceModel) evt.getSource();
isoButton.setSelected(model.isUseISO8601Format());
simpleTimeButton.setSelected(
!model.isUseISO8601Format() && !model.isCustomDateFormat());
if (model.isUseISO8601Format()) {
renderer.setDateFormatter(new ISO8601DateFormat());
} else {
renderer.setDateFormatter(
new SimpleDateFormat(model.getDateFormatPattern()));
}
table.tableChanged(new TableModelEvent(tableModel));
}
};
preferenceModel.addPropertyChangeListener(
"dateFormatPattern", datePrefsChangeListener);
preferenceModel.addPropertyChangeListener(
"dateFormatPattern", datePrefsChangeListener);
preferenceModel.addPropertyChangeListener(
"loggerPrecision",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
LogPanelPreferenceModel model =
(LogPanelPreferenceModel) evt.getSource();
renderer.setLoggerPrecision(model.getLoggerPrecision());
table.tableChanged(new TableModelEvent(tableModel));
}
});
preferenceModel.addPropertyChangeListener(
"toolTips",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean value = ((Boolean) evt.getNewValue()).booleanValue();
menuItemToggleToolTips.setSelected(value);
}
});
preferenceModel.addPropertyChangeListener(
"logTreePanelVisible",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean value = ((Boolean) evt.getNewValue()).booleanValue();
menuItemLoggerTree.setSelected(value);
}
});
preferenceModel.addPropertyChangeListener(
"scrollToBottom",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean value = ((Boolean) evt.getNewValue()).booleanValue();
menuItemScrollBottom.setSelected(value);
scroll = value;
if (scroll) {
table.scrollToBottom(table.columnAtPoint(table.getVisibleRect().getLocation()));
}
}
});
preferenceModel.addPropertyChangeListener(
"detailPaneVisible",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean value = ((Boolean) evt.getNewValue()).booleanValue();
menuItemToggleDetails.setSelected(value);
}
});
/*
*End of preferenceModel listeners
*/
tableModel = new ChainsawCyclicBufferTableModel(cyclicBufferSize);
table = new JSortTable(tableModel);
//add a listener to update the 'refine focus'
tableModel.addNewKeyListener(new NewKeyListener() {
public void newKeyAdded(NewKeyEvent e) {
columnNameKeywordMap.put(e.getKey(), "PROP." + e.getKey());
}
});
/*
* Set the Display rule to use the mediator, the model will add itself as
* a property change listener and update itself when the rule changes.
*/
tableModel.setDisplayRule(ruleMediator);
tableModel.addEventCountListener(
new EventCountListener() {
public void eventCountChanged(int currentCount, int totalCount) {
if (LogPanel.this.isVisible()) {
statusBar.setSelectedLine(
table.getSelectedRow() + 1, currentCount, totalCount);
}
}
});
tableModel.addEventCountListener(
new EventCountListener() {
final NumberFormat formatter = NumberFormat.getPercentInstance();
boolean warning75 = false;
boolean warning100 = false;
public void eventCountChanged(int currentCount, int totalCount) {
if (tableModel.isCyclic()) {
double percent =
((double) totalCount) / ((ChainsawCyclicBufferTableModel) tableModel)
.getMaxSize();
String msg = null;
if ((percent > 0.75) && (percent < 1.0) && !warning75) {
msg =
"Warning :: " + formatter.format(percent) + " of the '"
+ getIdentifier() + "' buffer has been used";
warning75 = true;
} else if ((percent >= 1.0) && !warning100) {
msg =
"Warning :: " + formatter.format(percent) + " of the '"
+ getIdentifier()
+ "' buffer has been used. Older events are being discarded.";
warning100 = true;
}
if (msg != null) {
MessageCenter.getInstance().getLogger().info(msg);
}
}
}
});
/*
* Logger tree panel
*
*/
LogPanelLoggerTreeModel logTreeModel = new LogPanelLoggerTreeModel();
logTreePanel = new LoggerNameTreePanel(logTreeModel, preferenceModel);
tableModel.addLoggerNameListener(logTreeModel);
/**
* Set the LoggerRule to be the LoggerTreePanel, as this visual component
* is a rule itself, and the RuleMediator will automatically listen when
* it's rule state changes.
*/
ruleMediator.setLoggerRule(logTreePanel);
colorizer.setLoggerRule(logTreePanel.getLoggerColorRule());
/*
* Color rule frame and panel
*/
colorFrame.setTitle("'" + identifier + "' Color Filter");
colorFrame.setIconImage(
((ImageIcon) ChainsawIcons.ICON_PREFERENCES).getImage());
final ColorPanel colorPanel = new ColorPanel(colorizer, filterModel);
colorFrame.getContentPane().add(colorPanel);
colorPanel.setCloseActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorFrame.setVisible(false);
}
});
colorizer.addPropertyChangeListener(
"colorrule",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (table != null) {
table.repaint();
}
}
});
/*
* Table definition. Actual construction is above (next to tablemodel)
*/
table.setRowHeight(20);
table.setShowGrid(false);
table.getColumnModel().addColumnModelListener(
new ChainsawTableColumnModelListener());
table.setAutoCreateColumnsFromModel(false);
table.addMouseMotionListener(new TableColumnDetailMouseListener());
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//set valueisadjusting if holding down a key - don't process setdetail events
table.addKeyListener(
new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
synchronized (detail) {
table.getSelectionModel().setValueIsAdjusting(true);
detail.notify();
}
}
public void keyReleased(KeyEvent e) {
synchronized (detail) {
table.getSelectionModel().setValueIsAdjusting(false);
detail.notify();
}
}
});
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
if (
((evt.getFirstIndex() == evt.getLastIndex())
&& (evt.getFirstIndex() > 0)) || (evt.getValueIsAdjusting())) {
return;
}
boolean lastIndexOnLastRow = (evt.getLastIndex() == (table.getRowCount() - 1));
boolean lastIndexSame = (previousLastIndex == evt.getLastIndex());
/*
* when scroll-to-bottom is active, here is what events look like:
* rowcount-1: 227, last: 227, previous last: 191..first: 191
*
* when the user has unselected the bottom row, here is what the events look like:
* rowcount-1: 227, last: 227, previous last: 227..first: 222
*
* note: previouslast is set after it is evaluated in the bypass scroll check
*/
//System.out.println("rowcount: " + (table.getRowCount() - 1) + ", last: " + evt.getLastIndex() +", previous last: " + previousLastIndex + "..first: " + evt.getFirstIndex());
boolean bypassScrollSelection = (lastIndexOnLastRow && lastIndexSame && previousLastIndex != evt.getFirstIndex());
if (bypassScrollSelection && scroll && table.getRowCount() > 0) {
preferenceModel.setScrollToBottom(false);
}
previousLastIndex = evt.getLastIndex();
final ListSelectionModel lsm = (ListSelectionModel) evt.getSource();
if (lsm.isSelectionEmpty()) {
if (isVisible()) {
statusBar.setNothingSelected();
}
if (detail.getDocument().getDefaultRootElement() != null) {
detailPaneUpdater.setSelectedRow(-1);
}
} else {
if (table.getSelectedRow() > -1) {
int selectedRow = table.getSelectedRow();
if (isVisible()) {
updateStatusBar();
}
try {
if (tableModel.getRowCount() >= selectedRow) {
detailPaneUpdater.setSelectedRow(table.getSelectedRow());
} else {
detailPaneUpdater.setSelectedRow(-1);
}
} catch (Exception e) {
e.printStackTrace();
detailPaneUpdater.setSelectedRow(-1);
}
}
}
}
});
renderer = new TableColorizingRenderer(colorizer);
renderer.setToolTipsVisible(preferenceModel.isToolTips());
table.setDefaultRenderer(Object.class, renderer);
/*
* Throwable popup
*/
throwableRenderPanel = new ThrowableRenderPanel();
final JDialog detailDialog = new JDialog((JFrame) null, true);
Container container = detailDialog.getContentPane();
final JTextArea detailArea = new JTextArea(10, 40);
detailArea.setEditable(false);
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
container.add(new JScrollPane(detailArea));
detailDialog.pack();
throwableRenderPanel.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object o = table.getValueAt(
table.getSelectedRow(), table.getSelectedColumn());
if (o == null) {
//no row selected - ignore
LogLog.debug("no row selected - unable to display throwable popup");
return;
}
detailDialog.setTitle(
table.getColumnName(table.getSelectedColumn()) + " detail...");
if (o instanceof String[]) {
StringBuffer buf = new StringBuffer();
String[] ti = (String[]) o;
buf.append(ti[0]).append("\n");
for (int i = 1; i < ti.length; i++) {
buf.append(ti[i]).append("\n ");
}
detailArea.setText(buf.toString());
} else {
detailArea.setText((o == null) ? "" : o.toString());
}
detailDialog.setLocation(lowerPanel.getLocationOnScreen());
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
detailDialog.setVisible(true);
}
});
}
});
/*
* We listen for new Key's coming in so we can get them automatically
* added as columns
*/
tableModel.addNewKeyListener(
new NewKeyListener() {
public void newKeyAdded(NewKeyEvent e) {
TableColumn col = new TableColumn(e.getNewModelIndex());
col.setHeaderValue(e.getKey());
table.addColumn(col);
}
});
tableModel.addPropertyChangeListener(
"cyclic",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent arg0) {
if (tableModel.isCyclic()) {
MessageCenter.getInstance().getLogger().warn(
"Changed to Cyclic Mode. Maximum # events kept: "
+ tableModel.getMaxSize());
} else {
MessageCenter.getInstance().getLogger().warn(
"Changed to Unlimited Mode. Warning, you may run out of memory.");
}
}
});
table.getTableHeader().addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
checkEvent(e);
}
public void mousePressed(MouseEvent e) {
checkEvent(e);
}
public void mouseReleased(MouseEvent e) {
checkEvent(e);
}
private void checkEvent(MouseEvent e) {
if (e.isPopupTrigger()) {
TableColumnModel colModel = table.getColumnModel();
int index = colModel.getColumnIndexAtX(e.getX());
int modelIndex = colModel.getColumn(index).getModelIndex();
if ((modelIndex + 1) == ChainsawColumns.INDEX_TIMESTAMP_COL_NAME) {
dateFormatChangePopup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
});
/*
* Upper panel definition
*/
JPanel upperPanel = new JPanel(new BorderLayout());
upperPanel.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0));
final JLabel filterLabel = new JLabel("Refine focus on: ");
filterLabel.setFont(filterLabel.getFont().deriveFont(Font.BOLD));
JPanel upperLeftPanel =
new JPanel(new FlowLayout(FlowLayout.CENTER, 3, 0));
upperLeftPanel.add(filterLabel);
//hold a reference to the combobox model so that we can check to prevent duplicates
final Vector v = new Vector();
final JComboBox filterCombo = new JComboBox(v);
final JTextField filterText;
if (filterCombo.getEditor().getEditorComponent() instanceof JTextField) {
String comboToolTipText =
"Enter an expression, press enter to add to list";
filterText = (JTextField) filterCombo.getEditor().getEditorComponent();
filterText.setToolTipText(comboToolTipText);
filterText.addKeyListener(
new ExpressionRuleContext(filterModel, filterText));
filterText.getDocument().addDocumentListener(
new DelayedFilterTextDocumentListener(filterText));
filterCombo.setEditable(true);
filterCombo.addActionListener(
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxEdited")) {
try {
//verify the expression is valid
ExpressionRule.getRule(
filterCombo.getSelectedItem().toString());
} catch (IllegalArgumentException iae) {
//don't add expressions that aren't valid
return;
}
//should be 'valid expression' check
if (!(v.contains(filterCombo.getSelectedItem()))) {
filterCombo.addItem(filterCombo.getSelectedItem());
}
}
}
});
upperPanel.add(filterCombo, BorderLayout.CENTER);
} else {
filterText = new JTextField();
filterText.setToolTipText("Enter an expression");
filterText.addKeyListener(
new ExpressionRuleContext(filterModel, filterText));
filterText.getDocument().addDocumentListener(
new DelayedFilterTextDocumentListener(filterText));
upperPanel.add(filterText, BorderLayout.CENTER);
}
upperPanel.add(upperLeftPanel, BorderLayout.WEST);
JPanel upperRightPanel =
new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
upperPanel.add(upperRightPanel, BorderLayout.EAST);
/*
* Detail pane definition
*/
detail = new JEditorPane(ChainsawConstants.DETAIL_CONTENT_TYPE, "");
detail.setEditable(false);
detailPaneUpdater = new DetailPaneUpdater();
addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
detailPaneUpdater.updateDetailPane();
}
public void focusLost(FocusEvent e) {
}
});
tableModel.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
detailPaneUpdater.setSelectedRow(table.getSelectedRow());
}
});
addPropertyChangeListener(
"detailPaneConversionPattern", detailPaneUpdater);
final JScrollPane detailPane = new JScrollPane(detail);
detailPane.setPreferredSize(new Dimension(900, 50));
detailPanel.add(detailPane, BorderLayout.CENTER);
JPanel eventsAndStatusPanel = new JPanel(new BorderLayout());
final JScrollPane eventsPane = new JScrollPane(table);
eventsAndStatusPanel.add(eventsPane, BorderLayout.CENTER);
final JPanel statusLabelPanel = new JPanel();
statusLabelPanel.setLayout(new BorderLayout());
statusLabelPanel.add(upperPanel, BorderLayout.CENTER);
eventsAndStatusPanel.add(statusLabelPanel, BorderLayout.NORTH);
lowerPanel =
new JSplitPane(
JSplitPane.VERTICAL_SPLIT, eventsAndStatusPanel, detailPanel);
dividerSize = lowerPanel.getDividerSize();
lowerPanel.setDividerLocation(-1);
lowerPanel.setResizeWeight(1.0);
lowerPanel.setBorder(null);
lowerPanel.setContinuousLayout(true);
if (preferenceModel.isDetailPaneVisible()) {
showDetailPane();
} else {
hideDetailPane();
}
/*
* Detail panel layout editor
*/
final JToolBar detailToolbar = new JToolBar(SwingConstants.HORIZONTAL);
detailToolbar.setFloatable(false);
final LayoutEditorPane layoutEditorPane = new LayoutEditorPane();
final JDialog layoutEditorDialog =
new JDialog((JFrame) null, "Pattern Editor");
layoutEditorDialog.getContentPane().add(layoutEditorPane);
layoutEditorDialog.setSize(640, 480);
layoutEditorPane.addCancelActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
layoutEditorDialog.setVisible(false);
}
});
layoutEditorPane.addOkActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
setDetailPaneConversionPattern(
layoutEditorPane.getConversionPattern());
layoutEditorDialog.setVisible(false);
}
});
Action editDetailAction =
new AbstractAction(
"Edit...", new ImageIcon(ChainsawIcons.ICON_EDIT_RECEIVER)) {
public void actionPerformed(ActionEvent e) {
layoutEditorPane.setConversionPattern(
getDetailPaneConversionPattern());
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
Point p =
new Point(
((int) ((size.getWidth() / 2)
- (layoutEditorDialog.getSize().getWidth() / 2))),
((int) ((size.getHeight() / 2)
- (layoutEditorDialog.getSize().getHeight() / 2))));
layoutEditorDialog.setLocation(p);
layoutEditorDialog.setVisible(true);
}
};
editDetailAction.putValue(
Action.SHORT_DESCRIPTION,
"opens a Dialog window to Edit the Pattern Layout text");
final SmallButton editDetailButton = new SmallButton(editDetailAction);
editDetailButton.setText(null);
detailToolbar.add(Box.createHorizontalGlue());
detailToolbar.add(editDetailButton);
detailToolbar.addSeparator();
detailToolbar.add(Box.createHorizontalStrut(5));
Action closeDetailAction =
new AbstractAction(null, LineIconFactory.createCloseIcon()) {
public void actionPerformed(ActionEvent arg0) {
preferenceModel.setDetailPaneVisible(false);
}
};
closeDetailAction.putValue(
Action.SHORT_DESCRIPTION, "Hides the Detail Panel");
SmallButton closeDetailButton = new SmallButton(closeDetailAction);
detailToolbar.add(closeDetailButton);
detailPanel.add(detailToolbar, BorderLayout.NORTH);
JPopupMenu editDetailPopupMenu = new JPopupMenu();
editDetailPopupMenu.add(editDetailAction);
editDetailPopupMenu.addSeparator();
final ButtonGroup layoutGroup = new ButtonGroup();
JRadioButtonMenuItem defaultLayoutRadio =
new JRadioButtonMenuItem(
new AbstractAction("Set to Default Layout") {
public void actionPerformed(ActionEvent e) {
setDetailPaneConversionPattern(
DefaultLayoutFactory.getDefaultPatternLayout());
}
});
editDetailPopupMenu.add(defaultLayoutRadio);
layoutGroup.add(defaultLayoutRadio);
defaultLayoutRadio.setSelected(true);
JRadioButtonMenuItem tccLayoutRadio =
new JRadioButtonMenuItem(
new AbstractAction("Set to TCCLayout") {
public void actionPerformed(ActionEvent e) {
setDetailPaneConversionPattern(
PatternLayout.TTCC_CONVERSION_PATTERN);
}
});
editDetailPopupMenu.add(tccLayoutRadio);
layoutGroup.add(tccLayoutRadio);
PopupListener editDetailPopupListener =
new PopupListener(editDetailPopupMenu);
detail.addMouseListener(editDetailPopupListener);
/*
* Logger tree splitpane definition
*/
nameTreeAndMainPanelSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, logTreePanel, lowerPanel);
nameTreeAndMainPanelSplit.setToolTipText("Still under development....");
nameTreeAndMainPanelSplit.setDividerLocation(-1);
add(nameTreeAndMainPanelSplit, BorderLayout.CENTER);
if (isLogTreeVisible()) {
showLogTreePanel();
} else {
hideLogTreePanel();
}
/*
* Other menu items
*/
final JMenuItem menuItemBestFit = new JMenuItem("Best fit column");
menuItemBestFit.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (currentPoint != null) {
int column = table.columnAtPoint(currentPoint);
int maxWidth = getMaxColumnWidth(column);
table.getColumnModel().getColumn(column).setPreferredWidth(
maxWidth);
}
}
});
JMenuItem menuItemColorPanel = new JMenuItem("LogPanel Color Filter...");
menuItemColorPanel.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
showColorPreferences();
}
});
menuItemColorPanel.setIcon(ChainsawIcons.ICON_PREFERENCES);
JMenuItem menuItemLogPanelPreferences =
new JMenuItem("LogPanel Preferences...");
menuItemLogPanelPreferences.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
showPreferences();
}
});
menuItemLogPanelPreferences.setIcon(ChainsawIcons.ICON_PREFERENCES);
final JMenuItem menuItemFocusOn =
new JMenuItem("Set 'refine focus' field");
menuItemFocusOn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (currentPoint != null) {
String operator = "==";
int column = table.columnAtPoint(currentPoint);
int row = table.rowAtPoint(currentPoint);
String colName = table.getColumnName(column);
String value = "";
if (colName.equalsIgnoreCase(ChainsawConstants.TIMESTAMP_COL_NAME)) {
value = timestampExpressionFormat.format(new Date(table.getValueAt(row, column).toString()));
} else {
Object o = table.getValueAt(row, column);
if (o != null) {
if (o instanceof String[]) {
value = ((String[]) o)[0];
operator = "~=";
} else {
value = o.toString();
}
}
}
if (columnNameKeywordMap.containsKey(colName)) {
filterText.setText(
columnNameKeywordMap.get(colName).toString() + " " + operator
+ " '" + value + "'");
}
}
}
});
final JMenuItem menuDefineAddCustomFilter =
new JMenuItem("Add to 'refine focus' field");
menuDefineAddCustomFilter.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (currentPoint != null) {
String operator = "==";
int column = table.columnAtPoint(currentPoint);
int row = table.rowAtPoint(currentPoint);
String colName = table.getColumnName(column);
String value = "";
if (colName.equalsIgnoreCase(ChainsawConstants.TIMESTAMP_COL_NAME)) {
JComponent comp =
(JComponent) table.getCellRenderer(row, column);
if (comp instanceof JLabel) {
value = ((JLabel) comp).getText();
}
} else {
Object o = table.getValueAt(row, column).toString();
if (o instanceof String[]) {
value = ((String[]) o)[0];
operator = "~=";
} else {
value = o.toString();
}
}
if (columnNameKeywordMap.containsKey(colName)) {
filterText.setText(
filterText.getText() + " && "
+ columnNameKeywordMap.get(colName).toString() + " "
+ operator + " '" + value + "'");
}
}
}
});
final JPopupMenu p = new JPopupMenu();
final Action clearFocusAction =
new AbstractAction("Clear 'refine focus' field") {
public void actionPerformed(ActionEvent e) {
filterText.setText(null);
ruleMediator.setRefinementRule(null);
}
};
final JMenuItem menuItemToggleDock = new JMenuItem("Undock/dock");
dockingAction =
new AbstractAction("Undock") {
public void actionPerformed(ActionEvent evt) {
if (isDocked()) {
undock();
} else {
dock();
}
}
};
dockingAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.UNDOCK));
menuItemToggleDock.setAction(dockingAction);
/*
* Popup definition
*/
p.add(clearFocusAction);
p.add(menuItemFocusOn);
p.add(menuDefineAddCustomFilter);
p.add(new JSeparator());
p.add(menuItemBestFit);
p.add(new JSeparator());
p.add(menuItemToggleDetails);
p.add(menuItemLoggerTree);
p.add(menuItemToggleToolTips);
p.add(new JSeparator());
p.add(menuItemScrollBottom);
p.add(new JSeparator());
p.add(menuItemToggleDock);
p.add(new JSeparator());
p.add(menuItemColorPanel);
p.add(menuItemLogPanelPreferences);
final PopupListener popupListener = new PopupListener(p);
eventsPane.addMouseListener(popupListener);
table.addMouseListener(popupListener);
}
/**
* Accessor
*
* @return scrollToBottom
*
*/
public boolean isScrollToBottom() {
return preferenceModel.isScrollToBottom();
}
/**
* Mutator
*
*/
public void toggleScrollToBottom() {
preferenceModel.setScrollToBottom(!preferenceModel.isScrollToBottom());
}
/**
* Accessor
*
* @return namespace
*
* @see Profileable
*/
public String getNamespace() {
return getIdentifier();
}
/**
* Accessor
*
* @return identifier
*
* @see EventBatchListener
*/
public String getInterestedIdentifier() {
return getIdentifier();
}
/**
* Process events associated with the identifier. Currently assumes it only
* receives events which share this LogPanel's identifier
*
* @param ident identifier shared by events
* @param eventBatchEntrys list of EventBatchEntry objects
*/
public void receiveEventBatch(String ident, List eventBatchEntrys) {
/*
* if this panel is paused, we totally ignore events
*/
if (isPaused()) {
return;
}
//table.getSelectionModel().setValueIsAdjusting(true);
boolean rowAdded = false;
int first = tableModel.getLastAdded() + 1;
for (Iterator iter = eventBatchEntrys.iterator(); iter.hasNext();) {
ChainsawEventBatchEntry entry = (ChainsawEventBatchEntry) iter.next();
updateOtherModels(entry);
boolean isCurrentRowAdded = tableModel.isAddRow(entry.getEvent(), true);
rowAdded = rowAdded ? true : isCurrentRowAdded;
}
table.getSelectionModel().setValueIsAdjusting(false);
//tell the model to notify the count listeners
tableModel.notifyCountListeners();
if (rowAdded) {
if (tableModel.isSortEnabled()) {
tableModel.sort();
}
tableModel.fireTableEvent(
first, tableModel.getLastAdded(), eventBatchEntrys.size());
if (scroll && !bypassScrollFind) {
table.scrollToBottom(
table.columnAtPoint(table.getVisibleRect().getLocation()));
}
//always update detail pane (since we may be using a cyclic buffer which is full)
detailPaneUpdater.setSelectedRow(table.getSelectedRow());
}
}
/**
* Load settings from the panel preference model
*
* @param event
*
* @see LogPanelPreferenceModel
*/
public void loadSettings(LoadSettingsEvent event) {
preferenceModel.setLevelIcons(event.asBoolean("levelIcons"));
preferenceModel.setDateFormatPattern(
event.getSetting("dateFormatPattern"));
preferenceModel.setLoggerPrecision(event.getSetting("loggerPrecision"));
preferenceModel.setToolTips(event.asBoolean("toolTips"));
preferenceModel.setScrollToBottom(event.asBoolean("scrollToBottom"));
scroll = event.asBoolean("scrollToBottom");
preferenceModel.setLogTreePanelVisible(
event.asBoolean("logTreePanelVisible"));
preferenceModel.setDetailPaneVisible(event.asBoolean("detailPaneVisible"));
logTreePanel.ignore(event.getSettingsStartingWith("Logger.Ignore."));
//first attempt to load encoded file
File f =
new File(
SettingsManager.getInstance().getSettingsDirectory(), URLEncoder.encode(identifier) + COLUMNS_EXTENSION);
if (!f.exists()) {
f =
new File(
SettingsManager.getInstance().getSettingsDirectory(), identifier + COLUMNS_EXTENSION);
}
if (f.exists()) {
loadColumnSettings(f);
} else {
loadDefaultColumnSettings(event);
}
//first attempt to load encoded file
File f2 =
new File(
SettingsManager.getInstance().getSettingsDirectory(), URLEncoder.encode(identifier) + COLORS_EXTENSION);
if (!f2.exists()) {
f2 =
new File(
SettingsManager.getInstance().getSettingsDirectory(), identifier + COLORS_EXTENSION);
}
if (f2.exists()) {
loadColorSettings(f2);
}
}
/**
* Save preferences to the panel preference model
*
* @param event
*
* @see LogPanelPreferenceModel
*/
public void saveSettings(SaveSettingsEvent event) {
event.saveSetting("levelIcons", preferenceModel.isLevelIcons());
event.saveSetting(
"dateFormatPattern", preferenceModel.getDateFormatPattern());
event.saveSetting("loggerPrecision", preferenceModel.getLoggerPrecision());
event.saveSetting("toolTips", preferenceModel.isToolTips());
event.saveSetting("scrollToBottom", preferenceModel.isScrollToBottom());
event.saveSetting(
"detailPaneVisible", preferenceModel.isDetailPaneVisible());
event.saveSetting(
"logTreePanelVisible", preferenceModel.isLogTreePanelVisible());
Set set = logTreePanel.getHiddenSet();
int index = 0;
for (Iterator iter = set.iterator(); iter.hasNext();) {
Object logger = iter.next();
event.saveSetting("Logger.Ignore." + index++, logger.toString());
}
saveColumnSettings();
saveColorSettings();
}
/**
* Display the panel preferences frame
*/
void showPreferences() {
preferencesPanel.updateModel();
preferencesFrame.show();
}
/**
* Display the color rule frame
*/
void showColorPreferences() {
colorFrame.pack();
colorFrame.show();
}
/**
* Toggle panel preference for detail visibility on or off
*/
void toggleDetailVisible() {
preferenceModel.setDetailPaneVisible(
!preferenceModel.isDetailPaneVisible());
}
/**
* Accessor
*
* @return detail visibility flag
*/
boolean isDetailVisible() {
return preferenceModel.isDetailPaneVisible();
}
/**
* Toggle panel preference for logger tree visibility on or off
*/
void toggleLogTreeVisible() {
preferenceModel.setLogTreePanelVisible(
!preferenceModel.isLogTreePanelVisible());
}
/**
* Accessor
*
* @return logger tree visibility flag
*/
boolean isLogTreeVisible() {
return preferenceModel.isLogTreePanelVisible();
}
/**
* Return all events
*
* @return list of LoggingEvents
*/
List getEvents() {
return tableModel.getAllEvents();
}
/**
* Return the events that are visible with the current filter applied
*
* @return list of LoggingEvents
*/
List getFilteredEvents() {
return tableModel.getFilteredEvents();
}
List getMatchingEvents(Rule rule) {
return tableModel.getMatchingEvents(rule);
}
/**
* Remove all events
*/
void clearEvents() {
clearModel();
}
/**
* Accessor
*
* @return identifier
*/
String getIdentifier() {
return identifier;
}
/**
* Undocks this DockablePanel by removing the panel from the LogUI window
* and placing it inside it's own JFrame.
*/
void undock() {
int row = table.getSelectedRow();
setDocked(false);
externalPanel.removeAll();
findPanel.removeAll();
findPanel.add(findField);
externalPanel.add(undockedToolbar, BorderLayout.NORTH);
externalPanel.add(nameTreeAndMainPanelSplit, BorderLayout.CENTER);
externalPanel.setDocked(false);
undockedFrame.setSize(getSize());
undockedFrame.setLocation(getBounds().x, getBounds().y);
undockedFrame.setVisible(true);
dockingAction.putValue(Action.NAME, "Dock");
dockingAction.putValue(Action.SMALL_ICON, ChainsawIcons.ICON_DOCK);
if (row > -1) {
table.scrollToRow(row, table.columnAtPoint(table.getVisibleRect().getLocation()));
}
}
/**
* Add an eventCountListener
*
* @param l
*/
void addEventCountListener(EventCountListener l) {
tableModel.addEventCountListener(l);
}
/**
* Accessor
*
* @return paused flag
*/
boolean isPaused() {
return paused;
}
/**
* Modifies the Paused property and notifies the listeners
*
* @param paused
*/
void setPaused(boolean paused) {
boolean oldValue = this.paused;
this.paused = paused;
firePropertyChange("paused", oldValue, paused);
}
/**
* Add a preference propertyChangeListener
*
* @param listener
*/
void addPreferencePropertyChangeListener(PropertyChangeListener listener) {
preferenceModel.addPropertyChangeListener(listener);
}
/**
* Toggle the LoggingEvent container from either managing a cyclic buffer of
* events or an ArrayList of events
*/
void toggleCyclic() {
tableModel.setCyclic(!tableModel.isCyclic());
}
/**
* Accessor
*
* @return flag answering if LoggingEvent container is a cyclic buffer
*/
boolean isCyclic() {
return tableModel.isCyclic();
}
public boolean updateRule(String ruleText) {
if ((ruleText == null) || ((ruleText != null) && ruleText.equals(""))) {
findRule = null;
colorizer.setFindRule(null);
bypassScrollFind = false;
findField.setToolTipText(
"Enter expression - right click or ctrl-space for menu");
return false;
} else {
bypassScrollFind = true;
try {
findField.setToolTipText(
"Enter expression - right click or ctrl-space for menu");
findRule = ExpressionRule.getRule(ruleText);
colorizer.setFindRule(findRule);
return true;
} catch (IllegalArgumentException re) {
findField.setToolTipText(re.getMessage());
colorizer.setFindRule(null);
return false;
}
}
}
/**
* Display the detail pane, using the last known divider location
*/
private void showDetailPane() {
lowerPanel.setDividerSize(dividerSize);
lowerPanel.setDividerLocation(lastDetailPanelSplitLocation);
detailPanel.setVisible(true);
lowerPanel.repaint();
}
/**
* Hide the detail pane, holding the current divider location for later use
*/
private void hideDetailPane() {
int currentSize = lowerPanel.getHeight() - lowerPanel.getDividerSize();
if (currentSize > 0) {
lastDetailPanelSplitLocation =
(double) lowerPanel.getDividerLocation() / currentSize;
}
lowerPanel.setDividerSize(0);
detailPanel.setVisible(false);
lowerPanel.repaint();
}
/**
* Display the log tree pane, using the last known divider location
*/
private void showLogTreePanel() {
nameTreeAndMainPanelSplit.setDividerSize(dividerSize);
nameTreeAndMainPanelSplit.setDividerLocation(
lastLogTreePanelSplitLocation);
logTreePanel.setVisible(true);
nameTreeAndMainPanelSplit.repaint();
}
/**
* Hide the log tree pane, holding the current divider location for later use
*/
private void hideLogTreePanel() {
//subtract one to make sizes match
int currentSize = nameTreeAndMainPanelSplit.getWidth() - nameTreeAndMainPanelSplit.getDividerSize() - 1;
if (currentSize > 0) {
lastLogTreePanelSplitLocation =
(double) nameTreeAndMainPanelSplit.getDividerLocation() / currentSize;
}
nameTreeAndMainPanelSplit.setDividerSize(0);
logTreePanel.setVisible(false);
nameTreeAndMainPanelSplit.repaint();
}
/**
* Return a toolbar used by the undocked LogPanel's frame
*
* @return toolbar
*/
private JToolBar createDockwindowToolbar() {
final JToolBar toolbar = new JToolBar();
toolbar.setFloatable(false);
final Action dockPauseAction =
new AbstractAction("Pause") {
public void actionPerformed(ActionEvent evt) {
setPaused(!isPaused());
}
};
dockPauseAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_P));
dockPauseAction.putValue(
Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("F12"));
dockPauseAction.putValue(
Action.SHORT_DESCRIPTION,
"Halts the display, while still allowing events to stream in the background");
dockPauseAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.PAUSE));
final SmallToggleButton dockPauseButton =
new SmallToggleButton(dockPauseAction);
dockPauseButton.setText("");
dockPauseButton.getModel().setSelected(isPaused());
addPropertyChangeListener(
"paused",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
dockPauseButton.getModel().setSelected(isPaused());
}
});
toolbar.add(dockPauseButton);
Action dockShowPrefsAction =
new AbstractAction("") {
public void actionPerformed(ActionEvent arg0) {
showPreferences();
}
};
dockShowPrefsAction.putValue(
Action.SHORT_DESCRIPTION, "Define preferences...");
dockShowPrefsAction.putValue(
Action.SMALL_ICON, ChainsawIcons.ICON_PREFERENCES);
toolbar.add(new SmallButton(dockShowPrefsAction));
Action dockToggleLogTreeAction =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
toggleLogTreeVisible();
}
};
dockToggleLogTreeAction.putValue(Action.SHORT_DESCRIPTION, "Toggles the Logger Tree Pane");
dockToggleLogTreeAction.putValue("enabled", Boolean.TRUE);
dockToggleLogTreeAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_T));
dockToggleLogTreeAction.putValue(
Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.ALT_MASK));
dockToggleLogTreeAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.WINDOW_ICON));
final SmallToggleButton toggleLogTreeButton =
new SmallToggleButton(dockToggleLogTreeAction);
preferenceModel.addPropertyChangeListener("logTreePanelVisible", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
toggleLogTreeButton.setSelected(preferenceModel.isLogTreePanelVisible());
}
});
toggleLogTreeButton.setSelected(isLogTreeVisible());
toolbar.add(toggleLogTreeButton);
toolbar.addSeparator();
final Action undockedClearAction =
new AbstractAction("Clear") {
public void actionPerformed(ActionEvent arg0) {
clearModel();
}
};
undockedClearAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.DELETE));
undockedClearAction.putValue(
Action.SHORT_DESCRIPTION, "Removes all the events from the current view");
final SmallButton dockClearButton = new SmallButton(undockedClearAction);
dockClearButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, InputEvent.CTRL_MASK),
undockedClearAction.getValue(Action.NAME));
dockClearButton.getActionMap().put(
undockedClearAction.getValue(Action.NAME), undockedClearAction);
dockClearButton.setText("");
toolbar.add(dockClearButton);
toolbar.addSeparator();
Action dockToggleScrollToBottomAction =
new AbstractAction("Toggles Scroll to Bottom") {
public void actionPerformed(ActionEvent e) {
toggleScrollToBottom();
}
};
dockToggleScrollToBottomAction.putValue(Action.SHORT_DESCRIPTION, "Toggles Scroll to Bottom");
dockToggleScrollToBottomAction.putValue("enabled", Boolean.TRUE);
dockToggleScrollToBottomAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.SCROLL_TO_BOTTOM));
final SmallToggleButton toggleScrollToBottomButton =
new SmallToggleButton(dockToggleScrollToBottomAction);
preferenceModel.addPropertyChangeListener("scrollToBottom", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
toggleScrollToBottomButton.setSelected(preferenceModel.isScrollToBottom());
}
});
toggleScrollToBottomButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_B, InputEvent.CTRL_MASK),
dockToggleScrollToBottomAction.getValue(Action.NAME));
toggleScrollToBottomButton.getActionMap().put(
dockToggleScrollToBottomAction.getValue(Action.NAME), dockToggleScrollToBottomAction);
toggleScrollToBottomButton.setSelected(isScrollToBottom());
toggleScrollToBottomButton.setText("");
toolbar.add(toggleScrollToBottomButton);
toolbar.addSeparator();
findField = new JTextField();
findField.addKeyListener(
new ExpressionRuleContext(filterModel, findField));
final Action undockedFindNextAction =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
findNext();
}
};
undockedFindNextAction.putValue(Action.NAME, "Find next");
undockedFindNextAction.putValue(
Action.SHORT_DESCRIPTION,
"Find the next occurrence of the rule from the current row");
undockedFindNextAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.DOWN));
SmallButton undockedFindNextButton =
new SmallButton(undockedFindNextAction);
undockedFindNextButton.setAction(undockedFindNextAction);
undockedFindNextButton.setText("");
undockedFindNextButton.getActionMap().put(
undockedFindNextAction.getValue(Action.NAME), undockedFindNextAction);
undockedFindNextButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("F3"),
undockedFindNextAction.getValue(Action.NAME));
final Action undockedFindPreviousAction =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
findPrevious();
}
};
undockedFindPreviousAction.putValue(Action.NAME, "Find previous");
undockedFindPreviousAction.putValue(
Action.SHORT_DESCRIPTION,
"Find the previous occurrence of the rule from the current row");
undockedFindPreviousAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.UP));
SmallButton undockedFindPreviousButton =
new SmallButton(undockedFindPreviousAction);
undockedFindPreviousButton.setAction(undockedFindPreviousAction);
undockedFindPreviousButton.setText("");
undockedFindPreviousButton.getActionMap().put(
undockedFindPreviousAction.getValue(Action.NAME),
undockedFindPreviousAction);
undockedFindPreviousButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(
KeyStroke.getKeyStroke(KeyEvent.VK_F3, KeyEvent.SHIFT_MASK),
undockedFindPreviousAction.getValue(Action.NAME));
Dimension findSize = new Dimension(170, 22);
Dimension findPanelSize = new Dimension(175, 30);
findPanel.setPreferredSize(findPanelSize);
findPanel.setMaximumSize(findPanelSize);
findPanel.setMinimumSize(findPanelSize);
findField.setPreferredSize(findSize);
findField.setMaximumSize(findSize);
findField.setMinimumSize(findSize);
findPanel.setAlignmentY(Component.CENTER_ALIGNMENT);
findField.setAlignmentY(Component.CENTER_ALIGNMENT);
toolbar.add(findPanel);
toolbar.add(undockedFindNextButton);
toolbar.add(undockedFindPreviousButton);
toolbar.addSeparator();
Action redockAction =
new AbstractAction("", ChainsawIcons.ICON_DOCK) {
public void actionPerformed(ActionEvent arg0) {
dock();
}
};
redockAction.putValue(
Action.SHORT_DESCRIPTION,
"Docks this window back with the main Chainsaw window");
SmallButton redockButton = new SmallButton(redockAction);
toolbar.add(redockButton);
return toolbar;
}
/**
* Update the status bar with current selected row and row count
*/
private void updateStatusBar() {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
statusBar.setSelectedLine(
table.getSelectedRow() + 1, tableModel.getRowCount(),
tableModel.size());
}
});
}
/**
* Update the detail pane layout text
*
* @param conversionPattern layout text
*/
private void setDetailPaneConversionPattern(String conversionPattern) {
String oldPattern = getDetailPaneConversionPattern();
((EventDetailLayout) detailLayout).setConversionPattern(conversionPattern);
firePropertyChange(
"detailPaneConversionPattern", oldPattern,
getDetailPaneConversionPattern());
}
/**
* Accessor
*
* @return conversionPattern layout text
*/
private String getDetailPaneConversionPattern() {
return ((EventDetailLayout) detailLayout).getConversionPattern();
}
/**
* Reset the LoggingEvent container, detail panel and status bar
*/
private void clearModel() {
tableModel.clearModel();
synchronized (detail) {
detailPaneUpdater.setSelectedRow(-1);
detail.notify();
}
statusBar.setNothingSelected();
}
/**
* Finds the next row matching the current find rule, and ensures it is made
* visible
*
*/
public void findNext() {
updateRule(findField.getText());
if (findRule != null) {
try {
final int nextRow =
tableModel.find(findRule, table.getSelectedRow() + 1, true);
if (nextRow > -1) {
table.scrollToRow(
nextRow, table.columnAtPoint(table.getVisibleRect().getLocation()));
findField.setToolTipText("Enter an expression");
}
} catch (IllegalArgumentException iae) {
findField.setToolTipText(iae.getMessage());
colorizer.setFindRule(null);
}
}
}
/**
* Finds the previous row matching the current find rule, and ensures it is made
* visible
*
*/
public void findPrevious() {
updateRule(findField.getText());
if (findRule != null) {
try {
final int previousRow =
tableModel.find(findRule, table.getSelectedRow() - 1, false);
if (previousRow > -1) {
table.scrollToRow(
previousRow,
table.columnAtPoint(table.getVisibleRect().getLocation()));
findField.setToolTipText("Enter an expression");
}
} catch (IllegalArgumentException iae) {
findField.setToolTipText(iae.getMessage());
}
}
}
/**
* Docks this DockablePanel by hiding the JFrame and placing the Panel back
* inside the LogUI window.
*/
private void dock() {
int row = table.getSelectedRow();
setDocked(true);
undockedFrame.setVisible(false);
removeAll();
add(nameTreeAndMainPanelSplit, BorderLayout.CENTER);
externalPanel.setDocked(true);
dockingAction.putValue(Action.NAME, "Undock");
dockingAction.putValue(Action.SMALL_ICON, ChainsawIcons.ICON_UNDOCK);
if (row > -1) {
table.scrollToRow(row, table.columnAtPoint(table.getVisibleRect().getLocation()));
}
}
/**
* Save panel column settings
*/
private void saveColumnSettings() {
ObjectOutputStream o = null;
try {
File f = new File(SettingsManager.getInstance().getSettingsDirectory(),
URLEncoder.encode(getIdentifier() + COLUMNS_EXTENSION));
LogLog.debug("writing columns to file: " + f);
o = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(f)));
Enumeration e = this.table.getColumnModel().getColumns();
while (e.hasMoreElements()) {
TableColumn c = (TableColumn) e.nextElement();
if (c.getModelIndex() < ChainsawColumns.getColumnsNames().size()) {
o.writeObject(
new TableColumnData(
(String) c.getHeaderValue(), c.getModelIndex(), c.getWidth()));
} else {
LogLog.debug(
"Not saving col ' " + c.getHeaderValue()
+ "' not part of standard columns");
}
}
o.flush();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (o != null) {
o.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
/**
* Save panel color settings
*/
private void saveColorSettings() {
ObjectOutputStream o = null;
try {
File f = new File(SettingsManager.getInstance().getSettingsDirectory(),
URLEncoder.encode(getIdentifier() + COLORS_EXTENSION));
LogLog.debug("writing colors to file: " + f);
o = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(f)));
o.writeObject(colorizer.getRules());
o.flush();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (o != null) {
o.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
/**
* Load panel column settings
*/
private void loadColumnSettings(File f) {
if (f.exists()) {
ArrayList newColumns = new ArrayList();
TableColumnData temp = null;
ObjectInputStream s = null;
try {
s = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(f)));
while (true) {
temp = (TableColumnData) s.readObject();
TableColumn tc = new TableColumn(temp.getIndex(), temp.getWidth());
tc.setHeaderValue(temp.getColName());
newColumns.add(tc);
}
} catch (EOFException eof) { //end of file - ignore..
}catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
//only remove columns and add serialized columns if
//at least one column was read from the file
TableColumnModel model = table.getColumnModel();
if (newColumns.size() > 0) {
//remove columns from model - will be re-added in the correct order
for (int i = model.getColumnCount() - 1; i > -1; i--) {
model.removeColumn(model.getColumn(i));
}
for (Iterator iter = newColumns.iterator(); iter.hasNext();) {
model.addColumn((TableColumn) iter.next());
}
}
}
}
/**
* Load default column settings if no settings exist for this identifier
*
* @param event
*/
private void loadDefaultColumnSettings(LoadSettingsEvent event) {
String columnOrder = event.getSetting(TABLE_COLUMN_ORDER);
TableColumnModel columnModel = table.getColumnModel();
Map columnNameMap = new HashMap();
for (int i = 0; i < columnModel.getColumnCount(); i++) {
columnNameMap.put(table.getColumnName(i), columnModel.getColumn(i));
}
int index = 0;
StringTokenizer tok = new StringTokenizer(columnOrder, ",");
List sortedColumnList = new ArrayList();
/*
remove all columns from the table that exist in the model
and add in the correct order to a new arraylist
(may be a subset of possible columns)
**/
while (tok.hasMoreElements()) {
String element = (String) tok.nextElement();
TableColumn column = (TableColumn) columnNameMap.get(element);
if (column != null) {
sortedColumnList.add(column);
table.removeColumn(column);
}
}
//re-add columns to the table in the order provided from the list
for (Iterator iter = sortedColumnList.iterator(); iter.hasNext();) {
TableColumn element = (TableColumn) iter.next();
table.addColumn(element);
}
String columnWidths = event.getSetting(TABLE_COLUMN_WIDTHS);
tok = new StringTokenizer(columnWidths, ",");
index = 0;
while (tok.hasMoreElements()) {
String element = (String) tok.nextElement();
try {
int width = Integer.parseInt(element);
if (index > (columnModel.getColumnCount() - 1)) {
LogLog.warn(
"loadsettings - failed attempt to set width for index " + index
+ ", width " + element);
} else {
columnModel.getColumn(index).setPreferredWidth(width);
}
index++;
} catch (NumberFormatException e) {
LogLog.error("Error decoding a Table width", e);
}
}
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
repaint();
}
});
}
public JTextField getFindTextField() {
return findField;
}
/**
* Load panel color settings
*/
private void loadColorSettings(File f) {
if (f.exists()) {
ObjectInputStream s = null;
try {
s = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(f)));
Map map = (Map) s.readObject();
colorizer.setRules(map);
} catch (EOFException eof) { //end of file - ignore..
}catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
}
/**
* Iterate over all values in the column and return the longest width
*
* @param index column index
*
* @return longest width - relies on FontMetrics.stringWidth for calculation
*/
private int getMaxColumnWidth(int index) {
FontMetrics metrics = getGraphics().getFontMetrics();
int longestWidth =
metrics.stringWidth(" " + table.getColumnName(index) + " ")
+ (2 * table.getColumnModel().getColumnMargin());
for (int i = 0, j = tableModel.getRowCount(); i < j; i++) {
Component c =
renderer.getTableCellRendererComponent(
table, table.getValueAt(i, index), false, false, i, index);
if (c instanceof JLabel) {
longestWidth =
Math.max(longestWidth, metrics.stringWidth(((JLabel) c).getText()));
}
}
return longestWidth + 5;
}
/**
* ensures the Entry map of all the unque logger names etc, that is used for
* the Filter panel is updated with any new information from the event
*
* @param entry
*/
private void updateOtherModels(ChainsawEventBatchEntry entry) {
LoggingEvent event = entry.getEvent();
/*
* EventContainer is a LoggerNameModel imp, use that for notifing
*/
tableModel.addLoggerName(event.getLoggerName());
filterModel.processNewLoggingEvent(event);
}
/**
* This class receives notification when the Refine focus text field is
* updated, where a backgrounh thread periodically wakes up and checks if
* they have stopped typing yet. This ensures that the filtering of the
* model is not done for every single character typed.
*
* @author Paul Smith psmith
*/
private final class DelayedFilterTextDocumentListener
implements DocumentListener {
private static final long CHECK_PERIOD = 1000;
private final JTextField filterText;
private long lastTimeStamp = System.currentTimeMillis();
private final Thread delayThread;
private final String defaultToolTip;
private String lastFilterText = null;
private DelayedFilterTextDocumentListener(final JTextField filterText) {
super();
this.filterText = filterText;
this.defaultToolTip = filterText.getToolTipText();
this.delayThread =
new Thread(
new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(CHECK_PERIOD);
} catch (InterruptedException e) {
}
if (
(System.currentTimeMillis() - lastTimeStamp) < CHECK_PERIOD) {
// They typed something since the last check. we ignor
// this for a sample period
// LogLog.debug("Typed something since the last check");
} else if (
(System.currentTimeMillis() - lastTimeStamp) < (2 * CHECK_PERIOD)) {
// they stopped typing recently, but have stopped for at least
// 1 sample period. lets apply the filter
// LogLog.debug("Typed something recently applying filter");
if (filterText.getText() != lastFilterText) {
lastFilterText = filterText.getText();
setFilter();
}
} else {
// they stopped typing a while ago, let's forget about it
// LogLog.debug(
// "They stoppped typing a while ago, assuming filter has been applied");
}
}
}
});
delayThread.setPriority(Thread.MIN_PRIORITY);
delayThread.start();
}
/**
* Update timestamp
*
* @param e
*/
public void insertUpdate(DocumentEvent e) {
notifyChange();
}
/**
* Update timestamp
*
* @param e
*/
public void removeUpdate(DocumentEvent e) {
notifyChange();
}
/**
* Update timestamp
*
* @param e
*/
public void changedUpdate(DocumentEvent e) {
notifyChange();
}
/**
* Update timestamp
*/
private void notifyChange() {
this.lastTimeStamp = System.currentTimeMillis();
}
/**
* Update refinement rule based on the entered expression
*/
private void setFilter() {
if (filterText.getText().equals("")) {
ruleMediator.setRefinementRule(null);
filterText.setToolTipText(defaultToolTip);
} else {
try {
ruleMediator.setRefinementRule(
ExpressionRule.getRule(filterText.getText()));
filterText.setToolTipText(defaultToolTip);
} catch (IllegalArgumentException iae) {
filterText.setToolTipText(iae.getMessage());
}
}
}
}
/**
* Update active tooltip
*/
private final class TableColumnDetailMouseListener extends MouseMotionAdapter {
private int currentRow = -1;
private TableColumnDetailMouseListener() {
}
/**
* Update tooltip based on mouse position
*
* @param evt
*/
public void mouseMoved(MouseEvent evt) {
currentPoint = evt.getPoint();
if (preferenceModel.isToolTips()) {
int row = table.rowAtPoint(evt.getPoint());
if ((row == currentRow) || (row == -1)) {
return;
}
currentRow = row;
LoggingEvent event = tableModel.getRow(currentRow);
if (event != null) {
StringBuffer buf = new StringBuffer();
buf.append(detailLayout.getHeader())
.append(detailLayout.format(event)).append(
detailLayout.getFooter());
table.setToolTipText(buf.toString());
}
} else {
table.setToolTipText(null);
}
}
}
/**
* Column data helper class - this class is serialized when saving column
* settings
*/
private class TableColumnData implements Serializable {
static final long serialVersionUID = 5350440293110513986L;
private String colName;
private int index;
private int width;
/**
* Creates a new TableColumnData object.
*
* @param colName
* @param index
* @param width
*/
public TableColumnData(String colName, int index, int width) {
this.colName = colName;
this.index = index;
this.width = width;
}
/**
* Accessor
*
* @return col name
*/
public String getColName() {
return colName;
}
/**
* Accessor
*
* @return displayed index
*/
public int getIndex() {
return index;
}
/**
* Accessor
*
* @return width
*/
public int getWidth() {
return width;
}
/**
* Deserialize the state of the object
*
* @param in
*
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
colName = (String) in.readObject();
index = in.readInt();
width = in.readInt();
}
/**
* Serialize the state of the object
*
* @param out
*
* @throws IOException
*/
private void writeObject(java.io.ObjectOutputStream out)
throws IOException {
out.writeObject(colName);
out.writeInt(index);
out.writeInt(width);
}
}
//if columnmoved or columnremoved callback received, re-apply table's sort index based
//sort column name
private class ChainsawTableColumnModelListener
implements TableColumnModelListener {
private ChainsawTableColumnModelListener() {
}
/**
* If a new column was added to the display and that column was the exception column,
* set the cell editor to the throwablerenderer
*
* @param e
*/
public void columnAdded(TableColumnModelEvent e) {
Enumeration enumeration = table.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
TableColumn column = (TableColumn) enumeration.nextElement();
if (
(column.getModelIndex() + 1) == ChainsawColumns.INDEX_THROWABLE_COL_NAME) {
column.setCellEditor(throwableRenderPanel);
}
if (column.getModelIndex() > 0) {
preferenceModel.setColumnVisible(column.getHeaderValue().toString(), true);
}
}
}
/**
* Update sorted column
*
* @param e
*/
public void columnRemoved(TableColumnModelEvent e) {
table.updateSortedColumn();
}
/**
* Update sorted column
*
* @param e
*/
public void columnMoved(TableColumnModelEvent e) {
table.updateSortedColumn();
}
/**
* Ignore margin changed
*
* @param e
*/
public void columnMarginChanged(ChangeEvent e) {
}
/**
* Ignore selection changed
*
* @param e
*/
public void columnSelectionChanged(ListSelectionEvent e) {
}
}
/**
* Thread that periodically checks if the selected row has changed, and if
* it was, updates the Detail Panel with the detailed Logging information
*/
private class DetailPaneUpdater implements PropertyChangeListener {
private int selectedRow = -1;
private DetailPaneUpdater() {
}
/**
* Update detail pane to display information about the LoggingEvent at index row
*
* @param row
*/
private void setSelectedRow(int row) {
selectedRow = row;
updateDetailPane();
}
/**
* Update detail pane
*/
private void updateDetailPane() {
/*
* Don't bother doing anything if it's not visible
*/
if (!detail.isVisible()) {
return;
}
LoggingEvent event = null;
if (selectedRow != -1) {
event = tableModel.getRow(selectedRow);
if (event != null) {
final StringBuffer buf = new StringBuffer();
buf.append(detailLayout.getHeader())
.append(detailLayout.format(event)).append(
detailLayout.getFooter());
if (buf.length() > 0) {
try {
final Document doc = detail.getEditorKit().createDefaultDocument();
detail.getEditorKit().read(new StringReader(buf.toString()), doc, 0);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
detail.setDocument(doc);
detail.setCaretPosition(0);
}
});
} catch (Exception e) {}
}
}
}
if (event == null) {
try {
final Document doc = detail.getEditorKit().createDefaultDocument();
detail.getEditorKit().read(new StringReader("<html>Nothing selected</html>"), doc, 0);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
detail.setDocument(doc);
detail.setCaretPosition(0);
}
});
} catch (Exception e) {}
}
}
/**
* Update detail pane layout if it's changed
*
* @param arg0
*/
public void propertyChange(PropertyChangeEvent arg0) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
updateDetailPane();
}
});
}
}
}
| src/java/org/apache/log4j/chainsaw/LogPanel.java | /*
* Copyright 1999,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.log4j.chainsaw;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StringReader;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.text.Document;
import org.apache.log4j.Layout;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.chainsaw.color.ColorPanel;
import org.apache.log4j.chainsaw.color.RuleColorizer;
import org.apache.log4j.chainsaw.filter.FilterModel;
import org.apache.log4j.chainsaw.icons.ChainsawIcons;
import org.apache.log4j.chainsaw.icons.LineIconFactory;
import org.apache.log4j.chainsaw.layout.DefaultLayoutFactory;
import org.apache.log4j.chainsaw.layout.EventDetailLayout;
import org.apache.log4j.chainsaw.layout.LayoutEditorPane;
import org.apache.log4j.chainsaw.messages.MessageCenter;
import org.apache.log4j.chainsaw.prefs.LoadSettingsEvent;
import org.apache.log4j.chainsaw.prefs.Profileable;
import org.apache.log4j.chainsaw.prefs.SaveSettingsEvent;
import org.apache.log4j.chainsaw.prefs.SettingsManager;
import org.apache.log4j.helpers.Constants;
import org.apache.log4j.helpers.ISO8601DateFormat;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.rule.ExpressionRule;
import org.apache.log4j.rule.ExpressionRuleContext;
import org.apache.log4j.rule.Rule;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.LoggingEventFieldResolver;
/**
* A LogPanel provides a view to a collection of LoggingEvents.<br>
* <br>
* As events are received, the keywords in the 'tab identifier' application
* preference are replaced with the values from the received event. The
* main application uses this expression to route received LoggingEvents to
* individual LogPanels which match each event's resolved expression.<br>
* <br>
* The LogPanel's capabilities can be broken up into four areas:<br>
* <ul><li> toolbar - provides 'find' and 'refine focus' features
* <li> logger tree - displays a tree of the logger hierarchy, which can be used
* to filter the display
* <li> table - displays the events which pass the filtering rules
* <li>detail panel - displays information about the currently selected event
* </ul>
* Here is a complete list of LogPanel's capabilities:<br>
* <ul><li>display selected LoggingEvent row number and total LoggingEvent count
* <li>pause or unpause reception of LoggingEvents
* <li>configure, load and save column settings (displayed columns, order, width)
* <li>configure, load and save color rules
* filter displayed LoggingEvents based on the logger tree settings
* <li>filter displayed LoggingEvents based on a 'refine focus' expression
* (evaluates only those LoggingEvents which pass the logger tree filter
* <li>colorize LoggingEvents based on expressions
* <li>hide, show and configure the detail pane and tooltip
* <li>configure the formatting of the logger, level and timestamp fields
* <li>dock or undock
* <li>table displays first line of exception, but when cell is clicked, a
* popup opens to display the full stack trace
* <li>find
* <li>scroll to bottom
* <li>sort
* <li>provide a context menu which can be used to build color or display expressions
* <li>hide or show the logger tree
* <li>toggle the container storing the LoggingEvents to use either a
* CyclicBuffer (defaults to max size of 5000, but configurable through
* CHAINSAW_CAPACITY system property) or ArrayList (no max size)
* <li>use the mouse context menu to 'best-fit' columns, define display
* expression filters based on mouse location and access other capabilities
*</ul>
*
*@see org.apache.log4j.chainsaw.color.ColorPanel
*@see org.apache.log4j.rule.ExpressionRule
*@see org.apache.log4j.spi.LoggingEventFieldResolver
*
*@author Scott Deboy (sdeboy at apache.org)
*@author Paul Smith (psmith at apache.org)
*@author Stephen Pain
*
*/
public class LogPanel extends DockablePanel implements EventBatchListener,
Profileable {
private static final double DEFAULT_DETAIL_SPLIT_LOCATION = .5;
private static final double DEFAULT_LOG_TREE_SPLIT_LOCATION = .25;
private final String identifier;
private final ChainsawStatusBar statusBar;
private final JFrame preferencesFrame = new JFrame();
private final JFrame colorFrame = new JFrame();
private final JFrame undockedFrame;
private final DockablePanel externalPanel;
private final Action dockingAction;
private final JToolBar undockedToolbar;
private final JSortTable table;
private final TableColorizingRenderer renderer;
private final EventContainer tableModel;
private final ThrowableRenderPanel throwableRenderPanel;
private final JEditorPane detail;
private final JSplitPane lowerPanel;
private final DetailPaneUpdater detailPaneUpdater;
private final JPanel detailPanel = new JPanel(new BorderLayout());
private final JSplitPane nameTreeAndMainPanelSplit;
private final LoggerNameTreePanel logTreePanel;
private final LogPanelPreferenceModel preferenceModel =
new LogPanelPreferenceModel();
private final LogPanelPreferencePanel preferencesPanel =
new LogPanelPreferencePanel(preferenceModel);
private final FilterModel filterModel = new FilterModel();
private final RuleColorizer colorizer = new RuleColorizer();
private final RuleMediator ruleMediator = new RuleMediator();
private Layout detailLayout = new EventDetailLayout();
private double lastDetailPanelSplitLocation = DEFAULT_DETAIL_SPLIT_LOCATION;
private double lastLogTreePanelSplitLocation =
DEFAULT_LOG_TREE_SPLIT_LOCATION;
private boolean bypassScrollFind;
private Point currentPoint;
private boolean scroll;
private boolean paused = false;
private Rule findRule;
private final JPanel findPanel;
private JTextField findField;
private int dividerSize;
static final String TABLE_COLUMN_ORDER = "table.columns.order";
static final String TABLE_COLUMN_WIDTHS = "table.columns.widths";
static final String COLUMNS_EXTENSION = ".columns";
static final String COLORS_EXTENSION = ".colors";
private int previousLastIndex = -1;
private final DateFormat timestampExpressionFormat = new SimpleDateFormat(Constants.TIMESTAMP_RULE_FORMAT);
/**
* Creates a new LogPanel object. If a LogPanel with this identifier has
* been loaded previously, reload settings saved on last exit.
*
* @param statusBar shared status bar, provided by main application
* @param identifier used to load and save settings
*/
public LogPanel(final ChainsawStatusBar statusBar, final String identifier, int cyclicBufferSize) {
this.identifier = identifier;
this.statusBar = statusBar;
setLayout(new BorderLayout());
scroll = true;
findPanel = new JPanel();
final Map columnNameKeywordMap = new HashMap();
columnNameKeywordMap.put(
ChainsawConstants.CLASS_COL_NAME, LoggingEventFieldResolver.CLASS_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.FILE_COL_NAME, LoggingEventFieldResolver.FILE_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.LEVEL_COL_NAME, LoggingEventFieldResolver.LEVEL_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.LINE_COL_NAME, LoggingEventFieldResolver.LINE_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.LOGGER_COL_NAME, LoggingEventFieldResolver.LOGGER_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.NDC_COL_NAME, LoggingEventFieldResolver.NDC_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.MESSAGE_COL_NAME, LoggingEventFieldResolver.MSG_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.THREAD_COL_NAME, LoggingEventFieldResolver.THREAD_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.THROWABLE_COL_NAME,
LoggingEventFieldResolver.EXCEPTION_FIELD);
columnNameKeywordMap.put(
ChainsawConstants.TIMESTAMP_COL_NAME,
LoggingEventFieldResolver.TIMESTAMP_FIELD);
preferencesFrame.setTitle("'" + identifier + "' Log Panel Preferences");
preferencesFrame.setIconImage(
((ImageIcon) ChainsawIcons.ICON_PREFERENCES).getImage());
preferencesFrame.getContentPane().add(preferencesPanel);
preferencesFrame.setSize(640, 480);
preferencesPanel.setOkCancelActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
preferencesFrame.setVisible(false);
}
});
setDetailPaneConversionPattern(
DefaultLayoutFactory.getDefaultPatternLayout());
((EventDetailLayout) detailLayout).setConversionPattern(
DefaultLayoutFactory.getDefaultPatternLayout());
undockedFrame = new JFrame(identifier);
undockedFrame.setDefaultCloseOperation(
WindowConstants.DO_NOTHING_ON_CLOSE);
if (ChainsawIcons.UNDOCKED_ICON != null) {
undockedFrame.setIconImage(
new ImageIcon(ChainsawIcons.UNDOCKED_ICON).getImage());
}
externalPanel = new DockablePanel();
externalPanel.setLayout(new BorderLayout());
undockedFrame.getContentPane().add(externalPanel);
undockedFrame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dock();
}
});
undockedToolbar = createDockwindowToolbar();
externalPanel.add(undockedToolbar, BorderLayout.NORTH);
undockedFrame.pack();
/*
* Menus on which the preferencemodels rely
*/
/**
* Setup a popup menu triggered for Timestamp column to allow time stamp
* format changes
*/
final JPopupMenu dateFormatChangePopup = new JPopupMenu();
final JRadioButtonMenuItem isoButton =
new JRadioButtonMenuItem(
new AbstractAction("Use ISO8601Format") {
public void actionPerformed(ActionEvent e) {
preferenceModel.setDateFormatPattern("ISO8601");
}
});
final JRadioButtonMenuItem simpleTimeButton =
new JRadioButtonMenuItem(
new AbstractAction("Use simple time") {
public void actionPerformed(ActionEvent e) {
preferenceModel.setDateFormatPattern("HH:mm:ss");
}
});
ButtonGroup dfBG = new ButtonGroup();
dfBG.add(isoButton);
dfBG.add(simpleTimeButton);
isoButton.setSelected(true);
dateFormatChangePopup.add(isoButton);
dateFormatChangePopup.add(simpleTimeButton);
final JCheckBoxMenuItem menuItemToggleToolTips =
new JCheckBoxMenuItem("Show ToolTips");
menuItemToggleToolTips.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
preferenceModel.setToolTips(menuItemToggleToolTips.isSelected());
}
});
menuItemToggleToolTips.setIcon(new ImageIcon(ChainsawIcons.TOOL_TIP));
final JCheckBoxMenuItem menuItemLoggerTree =
new JCheckBoxMenuItem("Show Logger Tree panel");
menuItemLoggerTree.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
preferenceModel.setLogTreePanelVisible(
menuItemLoggerTree.isSelected());
}
});
menuItemLoggerTree.setIcon(new ImageIcon(ChainsawIcons.WINDOW_ICON));
final JCheckBoxMenuItem menuItemScrollBottom =
new JCheckBoxMenuItem("Scroll to bottom");
menuItemScrollBottom.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
preferenceModel.setScrollToBottom(menuItemScrollBottom.isSelected());
}
});
menuItemScrollBottom.setIcon(
new ImageIcon(ChainsawIcons.SCROLL_TO_BOTTOM));
final JCheckBoxMenuItem menuItemToggleDetails =
new JCheckBoxMenuItem("Show Detail Pane");
menuItemToggleDetails.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
preferenceModel.setDetailPaneVisible(
menuItemToggleDetails.isSelected());
}
});
menuItemToggleDetails.setIcon(new ImageIcon(ChainsawIcons.INFO));
/*
* add preferencemodel listeners
*/
preferenceModel.addPropertyChangeListener(
"levelIcons",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
renderer.setLevelUseIcons(
((Boolean) evt.getNewValue()).booleanValue());
table.tableChanged(new TableModelEvent(tableModel));
}
});
preferenceModel.addPropertyChangeListener(
"detailPaneVisible",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean newValue = ((Boolean) evt.getNewValue()).booleanValue();
if (newValue) {
showDetailPane();
} else {
hideDetailPane();
}
}
});
preferenceModel.addPropertyChangeListener(
"logTreePanelVisible",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean newValue = ((Boolean) evt.getNewValue()).booleanValue();
if (newValue) {
showLogTreePanel();
} else {
hideLogTreePanel();
}
}
});
preferenceModel.addPropertyChangeListener(
"toolTips",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
renderer.setToolTipsVisible(
((Boolean) evt.getNewValue()).booleanValue());
}
});
preferenceModel.addPropertyChangeListener(
"visibleColumns",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
TableColumnModel columnModel = table.getColumnModel();
for (int i = 0; i < columnModel.getColumnCount(); i++) {
TableColumn column = columnModel.getColumn(i);
if (
!preferenceModel.isColumnVisible(
column.getHeaderValue().toString())) {
columnModel.removeColumn(column);
}
}
Set columnSet = new HashSet();
Enumeration enumeration = columnModel.getColumns();
while (enumeration.hasMoreElements()) {
TableColumn column = (TableColumn) enumeration.nextElement();
columnSet.add(column.getHeaderValue());
}
for (
Iterator iter = ChainsawColumns.getColumnsNames().iterator();
iter.hasNext();) {
String column = (String) iter.next();
if (
preferenceModel.isColumnVisible(column)
&& !columnSet.contains(column)) {
TableColumn newCol =
new TableColumn(
ChainsawColumns.getColumnsNames().indexOf(column));
newCol.setHeaderValue(column);
columnModel.addColumn(newCol);
}
}
}
});
PropertyChangeListener datePrefsChangeListener =
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
LogPanelPreferenceModel model =
(LogPanelPreferenceModel) evt.getSource();
isoButton.setSelected(model.isUseISO8601Format());
simpleTimeButton.setSelected(
!model.isUseISO8601Format() && !model.isCustomDateFormat());
if (model.isUseISO8601Format()) {
renderer.setDateFormatter(new ISO8601DateFormat());
} else {
renderer.setDateFormatter(
new SimpleDateFormat(model.getDateFormatPattern()));
}
table.tableChanged(new TableModelEvent(tableModel));
}
};
preferenceModel.addPropertyChangeListener(
"dateFormatPattern", datePrefsChangeListener);
preferenceModel.addPropertyChangeListener(
"dateFormatPattern", datePrefsChangeListener);
preferenceModel.addPropertyChangeListener(
"loggerPrecision",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
LogPanelPreferenceModel model =
(LogPanelPreferenceModel) evt.getSource();
renderer.setLoggerPrecision(model.getLoggerPrecision());
table.tableChanged(new TableModelEvent(tableModel));
}
});
preferenceModel.addPropertyChangeListener(
"toolTips",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean value = ((Boolean) evt.getNewValue()).booleanValue();
menuItemToggleToolTips.setSelected(value);
}
});
preferenceModel.addPropertyChangeListener(
"logTreePanelVisible",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean value = ((Boolean) evt.getNewValue()).booleanValue();
menuItemLoggerTree.setSelected(value);
}
});
preferenceModel.addPropertyChangeListener(
"scrollToBottom",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean value = ((Boolean) evt.getNewValue()).booleanValue();
menuItemScrollBottom.setSelected(value);
scroll = value;
if (scroll) {
table.scrollToBottom(table.columnAtPoint(table.getVisibleRect().getLocation()));
}
}
});
preferenceModel.addPropertyChangeListener(
"detailPaneVisible",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean value = ((Boolean) evt.getNewValue()).booleanValue();
menuItemToggleDetails.setSelected(value);
}
});
/*
*End of preferenceModel listeners
*/
tableModel = new ChainsawCyclicBufferTableModel(cyclicBufferSize);
table = new JSortTable(tableModel);
//add a listener to update the 'refine focus'
tableModel.addNewKeyListener(new NewKeyListener() {
public void newKeyAdded(NewKeyEvent e) {
columnNameKeywordMap.put(e.getKey(), "PROP." + e.getKey());
}
});
/*
* Set the Display rule to use the mediator, the model will add itself as
* a property change listener and update itself when the rule changes.
*/
tableModel.setDisplayRule(ruleMediator);
tableModel.addEventCountListener(
new EventCountListener() {
public void eventCountChanged(int currentCount, int totalCount) {
if (LogPanel.this.isVisible()) {
statusBar.setSelectedLine(
table.getSelectedRow() + 1, currentCount, totalCount);
}
}
});
tableModel.addEventCountListener(
new EventCountListener() {
final NumberFormat formatter = NumberFormat.getPercentInstance();
boolean warning75 = false;
boolean warning100 = false;
public void eventCountChanged(int currentCount, int totalCount) {
if (tableModel.isCyclic()) {
double percent =
((double) totalCount) / ((ChainsawCyclicBufferTableModel) tableModel)
.getMaxSize();
String msg = null;
if ((percent > 0.75) && (percent < 1.0) && !warning75) {
msg =
"Warning :: " + formatter.format(percent) + " of the '"
+ getIdentifier() + "' buffer has been used";
warning75 = true;
} else if ((percent >= 1.0) && !warning100) {
msg =
"Warning :: " + formatter.format(percent) + " of the '"
+ getIdentifier()
+ "' buffer has been used. Older events are being discarded.";
warning100 = true;
}
if (msg != null) {
MessageCenter.getInstance().getLogger().info(msg);
}
}
}
});
/*
* Logger tree panel
*
*/
LogPanelLoggerTreeModel logTreeModel = new LogPanelLoggerTreeModel();
logTreePanel = new LoggerNameTreePanel(logTreeModel, preferenceModel);
tableModel.addLoggerNameListener(logTreeModel);
/**
* Set the LoggerRule to be the LoggerTreePanel, as this visual component
* is a rule itself, and the RuleMediator will automatically listen when
* it's rule state changes.
*/
ruleMediator.setLoggerRule(logTreePanel);
colorizer.setLoggerRule(logTreePanel.getLoggerColorRule());
/*
* Color rule frame and panel
*/
colorFrame.setTitle("'" + identifier + "' Color Filter");
colorFrame.setIconImage(
((ImageIcon) ChainsawIcons.ICON_PREFERENCES).getImage());
final ColorPanel colorPanel = new ColorPanel(colorizer, filterModel);
colorFrame.getContentPane().add(colorPanel);
colorPanel.setCloseActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
colorFrame.setVisible(false);
}
});
colorizer.addPropertyChangeListener(
"colorrule",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (table != null) {
table.repaint();
}
}
});
/*
* Table definition. Actual construction is above (next to tablemodel)
*/
table.setRowHeight(20);
table.setShowGrid(false);
table.getColumnModel().addColumnModelListener(
new ChainsawTableColumnModelListener());
table.setAutoCreateColumnsFromModel(false);
table.addMouseMotionListener(new TableColumnDetailMouseListener());
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//set valueisadjusting if holding down a key - don't process setdetail events
table.addKeyListener(
new KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
synchronized (detail) {
table.getSelectionModel().setValueIsAdjusting(true);
detail.notify();
}
}
public void keyReleased(KeyEvent e) {
synchronized (detail) {
table.getSelectionModel().setValueIsAdjusting(false);
detail.notify();
}
}
});
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
if (
((evt.getFirstIndex() == evt.getLastIndex())
&& (evt.getFirstIndex() > 0)) || (evt.getValueIsAdjusting())) {
return;
}
boolean lastIndexOnLastRow = (evt.getLastIndex() == (table.getRowCount() - 1));
boolean lastIndexSame = (previousLastIndex == evt.getLastIndex());
/*
* when scroll-to-bottom is active, here is what events look like:
* rowcount-1: 227, last: 227, previous last: 191..first: 191
*
* when the user has unselected the bottom row, here is what the events look like:
* rowcount-1: 227, last: 227, previous last: 227..first: 222
*
* note: previouslast is set after it is evaluated in the bypass scroll check
*/
//System.out.println("rowcount: " + (table.getRowCount() - 1) + ", last: " + evt.getLastIndex() +", previous last: " + previousLastIndex + "..first: " + evt.getFirstIndex());
boolean bypassScrollSelection = (lastIndexOnLastRow && lastIndexSame && previousLastIndex != evt.getFirstIndex());
if (bypassScrollSelection && scroll && table.getRowCount() > 0) {
preferenceModel.setScrollToBottom(false);
}
previousLastIndex = evt.getLastIndex();
final ListSelectionModel lsm = (ListSelectionModel) evt.getSource();
if (lsm.isSelectionEmpty()) {
if (isVisible()) {
statusBar.setNothingSelected();
}
if (detail.getDocument().getDefaultRootElement() != null) {
detailPaneUpdater.setSelectedRow(-1);
}
} else {
if (table.getSelectedRow() > -1) {
int selectedRow = table.getSelectedRow();
if (isVisible()) {
updateStatusBar();
}
try {
if (tableModel.getRowCount() >= selectedRow) {
detailPaneUpdater.setSelectedRow(table.getSelectedRow());
} else {
detailPaneUpdater.setSelectedRow(-1);
}
} catch (Exception e) {
e.printStackTrace();
detailPaneUpdater.setSelectedRow(-1);
}
}
}
}
});
renderer = new TableColorizingRenderer(colorizer);
renderer.setToolTipsVisible(preferenceModel.isToolTips());
table.setDefaultRenderer(Object.class, renderer);
/*
* Throwable popup
*/
throwableRenderPanel = new ThrowableRenderPanel();
final JDialog detailDialog = new JDialog((JFrame) null, true);
Container container = detailDialog.getContentPane();
final JTextArea detailArea = new JTextArea(10, 40);
detailArea.setEditable(false);
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
container.add(new JScrollPane(detailArea));
detailDialog.pack();
throwableRenderPanel.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object o = table.getValueAt(
table.getSelectedRow(), table.getSelectedColumn());
if (o == null) {
//no row selected - ignore
LogLog.debug("no row selected - unable to display throwable popup");
return;
}
detailDialog.setTitle(
table.getColumnName(table.getSelectedColumn()) + " detail...");
if (o instanceof String[]) {
StringBuffer buf = new StringBuffer();
String[] ti = (String[]) o;
buf.append(ti[0]).append("\n");
for (int i = 1; i < ti.length; i++) {
buf.append(ti[i]).append("\n ");
}
detailArea.setText(buf.toString());
} else {
detailArea.setText((o == null) ? "" : o.toString());
}
detailDialog.setLocation(lowerPanel.getLocationOnScreen());
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
detailDialog.setVisible(true);
}
});
}
});
/*
* We listen for new Key's coming in so we can get them automatically
* added as columns
*/
tableModel.addNewKeyListener(
new NewKeyListener() {
public void newKeyAdded(NewKeyEvent e) {
TableColumn col = new TableColumn(e.getNewModelIndex());
col.setHeaderValue(e.getKey());
table.addColumn(col);
}
});
tableModel.addPropertyChangeListener(
"cyclic",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent arg0) {
if (tableModel.isCyclic()) {
MessageCenter.getInstance().getLogger().warn(
"Changed to Cyclic Mode. Maximum # events kept: "
+ tableModel.getMaxSize());
} else {
MessageCenter.getInstance().getLogger().warn(
"Changed to Unlimited Mode. Warning, you may run out of memory.");
}
}
});
table.getTableHeader().addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
checkEvent(e);
}
public void mousePressed(MouseEvent e) {
checkEvent(e);
}
public void mouseReleased(MouseEvent e) {
checkEvent(e);
}
private void checkEvent(MouseEvent e) {
if (e.isPopupTrigger()) {
TableColumnModel colModel = table.getColumnModel();
int index = colModel.getColumnIndexAtX(e.getX());
int modelIndex = colModel.getColumn(index).getModelIndex();
if ((modelIndex + 1) == ChainsawColumns.INDEX_TIMESTAMP_COL_NAME) {
dateFormatChangePopup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
});
/*
* Upper panel definition
*/
JPanel upperPanel = new JPanel(new BorderLayout());
upperPanel.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0));
final JLabel filterLabel = new JLabel("Refine focus on: ");
filterLabel.setFont(filterLabel.getFont().deriveFont(Font.BOLD));
JPanel upperLeftPanel =
new JPanel(new FlowLayout(FlowLayout.CENTER, 3, 0));
upperLeftPanel.add(filterLabel);
//hold a reference to the combobox model so that we can check to prevent duplicates
final Vector v = new Vector();
final JComboBox filterCombo = new JComboBox(v);
final JTextField filterText;
if (filterCombo.getEditor().getEditorComponent() instanceof JTextField) {
String comboToolTipText =
"Enter an expression, press enter to add to list";
filterText = (JTextField) filterCombo.getEditor().getEditorComponent();
filterText.setToolTipText(comboToolTipText);
filterText.addKeyListener(
new ExpressionRuleContext(filterModel, filterText));
filterText.getDocument().addDocumentListener(
new DelayedFilterTextDocumentListener(filterText));
filterCombo.setEditable(true);
filterCombo.addActionListener(
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxEdited")) {
try {
//verify the expression is valid
ExpressionRule.getRule(
filterCombo.getSelectedItem().toString());
} catch (IllegalArgumentException iae) {
//don't add expressions that aren't valid
return;
}
//should be 'valid expression' check
if (!(v.contains(filterCombo.getSelectedItem()))) {
filterCombo.addItem(filterCombo.getSelectedItem());
}
}
}
});
upperPanel.add(filterCombo, BorderLayout.CENTER);
} else {
filterText = new JTextField();
filterText.setToolTipText("Enter an expression");
filterText.addKeyListener(
new ExpressionRuleContext(filterModel, filterText));
filterText.getDocument().addDocumentListener(
new DelayedFilterTextDocumentListener(filterText));
upperPanel.add(filterText, BorderLayout.CENTER);
}
upperPanel.add(upperLeftPanel, BorderLayout.WEST);
JPanel upperRightPanel =
new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
upperPanel.add(upperRightPanel, BorderLayout.EAST);
/*
* Detail pane definition
*/
detail = new JEditorPane(ChainsawConstants.DETAIL_CONTENT_TYPE, "");
detail.setEditable(false);
detailPaneUpdater = new DetailPaneUpdater();
addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
detailPaneUpdater.updateDetailPane();
}
public void focusLost(FocusEvent e) {
}
});
tableModel.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
detailPaneUpdater.setSelectedRow(table.getSelectedRow());
}
});
addPropertyChangeListener(
"detailPaneConversionPattern", detailPaneUpdater);
final JScrollPane detailPane = new JScrollPane(detail);
detailPane.setPreferredSize(new Dimension(900, 50));
detailPanel.add(detailPane, BorderLayout.CENTER);
JPanel eventsAndStatusPanel = new JPanel(new BorderLayout());
final JScrollPane eventsPane = new JScrollPane(table);
eventsAndStatusPanel.add(eventsPane, BorderLayout.CENTER);
final JPanel statusLabelPanel = new JPanel();
statusLabelPanel.setLayout(new BorderLayout());
statusLabelPanel.add(upperPanel, BorderLayout.CENTER);
eventsAndStatusPanel.add(statusLabelPanel, BorderLayout.NORTH);
lowerPanel =
new JSplitPane(
JSplitPane.VERTICAL_SPLIT, eventsAndStatusPanel, detailPanel);
dividerSize = lowerPanel.getDividerSize();
lowerPanel.setDividerLocation(-1);
lowerPanel.setResizeWeight(1.0);
lowerPanel.setBorder(null);
lowerPanel.setContinuousLayout(true);
if (preferenceModel.isDetailPaneVisible()) {
showDetailPane();
} else {
hideDetailPane();
}
/*
* Detail panel layout editor
*/
final JToolBar detailToolbar = new JToolBar(SwingConstants.HORIZONTAL);
detailToolbar.setFloatable(false);
final LayoutEditorPane layoutEditorPane = new LayoutEditorPane();
final JDialog layoutEditorDialog =
new JDialog((JFrame) null, "Pattern Editor");
layoutEditorDialog.getContentPane().add(layoutEditorPane);
layoutEditorDialog.setSize(640, 480);
layoutEditorPane.addCancelActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
layoutEditorDialog.setVisible(false);
}
});
layoutEditorPane.addOkActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
setDetailPaneConversionPattern(
layoutEditorPane.getConversionPattern());
layoutEditorDialog.setVisible(false);
}
});
Action editDetailAction =
new AbstractAction(
"Edit...", new ImageIcon(ChainsawIcons.ICON_EDIT_RECEIVER)) {
public void actionPerformed(ActionEvent e) {
layoutEditorPane.setConversionPattern(
getDetailPaneConversionPattern());
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
Point p =
new Point(
((int) ((size.getWidth() / 2)
- (layoutEditorDialog.getSize().getWidth() / 2))),
((int) ((size.getHeight() / 2)
- (layoutEditorDialog.getSize().getHeight() / 2))));
layoutEditorDialog.setLocation(p);
layoutEditorDialog.setVisible(true);
}
};
editDetailAction.putValue(
Action.SHORT_DESCRIPTION,
"opens a Dialog window to Edit the Pattern Layout text");
final SmallButton editDetailButton = new SmallButton(editDetailAction);
editDetailButton.setText(null);
detailToolbar.add(Box.createHorizontalGlue());
detailToolbar.add(editDetailButton);
detailToolbar.addSeparator();
detailToolbar.add(Box.createHorizontalStrut(5));
Action closeDetailAction =
new AbstractAction(null, LineIconFactory.createCloseIcon()) {
public void actionPerformed(ActionEvent arg0) {
preferenceModel.setDetailPaneVisible(false);
}
};
closeDetailAction.putValue(
Action.SHORT_DESCRIPTION, "Hides the Detail Panel");
SmallButton closeDetailButton = new SmallButton(closeDetailAction);
detailToolbar.add(closeDetailButton);
detailPanel.add(detailToolbar, BorderLayout.NORTH);
JPopupMenu editDetailPopupMenu = new JPopupMenu();
editDetailPopupMenu.add(editDetailAction);
editDetailPopupMenu.addSeparator();
final ButtonGroup layoutGroup = new ButtonGroup();
JRadioButtonMenuItem defaultLayoutRadio =
new JRadioButtonMenuItem(
new AbstractAction("Set to Default Layout") {
public void actionPerformed(ActionEvent e) {
setDetailPaneConversionPattern(
DefaultLayoutFactory.getDefaultPatternLayout());
}
});
editDetailPopupMenu.add(defaultLayoutRadio);
layoutGroup.add(defaultLayoutRadio);
defaultLayoutRadio.setSelected(true);
JRadioButtonMenuItem tccLayoutRadio =
new JRadioButtonMenuItem(
new AbstractAction("Set to TCCLayout") {
public void actionPerformed(ActionEvent e) {
setDetailPaneConversionPattern(
PatternLayout.TTCC_CONVERSION_PATTERN);
}
});
editDetailPopupMenu.add(tccLayoutRadio);
layoutGroup.add(tccLayoutRadio);
PopupListener editDetailPopupListener =
new PopupListener(editDetailPopupMenu);
detail.addMouseListener(editDetailPopupListener);
/*
* Logger tree splitpane definition
*/
nameTreeAndMainPanelSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, logTreePanel, lowerPanel);
nameTreeAndMainPanelSplit.setToolTipText("Still under development....");
nameTreeAndMainPanelSplit.setDividerLocation(-1);
add(nameTreeAndMainPanelSplit, BorderLayout.CENTER);
if (isLogTreeVisible()) {
showLogTreePanel();
} else {
hideLogTreePanel();
}
/*
* Other menu items
*/
final JMenuItem menuItemBestFit = new JMenuItem("Best fit column");
menuItemBestFit.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (currentPoint != null) {
int column = table.columnAtPoint(currentPoint);
int maxWidth = getMaxColumnWidth(column);
table.getColumnModel().getColumn(column).setPreferredWidth(
maxWidth);
}
}
});
JMenuItem menuItemColorPanel = new JMenuItem("LogPanel Color Filter...");
menuItemColorPanel.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
showColorPreferences();
}
});
menuItemColorPanel.setIcon(ChainsawIcons.ICON_PREFERENCES);
JMenuItem menuItemLogPanelPreferences =
new JMenuItem("LogPanel Preferences...");
menuItemLogPanelPreferences.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
showPreferences();
}
});
menuItemLogPanelPreferences.setIcon(ChainsawIcons.ICON_PREFERENCES);
final JMenuItem menuItemFocusOn =
new JMenuItem("Set 'refine focus' field");
menuItemFocusOn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (currentPoint != null) {
String operator = "==";
int column = table.columnAtPoint(currentPoint);
int row = table.rowAtPoint(currentPoint);
String colName = table.getColumnName(column);
String value = "";
if (colName.equalsIgnoreCase(ChainsawConstants.TIMESTAMP_COL_NAME)) {
value = timestampExpressionFormat.format(new Date(table.getValueAt(row, column).toString()));
} else {
Object o = table.getValueAt(row, column);
if (o != null) {
if (o instanceof String[]) {
value = ((String[]) o)[0];
operator = "~=";
} else {
value = o.toString();
}
}
}
if (columnNameKeywordMap.containsKey(colName)) {
filterText.setText(
columnNameKeywordMap.get(colName).toString() + " " + operator
+ " '" + value + "'");
}
}
}
});
final JMenuItem menuDefineAddCustomFilter =
new JMenuItem("Add to 'refine focus' field");
menuDefineAddCustomFilter.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (currentPoint != null) {
String operator = "==";
int column = table.columnAtPoint(currentPoint);
int row = table.rowAtPoint(currentPoint);
String colName = table.getColumnName(column);
String value = "";
if (colName.equalsIgnoreCase(ChainsawConstants.TIMESTAMP_COL_NAME)) {
JComponent comp =
(JComponent) table.getCellRenderer(row, column);
if (comp instanceof JLabel) {
value = ((JLabel) comp).getText();
}
} else {
Object o = table.getValueAt(row, column).toString();
if (o instanceof String[]) {
value = ((String[]) o)[0];
operator = "~=";
} else {
value = o.toString();
}
}
if (columnNameKeywordMap.containsKey(colName)) {
filterText.setText(
filterText.getText() + " && "
+ columnNameKeywordMap.get(colName).toString() + " "
+ operator + " '" + value + "'");
}
}
}
});
final JPopupMenu p = new JPopupMenu();
final Action clearFocusAction =
new AbstractAction("Clear 'refine focus' field") {
public void actionPerformed(ActionEvent e) {
filterText.setText(null);
ruleMediator.setRefinementRule(null);
}
};
final JMenuItem menuItemToggleDock = new JMenuItem("Undock/dock");
dockingAction =
new AbstractAction("Undock") {
public void actionPerformed(ActionEvent evt) {
if (isDocked()) {
undock();
} else {
dock();
}
}
};
dockingAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.UNDOCK));
menuItemToggleDock.setAction(dockingAction);
/*
* Popup definition
*/
p.add(clearFocusAction);
p.add(menuItemFocusOn);
p.add(menuDefineAddCustomFilter);
p.add(new JSeparator());
p.add(menuItemBestFit);
p.add(new JSeparator());
p.add(menuItemToggleDetails);
p.add(menuItemLoggerTree);
p.add(menuItemToggleToolTips);
p.add(new JSeparator());
p.add(menuItemScrollBottom);
p.add(new JSeparator());
p.add(menuItemToggleDock);
p.add(new JSeparator());
p.add(menuItemColorPanel);
p.add(menuItemLogPanelPreferences);
final PopupListener popupListener = new PopupListener(p);
eventsPane.addMouseListener(popupListener);
table.addMouseListener(popupListener);
}
/**
* Accessor
*
* @return scrollToBottom
*
*/
public boolean isScrollToBottom() {
return preferenceModel.isScrollToBottom();
}
/**
* Mutator
*
*/
public void toggleScrollToBottom() {
preferenceModel.setScrollToBottom(!preferenceModel.isScrollToBottom());
}
/**
* Accessor
*
* @return namespace
*
* @see Profileable
*/
public String getNamespace() {
return getIdentifier();
}
/**
* Accessor
*
* @return identifier
*
* @see EventBatchListener
*/
public String getInterestedIdentifier() {
return getIdentifier();
}
/**
* Process events associated with the identifier. Currently assumes it only
* receives events which share this LogPanel's identifier
*
* @param ident identifier shared by events
* @param eventBatchEntrys list of EventBatchEntry objects
*/
public void receiveEventBatch(String ident, List eventBatchEntrys) {
/*
* if this panel is paused, we totally ignore events
*/
if (isPaused()) {
return;
}
//table.getSelectionModel().setValueIsAdjusting(true);
boolean rowAdded = false;
int first = tableModel.getLastAdded() + 1;
for (Iterator iter = eventBatchEntrys.iterator(); iter.hasNext();) {
ChainsawEventBatchEntry entry = (ChainsawEventBatchEntry) iter.next();
updateOtherModels(entry);
boolean isCurrentRowAdded = tableModel.isAddRow(entry.getEvent(), true);
rowAdded = rowAdded ? true : isCurrentRowAdded;
}
table.getSelectionModel().setValueIsAdjusting(false);
//tell the model to notify the count listeners
tableModel.notifyCountListeners();
if (rowAdded) {
if (tableModel.isSortEnabled()) {
tableModel.sort();
}
tableModel.fireTableEvent(
first, tableModel.getLastAdded(), eventBatchEntrys.size());
if (scroll && !bypassScrollFind) {
table.scrollToBottom(
table.columnAtPoint(table.getVisibleRect().getLocation()));
}
//always update detail pane (since we may be using a cyclic buffer which is full)
detailPaneUpdater.setSelectedRow(table.getSelectedRow());
}
}
/**
* Load settings from the panel preference model
*
* @param event
*
* @see LogPanelPreferenceModel
*/
public void loadSettings(LoadSettingsEvent event) {
preferenceModel.setLevelIcons(event.asBoolean("levelIcons"));
preferenceModel.setDateFormatPattern(
event.getSetting("dateFormatPattern"));
preferenceModel.setLoggerPrecision(event.getSetting("loggerPrecision"));
preferenceModel.setToolTips(event.asBoolean("toolTips"));
preferenceModel.setScrollToBottom(event.asBoolean("scrollToBottom"));
scroll = event.asBoolean("scrollToBottom");
preferenceModel.setLogTreePanelVisible(
event.asBoolean("logTreePanelVisible"));
preferenceModel.setDetailPaneVisible(event.asBoolean("detailPaneVisible"));
logTreePanel.ignore(event.getSettingsStartingWith("Logger.Ignore."));
//first attempt to load encoded file
File f =
new File(
SettingsManager.getInstance().getSettingsDirectory(), URLEncoder.encode(identifier) + COLUMNS_EXTENSION);
if (!f.exists()) {
f =
new File(
SettingsManager.getInstance().getSettingsDirectory(), identifier + COLUMNS_EXTENSION);
}
if (f.exists()) {
loadColumnSettings(f);
} else {
loadDefaultColumnSettings(event);
}
//first attempt to load encoded file
File f2 =
new File(
SettingsManager.getInstance().getSettingsDirectory(), URLEncoder.encode(identifier) + COLORS_EXTENSION);
if (!f2.exists()) {
f2 =
new File(
SettingsManager.getInstance().getSettingsDirectory(), identifier + COLORS_EXTENSION);
}
if (f2.exists()) {
loadColorSettings(f2);
}
}
/**
* Save preferences to the panel preference model
*
* @param event
*
* @see LogPanelPreferenceModel
*/
public void saveSettings(SaveSettingsEvent event) {
event.saveSetting("levelIcons", preferenceModel.isLevelIcons());
event.saveSetting(
"dateFormatPattern", preferenceModel.getDateFormatPattern());
event.saveSetting("loggerPrecision", preferenceModel.getLoggerPrecision());
event.saveSetting("toolTips", preferenceModel.isToolTips());
event.saveSetting("scrollToBottom", preferenceModel.isScrollToBottom());
event.saveSetting(
"detailPaneVisible", preferenceModel.isDetailPaneVisible());
event.saveSetting(
"logTreePanelVisible", preferenceModel.isLogTreePanelVisible());
Set set = logTreePanel.getHiddenSet();
int index = 0;
for (Iterator iter = set.iterator(); iter.hasNext();) {
Object logger = iter.next();
event.saveSetting("Logger.Ignore." + index++, logger.toString());
}
saveColumnSettings();
saveColorSettings();
}
/**
* Display the panel preferences frame
*/
void showPreferences() {
preferencesPanel.updateModel();
preferencesFrame.show();
}
/**
* Display the color rule frame
*/
void showColorPreferences() {
colorFrame.pack();
colorFrame.show();
}
/**
* Toggle panel preference for detail visibility on or off
*/
void toggleDetailVisible() {
preferenceModel.setDetailPaneVisible(
!preferenceModel.isDetailPaneVisible());
}
/**
* Accessor
*
* @return detail visibility flag
*/
boolean isDetailVisible() {
return preferenceModel.isDetailPaneVisible();
}
/**
* Toggle panel preference for logger tree visibility on or off
*/
void toggleLogTreeVisible() {
preferenceModel.setLogTreePanelVisible(
!preferenceModel.isLogTreePanelVisible());
}
/**
* Accessor
*
* @return logger tree visibility flag
*/
boolean isLogTreeVisible() {
return preferenceModel.isLogTreePanelVisible();
}
/**
* Return all events
*
* @return list of LoggingEvents
*/
List getEvents() {
return tableModel.getAllEvents();
}
/**
* Return the events that are visible with the current filter applied
*
* @return list of LoggingEvents
*/
List getFilteredEvents() {
return tableModel.getFilteredEvents();
}
List getMatchingEvents(Rule rule) {
return tableModel.getMatchingEvents(rule);
}
/**
* Remove all events
*/
void clearEvents() {
clearModel();
}
/**
* Accessor
*
* @return identifier
*/
String getIdentifier() {
return identifier;
}
/**
* Undocks this DockablePanel by removing the panel from the LogUI window
* and placing it inside it's own JFrame.
*/
void undock() {
int row = table.getSelectedRow();
setDocked(false);
externalPanel.removeAll();
findPanel.removeAll();
findPanel.add(findField);
externalPanel.add(undockedToolbar, BorderLayout.NORTH);
externalPanel.add(nameTreeAndMainPanelSplit, BorderLayout.CENTER);
externalPanel.setDocked(false);
undockedFrame.setSize(getSize());
undockedFrame.setLocation(getBounds().x, getBounds().y);
undockedFrame.setVisible(true);
dockingAction.putValue(Action.NAME, "Dock");
dockingAction.putValue(Action.SMALL_ICON, ChainsawIcons.ICON_DOCK);
if (row > -1) {
table.scrollToRow(row, table.columnAtPoint(table.getVisibleRect().getLocation()));
}
}
/**
* Add an eventCountListener
*
* @param l
*/
void addEventCountListener(EventCountListener l) {
tableModel.addEventCountListener(l);
}
/**
* Accessor
*
* @return paused flag
*/
boolean isPaused() {
return paused;
}
/**
* Modifies the Paused property and notifies the listeners
*
* @param paused
*/
void setPaused(boolean paused) {
boolean oldValue = this.paused;
this.paused = paused;
firePropertyChange("paused", oldValue, paused);
}
/**
* Add a preference propertyChangeListener
*
* @param listener
*/
void addPreferencePropertyChangeListener(PropertyChangeListener listener) {
preferenceModel.addPropertyChangeListener(listener);
}
/**
* Toggle the LoggingEvent container from either managing a cyclic buffer of
* events or an ArrayList of events
*/
void toggleCyclic() {
tableModel.setCyclic(!tableModel.isCyclic());
}
/**
* Accessor
*
* @return flag answering if LoggingEvent container is a cyclic buffer
*/
boolean isCyclic() {
return tableModel.isCyclic();
}
public boolean updateRule(String ruleText) {
if ((ruleText == null) || ((ruleText != null) && ruleText.equals(""))) {
findRule = null;
colorizer.setFindRule(null);
bypassScrollFind = false;
findField.setToolTipText(
"Enter expression - right click or ctrl-space for menu");
return false;
} else {
bypassScrollFind = true;
try {
findField.setToolTipText(
"Enter expression - right click or ctrl-space for menu");
findRule = ExpressionRule.getRule(ruleText);
colorizer.setFindRule(findRule);
return true;
} catch (IllegalArgumentException re) {
findField.setToolTipText(re.getMessage());
colorizer.setFindRule(null);
return false;
}
}
}
/**
* Display the detail pane, using the last known divider location
*/
private void showDetailPane() {
lowerPanel.setDividerSize(dividerSize);
lowerPanel.setDividerLocation(lastDetailPanelSplitLocation);
detailPanel.setVisible(true);
lowerPanel.repaint();
}
/**
* Hide the detail pane, holding the current divider location for later use
*/
private void hideDetailPane() {
int currentSize = lowerPanel.getHeight() - lowerPanel.getDividerSize();
if (currentSize > 0) {
lastDetailPanelSplitLocation =
(double) lowerPanel.getDividerLocation() / currentSize;
}
lowerPanel.setDividerSize(0);
detailPanel.setVisible(false);
lowerPanel.repaint();
}
/**
* Display the log tree pane, using the last known divider location
*/
private void showLogTreePanel() {
nameTreeAndMainPanelSplit.setDividerSize(dividerSize);
nameTreeAndMainPanelSplit.setDividerLocation(
lastLogTreePanelSplitLocation);
logTreePanel.setVisible(true);
nameTreeAndMainPanelSplit.repaint();
}
/**
* Hide the log tree pane, holding the current divider location for later use
*/
private void hideLogTreePanel() {
//subtract one to make sizes match
int currentSize = nameTreeAndMainPanelSplit.getWidth() - nameTreeAndMainPanelSplit.getDividerSize() - 1;
if (currentSize > 0) {
lastLogTreePanelSplitLocation =
(double) nameTreeAndMainPanelSplit.getDividerLocation() / currentSize;
}
nameTreeAndMainPanelSplit.setDividerSize(0);
logTreePanel.setVisible(false);
nameTreeAndMainPanelSplit.repaint();
}
/**
* Return a toolbar used by the undocked LogPanel's frame
*
* @return toolbar
*/
private JToolBar createDockwindowToolbar() {
final JToolBar toolbar = new JToolBar();
toolbar.setFloatable(false);
final Action dockPauseAction =
new AbstractAction("Pause") {
public void actionPerformed(ActionEvent evt) {
setPaused(!isPaused());
}
};
dockPauseAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_P));
dockPauseAction.putValue(
Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("F12"));
dockPauseAction.putValue(
Action.SHORT_DESCRIPTION,
"Halts the display, while still allowing events to stream in the background");
dockPauseAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.PAUSE));
final SmallToggleButton dockPauseButton =
new SmallToggleButton(dockPauseAction);
dockPauseButton.setText("");
dockPauseButton.getModel().setSelected(isPaused());
addPropertyChangeListener(
"paused",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
dockPauseButton.getModel().setSelected(isPaused());
}
});
toolbar.add(dockPauseButton);
Action dockShowPrefsAction =
new AbstractAction("") {
public void actionPerformed(ActionEvent arg0) {
showPreferences();
}
};
dockShowPrefsAction.putValue(
Action.SHORT_DESCRIPTION, "Define preferences...");
dockShowPrefsAction.putValue(
Action.SMALL_ICON, ChainsawIcons.ICON_PREFERENCES);
toolbar.add(new SmallButton(dockShowPrefsAction));
Action dockToggleLogTreeAction =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
toggleLogTreeVisible();
}
};
dockToggleLogTreeAction.putValue(Action.SHORT_DESCRIPTION, "Toggles the Logger Tree Pane");
dockToggleLogTreeAction.putValue("enabled", Boolean.TRUE);
dockToggleLogTreeAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_T));
dockToggleLogTreeAction.putValue(
Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.ALT_MASK));
dockToggleLogTreeAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.WINDOW_ICON));
final SmallToggleButton toggleLogTreeButton =
new SmallToggleButton(dockToggleLogTreeAction);
preferenceModel.addPropertyChangeListener("logTreePanelVisible", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
toggleLogTreeButton.setSelected(preferenceModel.isLogTreePanelVisible());
}
});
toggleLogTreeButton.setSelected(isLogTreeVisible());
toolbar.add(toggleLogTreeButton);
toolbar.addSeparator();
final Action undockedClearAction =
new AbstractAction("Clear") {
public void actionPerformed(ActionEvent arg0) {
clearModel();
}
};
undockedClearAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.DELETE));
undockedClearAction.putValue(
Action.SHORT_DESCRIPTION, "Removes all the events from the current view");
final SmallButton dockClearButton = new SmallButton(undockedClearAction);
dockClearButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, InputEvent.CTRL_MASK),
undockedClearAction.getValue(Action.NAME));
dockClearButton.getActionMap().put(
undockedClearAction.getValue(Action.NAME), undockedClearAction);
dockClearButton.setText("");
toolbar.add(dockClearButton);
toolbar.addSeparator();
Action dockToggleScrollToBottomAction =
new AbstractAction("Toggles Scroll to Bottom") {
public void actionPerformed(ActionEvent e) {
toggleScrollToBottom();
}
};
dockToggleScrollToBottomAction.putValue(Action.SHORT_DESCRIPTION, "Toggles Scroll to Bottom");
dockToggleScrollToBottomAction.putValue("enabled", Boolean.TRUE);
dockToggleScrollToBottomAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.SCROLL_TO_BOTTOM));
final SmallToggleButton toggleScrollToBottomButton =
new SmallToggleButton(dockToggleScrollToBottomAction);
preferenceModel.addPropertyChangeListener("scrollToBottom", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
toggleScrollToBottomButton.setSelected(preferenceModel.isScrollToBottom());
}
});
toggleScrollToBottomButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_B, InputEvent.CTRL_MASK),
dockToggleScrollToBottomAction.getValue(Action.NAME));
toggleScrollToBottomButton.getActionMap().put(
dockToggleScrollToBottomAction.getValue(Action.NAME), dockToggleScrollToBottomAction);
toggleScrollToBottomButton.setSelected(isScrollToBottom());
toggleScrollToBottomButton.setText("");
toolbar.add(toggleScrollToBottomButton);
toolbar.addSeparator();
findField = new JTextField();
findField.addKeyListener(
new ExpressionRuleContext(filterModel, findField));
final Action undockedFindNextAction =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
findNext();
}
};
undockedFindNextAction.putValue(Action.NAME, "Find next");
undockedFindNextAction.putValue(
Action.SHORT_DESCRIPTION,
"Find the next occurrence of the rule from the current row");
undockedFindNextAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.DOWN));
SmallButton undockedFindNextButton =
new SmallButton(undockedFindNextAction);
undockedFindNextButton.setAction(undockedFindNextAction);
undockedFindNextButton.setText("");
undockedFindNextButton.getActionMap().put(
undockedFindNextAction.getValue(Action.NAME), undockedFindNextAction);
undockedFindNextButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("F3"),
undockedFindNextAction.getValue(Action.NAME));
final Action undockedFindPreviousAction =
new AbstractAction() {
public void actionPerformed(ActionEvent e) {
findPrevious();
}
};
undockedFindPreviousAction.putValue(Action.NAME, "Find previous");
undockedFindPreviousAction.putValue(
Action.SHORT_DESCRIPTION,
"Find the previous occurrence of the rule from the current row");
undockedFindPreviousAction.putValue(
Action.SMALL_ICON, new ImageIcon(ChainsawIcons.UP));
SmallButton undockedFindPreviousButton =
new SmallButton(undockedFindPreviousAction);
undockedFindPreviousButton.setAction(undockedFindPreviousAction);
undockedFindPreviousButton.setText("");
undockedFindPreviousButton.getActionMap().put(
undockedFindPreviousAction.getValue(Action.NAME),
undockedFindPreviousAction);
undockedFindPreviousButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(
KeyStroke.getKeyStroke(KeyEvent.VK_F3, KeyEvent.SHIFT_MASK),
undockedFindPreviousAction.getValue(Action.NAME));
Dimension findSize = new Dimension(170, 22);
Dimension findPanelSize = new Dimension(175, 30);
findPanel.setPreferredSize(findPanelSize);
findPanel.setMaximumSize(findPanelSize);
findPanel.setMinimumSize(findPanelSize);
findField.setPreferredSize(findSize);
findField.setMaximumSize(findSize);
findField.setMinimumSize(findSize);
findPanel.setAlignmentY(Component.CENTER_ALIGNMENT);
findField.setAlignmentY(Component.CENTER_ALIGNMENT);
toolbar.add(findPanel);
toolbar.add(undockedFindNextButton);
toolbar.add(undockedFindPreviousButton);
toolbar.addSeparator();
Action redockAction =
new AbstractAction("", ChainsawIcons.ICON_DOCK) {
public void actionPerformed(ActionEvent arg0) {
dock();
}
};
redockAction.putValue(
Action.SHORT_DESCRIPTION,
"Docks this window back with the main Chainsaw window");
SmallButton redockButton = new SmallButton(redockAction);
toolbar.add(redockButton);
return toolbar;
}
/**
* Update the status bar with current selected row and row count
*/
private void updateStatusBar() {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
statusBar.setSelectedLine(
table.getSelectedRow() + 1, tableModel.getRowCount(),
tableModel.size());
}
});
}
/**
* Update the detail pane layout text
*
* @param conversionPattern layout text
*/
private void setDetailPaneConversionPattern(String conversionPattern) {
String oldPattern = getDetailPaneConversionPattern();
((EventDetailLayout) detailLayout).setConversionPattern(conversionPattern);
firePropertyChange(
"detailPaneConversionPattern", oldPattern,
getDetailPaneConversionPattern());
}
/**
* Accessor
*
* @return conversionPattern layout text
*/
private String getDetailPaneConversionPattern() {
return ((EventDetailLayout) detailLayout).getConversionPattern();
}
/**
* Reset the LoggingEvent container, detail panel and status bar
*/
private void clearModel() {
tableModel.clearModel();
synchronized (detail) {
detailPaneUpdater.setSelectedRow(-1);
detail.notify();
}
statusBar.setNothingSelected();
}
/**
* Finds the next row matching the current find rule, and ensures it is made
* visible
*
*/
public void findNext() {
updateRule(findField.getText());
if (findRule != null) {
try {
final int nextRow =
tableModel.find(findRule, table.getSelectedRow() + 1, true);
if (nextRow > -1) {
table.scrollToRow(
nextRow, table.columnAtPoint(table.getVisibleRect().getLocation()));
findField.setToolTipText("Enter an expression");
}
} catch (IllegalArgumentException iae) {
findField.setToolTipText(iae.getMessage());
colorizer.setFindRule(null);
}
}
}
/**
* Finds the previous row matching the current find rule, and ensures it is made
* visible
*
*/
public void findPrevious() {
updateRule(findField.getText());
if (findRule != null) {
try {
final int previousRow =
tableModel.find(findRule, table.getSelectedRow() - 1, false);
if (previousRow > -1) {
table.scrollToRow(
previousRow,
table.columnAtPoint(table.getVisibleRect().getLocation()));
findField.setToolTipText("Enter an expression");
}
} catch (IllegalArgumentException iae) {
findField.setToolTipText(iae.getMessage());
}
}
}
/**
* Docks this DockablePanel by hiding the JFrame and placing the Panel back
* inside the LogUI window.
*/
private void dock() {
int row = table.getSelectedRow();
setDocked(true);
undockedFrame.setVisible(false);
removeAll();
add(nameTreeAndMainPanelSplit, BorderLayout.CENTER);
externalPanel.setDocked(true);
dockingAction.putValue(Action.NAME, "Undock");
dockingAction.putValue(Action.SMALL_ICON, ChainsawIcons.ICON_UNDOCK);
if (row > -1) {
table.scrollToRow(row, table.columnAtPoint(table.getVisibleRect().getLocation()));
}
}
/**
* Save panel column settings
*/
private void saveColumnSettings() {
ObjectOutputStream o = null;
try {
File f = new File(SettingsManager.getInstance().getSettingsDirectory(),
URLEncoder.encode(getIdentifier() + COLUMNS_EXTENSION));
LogLog.debug("writing columns to file: " + f);
o = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(f)));
Enumeration e = this.table.getColumnModel().getColumns();
while (e.hasMoreElements()) {
TableColumn c = (TableColumn) e.nextElement();
if (c.getModelIndex() < ChainsawColumns.getColumnsNames().size()) {
o.writeObject(
new TableColumnData(
(String) c.getHeaderValue(), c.getModelIndex(), c.getWidth()));
} else {
LogLog.debug(
"Not saving col ' " + c.getHeaderValue()
+ "' not part of standard columns");
}
}
o.flush();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (o != null) {
o.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
/**
* Save panel color settings
*/
private void saveColorSettings() {
ObjectOutputStream o = null;
try {
File f = new File(SettingsManager.getInstance().getSettingsDirectory(),
URLEncoder.encode(getIdentifier() + COLORS_EXTENSION));
LogLog.debug("writing colors to file: " + f);
o = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(f)));
o.writeObject(colorizer.getRules());
o.flush();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (o != null) {
o.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
/**
* Load panel column settings
*/
private void loadColumnSettings(File f) {
if (f.exists()) {
ArrayList newColumns = new ArrayList();
TableColumnData temp = null;
ObjectInputStream s = null;
try {
s = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(f)));
while (true) {
temp = (TableColumnData) s.readObject();
TableColumn tc = new TableColumn(temp.getIndex(), temp.getWidth());
tc.setHeaderValue(temp.getColName());
newColumns.add(tc);
}
} catch (EOFException eof) { //end of file - ignore..
}catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
//only remove columns and add serialized columns if
//at least one column was read from the file
TableColumnModel model = table.getColumnModel();
if (newColumns.size() > 0) {
//remove columns from model - will be re-added in the correct order
for (int i = model.getColumnCount() - 1; i > -1; i--) {
model.removeColumn(model.getColumn(i));
}
for (Iterator iter = newColumns.iterator(); iter.hasNext();) {
model.addColumn((TableColumn) iter.next());
}
}
}
}
/**
* Load default column settings if no settings exist for this identifier
*
* @param event
*/
private void loadDefaultColumnSettings(LoadSettingsEvent event) {
String columnOrder = event.getSetting(TABLE_COLUMN_ORDER);
TableColumnModel columnModel = table.getColumnModel();
Map columnNameMap = new HashMap();
for (int i = 0; i < columnModel.getColumnCount(); i++) {
columnNameMap.put(table.getColumnName(i), columnModel.getColumn(i));
}
int index = 0;
StringTokenizer tok = new StringTokenizer(columnOrder, ",");
List sortedColumnList = new ArrayList();
/*
remove all columns from the table that exist in the model
and add in the correct order to a new arraylist
(may be a subset of possible columns)
**/
while (tok.hasMoreElements()) {
String element = (String) tok.nextElement();
TableColumn column = (TableColumn) columnNameMap.get(element);
if (column != null) {
sortedColumnList.add(column);
table.removeColumn(column);
}
}
//re-add columns to the table in the order provided from the list
for (Iterator iter = sortedColumnList.iterator(); iter.hasNext();) {
TableColumn element = (TableColumn) iter.next();
table.addColumn(element);
}
String columnWidths = event.getSetting(TABLE_COLUMN_WIDTHS);
tok = new StringTokenizer(columnWidths, ",");
index = 0;
while (tok.hasMoreElements()) {
String element = (String) tok.nextElement();
try {
int width = Integer.parseInt(element);
if (index > (columnModel.getColumnCount() - 1)) {
LogLog.warn(
"loadsettings - failed attempt to set width for index " + index
+ ", width " + element);
} else {
columnModel.getColumn(index).setPreferredWidth(width);
}
index++;
} catch (NumberFormatException e) {
LogLog.error("Error decoding a Table width", e);
}
}
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
repaint();
}
});
}
public JTextField getFindTextField() {
return findField;
}
/**
* Load panel color settings
*/
private void loadColorSettings(File f) {
if (f.exists()) {
ObjectInputStream s = null;
try {
s = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(f)));
Map map = (Map) s.readObject();
colorizer.setRules(map);
} catch (EOFException eof) { //end of file - ignore..
}catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
}
/**
* Iterate over all values in the column and return the longest width
*
* @param index column index
*
* @return longest width - relies on FontMetrics.stringWidth for calculation
*/
private int getMaxColumnWidth(int index) {
FontMetrics metrics = getGraphics().getFontMetrics();
int longestWidth =
metrics.stringWidth(" " + table.getColumnName(index) + " ")
+ (2 * table.getColumnModel().getColumnMargin());
for (int i = 0, j = tableModel.getRowCount(); i < j; i++) {
Component c =
renderer.getTableCellRendererComponent(
table, table.getValueAt(i, index), false, false, i, index);
if (c instanceof JLabel) {
longestWidth =
Math.max(longestWidth, metrics.stringWidth(((JLabel) c).getText()));
}
}
return longestWidth + 5;
}
/**
* ensures the Entry map of all the unque logger names etc, that is used for
* the Filter panel is updated with any new information from the event
*
* @param entry
*/
private void updateOtherModels(ChainsawEventBatchEntry entry) {
LoggingEvent event = entry.getEvent();
/*
* EventContainer is a LoggerNameModel imp, use that for notifing
*/
tableModel.addLoggerName(event.getLoggerName());
filterModel.processNewLoggingEvent(event);
}
/**
* This class receives notification when the Refine focus text field is
* updated, where a backgrounh thread periodically wakes up and checks if
* they have stopped typing yet. This ensures that the filtering of the
* model is not done for every single character typed.
*
* @author Paul Smith psmith
*/
private final class DelayedFilterTextDocumentListener
implements DocumentListener {
private static final long CHECK_PERIOD = 1000;
private final JTextField filterText;
private long lastTimeStamp = System.currentTimeMillis();
private final Thread delayThread;
private final String defaultToolTip;
private String lastFilterText = null;
private DelayedFilterTextDocumentListener(final JTextField filterText) {
super();
this.filterText = filterText;
this.defaultToolTip = filterText.getToolTipText();
this.delayThread =
new Thread(
new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(CHECK_PERIOD);
} catch (InterruptedException e) {
}
if (
(System.currentTimeMillis() - lastTimeStamp) < CHECK_PERIOD) {
// They typed something since the last check. we ignor
// this for a sample period
// LogLog.debug("Typed something since the last check");
} else if (
(System.currentTimeMillis() - lastTimeStamp) < (2 * CHECK_PERIOD)) {
// they stopped typing recently, but have stopped for at least
// 1 sample period. lets apply the filter
// LogLog.debug("Typed something recently applying filter");
if (filterText.getText() != lastFilterText) {
lastFilterText = filterText.getText();
setFilter();
}
} else {
// they stopped typing a while ago, let's forget about it
// LogLog.debug(
// "They stoppped typing a while ago, assuming filter has been applied");
}
}
}
});
delayThread.setPriority(Thread.MIN_PRIORITY);
delayThread.start();
}
/**
* Update timestamp
*
* @param e
*/
public void insertUpdate(DocumentEvent e) {
notifyChange();
}
/**
* Update timestamp
*
* @param e
*/
public void removeUpdate(DocumentEvent e) {
notifyChange();
}
/**
* Update timestamp
*
* @param e
*/
public void changedUpdate(DocumentEvent e) {
notifyChange();
}
/**
* Update timestamp
*/
private void notifyChange() {
this.lastTimeStamp = System.currentTimeMillis();
}
/**
* Update refinement rule based on the entered expression
*/
private void setFilter() {
if (filterText.getText().equals("")) {
ruleMediator.setRefinementRule(null);
filterText.setToolTipText(defaultToolTip);
} else {
try {
ruleMediator.setRefinementRule(
ExpressionRule.getRule(filterText.getText()));
filterText.setToolTipText(defaultToolTip);
} catch (IllegalArgumentException iae) {
filterText.setToolTipText(iae.getMessage());
}
}
}
}
/**
* Update active tooltip
*/
private final class TableColumnDetailMouseListener extends MouseMotionAdapter {
private int currentRow = -1;
private TableColumnDetailMouseListener() {
}
/**
* Update tooltip based on mouse position
*
* @param evt
*/
public void mouseMoved(MouseEvent evt) {
currentPoint = evt.getPoint();
if (preferenceModel.isToolTips()) {
int row = table.rowAtPoint(evt.getPoint());
if ((row == currentRow) || (row == -1)) {
return;
}
currentRow = row;
LoggingEvent event = tableModel.getRow(currentRow);
if (event != null) {
StringBuffer buf = new StringBuffer();
buf.append(detailLayout.getHeader())
.append(detailLayout.format(event)).append(
detailLayout.getFooter());
table.setToolTipText(buf.toString());
}
} else {
table.setToolTipText(null);
}
}
}
/**
* Column data helper class - this class is serialized when saving column
* settings
*/
private class TableColumnData implements Serializable {
static final long serialVersionUID = 5350440293110513986L;
private String colName;
private int index;
private int width;
/**
* Creates a new TableColumnData object.
*
* @param colName
* @param index
* @param width
*/
public TableColumnData(String colName, int index, int width) {
this.colName = colName;
this.index = index;
this.width = width;
}
/**
* Accessor
*
* @return col name
*/
public String getColName() {
return colName;
}
/**
* Accessor
*
* @return displayed index
*/
public int getIndex() {
return index;
}
/**
* Accessor
*
* @return width
*/
public int getWidth() {
return width;
}
/**
* Deserialize the state of the object
*
* @param in
*
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
colName = (String) in.readObject();
index = in.readInt();
width = in.readInt();
}
/**
* Serialize the state of the object
*
* @param out
*
* @throws IOException
*/
private void writeObject(java.io.ObjectOutputStream out)
throws IOException {
out.writeObject(colName);
out.writeInt(index);
out.writeInt(width);
}
}
//if columnmoved or columnremoved callback received, re-apply table's sort index based
//sort column name
private class ChainsawTableColumnModelListener
implements TableColumnModelListener {
private ChainsawTableColumnModelListener() {
}
/**
* If a new column was added to the display and that column was the exception column,
* set the cell editor to the throwablerenderer
*
* @param e
*/
public void columnAdded(TableColumnModelEvent e) {
Enumeration enumeration = table.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
TableColumn column = (TableColumn) enumeration.nextElement();
if (
(column.getModelIndex() + 1) == ChainsawColumns.INDEX_THROWABLE_COL_NAME) {
column.setCellEditor(throwableRenderPanel);
}
if (column.getModelIndex() > 0) {
preferenceModel.setColumnVisible(column.getHeaderValue().toString(), true);
}
}
}
/**
* Update sorted column
*
* @param e
*/
public void columnRemoved(TableColumnModelEvent e) {
table.updateSortedColumn();
}
/**
* Update sorted column
*
* @param e
*/
public void columnMoved(TableColumnModelEvent e) {
table.updateSortedColumn();
}
/**
* Ignore margin changed
*
* @param e
*/
public void columnMarginChanged(ChangeEvent e) {
}
/**
* Ignore selection changed
*
* @param e
*/
public void columnSelectionChanged(ListSelectionEvent e) {
}
}
/**
* Thread that periodically checks if the selected row has changed, and if
* it was, updates the Detail Panel with the detailed Logging information
*/
private class DetailPaneUpdater implements PropertyChangeListener {
private int selectedRow = -1;
private DetailPaneUpdater() {
}
/**
* Update detail pane to display information about the LoggingEvent at index row
*
* @param row
*/
private void setSelectedRow(int row) {
selectedRow = row;
updateDetailPane();
}
/**
* Update detail pane
*/
private void updateDetailPane() {
/*
* Don't bother doing anything if it's not visible
*/
if (!detail.isVisible()) {
return;
}
LoggingEvent event = null;
if (selectedRow != -1) {
event = tableModel.getRow(selectedRow);
if (event != null) {
final StringBuffer buf = new StringBuffer();
buf.append(detailLayout.getHeader())
.append(detailLayout.format(event)).append(
detailLayout.getFooter());
if (buf.length() > 0) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Document doc = detail.getEditorKit().createDefaultDocument();
detail.getEditorKit().read(new StringReader(buf.toString()), doc, 0);
detail.setDocument(doc);
detail.setCaretPosition(0);
} catch (Exception e) {}
}
});
}
}
}
if (event == null) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Document doc = detail.getEditorKit().createDefaultDocument();
detail.getEditorKit().read(new StringReader("<html>Nothing selected</html>"), doc, 0);
detail.setDocument(doc);
detail.setCaretPosition(0);
} catch (Exception e) {}
}
});
}
}
/**
* Update detail pane layout if it's changed
*
* @param arg0
*/
public void propertyChange(PropertyChangeEvent arg0) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
updateDetailPane();
}
});
}
}
}
| Modified detial pane update implementation to only set doc in swing thread.
git-svn-id: a7be136288eb2cd985a15786d66ec039c800a993@310720 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/log4j/chainsaw/LogPanel.java | Modified detial pane update implementation to only set doc in swing thread. | <ide><path>rc/java/org/apache/log4j/chainsaw/LogPanel.java
<ide> .append(detailLayout.format(event)).append(
<ide> detailLayout.getFooter());
<ide> if (buf.length() > 0) {
<del> SwingUtilities.invokeLater(new Runnable() {
<del> public void run() {
<del> try {
<del> Document doc = detail.getEditorKit().createDefaultDocument();
<del> detail.getEditorKit().read(new StringReader(buf.toString()), doc, 0);
<del> detail.setDocument(doc);
<del> detail.setCaretPosition(0);
<del> } catch (Exception e) {}
<del> }
<del> });
<del> }
<add> try {
<add> final Document doc = detail.getEditorKit().createDefaultDocument();
<add> detail.getEditorKit().read(new StringReader(buf.toString()), doc, 0);
<add> SwingUtilities.invokeLater(new Runnable() {
<add> public void run() {
<add> detail.setDocument(doc);
<add> detail.setCaretPosition(0);
<add> }
<add> });
<add> } catch (Exception e) {}
<add> }
<ide> }
<ide> }
<ide>
<ide> if (event == null) {
<del> SwingUtilities.invokeLater(new Runnable() {
<del> public void run() {
<del> try {
<del> Document doc = detail.getEditorKit().createDefaultDocument();
<del> detail.getEditorKit().read(new StringReader("<html>Nothing selected</html>"), doc, 0);
<del> detail.setDocument(doc);
<del> detail.setCaretPosition(0);
<del> } catch (Exception e) {}
<del> }
<del> });
<del> }
<add> try {
<add> final Document doc = detail.getEditorKit().createDefaultDocument();
<add> detail.getEditorKit().read(new StringReader("<html>Nothing selected</html>"), doc, 0);
<add> SwingUtilities.invokeLater(new Runnable() {
<add> public void run() {
<add> detail.setDocument(doc);
<add> detail.setCaretPosition(0);
<add> }
<add> });
<add> } catch (Exception e) {}
<add> }
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | 64622557f36c2934cb09eb57a1b696e8d05d297a | 0 | linkedin/ambry,pnarayanan/ambry,cgtz/ambry,linkedin/ambry,vgkholla/ambry,pnarayanan/ambry,cgtz/ambry,cgtz/ambry,linkedin/ambry,vgkholla/ambry,cgtz/ambry,linkedin/ambry | /**
* Copyright 2016 LinkedIn Corp. 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.
*/
package com.github.ambry.tools.admin;
import com.codahale.metrics.MetricRegistry;
import com.github.ambry.clustermap.ClusterAgentsFactory;
import com.github.ambry.clustermap.ClusterMap;
import com.github.ambry.clustermap.DataNodeId;
import com.github.ambry.clustermap.PartitionId;
import com.github.ambry.commons.BlobId;
import com.github.ambry.commons.SSLFactory;
import com.github.ambry.commons.ServerErrorCode;
import com.github.ambry.config.ClusterMapConfig;
import com.github.ambry.config.Config;
import com.github.ambry.config.Default;
import com.github.ambry.config.NetworkConfig;
import com.github.ambry.config.SSLConfig;
import com.github.ambry.config.VerifiableProperties;
import com.github.ambry.messageformat.BlobAll;
import com.github.ambry.messageformat.BlobData;
import com.github.ambry.messageformat.BlobProperties;
import com.github.ambry.messageformat.MessageFormatFlags;
import com.github.ambry.messageformat.MessageFormatRecord;
import com.github.ambry.network.NetworkClient;
import com.github.ambry.network.NetworkClientFactory;
import com.github.ambry.network.NetworkMetrics;
import com.github.ambry.network.Port;
import com.github.ambry.network.RequestInfo;
import com.github.ambry.network.ResponseInfo;
import com.github.ambry.network.Send;
import com.github.ambry.protocol.AdminRequest;
import com.github.ambry.protocol.AdminRequestOrResponseType;
import com.github.ambry.protocol.AdminResponse;
import com.github.ambry.protocol.BlobStoreControlAdminRequest;
import com.github.ambry.protocol.CatchupStatusAdminRequest;
import com.github.ambry.protocol.CatchupStatusAdminResponse;
import com.github.ambry.protocol.GetOption;
import com.github.ambry.protocol.GetRequest;
import com.github.ambry.protocol.GetResponse;
import com.github.ambry.protocol.PartitionRequestInfo;
import com.github.ambry.protocol.ReplicationControlAdminRequest;
import com.github.ambry.protocol.RequestControlAdminRequest;
import com.github.ambry.protocol.RequestOrResponseType;
import com.github.ambry.store.StoreKeyFactory;
import com.github.ambry.tools.util.ToolUtils;
import com.github.ambry.utils.ByteBufferInputStream;
import com.github.ambry.utils.Pair;
import com.github.ambry.utils.SystemTime;
import com.github.ambry.utils.Time;
import com.github.ambry.utils.Utils;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Tool to support admin related operations on Ambry server
* Currently supports:
* 1. Get of either BlobProperties, UserMetadata or blob data for a particular blob from a particular storage node.
* 2. Triggering of compaction of a particular partition on a particular node.
* 3. Get catchup status of peers for a particular blob.
* 4. Stop/Start a particular blob store via BlobStoreControl operation.
*/
public class ServerAdminTool implements Closeable {
private static final int MAX_CONNECTIONS_PER_SERVER = 1;
private static final int POLL_TIMEOUT_MS = 10;
private static final int OPERATION_TIMEOUT_MS = 5000;
private static final int CONNECTION_CHECKOUT_TIMEOUT_MS = 2000;
private static final String CLIENT_ID = "ServerAdminTool";
private static final Logger LOGGER = LoggerFactory.getLogger(ServerAdminTool.class);
private final NetworkClient networkClient;
private final AtomicInteger correlationId = new AtomicInteger(0);
private final Time time = SystemTime.getInstance();
/**
* The different operations supported by the tool.
*/
private enum Operation {
GetBlobProperties,
GetUserMetadata,
GetBlob,
TriggerCompaction,
RequestControl,
ReplicationControl,
CatchupStatus,
BlobStoreControl
}
/**
* Config values associated with the tool.
*/
private static class ServerAdminToolConfig {
/**
* The type of operation.
* Operations are: GetBlobProperties,GetUserMetadata,GetBlob,TriggerCompaction,RequestControl,ReplicationControl,
* CatchupStatus,BlobStoreControl
*/
@Config("type.of.operation")
final Operation typeOfOperation;
/**
* The path to the hardware layout file. Needed if using
* {@link com.github.ambry.clustermap.StaticClusterAgentsFactory}.
*/
@Config("hardware.layout.file.path")
@Default("")
final String hardwareLayoutFilePath;
/**
* The path to the partition layout file. Needed if using
* {@link com.github.ambry.clustermap.StaticClusterAgentsFactory}.
*/
@Config("partition.layout.file.path")
@Default("")
final String partitionLayoutFilePath;
/**
* The hostname of the target server as it appears in the partition layout.
*/
@Config("hostname")
@Default("localhost")
final String hostname;
/**
* The port of the target server in the partition layout (need not be the actual port to connect to).
*/
@Config("port")
@Default("6667")
final int port;
/**
* The id of the blob to operate on (if applicable).
* Applicable for: GetBlobProperties,GetUserMetadata,GetBlob
*/
@Config("blob.id")
@Default("")
final String blobId;
/**
* The get option to use to do the get operation (if applicable)
* Applicable for: GetBlobProperties,GetUserMetadata,GetBlob
*/
@Config("get.option")
@Default("None")
final GetOption getOption;
/**
* Comma separated list of the string representations of the partitions to operate on (if applicable).
* Some requests (TriggerCompaction) will not work with an empty list but some requests treat empty lists as "all
* partitions" (RequestControl,ReplicationControl,CatchupStatus,BlobStoreControl).
* Applicable for: TriggerCompaction,RequestControl,ReplicationControl,CatchupStatus,BlobStoreControl
*/
@Config("partition.ids")
@Default("")
final String[] partitionIds;
/**
* The type of request to control
* Applicable for: RequestControl
*/
@Config("request.type.to.control")
@Default("PutRequest")
final RequestOrResponseType requestTypeToControl;
/**
* Enables the request type or replication if {@code true}. Disables if {@code false}.
* Applicable for: RequestControl,ReplicationControl
*/
@Config("enable.state")
@Default("true")
final boolean enableState;
/**
* The comma separated names of the datacenters from which replication should be controlled.
* Applicable for: ReplicationControl
*/
@Config("replication.origins")
@Default("")
final String[] origins;
/**
* The acceptable lag in bytes in case of catchup status requests
* Applicable for: CatchupStatus
*/
@Config("acceptable.lag.in.bytes")
@Default("0")
final long acceptableLagInBytes;
/**
* The number of replicas of each partition that have to be within "acceptable.lag.in.bytes" in case of catchup
* status requests. The min of this value or the total count of replicas -1 is considered.
* Applicable for: CatchupStatus,BlobStoreControl
*/
@Config("num.replicas.caught.up.per.partition")
@Default("Short.MAX_VALUE")
final short numReplicasCaughtUpPerPartition;
/**
* Path of the file where the data from certain operations will output. For example, the blob from GetBlob and the
* user metadata from GetUserMetadata will be written into this file.
*/
@Config("data.output.file.path")
@Default("/tmp/ambryResult.out")
final String dataOutputFilePath;
/**
* Constructs the configs associated with the tool.
* @param verifiableProperties the props to use to load the config.
*/
ServerAdminToolConfig(VerifiableProperties verifiableProperties) {
typeOfOperation = Operation.valueOf(verifiableProperties.getString("type.of.operation"));
hardwareLayoutFilePath = verifiableProperties.getString("hardware.layout.file.path", "");
partitionLayoutFilePath = verifiableProperties.getString("partition.layout.file.path", "");
hostname = verifiableProperties.getString("hostname", "localhost");
port = verifiableProperties.getIntInRange("port", 6667, 1, 65535);
blobId = verifiableProperties.getString("blob.id", "");
getOption = GetOption.valueOf(verifiableProperties.getString("get.option", "None"));
partitionIds = verifiableProperties.getString("partition.ids", "").split(",");
requestTypeToControl =
RequestOrResponseType.valueOf(verifiableProperties.getString("request.type.to.control", "PutRequest"));
enableState = verifiableProperties.getBoolean("enable.state", true);
origins = verifiableProperties.getString("replication.origins", "").split(",");
acceptableLagInBytes = verifiableProperties.getLongInRange("acceptable.lag.in.bytes", 0, 0, Long.MAX_VALUE);
numReplicasCaughtUpPerPartition =
verifiableProperties.getShortInRange("num.replicas.caught.up.per.partition", Short.MAX_VALUE, (short) 1,
Short.MAX_VALUE);
dataOutputFilePath = verifiableProperties.getString("data.output.file.path", "/tmp/ambryResult.out");
}
}
/**
* Runs the server admin tool
* @param args associated arguments.
* @throws Exception
*/
public static void main(String args[]) throws Exception {
VerifiableProperties verifiableProperties = ToolUtils.getVerifiableProperties(args);
ServerAdminToolConfig config = new ServerAdminToolConfig(verifiableProperties);
ClusterMapConfig clusterMapConfig = new ClusterMapConfig(verifiableProperties);
ClusterMap clusterMap =
((ClusterAgentsFactory) Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory, clusterMapConfig,
config.hardwareLayoutFilePath, config.partitionLayoutFilePath)).getClusterMap();
SSLFactory sslFactory = !clusterMapConfig.clusterMapSslEnabledDatacenters.isEmpty() ? new SSLFactory(
new SSLConfig(verifiableProperties)) : null;
ServerAdminTool serverAdminTool =
new ServerAdminTool(clusterMap.getMetricRegistry(), sslFactory, verifiableProperties);
File file = new File(config.dataOutputFilePath);
if (!file.exists() && !file.createNewFile()) {
throw new IllegalStateException("Could not create " + file);
}
FileOutputStream outputFileStream = new FileOutputStream(config.dataOutputFilePath);
DataNodeId dataNodeId = clusterMap.getDataNodeId(config.hostname, config.port);
if (dataNodeId == null) {
throw new IllegalArgumentException(
"Could not find a data node corresponding to " + config.hostname + ":" + config.port);
}
switch (config.typeOfOperation) {
case GetBlobProperties:
BlobId blobId = new BlobId(config.blobId, clusterMap);
Pair<ServerErrorCode, BlobProperties> bpResponse =
serverAdminTool.getBlobProperties(dataNodeId, blobId, config.getOption, clusterMap);
if (bpResponse.getFirst() == ServerErrorCode.No_Error) {
LOGGER.info("Blob properties for {} from {}: {}", blobId, dataNodeId, bpResponse.getSecond());
} else {
LOGGER.error("Failed to get blob properties for {} from {} with option {}. Error code is {}", blobId,
dataNodeId, config.getOption, bpResponse.getFirst());
}
break;
case GetUserMetadata:
blobId = new BlobId(config.blobId, clusterMap);
Pair<ServerErrorCode, ByteBuffer> umResponse =
serverAdminTool.getUserMetadata(dataNodeId, blobId, config.getOption, clusterMap);
if (umResponse.getFirst() == ServerErrorCode.No_Error) {
writeBufferToFile(umResponse.getSecond(), outputFileStream);
LOGGER.info("User metadata for {} from {} written to {}", blobId, dataNodeId, config.dataOutputFilePath);
} else {
LOGGER.error("Failed to get user metadata for {} from {} with option {}. Error code is {}", blobId,
dataNodeId, config.getOption, umResponse.getFirst());
}
break;
case GetBlob:
blobId = new BlobId(config.blobId, clusterMap);
Pair<ServerErrorCode, BlobData> bResponse =
serverAdminTool.getBlob(dataNodeId, blobId, config.getOption, clusterMap);
if (bResponse.getFirst() == ServerErrorCode.No_Error) {
LOGGER.info("Blob type of {} from {} is {}", blobId, dataNodeId, bResponse.getSecond().getBlobType());
writeBufferToFile(bResponse.getSecond().getStream().getByteBuffer(), outputFileStream);
LOGGER.info("Blob data for {} from {} written to {}", blobId, dataNodeId, config.dataOutputFilePath);
} else {
LOGGER.error("Failed to get blob data for {} from {} with option {}. Error code is {}", blobId, dataNodeId,
config.getOption, bResponse.getFirst());
}
break;
case TriggerCompaction:
if (config.partitionIds.length > 0 && !config.partitionIds[0].isEmpty()) {
for (String partitionIdStr : config.partitionIds) {
PartitionId partitionId = getPartitionIdFromStr(partitionIdStr, clusterMap);
ServerErrorCode errorCode = serverAdminTool.triggerCompaction(dataNodeId, partitionId);
if (errorCode == ServerErrorCode.No_Error) {
LOGGER.info("Compaction has been triggered for {} on {}", partitionId, dataNodeId);
} else {
LOGGER.error("From {}, received server error code {} for trigger compaction request on {}", dataNodeId,
errorCode, partitionId);
}
}
} else {
LOGGER.error("There were no partitions provided to trigger compaction on");
}
break;
case RequestControl:
if (config.partitionIds.length > 0 && !config.partitionIds[0].isEmpty()) {
for (String partitionIdStr : config.partitionIds) {
PartitionId partitionId = getPartitionIdFromStr(partitionIdStr, clusterMap);
sendRequestControlRequest(serverAdminTool, dataNodeId, partitionId, config.requestTypeToControl,
config.enableState);
}
} else {
LOGGER.info("No partition list provided. Requesting enable status of {} to be set to {} on all partitions",
config.requestTypeToControl, config.enableState);
sendRequestControlRequest(serverAdminTool, dataNodeId, null, config.requestTypeToControl, config.enableState);
}
break;
case ReplicationControl:
List<String> origins = Collections.EMPTY_LIST;
if (config.origins.length > 0 && !config.origins[0].isEmpty()) {
origins = Arrays.asList(config.origins);
}
if (config.partitionIds.length > 0 && !config.partitionIds[0].isEmpty()) {
for (String partitionIdStr : config.partitionIds) {
PartitionId partitionId = getPartitionIdFromStr(partitionIdStr, clusterMap);
sendReplicationControlRequest(serverAdminTool, dataNodeId, partitionId, origins, config.enableState);
}
} else {
LOGGER.info("No partition list provided. Requesting enable status for replication from {} to be set to {} on "
+ "all partitions", origins.isEmpty() ? "all DCs" : origins, config.enableState);
sendReplicationControlRequest(serverAdminTool, dataNodeId, null, origins, config.enableState);
}
break;
case CatchupStatus:
if (config.partitionIds.length > 0 && !config.partitionIds[0].isEmpty()) {
for (String partitionIdStr : config.partitionIds) {
PartitionId partitionId = getPartitionIdFromStr(partitionIdStr, clusterMap);
Pair<ServerErrorCode, Boolean> response =
serverAdminTool.isCaughtUp(dataNodeId, partitionId, config.acceptableLagInBytes,
config.numReplicasCaughtUpPerPartition);
if (response.getFirst() == ServerErrorCode.No_Error) {
LOGGER.info("Replicas are {} within {} bytes for {}", response.getSecond() ? "" : "NOT",
config.acceptableLagInBytes, partitionId);
} else {
LOGGER.error("From {}, received server error code {} for request for catchup status of {}", dataNodeId,
response.getFirst(), partitionId);
}
}
} else {
Pair<ServerErrorCode, Boolean> response =
serverAdminTool.isCaughtUp(dataNodeId, null, config.acceptableLagInBytes,
config.numReplicasCaughtUpPerPartition);
if (response.getFirst() == ServerErrorCode.No_Error) {
LOGGER.info("Replicas are {} within {} for all partitions", response.getSecond() ? "" : "NOT",
config.acceptableLagInBytes);
} else {
LOGGER.error("From {}, received server error code {} for request for catchup status of all partitions",
dataNodeId, response.getFirst());
}
}
break;
case BlobStoreControl:
if (config.partitionIds.length > 0 && !config.partitionIds[0].isEmpty()) {
for (String partitionIdStr : config.partitionIds) {
PartitionId partitionId = getPartitionIdFromStr(partitionIdStr, clusterMap);
sendBlobStoreControlRequest(serverAdminTool, dataNodeId, partitionId,
config.numReplicasCaughtUpPerPartition, config.enableState);
}
} else {
LOGGER.error("There were no partitions provided to be controlled (Start/Stop)");
}
break;
default:
throw new IllegalStateException("Recognized but unsupported operation: " + config.typeOfOperation);
}
serverAdminTool.close();
outputFileStream.close();
clusterMap.close();
}
/**
* Gets the {@link PartitionId} in the {@code clusterMap} whose string representation matches {@code partitionIdStr}.
* @param partitionIdStr the string representation of the partition required.
* @param clusterMap the {@link ClusterMap} to use to list and process {@link PartitionId}s.
* @return the {@link PartitionId} in the {@code clusterMap} whose string repr matches {@code partitionIdStr}.
* {@code null} if {@code partitionIdStr} is {@code null}.
* @throws IllegalArgumentException if there is no @link PartitionId} in the {@code clusterMap} whose string repr
* matches {@code partitionIdStr}.
*/
public static PartitionId getPartitionIdFromStr(String partitionIdStr, ClusterMap clusterMap) {
if (partitionIdStr == null) {
return null;
}
PartitionId targetPartitionId = null;
List<? extends PartitionId> partitionIds = clusterMap.getAllPartitionIds(null);
for (PartitionId partitionId : partitionIds) {
if (partitionId.isEqual(partitionIdStr)) {
targetPartitionId = partitionId;
break;
}
}
if (targetPartitionId == null) {
throw new IllegalArgumentException("Partition Id is not valid: [" + partitionIdStr + "]");
}
return targetPartitionId;
}
/**
* Writes the content of {@code buffer} into {@link ServerAdminToolConfig#dataOutputFilePath}.
* @param buffer the {@link ByteBuffer} whose content needs to be written.
* @param outputFileStream the {@link FileOutputStream} to write to.
* @throws IOException
*/
private static void writeBufferToFile(ByteBuffer buffer, FileOutputStream outputFileStream) throws IOException {
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
outputFileStream.write(bytes);
}
/**
* Sends a {@link RequestControlAdminRequest} to {@code dataNodeId} to set enable status of {@code toControl} to
* {@code enable} for {@code partitionId}.
* @param serverAdminTool the {@link ServerAdminTool} instance to use.
* @param dataNodeId the {@link DataNodeId} to send the request to.
* @param partitionId the partition id (string) on which the operation will take place. Can be {@code null}.
* @param toControl the {@link RequestOrResponseType} to control.
* @param enable the enable (or disable) status required for {@code toControl}.
* @throws IOException
* @throws TimeoutException
*/
private static void sendRequestControlRequest(ServerAdminTool serverAdminTool, DataNodeId dataNodeId,
PartitionId partitionId, RequestOrResponseType toControl, boolean enable) throws IOException, TimeoutException {
ServerErrorCode errorCode = serverAdminTool.controlRequest(dataNodeId, partitionId, toControl, enable);
if (errorCode == ServerErrorCode.No_Error) {
LOGGER.info("{} enable state has been set to {} for {} on {}", toControl, enable, partitionId, dataNodeId);
} else {
LOGGER.error("From {}, received server error code {} for request to set enable state {} for {} on {}", dataNodeId,
errorCode, enable, toControl, partitionId);
}
}
/**
* Sends a {@link ReplicationControlAdminRequest} to {@code dataNodeId} to set enable status of replication from
* {@code origins} to {@code enable} for {@code partitionId}.
* @param serverAdminTool the {@link ServerAdminTool} instance to use.
* @param dataNodeId the {@link DataNodeId} to send the request to.
* @param partitionId the partition id on which the operation will take place. Can be {@code null}.
* @param origins the names of the datacenters from which replication should be controlled.
* @param enable the enable (or disable) status required for replication control.
* @throws IOException
* @throws TimeoutException
*/
private static void sendReplicationControlRequest(ServerAdminTool serverAdminTool, DataNodeId dataNodeId,
PartitionId partitionId, List<String> origins, boolean enable) throws IOException, TimeoutException {
ServerErrorCode errorCode = serverAdminTool.controlReplication(dataNodeId, partitionId, origins, enable);
if (errorCode == ServerErrorCode.No_Error) {
LOGGER.info("Enable state of replication from {} has been set to {} for {} on {}",
origins.isEmpty() ? "all DCs" : origins, enable, partitionId == null ? "all partitions" : partitionId,
dataNodeId);
} else {
LOGGER.error(
"From {}, received server error code {} for request to set enable state {} for replication from {} for {}",
dataNodeId, errorCode, enable, origins, partitionId);
}
}
/**
* Sends a {@link BlobStoreControlAdminRequest} to {@code dataNodeId} to set enable status of controlling BlobStore
* to {@code enable} for {@code partitionId}.
* @param serverAdminTool the {@link ServerAdminTool} instance to use.
* @param dataNodeId the {@link DataNodeId} to send the request to.
* @param partitionId the partition id on which the operation will take place. Can be {@code null}.
* @param numReplicasCaughtUpPerPartition the minimum number of peers should catch up with the partition.
* @param enable the enable (or disable) status required for BlobStore control.
* @throws IOException
* @throws TimeoutException
*/
private static void sendBlobStoreControlRequest(ServerAdminTool serverAdminTool, DataNodeId dataNodeId,
PartitionId partitionId, short numReplicasCaughtUpPerPartition, boolean enable)
throws IOException, TimeoutException {
ServerErrorCode errorCode =
serverAdminTool.controlBlobStore(dataNodeId, partitionId, numReplicasCaughtUpPerPartition, enable);
if (errorCode == ServerErrorCode.No_Error) {
LOGGER.info("Enable state of controlling BlobStore from has been set to {} for {} on {}", enable, partitionId,
dataNodeId);
} else {
LOGGER.error(
"From {}, received server error code {} for request to set enable state {} for controlling BlobStore for {}",
dataNodeId, errorCode, enable, partitionId);
}
}
/**
* Creates an instance of the server admin tool
* @param metricRegistry the {@link MetricRegistry} to use for metrics
* @param sslFactory the {@link SSLFactory} to use
* @param verifiableProperties the {@link VerifiableProperties} to use for config.
* @throws Exception
*/
public ServerAdminTool(MetricRegistry metricRegistry, SSLFactory sslFactory,
VerifiableProperties verifiableProperties) throws Exception {
NetworkMetrics metrics = new NetworkMetrics(metricRegistry);
NetworkConfig config = new NetworkConfig(verifiableProperties);
networkClient =
new NetworkClientFactory(metrics, config, sslFactory, MAX_CONNECTIONS_PER_SERVER, MAX_CONNECTIONS_PER_SERVER,
CONNECTION_CHECKOUT_TIMEOUT_MS, time).getNetworkClient();
}
/**
* Releases all resources associated with the tool.
* @throws IOException
*/
@Override
public void close() throws IOException {
networkClient.close();
}
/**
* Gets {@link BlobProperties} for {@code blobId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param blobId the {@link BlobId} to operate on.
* @param getOption the {@link GetOption} to send with the {@link GetRequest}.
* @param clusterMap the {@link ClusterMap} to use.
* @return the {@link ServerErrorCode} and {@link BlobProperties} of {@code blobId}.
* @throws Exception
*/
public Pair<ServerErrorCode, BlobProperties> getBlobProperties(DataNodeId dataNodeId, BlobId blobId,
GetOption getOption, ClusterMap clusterMap) throws Exception {
Pair<ServerErrorCode, InputStream> response =
getGetResponse(dataNodeId, blobId, MessageFormatFlags.BlobProperties, getOption, clusterMap);
InputStream stream = response.getSecond();
BlobProperties blobProperties = stream != null ? MessageFormatRecord.deserializeBlobProperties(stream) : null;
return new Pair<>(response.getFirst(), blobProperties);
}
/**
* Gets user metadata for {@code blobId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param blobId the {@link BlobId} to operate on.
* @param getOption the {@link GetOption} to send with the {@link GetRequest}.
* @param clusterMap the {@link ClusterMap} to use.
* @return the {@link ServerErrorCode} and user metadata as a {@link ByteBuffer} for {@code blobId}
* @throws Exception
*/
public Pair<ServerErrorCode, ByteBuffer> getUserMetadata(DataNodeId dataNodeId, BlobId blobId, GetOption getOption,
ClusterMap clusterMap) throws Exception {
Pair<ServerErrorCode, InputStream> response =
getGetResponse(dataNodeId, blobId, MessageFormatFlags.BlobUserMetadata, getOption, clusterMap);
InputStream stream = response.getSecond();
ByteBuffer userMetadata = stream != null ? MessageFormatRecord.deserializeUserMetadata(stream) : null;
return new Pair<>(response.getFirst(), userMetadata);
}
/**
* Gets blob data for {@code blobId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param blobId the {@link BlobId} to operate on.
* @param getOption the {@link GetOption} to send with the {@link GetRequest}.
* @param clusterMap the {@link ClusterMap} to use.
* @return the {@link ServerErrorCode} and {@link BlobData} for {@code blobId}
* @throws Exception
*/
public Pair<ServerErrorCode, BlobData> getBlob(DataNodeId dataNodeId, BlobId blobId, GetOption getOption,
ClusterMap clusterMap) throws Exception {
Pair<ServerErrorCode, InputStream> response =
getGetResponse(dataNodeId, blobId, MessageFormatFlags.Blob, getOption, clusterMap);
InputStream stream = response.getSecond();
BlobData blobData = stream != null ? MessageFormatRecord.deserializeBlob(stream) : null;
return new Pair<>(response.getFirst(), blobData);
}
/**
* Gets all data for {@code blobId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param blobId the {@link BlobId} to operate on.
* @param getOption the {@link GetOption} to send with the {@link GetRequest}.
* @param clusterMap the {@link ClusterMap} to use.
* @param storeKeyFactory the {@link StoreKeyFactory} to use.
* @return the {@link ServerErrorCode} and {@link BlobAll} for {@code blobId}
* @throws Exception
*/
public Pair<ServerErrorCode, BlobAll> getAll(DataNodeId dataNodeId, BlobId blobId, GetOption getOption,
ClusterMap clusterMap, StoreKeyFactory storeKeyFactory) throws Exception {
Pair<ServerErrorCode, InputStream> response =
getGetResponse(dataNodeId, blobId, MessageFormatFlags.All, getOption, clusterMap);
InputStream stream = response.getSecond();
BlobAll blobAll = stream != null ? MessageFormatRecord.deserializeBlobAll(stream, storeKeyFactory) : null;
return new Pair<>(response.getFirst(), blobAll);
}
/**
* Triggers compaction on {@code dataNodeId} for the partition defined in {@code partitionIdStr}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param partitionId the {@link PartitionId} to compact.
* @return the {@link ServerErrorCode} that is returned.
* @throws IOException
* @throws TimeoutException
*/
public ServerErrorCode triggerCompaction(DataNodeId dataNodeId, PartitionId partitionId)
throws IOException, TimeoutException {
AdminRequest adminRequest =
new AdminRequest(AdminRequestOrResponseType.TriggerCompaction, partitionId, correlationId.incrementAndGet(),
CLIENT_ID);
ByteBuffer responseBytes = sendRequestGetResponse(dataNodeId, adminRequest);
AdminResponse adminResponse = AdminResponse.readFrom(new DataInputStream(new ByteBufferInputStream(responseBytes)));
return adminResponse.getError();
}
/**
* Sends a {@link RequestControlAdminRequest} to set the enable state of {@code toControl} on {@code partitionIdStr}
* to {@code enable} in {@code dataNodeId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param partitionId the {@link PartitionId} to control requests to. Can be {@code null}.
* @param toControl the {@link RequestOrResponseType} to control.
* @param enable the enable (or disable) status required for {@code toControl}.
* @return the {@link ServerErrorCode} that is returned.
* @throws IOException
* @throws TimeoutException
*/
public ServerErrorCode controlRequest(DataNodeId dataNodeId, PartitionId partitionId, RequestOrResponseType toControl,
boolean enable) throws IOException, TimeoutException {
AdminRequest adminRequest =
new AdminRequest(AdminRequestOrResponseType.RequestControl, partitionId, correlationId.incrementAndGet(),
CLIENT_ID);
RequestControlAdminRequest controlRequest = new RequestControlAdminRequest(toControl, enable, adminRequest);
ByteBuffer responseBytes = sendRequestGetResponse(dataNodeId, controlRequest);
AdminResponse adminResponse = AdminResponse.readFrom(new DataInputStream(new ByteBufferInputStream(responseBytes)));
return adminResponse.getError();
}
/**
* Sends a {@link ReplicationControlAdminRequest} to enable/disable replication from {@code origins} for
* {@code partitionIdStr} in {@code dataNodeId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param partitionId the {@link PartitionId} to control replication for. Can be {@code null}.
* @param origins the names of the datacenters from which replication should be controlled.
* @param enable the enable (or disable) status required for replication from {@code origins}.
* @return the {@link ServerErrorCode} that is returned.
* @throws IOException
* @throws TimeoutException
*/
public ServerErrorCode controlReplication(DataNodeId dataNodeId, PartitionId partitionId, List<String> origins,
boolean enable) throws IOException, TimeoutException {
AdminRequest adminRequest =
new AdminRequest(AdminRequestOrResponseType.ReplicationControl, partitionId, correlationId.incrementAndGet(),
CLIENT_ID);
ReplicationControlAdminRequest controlRequest = new ReplicationControlAdminRequest(origins, enable, adminRequest);
ByteBuffer responseBytes = sendRequestGetResponse(dataNodeId, controlRequest);
AdminResponse adminResponse = AdminResponse.readFrom(new DataInputStream(new ByteBufferInputStream(responseBytes)));
return adminResponse.getError();
}
/**
* Sends a {@link BlobStoreControlAdminRequest} to start or stop a store associated with {@code partitionId}
* on {@code dataNodeId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param partitionId the {@link PartitionId} to start or stop.
* @param numReplicasCaughtUpPerPartition the minimum number of peers should catch up with partition if the store is
* being stopped
* @param enable the enable (or disable) status required for BlobStore control.
* @return the {@link ServerErrorCode} that is returned.
* @throws IOException
* @throws TimeoutException
*/
private ServerErrorCode controlBlobStore(DataNodeId dataNodeId, PartitionId partitionId,
short numReplicasCaughtUpPerPartition, boolean enable) throws IOException, TimeoutException {
AdminRequest adminRequest =
new AdminRequest(AdminRequestOrResponseType.BlobStoreControl, partitionId, correlationId.incrementAndGet(),
CLIENT_ID);
BlobStoreControlAdminRequest controlRequest =
new BlobStoreControlAdminRequest(numReplicasCaughtUpPerPartition, enable, adminRequest);
ByteBuffer responseBytes = sendRequestGetResponse(dataNodeId, controlRequest);
AdminResponse adminResponse = AdminResponse.readFrom(new DataInputStream(new ByteBufferInputStream(responseBytes)));
return adminResponse.getError();
}
/**
* Sends a {@link CatchupStatusAdminRequest} for {@code partitionIdStr} to {@code dataNodeId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param partitionId the {@link PartitionId} to check catchup status for. If {@code null}, status is for all
* partitions on {@code dataNodeId}
* @param acceptableLagInBytes that lag in bytes that is considered OK.
* @param numReplicasCaughtUpPerPartition the number of replicas that have to be within {@code acceptableLagInBytes}
* (per partition). The min of this value or the total count of replicas - 1 is
* considered.
* @return the {@link ServerErrorCode} and the catchup status that is returned if the error code is
* {@link ServerErrorCode#No_Error}, otherwise {@code false}.
* @throws IOException
* @throws TimeoutException
*/
public Pair<ServerErrorCode, Boolean> isCaughtUp(DataNodeId dataNodeId, PartitionId partitionId,
long acceptableLagInBytes, short numReplicasCaughtUpPerPartition) throws IOException, TimeoutException {
AdminRequest adminRequest =
new AdminRequest(AdminRequestOrResponseType.CatchupStatus, partitionId, correlationId.incrementAndGet(),
CLIENT_ID);
CatchupStatusAdminRequest catchupStatusRequest =
new CatchupStatusAdminRequest(acceptableLagInBytes, numReplicasCaughtUpPerPartition, adminRequest);
ByteBuffer responseBytes = sendRequestGetResponse(dataNodeId, catchupStatusRequest);
CatchupStatusAdminResponse response =
CatchupStatusAdminResponse.readFrom(new DataInputStream(new ByteBufferInputStream(responseBytes)));
return new Pair<>(response.getError(), response.getError() == ServerErrorCode.No_Error && response.isCaughtUp());
}
/**
* Sends a {@link GetRequest} based on the provided parameters and returns the response stream if the request was
* successful. {@code null} otherwise.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param blobId the {@link BlobId} to operate on.
* @param flags the {@link MessageFormatFlags} associated with the {@link GetRequest}.
* @param getOption the {@link GetOption} to send with the {@link GetRequest}.
* @param clusterMap the {@link ClusterMap} to use.
* @return the {@link ServerErrorCode} and response stream if the request was successful. {@code null} for the
* response stream otherwise.
* @throws Exception
*/
private Pair<ServerErrorCode, InputStream> getGetResponse(DataNodeId dataNodeId, BlobId blobId,
MessageFormatFlags flags, GetOption getOption, ClusterMap clusterMap) throws Exception {
PartitionRequestInfo partitionRequestInfo =
new PartitionRequestInfo(blobId.getPartition(), Collections.singletonList(blobId));
List<PartitionRequestInfo> partitionRequestInfos = new ArrayList<>();
partitionRequestInfos.add(partitionRequestInfo);
GetRequest getRequest =
new GetRequest(correlationId.incrementAndGet(), CLIENT_ID, flags, partitionRequestInfos, getOption);
InputStream serverResponseStream = new ByteBufferInputStream(sendRequestGetResponse(dataNodeId, getRequest));
GetResponse getResponse = GetResponse.readFrom(new DataInputStream(serverResponseStream), clusterMap);
ServerErrorCode partitionErrorCode = getResponse.getPartitionResponseInfoList().get(0).getErrorCode();
ServerErrorCode errorCode =
partitionErrorCode == ServerErrorCode.No_Error ? getResponse.getError() : partitionErrorCode;
InputStream stream = errorCode == ServerErrorCode.No_Error ? getResponse.getInputStream() : null;
return new Pair<>(errorCode, stream);
}
/**
* Sends {@code request} to {@code dataNodeId} and returns the response as a {@link ByteBuffer}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param request the request to send.
* @return the response as a {@link ByteBuffer} if the response was successfully received. {@code null} otherwise.
* @throws TimeoutException
*/
private ByteBuffer sendRequestGetResponse(DataNodeId dataNodeId, Send request) throws TimeoutException {
String hostname = dataNodeId.getHostname();
Port port = dataNodeId.getPortToConnectTo();
String identifier = hostname + ":" + port.getPort();
RequestInfo requestInfo = new RequestInfo(hostname, port, request);
List<RequestInfo> requestInfos = Collections.singletonList(requestInfo);
ResponseInfo responseInfo = null;
long startTimeMs = time.milliseconds();
do {
if (time.milliseconds() - startTimeMs > OPERATION_TIMEOUT_MS) {
throw new TimeoutException(identifier + ": Operation did not complete within " + OPERATION_TIMEOUT_MS + " ms");
}
List<ResponseInfo> responseInfos = networkClient.sendAndPoll(requestInfos, POLL_TIMEOUT_MS);
if (responseInfos.size() > 1) {
throw new IllegalStateException("Received more than one response even though a single request was sent");
} else if (!responseInfos.isEmpty()) {
responseInfo = responseInfos.get(0);
}
requestInfos = Collections.EMPTY_LIST;
} while (responseInfo == null);
if (responseInfo.getError() != null) {
throw new IllegalStateException(
identifier + ": Encountered error while trying to send request - " + responseInfo.getError());
}
return responseInfo.getResponse();
}
}
| ambry-tools/src/main/java/com.github.ambry/tools/admin/ServerAdminTool.java | /**
* Copyright 2016 LinkedIn Corp. 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.
*/
package com.github.ambry.tools.admin;
import com.codahale.metrics.MetricRegistry;
import com.github.ambry.clustermap.ClusterAgentsFactory;
import com.github.ambry.clustermap.ClusterMap;
import com.github.ambry.clustermap.DataNodeId;
import com.github.ambry.clustermap.PartitionId;
import com.github.ambry.commons.BlobId;
import com.github.ambry.commons.SSLFactory;
import com.github.ambry.commons.ServerErrorCode;
import com.github.ambry.config.ClusterMapConfig;
import com.github.ambry.config.Config;
import com.github.ambry.config.Default;
import com.github.ambry.config.NetworkConfig;
import com.github.ambry.config.SSLConfig;
import com.github.ambry.config.VerifiableProperties;
import com.github.ambry.messageformat.BlobAll;
import com.github.ambry.messageformat.BlobData;
import com.github.ambry.messageformat.BlobProperties;
import com.github.ambry.messageformat.MessageFormatFlags;
import com.github.ambry.messageformat.MessageFormatRecord;
import com.github.ambry.network.NetworkClient;
import com.github.ambry.network.NetworkClientFactory;
import com.github.ambry.network.NetworkMetrics;
import com.github.ambry.network.Port;
import com.github.ambry.network.RequestInfo;
import com.github.ambry.network.ResponseInfo;
import com.github.ambry.network.Send;
import com.github.ambry.protocol.AdminRequest;
import com.github.ambry.protocol.AdminRequestOrResponseType;
import com.github.ambry.protocol.AdminResponse;
import com.github.ambry.protocol.CatchupStatusAdminRequest;
import com.github.ambry.protocol.CatchupStatusAdminResponse;
import com.github.ambry.protocol.GetOption;
import com.github.ambry.protocol.GetRequest;
import com.github.ambry.protocol.GetResponse;
import com.github.ambry.protocol.PartitionRequestInfo;
import com.github.ambry.protocol.ReplicationControlAdminRequest;
import com.github.ambry.protocol.RequestControlAdminRequest;
import com.github.ambry.protocol.RequestOrResponseType;
import com.github.ambry.store.StoreKeyFactory;
import com.github.ambry.tools.util.ToolUtils;
import com.github.ambry.utils.ByteBufferInputStream;
import com.github.ambry.utils.Pair;
import com.github.ambry.utils.SystemTime;
import com.github.ambry.utils.Time;
import com.github.ambry.utils.Utils;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Tool to support admin related operations on Ambry server
* Currently supports:
* 1. Get of either BlobProperties, UserMetadata or blob data for a particular blob from a particular storage node.
* 2. Triggering of compaction of a particular partition on a particular node.
*/
public class ServerAdminTool implements Closeable {
private static final int MAX_CONNECTIONS_PER_SERVER = 1;
private static final int POLL_TIMEOUT_MS = 10;
private static final int OPERATION_TIMEOUT_MS = 5000;
private static final int CONNECTION_CHECKOUT_TIMEOUT_MS = 2000;
private static final String CLIENT_ID = "ServerAdminTool";
private static final Logger LOGGER = LoggerFactory.getLogger(ServerAdminTool.class);
private final NetworkClient networkClient;
private final AtomicInteger correlationId = new AtomicInteger(0);
private final Time time = SystemTime.getInstance();
/**
* The different operations supported by the tool.
*/
private enum Operation {
GetBlobProperties, GetUserMetadata, GetBlob, TriggerCompaction, RequestControl, ReplicationControl, CatchupStatus
}
/**
* Config values associated with the tool.
*/
private static class ServerAdminToolConfig {
/**
* The type of operation.
* Operations are: GetBlobProperties,GetUserMetadata,GetBlob,TriggerCompaction,RequestControl,ReplicationControl,
* CatchupStatus
*/
@Config("type.of.operation")
final Operation typeOfOperation;
/**
* The path to the hardware layout file. Needed if using
* {@link com.github.ambry.clustermap.StaticClusterAgentsFactory}.
*/
@Config("hardware.layout.file.path")
@Default("")
final String hardwareLayoutFilePath;
/**
* The path to the partition layout file. Needed if using
* {@link com.github.ambry.clustermap.StaticClusterAgentsFactory}.
*/
@Config("partition.layout.file.path")
@Default("")
final String partitionLayoutFilePath;
/**
* The hostname of the target server as it appears in the partition layout.
*/
@Config("hostname")
@Default("localhost")
final String hostname;
/**
* The port of the target server in the partition layout (need not be the actual port to connect to).
*/
@Config("port")
@Default("6667")
final int port;
/**
* The id of the blob to operate on (if applicable).
* Applicable for: GetBlobProperties,GetUserMetadata,GetBlob
*/
@Config("blob.id")
@Default("")
final String blobId;
/**
* The get option to use to do the get operation (if applicable)
* Applicable for: GetBlobProperties,GetUserMetadata,GetBlob
*/
@Config("get.option")
@Default("None")
final GetOption getOption;
/**
* Comma separated list of the string representations of the partitions to operate on (if applicable).
* Some requests (TriggerCompaction) will not work with an empty list but some requests treat empty lists as "all
* partitions" (RequestControl,ReplicationControl,CatchupStatus).
* Applicable for: TriggerCompaction,RequestControl,ReplicationControl,CatchupStatus
*/
@Config("partition.ids")
@Default("")
final String[] partitionIds;
/**
* The type of request to control
* Applicable for: RequestControl
*/
@Config("request.type.to.control")
@Default("PutRequest")
final RequestOrResponseType requestTypeToControl;
/**
* Enables the request type or replication if {@code true}. Disables if {@code false}.
* Applicable for: RequestControl,ReplicationControl
*/
@Config("enable.state")
@Default("true")
final boolean enableState;
/**
* The comma separated names of the datacenters from which replication should be controlled.
* Applicable for: ReplicationControl
*/
@Config("replication.origins")
@Default("")
final String[] origins;
/**
* The acceptable lag in bytes in case of catchup status requests
* Applicable for: CatchupStatus
*/
@Config("acceptable.lag.in.bytes")
@Default("0")
final long acceptableLagInBytes;
/**
* The number of replicas of each partition that have to be within "acceptable.lag.in.bytes" in case of catchup
* status requests. The min of this value or the total count of replicas -1 is considered.
* Applicable for: CatchupStatus
*/
@Config("num.replicas.caught.up.per.partition")
@Default("Short.MAX_VALUE")
final short numReplicasCaughtUpPerPartition;
/**
* Path of the file where the data from certain operations will output. For example, the blob from GetBlob and the
* user metadata from GetUserMetadata will be written into this file.
*/
@Config("data.output.file.path")
@Default("/tmp/ambryResult.out")
final String dataOutputFilePath;
/**
* Constructs the configs associated with the tool.
* @param verifiableProperties the props to use to load the config.
*/
ServerAdminToolConfig(VerifiableProperties verifiableProperties) {
typeOfOperation = Operation.valueOf(verifiableProperties.getString("type.of.operation"));
hardwareLayoutFilePath = verifiableProperties.getString("hardware.layout.file.path", "");
partitionLayoutFilePath = verifiableProperties.getString("partition.layout.file.path", "");
hostname = verifiableProperties.getString("hostname", "localhost");
port = verifiableProperties.getIntInRange("port", 6667, 1, 65535);
blobId = verifiableProperties.getString("blob.id", "");
getOption = GetOption.valueOf(verifiableProperties.getString("get.option", "None"));
partitionIds = verifiableProperties.getString("partition.ids", "").split(",");
requestTypeToControl =
RequestOrResponseType.valueOf(verifiableProperties.getString("request.type.to.control", "PutRequest"));
enableState = verifiableProperties.getBoolean("enable.state", true);
origins = verifiableProperties.getString("replication.origins", "").split(",");
acceptableLagInBytes = verifiableProperties.getLongInRange("acceptable.lag.in.bytes", 0, 0, Long.MAX_VALUE);
numReplicasCaughtUpPerPartition =
verifiableProperties.getShortInRange("num.replicas.caught.up.per.partition", Short.MAX_VALUE, (short) 1,
Short.MAX_VALUE);
dataOutputFilePath = verifiableProperties.getString("data.output.file.path", "/tmp/ambryResult.out");
}
}
/**
* Runs the server admin tool
* @param args associated arguments.
* @throws Exception
*/
public static void main(String args[]) throws Exception {
VerifiableProperties verifiableProperties = ToolUtils.getVerifiableProperties(args);
ServerAdminToolConfig config = new ServerAdminToolConfig(verifiableProperties);
ClusterMapConfig clusterMapConfig = new ClusterMapConfig(verifiableProperties);
ClusterMap clusterMap =
((ClusterAgentsFactory) Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory, clusterMapConfig,
config.hardwareLayoutFilePath, config.partitionLayoutFilePath)).getClusterMap();
SSLFactory sslFactory = !clusterMapConfig.clusterMapSslEnabledDatacenters.isEmpty() ? new SSLFactory(
new SSLConfig(verifiableProperties)) : null;
ServerAdminTool serverAdminTool =
new ServerAdminTool(clusterMap.getMetricRegistry(), sslFactory, verifiableProperties);
File file = new File(config.dataOutputFilePath);
if (!file.exists() && !file.createNewFile()) {
throw new IllegalStateException("Could not create " + file);
}
FileOutputStream outputFileStream = new FileOutputStream(config.dataOutputFilePath);
DataNodeId dataNodeId = clusterMap.getDataNodeId(config.hostname, config.port);
if (dataNodeId == null) {
throw new IllegalArgumentException(
"Could not find a data node corresponding to " + config.hostname + ":" + config.port);
}
switch (config.typeOfOperation) {
case GetBlobProperties:
BlobId blobId = new BlobId(config.blobId, clusterMap);
Pair<ServerErrorCode, BlobProperties> bpResponse =
serverAdminTool.getBlobProperties(dataNodeId, blobId, config.getOption, clusterMap);
if (bpResponse.getFirst() == ServerErrorCode.No_Error) {
LOGGER.info("Blob properties for {} from {}: {}", blobId, dataNodeId, bpResponse.getSecond());
} else {
LOGGER.error("Failed to get blob properties for {} from {} with option {}. Error code is {}", blobId,
dataNodeId, config.getOption, bpResponse.getFirst());
}
break;
case GetUserMetadata:
blobId = new BlobId(config.blobId, clusterMap);
Pair<ServerErrorCode, ByteBuffer> umResponse =
serverAdminTool.getUserMetadata(dataNodeId, blobId, config.getOption, clusterMap);
if (umResponse.getFirst() == ServerErrorCode.No_Error) {
writeBufferToFile(umResponse.getSecond(), outputFileStream);
LOGGER.info("User metadata for {} from {} written to {}", blobId, dataNodeId, config.dataOutputFilePath);
} else {
LOGGER.error("Failed to get user metadata for {} from {} with option {}. Error code is {}", blobId,
dataNodeId, config.getOption, umResponse.getFirst());
}
break;
case GetBlob:
blobId = new BlobId(config.blobId, clusterMap);
Pair<ServerErrorCode, BlobData> bResponse =
serverAdminTool.getBlob(dataNodeId, blobId, config.getOption, clusterMap);
if (bResponse.getFirst() == ServerErrorCode.No_Error) {
LOGGER.info("Blob type of {} from {} is {}", blobId, dataNodeId, bResponse.getSecond().getBlobType());
writeBufferToFile(bResponse.getSecond().getStream().getByteBuffer(), outputFileStream);
LOGGER.info("Blob data for {} from {} written to {}", blobId, dataNodeId, config.dataOutputFilePath);
} else {
LOGGER.error("Failed to get blob data for {} from {} with option {}. Error code is {}", blobId, dataNodeId,
config.getOption, bResponse.getFirst());
}
break;
case TriggerCompaction:
if (config.partitionIds.length > 0 && !config.partitionIds[0].isEmpty()) {
for (String partitionIdStr : config.partitionIds) {
PartitionId partitionId = getPartitionIdFromStr(partitionIdStr, clusterMap);
ServerErrorCode errorCode = serverAdminTool.triggerCompaction(dataNodeId, partitionId);
if (errorCode == ServerErrorCode.No_Error) {
LOGGER.info("Compaction has been triggered for {} on {}", partitionId, dataNodeId);
} else {
LOGGER.error("From {}, received server error code {} for trigger compaction request on {}", dataNodeId,
errorCode, partitionId);
}
}
} else {
LOGGER.error("There were no partitions provided to trigger compaction on");
}
break;
case RequestControl:
if (config.partitionIds.length > 0 && !config.partitionIds[0].isEmpty()) {
for (String partitionIdStr : config.partitionIds) {
PartitionId partitionId = getPartitionIdFromStr(partitionIdStr, clusterMap);
sendRequestControlRequest(serverAdminTool, dataNodeId, partitionId, config.requestTypeToControl,
config.enableState);
}
} else {
LOGGER.info("No partition list provided. Requesting enable status of {} to be set to {} on all partitions",
config.requestTypeToControl, config.enableState);
sendRequestControlRequest(serverAdminTool, dataNodeId, null, config.requestTypeToControl, config.enableState);
}
break;
case ReplicationControl:
List<String> origins = Collections.EMPTY_LIST;
if (config.origins.length > 0 && !config.origins[0].isEmpty()) {
origins = Arrays.asList(config.origins);
}
if (config.partitionIds.length > 0 && !config.partitionIds[0].isEmpty()) {
for (String partitionIdStr : config.partitionIds) {
PartitionId partitionId = getPartitionIdFromStr(partitionIdStr, clusterMap);
sendReplicationControlRequest(serverAdminTool, dataNodeId, partitionId, origins, config.enableState);
}
} else {
LOGGER.info("No partition list provided. Requesting enable status for replication from {} to be set to {} on "
+ "all partitions", origins.isEmpty() ? "all DCs" : origins, config.enableState);
sendReplicationControlRequest(serverAdminTool, dataNodeId, null, origins, config.enableState);
}
break;
case CatchupStatus:
if (config.partitionIds.length > 0 && !config.partitionIds[0].isEmpty()) {
for (String partitionIdStr : config.partitionIds) {
PartitionId partitionId = getPartitionIdFromStr(partitionIdStr, clusterMap);
Pair<ServerErrorCode, Boolean> response =
serverAdminTool.isCaughtUp(dataNodeId, partitionId, config.acceptableLagInBytes,
config.numReplicasCaughtUpPerPartition);
if (response.getFirst() == ServerErrorCode.No_Error) {
LOGGER.info("Replicas are {} within {} bytes for {}", response.getSecond() ? "" : "NOT",
config.acceptableLagInBytes, partitionId);
} else {
LOGGER.error("From {}, received server error code {} for request for catchup status of {}", dataNodeId,
response.getFirst(), partitionId);
}
}
} else {
Pair<ServerErrorCode, Boolean> response =
serverAdminTool.isCaughtUp(dataNodeId, null, config.acceptableLagInBytes,
config.numReplicasCaughtUpPerPartition);
if (response.getFirst() == ServerErrorCode.No_Error) {
LOGGER.info("Replicas are {} within {} for all partitions", response.getSecond() ? "" : "NOT",
config.acceptableLagInBytes);
} else {
LOGGER.error("From {}, received server error code {} for request for catchup status of all partitions",
dataNodeId, response.getFirst());
}
}
break;
default:
throw new IllegalStateException("Recognized but unsupported operation: " + config.typeOfOperation);
}
serverAdminTool.close();
outputFileStream.close();
clusterMap.close();
}
/**
* Gets the {@link PartitionId} in the {@code clusterMap} whose string representation matches {@code partitionIdStr}.
* @param partitionIdStr the string representation of the partition required.
* @param clusterMap the {@link ClusterMap} to use to list and process {@link PartitionId}s.
* @return the {@link PartitionId} in the {@code clusterMap} whose string repr matches {@code partitionIdStr}.
* {@code null} if {@code partitionIdStr} is {@code null}.
* @throws IllegalArgumentException if there is no @link PartitionId} in the {@code clusterMap} whose string repr
* matches {@code partitionIdStr}.
*/
public static PartitionId getPartitionIdFromStr(String partitionIdStr, ClusterMap clusterMap) {
if (partitionIdStr == null) {
return null;
}
PartitionId targetPartitionId = null;
List<? extends PartitionId> partitionIds = clusterMap.getAllPartitionIds(null);
for (PartitionId partitionId : partitionIds) {
if (partitionId.isEqual(partitionIdStr)) {
targetPartitionId = partitionId;
break;
}
}
if (targetPartitionId == null) {
throw new IllegalArgumentException("Partition Id is not valid: [" + partitionIdStr + "]");
}
return targetPartitionId;
}
/**
* Writes the content of {@code buffer} into {@link ServerAdminToolConfig#dataOutputFilePath}.
* @param buffer the {@link ByteBuffer} whose content needs to be written.
* @param outputFileStream the {@link FileOutputStream} to write to.
* @throws IOException
*/
private static void writeBufferToFile(ByteBuffer buffer, FileOutputStream outputFileStream) throws IOException {
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
outputFileStream.write(bytes);
}
/**
* Sends a {@link RequestControlAdminRequest} to {@code dataNodeId} to set enable status of {@code toControl} to
* {@code enable} for {@code partitionId}.
* @param serverAdminTool the {@link ServerAdminTool} instance to use.
* @param dataNodeId the {@link DataNodeId} to send the request to.
* @param partitionId the partition id (string) on which the operation will take place. Can be {@code null}.
* @param toControl the {@link RequestOrResponseType} to control.
* @param enable the enable (or disable) status required for {@code toControl}.
* @throws IOException
* @throws TimeoutException
*/
private static void sendRequestControlRequest(ServerAdminTool serverAdminTool, DataNodeId dataNodeId,
PartitionId partitionId, RequestOrResponseType toControl, boolean enable) throws IOException, TimeoutException {
ServerErrorCode errorCode = serverAdminTool.controlRequest(dataNodeId, partitionId, toControl, enable);
if (errorCode == ServerErrorCode.No_Error) {
LOGGER.info("{} enable state has been set to {} for {} on {}", toControl, enable, partitionId, dataNodeId);
} else {
LOGGER.error("From {}, received server error code {} for request to set enable state {} for {} on {}", dataNodeId,
errorCode, enable, toControl, partitionId);
}
}
/**
* Sends a {@link ReplicationControlAdminRequest} to {@code dataNodeId} to set enable status of replication from
* {@code origins} to {@code enable} for {@code partitionId}.
* @param serverAdminTool the {@link ServerAdminTool} instance to use.
* @param dataNodeId the {@link DataNodeId} to send the request to.
* @param partitionId the partition id on which the operation will take place. Can be {@code null}.
* @param origins the names of the datacenters from which replication should be controlled.
* @param enable the enable (or disable) status required for {@code toControl}.
* @throws IOException
* @throws TimeoutException
*/
private static void sendReplicationControlRequest(ServerAdminTool serverAdminTool, DataNodeId dataNodeId,
PartitionId partitionId, List<String> origins, boolean enable) throws IOException, TimeoutException {
ServerErrorCode errorCode = serverAdminTool.controlReplication(dataNodeId, partitionId, origins, enable);
if (errorCode == ServerErrorCode.No_Error) {
LOGGER.info("Enable state of replication from {} has been set to {} for {} on {}",
origins.isEmpty() ? "all DCs" : origins, enable, partitionId == null ? "all partitions" : partitionId,
dataNodeId);
} else {
LOGGER.error(
"From {}, received server error code {} for request to set enable state {} for replication from {} for {}",
dataNodeId, errorCode, enable, origins, partitionId);
}
}
/**
* Creates an instance of the server admin tool
* @param metricRegistry the {@link MetricRegistry} to use for metrics
* @param sslFactory the {@link SSLFactory} to use
* @param verifiableProperties the {@link VerifiableProperties} to use for config.
* @throws Exception
*/
public ServerAdminTool(MetricRegistry metricRegistry, SSLFactory sslFactory,
VerifiableProperties verifiableProperties) throws Exception {
NetworkMetrics metrics = new NetworkMetrics(metricRegistry);
NetworkConfig config = new NetworkConfig(verifiableProperties);
networkClient =
new NetworkClientFactory(metrics, config, sslFactory, MAX_CONNECTIONS_PER_SERVER, MAX_CONNECTIONS_PER_SERVER,
CONNECTION_CHECKOUT_TIMEOUT_MS, time).getNetworkClient();
}
/**
* Releases all resources associated with the tool.
* @throws IOException
*/
@Override
public void close() throws IOException {
networkClient.close();
}
/**
* Gets {@link BlobProperties} for {@code blobId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param blobId the {@link BlobId} to operate on.
* @param getOption the {@link GetOption} to send with the {@link GetRequest}.
* @param clusterMap the {@link ClusterMap} to use.
* @return the {@link ServerErrorCode} and {@link BlobProperties} of {@code blobId}.
* @throws Exception
*/
public Pair<ServerErrorCode, BlobProperties> getBlobProperties(DataNodeId dataNodeId, BlobId blobId,
GetOption getOption, ClusterMap clusterMap) throws Exception {
Pair<ServerErrorCode, InputStream> response =
getGetResponse(dataNodeId, blobId, MessageFormatFlags.BlobProperties, getOption, clusterMap);
InputStream stream = response.getSecond();
BlobProperties blobProperties = stream != null ? MessageFormatRecord.deserializeBlobProperties(stream) : null;
return new Pair<>(response.getFirst(), blobProperties);
}
/**
* Gets user metadata for {@code blobId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param blobId the {@link BlobId} to operate on.
* @param getOption the {@link GetOption} to send with the {@link GetRequest}.
* @param clusterMap the {@link ClusterMap} to use.
* @return the {@link ServerErrorCode} and user metadata as a {@link ByteBuffer} for {@code blobId}
* @throws Exception
*/
public Pair<ServerErrorCode, ByteBuffer> getUserMetadata(DataNodeId dataNodeId, BlobId blobId, GetOption getOption,
ClusterMap clusterMap) throws Exception {
Pair<ServerErrorCode, InputStream> response =
getGetResponse(dataNodeId, blobId, MessageFormatFlags.BlobUserMetadata, getOption, clusterMap);
InputStream stream = response.getSecond();
ByteBuffer userMetadata = stream != null ? MessageFormatRecord.deserializeUserMetadata(stream) : null;
return new Pair<>(response.getFirst(), userMetadata);
}
/**
* Gets blob data for {@code blobId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param blobId the {@link BlobId} to operate on.
* @param getOption the {@link GetOption} to send with the {@link GetRequest}.
* @param clusterMap the {@link ClusterMap} to use.
* @return the {@link ServerErrorCode} and {@link BlobData} for {@code blobId}
* @throws Exception
*/
public Pair<ServerErrorCode, BlobData> getBlob(DataNodeId dataNodeId, BlobId blobId, GetOption getOption,
ClusterMap clusterMap) throws Exception {
Pair<ServerErrorCode, InputStream> response =
getGetResponse(dataNodeId, blobId, MessageFormatFlags.Blob, getOption, clusterMap);
InputStream stream = response.getSecond();
BlobData blobData = stream != null ? MessageFormatRecord.deserializeBlob(stream) : null;
return new Pair<>(response.getFirst(), blobData);
}
/**
* Gets all data for {@code blobId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param blobId the {@link BlobId} to operate on.
* @param getOption the {@link GetOption} to send with the {@link GetRequest}.
* @param clusterMap the {@link ClusterMap} to use.
* @param storeKeyFactory the {@link StoreKeyFactory} to use.
* @return the {@link ServerErrorCode} and {@link BlobAll} for {@code blobId}
* @throws Exception
*/
public Pair<ServerErrorCode, BlobAll> getAll(DataNodeId dataNodeId, BlobId blobId, GetOption getOption,
ClusterMap clusterMap, StoreKeyFactory storeKeyFactory) throws Exception {
Pair<ServerErrorCode, InputStream> response =
getGetResponse(dataNodeId, blobId, MessageFormatFlags.All, getOption, clusterMap);
InputStream stream = response.getSecond();
BlobAll blobAll = stream != null ? MessageFormatRecord.deserializeBlobAll(stream, storeKeyFactory) : null;
return new Pair<>(response.getFirst(), blobAll);
}
/**
* Triggers compaction on {@code dataNodeId} for the partition defined in {@code partitionIdStr}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param partitionId the {@link PartitionId} to compact.
* @return the {@link ServerErrorCode} that is returned.
* @throws IOException
* @throws TimeoutException
*/
public ServerErrorCode triggerCompaction(DataNodeId dataNodeId, PartitionId partitionId)
throws IOException, TimeoutException {
AdminRequest adminRequest =
new AdminRequest(AdminRequestOrResponseType.TriggerCompaction, partitionId, correlationId.incrementAndGet(),
CLIENT_ID);
ByteBuffer responseBytes = sendRequestGetResponse(dataNodeId, adminRequest);
AdminResponse adminResponse = AdminResponse.readFrom(new DataInputStream(new ByteBufferInputStream(responseBytes)));
return adminResponse.getError();
}
/**
* Sends a {@link RequestControlAdminRequest} to set the enable state of {@code toControl} on {@code partitionIdStr}
* to {@code enable} in {@code dataNodeId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param partitionId the {@link PartitionId} to control requests to. Can be {@code null}.
* @param toControl the {@link RequestOrResponseType} to control.
* @param enable the enable (or disable) status required for {@code toControl}.
* @return the {@link ServerErrorCode} that is returned.
* @throws IOException
* @throws TimeoutException
*/
public ServerErrorCode controlRequest(DataNodeId dataNodeId, PartitionId partitionId, RequestOrResponseType toControl,
boolean enable) throws IOException, TimeoutException {
AdminRequest adminRequest =
new AdminRequest(AdminRequestOrResponseType.RequestControl, partitionId, correlationId.incrementAndGet(),
CLIENT_ID);
RequestControlAdminRequest controlRequest = new RequestControlAdminRequest(toControl, enable, adminRequest);
ByteBuffer responseBytes = sendRequestGetResponse(dataNodeId, controlRequest);
AdminResponse adminResponse = AdminResponse.readFrom(new DataInputStream(new ByteBufferInputStream(responseBytes)));
return adminResponse.getError();
}
/**
* Sends a {@link ReplicationControlAdminRequest} to enable/disable replication from {@code origins} for
* {@code partitionIdStr} in {@code dataNodeId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param partitionId the {@link PartitionId} to control replication for. Can be {@code null}.
* @param origins the names of the datacenters from which replication should be controlled.
* @param enable the enable (or disable) status required for replication from {@code origins}.
* @return the {@link ServerErrorCode} that is returned.
* @throws IOException
* @throws TimeoutException
*/
public ServerErrorCode controlReplication(DataNodeId dataNodeId, PartitionId partitionId, List<String> origins,
boolean enable) throws IOException, TimeoutException {
AdminRequest adminRequest =
new AdminRequest(AdminRequestOrResponseType.ReplicationControl, partitionId, correlationId.incrementAndGet(),
CLIENT_ID);
ReplicationControlAdminRequest controlRequest = new ReplicationControlAdminRequest(origins, enable, adminRequest);
ByteBuffer responseBytes = sendRequestGetResponse(dataNodeId, controlRequest);
AdminResponse adminResponse = AdminResponse.readFrom(new DataInputStream(new ByteBufferInputStream(responseBytes)));
return adminResponse.getError();
}
/**
* Sends a {@link CatchupStatusAdminRequest} for {@code partitionIdStr} to {@code dataNodeId}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param partitionId the {@link PartitionId} to check catchup status for. If {@code null}, status is for all
* partitions on {@code dataNodeId}
* @param acceptableLagInBytes that lag in bytes that is considered OK.
* @param numReplicasCaughtUpPerPartition the number of replicas that have to be within {@code acceptableLagInBytes}
* (per partition). The min of this value or the total count of replicas - 1 is
* considered.
* @return the {@link ServerErrorCode} and the catchup status that is returned if the error code is
* {@link ServerErrorCode#No_Error}, otherwise {@code false}.
* @throws IOException
* @throws TimeoutException
*/
public Pair<ServerErrorCode, Boolean> isCaughtUp(DataNodeId dataNodeId, PartitionId partitionId,
long acceptableLagInBytes, short numReplicasCaughtUpPerPartition) throws IOException, TimeoutException {
AdminRequest adminRequest =
new AdminRequest(AdminRequestOrResponseType.CatchupStatus, partitionId, correlationId.incrementAndGet(),
CLIENT_ID);
CatchupStatusAdminRequest catchupStatusRequest =
new CatchupStatusAdminRequest(acceptableLagInBytes, numReplicasCaughtUpPerPartition, adminRequest);
ByteBuffer responseBytes = sendRequestGetResponse(dataNodeId, catchupStatusRequest);
CatchupStatusAdminResponse response =
CatchupStatusAdminResponse.readFrom(new DataInputStream(new ByteBufferInputStream(responseBytes)));
return new Pair<>(response.getError(), response.getError() == ServerErrorCode.No_Error && response.isCaughtUp());
}
/**
* Sends a {@link GetRequest} based on the provided parameters and returns the response stream if the request was
* successful. {@code null} otherwise.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param blobId the {@link BlobId} to operate on.
* @param flags the {@link MessageFormatFlags} associated with the {@link GetRequest}.
* @param getOption the {@link GetOption} to send with the {@link GetRequest}.
* @param clusterMap the {@link ClusterMap} to use.
* @return the {@link ServerErrorCode} and response stream if the request was successful. {@code null} for the
* response stream otherwise.
* @throws Exception
*/
private Pair<ServerErrorCode, InputStream> getGetResponse(DataNodeId dataNodeId, BlobId blobId,
MessageFormatFlags flags, GetOption getOption, ClusterMap clusterMap) throws Exception {
PartitionRequestInfo partitionRequestInfo =
new PartitionRequestInfo(blobId.getPartition(), Collections.singletonList(blobId));
List<PartitionRequestInfo> partitionRequestInfos = new ArrayList<>();
partitionRequestInfos.add(partitionRequestInfo);
GetRequest getRequest =
new GetRequest(correlationId.incrementAndGet(), CLIENT_ID, flags, partitionRequestInfos, getOption);
InputStream serverResponseStream = new ByteBufferInputStream(sendRequestGetResponse(dataNodeId, getRequest));
GetResponse getResponse = GetResponse.readFrom(new DataInputStream(serverResponseStream), clusterMap);
ServerErrorCode partitionErrorCode = getResponse.getPartitionResponseInfoList().get(0).getErrorCode();
ServerErrorCode errorCode =
partitionErrorCode == ServerErrorCode.No_Error ? getResponse.getError() : partitionErrorCode;
InputStream stream = errorCode == ServerErrorCode.No_Error ? getResponse.getInputStream() : null;
return new Pair<>(errorCode, stream);
}
/**
* Sends {@code request} to {@code dataNodeId} and returns the response as a {@link ByteBuffer}.
* @param dataNodeId the {@link DataNodeId} to contact.
* @param request the request to send.
* @return the response as a {@link ByteBuffer} if the response was successfully received. {@code null} otherwise.
* @throws TimeoutException
*/
private ByteBuffer sendRequestGetResponse(DataNodeId dataNodeId, Send request) throws TimeoutException {
String hostname = dataNodeId.getHostname();
Port port = dataNodeId.getPortToConnectTo();
String identifier = hostname + ":" + port.getPort();
RequestInfo requestInfo = new RequestInfo(hostname, port, request);
List<RequestInfo> requestInfos = Collections.singletonList(requestInfo);
ResponseInfo responseInfo = null;
long startTimeMs = time.milliseconds();
do {
if (time.milliseconds() - startTimeMs > OPERATION_TIMEOUT_MS) {
throw new TimeoutException(identifier + ": Operation did not complete within " + OPERATION_TIMEOUT_MS + " ms");
}
List<ResponseInfo> responseInfos = networkClient.sendAndPoll(requestInfos, POLL_TIMEOUT_MS);
if (responseInfos.size() > 1) {
throw new IllegalStateException("Received more than one response even though a single request was sent");
} else if (!responseInfos.isEmpty()) {
responseInfo = responseInfos.get(0);
}
requestInfos = Collections.EMPTY_LIST;
} while (responseInfo == null);
if (responseInfo.getError() != null) {
throw new IllegalStateException(
identifier + ": Encountered error while trying to send request - " + responseInfo.getError());
}
return responseInfo.getResponse();
}
}
| Add a ServerAdminTool to control BlobStore (#889)
- Add BlobStoreControl as a new type of Operation in ServerAdminTool.
- Add new case and associated methods to send BlobStoreControlRequest.
| ambry-tools/src/main/java/com.github.ambry/tools/admin/ServerAdminTool.java | Add a ServerAdminTool to control BlobStore (#889) | <ide><path>mbry-tools/src/main/java/com.github.ambry/tools/admin/ServerAdminTool.java
<ide> import com.github.ambry.protocol.AdminRequest;
<ide> import com.github.ambry.protocol.AdminRequestOrResponseType;
<ide> import com.github.ambry.protocol.AdminResponse;
<add>import com.github.ambry.protocol.BlobStoreControlAdminRequest;
<ide> import com.github.ambry.protocol.CatchupStatusAdminRequest;
<ide> import com.github.ambry.protocol.CatchupStatusAdminResponse;
<ide> import com.github.ambry.protocol.GetOption;
<ide> * Currently supports:
<ide> * 1. Get of either BlobProperties, UserMetadata or blob data for a particular blob from a particular storage node.
<ide> * 2. Triggering of compaction of a particular partition on a particular node.
<add> * 3. Get catchup status of peers for a particular blob.
<add> * 4. Stop/Start a particular blob store via BlobStoreControl operation.
<ide> */
<ide> public class ServerAdminTool implements Closeable {
<ide> private static final int MAX_CONNECTIONS_PER_SERVER = 1;
<ide> * The different operations supported by the tool.
<ide> */
<ide> private enum Operation {
<del> GetBlobProperties, GetUserMetadata, GetBlob, TriggerCompaction, RequestControl, ReplicationControl, CatchupStatus
<add> GetBlobProperties,
<add> GetUserMetadata,
<add> GetBlob,
<add> TriggerCompaction,
<add> RequestControl,
<add> ReplicationControl,
<add> CatchupStatus,
<add> BlobStoreControl
<ide> }
<ide>
<ide> /**
<ide> /**
<ide> * The type of operation.
<ide> * Operations are: GetBlobProperties,GetUserMetadata,GetBlob,TriggerCompaction,RequestControl,ReplicationControl,
<del> * CatchupStatus
<add> * CatchupStatus,BlobStoreControl
<ide> */
<ide> @Config("type.of.operation")
<ide> final Operation typeOfOperation;
<ide> /**
<ide> * Comma separated list of the string representations of the partitions to operate on (if applicable).
<ide> * Some requests (TriggerCompaction) will not work with an empty list but some requests treat empty lists as "all
<del> * partitions" (RequestControl,ReplicationControl,CatchupStatus).
<del> * Applicable for: TriggerCompaction,RequestControl,ReplicationControl,CatchupStatus
<add> * partitions" (RequestControl,ReplicationControl,CatchupStatus,BlobStoreControl).
<add> * Applicable for: TriggerCompaction,RequestControl,ReplicationControl,CatchupStatus,BlobStoreControl
<ide> */
<ide> @Config("partition.ids")
<ide> @Default("")
<ide> /**
<ide> * The number of replicas of each partition that have to be within "acceptable.lag.in.bytes" in case of catchup
<ide> * status requests. The min of this value or the total count of replicas -1 is considered.
<del> * Applicable for: CatchupStatus
<add> * Applicable for: CatchupStatus,BlobStoreControl
<ide> */
<ide> @Config("num.replicas.caught.up.per.partition")
<ide> @Default("Short.MAX_VALUE")
<ide> }
<ide> }
<ide> break;
<add> case BlobStoreControl:
<add> if (config.partitionIds.length > 0 && !config.partitionIds[0].isEmpty()) {
<add> for (String partitionIdStr : config.partitionIds) {
<add> PartitionId partitionId = getPartitionIdFromStr(partitionIdStr, clusterMap);
<add> sendBlobStoreControlRequest(serverAdminTool, dataNodeId, partitionId,
<add> config.numReplicasCaughtUpPerPartition, config.enableState);
<add> }
<add> } else {
<add> LOGGER.error("There were no partitions provided to be controlled (Start/Stop)");
<add> }
<add> break;
<ide> default:
<ide> throw new IllegalStateException("Recognized but unsupported operation: " + config.typeOfOperation);
<ide> }
<ide> * @param dataNodeId the {@link DataNodeId} to send the request to.
<ide> * @param partitionId the partition id on which the operation will take place. Can be {@code null}.
<ide> * @param origins the names of the datacenters from which replication should be controlled.
<del> * @param enable the enable (or disable) status required for {@code toControl}.
<add> * @param enable the enable (or disable) status required for replication control.
<ide> * @throws IOException
<ide> * @throws TimeoutException
<ide> */
<ide> }
<ide>
<ide> /**
<add> * Sends a {@link BlobStoreControlAdminRequest} to {@code dataNodeId} to set enable status of controlling BlobStore
<add> * to {@code enable} for {@code partitionId}.
<add> * @param serverAdminTool the {@link ServerAdminTool} instance to use.
<add> * @param dataNodeId the {@link DataNodeId} to send the request to.
<add> * @param partitionId the partition id on which the operation will take place. Can be {@code null}.
<add> * @param numReplicasCaughtUpPerPartition the minimum number of peers should catch up with the partition.
<add> * @param enable the enable (or disable) status required for BlobStore control.
<add> * @throws IOException
<add> * @throws TimeoutException
<add> */
<add> private static void sendBlobStoreControlRequest(ServerAdminTool serverAdminTool, DataNodeId dataNodeId,
<add> PartitionId partitionId, short numReplicasCaughtUpPerPartition, boolean enable)
<add> throws IOException, TimeoutException {
<add> ServerErrorCode errorCode =
<add> serverAdminTool.controlBlobStore(dataNodeId, partitionId, numReplicasCaughtUpPerPartition, enable);
<add> if (errorCode == ServerErrorCode.No_Error) {
<add> LOGGER.info("Enable state of controlling BlobStore from has been set to {} for {} on {}", enable, partitionId,
<add> dataNodeId);
<add> } else {
<add> LOGGER.error(
<add> "From {}, received server error code {} for request to set enable state {} for controlling BlobStore for {}",
<add> dataNodeId, errorCode, enable, partitionId);
<add> }
<add> }
<add>
<add> /**
<ide> * Creates an instance of the server admin tool
<ide> * @param metricRegistry the {@link MetricRegistry} to use for metrics
<ide> * @param sslFactory the {@link SSLFactory} to use
<ide> new AdminRequest(AdminRequestOrResponseType.ReplicationControl, partitionId, correlationId.incrementAndGet(),
<ide> CLIENT_ID);
<ide> ReplicationControlAdminRequest controlRequest = new ReplicationControlAdminRequest(origins, enable, adminRequest);
<add> ByteBuffer responseBytes = sendRequestGetResponse(dataNodeId, controlRequest);
<add> AdminResponse adminResponse = AdminResponse.readFrom(new DataInputStream(new ByteBufferInputStream(responseBytes)));
<add> return adminResponse.getError();
<add> }
<add>
<add> /**
<add> * Sends a {@link BlobStoreControlAdminRequest} to start or stop a store associated with {@code partitionId}
<add> * on {@code dataNodeId}.
<add> * @param dataNodeId the {@link DataNodeId} to contact.
<add> * @param partitionId the {@link PartitionId} to start or stop.
<add> * @param numReplicasCaughtUpPerPartition the minimum number of peers should catch up with partition if the store is
<add> * being stopped
<add> * @param enable the enable (or disable) status required for BlobStore control.
<add> * @return the {@link ServerErrorCode} that is returned.
<add> * @throws IOException
<add> * @throws TimeoutException
<add> */
<add> private ServerErrorCode controlBlobStore(DataNodeId dataNodeId, PartitionId partitionId,
<add> short numReplicasCaughtUpPerPartition, boolean enable) throws IOException, TimeoutException {
<add> AdminRequest adminRequest =
<add> new AdminRequest(AdminRequestOrResponseType.BlobStoreControl, partitionId, correlationId.incrementAndGet(),
<add> CLIENT_ID);
<add> BlobStoreControlAdminRequest controlRequest =
<add> new BlobStoreControlAdminRequest(numReplicasCaughtUpPerPartition, enable, adminRequest);
<ide> ByteBuffer responseBytes = sendRequestGetResponse(dataNodeId, controlRequest);
<ide> AdminResponse adminResponse = AdminResponse.readFrom(new DataInputStream(new ByteBufferInputStream(responseBytes)));
<ide> return adminResponse.getError(); |
|
Java | bsd-3-clause | 037fc459bfeef6e448033e3b4bbef9259a2b0edb | 0 | orwell-int/proxy-robots,miludmann/proxy-robots,miludmann/proxy-robots,orwell-int/proxy-robots | package orwell.proxy;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import orwell.proxy.config.*;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.*;
/**
* Tests for {@link ConfigModel}.
*
* @author [email protected] (Michael Ludmann)
*/
@RunWith(JUnit4.class)
public class ConfigurationTest {
final static Logger logback = LoggerFactory.getLogger(ConfigurationTest.class);
private static final String CONFIGURATION_FILE_TEST = "/configurationTest.xml";
private static final String CONFIGURATION_URL_TEST = "https://github.com/orwell-int/proxy-robots/blob/master/proxy-robots-module/src/main/resources/configuration.xml";
@Rule
public ExpectedException exception = ExpectedException.none();
private ConfigCli configCli;
private Configuration buildConfigTest(final String fileName, final EnumConfigFileType configFileType) {
configCli = new ConfigCli(fileName, configFileType);
return new Configuration(configCli);
}
@Before
public void setUp() {
assertNotNull("Test file missing", getClass().getResource(CONFIGURATION_FILE_TEST));
}
@Test
public void testPopulateConfigModel() {
assertTrue(buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).isPopulated);
}
@Test
public void testProxyList() {
final ConfigProxy configProxy;
configProxy = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
.getConfigProxy();
assertEquals(3, configProxy.getConfigServerGames().size());
try {
assertNotNull(configProxy.getConfigServerGame());
} catch (Exception e) {
logback.error(e.getMessage());
}
assertEquals("localhost", configProxy.getConfigServerGames().get(2)
.getName());
}
@Test
public void testServerGameElement() {
final ConfigServerGame configServerGame;
try {
configServerGame = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
.getConfigProxy().getConfigServerGame();
assertEquals("192.168.1.46", configServerGame.getIp());
assertEquals(9000, configServerGame.getPushPort());
assertEquals(9001, configServerGame.getSubPort());
} catch (Exception e) {
fail(e.toString());
}
}
@Test
public void testCommonElements() {
final ConfigProxy configProxy;
configProxy = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
.getConfigProxy();
assertEquals(1000, configProxy.getSenderLinger());
assertEquals(1000, configProxy.getReceiverLinger());
}
@Test
public void testRobotsList() {
final ConfigRobots configRobots;
configRobots = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
.getConfigRobots();
assertEquals(2, configRobots.getConfigTanks().size());
try {
assertNotNull(configRobots.getConfigTank("BananaOne"));
} catch (Exception e) {
fail(e.toString());
}
}
@Test
public void testTankElement() {
final ConfigTank configTank;
try {
configTank = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel().getConfigRobots()
.getConfigTank("BananaOne");
assertEquals("001653119482", configTank.getBluetoothID());
assertEquals("Daneel", configTank.getBluetoothName());
assertNotNull(configTank.getConfigCamera());
assertEquals("192.168.1.50", configTank.getConfigCamera().getIp());
assertEquals(9100, configTank.getConfigCamera().getPort());
assertEquals("Yellow hull -- TO BE BETTER CONFIGURED", configTank.getImage());
} catch (Exception e) {
fail(e.toString());
}
}
@Test
public void testRobotsToRegister() {
final ConfigRobots configRobots;
configRobots = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
.getConfigRobots();
assertEquals(1, configRobots.getConfigRobotsToRegister().size());
}
@Test
public void testConfigurationFailsWithEmptyFile() {
logback.debug("IN");
File file = null;
try {
// Create empty file
file = File.createTempFile("testConfigurationWithFile", ".tmp");
} catch (IOException e) {
logback.error(e.getMessage());
}
// Population fails since file is empty
assertFalse(buildConfigTest(file.getAbsolutePath(), EnumConfigFileType.FILE).isPopulated);
logback.debug("OUT");
}
@Test
public void testConfigurationFailsWithURL() {
logback.debug("IN");
assertFalse(buildConfigTest(CONFIGURATION_URL_TEST, EnumConfigFileType.URL).isPopulated);
logback.debug("OUT");
}
}
| proxy-robots-module/src/test/java/orwell/proxy/ConfigurationTest.java | package orwell.proxy;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import orwell.proxy.config.*;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.*;
/**
* Tests for {@link ConfigModel}.
*
* @author [email protected] (Michael Ludmann)
*/
@RunWith(JUnit4.class)
public class ConfigurationTest {
final static Logger logback = LoggerFactory.getLogger(ConfigurationTest.class);
private static final String CONFIGURATION_FILE_TEST = "/configurationTest.xml";
private static final String CONFIGURATION_URL_TEST = "https://github.com/orwell-int/proxy-robots/blob/master/proxy-robots-module/src/main/resources/configuration.xml";
@Rule
public ExpectedException exception = ExpectedException.none();
private ConfigCli configCli;
private Configuration buildConfigTest(String fileName, EnumConfigFileType configFileType) {
configCli = new ConfigCli(fileName, configFileType);
Configuration configTest = new Configuration(configCli);
return configTest;
}
@Before
public void setUp() {
assertNotNull("Test file missing", getClass().getResource(CONFIGURATION_FILE_TEST));
}
@Test
public void testPopulateConfigModel() {
assertTrue(buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).isPopulated);
}
@Test
public void testProxyList() {
ConfigProxy configProxy = null;
configProxy = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
.getConfigProxy();
assertEquals(3, configProxy.getConfigServerGames().size());
try {
assertNotNull(configProxy.getConfigServerGame());
} catch (Exception e) {
logback.error(e.getMessage());
}
assertEquals("localhost", configProxy.getConfigServerGames().get(2)
.getName());
}
@Test
public void testServerGameElement() {
ConfigServerGame configServerGame;
try {
configServerGame = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
.getConfigProxy().getConfigServerGame();
assertEquals("192.168.1.46", configServerGame.getIp());
assertEquals(9000, configServerGame.getPushPort());
assertEquals(9001, configServerGame.getSubPort());
} catch (Exception e) {
fail(e.toString());
}
}
@Test
public void testCommonElements() {
ConfigProxy configProxy = null;
configProxy = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
.getConfigProxy();
assertEquals(1000, configProxy.getSenderLinger());
assertEquals(1000, configProxy.getReceiverLinger());
}
@Test
public void testRobotsList() {
ConfigRobots configRobots = null;
configRobots = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
.getConfigRobots();
assertEquals(2, configRobots.getConfigTanks().size());
try {
assertNotNull(configRobots.getConfigTank("BananaOne"));
} catch (Exception e) {
fail(e.toString());
}
}
@Test
public void testTankElement() {
ConfigTank configTank;
try {
configTank = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel().getConfigRobots()
.getConfigTank("BananaOne");
assertEquals("001653119482", configTank.getBluetoothID());
assertEquals("Daneel", configTank.getBluetoothName());
assertNotNull(configTank.getConfigCamera());
assertEquals("192.168.1.50", configTank.getConfigCamera().getIp());
assertEquals(9100, configTank.getConfigCamera().getPort());
assertEquals("Yellow hull -- TO BE BETTER CONFIGURED", configTank.getImage());
} catch (Exception e) {
fail(e.toString());
}
}
@Test
public void testRobotsToRegister() {
ConfigRobots configRobots = null;
configRobots = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
.getConfigRobots();
assertEquals(1, configRobots.getConfigRobotsToRegister().size());
}
@Test
public void testConfigurationFailsWithEmptyFile() {
logback.debug("IN");
File file = null;
try {
// Create empty file
file = File.createTempFile("testConfigurationWithFile", ".tmp");
} catch (IOException e) {
logback.error(e.getMessage());
}
// Population fails since file is empty
assertFalse(buildConfigTest(file.getAbsolutePath(), EnumConfigFileType.FILE).isPopulated);
logback.debug("OUT");
}
@Test
public void testConfigurationFailsWithURL() {
logback.debug("IN");
assertFalse(buildConfigTest(CONFIGURATION_URL_TEST, EnumConfigFileType.URL).isPopulated);
logback.debug("OUT");
}
}
| Refactor test code
| proxy-robots-module/src/test/java/orwell/proxy/ConfigurationTest.java | Refactor test code | <ide><path>roxy-robots-module/src/test/java/orwell/proxy/ConfigurationTest.java
<ide> public ExpectedException exception = ExpectedException.none();
<ide> private ConfigCli configCli;
<ide>
<del> private Configuration buildConfigTest(String fileName, EnumConfigFileType configFileType) {
<add> private Configuration buildConfigTest(final String fileName, final EnumConfigFileType configFileType) {
<ide> configCli = new ConfigCli(fileName, configFileType);
<del> Configuration configTest = new Configuration(configCli);
<del> return configTest;
<add> return new Configuration(configCli);
<ide> }
<ide>
<ide> @Before
<ide> @Test
<ide> public void testPopulateConfigModel() {
<ide>
<del>
<ide> assertTrue(buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).isPopulated);
<del>
<ide> }
<ide>
<ide> @Test
<ide> public void testProxyList() {
<ide>
<del> ConfigProxy configProxy = null;
<add> final ConfigProxy configProxy;
<ide>
<ide> configProxy = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
<ide> .getConfigProxy();
<ide> @Test
<ide> public void testServerGameElement() {
<ide>
<del> ConfigServerGame configServerGame;
<add> final ConfigServerGame configServerGame;
<ide> try {
<ide> configServerGame = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
<ide> .getConfigProxy().getConfigServerGame();
<ide> @Test
<ide> public void testCommonElements() {
<ide>
<del> ConfigProxy configProxy = null;
<add> final ConfigProxy configProxy;
<ide> configProxy = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
<ide> .getConfigProxy();
<ide>
<ide> @Test
<ide> public void testRobotsList() {
<ide>
<del> ConfigRobots configRobots = null;
<add> final ConfigRobots configRobots;
<ide> configRobots = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
<ide> .getConfigRobots();
<ide>
<ide> @Test
<ide> public void testTankElement() {
<ide>
<del> ConfigTank configTank;
<add> final ConfigTank configTank;
<ide> try {
<ide> configTank = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel().getConfigRobots()
<ide> .getConfigTank("BananaOne");
<ide> @Test
<ide> public void testRobotsToRegister() {
<ide>
<del> ConfigRobots configRobots = null;
<add> final ConfigRobots configRobots;
<ide> configRobots = buildConfigTest(CONFIGURATION_FILE_TEST, EnumConfigFileType.RESOURCE).getConfigModel()
<ide> .getConfigRobots();
<ide> |
|
Java | apache-2.0 | b9321bc6f07385380baf0a28784ba45c88f0a818 | 0 | T-Systems-MMS/perfsig-jenkins,T-Systems-MMS/perfsig-jenkins | /*
* Copyright (c) 2008-2015, DYNATRACE LLC
* 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 dynaTrace software 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 de.tsystems.mms.apm.performancesignature.dynatrace.rest;
import de.tsystems.mms.apm.performancesignature.util.PerfSigUIUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
public class ManagementURLBuilder {
private static final Logger LOGGER = Logger.getLogger(ManagementURLBuilder.class.getName());
private String serverAddress;
private String parameters;
public String getPostParameters() {
return this.parameters;
}
public void setServerAddress(final String serverAddress) {
this.serverAddress = serverAddress;
}
public URL serverVersionURL() {
try {
final String s = String.format("%1$s/rest/management/version", this.serverAddress);
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL reanalyzeSessionURL(final String sessionName) {
try {
return new URL(String.format("%1$s/rest/management/sessions/%2$s/reanalyze", this.serverAddress,
PerfSigUIUtils.encodeString(sessionName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL reanalyzeSessionStatusURL(final String sessionName) {
try {
return new URL(String.format("%1$s/rest/management/sessions/%2$s/reanalyze/finished", this.serverAddress,
PerfSigUIUtils.encodeString(sessionName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL storePurePathsURL(final String profileName, final String sessionName, final String timeframeStart, final String timeframeEnd,
final String recordingOption, final boolean sessionLocked, final boolean appendTimestamp) {
try {
return new URL(String.format("%1$s/rest/management/profiles/%2$s/storepurepaths?storedSessionName=%3$s&timeframeStart=%4$s&timeframeEnd=%5$s&" +
"recordingOption=%6$s&isSessionLocked=%7$s&appendTimestamp=%8$s",
this.serverAddress, PerfSigUIUtils.encodeString(profileName), PerfSigUIUtils.encodeString(sessionName), timeframeStart, timeframeEnd,
StringUtils.isBlank(recordingOption) ? "all" : recordingOption, sessionLocked, appendTimestamp));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL startRecordingURL(final String profileName, final String sessionName, final String description,
final String recordingOption, final boolean sessionLocked, final boolean isTimeStampAllowed) {
try {
this.parameters = String.format("recordingOption=%1$s&isSessionLocked=%2$s&isTimeStampAllowed=%3$s&description=%4$s&presentableName=%5$s",
StringUtils.isBlank(recordingOption) ? "all" : recordingOption, sessionLocked, isTimeStampAllowed,
StringUtils.isBlank(description) ? "" : PerfSigUIUtils.encodeString(description),
StringUtils.isBlank(sessionName) ? PerfSigUIUtils.encodeString(profileName) : PerfSigUIUtils.encodeString(sessionName));
final String url = String.format("%1$s/rest/management/profiles/%2$s/startrecording", this.serverAddress,
PerfSigUIUtils.encodeString(profileName));
return new URL(url);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL stopRecordingURL(final String profileName) {
try {
final String s = String.format("%1$s/rest/management/profiles/%2$s/stoprecording", this.serverAddress,
PerfSigUIUtils.encodeString(profileName));
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL listProfilesURL() {
try {
final String s = String.format("%1$s/rest/management/profiles/", this.serverAddress);
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL listConfigurationsURL(final String profileName) {
try {
final String s = String.format("%1$s/rest/management/profiles/%2$s/configurations", this.serverAddress,
PerfSigUIUtils.encodeString(profileName));
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL activateConfigurationURL(final String profileName, final String configuration) {
try {
final String s = String.format("%1$s/rest/management/profiles/%2$s/configurations/%3$s/activate", this.serverAddress,
PerfSigUIUtils.encodeString(profileName), PerfSigUIUtils.encodeString(configuration));
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL listAgentsURL() {
try {
final String s = String.format("%1$s/rest/management/agents", this.serverAddress);
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL hotSensorPlacementURL(final int agentId) {
try {
final String s = String.format("%1$s/rest/management/agents/%2$s/hotsensorplacement", this.serverAddress,
PerfSigUIUtils.encodeString(String.valueOf(agentId)));
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL listSessionsURL() {
try {
final String s = String.format("%1$s/rest/management/sessions?type=purepath", this.serverAddress);
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL listDashboardsURL() {
try {
final String s = String.format("%1$s/rest/management/dashboards", this.serverAddress);
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL downloadSessionURL(final String sessionName) {
try {
final String s = String.format("%1$s/rest/management/sessions/%2$s/export", this.serverAddress, PerfSigUIUtils.encodeString(sessionName));
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public StringBuilder resourceDumpURL(final String agentName, final String hostName, final int processId, final boolean sessionLocked) {
StringBuilder builder = new StringBuilder();
builder.append(String.format("agentName=%1$s&isSessionLocked=%2$s&hostName=%3$s&processId=%4$s",
agentName, String.valueOf(sessionLocked), hostName, String.valueOf(processId)));
return builder;
}
public URL memoryDumpStatusURL(final String profileName, final String memoryDumpName) {
try {
return new URL(String.format("%1$s/rest/management/profiles/%2$s/memorydumpcreated/%3$s", this.serverAddress,
PerfSigUIUtils.encodeString(profileName), PerfSigUIUtils.encodeString(memoryDumpName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL memoryDumpURL(final String profileName, final String agentName, final String hostName, final int processId,
final String dumpType, final boolean sessionLocked, final boolean captureStrings, final boolean capturePrimitives,
final boolean autoPostProcess, final boolean dogc) {
try {
StringBuilder builder = resourceDumpURL(agentName, hostName, processId, sessionLocked);
builder.append("&type=").append(StringUtils.isBlank(dumpType) ? "simple" : dumpType);
builder.append(captureStrings ? "&capturestrings=true" : "");
builder.append(capturePrimitives ? "&captureprimitives=true" : "");
builder.append(autoPostProcess ? "&autopostprocess=true" : "");
builder.append(dogc ? "&dogc=true" : "");
this.parameters = builder.toString();
return new URL(String.format("%1$s/rest/management/profiles/%2$s/memorydump",
this.serverAddress, PerfSigUIUtils.encodeString(profileName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL threadDumpStatusURL(final String profileName, final String threadDumpName) {
try {
return new URL(String.format("%1$s/rest/management/profiles/%2$s/threaddumpcreated/%3$s", this.serverAddress,
PerfSigUIUtils.encodeString(profileName), PerfSigUIUtils.encodeString(threadDumpName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL threadDumpURL(final String profileName, final String agentName, final String hostName, final int processId, final boolean sessionLocked) {
try {
this.parameters = String.format("agentName=%1$s&isSessionLocked=%2$s&hostName=%3$s&processId=%4$s", agentName, sessionLocked, hostName, processId);
return new URL(String.format("%1$s/rest/management/profiles/%2$s/threaddump", this.serverAddress, PerfSigUIUtils.encodeString(profileName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL registerTestRunURL(final String profileName) {
try {
return new URL(String.format("%1$s/rest/management/profiles/%2$s/testruns", this.serverAddress, PerfSigUIUtils.encodeString(profileName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL testRunDetailsURL(final String profileName, final String testRunID) {
try {
return new URL(String.format("%1$s/rest/management/profiles/%2$s/testruns/%3$s.xml", this.serverAddress,
PerfSigUIUtils.encodeString(profileName), testRunID));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
}
| dynatrace/src/main/java/de/tsystems/mms/apm/performancesignature/dynatrace/rest/ManagementURLBuilder.java | /*
* Copyright (c) 2008-2015, DYNATRACE LLC
* 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 dynaTrace software 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 de.tsystems.mms.apm.performancesignature.dynatrace.rest;
import de.tsystems.mms.apm.performancesignature.util.PerfSigUIUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
public class ManagementURLBuilder {
private static final Logger LOGGER = Logger.getLogger(ManagementURLBuilder.class.getName());
private String serverAddress;
private String parameters;
public String getPostParameters() {
return this.parameters;
}
public void setServerAddress(final String serverAddress) {
this.serverAddress = serverAddress;
}
public URL serverVersionURL() {
try {
final String s = String.format("%1$s/rest/management/version", this.serverAddress);
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL reanalyzeSessionURL(final String sessionName) {
try {
return new URL(String.format("%1$s/rest/management/sessions/%2$s/reanalyze", this.serverAddress,
PerfSigUIUtils.encodeString(sessionName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL reanalyzeSessionStatusURL(final String sessionName) {
try {
return new URL(String.format("%1$s/rest/management/sessions/%2$s/reanalyze/finished", this.serverAddress,
PerfSigUIUtils.encodeString(sessionName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL storePurePathsURL(final String profileName, final String sessionName, final String timeframeStart, final String timeframeEnd,
final String recordingOption, final boolean sessionLocked, final boolean appendTimestamp) {
try {
return new URL(String.format("%1$s/rest/management/profiles/%2$s/storepurepaths?storedSessionName=%3$s&timeframeStart=%4$s&timeframeEnd=%5$s&" +
"recordingOption=%6$s&isSessionLocked=%7$s&appendTimestamp=%8$s",
this.serverAddress, PerfSigUIUtils.encodeString(profileName), PerfSigUIUtils.encodeString(sessionName), timeframeStart, timeframeEnd,
StringUtils.isBlank(recordingOption) ? "all" : recordingOption, sessionLocked, appendTimestamp));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL startRecordingURL(final String profileName, final String sessionName, final String description,
String recordingOption, final boolean sessionLocked, final boolean isTimeStampAllowed) {
if (StringUtils.isBlank(recordingOption)) {
recordingOption = "all";
}
try {
this.parameters = String.format("recordingOption=%1$s&isSessionLocked=%2$s&isTimeStampAllowed=%3$s&description=%4$s&presentableName=%5$s",
recordingOption, sessionLocked, isTimeStampAllowed, StringUtils.isBlank(description) ? "" : PerfSigUIUtils.encodeString(description),
StringUtils.isBlank(sessionName) ? PerfSigUIUtils.encodeString(profileName) : PerfSigUIUtils.encodeString(sessionName));
final String url = String.format("%1$s/rest/management/profiles/%2$s/startrecording", this.serverAddress,
PerfSigUIUtils.encodeString(profileName));
return new URL(url);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL stopRecordingURL(final String profileName) {
try {
final String s = String.format("%1$s/rest/management/profiles/%2$s/stoprecording", this.serverAddress,
PerfSigUIUtils.encodeString(profileName));
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL listProfilesURL() {
try {
final String s = String.format("%1$s/rest/management/profiles/", this.serverAddress);
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL listConfigurationsURL(final String profileName) {
try {
final String s = String.format("%1$s/rest/management/profiles/%2$s/configurations", this.serverAddress,
PerfSigUIUtils.encodeString(profileName));
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL activateConfigurationURL(final String profileName, final String configuration) {
try {
final String s = String.format("%1$s/rest/management/profiles/%2$s/configurations/%3$s/activate", this.serverAddress,
PerfSigUIUtils.encodeString(profileName), PerfSigUIUtils.encodeString(configuration));
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL listAgentsURL() {
try {
final String s = String.format("%1$s/rest/management/agents", this.serverAddress);
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL hotSensorPlacementURL(final int agentId) {
try {
final String s = String.format("%1$s/rest/management/agents/%2$s/hotsensorplacement", this.serverAddress,
PerfSigUIUtils.encodeString(String.valueOf(agentId)));
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL listSessionsURL() {
try {
final String s = String.format("%1$s/rest/management/sessions?type=purepath", this.serverAddress);
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL listDashboardsURL() {
try {
final String s = String.format("%1$s/rest/management/dashboards", this.serverAddress);
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL downloadSessionURL(final String sessionName) {
try {
final String s = String.format("%1$s/rest/management/sessions/%2$s/export", this.serverAddress, PerfSigUIUtils.encodeString(sessionName));
return new URL(s);
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public StringBuilder resourceDumpURL(final String agentName, final String hostName, final int processId, final boolean sessionLocked) {
StringBuilder builder = new StringBuilder();
builder.append(String.format("agentName=%1$s&isSessionLocked=%2$s&hostName=%3$s&processId=%4$s",
agentName, String.valueOf(sessionLocked), hostName, String.valueOf(processId)));
return builder;
}
public URL memoryDumpStatusURL(final String profileName, final String memoryDumpName) {
try {
return new URL(String.format("%1$s/rest/management/profiles/%2$s/memorydumpcreated/%3$s", this.serverAddress,
PerfSigUIUtils.encodeString(profileName), PerfSigUIUtils.encodeString(memoryDumpName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL memoryDumpURL(final String profileName, final String agentName, final String hostName, final int processId,
String dumpType, final boolean sessionLocked, final boolean captureStrings, final boolean capturePrimitives,
final boolean autoPostProcess, final boolean dogc) {
if (StringUtils.isBlank(dumpType)) {
dumpType = "simple";
}
try {
StringBuilder builder = resourceDumpURL(agentName, hostName, processId, sessionLocked);
builder.append("&type=").append(dumpType);
builder.append(captureStrings ? "&capturestrings=true" : "");
builder.append(capturePrimitives ? "&captureprimitives=true" : "");
builder.append(autoPostProcess ? "&autopostprocess=true" : "");
builder.append(dogc ? "&dogc=true" : "");
this.parameters = builder.toString();
return new URL(String.format("%1$s/rest/management/profiles/%2$s/memorydump",
this.serverAddress, PerfSigUIUtils.encodeString(profileName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL threadDumpStatusURL(final String profileName, final String threadDumpName) {
try {
return new URL(String.format("%1$s/rest/management/profiles/%2$s/threaddumpcreated/%3$s", this.serverAddress,
PerfSigUIUtils.encodeString(profileName), PerfSigUIUtils.encodeString(threadDumpName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL threadDumpURL(final String profileName, final String agentName, final String hostName, final int processId, final boolean sessionLocked) {
try {
this.parameters = String.format("agentName=%1$s&isSessionLocked=%2$s&hostName=%3$s&processId=%4$s", agentName, sessionLocked, hostName, processId);
return new URL(String.format("%1$s/rest/management/profiles/%2$s/threaddump", this.serverAddress, PerfSigUIUtils.encodeString(profileName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL registerTestRunURL(final String profileName) {
try {
return new URL(String.format("%1$s/rest/management/profiles/%2$s/testruns", this.serverAddress, PerfSigUIUtils.encodeString(profileName)));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
public URL testRunDetailsURL(final String profileName, final String testRunID) {
try {
return new URL(String.format("%1$s/rest/management/profiles/%2$s/testruns/%3$s.xml", this.serverAddress,
PerfSigUIUtils.encodeString(profileName), testRunID));
} catch (MalformedURLException e) {
LOGGER.severe(ExceptionUtils.getFullStackTrace(e));
}
return null;
}
}
| don't reuse method parameter
| dynatrace/src/main/java/de/tsystems/mms/apm/performancesignature/dynatrace/rest/ManagementURLBuilder.java | don't reuse method parameter | <ide><path>ynatrace/src/main/java/de/tsystems/mms/apm/performancesignature/dynatrace/rest/ManagementURLBuilder.java
<ide> }
<ide>
<ide> public URL startRecordingURL(final String profileName, final String sessionName, final String description,
<del> String recordingOption, final boolean sessionLocked, final boolean isTimeStampAllowed) {
<del> if (StringUtils.isBlank(recordingOption)) {
<del> recordingOption = "all";
<del> }
<add> final String recordingOption, final boolean sessionLocked, final boolean isTimeStampAllowed) {
<ide> try {
<ide> this.parameters = String.format("recordingOption=%1$s&isSessionLocked=%2$s&isTimeStampAllowed=%3$s&description=%4$s&presentableName=%5$s",
<del> recordingOption, sessionLocked, isTimeStampAllowed, StringUtils.isBlank(description) ? "" : PerfSigUIUtils.encodeString(description),
<add> StringUtils.isBlank(recordingOption) ? "all" : recordingOption, sessionLocked, isTimeStampAllowed,
<add> StringUtils.isBlank(description) ? "" : PerfSigUIUtils.encodeString(description),
<ide> StringUtils.isBlank(sessionName) ? PerfSigUIUtils.encodeString(profileName) : PerfSigUIUtils.encodeString(sessionName));
<ide> final String url = String.format("%1$s/rest/management/profiles/%2$s/startrecording", this.serverAddress,
<ide> PerfSigUIUtils.encodeString(profileName));
<ide> }
<ide>
<ide> public URL memoryDumpURL(final String profileName, final String agentName, final String hostName, final int processId,
<del> String dumpType, final boolean sessionLocked, final boolean captureStrings, final boolean capturePrimitives,
<add> final String dumpType, final boolean sessionLocked, final boolean captureStrings, final boolean capturePrimitives,
<ide> final boolean autoPostProcess, final boolean dogc) {
<del> if (StringUtils.isBlank(dumpType)) {
<del> dumpType = "simple";
<del> }
<ide> try {
<ide> StringBuilder builder = resourceDumpURL(agentName, hostName, processId, sessionLocked);
<del> builder.append("&type=").append(dumpType);
<add> builder.append("&type=").append(StringUtils.isBlank(dumpType) ? "simple" : dumpType);
<ide> builder.append(captureStrings ? "&capturestrings=true" : "");
<ide> builder.append(capturePrimitives ? "&captureprimitives=true" : "");
<ide> builder.append(autoPostProcess ? "&autopostprocess=true" : ""); |
|
Java | apache-2.0 | 27de594c31474824ab4d53d80e682707064008e5 | 0 | cogfor/mcf-cogfor,apache/manifoldcf,gladyscarrizales/manifoldcf,apache/manifoldcf,gladyscarrizales/manifoldcf,gladyscarrizales/manifoldcf,kishorejangid/manifoldcf,kishorejangid/manifoldcf,cogfor/mcf-cogfor,kishorejangid/manifoldcf,kishorejangid/manifoldcf,gladyscarrizales/manifoldcf,kishorejangid/manifoldcf,cogfor/mcf-cogfor,apache/manifoldcf,cogfor/mcf-cogfor,cogfor/mcf-cogfor,apache/manifoldcf,gladyscarrizales/manifoldcf,gladyscarrizales/manifoldcf,kishorejangid/manifoldcf,apache/manifoldcf,cogfor/mcf-cogfor,apache/manifoldcf | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $Id: CommonsHTTPSender.java 988245 2010-08-23 18:39:35Z kwright $
*/
package org.apache.manifoldcf.crawler.connectors.sharepoint;
import org.apache.manifoldcf.core.common.XThreadInputStream;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.components.net.CommonsHTTPClientProperties;
import org.apache.axis.components.net.CommonsHTTPClientPropertiesFactory;
import org.apache.axis.components.net.TransportClientProperties;
import org.apache.axis.components.net.TransportClientPropertiesFactory;
import org.apache.axis.transport.http.HTTPConstants;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.soap.SOAP12Constants;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.utils.JavaUtils;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.NetworkUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.Header;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.ProtocolVersion;
import org.apache.http.util.EntityUtils;
import org.apache.http.message.BasicHeader;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.client.RedirectException;
import org.apache.http.client.CircularRedirectException;
import org.apache.http.NoHttpResponseException;
import org.apache.http.HttpException;
import org.apache.commons.logging.Log;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPException;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.InputStreamReader;
import java.io.Writer;
import java.io.StringWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
/* Class to use httpcomponents to communicate with a SOAP server.
* I've replaced the original rather complicated class with a much simpler one that
* relies on having an HttpClient object passed into the invoke() method. Since
* the object is already set up, not much needs to be done in here.
*/
public class CommonsHTTPSender extends BasicHandler {
/** Field log */
protected static Log log =
LogFactory.getLog(CommonsHTTPSender.class.getName());
/** Properties */
protected CommonsHTTPClientProperties clientProperties;
public CommonsHTTPSender() {
this.clientProperties = CommonsHTTPClientPropertiesFactory.create();
}
/**
* invoke creates a socket connection, sends the request SOAP message and then
* reads the response SOAP message back from the SOAP server
*
* @param msgContext the messsage context
*
* @throws AxisFault
*/
public void invoke(MessageContext msgContext) throws AxisFault {
if (log.isDebugEnabled())
{
log.debug(Messages.getMessage("enter00",
"CommonsHTTPSender::invoke"));
}
// Catch all exceptions and turn them into AxisFaults
try
{
// Get the URL
URL targetURL =
new URL(msgContext.getStrProp(MessageContext.TRANS_URL));
// Get the HttpClient
HttpClient httpClient = (HttpClient)msgContext.getProperty(SPSProxyHelper.HTTPCLIENT_PROPERTY);
boolean posting = true;
// If we're SOAP 1.2, allow the web method to be set from the
// MessageContext.
if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
if (webMethod != null) {
posting = webMethod.equals(HTTPConstants.HEADER_POST);
}
}
boolean http10 = false;
String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
if (httpVersion != null) {
if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
http10 = true;
}
// assume 1.1
}
HttpRequestBase method;
if (posting) {
HttpPost postMethod = new HttpPost(targetURL.toString());
// set false as default, addContetInfo can overwrite
HttpProtocolParams.setUseExpectContinue(postMethod.getParams(),false);
Message reqMessage = msgContext.getRequestMessage();
boolean httpChunkStream = addContextInfo(postMethod, msgContext);
HttpEntity requestEntity = null;
requestEntity = new MessageRequestEntity(reqMessage, httpChunkStream,
http10 || !httpChunkStream);
postMethod.setEntity(requestEntity);
method = postMethod;
} else {
method = new HttpGet(targetURL.toString());
}
if (http10)
HttpProtocolParams.setVersion(method.getParams(),new ProtocolVersion("HTTP",1,0));
BackgroundHTTPThread methodThread = new BackgroundHTTPThread(httpClient,method);
methodThread.start();
try
{
int returnCode = methodThread.getResponseCode();
String contentType =
getHeader(methodThread, HTTPConstants.HEADER_CONTENT_TYPE);
String contentLocation =
getHeader(methodThread, HTTPConstants.HEADER_CONTENT_LOCATION);
String contentLength =
getHeader(methodThread, HTTPConstants.HEADER_CONTENT_LENGTH);
if ((returnCode > 199) && (returnCode < 300)) {
// SOAP return is OK - so fall through
} else if (msgContext.getSOAPConstants() ==
SOAPConstants.SOAP12_CONSTANTS) {
// For now, if we're SOAP 1.2, fall through, since the range of
// valid result codes is much greater
} else if ((contentType != null) && !contentType.equals("text/html")
&& ((returnCode > 499) && (returnCode < 600))) {
// SOAP Fault should be in here - so fall through
} else {
String statusMessage = methodThread.getResponseStatus();
AxisFault fault = new AxisFault("HTTP",
"(" + returnCode + ")"
+ statusMessage, null,
null);
fault.setFaultDetailString(
Messages.getMessage("return01",
"" + returnCode,
getResponseBodyAsString(methodThread)));
fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
Integer.toString(returnCode));
throw fault;
}
String contentEncoding =
methodThread.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
if (contentEncoding != null) {
AxisFault fault = new AxisFault("HTTP",
"unsupported content-encoding of '"
+ contentEncoding
+ "' found", null, null);
throw fault;
}
Map<String,List<String>> responseHeaders = methodThread.getResponseHeaders();
InputStream dataStream = methodThread.getSafeInputStream();
Message outMsg = new Message(new BackgroundInputStream(methodThread,dataStream),
false, contentType, contentLocation);
// Transfer HTTP headers of HTTP message to MIME headers of SOAP message
MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
for (String name : responseHeaders.keySet())
{
List<String> values = responseHeaders.get(name);
for (String value : values) {
responseMimeHeaders.addHeader(name,value);
}
}
outMsg.setMessageType(Message.RESPONSE);
// Put the message in the message context.
msgContext.setResponseMessage(outMsg);
// Pass off the method thread to the stream for closure
methodThread = null;
}
finally
{
if (methodThread != null)
{
methodThread.abort();
methodThread.finishUp();
}
}
/*
ExecuteMethodThread t = new ExecuteMethodThread(httpClient,targetURL.toString(),msgContext);
try
{
t.start();
t.join();
Throwable thr = t.getException();
if (thr != null)
{
if (thr instanceof RuntimeException)
throw (RuntimeException)thr;
else if (thr instanceof Exception)
throw (Exception)thr;
else
throw (Error)thr;
}
}
catch (InterruptedException e)
{
t.interrupt();
throw e;
}
*/
/*
if (log.isDebugEnabled()) {
if (null == contentLength) {
log.debug("\n"
+ Messages.getMessage("no00", "Content-Length"));
}
log.debug("\n" + Messages.getMessage("xmlRecd00"));
log.debug("-----------------------------------------------");
log.debug(msgContext.getResponseMessage().getSOAPPartAsString());
}
}
*/
} catch (AxisFault af) {
log.debug(af);
throw af;
} catch (Exception e) {
log.debug(e);
throw AxisFault.makeFault(e);
}
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("exit00",
"CommonsHTTPSender::invoke"));
}
}
/**
* Extracts info from message context.
*
* @param method Post or get method
* @param msgContext the message context
*/
private static boolean addContextInfo(HttpPost method,
MessageContext msgContext)
throws AxisFault {
boolean httpChunkStream = false;
// Get SOAPAction, default to ""
String action = msgContext.useSOAPAction()
? msgContext.getSOAPActionURI()
: "";
if (action == null) {
action = "";
}
Message msg = msgContext.getRequestMessage();
if (msg != null){
// First, transfer MIME headers of SOAPMessage to HTTP headers.
// Some of these might be overridden later.
MimeHeaders mimeHeaders = msg.getMimeHeaders();
if (mimeHeaders != null) {
for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext(); ) {
MimeHeader mimeHeader = (MimeHeader) i.next();
method.addHeader(mimeHeader.getName(),
mimeHeader.getValue());
}
}
method.setHeader(new BasicHeader(HTTPConstants.HEADER_CONTENT_TYPE,
msg.getContentType(msgContext.getSOAPConstants())));
}
method.setHeader(new BasicHeader(HTTPConstants.HEADER_SOAP_ACTION,
"\"" + action + "\""));
method.setHeader(new BasicHeader(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
// process user defined headers for information.
Hashtable userHeaderTable =
(Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);
if (userHeaderTable != null) {
for (Iterator e = userHeaderTable.entrySet().iterator();
e.hasNext();) {
Map.Entry me = (Map.Entry) e.next();
Object keyObj = me.getKey();
if (null == keyObj) {
continue;
}
String key = keyObj.toString().trim();
String value = me.getValue().toString().trim();
if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT) &&
value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
HttpProtocolParams.setUseExpectContinue(method.getParams(),true);
} else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
String val = me.getValue().toString();
if (null != val) {
httpChunkStream = JavaUtils.isTrue(val);
}
} else {
method.addHeader(key, value);
}
}
}
return httpChunkStream;
}
private static String getHeader(BackgroundHTTPThread methodThread, String headerName)
throws IOException, InterruptedException, HttpException {
String header = methodThread.getFirstHeader(headerName);
return (header == null) ? null : header.trim();
}
private static String getResponseBodyAsString(BackgroundHTTPThread methodThread)
throws IOException, InterruptedException, HttpException {
InputStream is = methodThread.getSafeInputStream();
if (is != null)
{
try
{
String charSet = methodThread.getCharSet();
if (charSet == null)
charSet = "utf-8";
char[] buffer = new char[65536];
Reader r = new InputStreamReader(is,charSet);
Writer w = new StringWriter();
try
{
while (true)
{
int amt = r.read(buffer);
if (amt == -1)
break;
w.write(buffer,0,amt);
}
}
finally
{
w.flush();
}
return w.toString();
}
finally
{
is.close();
}
}
return "";
}
private static class MessageRequestEntity implements HttpEntity {
private final Message message;
private final boolean httpChunkStream; //Use HTTP chunking or not.
private final boolean contentLengthNeeded;
public MessageRequestEntity(Message message, boolean httpChunkStream, boolean contentLengthNeeded) {
this.message = message;
this.httpChunkStream = httpChunkStream;
this.contentLengthNeeded = contentLengthNeeded;
}
@Override
public boolean isChunked() {
return httpChunkStream;
}
@Override
public void consumeContent()
throws IOException {
EntityUtils.consume(this);
}
@Override
public boolean isRepeatable() {
return true;
}
@Override
public boolean isStreaming() {
return false;
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
// MHL
return null;
}
@Override
public void writeTo(OutputStream out)
throws IOException {
try {
this.message.writeTo(out);
} catch (SOAPException e) {
throw new IOException(e.getMessage());
}
}
@Override
public long getContentLength() {
if (contentLengthNeeded) {
try {
return message.getContentLength();
} catch (Exception e) {
}
}
// Unknown (chunked) length
return -1L;
}
@Override
public Header getContentType() {
return null; // a separate header is added
}
@Override
public Header getContentEncoding() {
return null;
}
}
/** This input stream wraps a background http transaction thread, so that
* the thread is ended when the stream is closed.
*/
private static class BackgroundInputStream extends InputStream {
private BackgroundHTTPThread methodThread = null;
private InputStream xThreadInputStream = null;
/** Construct an http transaction stream. The stream is driven by a background
* thread, whose existence is tied to this class. The sequence of activity that
* this class expects is as follows:
* (1) Construct the httpclient and request object and initialize them
* (2) Construct a background method thread, and start it
* (3) If the response calls for it, call this constructor, and put the resulting stream
* into the message response
* (4) Otherwise, terminate the background method thread in the standard manner,
* being sure NOT
*/
public BackgroundInputStream(BackgroundHTTPThread methodThread, InputStream xThreadInputStream)
{
this.methodThread = methodThread;
this.xThreadInputStream = xThreadInputStream;
}
@Override
public int available()
throws IOException
{
if (xThreadInputStream != null)
return xThreadInputStream.available();
return super.available();
}
@Override
public void close()
throws IOException
{
try
{
if (xThreadInputStream != null)
{
xThreadInputStream.close();
xThreadInputStream = null;
}
}
finally
{
if (methodThread != null)
{
methodThread.abort();
try
{
methodThread.finishUp();
}
catch (InterruptedException e)
{
throw new InterruptedIOException(e.getMessage());
}
methodThread = null;
}
}
}
@Override
public void mark(int readlimit)
{
if (xThreadInputStream != null)
xThreadInputStream.mark(readlimit);
else
super.mark(readlimit);
}
@Override
public void reset()
throws IOException
{
if (xThreadInputStream != null)
xThreadInputStream.reset();
else
super.reset();
}
@Override
public boolean markSupported()
{
if (xThreadInputStream != null)
return xThreadInputStream.markSupported();
return super.markSupported();
}
@Override
public long skip(long n)
throws IOException
{
if (xThreadInputStream != null)
return xThreadInputStream.skip(n);
return super.skip(n);
}
@Override
public int read(byte[] b, int off, int len)
throws IOException
{
if (xThreadInputStream != null)
return xThreadInputStream.read(b,off,len);
return super.read(b,off,len);
}
@Override
public int read(byte[] b)
throws IOException
{
if (xThreadInputStream != null)
return xThreadInputStream.read(b);
return super.read(b);
}
@Override
public int read()
throws IOException
{
if (xThreadInputStream != null)
return xThreadInputStream.read();
return -1;
}
}
/** This thread does the actual socket communication with the server.
* It's set up so that it can be abandoned at shutdown time.
*
* The way it works is as follows:
* - it starts the transaction
* - it receives the response, and saves that for the calling class to inspect
* - it transfers the data part to an input stream provided to the calling class
* - it shuts the connection down
*
* If there is an error, the sequence is aborted, and an exception is recorded
* for the calling class to examine.
*
* The calling class basically accepts the sequence above. It starts the
* thread, and tries to get a response code. If instead an exception is seen,
* the exception is thrown up the stack.
*/
protected static class BackgroundHTTPThread extends Thread
{
/** Client and method, all preconfigured */
protected final HttpClient httpClient;
protected final HttpRequestBase executeMethod;
protected HttpResponse response = null;
protected Throwable responseException = null;
protected XThreadInputStream threadStream = null;
protected String charSet = null;
protected boolean streamCreated = false;
protected Throwable streamException = null;
protected boolean abortThread = false;
protected Throwable shutdownException = null;
protected Throwable generalException = null;
public BackgroundHTTPThread(HttpClient httpClient, HttpRequestBase executeMethod)
{
super();
setDaemon(true);
this.httpClient = httpClient;
this.executeMethod = executeMethod;
}
public void run()
{
try
{
try
{
// Call the execute method appropriately
synchronized (this)
{
if (!abortThread)
{
try
{
response = httpClient.execute(executeMethod);
}
catch (java.net.SocketTimeoutException e)
{
responseException = e;
}
catch (ConnectTimeoutException e)
{
responseException = e;
}
catch (InterruptedIOException e)
{
throw e;
}
catch (Throwable e)
{
responseException = e;
}
this.notifyAll();
}
}
// Start the transfer of the content
if (responseException == null)
{
synchronized (this)
{
if (!abortThread)
{
try
{
HttpEntity entity = response.getEntity();
InputStream bodyStream = entity.getContent();
if (bodyStream != null)
{
threadStream = new XThreadInputStream(bodyStream);
charSet = EntityUtils.getContentCharSet(entity);
}
streamCreated = true;
}
catch (java.net.SocketTimeoutException e)
{
streamException = e;
}
catch (ConnectTimeoutException e)
{
streamException = e;
}
catch (InterruptedIOException e)
{
throw e;
}
catch (Throwable e)
{
streamException = e;
}
this.notifyAll();
}
}
}
if (responseException == null && streamException == null)
{
if (threadStream != null)
{
// Stuff the content until we are done
threadStream.stuffQueue();
}
}
}
finally
{
synchronized (this)
{
try
{
executeMethod.abort();
}
catch (Throwable e)
{
shutdownException = e;
}
this.notifyAll();
}
}
}
catch (Throwable e)
{
// We catch exceptions here that should ONLY be InterruptedExceptions, as a result of the thread being aborted.
this.generalException = e;
}
}
public int getResponseCode()
throws InterruptedException, IOException, HttpException
{
// Must wait until the response object is there
while (true)
{
synchronized (this)
{
checkException(responseException);
if (response != null)
return response.getStatusLine().getStatusCode();
wait();
}
}
}
public String getResponseStatus()
throws InterruptedException, IOException, HttpException
{
// Must wait until the response object is there
while (true)
{
synchronized (this)
{
checkException(responseException);
if (response != null)
return response.getStatusLine().toString();
wait();
}
}
}
public Map<String,List<String>> getResponseHeaders()
throws InterruptedException, IOException, HttpException
{
// Must wait for the response object to appear
while (true)
{
synchronized (this)
{
checkException(responseException);
if (response != null)
{
Header[] headers = response.getAllHeaders();
Map<String,List<String>> rval = new HashMap<String,List<String>>();
int i = 0;
while (i < headers.length)
{
Header h = headers[i++];
String name = h.getName();
String value = h.getValue();
List<String> values = rval.get(name);
if (values == null)
{
values = new ArrayList<String>();
rval.put(name,values);
}
values.add(value);
}
return rval;
}
wait();
}
}
}
public String getFirstHeader(String headerName)
throws InterruptedException, IOException, HttpException
{
// Must wait for the response object to appear
while (true)
{
synchronized (this)
{
checkException(responseException);
if (response != null)
{
Header h = response.getFirstHeader(headerName);
if (h == null)
return null;
return h.getValue();
}
wait();
}
}
}
public InputStream getSafeInputStream()
throws InterruptedException, IOException, HttpException
{
// Must wait until stream is created, or until we note an exception was thrown.
while (true)
{
synchronized (this)
{
if (responseException != null)
throw new IllegalStateException("Check for response before getting stream");
checkException(streamException);
if (streamCreated)
return threadStream;
wait();
}
}
}
public String getCharSet()
throws InterruptedException, IOException, HttpException
{
while (true)
{
synchronized (this)
{
if (responseException != null)
throw new IllegalStateException("Check for response before getting charset");
checkException(streamException);
if (streamCreated)
return charSet;
wait();
}
}
}
public void abort()
{
// This will be called during the finally
// block in the case where all is well (and
// the stream completed) and in the case where
// there were exceptions.
synchronized (this)
{
if (streamCreated)
{
if (threadStream != null)
threadStream.abort();
}
abortThread = true;
}
}
public void finishUp()
throws InterruptedException
{
join();
}
protected synchronized void checkException(Throwable exception)
throws IOException, HttpException
{
if (exception != null)
{
// Throw the current exception, but clear it, so no further throwing is possible on the same problem.
Throwable e = exception;
if (e instanceof IOException)
throw (IOException)e;
else if (e instanceof HttpException)
throw (HttpException)e;
else if (e instanceof RuntimeException)
throw (RuntimeException)e;
else if (e instanceof Error)
throw (Error)e;
else
throw new RuntimeException("Unhandled exception of type: "+e.getClass().getName(),e);
}
}
}
}
| connectors/sharepoint/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/sharepoint/CommonsHTTPSender.java | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* $Id: CommonsHTTPSender.java 988245 2010-08-23 18:39:35Z kwright $
*/
package org.apache.manifoldcf.crawler.connectors.sharepoint;
import org.apache.axis.AxisFault;
import org.apache.axis.Constants;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.components.net.CommonsHTTPClientProperties;
import org.apache.axis.components.net.CommonsHTTPClientPropertiesFactory;
import org.apache.axis.components.net.TransportClientProperties;
import org.apache.axis.components.net.TransportClientPropertiesFactory;
import org.apache.axis.transport.http.HTTPConstants;
import org.apache.axis.handlers.BasicHandler;
import org.apache.axis.soap.SOAP12Constants;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.utils.JavaUtils;
import org.apache.axis.utils.Messages;
import org.apache.axis.utils.NetworkUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.Header;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.ProtocolVersion;
import org.apache.http.util.EntityUtils;
import org.apache.http.message.BasicHeader;
import org.apache.commons.logging.Log;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPException;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.InputStreamReader;
import java.io.Writer;
import java.io.StringWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
/* Class to use httpcomponents to communicate with a SOAP server.
* I've replaced the original rather complicated class with a much simpler one that
* relies on having an HttpClient object passed into the invoke() method. Since
* the object is already set up, not much needs to be done in here.
*/
public class CommonsHTTPSender extends BasicHandler {
/** Field log */
protected static Log log =
LogFactory.getLog(CommonsHTTPSender.class.getName());
/** Properties */
protected CommonsHTTPClientProperties clientProperties;
public CommonsHTTPSender() {
this.clientProperties = CommonsHTTPClientPropertiesFactory.create();
}
protected static class ExecuteMethodThread extends Thread
{
protected final HttpClient httpClient;
protected final String targetURL;
protected final MessageContext msgContext;
protected Throwable exception = null;
protected int returnCode = 0;
public ExecuteMethodThread( HttpClient httpClient, String targetURL, MessageContext msgContext )
{
super();
setDaemon(true);
this.httpClient = httpClient;
this.targetURL = targetURL;
this.msgContext = msgContext;
}
public void run()
{
try
{
boolean posting = true;
// If we're SOAP 1.2, allow the web method to be set from the
// MessageContext.
if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
if (webMethod != null) {
posting = webMethod.equals(HTTPConstants.HEADER_POST);
}
}
boolean http10 = false;
String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
if (httpVersion != null) {
if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
http10 = true;
}
// assume 1.1
}
HttpRequestBase method;
if (posting) {
HttpPost postMethod = new HttpPost(targetURL);
// set false as default, addContetInfo can overwrite
HttpProtocolParams.setUseExpectContinue(postMethod.getParams(),false);
Message reqMessage = msgContext.getRequestMessage();
boolean httpChunkStream = addContextInfo(postMethod, msgContext);
HttpEntity requestEntity = null;
requestEntity = new MessageRequestEntity(reqMessage, httpChunkStream,
http10 || !httpChunkStream);
postMethod.setEntity(requestEntity);
method = postMethod;
} else {
method = new HttpGet(targetURL);
}
if (http10)
HttpProtocolParams.setVersion(method.getParams(),new ProtocolVersion("HTTP",1,0));
// Try block to insure that the connection gets cleaned up
try
{
// Begin the fetch
HttpResponse response = httpClient.execute(method);
returnCode = response.getStatusLine().getStatusCode();
String contentType =
getHeader(response, HTTPConstants.HEADER_CONTENT_TYPE);
String contentLocation =
getHeader(response, HTTPConstants.HEADER_CONTENT_LOCATION);
String contentLength =
getHeader(response, HTTPConstants.HEADER_CONTENT_LENGTH);
if ((returnCode > 199) && (returnCode < 300)) {
// SOAP return is OK - so fall through
} else if (msgContext.getSOAPConstants() ==
SOAPConstants.SOAP12_CONSTANTS) {
// For now, if we're SOAP 1.2, fall through, since the range of
// valid result codes is much greater
} else if ((contentType != null) && !contentType.equals("text/html")
&& ((returnCode > 499) && (returnCode < 600))) {
// SOAP Fault should be in here - so fall through
} else {
String statusMessage = response.getStatusLine().toString();
AxisFault fault = new AxisFault("HTTP",
"(" + returnCode + ")"
+ statusMessage, null,
null);
fault.setFaultDetailString(
Messages.getMessage("return01",
"" + returnCode,
getResponseBodyAsString(response)));
fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
Integer.toString(returnCode));
throw fault;
}
// Transfer to a temporary file. If we stream it, we may wind up waiting on the socket outside this thread.
InputStream releaseConnectionOnCloseStream = new FileBackedInputStream(response.getEntity().getContent());
Header contentEncoding =
response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
if (contentEncoding != null) {
AxisFault fault = new AxisFault("HTTP",
"unsupported content-encoding of '"
+ contentEncoding.getValue()
+ "' found", null, null);
throw fault;
}
Message outMsg = new Message(releaseConnectionOnCloseStream,
false, contentType, contentLocation);
// Transfer HTTP headers of HTTP message to MIME headers of SOAP message
Header[] responseHeaders = response.getAllHeaders();
MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
for (int i = 0; i < responseHeaders.length; i++) {
Header responseHeader = responseHeaders[i];
responseMimeHeaders.addHeader(responseHeader.getName(),
responseHeader.getValue());
}
outMsg.setMessageType(Message.RESPONSE);
// Put the message in the message context.
msgContext.setResponseMessage(outMsg);
}
finally
{
// Consumes and closes the stream, releasing the connection
method.abort();
}
}
catch (Throwable e)
{
this.exception = e;
}
}
public Throwable getException()
{
return exception;
}
public int getResponse()
{
return returnCode;
}
}
/**
* invoke creates a socket connection, sends the request SOAP message and then
* reads the response SOAP message back from the SOAP server
*
* @param msgContext the messsage context
*
* @throws AxisFault
*/
public void invoke(MessageContext msgContext) throws AxisFault {
if (log.isDebugEnabled())
{
log.debug(Messages.getMessage("enter00",
"CommonsHTTPSender::invoke"));
}
// Catch all exceptions and turn them into AxisFaults
try
{
// Get the URL
URL targetURL =
new URL(msgContext.getStrProp(MessageContext.TRANS_URL));
// Get the HttpClient
HttpClient httpClient = (HttpClient)msgContext.getProperty(SPSProxyHelper.HTTPCLIENT_PROPERTY);
ExecuteMethodThread t = new ExecuteMethodThread(httpClient,targetURL.toString(),msgContext);
try
{
t.start();
t.join();
Throwable thr = t.getException();
if (thr != null)
{
if (thr instanceof RuntimeException)
throw (RuntimeException)thr;
else if (thr instanceof Exception)
throw (Exception)thr;
else
throw (Error)thr;
}
}
catch (InterruptedException e)
{
t.interrupt();
throw e;
}
/*
if (log.isDebugEnabled()) {
if (null == contentLength) {
log.debug("\n"
+ Messages.getMessage("no00", "Content-Length"));
}
log.debug("\n" + Messages.getMessage("xmlRecd00"));
log.debug("-----------------------------------------------");
log.debug(msgContext.getResponseMessage().getSOAPPartAsString());
}
}
*/
} catch (AxisFault af) {
log.debug(af);
throw af;
} catch (Exception e) {
log.debug(e);
throw AxisFault.makeFault(e);
}
if (log.isDebugEnabled()) {
log.debug(Messages.getMessage("exit00",
"CommonsHTTPSender::invoke"));
}
}
/**
* Extracts info from message context.
*
* @param method Post or get method
* @param msgContext the message context
*/
private static boolean addContextInfo(HttpPost method,
MessageContext msgContext)
throws AxisFault {
boolean httpChunkStream = false;
// Get SOAPAction, default to ""
String action = msgContext.useSOAPAction()
? msgContext.getSOAPActionURI()
: "";
if (action == null) {
action = "";
}
Message msg = msgContext.getRequestMessage();
if (msg != null){
// First, transfer MIME headers of SOAPMessage to HTTP headers.
// Some of these might be overridden later.
MimeHeaders mimeHeaders = msg.getMimeHeaders();
if (mimeHeaders != null) {
for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext(); ) {
MimeHeader mimeHeader = (MimeHeader) i.next();
method.addHeader(mimeHeader.getName(),
mimeHeader.getValue());
}
}
method.setHeader(new BasicHeader(HTTPConstants.HEADER_CONTENT_TYPE,
msg.getContentType(msgContext.getSOAPConstants())));
}
method.setHeader(new BasicHeader(HTTPConstants.HEADER_SOAP_ACTION,
"\"" + action + "\""));
method.setHeader(new BasicHeader(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")));
// process user defined headers for information.
Hashtable userHeaderTable =
(Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);
if (userHeaderTable != null) {
for (Iterator e = userHeaderTable.entrySet().iterator();
e.hasNext();) {
Map.Entry me = (Map.Entry) e.next();
Object keyObj = me.getKey();
if (null == keyObj) {
continue;
}
String key = keyObj.toString().trim();
String value = me.getValue().toString().trim();
if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT) &&
value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) {
HttpProtocolParams.setUseExpectContinue(method.getParams(),true);
} else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) {
String val = me.getValue().toString();
if (null != val) {
httpChunkStream = JavaUtils.isTrue(val);
}
} else {
method.addHeader(key, value);
}
}
}
return httpChunkStream;
}
private static String getHeader(HttpResponse response, String headerName) {
Header header = response.getFirstHeader(headerName);
return (header == null) ? null : header.getValue().trim();
}
private static String getResponseBodyAsString(HttpResponse httpResponse)
throws IOException {
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream is = entity.getContent();
try
{
String charSet = EntityUtils.getContentCharSet(entity);
if (charSet == null)
charSet = "utf-8";
char[] buffer = new char[65536];
Reader r = new InputStreamReader(is,charSet);
Writer w = new StringWriter();
try
{
while (true)
{
int amt = r.read(buffer);
if (amt == -1)
break;
w.write(buffer,0,amt);
}
}
finally
{
w.flush();
}
return w.toString();
}
finally
{
is.close();
}
}
return "";
}
private static class FileBackedInputStream extends InputStream {
private InputStream fileInputStream = null;
private File file = null;
public FileBackedInputStream(InputStream is)
throws IOException
{
File readyToOpenFile = null;
// Create a file and read into it
File tempFile = File.createTempFile("__shp__",".tmp");
try
{
// Open the output stream
OutputStream os = new FileOutputStream(tempFile);
try
{
byte[] buffer = new byte[65536];
while (true)
{
int amt = is.read(buffer);
if (amt == -1)
break;
os.write(buffer,0,amt);
}
}
finally
{
os.close();
}
readyToOpenFile = tempFile;
tempFile = null;
}
finally
{
if (tempFile != null)
tempFile.delete();
}
try
{
fileInputStream = new FileInputStream(readyToOpenFile);
file = readyToOpenFile;
readyToOpenFile = null;
}
finally
{
if (readyToOpenFile != null)
readyToOpenFile.delete();
}
}
@Override
public int available()
throws IOException
{
if (fileInputStream != null)
return fileInputStream.available();
return super.available();
}
@Override
public void close()
throws IOException
{
IOException exception = null;
try
{
if (fileInputStream != null)
fileInputStream.close();
}
catch (IOException e)
{
exception = e;
}
fileInputStream = null;
if (file != null)
file.delete();
file = null;
if (exception != null)
throw exception;
}
@Override
public void mark(int readlimit)
{
if (fileInputStream != null)
fileInputStream.mark(readlimit);
else
super.mark(readlimit);
}
@Override
public void reset()
throws IOException
{
if (fileInputStream != null)
fileInputStream.reset();
else
super.reset();
}
@Override
public boolean markSupported()
{
if (fileInputStream != null)
return fileInputStream.markSupported();
return super.markSupported();
}
@Override
public long skip(long n)
throws IOException
{
if (fileInputStream != null)
return fileInputStream.skip(n);
return super.skip(n);
}
@Override
public int read(byte[] b, int off, int len)
throws IOException
{
if (fileInputStream != null)
return fileInputStream.read(b,off,len);
return super.read(b,off,len);
}
@Override
public int read(byte[] b)
throws IOException
{
if (fileInputStream != null)
return fileInputStream.read(b);
return super.read(b);
}
@Override
public int read()
throws IOException
{
if (fileInputStream != null)
return fileInputStream.read();
return -1;
}
}
private static class MessageRequestEntity implements HttpEntity {
private final Message message;
private final boolean httpChunkStream; //Use HTTP chunking or not.
private final boolean contentLengthNeeded;
public MessageRequestEntity(Message message, boolean httpChunkStream, boolean contentLengthNeeded) {
this.message = message;
this.httpChunkStream = httpChunkStream;
this.contentLengthNeeded = contentLengthNeeded;
}
@Override
public boolean isChunked() {
return httpChunkStream;
}
@Override
public void consumeContent()
throws IOException {
EntityUtils.consume(this);
}
@Override
public boolean isRepeatable() {
return true;
}
@Override
public boolean isStreaming() {
return false;
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
// MHL
return null;
}
@Override
public void writeTo(OutputStream out)
throws IOException {
try {
this.message.writeTo(out);
} catch (SOAPException e) {
throw new IOException(e.getMessage());
}
}
@Override
public long getContentLength() {
if (contentLengthNeeded) {
try {
return message.getContentLength();
} catch (Exception e) {
}
}
// Unknown (chunked) length
return -1L;
}
@Override
public Header getContentType() {
return null; // a separate header is added
}
@Override
public Header getContentEncoding() {
return null;
}
}
}
| Convert file-backed http access to streaming http access.
git-svn-id: c7e708070c8e72aa5fc6533a297892ddf6349eb8@1413111 13f79535-47bb-0310-9956-ffa450edef68
| connectors/sharepoint/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/sharepoint/CommonsHTTPSender.java | Convert file-backed http access to streaming http access. | <ide><path>onnectors/sharepoint/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/sharepoint/CommonsHTTPSender.java
<ide> */
<ide> package org.apache.manifoldcf.crawler.connectors.sharepoint;
<ide>
<add>import org.apache.manifoldcf.core.common.XThreadInputStream;
<add>
<ide> import org.apache.axis.AxisFault;
<ide> import org.apache.axis.Constants;
<ide> import org.apache.axis.Message;
<ide> import org.apache.http.ProtocolVersion;
<ide> import org.apache.http.util.EntityUtils;
<ide> import org.apache.http.message.BasicHeader;
<add>
<add>import org.apache.http.conn.ConnectTimeoutException;
<add>import org.apache.http.client.RedirectException;
<add>import org.apache.http.client.CircularRedirectException;
<add>import org.apache.http.NoHttpResponseException;
<add>import org.apache.http.HttpException;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.Hashtable;
<ide> import java.util.Iterator;
<add>import java.util.HashMap;
<ide> import java.util.Map;
<add>import java.util.List;
<ide>
<ide> /* Class to use httpcomponents to communicate with a SOAP server.
<ide> * I've replaced the original rather complicated class with a much simpler one that
<ide>
<ide> public CommonsHTTPSender() {
<ide> this.clientProperties = CommonsHTTPClientPropertiesFactory.create();
<del> }
<del>
<del> protected static class ExecuteMethodThread extends Thread
<del> {
<del> protected final HttpClient httpClient;
<del> protected final String targetURL;
<del> protected final MessageContext msgContext;
<del>
<del> protected Throwable exception = null;
<del> protected int returnCode = 0;
<del>
<del> public ExecuteMethodThread( HttpClient httpClient, String targetURL, MessageContext msgContext )
<del> {
<del> super();
<del> setDaemon(true);
<del> this.httpClient = httpClient;
<del> this.targetURL = targetURL;
<del> this.msgContext = msgContext;
<del> }
<del>
<del> public void run()
<del> {
<del> try
<del> {
<del> boolean posting = true;
<del> // If we're SOAP 1.2, allow the web method to be set from the
<del> // MessageContext.
<del> if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
<del> String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
<del> if (webMethod != null) {
<del> posting = webMethod.equals(HTTPConstants.HEADER_POST);
<del> }
<del> }
<del>
<del> boolean http10 = false;
<del> String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
<del> if (httpVersion != null) {
<del> if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
<del> http10 = true;
<del> }
<del> // assume 1.1
<del> }
<del>
<del> HttpRequestBase method;
<del> if (posting) {
<del> HttpPost postMethod = new HttpPost(targetURL);
<del>
<del> // set false as default, addContetInfo can overwrite
<del> HttpProtocolParams.setUseExpectContinue(postMethod.getParams(),false);
<del>
<del> Message reqMessage = msgContext.getRequestMessage();
<del>
<del> boolean httpChunkStream = addContextInfo(postMethod, msgContext);
<del>
<del> HttpEntity requestEntity = null;
<del> requestEntity = new MessageRequestEntity(reqMessage, httpChunkStream,
<del> http10 || !httpChunkStream);
<del> postMethod.setEntity(requestEntity);
<del> method = postMethod;
<del> } else {
<del> method = new HttpGet(targetURL);
<del> }
<del>
<del> if (http10)
<del> HttpProtocolParams.setVersion(method.getParams(),new ProtocolVersion("HTTP",1,0));
<del>
<del> // Try block to insure that the connection gets cleaned up
<del> try
<del> {
<del> // Begin the fetch
<del> HttpResponse response = httpClient.execute(method);
<del>
<del> returnCode = response.getStatusLine().getStatusCode();
<del>
<del> String contentType =
<del> getHeader(response, HTTPConstants.HEADER_CONTENT_TYPE);
<del> String contentLocation =
<del> getHeader(response, HTTPConstants.HEADER_CONTENT_LOCATION);
<del> String contentLength =
<del> getHeader(response, HTTPConstants.HEADER_CONTENT_LENGTH);
<del>
<del> if ((returnCode > 199) && (returnCode < 300)) {
<del>
<del> // SOAP return is OK - so fall through
<del> } else if (msgContext.getSOAPConstants() ==
<del> SOAPConstants.SOAP12_CONSTANTS) {
<del> // For now, if we're SOAP 1.2, fall through, since the range of
<del> // valid result codes is much greater
<del> } else if ((contentType != null) && !contentType.equals("text/html")
<del> && ((returnCode > 499) && (returnCode < 600))) {
<del>
<del> // SOAP Fault should be in here - so fall through
<del> } else {
<del> String statusMessage = response.getStatusLine().toString();
<del> AxisFault fault = new AxisFault("HTTP",
<del> "(" + returnCode + ")"
<del> + statusMessage, null,
<del> null);
<del>
<del> fault.setFaultDetailString(
<del> Messages.getMessage("return01",
<del> "" + returnCode,
<del> getResponseBodyAsString(response)));
<del> fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
<del> Integer.toString(returnCode));
<del> throw fault;
<del> }
<del>
<del> // Transfer to a temporary file. If we stream it, we may wind up waiting on the socket outside this thread.
<del> InputStream releaseConnectionOnCloseStream = new FileBackedInputStream(response.getEntity().getContent());
<del>
<del> Header contentEncoding =
<del> response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
<del> if (contentEncoding != null) {
<del> AxisFault fault = new AxisFault("HTTP",
<del> "unsupported content-encoding of '"
<del> + contentEncoding.getValue()
<del> + "' found", null, null);
<del> throw fault;
<del> }
<del>
<del> Message outMsg = new Message(releaseConnectionOnCloseStream,
<del> false, contentType, contentLocation);
<del>
<del> // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
<del> Header[] responseHeaders = response.getAllHeaders();
<del> MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
<del> for (int i = 0; i < responseHeaders.length; i++) {
<del> Header responseHeader = responseHeaders[i];
<del> responseMimeHeaders.addHeader(responseHeader.getName(),
<del> responseHeader.getValue());
<del> }
<del> outMsg.setMessageType(Message.RESPONSE);
<del>
<del> // Put the message in the message context.
<del> msgContext.setResponseMessage(outMsg);
<del> }
<del> finally
<del> {
<del> // Consumes and closes the stream, releasing the connection
<del> method.abort();
<del> }
<del>
<del> }
<del> catch (Throwable e)
<del> {
<del> this.exception = e;
<del> }
<del> }
<del>
<del> public Throwable getException()
<del> {
<del> return exception;
<del> }
<del>
<del> public int getResponse()
<del> {
<del> return returnCode;
<del> }
<ide> }
<ide>
<ide> /**
<ide> // Get the HttpClient
<ide> HttpClient httpClient = (HttpClient)msgContext.getProperty(SPSProxyHelper.HTTPCLIENT_PROPERTY);
<ide>
<add> boolean posting = true;
<add> // If we're SOAP 1.2, allow the web method to be set from the
<add> // MessageContext.
<add> if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
<add> String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
<add> if (webMethod != null) {
<add> posting = webMethod.equals(HTTPConstants.HEADER_POST);
<add> }
<add> }
<add>
<add> boolean http10 = false;
<add> String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
<add> if (httpVersion != null) {
<add> if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
<add> http10 = true;
<add> }
<add> // assume 1.1
<add> }
<add>
<add> HttpRequestBase method;
<add>
<add> if (posting) {
<add> HttpPost postMethod = new HttpPost(targetURL.toString());
<add>
<add> // set false as default, addContetInfo can overwrite
<add> HttpProtocolParams.setUseExpectContinue(postMethod.getParams(),false);
<add>
<add> Message reqMessage = msgContext.getRequestMessage();
<add>
<add> boolean httpChunkStream = addContextInfo(postMethod, msgContext);
<add>
<add> HttpEntity requestEntity = null;
<add> requestEntity = new MessageRequestEntity(reqMessage, httpChunkStream,
<add> http10 || !httpChunkStream);
<add> postMethod.setEntity(requestEntity);
<add> method = postMethod;
<add> } else {
<add> method = new HttpGet(targetURL.toString());
<add> }
<add>
<add> if (http10)
<add> HttpProtocolParams.setVersion(method.getParams(),new ProtocolVersion("HTTP",1,0));
<add>
<add> BackgroundHTTPThread methodThread = new BackgroundHTTPThread(httpClient,method);
<add> methodThread.start();
<add> try
<add> {
<add> int returnCode = methodThread.getResponseCode();
<add>
<add> String contentType =
<add> getHeader(methodThread, HTTPConstants.HEADER_CONTENT_TYPE);
<add> String contentLocation =
<add> getHeader(methodThread, HTTPConstants.HEADER_CONTENT_LOCATION);
<add> String contentLength =
<add> getHeader(methodThread, HTTPConstants.HEADER_CONTENT_LENGTH);
<add>
<add> if ((returnCode > 199) && (returnCode < 300)) {
<add>
<add> // SOAP return is OK - so fall through
<add> } else if (msgContext.getSOAPConstants() ==
<add> SOAPConstants.SOAP12_CONSTANTS) {
<add> // For now, if we're SOAP 1.2, fall through, since the range of
<add> // valid result codes is much greater
<add> } else if ((contentType != null) && !contentType.equals("text/html")
<add> && ((returnCode > 499) && (returnCode < 600))) {
<add>
<add> // SOAP Fault should be in here - so fall through
<add> } else {
<add> String statusMessage = methodThread.getResponseStatus();
<add> AxisFault fault = new AxisFault("HTTP",
<add> "(" + returnCode + ")"
<add> + statusMessage, null,
<add> null);
<add>
<add> fault.setFaultDetailString(
<add> Messages.getMessage("return01",
<add> "" + returnCode,
<add> getResponseBodyAsString(methodThread)));
<add> fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE,
<add> Integer.toString(returnCode));
<add> throw fault;
<add> }
<add>
<add> String contentEncoding =
<add> methodThread.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
<add> if (contentEncoding != null) {
<add> AxisFault fault = new AxisFault("HTTP",
<add> "unsupported content-encoding of '"
<add> + contentEncoding
<add> + "' found", null, null);
<add> throw fault;
<add> }
<add>
<add> Map<String,List<String>> responseHeaders = methodThread.getResponseHeaders();
<add>
<add> InputStream dataStream = methodThread.getSafeInputStream();
<add>
<add> Message outMsg = new Message(new BackgroundInputStream(methodThread,dataStream),
<add> false, contentType, contentLocation);
<add>
<add> // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
<add> MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
<add> for (String name : responseHeaders.keySet())
<add> {
<add> List<String> values = responseHeaders.get(name);
<add> for (String value : values) {
<add> responseMimeHeaders.addHeader(name,value);
<add> }
<add> }
<add> outMsg.setMessageType(Message.RESPONSE);
<add>
<add> // Put the message in the message context.
<add> msgContext.setResponseMessage(outMsg);
<add>
<add> // Pass off the method thread to the stream for closure
<add> methodThread = null;
<add> }
<add> finally
<add> {
<add> if (methodThread != null)
<add> {
<add> methodThread.abort();
<add> methodThread.finishUp();
<add> }
<add> }
<add>
<add>/*
<ide> ExecuteMethodThread t = new ExecuteMethodThread(httpClient,targetURL.toString(),msgContext);
<ide> try
<ide> {
<ide> t.interrupt();
<ide> throw e;
<ide> }
<del>
<add>*/
<ide> /*
<ide> if (log.isDebugEnabled()) {
<ide> if (null == contentLength) {
<ide> return httpChunkStream;
<ide> }
<ide>
<del> private static String getHeader(HttpResponse response, String headerName) {
<del> Header header = response.getFirstHeader(headerName);
<del> return (header == null) ? null : header.getValue().trim();
<add> private static String getHeader(BackgroundHTTPThread methodThread, String headerName)
<add> throws IOException, InterruptedException, HttpException {
<add> String header = methodThread.getFirstHeader(headerName);
<add> return (header == null) ? null : header.trim();
<ide> }
<ide>
<del> private static String getResponseBodyAsString(HttpResponse httpResponse)
<del> throws IOException {
<del> HttpEntity entity = httpResponse.getEntity();
<del> if (entity != null)
<del> {
<del> InputStream is = entity.getContent();
<add> private static String getResponseBodyAsString(BackgroundHTTPThread methodThread)
<add> throws IOException, InterruptedException, HttpException {
<add> InputStream is = methodThread.getSafeInputStream();
<add> if (is != null)
<add> {
<ide> try
<ide> {
<del> String charSet = EntityUtils.getContentCharSet(entity);
<add> String charSet = methodThread.getCharSet();
<ide> if (charSet == null)
<ide> charSet = "utf-8";
<ide> char[] buffer = new char[65536];
<ide> return "";
<ide> }
<ide>
<del> private static class FileBackedInputStream extends InputStream {
<del>
<del> private InputStream fileInputStream = null;
<del> private File file = null;
<del>
<del> public FileBackedInputStream(InputStream is)
<del> throws IOException
<del> {
<del> File readyToOpenFile = null;
<del> // Create a file and read into it
<del> File tempFile = File.createTempFile("__shp__",".tmp");
<del> try
<del> {
<del> // Open the output stream
<del> OutputStream os = new FileOutputStream(tempFile);
<del> try
<del> {
<del> byte[] buffer = new byte[65536];
<del> while (true)
<del> {
<del> int amt = is.read(buffer);
<del> if (amt == -1)
<del> break;
<del> os.write(buffer,0,amt);
<del> }
<del> }
<del> finally
<del> {
<del> os.close();
<del> }
<del> readyToOpenFile = tempFile;
<del> tempFile = null;
<del> }
<del> finally
<del> {
<del> if (tempFile != null)
<del> tempFile.delete();
<del> }
<del>
<del> try
<del> {
<del> fileInputStream = new FileInputStream(readyToOpenFile);
<del> file = readyToOpenFile;
<del> readyToOpenFile = null;
<del> }
<del> finally
<del> {
<del> if (readyToOpenFile != null)
<del> readyToOpenFile.delete();
<del> }
<del> }
<del>
<del> @Override
<del> public int available()
<del> throws IOException
<del> {
<del> if (fileInputStream != null)
<del> return fileInputStream.available();
<del> return super.available();
<del> }
<del>
<del> @Override
<del> public void close()
<del> throws IOException
<del> {
<del> IOException exception = null;
<del> try
<del> {
<del> if (fileInputStream != null)
<del> fileInputStream.close();
<del> }
<del> catch (IOException e)
<del> {
<del> exception = e;
<del> }
<del> fileInputStream = null;
<del> if (file != null)
<del> file.delete();
<del> file = null;
<del> if (exception != null)
<del> throw exception;
<del> }
<del>
<del> @Override
<del> public void mark(int readlimit)
<del> {
<del> if (fileInputStream != null)
<del> fileInputStream.mark(readlimit);
<del> else
<del> super.mark(readlimit);
<del> }
<del>
<del> @Override
<del> public void reset()
<del> throws IOException
<del> {
<del> if (fileInputStream != null)
<del> fileInputStream.reset();
<del> else
<del> super.reset();
<del> }
<del>
<del> @Override
<del> public boolean markSupported()
<del> {
<del> if (fileInputStream != null)
<del> return fileInputStream.markSupported();
<del> return super.markSupported();
<del> }
<del>
<del> @Override
<del> public long skip(long n)
<del> throws IOException
<del> {
<del> if (fileInputStream != null)
<del> return fileInputStream.skip(n);
<del> return super.skip(n);
<del> }
<del>
<del> @Override
<del> public int read(byte[] b, int off, int len)
<del> throws IOException
<del> {
<del> if (fileInputStream != null)
<del> return fileInputStream.read(b,off,len);
<del> return super.read(b,off,len);
<del> }
<del>
<del> @Override
<del> public int read(byte[] b)
<del> throws IOException
<del> {
<del> if (fileInputStream != null)
<del> return fileInputStream.read(b);
<del> return super.read(b);
<del> }
<del>
<del> @Override
<del> public int read()
<del> throws IOException
<del> {
<del> if (fileInputStream != null)
<del> return fileInputStream.read();
<del> return -1;
<del> }
<del>
<del> }
<del>
<ide> private static class MessageRequestEntity implements HttpEntity {
<ide>
<ide> private final Message message;
<ide> }
<ide> }
<ide>
<add> /** This input stream wraps a background http transaction thread, so that
<add> * the thread is ended when the stream is closed.
<add> */
<add> private static class BackgroundInputStream extends InputStream {
<add>
<add> private BackgroundHTTPThread methodThread = null;
<add> private InputStream xThreadInputStream = null;
<add>
<add> /** Construct an http transaction stream. The stream is driven by a background
<add> * thread, whose existence is tied to this class. The sequence of activity that
<add> * this class expects is as follows:
<add> * (1) Construct the httpclient and request object and initialize them
<add> * (2) Construct a background method thread, and start it
<add> * (3) If the response calls for it, call this constructor, and put the resulting stream
<add> * into the message response
<add> * (4) Otherwise, terminate the background method thread in the standard manner,
<add> * being sure NOT
<add> */
<add> public BackgroundInputStream(BackgroundHTTPThread methodThread, InputStream xThreadInputStream)
<add> {
<add> this.methodThread = methodThread;
<add> this.xThreadInputStream = xThreadInputStream;
<add> }
<add>
<add> @Override
<add> public int available()
<add> throws IOException
<add> {
<add> if (xThreadInputStream != null)
<add> return xThreadInputStream.available();
<add> return super.available();
<add> }
<add>
<add> @Override
<add> public void close()
<add> throws IOException
<add> {
<add> try
<add> {
<add> if (xThreadInputStream != null)
<add> {
<add> xThreadInputStream.close();
<add> xThreadInputStream = null;
<add> }
<add> }
<add> finally
<add> {
<add> if (methodThread != null)
<add> {
<add> methodThread.abort();
<add> try
<add> {
<add> methodThread.finishUp();
<add> }
<add> catch (InterruptedException e)
<add> {
<add> throw new InterruptedIOException(e.getMessage());
<add> }
<add> methodThread = null;
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void mark(int readlimit)
<add> {
<add> if (xThreadInputStream != null)
<add> xThreadInputStream.mark(readlimit);
<add> else
<add> super.mark(readlimit);
<add> }
<add>
<add> @Override
<add> public void reset()
<add> throws IOException
<add> {
<add> if (xThreadInputStream != null)
<add> xThreadInputStream.reset();
<add> else
<add> super.reset();
<add> }
<add>
<add> @Override
<add> public boolean markSupported()
<add> {
<add> if (xThreadInputStream != null)
<add> return xThreadInputStream.markSupported();
<add> return super.markSupported();
<add> }
<add>
<add> @Override
<add> public long skip(long n)
<add> throws IOException
<add> {
<add> if (xThreadInputStream != null)
<add> return xThreadInputStream.skip(n);
<add> return super.skip(n);
<add> }
<add>
<add> @Override
<add> public int read(byte[] b, int off, int len)
<add> throws IOException
<add> {
<add> if (xThreadInputStream != null)
<add> return xThreadInputStream.read(b,off,len);
<add> return super.read(b,off,len);
<add> }
<add>
<add> @Override
<add> public int read(byte[] b)
<add> throws IOException
<add> {
<add> if (xThreadInputStream != null)
<add> return xThreadInputStream.read(b);
<add> return super.read(b);
<add> }
<add>
<add> @Override
<add> public int read()
<add> throws IOException
<add> {
<add> if (xThreadInputStream != null)
<add> return xThreadInputStream.read();
<add> return -1;
<add> }
<add>
<add> }
<add>
<add> /** This thread does the actual socket communication with the server.
<add> * It's set up so that it can be abandoned at shutdown time.
<add> *
<add> * The way it works is as follows:
<add> * - it starts the transaction
<add> * - it receives the response, and saves that for the calling class to inspect
<add> * - it transfers the data part to an input stream provided to the calling class
<add> * - it shuts the connection down
<add> *
<add> * If there is an error, the sequence is aborted, and an exception is recorded
<add> * for the calling class to examine.
<add> *
<add> * The calling class basically accepts the sequence above. It starts the
<add> * thread, and tries to get a response code. If instead an exception is seen,
<add> * the exception is thrown up the stack.
<add> */
<add> protected static class BackgroundHTTPThread extends Thread
<add> {
<add> /** Client and method, all preconfigured */
<add> protected final HttpClient httpClient;
<add> protected final HttpRequestBase executeMethod;
<add>
<add> protected HttpResponse response = null;
<add> protected Throwable responseException = null;
<add> protected XThreadInputStream threadStream = null;
<add> protected String charSet = null;
<add> protected boolean streamCreated = false;
<add> protected Throwable streamException = null;
<add> protected boolean abortThread = false;
<add>
<add> protected Throwable shutdownException = null;
<add>
<add> protected Throwable generalException = null;
<add>
<add> public BackgroundHTTPThread(HttpClient httpClient, HttpRequestBase executeMethod)
<add> {
<add> super();
<add> setDaemon(true);
<add> this.httpClient = httpClient;
<add> this.executeMethod = executeMethod;
<add> }
<add>
<add> public void run()
<add> {
<add> try
<add> {
<add> try
<add> {
<add> // Call the execute method appropriately
<add> synchronized (this)
<add> {
<add> if (!abortThread)
<add> {
<add> try
<add> {
<add> response = httpClient.execute(executeMethod);
<add> }
<add> catch (java.net.SocketTimeoutException e)
<add> {
<add> responseException = e;
<add> }
<add> catch (ConnectTimeoutException e)
<add> {
<add> responseException = e;
<add> }
<add> catch (InterruptedIOException e)
<add> {
<add> throw e;
<add> }
<add> catch (Throwable e)
<add> {
<add> responseException = e;
<add> }
<add> this.notifyAll();
<add> }
<add> }
<add>
<add> // Start the transfer of the content
<add> if (responseException == null)
<add> {
<add> synchronized (this)
<add> {
<add> if (!abortThread)
<add> {
<add> try
<add> {
<add> HttpEntity entity = response.getEntity();
<add> InputStream bodyStream = entity.getContent();
<add> if (bodyStream != null)
<add> {
<add> threadStream = new XThreadInputStream(bodyStream);
<add> charSet = EntityUtils.getContentCharSet(entity);
<add> }
<add> streamCreated = true;
<add> }
<add> catch (java.net.SocketTimeoutException e)
<add> {
<add> streamException = e;
<add> }
<add> catch (ConnectTimeoutException e)
<add> {
<add> streamException = e;
<add> }
<add> catch (InterruptedIOException e)
<add> {
<add> throw e;
<add> }
<add> catch (Throwable e)
<add> {
<add> streamException = e;
<add> }
<add> this.notifyAll();
<add> }
<add> }
<add> }
<add>
<add> if (responseException == null && streamException == null)
<add> {
<add> if (threadStream != null)
<add> {
<add> // Stuff the content until we are done
<add> threadStream.stuffQueue();
<add> }
<add> }
<add>
<add> }
<add> finally
<add> {
<add> synchronized (this)
<add> {
<add> try
<add> {
<add> executeMethod.abort();
<add> }
<add> catch (Throwable e)
<add> {
<add> shutdownException = e;
<add> }
<add> this.notifyAll();
<add> }
<add> }
<add> }
<add> catch (Throwable e)
<add> {
<add> // We catch exceptions here that should ONLY be InterruptedExceptions, as a result of the thread being aborted.
<add> this.generalException = e;
<add> }
<add> }
<add>
<add> public int getResponseCode()
<add> throws InterruptedException, IOException, HttpException
<add> {
<add> // Must wait until the response object is there
<add> while (true)
<add> {
<add> synchronized (this)
<add> {
<add> checkException(responseException);
<add> if (response != null)
<add> return response.getStatusLine().getStatusCode();
<add> wait();
<add> }
<add> }
<add> }
<add>
<add> public String getResponseStatus()
<add> throws InterruptedException, IOException, HttpException
<add> {
<add> // Must wait until the response object is there
<add> while (true)
<add> {
<add> synchronized (this)
<add> {
<add> checkException(responseException);
<add> if (response != null)
<add> return response.getStatusLine().toString();
<add> wait();
<add> }
<add> }
<add> }
<add>
<add> public Map<String,List<String>> getResponseHeaders()
<add> throws InterruptedException, IOException, HttpException
<add> {
<add> // Must wait for the response object to appear
<add> while (true)
<add> {
<add> synchronized (this)
<add> {
<add> checkException(responseException);
<add> if (response != null)
<add> {
<add> Header[] headers = response.getAllHeaders();
<add> Map<String,List<String>> rval = new HashMap<String,List<String>>();
<add> int i = 0;
<add> while (i < headers.length)
<add> {
<add> Header h = headers[i++];
<add> String name = h.getName();
<add> String value = h.getValue();
<add> List<String> values = rval.get(name);
<add> if (values == null)
<add> {
<add> values = new ArrayList<String>();
<add> rval.put(name,values);
<add> }
<add> values.add(value);
<add> }
<add> return rval;
<add> }
<add> wait();
<add> }
<add> }
<add>
<add> }
<add>
<add> public String getFirstHeader(String headerName)
<add> throws InterruptedException, IOException, HttpException
<add> {
<add> // Must wait for the response object to appear
<add> while (true)
<add> {
<add> synchronized (this)
<add> {
<add> checkException(responseException);
<add> if (response != null)
<add> {
<add> Header h = response.getFirstHeader(headerName);
<add> if (h == null)
<add> return null;
<add> return h.getValue();
<add> }
<add> wait();
<add> }
<add> }
<add> }
<add>
<add> public InputStream getSafeInputStream()
<add> throws InterruptedException, IOException, HttpException
<add> {
<add> // Must wait until stream is created, or until we note an exception was thrown.
<add> while (true)
<add> {
<add> synchronized (this)
<add> {
<add> if (responseException != null)
<add> throw new IllegalStateException("Check for response before getting stream");
<add> checkException(streamException);
<add> if (streamCreated)
<add> return threadStream;
<add> wait();
<add> }
<add> }
<add> }
<add>
<add> public String getCharSet()
<add> throws InterruptedException, IOException, HttpException
<add> {
<add> while (true)
<add> {
<add> synchronized (this)
<add> {
<add> if (responseException != null)
<add> throw new IllegalStateException("Check for response before getting charset");
<add> checkException(streamException);
<add> if (streamCreated)
<add> return charSet;
<add> wait();
<add> }
<add> }
<add> }
<add>
<add> public void abort()
<add> {
<add> // This will be called during the finally
<add> // block in the case where all is well (and
<add> // the stream completed) and in the case where
<add> // there were exceptions.
<add> synchronized (this)
<add> {
<add> if (streamCreated)
<add> {
<add> if (threadStream != null)
<add> threadStream.abort();
<add> }
<add> abortThread = true;
<add> }
<add> }
<add>
<add> public void finishUp()
<add> throws InterruptedException
<add> {
<add> join();
<add> }
<add>
<add> protected synchronized void checkException(Throwable exception)
<add> throws IOException, HttpException
<add> {
<add> if (exception != null)
<add> {
<add> // Throw the current exception, but clear it, so no further throwing is possible on the same problem.
<add> Throwable e = exception;
<add> if (e instanceof IOException)
<add> throw (IOException)e;
<add> else if (e instanceof HttpException)
<add> throw (HttpException)e;
<add> else if (e instanceof RuntimeException)
<add> throw (RuntimeException)e;
<add> else if (e instanceof Error)
<add> throw (Error)e;
<add> else
<add> throw new RuntimeException("Unhandled exception of type: "+e.getClass().getName(),e);
<add> }
<add> }
<add>
<add> }
<add>
<ide> }
<ide> |
|
Java | mit | 53fe4b2649cab344f1d3cc68af9aa107d4ccf362 | 0 | oscargus/jabref,oscargus/jabref,tobiasdiez/jabref,JabRef/jabref,Siedlerchr/jabref,sauliusg/jabref,zellerdev/jabref,sauliusg/jabref,tobiasdiez/jabref,sauliusg/jabref,Siedlerchr/jabref,shitikanth/jabref,tobiasdiez/jabref,Siedlerchr/jabref,oscargus/jabref,JabRef/jabref,JabRef/jabref,oscargus/jabref,oscargus/jabref,zellerdev/jabref,zellerdev/jabref,shitikanth/jabref,JabRef/jabref,Siedlerchr/jabref,shitikanth/jabref,shitikanth/jabref,zellerdev/jabref,tobiasdiez/jabref,shitikanth/jabref,zellerdev/jabref,sauliusg/jabref | package org.jabref.gui.groups;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.swing.SwingUtilities;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.FieldChange;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.groups.AbstractGroup;
import org.jabref.model.groups.ExplicitGroup;
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.metadata.MetaData;
public class GroupTreeViewModel extends AbstractViewModel {
private final ObjectProperty<GroupNodeViewModel> rootGroup = new SimpleObjectProperty<>();
private final ListProperty<GroupNodeViewModel> selectedGroups = new SimpleListProperty<>(FXCollections.observableArrayList());
private final StateManager stateManager;
private final DialogService dialogService;
private final TaskExecutor taskExecutor;
private final ObjectProperty<Predicate<GroupNodeViewModel>> filterPredicate = new SimpleObjectProperty<>();
private final StringProperty filterText = new SimpleStringProperty();
private final Comparator<GroupTreeNode> compAlphabetIgnoreCase = (GroupTreeNode v1, GroupTreeNode v2) -> v1
.getName()
.compareToIgnoreCase(v2.getName());
private Optional<BibDatabaseContext> currentDatabase;
public GroupTreeViewModel(StateManager stateManager, DialogService dialogService, TaskExecutor taskExecutor) {
this.stateManager = Objects.requireNonNull(stateManager);
this.dialogService = Objects.requireNonNull(dialogService);
this.taskExecutor = Objects.requireNonNull(taskExecutor);
// Register listener
stateManager.activeDatabaseProperty()
.addListener((observable, oldValue, newValue) -> onActiveDatabaseChanged(newValue));
selectedGroups.addListener((observable, oldValue, newValue) -> onSelectedGroupChanged(newValue));
// Set-up bindings
filterPredicate
.bind(Bindings.createObjectBinding(() -> group -> group.isMatchedBy(filterText.get()), filterText));
// Init
onActiveDatabaseChanged(stateManager.activeDatabaseProperty().getValue());
}
public ObjectProperty<GroupNodeViewModel> rootGroupProperty() {
return rootGroup;
}
public ListProperty<GroupNodeViewModel> selectedGroupsProperty() {
return selectedGroups;
}
public ObjectProperty<Predicate<GroupNodeViewModel>> filterPredicateProperty() {
return filterPredicate;
}
public StringProperty filterTextProperty() {
return filterText;
}
/**
* Gets invoked if the user selects a different group.
* We need to notify the {@link StateManager} about this change so that the main table gets updated.
*/
private void onSelectedGroupChanged(ObservableList<GroupNodeViewModel> newValue) {
if (!currentDatabase.equals(stateManager.activeDatabaseProperty().getValue())) {
// Switch of database occurred -> do nothing
return;
}
currentDatabase.ifPresent(database -> {
if (newValue == null) {
stateManager.clearSelectedGroups(database);
} else {
stateManager.setSelectedGroups(database, newValue.stream().map(GroupNodeViewModel::getGroupNode).collect(Collectors.toList()));
}
});
}
/**
* Opens "New Group Dialog" and add the resulting group to the root
*/
public void addNewGroupToRoot() {
addNewSubgroup(rootGroup.get());
}
/**
* Gets invoked if the user changes the active database.
* We need to get the new group tree and update the view
*/
private void onActiveDatabaseChanged(Optional<BibDatabaseContext> newDatabase) {
if (newDatabase.isPresent()) {
GroupNodeViewModel newRoot = newDatabase
.map(BibDatabaseContext::getMetaData)
.flatMap(MetaData::getGroups)
.map(root -> new GroupNodeViewModel(newDatabase.get(), stateManager, taskExecutor, root))
.orElse(GroupNodeViewModel.getAllEntriesGroup(newDatabase.get(), stateManager, taskExecutor));
rootGroup.setValue(newRoot);
this.selectedGroups.setAll(
stateManager.getSelectedGroup(newDatabase.get()).stream()
.map(selectedGroup -> new GroupNodeViewModel(newDatabase.get(), stateManager, taskExecutor, selectedGroup))
.collect(Collectors.toList()));
}
currentDatabase = newDatabase;
}
/**
* Opens "New Group Dialog" and add the resulting group to the specified group
*/
public void addNewSubgroup(GroupNodeViewModel parent) {
SwingUtilities.invokeLater(() -> {
Optional<AbstractGroup> newGroup = dialogService.showCustomDialogAndWait(new GroupDialog());
newGroup.ifPresent(group -> {
GroupTreeNode newGroupNode = parent.addSubgroup(group);
// TODO: Add undo
//UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(parent, new GroupTreeNodeViewModel(newGroupNode), UndoableAddOrRemoveGroup.ADD_NODE);
//panel.getUndoManager().addEdit(undo);
// TODO: Expand parent to make new group visible
//parent.expand();
dialogService.notify(Localization.lang("Added group \"%0\".", group.getName()));
writeGroupChangesToMetaData();
});
});
}
private void writeGroupChangesToMetaData() {
currentDatabase.get().getMetaData().setGroups(rootGroup.get().getGroupNode());
}
/**
* Opens "Edit Group Dialog" and changes the given group to the edited one.
*/
public void editGroup(GroupNodeViewModel oldGroup) {
SwingUtilities.invokeLater(() -> {
Optional<AbstractGroup> newGroup = dialogService
.showCustomDialogAndWait(new GroupDialog(oldGroup.getGroupNode().getGroup()));
newGroup.ifPresent(group -> {
Platform.runLater(() -> {
// TODO: Keep assignments
boolean keepPreviousAssignments = dialogService.showConfirmationDialogAndWait(
Localization.lang("Change of Grouping Method"),
Localization.lang("Assign the original group's entries to this group?"));
// WarnAssignmentSideEffects.warnAssignmentSideEffects(newGroup, panel.frame());
boolean removePreviousAssignents = (oldGroup.getGroupNode().getGroup() instanceof ExplicitGroup)
&& (group instanceof ExplicitGroup);
List<FieldChange> addChange = oldGroup.getGroupNode().setGroup(
group,
keepPreviousAssignments,
removePreviousAssignents,
stateManager.getEntriesInCurrentDatabase());
// TODO: Add undo
// Store undo information.
// AbstractUndoableEdit undoAddPreviousEntries = null;
// UndoableModifyGroup undo = new UndoableModifyGroup(GroupSelector.this, groupsRoot, node, newGroup);
// if (undoAddPreviousEntries == null) {
// panel.getUndoManager().addEdit(undo);
//} else {
// NamedCompound nc = new NamedCompound("Modify Group");
// nc.addEdit(undo);
// nc.addEdit(undoAddPreviousEntries);
// nc.end();/
// panel.getUndoManager().addEdit(nc);
//}
//if (!addChange.isEmpty()) {
// undoAddPreviousEntries = UndoableChangeEntriesOfGroup.getUndoableEdit(null, addChange);
//}
dialogService.notify(Localization.lang("Modified group \"%0\".", group.getName()));
writeGroupChangesToMetaData();
});
});
});
}
public void removeSubgroups(GroupNodeViewModel group) {
boolean confirmation = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove subgroups"),
Localization.lang("Remove all subgroups of \"%0\"?", group.getDisplayName()));
if (confirmation) {
/// TODO: Add undo
//final UndoableModifySubtree undo = new UndoableModifySubtree(getGroupTreeRoot(), node, "Remove subgroups");
//panel.getUndoManager().addEdit(undo);
group.getGroupNode().removeAllChildren();
dialogService.notify(Localization.lang("Removed all subgroups of group \"%0\".", group.getDisplayName()));
writeGroupChangesToMetaData();
}
}
public void removeGroupKeepSubgroups(GroupNodeViewModel group) {
boolean confirmation = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove group"),
Localization.lang("Remove group \"%0\"?", group.getDisplayName()));
if (confirmation) {
// TODO: Add undo
//final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node, UndoableAddOrRemoveGroup.REMOVE_NODE_KEEP_CHILDREN);
//panel.getUndoManager().addEdit(undo);
GroupTreeNode groupNode = group.getGroupNode();
groupNode.getParent()
.ifPresent(parent -> groupNode.moveAllChildrenTo(parent, parent.getIndexOfChild(groupNode).get()));
groupNode.removeFromParent();
dialogService.notify(Localization.lang("Removed group \"%0\".", group.getDisplayName()));
writeGroupChangesToMetaData();
}
}
/**
* Removes the specified group and its subgroups (after asking for confirmation).
*/
public void removeGroupAndSubgroups(GroupNodeViewModel group) {
boolean confirmed = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove group and subgroups"),
Localization.lang("Remove group \"%0\" and its subgroups?", group.getDisplayName()),
Localization.lang("Remove"));
if (confirmed) {
// TODO: Add undo
//final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node, UndoableAddOrRemoveGroup.REMOVE_NODE_AND_CHILDREN);
//panel.getUndoManager().addEdit(undo);
removeGroupsAndSubGroupsFromEntries(group);
group.getGroupNode().removeFromParent();
dialogService.notify(Localization.lang("Removed group \"%0\" and its subgroups.", group.getDisplayName()));
writeGroupChangesToMetaData();
}
}
private void removeGroupsAndSubGroupsFromEntries(GroupNodeViewModel group) {
for (GroupNodeViewModel child: group.getChildren()) {
removeGroupsAndSubGroupsFromEntries(child);
}
// only remove explicit groups from the entries, keyword groups should not be deleted
if (group.getGroupNode().getGroup() instanceof ExplicitGroup) {
List<BibEntry> entriesInGroup = group.getGroupNode().getEntriesInGroup(this.currentDatabase.get().getEntries());
group.getGroupNode().removeEntriesFromGroup(entriesInGroup);
}
}
public void addSelectedEntries(GroupNodeViewModel group) {
// TODO: Warn
// if (!WarnAssignmentSideEffects.warnAssignmentSideEffects(node.getNode().getGroup(), panel.frame())) {
// return; // user aborted operation
List<FieldChange> addChange = group.getGroupNode().addEntriesToGroup(stateManager.getSelectedEntries());
// TODO: Add undo
// NamedCompound undoAll = new NamedCompound(Localization.lang("change assignment of entries"));
// if (!undoAdd.isEmpty()) { undo.addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(node, undoAdd)); }
// panel.getUndoManager().addEdit(undoAll);
// TODO Display massages
//if (undo == null) {
// frame.output(Localization.lang("The group \"%0\" already contains the selection.",
// node.getGroup().getName()));
// return;
//}
// panel.getUndoManager().addEdit(undo);
// final String groupName = node.getGroup().getName();
// if (assignedEntries == 1) {
// frame.output(Localization.lang("Assigned 1 entry to group \"%0\".", groupName));
// } else {
// frame.output(Localization.lang("Assigned %0 entries to group \"%1\".", String.valueOf(assignedEntries),
// groupName));
//}
}
public void removeSelectedEntries(GroupNodeViewModel group) {
// TODO: warn if assignment has undesired side effects (modifies a field != keywords)
// if (!WarnAssignmentSideEffects.warnAssignmentSideEffects(mNode.getNode().getGroup(), mPanel.frame())) {
// return; // user aborted operation
List<FieldChange> removeChange = group.getGroupNode().removeEntriesFromGroup(stateManager.getSelectedEntries());
// TODO: Add undo
// if (!undo.isEmpty()) {
// mPanel.getUndoManager().addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(mNode, undo));
}
public void sortAlphabeticallyRecursive(GroupNodeViewModel group) {
group.getGroupNode().sortChildren(compAlphabetIgnoreCase, true);
}
}
| src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java | package org.jabref.gui.groups;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.swing.SwingUtilities;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ListProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.jabref.gui.AbstractViewModel;
import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.util.TaskExecutor;
import org.jabref.logic.l10n.Localization;
import org.jabref.model.FieldChange;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.groups.AbstractGroup;
import org.jabref.model.groups.ExplicitGroup;
import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.metadata.MetaData;
public class GroupTreeViewModel extends AbstractViewModel {
private final ObjectProperty<GroupNodeViewModel> rootGroup = new SimpleObjectProperty<>();
private final ListProperty<GroupNodeViewModel> selectedGroups = new SimpleListProperty<>(FXCollections.observableArrayList());
private final StateManager stateManager;
private final DialogService dialogService;
private final TaskExecutor taskExecutor;
private final ObjectProperty<Predicate<GroupNodeViewModel>> filterPredicate = new SimpleObjectProperty<>();
private final StringProperty filterText = new SimpleStringProperty();
private final Comparator<GroupTreeNode> compAlphabetIgnoreCase = (GroupTreeNode v1, GroupTreeNode v2) -> v1
.getName()
.compareToIgnoreCase(v2.getName());
private Optional<BibDatabaseContext> currentDatabase;
public GroupTreeViewModel(StateManager stateManager, DialogService dialogService, TaskExecutor taskExecutor) {
this.stateManager = Objects.requireNonNull(stateManager);
this.dialogService = Objects.requireNonNull(dialogService);
this.taskExecutor = Objects.requireNonNull(taskExecutor);
// Register listener
stateManager.activeDatabaseProperty()
.addListener((observable, oldValue, newValue) -> onActiveDatabaseChanged(newValue));
selectedGroups.addListener((observable, oldValue, newValue) -> onSelectedGroupChanged(newValue));
// Set-up bindings
filterPredicate
.bind(Bindings.createObjectBinding(() -> group -> group.isMatchedBy(filterText.get()), filterText));
// Init
onActiveDatabaseChanged(stateManager.activeDatabaseProperty().getValue());
}
public ObjectProperty<GroupNodeViewModel> rootGroupProperty() {
return rootGroup;
}
public ListProperty<GroupNodeViewModel> selectedGroupsProperty() {
return selectedGroups;
}
public ObjectProperty<Predicate<GroupNodeViewModel>> filterPredicateProperty() {
return filterPredicate;
}
public StringProperty filterTextProperty() {
return filterText;
}
/**
* Gets invoked if the user selects a different group.
* We need to notify the {@link StateManager} about this change so that the main table gets updated.
*/
private void onSelectedGroupChanged(ObservableList<GroupNodeViewModel> newValue) {
if (!currentDatabase.equals(stateManager.activeDatabaseProperty().getValue())) {
// Switch of database occurred -> do nothing
return;
}
currentDatabase.ifPresent(database -> {
if (newValue == null) {
stateManager.clearSelectedGroups(database);
} else {
stateManager.setSelectedGroups(database, newValue.stream().map(GroupNodeViewModel::getGroupNode).collect(Collectors.toList()));
}
});
}
/**
* Opens "New Group Dialog" and add the resulting group to the root
*/
public void addNewGroupToRoot() {
addNewSubgroup(rootGroup.get());
}
/**
* Gets invoked if the user changes the active database.
* We need to get the new group tree and update the view
*/
private void onActiveDatabaseChanged(Optional<BibDatabaseContext> newDatabase) {
if (newDatabase.isPresent()) {
GroupNodeViewModel newRoot = newDatabase
.map(BibDatabaseContext::getMetaData)
.flatMap(MetaData::getGroups)
.map(root -> new GroupNodeViewModel(newDatabase.get(), stateManager, taskExecutor, root))
.orElse(GroupNodeViewModel.getAllEntriesGroup(newDatabase.get(), stateManager, taskExecutor));
rootGroup.setValue(newRoot);
this.selectedGroups.setAll(
stateManager.getSelectedGroup(newDatabase.get()).stream()
.map(selectedGroup -> new GroupNodeViewModel(newDatabase.get(), stateManager, taskExecutor, selectedGroup))
.collect(Collectors.toList()));
}
currentDatabase = newDatabase;
}
/**
* Opens "New Group Dialog" and add the resulting group to the specified group
*/
public void addNewSubgroup(GroupNodeViewModel parent) {
SwingUtilities.invokeLater(() -> {
Optional<AbstractGroup> newGroup = dialogService.showCustomDialogAndWait(new GroupDialog());
newGroup.ifPresent(group -> {
GroupTreeNode newGroupNode = parent.addSubgroup(group);
// TODO: Add undo
//UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(parent, new GroupTreeNodeViewModel(newGroupNode), UndoableAddOrRemoveGroup.ADD_NODE);
//panel.getUndoManager().addEdit(undo);
// TODO: Expand parent to make new group visible
//parent.expand();
dialogService.notify(Localization.lang("Added group \"%0\".", group.getName()));
writeGroupChangesToMetaData();
});
});
}
private void writeGroupChangesToMetaData() {
currentDatabase.get().getMetaData().setGroups(rootGroup.get().getGroupNode());
}
/**
* Opens "Edit Group Dialog" and changes the given group to the edited one.
*/
public void editGroup(GroupNodeViewModel oldGroup) {
SwingUtilities.invokeLater(() -> {
Optional<AbstractGroup> newGroup = dialogService
.showCustomDialogAndWait(new GroupDialog(oldGroup.getGroupNode().getGroup()));
newGroup.ifPresent(group -> {
Platform.runLater(() -> {
// TODO: Keep assignments
boolean keepPreviousAssignments = dialogService.showConfirmationDialogAndWait(
Localization.lang("Change of Grouping Method"),
Localization.lang("Assign the original group's entries to this group?"));
// WarnAssignmentSideEffects.warnAssignmentSideEffects(newGroup, panel.frame());
boolean removePreviousAssignents = (oldGroup.getGroupNode().getGroup() instanceof ExplicitGroup)
&& (group instanceof ExplicitGroup);
List<FieldChange> addChange = oldGroup.getGroupNode().setGroup(
group,
keepPreviousAssignments,
removePreviousAssignents,
stateManager.getEntriesInCurrentDatabase());
// TODO: Add undo
// Store undo information.
// AbstractUndoableEdit undoAddPreviousEntries = null;
// UndoableModifyGroup undo = new UndoableModifyGroup(GroupSelector.this, groupsRoot, node, newGroup);
// if (undoAddPreviousEntries == null) {
// panel.getUndoManager().addEdit(undo);
//} else {
// NamedCompound nc = new NamedCompound("Modify Group");
// nc.addEdit(undo);
// nc.addEdit(undoAddPreviousEntries);
// nc.end();/
// panel.getUndoManager().addEdit(nc);
//}
//if (!addChange.isEmpty()) {
// undoAddPreviousEntries = UndoableChangeEntriesOfGroup.getUndoableEdit(null, addChange);
//}
dialogService.notify(Localization.lang("Modified group \"%0\".", group.getName()));
writeGroupChangesToMetaData();
});
});
});
}
public void removeSubgroups(GroupNodeViewModel group) {
boolean confirmation = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove subgroups"),
Localization.lang("Remove all subgroups of \"%0\"?", group.getDisplayName()));
if (confirmation) {
/// TODO: Add undo
//final UndoableModifySubtree undo = new UndoableModifySubtree(getGroupTreeRoot(), node, "Remove subgroups");
//panel.getUndoManager().addEdit(undo);
group.getGroupNode().removeAllChildren();
dialogService.notify(Localization.lang("Removed all subgroups of group \"%0\".", group.getDisplayName()));
writeGroupChangesToMetaData();
}
}
public void removeGroupKeepSubgroups(GroupNodeViewModel group) {
boolean confirmation = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove group"),
Localization.lang("Remove group \"%0\"?", group.getDisplayName()));
if (confirmation) {
// TODO: Add undo
//final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node, UndoableAddOrRemoveGroup.REMOVE_NODE_KEEP_CHILDREN);
//panel.getUndoManager().addEdit(undo);
GroupTreeNode groupNode = group.getGroupNode();
groupNode.getParent()
.ifPresent(parent -> groupNode.moveAllChildrenTo(parent, parent.getIndexOfChild(groupNode).get()));
groupNode.removeFromParent();
dialogService.notify(Localization.lang("Removed group \"%0\".", group.getDisplayName()));
writeGroupChangesToMetaData();
}
}
/**
* Removes the specified group and its subgroups (after asking for confirmation).
*/
public void removeGroupAndSubgroups(GroupNodeViewModel group) {
boolean confirmed = dialogService.showConfirmationDialogAndWait(
Localization.lang("Remove group and subgroups"),
Localization.lang("Remove group \"%0\" and its subgroups?", group.getDisplayName()),
Localization.lang("Remove"));
if (confirmed) {
// TODO: Add undo
//final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node, UndoableAddOrRemoveGroup.REMOVE_NODE_AND_CHILDREN);
//panel.getUndoManager().addEdit(undo);
// only remove explicit groups from the entries, keyword groups should not be deleted
if (group.getGroupNode().getGroup() instanceof ExplicitGroup) {
removeGroupsAndSubGroupsFromEntries(group);
}
group.getGroupNode().removeFromParent();
dialogService.notify(Localization.lang("Removed group \"%0\" and its subgroups.", group.getDisplayName()));
writeGroupChangesToMetaData();
}
}
private void removeGroupsAndSubGroupsFromEntries(GroupNodeViewModel group) {
for (GroupNodeViewModel child: group.getChildren()) {
removeGroupsAndSubGroupsFromEntries(child);
}
List<BibEntry> entriesInGroup = group.getGroupNode().getEntriesInGroup(this.currentDatabase.get().getEntries());
group.getGroupNode().removeEntriesFromGroup(entriesInGroup);
}
public void addSelectedEntries(GroupNodeViewModel group) {
// TODO: Warn
// if (!WarnAssignmentSideEffects.warnAssignmentSideEffects(node.getNode().getGroup(), panel.frame())) {
// return; // user aborted operation
List<FieldChange> addChange = group.getGroupNode().addEntriesToGroup(stateManager.getSelectedEntries());
// TODO: Add undo
// NamedCompound undoAll = new NamedCompound(Localization.lang("change assignment of entries"));
// if (!undoAdd.isEmpty()) { undo.addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(node, undoAdd)); }
// panel.getUndoManager().addEdit(undoAll);
// TODO Display massages
//if (undo == null) {
// frame.output(Localization.lang("The group \"%0\" already contains the selection.",
// node.getGroup().getName()));
// return;
//}
// panel.getUndoManager().addEdit(undo);
// final String groupName = node.getGroup().getName();
// if (assignedEntries == 1) {
// frame.output(Localization.lang("Assigned 1 entry to group \"%0\".", groupName));
// } else {
// frame.output(Localization.lang("Assigned %0 entries to group \"%1\".", String.valueOf(assignedEntries),
// groupName));
//}
}
public void removeSelectedEntries(GroupNodeViewModel group) {
// TODO: warn if assignment has undesired side effects (modifies a field != keywords)
// if (!WarnAssignmentSideEffects.warnAssignmentSideEffects(mNode.getNode().getGroup(), mPanel.frame())) {
// return; // user aborted operation
List<FieldChange> removeChange = group.getGroupNode().removeEntriesFromGroup(stateManager.getSelectedEntries());
// TODO: Add undo
// if (!undo.isEmpty()) {
// mPanel.getUndoManager().addEdit(UndoableChangeEntriesOfGroup.getUndoableEdit(mNode, undo));
}
public void sortAlphabeticallyRecursive(GroupNodeViewModel group) {
group.getGroupNode().sortChildren(compAlphabetIgnoreCase, true);
}
}
| Check for explicit group at different location | src/main/java/org/jabref/gui/groups/GroupTreeViewModel.java | Check for explicit group at different location | <ide><path>rc/main/java/org/jabref/gui/groups/GroupTreeViewModel.java
<ide> //final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(groupsRoot, node, UndoableAddOrRemoveGroup.REMOVE_NODE_AND_CHILDREN);
<ide> //panel.getUndoManager().addEdit(undo);
<ide>
<del> // only remove explicit groups from the entries, keyword groups should not be deleted
<del> if (group.getGroupNode().getGroup() instanceof ExplicitGroup) {
<del> removeGroupsAndSubGroupsFromEntries(group);
<del> }
<add> removeGroupsAndSubGroupsFromEntries(group);
<add>
<ide> group.getGroupNode().removeFromParent();
<ide>
<ide> dialogService.notify(Localization.lang("Removed group \"%0\" and its subgroups.", group.getDisplayName()));
<ide> for (GroupNodeViewModel child: group.getChildren()) {
<ide> removeGroupsAndSubGroupsFromEntries(child);
<ide> }
<del>
<del> List<BibEntry> entriesInGroup = group.getGroupNode().getEntriesInGroup(this.currentDatabase.get().getEntries());
<del> group.getGroupNode().removeEntriesFromGroup(entriesInGroup);
<add>
<add> // only remove explicit groups from the entries, keyword groups should not be deleted
<add> if (group.getGroupNode().getGroup() instanceof ExplicitGroup) {
<add> List<BibEntry> entriesInGroup = group.getGroupNode().getEntriesInGroup(this.currentDatabase.get().getEntries());
<add> group.getGroupNode().removeEntriesFromGroup(entriesInGroup);
<add> }
<ide> }
<ide>
<ide> public void addSelectedEntries(GroupNodeViewModel group) { |
|
Java | lgpl-2.1 | e78b8576adf4f2a5ca554c155ae3241ed9ca8f35 | 0 | ggiudetti/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,it-tavis/opencms-core,alkacon/opencms-core,victos/opencms-core,mediaworx/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,victos/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,MenZil/opencms-core,gallardo/opencms-core,mediaworx/opencms-core,victos/opencms-core,MenZil/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,victos/opencms-core,alkacon/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,gallardo/opencms-core,serrapos/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,sbonoc/opencms-core,serrapos/opencms-core | /*
* File : $Source: /alkacon/cvs/opencms/src-modules/org/opencms/ade/publish/Attic/CmsPublishService.java,v $
* Date : $Date: 2010/04/13 13:59:20 $
* Version: $Revision: 1.6 $
*
* 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.ade.publish;
import org.opencms.ade.publish.shared.CmsProjectBean;
import org.opencms.ade.publish.shared.CmsPublishData;
import org.opencms.ade.publish.shared.CmsPublishGroup;
import org.opencms.ade.publish.shared.CmsPublishOptions;
import org.opencms.ade.publish.shared.CmsPublishResource;
import org.opencms.ade.publish.shared.rpc.I_CmsPublishService;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.gwt.CmsGwtService;
import org.opencms.gwt.shared.rpc.CmsRpcException;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.util.CmsUUID;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
/**
* The implementation of the publish service.<p>
*
* @author Georg Westenberger
*
* @version $Revision: 1.6 $
*
* @since 8.0.0
*
*/
public class CmsPublishService extends CmsGwtService implements I_CmsPublishService {
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsPublishService.class);
/** The version id for serialization. */
private static final long serialVersionUID = 1L;
/** Session attribute name constant. */
private static final String SESSION_ATTR_ADE_PUB_OPTS_CACHE = "__OCMS_ADE_PUB_OPTS_CACHE__";
/**
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#getInitData()
*/
public CmsPublishData getInitData() throws CmsRpcException {
try {
CmsPublishOptions options = getCachedOptions();
return new CmsPublishData(options, getProjects(), getPublishGroups(options));
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsRpcException(CmsException.getStackTraceAsString(e));
}
}
/**
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#getProjects()
*/
public List<CmsProjectBean> getProjects() throws CmsRpcException {
try {
return new CmsPublish(getCmsObject()).getManageableProjects();
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsRpcException(CmsException.getStackTraceAsString(e));
}
}
/**
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#getPublishGroups(org.opencms.ade.publish.shared.CmsPublishOptions)
*/
public List<CmsPublishGroup> getPublishGroups(CmsPublishOptions options) throws CmsRpcException {
try {
CmsPublish pub = new CmsPublish(getCmsObject(), options);
setCachedOptions(options);
return pub.getPublishGroups();
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsRpcException(CmsException.getStackTraceAsString(e));
}
}
/**
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#getPublishOptions()
*/
public CmsPublishOptions getPublishOptions() throws CmsRpcException {
try {
return getCachedOptions();
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsRpcException(CmsException.getStackTraceAsString(e));
}
}
/**
*
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#publishResources(java.util.List, java.util.List, boolean)
*/
public List<CmsPublishResource> publishResources(List<CmsUUID> toPublish, List<CmsUUID> toRemove, boolean force)
throws CmsRpcException {
try {
CmsObject cms = getCmsObject();
CmsPublish pub = new CmsPublish(cms, getCachedOptions());
List<CmsResource> publishResources = idsToResources(cms, toPublish);
List<CmsPublishResource> brokenLinkBeans = pub.getBrokenResources(publishResources);
if (brokenLinkBeans.size() == 0) {
pub.publishResources(publishResources);
pub.removeResourcesFromPublishList(toRemove);
}
return brokenLinkBeans;
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsRpcException(CmsException.getStackTraceAsString(e));
}
}
/**
* Returns the cached publish options, creating it if it doesn't already exist.<p>
*
* @return the cached publish options
*/
private CmsPublishOptions getCachedOptions() {
CmsPublishOptions cache = (CmsPublishOptions)getRequest().getSession().getAttribute(
SESSION_ATTR_ADE_PUB_OPTS_CACHE);
if (cache == null) {
cache = new CmsPublishOptions();
getRequest().getSession().setAttribute(SESSION_ATTR_ADE_PUB_OPTS_CACHE, cache);
}
return cache;
}
/**
* Converts a list of IDs to resources.<p>
*
* @param cms the CmObject used for reading the resources
* @param ids the list of IDs
*
* @return a list of resources
*/
private List<CmsResource> idsToResources(CmsObject cms, List<CmsUUID> ids) {
List<CmsResource> result = new ArrayList<CmsResource>();
for (CmsUUID id : ids) {
try {
CmsResource resource = cms.readResource(id, CmsResourceFilter.ALL);
result.add(resource);
} catch (CmsException e) {
// should never happen
LOG.error(e.getLocalizedMessage(), e);
}
}
return result;
}
/**
* Saves the given options to the session.<p>
*
* @param options the options to save
*/
private void setCachedOptions(CmsPublishOptions options) {
getRequest().getSession().setAttribute(SESSION_ATTR_ADE_PUB_OPTS_CACHE, options);
}
}
| src-modules/org/opencms/ade/publish/CmsPublishService.java | /*
* File : $Source: /alkacon/cvs/opencms/src-modules/org/opencms/ade/publish/Attic/CmsPublishService.java,v $
* Date : $Date: 2010/04/13 09:17:28 $
* Version: $Revision: 1.5 $
*
* 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.ade.publish;
import org.opencms.ade.publish.shared.CmsProjectBean;
import org.opencms.ade.publish.shared.CmsPublishData;
import org.opencms.ade.publish.shared.CmsPublishGroup;
import org.opencms.ade.publish.shared.CmsPublishOptions;
import org.opencms.ade.publish.shared.CmsPublishResource;
import org.opencms.ade.publish.shared.rpc.I_CmsPublishService;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsResourceFilter;
import org.opencms.gwt.CmsGwtService;
import org.opencms.gwt.shared.rpc.CmsRpcException;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.util.CmsUUID;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
/**
* The implementation of the publish service.<p>
*
* @author Georg Westenberger
*
* @version $Revision: 1.5 $
*
* @since 8.0.0
*
*/
public class CmsPublishService extends CmsGwtService implements I_CmsPublishService {
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsPublishService.class);
/** The version id for serialization. */
private static final long serialVersionUID = 1L;
/** Session attribute name constant. */
private static final String SESSION_ATTR_ADE_PUB_OPTS_CACHE = "__OCMS_ADE_PUB_OPTS_CACHE__";
/**
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#getInitData()
*/
public CmsPublishData getInitData() throws CmsRpcException {
try {
CmsPublishOptions options = getCachedOptions();
return new CmsPublishData(options, getProjects(), getPublishGroups(options));
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsRpcException(CmsException.getStackTraceAsString(e));
}
}
/**
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#getProjects()
*/
public List<CmsProjectBean> getProjects() throws CmsRpcException {
try {
return new CmsPublish(getCmsObject()).getManageableProjects();
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsRpcException(CmsException.getStackTraceAsString(e));
}
}
/**
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#getPublishGroups(org.opencms.ade.publish.shared.CmsPublishOptions)
*/
public List<CmsPublishGroup> getPublishGroups(CmsPublishOptions options) throws CmsRpcException {
try {
CmsPublish pub = new CmsPublish(getCmsObject(), options);
setCachedOptions(options);
return pub.getPublishGroups();
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsRpcException(CmsException.getStackTraceAsString(e));
}
}
/**
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#getPublishOptions()
*/
public CmsPublishOptions getPublishOptions() throws CmsRpcException {
try {
return getCachedOptions();
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsRpcException(CmsException.getStackTraceAsString(e));
}
}
/**
*
* @see org.opencms.ade.publish.shared.rpc.I_CmsPublishService#publishResources(java.util.List, java.util.List, boolean)
*/
public List<CmsPublishResource> publishResources(List<CmsUUID> toPublish, List<CmsUUID> toRemove, boolean force)
throws CmsRpcException {
try {
CmsObject cms = getCmsObject();
// TODO: i think we need the publish options here!
CmsPublish pub = new CmsPublish(cms);
List<CmsResource> publishResources = idsToResources(cms, toPublish);
List<CmsPublishResource> brokenLinkBeans = pub.getBrokenResources(publishResources);
if (brokenLinkBeans.size() == 0) {
pub.publishResources(publishResources);
pub.removeResourcesFromPublishList(toRemove);
}
return brokenLinkBeans;
} catch (Throwable e) {
LOG.error(e.getLocalizedMessage(), e);
throw new CmsRpcException(CmsException.getStackTraceAsString(e));
}
}
/**
* Returns the cached publish options, creating it if it doesn't already exist.<p>
*
* @return the cached publish options
*/
private CmsPublishOptions getCachedOptions() {
CmsPublishOptions cache = (CmsPublishOptions)getRequest().getSession().getAttribute(
SESSION_ATTR_ADE_PUB_OPTS_CACHE);
if (cache == null) {
cache = new CmsPublishOptions();
getRequest().getSession().setAttribute(SESSION_ATTR_ADE_PUB_OPTS_CACHE, cache);
}
return cache;
}
/**
* Converts a list of IDs to resources.<p>
*
* @param cms the CmObject used for reading the resources
* @param ids the list of IDs
*
* @return a list of resources
*/
private List<CmsResource> idsToResources(CmsObject cms, List<CmsUUID> ids) {
List<CmsResource> result = new ArrayList<CmsResource>();
for (CmsUUID id : ids) {
try {
CmsResource resource = cms.readResource(id, CmsResourceFilter.ALL);
result.add(resource);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
// TODO: do something with these resources. show them to the user?
}
}
return result;
}
/**
* Saves the given options to the session.<p>
*
* @param options the options to save
*/
private void setCachedOptions(CmsPublishOptions options) {
getRequest().getSession().setAttribute(SESSION_ATTR_ADE_PUB_OPTS_CACHE, options);
}
}
| minor improvements
| src-modules/org/opencms/ade/publish/CmsPublishService.java | minor improvements | <ide><path>rc-modules/org/opencms/ade/publish/CmsPublishService.java
<ide> /*
<ide> * File : $Source: /alkacon/cvs/opencms/src-modules/org/opencms/ade/publish/Attic/CmsPublishService.java,v $
<del> * Date : $Date: 2010/04/13 09:17:28 $
<del> * Version: $Revision: 1.5 $
<add> * Date : $Date: 2010/04/13 13:59:20 $
<add> * Version: $Revision: 1.6 $
<ide> *
<ide> * This library is part of OpenCms -
<ide> * the Open Source Content Management System
<ide> *
<ide> * @author Georg Westenberger
<ide> *
<del> * @version $Revision: 1.5 $
<add> * @version $Revision: 1.6 $
<ide> *
<ide> * @since 8.0.0
<ide> *
<ide>
<ide> try {
<ide> CmsObject cms = getCmsObject();
<del> // TODO: i think we need the publish options here!
<del> CmsPublish pub = new CmsPublish(cms);
<add> CmsPublish pub = new CmsPublish(cms, getCachedOptions());
<ide> List<CmsResource> publishResources = idsToResources(cms, toPublish);
<ide> List<CmsPublishResource> brokenLinkBeans = pub.getBrokenResources(publishResources);
<ide> if (brokenLinkBeans.size() == 0) {
<ide> CmsResource resource = cms.readResource(id, CmsResourceFilter.ALL);
<ide> result.add(resource);
<ide> } catch (CmsException e) {
<add> // should never happen
<ide> LOG.error(e.getLocalizedMessage(), e);
<del> // TODO: do something with these resources. show them to the user?
<ide> }
<ide> }
<ide> return result; |
|
Java | agpl-3.0 | 11d933ad8ae4c5cd3f0f1bb6860200f857d10f3a | 0 | ubicity-devs/ubicity-rss | package at.ac.ait.ubicity.rss.impl;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.jdom2.Element;
import at.ac.ait.ubicity.contracts.rss.RssDTO;
import com.rometools.rome.feed.synd.SyndCategory;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
public class RssParser {
final static Logger logger = Logger.getLogger(RssParser.class);
private final URL url;
private static SyndFeedInput input = new SyndFeedInput();
private final String lastGuid;
public RssParser(String urlString, String lastGuid)
throws MalformedURLException {
this.url = new URL(urlString);
this.lastGuid = lastGuid;
}
public List<RssDTO> fetchUpdates() throws Exception {
List<RssDTO> list = new ArrayList<RssDTO>();
// run fetching as thread to enable interrupt
Runnable r = new Runnable() {
@Override
public void run() {
try {
SyndFeed feed = input.build(new XmlReader(url));
for (SyndEntry e : feed.getEntries()) {
if (isNewEntry(e.getUri())) {
RssDTO dto = new RssDTO();
dto.setId(e.getUri());
dto.setTitle(e.getTitle());
dto.setText(e.getDescription().getValue());
dto.setSource(e.getLink());
dto.setCreatedAt(e.getPublishedDate());
List<String> cats = new ArrayList<String>();
for (SyndCategory cat : e.getCategories()) {
cats.add(cat.getName());
}
dto.setCategories(cats);
dto.setLang(readForeignMarkup(e.getForeignMarkup(),
ForeignRssTag.LANG));
String geo = readForeignMarkup(
e.getForeignMarkup(),
ForeignRssTag.GEO_POINT);
if (geo != null) {
String[] geoAr = geo.split(" ");
dto.setGeoRssPoint(Float.parseFloat(geoAr[1]),
Float.parseFloat(geoAr[0]));
}
list.add(dto);
}
}
} catch (Exception e) {
logger.warn("Exc caught ", e);
}
}
};
Thread thr = new Thread(r);
thr.start();
// sleep max 30sek - afterwards interrupt thread
for (int i = 0; i < 30 && thr.isAlive(); i++) {
Thread.sleep(1000L);
}
if (thr.isAlive()) {
thr.interrupt();
logger.info("Task interrupted of URL: " + this.url.toString());
return list;
}
logger.info(list.size() + " new RSS Entries read from "
+ this.url.toString());
return list;
}
private boolean isNewEntry(String curGuid) {
if (this.lastGuid == null || curGuid == null) {
return true;
}
return this.lastGuid.equals(curGuid);
}
private String readForeignMarkup(List<Element> list, ForeignRssTag tag) {
for (Element e : list) {
if (tag.getName().equalsIgnoreCase(e.getName())) {
return e.getContent(0).getValue();
}
}
return null;
}
} | src/main/java/at/ac/ait/ubicity/rss/impl/RssParser.java | package at.ac.ait.ubicity.rss.impl;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.jdom2.Element;
import at.ac.ait.ubicity.contracts.rss.RssDTO;
import com.rometools.rome.feed.synd.SyndCategory;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
public class RssParser {
final static Logger logger = Logger.getLogger(RssParser.class);
private final URL url;
private static SyndFeedInput input = new SyndFeedInput();
private final String lastGuid;
public RssParser(String urlString, String lastGuid)
throws MalformedURLException {
this.url = new URL(urlString);
this.lastGuid = lastGuid;
}
public List<RssDTO> fetchUpdates() throws Exception {
List<RssDTO> list = new ArrayList<RssDTO>();
// run fetching as thread to enable interrupt
Runnable r = new Runnable() {
@Override
public void run() {
try {
SyndFeed feed = input.build(new XmlReader(url));
for (SyndEntry e : feed.getEntries()) {
if (isNewEntry(e.getPublishedDate())) {
RssDTO dto = new RssDTO();
dto.setId(e.getUri());
dto.setTitle(e.getTitle());
dto.setText(e.getDescription().getValue());
dto.setSource(e.getLink());
dto.setCreatedAt(e.getPublishedDate());
List<String> cats = new ArrayList<String>();
for (SyndCategory cat : e.getCategories()) {
cats.add(cat.getName());
}
dto.setCategories(cats);
dto.setLang(readForeignMarkup(e.getForeignMarkup(),
ForeignRssTag.LANG));
String geo = readForeignMarkup(
e.getForeignMarkup(),
ForeignRssTag.GEO_POINT);
if (geo != null) {
String[] geoAr = geo.split(" ");
dto.setGeoRssPoint(Float.parseFloat(geoAr[1]),
Float.parseFloat(geoAr[0]));
}
list.add(dto);
}
}
} catch (Exception e) {
logger.warn("Exc caught ", e);
}
}
};
Thread thr = new Thread(r);
thr.start();
// sleep max 30sek - afterwards interrupt thread
for (int i = 0; i < 30 && thr.isAlive(); i++) {
Thread.sleep(1000L);
}
if (thr.isAlive()) {
thr.interrupt();
logger.info("Task interrupted of URL: " + this.url.toString());
return list;
}
logger.info(list.size() + " new RSS Entries read from "
+ this.url.toString());
return list;
}
private boolean isNewEntry(Date curGuid) {
if (this.lastGuid == null || curGuid == null) {
return true;
}
return this.lastGuid.equals(curGuid);
}
private String readForeignMarkup(List<Element> list, ForeignRssTag tag) {
for (Element e : list) {
if (tag.getName().equalsIgnoreCase(e.getName())) {
return e.getContent(0).getValue();
}
}
return null;
}
} | fixed newEntry method | src/main/java/at/ac/ait/ubicity/rss/impl/RssParser.java | fixed newEntry method | <ide><path>rc/main/java/at/ac/ait/ubicity/rss/impl/RssParser.java
<ide> import java.net.MalformedURLException;
<ide> import java.net.URL;
<ide> import java.util.ArrayList;
<del>import java.util.Date;
<ide> import java.util.List;
<ide>
<ide> import org.apache.log4j.Logger;
<ide> SyndFeed feed = input.build(new XmlReader(url));
<ide>
<ide> for (SyndEntry e : feed.getEntries()) {
<del> if (isNewEntry(e.getPublishedDate())) {
<add> if (isNewEntry(e.getUri())) {
<ide> RssDTO dto = new RssDTO();
<ide> dto.setId(e.getUri());
<ide> dto.setTitle(e.getTitle());
<ide> return list;
<ide> }
<ide>
<del> private boolean isNewEntry(Date curGuid) {
<add> private boolean isNewEntry(String curGuid) {
<ide>
<ide> if (this.lastGuid == null || curGuid == null) {
<ide> return true; |
|
JavaScript | mit | 4436bb95d016b21de68cdebeccc117cb2ed99443 | 0 | 4commerce-technologies-AG/meteor,AnthonyAstige/meteor,mjmasn/meteor,Hansoft/meteor,4commerce-technologies-AG/meteor,Hansoft/meteor,AnthonyAstige/meteor,nuvipannu/meteor,jdivy/meteor,AnthonyAstige/meteor,Hansoft/meteor,nuvipannu/meteor,nuvipannu/meteor,lorensr/meteor,AnthonyAstige/meteor,mjmasn/meteor,lorensr/meteor,lorensr/meteor,mjmasn/meteor,jdivy/meteor,DAB0mB/meteor,chasertech/meteor,nuvipannu/meteor,mjmasn/meteor,AnthonyAstige/meteor,chasertech/meteor,4commerce-technologies-AG/meteor,DAB0mB/meteor,Hansoft/meteor,chasertech/meteor,AnthonyAstige/meteor,4commerce-technologies-AG/meteor,jdivy/meteor,Hansoft/meteor,DAB0mB/meteor,AnthonyAstige/meteor,chasertech/meteor,jdivy/meteor,AnthonyAstige/meteor,mjmasn/meteor,4commerce-technologies-AG/meteor,jdivy/meteor,4commerce-technologies-AG/meteor,mjmasn/meteor,chasertech/meteor,DAB0mB/meteor,DAB0mB/meteor,DAB0mB/meteor,Hansoft/meteor,4commerce-technologies-AG/meteor,lorensr/meteor,jdivy/meteor,lorensr/meteor,nuvipannu/meteor,nuvipannu/meteor,Hansoft/meteor,DAB0mB/meteor,jdivy/meteor,mjmasn/meteor,chasertech/meteor,lorensr/meteor,lorensr/meteor,nuvipannu/meteor,chasertech/meteor | var callbackQueue = [];
var isLoadingCompleted = false;
var isReady = false;
// Keeps track of how many events to wait for in addition to loading completing,
// before we're considered ready.
var readyHoldsCount = 0;
var holdReady = function () {
readyHoldsCount++;
}
var releaseReadyHold = function () {
readyHoldsCount--;
maybeReady();
}
var maybeReady = function () {
if (isReady || !isLoadingCompleted || readyHoldsCount > 0)
return;
isReady = true;
// Run startup callbacks
while (callbackQueue.length)
(callbackQueue.shift())();
if (Meteor.isCordova) {
// Notify the WebAppCordova plugin startup was completed successfully, so we can
// roll back faulty versions if this doesn't occur
WebAppCordova.startupDidComplete();
}
};
var loadingCompleted = function () {
if (!isLoadingCompleted) {
isLoadingCompleted = true;
maybeReady();
}
}
if (Meteor.isCordova) {
holdReady();
document.addEventListener('deviceready', releaseReadyHold, false);
}
if (document.readyState === 'complete' || document.readyState === 'loaded') {
// Loading has completed,
// but allow other scripts the opportunity to hold ready
window.setTimeout(loadingCompleted);
} else { // Attach event listeners to wait for loading to complete
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', loadingCompleted, false);
window.addEventListener('load', loadingCompleted, false);
} else { // Use IE event model for < IE9
document.attachEvent('onreadystatechange', function () {
if (document.readyState === "complete") {
loadingCompleted();
}
});
window.attachEvent('load', loadingCompleted);
}
}
/**
* @summary Run code when a client or a server starts.
* @locus Anywhere
* @param {Function} func A function to run on startup.
*/
Meteor.startup = function (callback) {
// Fix for < IE9, see http://javascript.nwbox.com/IEContentLoaded/
var doScroll = !document.addEventListener &&
document.documentElement.doScroll;
if (!doScroll || window !== top) {
if (isReady)
callback();
else
callbackQueue.push(callback);
} else {
try { doScroll('left'); }
catch (error) {
setTimeout(function () { Meteor.startup(callback); }, 50);
return;
};
callback();
}
};
| packages/meteor/startup_client.js | var callbackQueue = [];
var isLoadingCompleted = false;
var isReady = false;
// Keeps track of how many events to wait for in addition to loading completing,
// before we're considered ready.
var readyHoldsCount = 0;
var holdReady = function () {
readyHoldsCount++;
}
var releaseReadyHold = function () {
readyHoldsCount--;
maybeReady();
}
var maybeReady = function () {
if (isReady || !isLoadingCompleted || readyHoldsCount > 0)
return;
isReady = true;
// Run startup callbacks
while (callbackQueue.length)
(callbackQueue.shift())();
};
var loadingCompleted = function () {
if (!isLoadingCompleted) {
isLoadingCompleted = true;
maybeReady();
}
}
if (Meteor.isCordova) {
holdReady();
document.addEventListener('deviceready', releaseReadyHold, false);
}
if (document.readyState === 'complete' || document.readyState === 'loaded') {
// Loading has completed,
// but allow other scripts the opportunity to hold ready
window.setTimeout(loadingCompleted);
} else { // Attach event listeners to wait for loading to complete
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', loadingCompleted, false);
window.addEventListener('load', loadingCompleted, false);
} else { // Use IE event model for < IE9
document.attachEvent('onreadystatechange', function () {
if (document.readyState === "complete") {
loadingCompleted();
}
});
window.attachEvent('load', loadingCompleted);
}
}
/**
* @summary Run code when a client or a server starts.
* @locus Anywhere
* @param {Function} func A function to run on startup.
*/
Meteor.startup = function (callback) {
// Fix for < IE9, see http://javascript.nwbox.com/IEContentLoaded/
var doScroll = !document.addEventListener &&
document.documentElement.doScroll;
if (!doScroll || window !== top) {
if (isReady)
callback();
else
callbackQueue.push(callback);
} else {
try { doScroll('left'); }
catch (error) {
setTimeout(function () { Meteor.startup(callback); }, 50);
return;
};
callback();
}
};
| Consider startup successful after all callbacks have completed
| packages/meteor/startup_client.js | Consider startup successful after all callbacks have completed | <ide><path>ackages/meteor/startup_client.js
<ide> // Run startup callbacks
<ide> while (callbackQueue.length)
<ide> (callbackQueue.shift())();
<add>
<add> if (Meteor.isCordova) {
<add> // Notify the WebAppCordova plugin startup was completed successfully, so we can
<add> // roll back faulty versions if this doesn't occur
<add> WebAppCordova.startupDidComplete();
<add> }
<ide> };
<ide>
<ide> var loadingCompleted = function () { |
|
Java | apache-2.0 | 7dd2316d4a659a8395609197f53ab33030b869f7 | 0 | cuba-platform/cuba,cuba-platform/cuba,cuba-platform/cuba | package com.haulmont.cuba.gui.components;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.cuba.core.app.LockService;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.gui.ComponentsHelper;
import com.haulmont.cuba.gui.components.actions.CreateAction;
import com.haulmont.cuba.gui.components.actions.EditAction;
import com.haulmont.cuba.gui.components.actions.RemoveAction;
import com.haulmont.cuba.gui.data.CollectionDatasource;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.security.entity.EntityOp;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Base class for controllers of combined browser/editor screens.
*/
public class EntityCombinedScreen extends AbstractLookup {
/**
* Indicates that a new instance of entity is being created.
*/
protected boolean creating;
/**
* Indicates that the screen is in editing mode.
*/
protected boolean editing;
/**
* Indicates that edited entity is pessimistically locked.
*/
protected boolean justLocked;
/**
* Returns the left container with browse components. Override if the container id differs from "lookupBox".
*/
protected ComponentContainer getLookupBox() {
return (ComponentContainer) getComponentNN("lookupBox");
}
/**
* Returns the browse table. Override if the table id differs from "table".
*/
protected ListComponent getTable() {
return (ListComponent) getComponentNN("table");
}
/**
* Returns the right container with edit components. Override if the container id differs from "editBox".
*/
protected ComponentContainer getEditBox() {
return (ComponentContainer) getComponentNN("editBox");
}
/**
* Returns the tab sheet with edit components. Can be null if the screen contains a field group only.
* Override if the tab sheet id differs from "tabSheet".
*/
@Nullable
protected TabSheet getTabSheet() {
return (TabSheet) getComponent("tabSheet");
}
/**
* Returns the field group. Override if the field group id differs from "fieldGroup".
*/
protected FieldGroup getFieldGroup() {
return (FieldGroup) getComponentNN("fieldGroup");
}
/**
* Returns the container with edit actions (save, cancel). Override if the container id differs from "actionsPane".
*/
protected ComponentContainer getActionsPane() {
return (ComponentContainer) getComponentNN("actionsPane");
}
@Override
public void init(Map<String, Object> params) {
initBrowseItemChangeListener();
initBrowseCreateAction();
initBrowseEditAction();
initBrowseRemoveAction();
initShortcuts();
disableEditControls();
}
/**
* Adds a listener that reloads the selected record with the specified view and sets it to editDs.
*/
@SuppressWarnings("unchecked")
protected void initBrowseItemChangeListener() {
CollectionDatasource browseDs = getTable().getDatasource();
Datasource editDs = getFieldGroup().getDatasource();
browseDs.addItemChangeListener(e -> {
if (e.getItem() != null) {
Entity reloadedItem = getDsContext().getDataSupplier().reload(
e.getDs().getItem(), editDs.getView(), null, e.getDs().getLoadDynamicAttributes());
editDs.setItem(reloadedItem);
}
});
}
/**
* Adds a CreateAction that removes selection in table, sets a newly created item to editDs
* and enables controls for record editing.
*/
protected void initBrowseCreateAction() {
ListComponent table = getTable();
table.addAction(new CreateAction(table) {
@SuppressWarnings("unchecked")
@Override
protected void internalOpenEditor(CollectionDatasource datasource, Entity newItem, Datasource parentDs, Map<String, Object> params) {
initNewItem(newItem);
table.setSelected(Collections.emptyList());
getFieldGroup().getDatasource().setItem(newItem);
refreshOptionsForLookupFields();
enableEditControls(true);
}
});
}
/**
* Hook to be implemented in subclasses. Called when the screen turns into editing mode
* for a new entity instance. Enables additional initialization of the new entity instance
* before setting it into the datasource.
* @param item new entity instance
*/
protected void initNewItem(Entity item) {
}
/**
* Adds an EditAction that enables controls for editing.
*/
protected void initBrowseEditAction() {
ListComponent table = getTable();
table.addAction(new EditAction(table) {
@Override
public void actionPerform(Component component) {
if (table.getSelected().size() == 1) {
if (lockIfNeeded((Entity) table.getSelected().iterator().next())) {
super.actionPerform(component);
}
}
}
@Override
protected void internalOpenEditor(CollectionDatasource datasource, Entity existingItem, Datasource parentDs, Map<String, Object> params) {
refreshOptionsForLookupFields();
enableEditControls(false);
}
@Override
public void refreshState() {
if (target != null) {
CollectionDatasource ds = target.getDatasource();
if (ds != null && !captionInitialized) {
setCaption(messages.getMainMessage("actions.Edit"));
}
}
super.refreshState();
}
@Override
protected boolean isPermitted() {
CollectionDatasource ownerDatasource = target.getDatasource();
boolean entityOpPermitted = security.isEntityOpPermitted(ownerDatasource.getMetaClass(), EntityOp.UPDATE);
if (!entityOpPermitted) {
return false;
}
return super.isPermitted();
}
});
}
/**
* Pessimistic lock before start of editing, if it is configured for the entity.
*/
protected boolean lockIfNeeded(Entity entity) {
MetaClass metaClass = getMetaClassForLocking(entity);
LockInfo lockInfo = AppBeans.get(LockService.class).lock(metaClass.getName(), entity.getId().toString());
if (lockInfo == null) {
justLocked = true;
} else if (!(lockInfo instanceof LockNotSupported)) {
showNotification(
messages.getMainMessage("entityLocked.msg"),
String.format(messages.getMainMessage("entityLocked.desc"),
lockInfo.getUser().getLogin(),
AppBeans.get(DatatypeFormatter.class).formatDateTime(lockInfo.getSince())
),
Frame.NotificationType.HUMANIZED
);
return false;
}
return true;
}
/**
* Release pessimistic lock if it was applied.
*/
protected void releaseLock() {
if (justLocked) {
Datasource ds = getFieldGroup().getDatasource();
Entity entity = ds.getItem();
if (entity != null) {
MetaClass metaClass = getMetaClassForLocking(entity);
AppBeans.get(LockService.class).unlock(metaClass.getName(), entity.getId().toString());
}
}
}
protected MetaClass getMetaClassForLocking(Entity item) {
// lock original metaClass, if any, because by convention all the configuration is based on original entities
MetaClass metaClass = AppBeans.get(ExtendedEntities.class).getOriginalMetaClass(item.getMetaClass());
if (metaClass == null) {
metaClass = getTable().getDatasource().getMetaClass();
}
return metaClass;
}
/**
* Adds AfterRemoveHandler for table's Remove action to reset the record contained in editDs.
*/
@SuppressWarnings("unchecked")
protected void initBrowseRemoveAction() {
ListComponent table = getTable();
Datasource editDs = getFieldGroup().getDatasource();
RemoveAction removeAction = (RemoveAction) table.getAction(RemoveAction.ACTION_ID);
if (removeAction != null)
removeAction.setAfterRemoveHandler(removedItems -> editDs.setItem(null));
}
/**
* Adds ESCAPE shortcut that invokes cancel() method.
*/
protected void initShortcuts() {
ComponentContainer editBox = getEditBox();
if (editBox instanceof ShortcutNotifier) {
((ShortcutNotifier) editBox).addShortcutAction(
new ShortcutAction(new KeyCombination(KeyCombination.Key.ESCAPE),
shortcutTriggeredEvent -> cancel()));
}
}
protected void refreshOptionsForLookupFields() {
for (Component component : getFieldGroup().getOwnComponents()) {
if (component instanceof LookupField) {
CollectionDatasource optionsDatasource = ((LookupField) component).getOptionsDatasource();
if (optionsDatasource != null) {
optionsDatasource.refresh();
}
}
}
}
/**
* Enables controls for editing.
* @param creating indicates that a new instance is being created
*/
protected void enableEditControls(boolean creating) {
this.editing = true;
this.creating = creating;
initEditComponents(true);
getFieldGroup().requestFocus();
}
/**
* Disables edit controls.
*/
protected void disableEditControls() {
this.editing = false;
initEditComponents(false);
((Focusable) getTable()).focus();
}
/**
* Initializes edit controls, depending on if they should be enabled or disabled.
* @param enabled if true - enables edit controls and disables controls on the left side of the splitter
* if false - vice versa
*/
protected void initEditComponents(boolean enabled) {
TabSheet tabSheet = getTabSheet();
if (tabSheet != null) {
ComponentsHelper.walkComponents(tabSheet, (component, name) -> {
if (component instanceof FieldGroup) {
((FieldGroup) component).setEditable(enabled);
} else if (component instanceof Table) {
((Table) component).getActions().forEach(action -> action.setEnabled(enabled));
} else if (!(component instanceof ComponentContainer)) {
component.setEnabled(enabled);
}
});
}
getFieldGroup().setEditable(enabled);
getActionsPane().setVisible(enabled);
getLookupBox().setEnabled(!enabled);
}
/**
* Validates editor fields.
*
* @return true if all fields are valid or false otherwise
*/
protected boolean validateEditor() {
FieldGroup fieldGroup = getFieldGroup();
List<Validatable> components = new ArrayList<>();
for (Component component: fieldGroup.getComponents()) {
if (component instanceof Validatable) {
components.add((Validatable)component);
}
}
return validate(components);
}
/**
* Method that is invoked by clicking Ok button after editing an existing or creating a new record.
*/
@SuppressWarnings("unchecked")
public void save() {
if (!editing)
return;
if (!validateEditor()) {
return;
}
getDsContext().commit();
ListComponent table = getTable();
CollectionDatasource browseDs = table.getDatasource();
Entity editedItem = getFieldGroup().getDatasource().getItem();
if (creating) {
browseDs.includeItem(editedItem);
} else {
browseDs.updateItem(editedItem);
}
table.setSelected(editedItem);
releaseLock();
disableEditControls();
}
/**
* Method that is invoked by clicking Cancel button, discards changes and disables controls for editing.
*/
@SuppressWarnings("unchecked")
public void cancel() {
CollectionDatasource browseDs = getTable().getDatasource();
Datasource editDs = getFieldGroup().getDatasource();
Entity selectedItem = browseDs.getItem();
if (selectedItem != null) {
Entity reloadedItem = getDsContext().getDataSupplier().reload(
selectedItem, editDs.getView(), null, editDs.getLoadDynamicAttributes());
browseDs.setItem(reloadedItem);
} else {
editDs.setItem(null);
}
releaseLock();
disableEditControls();
}
}
| modules/gui/src/com/haulmont/cuba/gui/components/EntityCombinedScreen.java | package com.haulmont.cuba.gui.components;
import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.cuba.core.app.LockService;
import com.haulmont.cuba.core.entity.Entity;
import com.haulmont.cuba.core.global.*;
import com.haulmont.cuba.gui.ComponentsHelper;
import com.haulmont.cuba.gui.components.actions.CreateAction;
import com.haulmont.cuba.gui.components.actions.EditAction;
import com.haulmont.cuba.gui.components.actions.RemoveAction;
import com.haulmont.cuba.gui.data.CollectionDatasource;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.security.entity.EntityOp;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Base class for controllers of combined browser/editor screens.
*/
public class EntityCombinedScreen extends AbstractLookup {
/**
* Indicates that a new instance of entity is being created.
*/
protected boolean creating;
/**
* Indicates that the screen is in editing mode.
*/
protected boolean editing;
/**
* Indicates that edited entity is pessimistically locked.
*/
protected boolean justLocked;
/**
* Returns the left container with browse components. Override if the container id differs from "lookupBox".
*/
protected ComponentContainer getLookupBox() {
return (ComponentContainer) getComponentNN("lookupBox");
}
/**
* Returns the browse table. Override if the table id differs from "table".
*/
protected ListComponent getTable() {
return (ListComponent) getComponentNN("table");
}
/**
* Returns the right container with edit components. Override if the container id differs from "editBox".
*/
protected ComponentContainer getEditBox() {
return (ComponentContainer) getComponentNN("editBox");
}
/**
* Returns the tab sheet with edit components. Can be null if the screen contains a field group only.
* Override if the tab sheet id differs from "tabSheet".
*/
@Nullable
protected TabSheet getTabSheet() {
return (TabSheet) getComponent("tabSheet");
}
/**
* Returns the field group. Override if the field group id differs from "fieldGroup".
*/
protected FieldGroup getFieldGroup() {
return (FieldGroup) getComponentNN("fieldGroup");
}
/**
* Returns the container with edit actions (save, cancel). Override if the container id differs from "actionsPane".
*/
protected ComponentContainer getActionsPane() {
return (ComponentContainer) getComponentNN("actionsPane");
}
@Override
public void init(Map<String, Object> params) {
initBrowseItemChangeListener();
initBrowseCreateAction();
initBrowseEditAction();
initBrowseRemoveAction();
initShortcuts();
disableEditControls();
}
/**
* Adds a listener that reloads the selected record with the specified view and sets it to editDs.
*/
@SuppressWarnings("unchecked")
protected void initBrowseItemChangeListener() {
CollectionDatasource browseDs = getTable().getDatasource();
Datasource editDs = getFieldGroup().getDatasource();
browseDs.addItemChangeListener(e -> {
if (e.getItem() != null) {
Entity reloadedItem = getDsContext().getDataSupplier().reload(
e.getDs().getItem(), editDs.getView(), null, e.getDs().getLoadDynamicAttributes());
editDs.setItem(reloadedItem);
}
});
}
/**
* Adds a CreateAction that removes selection in table, sets a newly created item to editDs
* and enables controls for record editing.
*/
protected void initBrowseCreateAction() {
ListComponent table = getTable();
table.addAction(new CreateAction(table) {
@SuppressWarnings("unchecked")
@Override
protected void internalOpenEditor(CollectionDatasource datasource, Entity newItem, Datasource parentDs, Map<String, Object> params) {
initNewItem(newItem);
table.setSelected(Collections.emptyList());
getFieldGroup().getDatasource().setItem(newItem);
refreshOptionsForLookupFields();
enableEditControls(true);
}
});
}
/**
* Hook to be implemented in subclasses. Called when the screen turns into editing mode
* for a new entity instance. Enables additional initialization of the new entity instance
* before setting it into the datasource.
* @param item new entity instance
*/
protected void initNewItem(Entity item) {
}
/**
* Adds an EditAction that enables controls for editing.
*/
protected void initBrowseEditAction() {
ListComponent table = getTable();
table.addAction(new EditAction(table) {
@Override
public void actionPerform(Component component) {
if (table.getSelected().size() == 1) {
if (lockIfNeeded((Entity) table.getSelected().iterator().next())) {
super.actionPerform(component);
}
}
}
@Override
protected void internalOpenEditor(CollectionDatasource datasource, Entity existingItem, Datasource parentDs, Map<String, Object> params) {
refreshOptionsForLookupFields();
enableEditControls(false);
}
@Override
public void refreshState() {
if (target != null) {
CollectionDatasource ds = target.getDatasource();
if (ds != null && !captionInitialized) {
setCaption(messages.getMainMessage("actions.Edit"));
}
}
super.refreshState();
}
@Override
protected boolean isPermitted() {
CollectionDatasource ownerDatasource = target.getDatasource();
boolean entityOpPermitted = security.isEntityOpPermitted(ownerDatasource.getMetaClass(), EntityOp.UPDATE);
if (!entityOpPermitted) {
return false;
}
return super.isPermitted();
}
});
}
/**
* Pessimistic lock before start of editing, if it is configured for the entity.
*/
protected boolean lockIfNeeded(Entity entity) {
MetaClass metaClass = getMetaClassForLocking(entity);
LockInfo lockInfo = AppBeans.get(LockService.class).lock(metaClass.getName(), entity.getId().toString());
if (lockInfo == null) {
justLocked = true;
} else if (!(lockInfo instanceof LockNotSupported)) {
showNotification(
messages.getMainMessage("entityLocked.msg"),
String.format(messages.getMainMessage("entityLocked.desc"),
lockInfo.getUser().getLogin(),
AppBeans.get(DatatypeFormatter.class).formatDateTime(lockInfo.getSince())
),
Frame.NotificationType.HUMANIZED
);
return false;
}
return true;
}
/**
* Release pessimistic lock if it was applied.
*/
protected void releaseLock() {
if (justLocked) {
Datasource ds = getFieldGroup().getDatasource();
Entity entity = ds.getItem();
if (entity != null) {
MetaClass metaClass = getMetaClassForLocking(entity);
AppBeans.get(LockService.class).unlock(metaClass.getName(), entity.getId().toString());
}
}
}
protected MetaClass getMetaClassForLocking(Entity item) {
// lock original metaClass, if any, because by convention all the configuration is based on original entities
MetaClass metaClass = AppBeans.get(ExtendedEntities.class).getOriginalMetaClass(item.getMetaClass());
if (metaClass == null) {
metaClass = getTable().getDatasource().getMetaClass();
}
return metaClass;
}
/**
* Adds AfterRemoveHandler for table's Remove action to reset the record contained in editDs.
*/
@SuppressWarnings("unchecked")
protected void initBrowseRemoveAction() {
ListComponent table = getTable();
Datasource editDs = getFieldGroup().getDatasource();
RemoveAction removeAction = (RemoveAction) table.getAction(RemoveAction.ACTION_ID);
if (removeAction != null)
removeAction.setAfterRemoveHandler(removedItems -> editDs.setItem(null));
}
/**
* Adds ESCAPE shortcut that invokes cancel() method.
*/
protected void initShortcuts() {
ComponentContainer editBox = getEditBox();
if (editBox instanceof ShortcutNotifier) {
((ShortcutNotifier) editBox).addShortcutAction(
new ShortcutAction(new KeyCombination(KeyCombination.Key.ESCAPE),
shortcutTriggeredEvent -> cancel()));
}
}
protected void refreshOptionsForLookupFields() {
for (Component component : getFieldGroup().getOwnComponents()) {
if (component instanceof LookupField) {
CollectionDatasource optionsDatasource = ((LookupField) component).getOptionsDatasource();
if (optionsDatasource != null) {
optionsDatasource.refresh();
}
}
}
}
/**
* Enables controls for editing.
* @param creating indicates that a new instance is being created
*/
protected void enableEditControls(boolean creating) {
this.editing = true;
this.creating = creating;
initEditComponents(true);
getFieldGroup().requestFocus();
}
/**
* Disables edit controls.
*/
protected void disableEditControls() {
this.editing = false;
initEditComponents(false);
((Focusable) getTable()).focus();
}
/**
* Initializes edit controls, depending on if they should be enabled or disabled.
* @param enabled if true - enables edit controls and disables controls on the left side of the splitter
* if false - vice versa
*/
protected void initEditComponents(boolean enabled) {
TabSheet tabSheet = getTabSheet();
if (tabSheet != null) {
ComponentsHelper.walkComponents(tabSheet, (component, name) -> {
if (component instanceof FieldGroup) {
((FieldGroup) component).setEditable(enabled);
} else if (component instanceof Table) {
((Table) component).getActions().forEach(action -> action.setEnabled(enabled));
} else if (!(component instanceof ComponentContainer)) {
component.setEnabled(enabled);
}
});
}
getFieldGroup().setEditable(enabled);
getActionsPane().setVisible(enabled);
getLookupBox().setEnabled(!enabled);
}
/**
* Method that is invoked by clicking Ok button after editing an existing or creating a new record.
*/
@SuppressWarnings("unchecked")
public void save() {
if (!editing)
return;
FieldGroup fieldGroup = getFieldGroup();
List<Validatable> components = new ArrayList<>();
for (Component component: fieldGroup.getComponents()) {
if (component instanceof Validatable) {
components.add((Validatable)component);
}
}
if (!validate(components)) {
return;
}
getDsContext().commit();
ListComponent table = getTable();
CollectionDatasource browseDs = table.getDatasource();
Entity editedItem = fieldGroup.getDatasource().getItem();
if (creating) {
browseDs.includeItem(editedItem);
} else {
browseDs.updateItem(editedItem);
}
table.setSelected(editedItem);
releaseLock();
disableEditControls();
}
/**
* Method that is invoked by clicking Cancel button, discards changes and disables controls for editing.
*/
@SuppressWarnings("unchecked")
public void cancel() {
CollectionDatasource browseDs = getTable().getDatasource();
Datasource editDs = getFieldGroup().getDatasource();
Entity selectedItem = browseDs.getItem();
if (selectedItem != null) {
Entity reloadedItem = getDsContext().getDataSupplier().reload(
selectedItem, editDs.getView(), null, editDs.getLoadDynamicAttributes());
browseDs.setItem(reloadedItem);
} else {
editDs.setItem(null);
}
releaseLock();
disableEditControls();
}
}
| Add an ability to check required fields in more than one FieldGroup in the entity combined screen #1249
| modules/gui/src/com/haulmont/cuba/gui/components/EntityCombinedScreen.java | Add an ability to check required fields in more than one FieldGroup in the entity combined screen #1249 | <ide><path>odules/gui/src/com/haulmont/cuba/gui/components/EntityCombinedScreen.java
<ide> }
<ide>
<ide> /**
<del> * Method that is invoked by clicking Ok button after editing an existing or creating a new record.
<del> */
<del> @SuppressWarnings("unchecked")
<del> public void save() {
<del> if (!editing)
<del> return;
<del>
<add> * Validates editor fields.
<add> *
<add> * @return true if all fields are valid or false otherwise
<add> */
<add> protected boolean validateEditor() {
<ide> FieldGroup fieldGroup = getFieldGroup();
<ide> List<Validatable> components = new ArrayList<>();
<ide> for (Component component: fieldGroup.getComponents()) {
<ide> components.add((Validatable)component);
<ide> }
<ide> }
<del> if (!validate(components)) {
<add> return validate(components);
<add> }
<add>
<add> /**
<add> * Method that is invoked by clicking Ok button after editing an existing or creating a new record.
<add> */
<add> @SuppressWarnings("unchecked")
<add> public void save() {
<add> if (!editing)
<add> return;
<add>
<add> if (!validateEditor()) {
<ide> return;
<ide> }
<ide> getDsContext().commit();
<ide>
<ide> ListComponent table = getTable();
<ide> CollectionDatasource browseDs = table.getDatasource();
<del> Entity editedItem = fieldGroup.getDatasource().getItem();
<add> Entity editedItem = getFieldGroup().getDatasource().getItem();
<ide> if (creating) {
<ide> browseDs.includeItem(editedItem);
<ide> } else { |
|
Java | apache-2.0 | e733d2372df0d7de0124337dac80f415f171faa4 | 0 | ef-labs/vertigo,englishtown/vertigo,ef-labs/vertigo,englishtown/vertigo,kuujo/vertigo,kuujo/vertigo,kuujo/vertigo | /*
* Copyright 2013 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 net.kuujo.vertigo.auditor;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.platform.Container;
import net.kuujo.vertigo.message.MessageId;
/**
* A basic auditor implementation.
*
* This auditor tracks message trees by utilizing unique numbers assigned to
* each message ID. Each time a message is created in the tree, its unique number
* is added to the tree count. Each time a message is acked in the tree, its
* number is subtracted from the tree count. Once the tree count returns to zero,
* the tree is considered fully processed and the message source is notified.
*
* This auditor protects against race conditions by allowing creations, acks,
* and failures to arrive in *any* order. When a creation, ack, or failure arrives
* for a not-previously-known message tree, the tree will be automatically created.
* Because of the mathematics involved, the tree will not be considered fully
* processed until all create/ack/fail messages have been received.
*
* @author Jordan Halterman
*/
public class BasicAuditor implements Auditor {
private Vertx vertx;
private AuditorVerticle acker;
private long timeout = 30000;
private long cleanupInterval = 100;
private long timeoutTimer;
private final Map<String, Root> roots = new LinkedHashMap<String, Root>();
@Override
public void setVertx(Vertx vertx) {
this.vertx = vertx;
}
@Override
public void setContainer(Container container) {
}
@Override
public void setAcker(AuditorVerticle auditorVerticle) {
this.acker = auditorVerticle;
}
@Override
public void setTimeout(long timeout) {
this.timeout = timeout;
}
@Override
public void start() {
// Only start the timeouts timer if timeouts are enabled (greater than 0).
if (timeout > 0) startTimer();
}
/**
* Starts a periodic timer that checks for timed out messages.
*/
private void startTimer() {
timeoutTimer = vertx.setPeriodic(cleanupInterval, new Handler<Long>() {
@Override
public void handle(Long timerId) {
checkTimeout();
}
});
}
/**
* Checks messages for timeouts.
*/
private void checkTimeout() {
// If timeout == 0 then timeouts are disabled for the network. Skip the check.
if (timeout == 0) return;
// Iterate over nodes and fail any nodes whose expiration time has passed.
// Nodes are stored in a LinkedHashMap in the order in which they're created,
// so we can iterate up to the oldest node which has not yet timed out and stop.
long currentTime = System.currentTimeMillis();
Iterator<Map.Entry<String, Root>> iterator = roots.entrySet().iterator();
while (iterator.hasNext()) {
Root root = iterator.next().getValue();
if (root.timeout <= currentTime) {
iterator.remove();
acker.timeout(root.id);
}
else {
break;
}
}
}
@Override
public void create(MessageId messageId) {
Root root = getRoot(messageId.correlationId());
root.id = messageId;
}
@Override
public void fork(MessageId messageId) {
String rootId = messageId.root();
if (rootId != null) {
Root root = getRoot(rootId);
root.fork(messageId.ackCode());
// The root may have already been created and the child ID acked. To guard
// against race conditions, we account for this and assume the tree could
// have been completely processed with the addition of this ID.
if (root.complete()) {
finish(roots.remove(rootId));
}
}
}
@Override
public void ack(MessageId messageId) {
String rootId = messageId.root();
if (rootId == null) {
rootId = messageId.correlationId();
}
Root root = getRoot(rootId);
root.ack(messageId.ackCode());
if (root.complete()) {
finish(roots.remove(rootId));
}
}
@Override
public void fail(MessageId messageId) {
String rootId = messageId.root();
if (rootId == null) {
rootId = messageId.correlationId();
}
Root root = getRoot(rootId);
root.fail(messageId.ackCode());
if (root.complete()) {
finish(roots.remove(rootId));
}
}
/**
* Finishes acking of a tree.
*/
private void finish(Root root) {
if (root.failed) {
acker.fail(root.id);
}
else {
acker.complete(root.id);
}
}
/**
* Gets a root. If the root does not yet exist then it will be created. This
* protected against race conditions by allowing roots to be created even
* before the "create" message is received by the auditor, resulting in creation
* simply having the effect of appending forks to the root.
*/
private Root getRoot(String rootId) {
if (roots.containsKey(rootId)) {
return roots.get(rootId);
}
else {
Root root = new Root(null, System.currentTimeMillis() + timeout);
roots.put(rootId, root);
return root;
}
}
/**
* A tree root.
*/
private static final class Root {
private MessageId id;
private final long timeout;
private long count;
private boolean failed;
private Root(MessageId id, long timeout) {
this.id = id;
this.timeout = timeout;
}
/**
* Adds a new message code to the tree.
*/
private void fork(long code) {
count += code;
}
/**
* Acks a message code in the tree.
*/
private void ack(long code) {
count -= code;
}
/**
* Fails a message code in the tree.
*/
private void fail(long code) {
count -= code;
failed = true;
}
/**
* Indicates whether the tree has been completely processed.
*/
private boolean complete() {
return id != null && count == 0;
}
}
@Override
public void stop() {
vertx.cancelTimer(timeoutTimer);
}
}
| src/main/java/net/kuujo/vertigo/auditor/BasicAuditor.java | /*
* Copyright 2013 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 net.kuujo.vertigo.auditor;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.platform.Container;
import net.kuujo.vertigo.message.MessageId;
/**
* A basic auditor implementation.
*
* This auditor tracks message trees by utilizing unique numbers assigned to
* each message ID. Each time a message is created in the tree, its unique number
* is added to the tree count. Each time a message is acked in the tree, its
* number is subtracted from the tree count. Once the tree count returns to zero,
* the tree is considered fully processed and the message source is notified.
*
* This auditor protects against race conditions by allowing creations, acks,
* and failures to arrive in *any* order. When a creation, ack, or failure arrives
* for a not-previously-known message tree, the tree will be automatically created.
* Because of the mathematics involved, the tree will not be considered fully
* processed until all create/ack/fail messages have been received.
*
* @author Jordan Halterman
*/
public class BasicAuditor implements Auditor {
private Vertx vertx;
private AuditorVerticle acker;
private long timeout = 30000;
private long cleanupInterval = 500;
private long timeoutTimer;
private final Map<String, Root> roots = new LinkedHashMap<String, Root>();
@Override
public void setVertx(Vertx vertx) {
this.vertx = vertx;
}
@Override
public void setContainer(Container container) {
}
@Override
public void setAcker(AuditorVerticle auditorVerticle) {
this.acker = auditorVerticle;
}
@Override
public void setTimeout(long timeout) {
this.timeout = timeout;
}
@Override
public void start() {
startTimer();
}
/**
* Starts a periodic timer that checks for timed out messages.
*/
private void startTimer() {
timeoutTimer = vertx.setPeriodic(cleanupInterval, new Handler<Long>() {
@Override
public void handle(Long timerId) {
checkTimeout();
}
});
}
/**
* Checks messages for timeouts.
*/
private void checkTimeout() {
// Iterate over nodes and fail any nodes whose expiration time has passed.
// Nodes are stored in a LinkedHashMap in the order in which they're created,
// so we can iterate up to the oldest node which has not yet timed out and stop.
long currentTime = System.currentTimeMillis();
Iterator<Map.Entry<String, Root>> iterator = roots.entrySet().iterator();
while (iterator.hasNext()) {
Root root = iterator.next().getValue();
if (root.timeout <= currentTime) {
iterator.remove();
acker.timeout(root.id);
}
else {
break;
}
}
}
@Override
public void create(MessageId messageId) {
Root root = getRoot(messageId.correlationId());
root.id = messageId;
}
@Override
public void fork(MessageId messageId) {
String rootId = messageId.root();
if (rootId != null) {
Root root = getRoot(rootId);
root.fork(messageId.ackCode());
// The root may have already been created and the child ID acked. To guard
// against race conditions, we account for this and assume the tree could
// have been completely processed with the addition of this ID.
if (root.complete()) {
finish(roots.remove(rootId));
}
}
}
@Override
public void ack(MessageId messageId) {
String rootId = messageId.root();
if (rootId == null) {
rootId = messageId.correlationId();
}
Root root = getRoot(rootId);
root.ack(messageId.ackCode());
if (root.complete()) {
finish(roots.remove(rootId));
}
}
@Override
public void fail(MessageId messageId) {
String rootId = messageId.root();
if (rootId == null) {
rootId = messageId.correlationId();
}
Root root = getRoot(rootId);
root.fail(messageId.ackCode());
if (root.complete()) {
finish(roots.remove(rootId));
}
}
/**
* Finishes acking of a tree.
*/
private void finish(Root root) {
if (root.failed) {
acker.fail(root.id);
}
else {
acker.complete(root.id);
}
}
/**
* Gets a root. If the root does not yet exist then it will be created. This
* protected against race conditions by allowing roots to be created even
* before the "create" message is received by the auditor, resulting in creation
* simply having the effect of appending forks to the root.
*/
private Root getRoot(String rootId) {
if (roots.containsKey(rootId)) {
return roots.get(rootId);
}
else {
Root root = new Root(null, System.currentTimeMillis() + timeout);
roots.put(rootId, root);
return root;
}
}
/**
* A tree root.
*/
private static final class Root {
private MessageId id;
private final long timeout;
private long count;
private boolean failed;
private Root(MessageId id, long timeout) {
this.id = id;
this.timeout = timeout;
}
/**
* Adds a new message code to the tree.
*/
private void fork(long code) {
count += code;
}
/**
* Acks a message code in the tree.
*/
private void ack(long code) {
count -= code;
}
/**
* Fails a message code in the tree.
*/
private void fail(long code) {
count -= code;
failed = true;
}
/**
* Indicates whether the tree has been completely processed.
*/
private boolean complete() {
return id != null && count == 0;
}
}
@Override
public void stop() {
vertx.cancelTimer(timeoutTimer);
}
}
| Support disabling timeouts in network auditors.
| src/main/java/net/kuujo/vertigo/auditor/BasicAuditor.java | Support disabling timeouts in network auditors. | <ide><path>rc/main/java/net/kuujo/vertigo/auditor/BasicAuditor.java
<ide> private Vertx vertx;
<ide> private AuditorVerticle acker;
<ide> private long timeout = 30000;
<del> private long cleanupInterval = 500;
<add> private long cleanupInterval = 100;
<ide> private long timeoutTimer;
<ide> private final Map<String, Root> roots = new LinkedHashMap<String, Root>();
<ide>
<ide>
<ide> @Override
<ide> public void start() {
<del> startTimer();
<add> // Only start the timeouts timer if timeouts are enabled (greater than 0).
<add> if (timeout > 0) startTimer();
<ide> }
<ide>
<ide> /**
<ide> * Checks messages for timeouts.
<ide> */
<ide> private void checkTimeout() {
<add> // If timeout == 0 then timeouts are disabled for the network. Skip the check.
<add> if (timeout == 0) return;
<add>
<ide> // Iterate over nodes and fail any nodes whose expiration time has passed.
<ide> // Nodes are stored in a LinkedHashMap in the order in which they're created,
<ide> // so we can iterate up to the oldest node which has not yet timed out and stop. |
|
Java | mit | a45deb9ca1d4cb011ecd037d5d57dfd99cdd7a14 | 0 | cs2103aug2014-w13-2j/main,cs2103aug2014-w13-2j/main | package edu.dynamic.dynamiz.UI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Formatter;
import java.awt.color.*;
import edu.dynamic.dynamiz.structure.Date;
import edu.dynamic.dynamiz.structure.EventItem;
import edu.dynamic.dynamiz.structure.Feedback;
import edu.dynamic.dynamiz.structure.TaskItem;
import edu.dynamic.dynamiz.structure.ToDoItem;
/**
* @author Hu Wenyan
* Implement Display functions for tasks, events and todoItems
*/
public class Display implements DisplayerInterface {
private static final String WELCOME_MESSAGE= "Welcome to Dynamiz!";
public String dateFormatter(Calendar c){
String s = String.format("%1$tm,%1$te",c);
return s;
}
public String dateFormatter(Date d){
String s = String.format("%tm,%td,%ty", d);
return s;
}
public String timeFormatter(Date d){
String s = String.format("%tH:%tM", d);
return s;
}
public String displayWelcomeMessage(){
return WELCOME_MESSAGE;
}
public String displayTitleLine() {
String s=String.format("%-20s%15s %12s %8s %8s ", "Task","Status","Priority","Start Time","End Time");
return s;
}
@Override
public String displayDividingLine() {
return "--------------------------------------------------------------------------------------------------------";
}
@Override
public String displaytString(String str) {
return str;
}
@Override
public String displayStringList(ArrayList<String> arr) {
if(arr == null) return "null";
StringBuilder s = new StringBuilder();
for(int i=0;i<arr.size();i++){
if(!arr.get(i).isEmpty())
s.append(arr.get(i).trim()).append("\n");
}
return s.toString();
}
@Override
public String displayTaskItem(TaskItem task) {
if(task == null) return "null task";
else return task.toString();
}
@Override
public String displayTaskFile(TaskItem task) {
if(task == null) return "null task";
else return task.toFileString();
}
@Override
public String displayTaskFeedBack(TaskItem task) {
if(task == null) return "null task";
else return task.getFeedbackString();
}
@Override
public String displayTaskList(ArrayList<TaskItem> taskList) {
if(taskList == null ) return "null";
StringBuilder s = new StringBuilder();
for(int i = 0; i< taskList.size(); i++){
s.append(taskList.get(i).toString()).append("\n");
}
return s.toString();
}
@Override
public String displayTaskList(TaskItem[] taskList) {
if(taskList == null ) return "null";
StringBuilder s = new StringBuilder();
for(int i = 0; i< taskList.length; i++){
s.append(taskList[i].toString()).append("\n");
}
return s.toString();
}
@Override
public String displayEventFeedBack(EventItem event) {
if(event == null) return "null event";
else return event.getFeedbackString();
}
@Override
public String displayEventFile(EventItem event) {
if(event == null) return "null event";
else return event.toFileString();
}
@Override
public String displayEventItem(EventItem event) {
if(event == null) return "null event";
else return event.toString();
}
@Override
public String displayEventList(ArrayList<EventItem> eventList) {
if(eventList == null ) return "null";
StringBuilder s = new StringBuilder();
for(int i = 0; i< eventList.size(); i++){
s.append(eventList.get(i).toString()).append("\n");
}
return s.toString();
}
@Override
public String displayEventList(EventItem[] eventList) {
if(eventList == null ) return "null";
StringBuilder s = new StringBuilder();
for(int i = 0; i< eventList.length; i++){
s.append(eventList[i].toString()).append("\n");
}
return s.toString();
}
@Override
public String displayToDoItem(ToDoItem todoItem) {
if(todoItem == null) return "null todo Item";
else return todoItem.toString();
}
@Override
public String displayToDoFeedBack(ToDoItem todoItem) {
if(todoItem == null) return "null todo Item";
else return todoItem.getFeedbackString();
}
@Override
public String displayToDoFile(ToDoItem todoItem) {
if(todoItem == null) return "null todo Item";
else return todoItem.toFileString();
}
@Override
public String displayToDoList(ArrayList<ToDoItem> todoList) {
if(todoList == null ) return "null";
StringBuilder s = new StringBuilder();
for(int i = 0; i< todoList.size(); i++){
s.append(todoList.get(i).toString()).append("\n");
}
return s.toString();
}
@Override
public String displayToDoList(ToDoItem[] todoList) {
if(todoList == null ) return "null";
StringBuilder s = new StringBuilder();
for(int i = 0; i< todoList.length; i++){
s.append(todoList[i].toString()).append("\n");
}
return s.toString();
}
@Override
public String displayPrompt() {
return "Please Enter Command:";
}
@Override
public String displayPrompt(PromptTag prompt) {
String tag = new String();
switch(prompt){
case EnterCommand:
tag = "Please Enter Command:";
case EnterTodoItem:
tag = "Please Enter Task:";
case EnterTaskIndex:
tag = "Please Enter Task Index:";
case InvalidCommand:
tag = "Please Enter Valid Command:";
}
tag+="\n";
return tag;
}
public String displayPrompt(String promptMessage) {
return promptMessage;
}
public String displayFeedBack(Feedback commandFeedBack) {
String s = new String();
// commandFeedBack.getClass();
return s;
}
@Override
public String displayHelpPage() {
// TODO Auto-generated method stub
return null;
}
}
| src/edu/dynamic/dynamiz/UI/Display.java | package edu.dynamic.dynamiz.UI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Formatter;
import java.awt.color.*;
import edu.dynamic.dynamiz.structure.Date;
import edu.dynamic.dynamiz.structure.EventItem;
import edu.dynamic.dynamiz.structure.Feedback;
import edu.dynamic.dynamiz.structure.TaskItem;
import edu.dynamic.dynamiz.structure.ToDoItem;
/**
* @author Hu Wenyan
* Implement Display functions for tasks, events and todoItems
*/
public class Display implements DisplayerInterface {
private static final String WELCOME_MESSAGE= "Welcome to Dynamiz!";
public String dateFormatter(Calendar c){
String s = String.format("%1$tm,%1$te",c);
return s;
}
public String dateFormatter(Date d){
String s = String.format("%tm,%td,%ty", d);
return s;
}
public String timeFormatter(Date d){
String s = String.format("%tH:%tM", d);
return s;
}
public String displayWelcomeMessage(){
return WELCOME_MESSAGE;
}
public String displayTitleLine() {
String s=String.format("%-20s%15s %12s %8s %8s ", "Task","Status","Priority","Start Time","End Time");
return s;
}
@Override
public String displayDividingLine() {
return "--------------------------------------------------------------------------------------------------------";
}
@Override
public String displaytString(String str) {
return str;
}
@Override
public String displayStringList(ArrayList<String> arr) {
if(arr == null) return "null";
StringBuilder s = new StringBuilder();
for(int i=0;i<arr.size();i++){
if(!arr.get(i).isEmpty())
s.append(arr.get(i).trim()).append("\n");
}
return s.toString();
}
@Override
public String displayTaskItem(TaskItem task) {
if(task == null) return "null task";
else return task.toString();
}
@Override
public String displayTaskFile(TaskItem task) {
if(task == null) return "null task";
else return task.toFileString();
}
@Override
public String displayTaskFeedBack(TaskItem task) {
if(task == null) return "null task";
else return task.getFeedbackString();
}
@Override
public String displayTaskList(ArrayList<TaskItem> taskList) {
if(taskList == null ) return "null";
StringBuilder s = new StringBuilder();
for(int i = 0; i< taskList.size(); i++){
s.append(taskList.get(i).toString()).append("\n");
}
return s.toString();
}
@Override
public String displayTaskList(TaskItem[] taskList) {
if(taskList == null ) return "null";
StringBuilder s = new StringBuilder();
for(int i = 0; i< taskList.length; i++){
s.append(taskList[i].toString()).append("\n");
}
return s.toString();
}
@Override
public String displayEventFeedBack(EventItem event) {
if(event == null) return "null event";
else return event.getFeedbackString();
}
@Override
public String displayEventFile(EventItem event) {
if(event == null) return "null event";
else return event.toFileString();
}
@Override
public String displayEventItem(EventItem event) {
if(event == null) return "null event";
else return event.toString();
}
@Override
public String displayEventList(ArrayList<EventItem> eventList) {
if(eventList == null ) return "null";
StringBuilder s = new StringBuilder();
for(int i = 0; i< eventList.size(); i++){
s.append(eventList.get(i).toString()).append("\n");
}
return s.toString();
}
@Override
public String displayEventList(EventItem[] eventList) {
if(eventList == null ) return "null";
StringBuilder s = new StringBuilder();
for(int i = 0; i< eventList.length; i++){
s.append(eventList[i].toString()).append("\n");
}
return s.toString();
}
@Override
public String displayToDoItem(ToDoItem todoItem) {
if(todoItem == null) return "null todo Item";
else return todoItem.toString();
}
@Override
public String displayToDoFeedBack(ToDoItem todoItem) {
if(todoItem == null) return "null todo Item";
else return todoItem.getFeedbackString();
}
@Override
public String displayToDoFile(ToDoItem todoItem) {
if(todoItem == null) return "null todo Item";
else return todoItem.toFileString();
}
@Override
public String displayToDoList(ArrayList<ToDoItem> todoList) {
if(todoList == null ) return "null";
StringBuilder s = new StringBuilder();
for(int i = 0; i< todoList.size(); i++){
s.append(todoList.get(i).toString()).append("\n");
}
return s.toString();
}
@Override
public String displayToDoList(ToDoItem[] todoList) {
if(todoList == null ) return "null";
StringBuilder s = new StringBuilder();
for(int i = 0; i< todoList.length; i++){
s.append(todoList[i].toString()).append("\n");
}
return s.toString();
}
@Override
public String displayPrompt() {
return "Please Enter Command:";
}
@Override
public String displayPrompt(PromptTag prompt) {
String tag = new String();
switch(prompt){
case EnterCommand:
tag = "Please Enter Command:";
case EnterTodoItem:
tag = "Please Enter Task:";
case EnterTaskIndex:
tag = "Please Enter Task Index:";
case InvalidCommand:
tag = "Please Enter Valid Command:";
}
tag+="\n";
return tag;
}
@Override
public String displayPrompt(String promptMessage) {
return promptMessage;
}
@Override
public String displayFeedBack(Feedback commandFeedBack) {
String s = new String();
return s;
}
@Override
public String displayHelpPage() {
// TODO Auto-generated method stub
return null;
}
}
| FeedBack display
| src/edu/dynamic/dynamiz/UI/Display.java | FeedBack display | <ide><path>rc/edu/dynamic/dynamiz/UI/Display.java
<ide> return tag;
<ide> }
<ide>
<del> @Override
<ide> public String displayPrompt(String promptMessage) {
<ide> return promptMessage;
<ide> }
<ide>
<ide>
<del> @Override
<ide> public String displayFeedBack(Feedback commandFeedBack) {
<del> String s = new String();
<add> String s = new String();
<add> // commandFeedBack.getClass();
<ide>
<ide> return s;
<ide> } |
|
Java | mit | ca98c67e1c8cca53ec33bb80a04bc206abdaddc0 | 0 | nilsschmidt1337/ldparteditor,nilsschmidt1337/ldparteditor | /* MIT - License
Copyright (c) 2012 - this year, Nils Schmidt
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
package org.nschmidt.ldparteditor.data;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.nschmidt.ldparteditor.enumtype.LDConfig;
import org.nschmidt.ldparteditor.enumtype.View;
import org.nschmidt.ldparteditor.helper.composite3d.YTruderSettings;
import org.nschmidt.ldparteditor.logger.NLogger;
import org.nschmidt.ldparteditor.text.DatParser;
class VM27YTruder extends VM26LineIntersector {
private static final double EPSILON = 0.000001;
private static final double SMALL = 0.01;
private double[] nullv = new double[] { 0.0, 0.0, 0.0 };
private static final int X_AXIS = 0;
private static final int Y_AXIS = 1;
private static final int Z_AXIS = 2;
protected VM27YTruder(DatFile linkedDatFile) {
super(linkedDatFile);
}
@SuppressWarnings("java:S2111")
public void yTruder(YTruderSettings ys) {
if (linkedDatFile.isReadOnly())
return;
final double distance = ys.getDistance();
int mode = ys.getMode();
if (distance == 0 && (mode == YTruderSettings.MODE_TRANSLATE_BY_DISTANCE || mode == YTruderSettings.MODE_EXTRUDE_RADIALLY))
return;
final Set<GData2> originalSelection = new HashSet<>();
originalSelection.addAll(selectedLines);
if (originalSelection.isEmpty())
return;
final Set<GData2> newLines = new HashSet<>();
final Set<GData3> newTriangles = new HashSet<>();
final Set<GData4> newQuads = new HashSet<>();
final Set<GData5> newCondlines = new HashSet<>();
final GColour col16 = LDConfig.getColour16();
final GColour lineColour = DatParser.validateColour(24, .5f, .5f, .5f, 1f).createClone();
final GColour bodyColour = DatParser.validateColour(16, col16.getR(), col16.getG(), col16.getB(), 1f).createClone();
final int maxLine = originalSelection.size() * 3;
final int maxTri = originalSelection.size() * 3;
double[][][] inLine = new double[maxLine][2][3];
int[] lineUsed = new int[maxLine];
double[][][] surf = new double[maxTri][4][3];
double[][][] condLine = new double[maxTri][4][3];
int[] condFlag = new int[maxTri];
int numSurf;
int numCond;
int x = 0;
int y = 1;
int z = 2;
double angleLineThr = ys.getCondlineAngleThreshold();
int end;
int current;
int surfstart;
boolean flag = false;
if (ys.getAxis() == X_AXIS) {
x = 1;
y = 0;
z = 2;
} else if (ys.getAxis() == Y_AXIS) {
x = 0;
y = 1;
z = 2;
} else if (ys.getAxis() == Z_AXIS) {
x = 0;
y = 2;
z = 1;
}
int originalLineCount = 0;
for (GData2 gData2 : originalSelection) {
Vertex[] verts = lines.get(gData2);
if (verts != null) {
inLine[originalLineCount][0][x] = verts[0].xp.doubleValue();
inLine[originalLineCount][0][y] = verts[0].yp.doubleValue();
inLine[originalLineCount][0][z] = verts[0].zp.doubleValue();
inLine[originalLineCount][1][x] = verts[1].xp.doubleValue();
inLine[originalLineCount][1][y] = verts[1].yp.doubleValue();
inLine[originalLineCount][1][z] = verts[1].zp.doubleValue();
lineUsed[originalLineCount] = 0;
originalLineCount++;
}
}
// Extruding...
numSurf = 0;
numCond = 0;
condFlag[numCond] = 0;
for (int i = 0; i < originalLineCount; i++) {
double[] p0 = new double[3];
double[] p1 = new double[3];
double d0;
double d1;
if (lineUsed[i] == 0) {
lineUsed[i] = 1;
current = i;
end = 0;
do {
flag = false;
for (int j = 0; j < originalLineCount; j++) {
if (lineUsed[j] == 0) {
for (int k = 0; k < 2; k++) {
if (manhattan(inLine[current][end], inLine[j][k]) < SMALL) {
current = j;
end = 1 - k;
lineUsed[current] = 1;
flag = true;
break;
}
}
}
if (flag)
break;
}
} while (flag);
end = 1 - end;
surfstart = numSurf;
set(surf[numSurf][0], inLine[current][1 - end]);
set(surf[numSurf][1], inLine[current][end]);
set(surf[numSurf][2], inLine[current][end]);
set(surf[numSurf][3], inLine[current][1 - end]);
switch (mode) {
case YTruderSettings.MODE_TRANSLATE_BY_DISTANCE:
surf[numSurf][2][1] = surf[numSurf][2][1] + distance;
surf[numSurf][3][1] = surf[numSurf][3][1] + distance;
break;
case YTruderSettings.MODE_SYMMETRY_ACROSS_PLANE:
surf[numSurf][2][1] = 2 * distance - surf[numSurf][2][1];
surf[numSurf][3][1] = 2 * distance - surf[numSurf][3][1];
break;
case YTruderSettings.MODE_PROJECTION_ON_PLANE:
surf[numSurf][2][1] = distance;
surf[numSurf][3][1] = distance;
break;
case YTruderSettings.MODE_EXTRUDE_RADIALLY:
p0[0] = 0;
p0[1] = surf[numSurf][0][1];
p0[2] = 0;
p1[0] = 0;
p1[1] = surf[numSurf][1][1];
p1[2] = 0;
d0 = dist(p0, surf[numSurf][0]);
d1 = dist(p1, surf[numSurf][1]);
if (d0 > EPSILON) {
surf[numSurf][3][0] = surf[numSurf][3][0] * (d0 + distance) / d0;
surf[numSurf][3][2] = surf[numSurf][3][2] * (d0 + distance) / d0;
}
if (d1 > EPSILON) {
surf[numSurf][2][0] = surf[numSurf][2][0] * (d1 + distance) / d1;
surf[numSurf][2][2] = surf[numSurf][2][2] * (d1 + distance) / d1;
}
double a;
a = triAngle(surf[numSurf][0], surf[numSurf][1], surf[numSurf][2], surf[numSurf][0], surf[numSurf][2], surf[numSurf][3]);
if (a > 0.5) {
set(condLine[numCond][0], surf[numSurf][0]);
set(condLine[numCond][1], surf[numSurf][2]);
set(condLine[numCond][2], surf[numSurf][1]);
set(condLine[numCond][3], surf[numSurf][3]);
condFlag[numCond] = 5;
numCond++;
}
break;
default:
break;
}
numSurf++;
lineUsed[current] = 2;
do {
flag = false;
for (int j = 0; j < originalLineCount; j++) {
if (lineUsed[j] < 2) {
for (int k = 0; k < 2; k++) {
if (manhattan(inLine[current][end], inLine[j][k]) < SMALL && lineUsed[j] < 2) {
current = j;
end = 1 - k;
flag = true;
set(surf[numSurf][0], inLine[current][1 - end]);
set(surf[numSurf][1], inLine[current][end]);
set(surf[numSurf][2], inLine[current][end]);
set(surf[numSurf][3], inLine[current][1 - end]);
switch (mode) {
case YTruderSettings.MODE_TRANSLATE_BY_DISTANCE:
surf[numSurf][2][1] = surf[numSurf][2][1] + distance;
surf[numSurf][3][1] = surf[numSurf][3][1] + distance;
break;
case YTruderSettings.MODE_SYMMETRY_ACROSS_PLANE:
surf[numSurf][2][1] = 2 * distance - surf[numSurf][2][1];
surf[numSurf][3][1] = 2 * distance - surf[numSurf][3][1];
break;
case YTruderSettings.MODE_PROJECTION_ON_PLANE:
surf[numSurf][2][1] = distance;
surf[numSurf][3][1] = distance;
break;
case YTruderSettings.MODE_EXTRUDE_RADIALLY:
p0[0] = 0;
p0[1] = surf[numSurf][0][1];
p0[2] = 0;
p1[0] = 0;
p1[1] = surf[numSurf][1][1];
p1[2] = 0;
d0 = dist(p0, surf[numSurf][0]);
d1 = dist(p1, surf[numSurf][1]);
if (d0 > EPSILON) {
surf[numSurf][3][0] = surf[numSurf][3][0] * (d0 + distance) / d0;
surf[numSurf][3][2] = surf[numSurf][3][2] * (d0 + distance) / d0;
}
if (d1 > EPSILON) {
surf[numSurf][2][0] = surf[numSurf][2][0] * (d1 + distance) / d1;
surf[numSurf][2][2] = surf[numSurf][2][2] * (d1 + distance) / d1;
}
set(condLine[numCond][0], surf[numSurf][0]);
set(condLine[numCond][1], surf[numSurf][2]);
set(condLine[numCond][2], surf[numSurf][1]);
set(condLine[numCond][3], surf[numSurf][3]);
condFlag[numCond] = 5;
numCond++;
break;
default:
break;
}
set(condLine[numCond][0], surf[numSurf][0]);
set(condLine[numCond][1], surf[numSurf][3]);
set(condLine[numCond][2], surf[numSurf][1]);
set(condLine[numCond][3], surf[numSurf - 1][0]);
condFlag[numCond] = 5;
numSurf++;
numCond++;
lineUsed[current] = 2;
}
if (flag)
break;
}
}
if (flag)
break;
}
} while (flag);
if (manhattan(surf[numSurf - 1][1], surf[surfstart][0]) < SMALL) {
set(condLine[numCond][0], surf[numSurf - 1][1]);
set(condLine[numCond][1], surf[numSurf - 1][2]);
set(condLine[numCond][2], surf[numSurf - 1][0]);
set(condLine[numCond][3], surf[surfstart][1]);
condFlag[numCond] = 5;
numCond++;
} else {
set(condLine[numCond][0], surf[numSurf - 1][1]);
set(condLine[numCond][1], surf[numSurf - 1][2]);
condFlag[numCond] = 2;
numCond++;
set(condLine[numCond][0], surf[surfstart][0]);
set(condLine[numCond][1], surf[surfstart][3]);
condFlag[numCond] = 2;
numCond++;
}
}
}
for (int k = 0; k < numSurf; k++) {
if (manhattan(surf[k][0], surf[k][3]) < SMALL && manhattan(surf[k][1], surf[k][2]) < SMALL)
continue;
if (manhattan(surf[k][0], surf[k][3]) < SMALL) {
Vertex v1 = new Vertex(new BigDecimal(surf[k][0][x]), new BigDecimal(surf[k][0][y]), new BigDecimal(surf[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(surf[k][1][x]), new BigDecimal(surf[k][1][y]), new BigDecimal(surf[k][1][z]));
Vertex v3 = new Vertex(new BigDecimal(surf[k][2][x]), new BigDecimal(surf[k][2][y]), new BigDecimal(surf[k][2][z]));
newTriangles.add(new GData3(
bodyColour.getColourNumber(), bodyColour.getR(), bodyColour.getG(), bodyColour.getB(), bodyColour.getA(),
v1, v2, v3, View.DUMMY_REFERENCE, linkedDatFile, true));
} else if (manhattan(surf[k][1], surf[k][2]) < SMALL) {
Vertex v1 = new Vertex(new BigDecimal(surf[k][0][x]), new BigDecimal(surf[k][0][y]), new BigDecimal(surf[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(surf[k][1][x]), new BigDecimal(surf[k][1][y]), new BigDecimal(surf[k][1][z]));
Vertex v3 = new Vertex(new BigDecimal(surf[k][3][x]), new BigDecimal(surf[k][3][y]), new BigDecimal(surf[k][3][z]));
newTriangles.add(new GData3(
bodyColour.getColourNumber(), bodyColour.getR(), bodyColour.getG(), bodyColour.getB(), bodyColour.getA(),
v1, v2, v3, View.DUMMY_REFERENCE, linkedDatFile, true));
} else if (mode == YTruderSettings.MODE_TRANSLATE_BY_DISTANCE
|| mode == YTruderSettings.MODE_SYMMETRY_ACROSS_PLANE
|| triAngle(surf[k][0], surf[k][1], surf[k][2], surf[k][0], surf[k][2], surf[k][3]) <= 0.5) {
Vertex v1 = new Vertex(new BigDecimal(surf[k][0][x]), new BigDecimal(surf[k][0][y]), new BigDecimal(surf[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(surf[k][1][x]), new BigDecimal(surf[k][1][y]), new BigDecimal(surf[k][1][z]));
Vertex v3 = new Vertex(new BigDecimal(surf[k][2][x]), new BigDecimal(surf[k][2][y]), new BigDecimal(surf[k][2][z]));
Vertex v4 = new Vertex(new BigDecimal(surf[k][3][x]), new BigDecimal(surf[k][3][y]), new BigDecimal(surf[k][3][z]));
newQuads.add(new GData4(
bodyColour.getColourNumber(), bodyColour.getR(), bodyColour.getG(), bodyColour.getB(), bodyColour.getA(),
v1, v2, v3, v4, View.DUMMY_REFERENCE, linkedDatFile));
} else {
{
Vertex v1 = new Vertex(new BigDecimal(surf[k][0][x]), new BigDecimal(surf[k][0][y]), new BigDecimal(surf[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(surf[k][1][x]), new BigDecimal(surf[k][1][y]), new BigDecimal(surf[k][1][z]));
Vertex v3 = new Vertex(new BigDecimal(surf[k][2][x]), new BigDecimal(surf[k][2][y]), new BigDecimal(surf[k][2][z]));
newTriangles.add(new GData3(
bodyColour.getColourNumber(), bodyColour.getR(), bodyColour.getG(), bodyColour.getB(), bodyColour.getA(),
v1, v2, v3, View.DUMMY_REFERENCE, linkedDatFile, true));
}
{
Vertex v1 = new Vertex(new BigDecimal(surf[k][0][x]), new BigDecimal(surf[k][0][y]), new BigDecimal(surf[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(surf[k][2][x]), new BigDecimal(surf[k][2][y]), new BigDecimal(surf[k][2][z]));
Vertex v3 = new Vertex(new BigDecimal(surf[k][3][x]), new BigDecimal(surf[k][3][y]), new BigDecimal(surf[k][3][z]));
newTriangles.add(new GData3(
bodyColour.getColourNumber(), bodyColour.getR(), bodyColour.getG(), bodyColour.getB(), bodyColour.getA(),
v1, v2, v3, View.DUMMY_REFERENCE, linkedDatFile, true));
}
}
}
for (int k = 0; k < numCond; k++) {
if (manhattan(condLine[k][0], condLine[k][1]) < SMALL)
continue;
if (condFlag[k] == 5) {
double a;
a = triAngle(condLine[k][0], condLine[k][1], condLine[k][2], condLine[k][0], condLine[k][3], condLine[k][1]);
if (a < angleLineThr) {
Vertex v1 = new Vertex(new BigDecimal(condLine[k][0][x]), new BigDecimal(condLine[k][0][y]), new BigDecimal(condLine[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(condLine[k][1][x]), new BigDecimal(condLine[k][1][y]), new BigDecimal(condLine[k][1][z]));
Vertex v3 = new Vertex(new BigDecimal(condLine[k][2][x]), new BigDecimal(condLine[k][2][y]), new BigDecimal(condLine[k][2][z]));
Vertex v4 = new Vertex(new BigDecimal(condLine[k][3][x]), new BigDecimal(condLine[k][3][y]), new BigDecimal(condLine[k][3][z]));
newCondlines.add(new GData5(
lineColour.getColourNumber(), lineColour.getR(), lineColour.getG(), lineColour.getB(), lineColour.getA(),
v1, v2, v3, v4, View.DUMMY_REFERENCE, linkedDatFile));
} else {
Vertex v1 = new Vertex(new BigDecimal(condLine[k][0][x]), new BigDecimal(condLine[k][0][y]), new BigDecimal(condLine[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(condLine[k][1][x]), new BigDecimal(condLine[k][1][y]), new BigDecimal(condLine[k][1][z]));
newLines.add(new GData2(
lineColour.getColourNumber(), lineColour.getR(), lineColour.getG(), lineColour.getB(), lineColour.getA(),
v1, v2, View.DUMMY_REFERENCE, linkedDatFile, true));
}
}
if (condFlag[k] == 2) {
Vertex v1 = new Vertex(new BigDecimal(condLine[k][0][x]), new BigDecimal(condLine[k][0][y]), new BigDecimal(condLine[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(condLine[k][1][x]), new BigDecimal(condLine[k][1][y]), new BigDecimal(condLine[k][1][z]));
newLines.add(new GData2(
lineColour.getColourNumber(), lineColour.getR(), lineColour.getG(), lineColour.getB(), lineColour.getA(),
v1, v2, View.DUMMY_REFERENCE, linkedDatFile, true));
}
}
NLogger.debug(getClass(), "Check for identical vertices and collinearity."); //$NON-NLS-1$
final Set<GData2> linesToDelete2 = new HashSet<>();
final Set<GData3> trisToDelete2 = new HashSet<>();
final Set<GData4> quadsToDelete2 = new HashSet<>();
final Set<GData5> condlinesToDelete2 = new HashSet<>();
{
for (GData2 g2 : newLines) {
Vertex[] verts = lines.get(g2);
SortedSet<Vertex> verts2 = new TreeSet<>();
verts2.addAll(Arrays.asList(verts));
if (verts2.size() < 2) {
linesToDelete2.add(g2);
}
}
for (GData3 g3 : newTriangles) {
Vertex[] verts = triangles.get(g3);
SortedSet<Vertex> verts2 = new TreeSet<>();
verts2.addAll(Arrays.asList(verts));
if (verts2.size() < 3 || g3.isCollinear()) {
trisToDelete2.add(g3);
}
}
for (GData4 g4 : newQuads) {
Vertex[] verts = quads.get(g4);
SortedSet<Vertex> verts2 = new TreeSet<>();
verts2.addAll(Arrays.asList(verts));
if (verts2.size() < 4 || g4.isCollinear()) {
quadsToDelete2.add(g4);
}
}
for (GData5 g5 : newCondlines) {
Vertex[] verts = condlines.get(g5);
SortedSet<Vertex> verts2 = new TreeSet<>();
verts2.addAll(Arrays.asList(verts));
if (verts2.size() < 4) {
condlinesToDelete2.add(g5);
}
}
}
// Append the new data
for (GData2 line : newLines) {
linkedDatFile.addToTailOrInsertAfterCursor(line);
}
for (GData3 tri : newTriangles) {
linkedDatFile.addToTailOrInsertAfterCursor(tri);
}
for (GData4 quad : newQuads) {
linkedDatFile.addToTailOrInsertAfterCursor(quad);
}
for (GData5 condline : newCondlines) {
linkedDatFile.addToTailOrInsertAfterCursor(condline);
}
NLogger.debug(getClass(), "Delete new, but invalid objects."); //$NON-NLS-1$
clearSelection2();
newLines.removeAll(linesToDelete2);
newTriangles.removeAll(trisToDelete2);
newQuads.removeAll(quadsToDelete2);
newCondlines.removeAll(condlinesToDelete2);
selectedLines.addAll(linesToDelete2);
selectedTriangles.addAll(trisToDelete2);
selectedQuads.addAll(quadsToDelete2);
selectedCondlines.addAll(condlinesToDelete2);
selectedData.addAll(selectedLines);
selectedData.addAll(selectedTriangles);
selectedData.addAll(selectedQuads);
selectedData.addAll(selectedCondlines);
delete(false, false);
// Round to 6 decimal places
selectedLines.addAll(newLines);
selectedTriangles.addAll(newTriangles);
selectedQuads.addAll(newQuads);
selectedCondlines.addAll(newCondlines);
selectedData.addAll(selectedLines);
selectedData.addAll(selectedTriangles);
selectedData.addAll(selectedQuads);
selectedData.addAll(selectedCondlines);
NLogger.debug(getClass(), "Round."); //$NON-NLS-1$
roundSelection(6, 10, true, false, true, true, true);
setModified(true, true);
validateState();
NLogger.debug(getClass(), "Done."); //$NON-NLS-1$
}
private void cross(double[] dest, double[] left, double[] right) {
dest[0] = left[1] * right[2] - left[2] * right[1];
dest[1] = left[2] * right[0] - left[0] * right[2];
dest[2] = left[0] * right[1] - left[1] * right[0];
}
private double dot(double[] v1, double[] v2) {
return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
}
private void sub(double[] dest, double[] left, double[] right) {
dest[0] = left[0] - right[0];
dest[1] = left[1] - right[1];
dest[2] = left[2] - right[2];
}
private void mult(double[] dest, double[] v, double factor) {
dest[0] = factor * v[0];
dest[1] = factor * v[1];
dest[2] = factor * v[2];
}
private void set(double[] dest, double[] src) {
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
}
private double manhattan(double[] v1, double[] v2) {
return Math.abs(v1[0] - v2[0]) + Math.abs(v1[1] - v2[1]) + Math.abs(v1[2] - v2[2]);
}
private double dist(double[] v1, double[] v2) {
return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]) + (v1[2] - v2[2]) * (v1[2] - v2[2]));
}
// Tri_Angle computes the cosine of the angle between the planes of two
// triangles.
// They are assumed to be non-degenerated
private double triAngle(double[] u0, double[] u1, double[] u2, double[] v0, double[] v1, double[] v2) {
double[] unorm = new double[3];
double[] vnorm = new double[3];
double[] temp = new double[3];
double[] u10 = new double[3];
double[] u20 = new double[3];
double[] v10 = new double[3];
double[] v20 = new double[3];
double len;
sub(u10, u1, u0);
sub(u20, u2, u0);
sub(v10, v1, v0);
sub(v20, v2, v0);
cross(temp, u10, u20);
len = dist(temp, nullv);
mult(unorm, temp, 1 / len);
cross(temp, v10, v20);
len = dist(temp, nullv);
mult(vnorm, temp, 1 / len);
return 180 / 3.14159 * Math.acos(dot(unorm, vnorm));
}
}
| src/org/nschmidt/ldparteditor/data/VM27YTruder.java | /* MIT - License
Copyright (c) 2012 - this year, Nils Schmidt
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
package org.nschmidt.ldparteditor.data;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.nschmidt.ldparteditor.enumtype.LDConfig;
import org.nschmidt.ldparteditor.enumtype.View;
import org.nschmidt.ldparteditor.helper.composite3d.YTruderSettings;
import org.nschmidt.ldparteditor.logger.NLogger;
import org.nschmidt.ldparteditor.text.DatParser;
class VM27YTruder extends VM26LineIntersector {
private static final double EPSILON = 0.000001;
private static final double SMALL = 0.01;
private double[] nullv = new double[] { 0.0, 0.0, 0.0 };
protected VM27YTruder(DatFile linkedDatFile) {
super(linkedDatFile);
}
@SuppressWarnings("java:S2111")
public void yTruder(YTruderSettings ys) {
if (linkedDatFile.isReadOnly())
return;
final double distance = ys.getDistance();
int mode = ys.getMode();
if (distance == 0 && (mode == YTruderSettings.MODE_TRANSLATE_BY_DISTANCE || mode == YTruderSettings.MODE_EXTRUDE_RADIALLY))
return;
final Set<GData2> originalSelection = new HashSet<>();
originalSelection.addAll(selectedLines);
if (originalSelection.isEmpty())
return;
final Set<GData2> newLines = new HashSet<>();
final Set<GData3> newTriangles = new HashSet<>();
final Set<GData4> newQuads = new HashSet<>();
final Set<GData5> newCondlines = new HashSet<>();
final GColour col16 = LDConfig.getColour16();
final GColour lineColour = DatParser.validateColour(24, .5f, .5f, .5f, 1f).createClone();
final GColour bodyColour = DatParser.validateColour(16, col16.getR(), col16.getG(), col16.getB(), 1f).createClone();
final int maxLine = originalSelection.size() * 3;
final int maxTri = originalSelection.size() * 3;
double[][][] inLine = new double[maxLine][2][3];
int[] lineUsed = new int[maxLine];
double[][][] surf = new double[maxTri][4][3];
double[][][] condLine = new double[maxTri][4][3];
int[] condFlag = new int[maxTri];
int numSurf;
int numCond;
int x = 0;
int y = 1;
int z = 2;
double angleLineThr = ys.getCondlineAngleThreshold();
int end;
int current;
int surfstart;
boolean flag = false;
if (ys.getAxis() == 0) {
x = 1;
y = 0;
z = 2;
} else if (ys.getAxis() == 1) {
x = 0;
y = 1;
z = 2;
} else if (ys.getAxis() == 2) {
x = 0;
y = 2;
z = 1;
}
int originalLineCount = 0;
for (GData2 gData2 : originalSelection) {
inLine[originalLineCount][0][x] = gData2.x1p.doubleValue();
inLine[originalLineCount][0][y] = gData2.y1p.doubleValue();
inLine[originalLineCount][0][z] = gData2.z1p.doubleValue();
inLine[originalLineCount][1][x] = gData2.x2p.doubleValue();
inLine[originalLineCount][1][y] = gData2.y2p.doubleValue();
inLine[originalLineCount][1][z] = gData2.z2p.doubleValue();
lineUsed[originalLineCount] = 0;
originalLineCount++;
}
// Extruding...
numSurf = 0;
numCond = 0;
condFlag[numCond] = 0;
for (int i = 0; i < originalLineCount; i++) {
double[] p0 = new double[3];
double[] p1 = new double[3];
double d0;
double d1;
if (lineUsed[i] == 0) {
lineUsed[i] = 1;
current = i;
end = 0;
do {
flag = false;
for (int j = 0; j < originalLineCount; j++) {
if (lineUsed[j] == 0) {
for (int k = 0; k < 2; k++) {
if (manhattan(inLine[current][end], inLine[j][k]) < SMALL) {
current = j;
end = 1 - k;
lineUsed[current] = 1;
flag = true;
break;
}
}
}
if (flag)
break;
}
} while (flag);
end = 1 - end;
surfstart = numSurf;
set(surf[numSurf][0], inLine[current][1 - end]);
set(surf[numSurf][1], inLine[current][end]);
set(surf[numSurf][2], inLine[current][end]);
set(surf[numSurf][3], inLine[current][1 - end]);
switch (mode) {
case YTruderSettings.MODE_TRANSLATE_BY_DISTANCE:
surf[numSurf][2][1] = surf[numSurf][2][1] + distance;
surf[numSurf][3][1] = surf[numSurf][3][1] + distance;
break;
case YTruderSettings.MODE_SYMMETRY_ACROSS_PLANE:
surf[numSurf][2][1] = 2 * distance - surf[numSurf][2][1];
surf[numSurf][3][1] = 2 * distance - surf[numSurf][3][1];
break;
case YTruderSettings.MODE_PROJECTION_ON_PLANE:
surf[numSurf][2][1] = distance;
surf[numSurf][3][1] = distance;
break;
case YTruderSettings.MODE_EXTRUDE_RADIALLY:
p0[0] = 0;
p0[1] = surf[numSurf][0][1];
p0[2] = 0;
p1[0] = 0;
p1[1] = surf[numSurf][1][1];
p1[2] = 0;
d0 = dist(p0, surf[numSurf][0]);
d1 = dist(p1, surf[numSurf][1]);
if (d0 > EPSILON) {
surf[numSurf][3][0] = surf[numSurf][3][0] * (d0 + distance) / d0;
surf[numSurf][3][2] = surf[numSurf][3][2] * (d0 + distance) / d0;
}
if (d1 > EPSILON) {
surf[numSurf][2][0] = surf[numSurf][2][0] * (d1 + distance) / d1;
surf[numSurf][2][2] = surf[numSurf][2][2] * (d1 + distance) / d1;
}
double a;
a = triAngle(surf[numSurf][0], surf[numSurf][1], surf[numSurf][2], surf[numSurf][0], surf[numSurf][2], surf[numSurf][3]);
if (a > 0.5) {
set(condLine[numCond][0], surf[numSurf][0]);
set(condLine[numCond][1], surf[numSurf][2]);
set(condLine[numCond][2], surf[numSurf][1]);
set(condLine[numCond][3], surf[numSurf][3]);
condFlag[numCond] = 5;
numCond++;
}
break;
default:
break;
}
numSurf++;
lineUsed[current] = 2;
do {
flag = false;
for (int j = 0; j < originalLineCount; j++) {
if (lineUsed[j] < 2) {
for (int k = 0; k < 2; k++) {
if (manhattan(inLine[current][end], inLine[j][k]) < SMALL && lineUsed[j] < 2) {
current = j;
end = 1 - k;
flag = true;
set(surf[numSurf][0], inLine[current][1 - end]);
set(surf[numSurf][1], inLine[current][end]);
set(surf[numSurf][2], inLine[current][end]);
set(surf[numSurf][3], inLine[current][1 - end]);
switch (mode) {
case YTruderSettings.MODE_TRANSLATE_BY_DISTANCE:
surf[numSurf][2][1] = surf[numSurf][2][1] + distance;
surf[numSurf][3][1] = surf[numSurf][3][1] + distance;
break;
case YTruderSettings.MODE_SYMMETRY_ACROSS_PLANE:
surf[numSurf][2][1] = 2 * distance - surf[numSurf][2][1];
surf[numSurf][3][1] = 2 * distance - surf[numSurf][3][1];
break;
case YTruderSettings.MODE_PROJECTION_ON_PLANE:
surf[numSurf][2][1] = distance;
surf[numSurf][3][1] = distance;
break;
case YTruderSettings.MODE_EXTRUDE_RADIALLY:
p0[0] = 0;
p0[1] = surf[numSurf][0][1];
p0[2] = 0;
p1[0] = 0;
p1[1] = surf[numSurf][1][1];
p1[2] = 0;
d0 = dist(p0, surf[numSurf][0]);
d1 = dist(p1, surf[numSurf][1]);
if (d0 > EPSILON) {
surf[numSurf][3][0] = surf[numSurf][3][0] * (d0 + distance) / d0;
surf[numSurf][3][2] = surf[numSurf][3][2] * (d0 + distance) / d0;
}
if (d1 > EPSILON) {
surf[numSurf][2][0] = surf[numSurf][2][0] * (d1 + distance) / d1;
surf[numSurf][2][2] = surf[numSurf][2][2] * (d1 + distance) / d1;
}
set(condLine[numCond][0], surf[numSurf][0]);
set(condLine[numCond][1], surf[numSurf][2]);
set(condLine[numCond][2], surf[numSurf][1]);
set(condLine[numCond][3], surf[numSurf][3]);
condFlag[numCond] = 5;
numCond++;
break;
default:
break;
}
set(condLine[numCond][0], surf[numSurf][0]);
set(condLine[numCond][1], surf[numSurf][3]);
set(condLine[numCond][2], surf[numSurf][1]);
set(condLine[numCond][3], surf[numSurf - 1][0]);
condFlag[numCond] = 5;
numSurf++;
numCond++;
lineUsed[current] = 2;
}
if (flag)
break;
}
}
if (flag)
break;
}
} while (flag);
if (manhattan(surf[numSurf - 1][1], surf[surfstart][0]) < SMALL) {
set(condLine[numCond][0], surf[numSurf - 1][1]);
set(condLine[numCond][1], surf[numSurf - 1][2]);
set(condLine[numCond][2], surf[numSurf - 1][0]);
set(condLine[numCond][3], surf[surfstart][1]);
condFlag[numCond] = 5;
numCond++;
} else {
set(condLine[numCond][0], surf[numSurf - 1][1]);
set(condLine[numCond][1], surf[numSurf - 1][2]);
condFlag[numCond] = 2;
numCond++;
set(condLine[numCond][0], surf[surfstart][0]);
set(condLine[numCond][1], surf[surfstart][3]);
condFlag[numCond] = 2;
numCond++;
}
}
}
for (int k = 0; k < numSurf; k++) {
if (manhattan(surf[k][0], surf[k][3]) < SMALL && manhattan(surf[k][1], surf[k][2]) < SMALL)
continue;
if (manhattan(surf[k][0], surf[k][3]) < SMALL) {
Vertex v1 = new Vertex(new BigDecimal(surf[k][0][x]), new BigDecimal(surf[k][0][y]), new BigDecimal(surf[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(surf[k][1][x]), new BigDecimal(surf[k][1][y]), new BigDecimal(surf[k][1][z]));
Vertex v3 = new Vertex(new BigDecimal(surf[k][2][x]), new BigDecimal(surf[k][2][y]), new BigDecimal(surf[k][2][z]));
newTriangles.add(new GData3(
bodyColour.getColourNumber(), bodyColour.getR(), bodyColour.getG(), bodyColour.getB(), bodyColour.getA(),
v1, v2, v3, View.DUMMY_REFERENCE, linkedDatFile, true));
} else if (manhattan(surf[k][1], surf[k][2]) < SMALL) {
Vertex v1 = new Vertex(new BigDecimal(surf[k][0][x]), new BigDecimal(surf[k][0][y]), new BigDecimal(surf[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(surf[k][1][x]), new BigDecimal(surf[k][1][y]), new BigDecimal(surf[k][1][z]));
Vertex v3 = new Vertex(new BigDecimal(surf[k][3][x]), new BigDecimal(surf[k][3][y]), new BigDecimal(surf[k][3][z]));
newTriangles.add(new GData3(
bodyColour.getColourNumber(), bodyColour.getR(), bodyColour.getG(), bodyColour.getB(), bodyColour.getA(),
v1, v2, v3, View.DUMMY_REFERENCE, linkedDatFile, true));
} else if (mode == YTruderSettings.MODE_TRANSLATE_BY_DISTANCE
|| mode == YTruderSettings.MODE_SYMMETRY_ACROSS_PLANE
|| triAngle(surf[k][0], surf[k][1], surf[k][2], surf[k][0], surf[k][2], surf[k][3]) <= 0.5) {
Vertex v1 = new Vertex(new BigDecimal(surf[k][0][x]), new BigDecimal(surf[k][0][y]), new BigDecimal(surf[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(surf[k][1][x]), new BigDecimal(surf[k][1][y]), new BigDecimal(surf[k][1][z]));
Vertex v3 = new Vertex(new BigDecimal(surf[k][2][x]), new BigDecimal(surf[k][2][y]), new BigDecimal(surf[k][2][z]));
Vertex v4 = new Vertex(new BigDecimal(surf[k][3][x]), new BigDecimal(surf[k][3][y]), new BigDecimal(surf[k][3][z]));
newQuads.add(new GData4(
bodyColour.getColourNumber(), bodyColour.getR(), bodyColour.getG(), bodyColour.getB(), bodyColour.getA(),
v1, v2, v3, v4, View.DUMMY_REFERENCE, linkedDatFile));
} else {
{
Vertex v1 = new Vertex(new BigDecimal(surf[k][0][x]), new BigDecimal(surf[k][0][y]), new BigDecimal(surf[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(surf[k][1][x]), new BigDecimal(surf[k][1][y]), new BigDecimal(surf[k][1][z]));
Vertex v3 = new Vertex(new BigDecimal(surf[k][2][x]), new BigDecimal(surf[k][2][y]), new BigDecimal(surf[k][2][z]));
newTriangles.add(new GData3(
bodyColour.getColourNumber(), bodyColour.getR(), bodyColour.getG(), bodyColour.getB(), bodyColour.getA(),
v1, v2, v3, View.DUMMY_REFERENCE, linkedDatFile, true));
}
{
Vertex v1 = new Vertex(new BigDecimal(surf[k][0][x]), new BigDecimal(surf[k][0][y]), new BigDecimal(surf[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(surf[k][2][x]), new BigDecimal(surf[k][2][y]), new BigDecimal(surf[k][2][z]));
Vertex v3 = new Vertex(new BigDecimal(surf[k][3][x]), new BigDecimal(surf[k][3][y]), new BigDecimal(surf[k][3][z]));
newTriangles.add(new GData3(
bodyColour.getColourNumber(), bodyColour.getR(), bodyColour.getG(), bodyColour.getB(), bodyColour.getA(),
v1, v2, v3, View.DUMMY_REFERENCE, linkedDatFile, true));
}
}
}
for (int k = 0; k < numCond; k++) {
if (manhattan(condLine[k][0], condLine[k][1]) < SMALL)
continue;
if (condFlag[k] == 5) {
double a;
a = triAngle(condLine[k][0], condLine[k][1], condLine[k][2], condLine[k][0], condLine[k][3], condLine[k][1]);
if (a < angleLineThr) {
Vertex v1 = new Vertex(new BigDecimal(condLine[k][0][x]), new BigDecimal(condLine[k][0][y]), new BigDecimal(condLine[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(condLine[k][1][x]), new BigDecimal(condLine[k][1][y]), new BigDecimal(condLine[k][1][z]));
Vertex v3 = new Vertex(new BigDecimal(condLine[k][2][x]), new BigDecimal(condLine[k][2][y]), new BigDecimal(condLine[k][2][z]));
Vertex v4 = new Vertex(new BigDecimal(condLine[k][3][x]), new BigDecimal(condLine[k][3][y]), new BigDecimal(condLine[k][3][z]));
newCondlines.add(new GData5(
lineColour.getColourNumber(), lineColour.getR(), lineColour.getG(), lineColour.getB(), lineColour.getA(),
v1, v2, v3, v4, View.DUMMY_REFERENCE, linkedDatFile));
} else {
Vertex v1 = new Vertex(new BigDecimal(condLine[k][0][x]), new BigDecimal(condLine[k][0][y]), new BigDecimal(condLine[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(condLine[k][1][x]), new BigDecimal(condLine[k][1][y]), new BigDecimal(condLine[k][1][z]));
newLines.add(new GData2(
lineColour.getColourNumber(), lineColour.getR(), lineColour.getG(), lineColour.getB(), lineColour.getA(),
v1, v2, View.DUMMY_REFERENCE, linkedDatFile, true));
}
}
if (condFlag[k] == 2) {
Vertex v1 = new Vertex(new BigDecimal(condLine[k][0][x]), new BigDecimal(condLine[k][0][y]), new BigDecimal(condLine[k][0][z]));
Vertex v2 = new Vertex(new BigDecimal(condLine[k][1][x]), new BigDecimal(condLine[k][1][y]), new BigDecimal(condLine[k][1][z]));
newLines.add(new GData2(
lineColour.getColourNumber(), lineColour.getR(), lineColour.getG(), lineColour.getB(), lineColour.getA(),
v1, v2, View.DUMMY_REFERENCE, linkedDatFile, true));
}
}
NLogger.debug(getClass(), "Check for identical vertices and collinearity."); //$NON-NLS-1$
final Set<GData2> linesToDelete2 = new HashSet<>();
final Set<GData3> trisToDelete2 = new HashSet<>();
final Set<GData4> quadsToDelete2 = new HashSet<>();
final Set<GData5> condlinesToDelete2 = new HashSet<>();
{
for (GData2 g2 : newLines) {
Vertex[] verts = lines.get(g2);
SortedSet<Vertex> verts2 = new TreeSet<>();
verts2.addAll(Arrays.asList(verts));
if (verts2.size() < 2) {
linesToDelete2.add(g2);
}
}
for (GData3 g3 : newTriangles) {
Vertex[] verts = triangles.get(g3);
SortedSet<Vertex> verts2 = new TreeSet<>();
verts2.addAll(Arrays.asList(verts));
if (verts2.size() < 3 || g3.isCollinear()) {
trisToDelete2.add(g3);
}
}
for (GData4 g4 : newQuads) {
Vertex[] verts = quads.get(g4);
SortedSet<Vertex> verts2 = new TreeSet<>();
verts2.addAll(Arrays.asList(verts));
if (verts2.size() < 4 || g4.isCollinear()) {
quadsToDelete2.add(g4);
}
}
for (GData5 g5 : newCondlines) {
Vertex[] verts = condlines.get(g5);
SortedSet<Vertex> verts2 = new TreeSet<>();
verts2.addAll(Arrays.asList(verts));
if (verts2.size() < 4) {
condlinesToDelete2.add(g5);
}
}
}
// Append the new data
for (GData2 line : newLines) {
linkedDatFile.addToTailOrInsertAfterCursor(line);
}
for (GData3 tri : newTriangles) {
linkedDatFile.addToTailOrInsertAfterCursor(tri);
}
for (GData4 quad : newQuads) {
linkedDatFile.addToTailOrInsertAfterCursor(quad);
}
for (GData5 condline : newCondlines) {
linkedDatFile.addToTailOrInsertAfterCursor(condline);
}
NLogger.debug(getClass(), "Delete new, but invalid objects."); //$NON-NLS-1$
clearSelection2();
newLines.removeAll(linesToDelete2);
newTriangles.removeAll(trisToDelete2);
newQuads.removeAll(quadsToDelete2);
newCondlines.removeAll(condlinesToDelete2);
selectedLines.addAll(linesToDelete2);
selectedTriangles.addAll(trisToDelete2);
selectedQuads.addAll(quadsToDelete2);
selectedCondlines.addAll(condlinesToDelete2);
selectedData.addAll(selectedLines);
selectedData.addAll(selectedTriangles);
selectedData.addAll(selectedQuads);
selectedData.addAll(selectedCondlines);
delete(false, false);
// Round to 6 decimal places
selectedLines.addAll(newLines);
selectedTriangles.addAll(newTriangles);
selectedQuads.addAll(newQuads);
selectedCondlines.addAll(newCondlines);
selectedData.addAll(selectedLines);
selectedData.addAll(selectedTriangles);
selectedData.addAll(selectedQuads);
selectedData.addAll(selectedCondlines);
NLogger.debug(getClass(), "Round."); //$NON-NLS-1$
roundSelection(6, 10, true, false, true, true, true);
setModified(true, true);
validateState();
NLogger.debug(getClass(), "Done."); //$NON-NLS-1$
}
private void cross(double[] dest, double[] left, double[] right) {
dest[0] = left[1] * right[2] - left[2] * right[1];
dest[1] = left[2] * right[0] - left[0] * right[2];
dest[2] = left[0] * right[1] - left[1] * right[0];
}
private double dot(double[] v1, double[] v2) {
return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
}
private void sub(double[] dest, double[] left, double[] right) {
dest[0] = left[0] - right[0];
dest[1] = left[1] - right[1];
dest[2] = left[2] - right[2];
}
private void mult(double[] dest, double[] v, double factor) {
dest[0] = factor * v[0];
dest[1] = factor * v[1];
dest[2] = factor * v[2];
}
private void set(double[] dest, double[] src) {
dest[0] = src[0];
dest[1] = src[1];
dest[2] = src[2];
}
private double manhattan(double[] v1, double[] v2) {
return Math.abs(v1[0] - v2[0]) + Math.abs(v1[1] - v2[1]) + Math.abs(v1[2] - v2[2]);
}
private double dist(double[] v1, double[] v2) {
return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]) + (v1[2] - v2[2]) * (v1[2] - v2[2]));
}
// Tri_Angle computes the cosine of the angle between the planes of two
// triangles.
// They are assumed to be non-degenerated
private double triAngle(double[] u0, double[] u1, double[] u2, double[] v0, double[] v1, double[] v2) {
double[] unorm = new double[3];
double[] vnorm = new double[3];
double[] temp = new double[3];
double[] u10 = new double[3];
double[] u20 = new double[3];
double[] v10 = new double[3];
double[] v20 = new double[3];
double len;
sub(u10, u1, u0);
sub(u20, u2, u0);
sub(v10, v1, v0);
sub(v20, v2, v0);
cross(temp, u10, u20);
len = dist(temp, nullv);
mult(unorm, temp, 1 / len);
cross(temp, v10, v20);
len = dist(temp, nullv);
mult(vnorm, temp, 1 / len);
return 180 / 3.14159 * Math.acos(dot(unorm, vnorm));
}
}
| Fixed issue #915. | src/org/nschmidt/ldparteditor/data/VM27YTruder.java | Fixed issue #915. | <ide><path>rc/org/nschmidt/ldparteditor/data/VM27YTruder.java
<ide> private static final double EPSILON = 0.000001;
<ide> private static final double SMALL = 0.01;
<ide> private double[] nullv = new double[] { 0.0, 0.0, 0.0 };
<add> private static final int X_AXIS = 0;
<add> private static final int Y_AXIS = 1;
<add> private static final int Z_AXIS = 2;
<ide>
<ide> protected VM27YTruder(DatFile linkedDatFile) {
<ide> super(linkedDatFile);
<ide>
<ide> boolean flag = false;
<ide>
<del> if (ys.getAxis() == 0) {
<add> if (ys.getAxis() == X_AXIS) {
<ide> x = 1;
<ide> y = 0;
<ide> z = 2;
<del> } else if (ys.getAxis() == 1) {
<add> } else if (ys.getAxis() == Y_AXIS) {
<ide> x = 0;
<ide> y = 1;
<ide> z = 2;
<del> } else if (ys.getAxis() == 2) {
<add> } else if (ys.getAxis() == Z_AXIS) {
<ide> x = 0;
<ide> y = 2;
<ide> z = 1;
<ide>
<ide> int originalLineCount = 0;
<ide> for (GData2 gData2 : originalSelection) {
<del> inLine[originalLineCount][0][x] = gData2.x1p.doubleValue();
<del> inLine[originalLineCount][0][y] = gData2.y1p.doubleValue();
<del> inLine[originalLineCount][0][z] = gData2.z1p.doubleValue();
<del> inLine[originalLineCount][1][x] = gData2.x2p.doubleValue();
<del> inLine[originalLineCount][1][y] = gData2.y2p.doubleValue();
<del> inLine[originalLineCount][1][z] = gData2.z2p.doubleValue();
<del> lineUsed[originalLineCount] = 0;
<del> originalLineCount++;
<add> Vertex[] verts = lines.get(gData2);
<add> if (verts != null) {
<add> inLine[originalLineCount][0][x] = verts[0].xp.doubleValue();
<add> inLine[originalLineCount][0][y] = verts[0].yp.doubleValue();
<add> inLine[originalLineCount][0][z] = verts[0].zp.doubleValue();
<add> inLine[originalLineCount][1][x] = verts[1].xp.doubleValue();
<add> inLine[originalLineCount][1][y] = verts[1].yp.doubleValue();
<add> inLine[originalLineCount][1][z] = verts[1].zp.doubleValue();
<add> lineUsed[originalLineCount] = 0;
<add> originalLineCount++;
<add> }
<ide> }
<ide>
<ide> // Extruding... |
|
JavaScript | mit | 56bce7a816701f4d72cfdd8d3b90a141601c6336 | 0 | StraboSpot/strabo-mobile,StraboSpot/strabo-mobile | Math.radians = function(deg) {
return deg * (Math.PI / 180);
};
angular.module('app')
.controller("MapCtrl", function(
$scope,
$rootScope,
$cordovaGeolocation,
$location,
$filter,
$ionicHistory,
$ionicModal,
$ionicPopup,
$ionicActionSheet,
$ionicSideMenuDelegate,
NewSpot,
MapView,
OfflineTilesFactory,
SlippyTileNamesFactory,
SpotsFactory,
ViewExtentFactory,
ImagesFactory,
MapLayerFactory) {
// disable dragging back to ionic side menu because this affects drawing tools
$ionicSideMenuDelegate.canDragContent(false);
// ol3 map
var map;
// draw is a ol3 drawing interaction
var draw;
// added draw controls
var drawControls = function(opt_options) {
var options = opt_options || {};
var drawPoint, drawLine, drawPoly;
drawPoint = document.createElement('a');
drawPoint.id = 'drawPointControl';
drawPoint.href = '#drawPointControl';
drawPoint.className = 'point';
drawLine = document.createElement('a');
drawLine.id = 'drawLineControl';
drawLine.href = '#drawLineControl';
drawLine.className = 'line';
drawPoly = document.createElement('a');
drawPoly.id = 'drawPolyControl';
drawPoly.href = '#drawPolyControl';
drawPoly.className = 'poly';
var handleDrawPoint = function(e) {
if (drawPoint.style.backgroundColor === '')
drawPoint.style.backgroundColor = '#DDDDDD';
else
drawPoint.style.backgroundColor = '';
drawLine.style.backgroundColor = '';
drawPoly.style.backgroundColor = '';
e.preventDefault();
$scope.startDraw("Point");
};
var handleDrawLine = function(e) {
if (drawLine.style.backgroundColor === '')
drawLine.style.backgroundColor = '#DDDDDD';
else
drawLine.style.backgroundColor = '';
drawPoint.style.backgroundColor = '';
drawPoly.style.backgroundColor = '';
e.preventDefault();
$scope.startDraw("LineString");
};
var handleDrawPoly = function(e) {
if (drawPoly.style.backgroundColor === '')
drawPoly.style.backgroundColor = '#DDDDDD';
else
drawPoly.style.backgroundColor = '';
drawPoint.style.backgroundColor = '';
drawLine.style.backgroundColor = '';
e.preventDefault();
$scope.startDraw("Polygon");
};
drawPoint.addEventListener('click', handleDrawPoint, false);
drawPoint.addEventListener('touchstart', handleDrawPoint, false);
drawLine.addEventListener('click', handleDrawLine, false);
drawLine.addEventListener('touchstart', handleDrawLine, false);
drawPoly.addEventListener('click', handleDrawPoly, false);
drawPoly.addEventListener('touchstart', handleDrawPoly, false);
var element = document.createElement('div');
element.className = 'draw-controls ol-unselectable';
element.appendChild(drawPoint);
element.appendChild(drawLine);
element.appendChild(drawPoly);
ol.control.Control.call(this, {
element: element,
target: options.target
});
};
ol.inherits(drawControls, ol.control.Control);
// initial map view, used for setting the view upon map creation
var initialMapView = new ol.View({
projection: 'EPSG:3857',
center: [-11000000, 4600000],
zoom: 4,
minZoom: 4
});
// lets create a new map
map = new ol.Map({
target: 'mapdiv',
view: initialMapView,
// remove rotate icon from controls and add drawing controls
controls: ol.control.defaults({
rotate: false
}),
// turn off ability to rotate map via keyboard+mouse and using fingers on a mobile device
interactions: ol.interaction.defaults({
altShiftDragRotate: false,
pinchRotate: false
})
});
// restricts the map constraint to these coordinates
// var mapExtent = ol.proj.transformExtent([-180,80,180,-80], 'EPSG:4326', 'EPSG:3857');
var mlf = MapLayerFactory;
// map layers
var onlineLayer = mlf.getOnlineLayer();
var onlineOverlayLayer = mlf.getOnlineOverlayLayer();
var offlineLayer = mlf.getOfflineLayer();
var offlineOverlayLayer = mlf.getOfflineOverlayLayer();
var geolocationLayer = mlf.getGeolocationLayer();
var featureLayer = mlf.getFeatureLayer();
// var drawLayer = mlf.getDrawLayer(); //bug, TODO
// layer where the drawing will go to
var drawLayer = new ol.layer.Vector({
name: 'drawLayer',
source: new ol.source.Vector(),
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
});
///////////////////////////
// map adding layers
///////////////////////////
// add the feature layer to the map first
map.addLayer(featureLayer);
// add draw layer
map.addLayer(drawLayer);
// add geolocation layer
map.addLayer(geolocationLayer);
// add draw controls
map.addControl(new drawControls());
// layer switcher
map.addControl(new ol.control.LayerSwitcher());
// Popup
var popup = new ol.Overlay.Popup();
map.addOverlay(popup);
/////////////////
// END MAP LAYERS
/////////////////
// did we come back from a map provider?
if (OfflineTilesFactory.getCurrentMapProvider()) {
// yes -- then we need to change the current visible layer
console.log("back at map, ", OfflineTilesFactory.getCurrentMapProvider());
var onlineLayerCollection = onlineLayer.getLayers().getArray();
_.each(onlineLayerCollection, function(layer) {
if (layer.get('id') == OfflineTilesFactory.getCurrentMapProvider()) {
layer.setVisible(true);
} else {
layer.setVisible(false);
}
});
}
// update the current visible layer, there is no return type as it updates the scope variable directly
var getCurrentVisibleLayer = function() {
// the first element in the layers array is our ol.layer.group that contains all the map tile layers
var mapTileLayers = map.getLayers().getArray()[0].getLayers().getArray();
// loop through and get the first layer that is visible
var mapTileId = _.find(mapTileLayers, function(layer) {
return layer.getVisible();
});
return mapTileId.get('id');
};
$scope.isOnline = function() {
return navigator.onLine;
};
// Watch whether we have internet access or not
$scope.$watch('isOnline()', function(online) {
if (!online) {
console.log("Offline");
// remove the online maps
map.removeLayer(onlineLayer);
map.removeLayer(onlineOverlayLayer);
// Add offline tile layer
map.getLayers().insertAt(0, offlineLayer);
map.getLayers().insertAt(1, offlineOverlayLayer);
// clear the tiles, because we need to redraw if tiles have already been loaded to the screen
map.getLayers().getArray()[0].getLayers().item(0).getSource().tileCache.clear();
map.getLayers().getArray()[0].getLayers().item(1).getSource().tileCache.clear();
map.getLayers().getArray()[1].getLayers().item(0).getSource().tileCache.clear();
// re-render the map, grabs "new" tiles from storage
map.render();
}
else {
console.log("Online");
// remove the offline layers
map.removeLayer(offlineLayer);
map.removeLayer(offlineOverlayLayer);
// Add online map layer
map.getLayers().insertAt(0, onlineLayer);
map.getLayers().insertAt(1, onlineOverlayLayer);
}
});
// cache the tiles in the current view but don't switch to the offline layer
$scope.cacheOfflineTiles = function() {
if (navigator.onLine) {
// get the map extent
var mapViewExtent = getMapViewExtent();
// set the extent into the ViewExtentFactory
ViewExtentFactory.setExtent(getCurrentVisibleLayer(), mapViewExtent.topRight, mapViewExtent.bottomLeft, mapViewExtent.zoom);
// we set the current map provider so if we ever come back, we should try to use that map provider instead of the default provider
OfflineTilesFactory.setCurrentMapProvider(getCurrentVisibleLayer());
$location.path("/app/map/archiveTiles");
}
else
$ionicPopup.alert({
title: 'Offline!',
template: 'You must be online to save a map!'
});
};
// drawButtonActive used to keep state of which selected drawing tool is active
$scope.drawButtonActive = null;
$scope.startDraw = function(type, isFreeHand) {
//if the type is already selected, we want to stop drawing
if ($scope.drawButtonActive === type && !isFreeHand) {
$scope.drawButtonActive = null;
$scope.cancelDraw();
return;
} else {
$scope.drawButtonActive = type;
}
console.log("isFreeHand, ", isFreeHand);
// are we in freehand mode?
if (isFreeHand) {
// yes -- then disable the map drag pan
map.getInteractions().forEach(function (interaction) {
if (interaction instanceof ol.interaction.DragPan) {
console.log(interaction);
map.getInteractions().remove(interaction);
}
});
}
// is draw already set?
if (draw !== null) {
// yes, stop and remove the drawing interaction
$scope.cancelDraw();
}
if (isFreeHand) {
draw = new ol.interaction.Draw({
source: drawLayer.getSource(),
type: type,
condition: ol.events.condition.singleClick,
freehandCondition: ol.events.condition.noModifierKeys,
snapTolerance: 96
});
} else {
draw = new ol.interaction.Draw({
source: drawLayer.getSource(),
type: type
});
}
draw.on("drawend", function(e) {
// we want a geojson object when the user finishes drawing
var geojson = new ol.format.GeoJSON;
// the actual geojson object that was drawn
var geojsonObj = JSON.parse(geojson.writeFeature(e.feature, {
featureProjection: "EPSG:3857"
}));
if (isFreeHand) {
console.log("Drawend : Freehand");
// contains all the lassoed objects
var isLassoed = [];
SpotsFactory.all().then(function(spots) {
_.each(spots, function (spot) {
// if the spot is a point, we test using turf.inside
// if the spot is a polygon or line, we test using turf.intersect
var spotType = spot.geometry.type;
if (spotType === "Point") {
// is the point inside the drawn polygon?
if (turf.inside(spot, geojsonObj)) {
isLassoed.push(spot.properties.name);
}
}
if (spotType === "LineString" || spotType === "Polygon") {
// is the line or polygon within/intersected in the drawn polygon?
if (turf.intersect(spot, geojsonObj)) {
isLassoed.push(spot.properties.name);
}
}
});
// add the regular draw controls back
map.addControl(new drawControls());
// add the layer switcher controls back
map.addControl(new ol.control.LayerSwitcher());
// add the dragging back in
map.addInteraction(new ol.interaction.DragPan());
console.log("isLassoed, ", isLassoed);
});
} else {
console.log("Drawend: Normal (not freehand)");
// Initialize new Spot
NewSpot.setNewSpot(geojsonObj);
// If we got to the map from the spot view go back to that view
var backView = $ionicHistory.backView();
if (backView) {
if (backView.stateName == "app.spot") {
$rootScope.$apply(function() {
$location.path("/app/spots/newspot");
});
}
}
else {
// Initialize new Spot
NewSpot.setNewSpot(geojsonObj);
switch ($scope.drawButtonActive) {
case "Point":
$scope.openModal("pointModal");
break;
case "LineString":
$scope.openModal("lineModal");
break;
case "Polygon":
$scope.openModal("polyModal");
break;
}
}
}
});
map.addInteraction(draw);
};
// If the map is moved save the view
map.on('moveend', function(evt) {
MapView.setMapView(map.getView());
});
// Zoom to the extent of the spots, if that fails geolocate the user
$scope.zoomToSpotsExtent = function() {
// nope, we have NO mapview set, so...
// Loop through all spots and create ol vector layers
SpotsFactory.all().then(function(spots) {
// do we even have any spots?
if (spots.length > 0) {
console.log("found spots, attempting to get the center of all spots and change the map view to that");
var cr = new CoordinateRange(spots);
var newExtent = ol.extent.boundingExtent(cr._getAllCoordinates());
var newExtentCenter = ol.extent.getCenter(newExtent);
// fly-by map animation
var duration = 2000;
var start = +new Date();
var pan = ol.animation.pan({
duration: duration,
source: map.getView().getCenter(),
start: start
});
var bounce = ol.animation.bounce({
duration: duration,
resolution: map.getView().getResolution(),
start: start
});
map.beforeRender(pan, bounce);
if (spots.length === 1) {
// we just have a single spot, so we should fixate the resolution manually
initialMapView.setCenter(ol.proj.transform([newExtentCenter[0], newExtentCenter[1]], 'EPSG:4326', 'EPSG:3857'));
initialMapView.setZoom(15);
} else {
// we have multiple spots -- need to create the new view with the new center
var newView = new ol.View({
center: ol.proj.transform([newExtentCenter[0], newExtentCenter[1]], 'EPSG:4326', 'EPSG:3857')
});
map.setView(newView);
map.getView().fitExtent(ol.proj.transformExtent(newExtent, 'EPSG:4326', 'EPSG:3857'), map.getSize());
}
}
// no spots either, then attempt to geolocate the user
else {
console.log("no spots found, attempting to geolocate");
// attempt to geolocate instead
$cordovaGeolocation.getCurrentPosition({
maximumAge: 0,
timeout: 10000,
enableHighAccuracy: true
})
.then(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log("initial getLocation ", [lat, lng]);
var newView = new ol.View({
center: ol.proj.transform([lng, lat], 'EPSG:4326', 'EPSG:3857'),
zoom: 17,
minZoom: 4
});
map.setView(newView);
}, function(err) {
// uh oh, cannot geolocate, nor have any spots
$ionicPopup.alert({
title: 'Alert!',
template: 'Could not geolocate your position. Defaulting you to 0,0'
});
var newView = new ol.View({
center: ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857'),
zoom: 4,
minZoom: 4
});
map.setView(newView);
});
}
});
};
// do we currently have mapview set? if so, we should reset the map view to that first
if (MapView.getMapView()) {
console.log("have mapview set, changing map view to that");
map.setView(MapView.getMapView());
} else {
$scope.zoomToSpotsExtent();
}
$scope.cancelDraw = function() {
if (draw === null) return;
map.removeInteraction(draw);
};
// converts blobs to base64
var blobToBase64 = function(blob, callback) {
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
base64data = reader.result;
callback(base64data);
};
};
// Point object
var Point = function(lat, lng) {
this.lat = lat;
this.lng = lng;
};
var getMapViewExtent = function() {
var extent = map.getView().calculateExtent(map.getSize());
var zoom = map.getView().getZoom();
var bottomLeft = ol.proj.transform(ol.extent.getBottomLeft(extent),
'EPSG:3857', 'EPSG:4326');
var topRight = ol.proj.transform(ol.extent.getTopRight(extent),
'EPSG:3857', 'EPSG:4326');
return {
topRight: new Point(topRight[1], topRight[0]),
bottomLeft: new Point(bottomLeft[1], bottomLeft[0]),
zoom: zoom
};
};
// we want to load all the geojson markers from the persistence storage onto the map
// creates a ol vector layer for supplied geojson object
var geojsonToVectorLayer = function(geojson) {
// textStyle is a function because each point has a different text associated
var textStyle = function(text) {
return new ol.style.Text({
font: '12px Calibri,sans-serif',
text: text,
fill: new ol.style.Fill({
color: '#000'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 3
})
});
};
var icon = {
contact_outcrop: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('contact_outcrop'),
scale: 0.05
});
},
fault_outcrop: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('fault_outcrop'),
scale: 1
});
},
shear_zone: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('shear_zone'),
scale: 0.05
});
},
fold: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('fold'),
scale: 0.05
});
},
notes: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('notes'),
scale: 0.75
});
},
orientation: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('orientation'),
scale: 1
});
},
sample: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('sample'),
scale: 0.07
});
},
group: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('group'),
scale: 0.4
});
},
default: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('default'),
scale: 0.75
});
}
};
var getIconForFeature = function(feature) {
var contentModel = feature.get('type');
var dip = null;
var plunge = null;
// do we have a dip?
if (typeof feature.get('dip') !== 'undefined') {
dip = feature.get('dip');
}
// do we have a plunge?
if (typeof feature.get('plunge') !== 'undefined') {
plunge = feature.get('plunge');
}
var rotation = (dip || plunge) ? dip || plunge : 0;
switch (contentModel) {
case "Contact":
return icon.contact_outcrop(rotation);
case "Fault":
return icon.fault_outcrop(rotation);
case "Shear Zone":
return icon.shear_zone(rotation);
case "Fold":
return icon.fold(rotation);
case "Notes":
return icon.notes(rotation);
case "Orientation":
return icon.orientation(rotation);
case "Rock Description":
return icon.notes(rotation);
case "Sample Locality":
return icon.sample(rotation);
case "Spot Grouping":
return icon.group(rotation);
default:
return icon.default(rotation);
}
// if (contentModel == "Orientation") {
// // we do something else with orientation content models
// } else {
// // get the links
// // TODO: what if there's more than one relationship? What do we use then?
//
// if (feature.get('links') === undefined) {
// // TODO: what if there's NO relationship?
// return;
// } else {
// var linkedRelationshipId = feature.get('links')[0].id;
// console.log("aaa", linkedRelationshipId);
//
// // get the actual spot
// return SpotsFactory.getSpotId(linkedRelationshipId).then(function(spot) {
//
// // we only care about orientations linkages at this point
// if (spot.properties.type == "Orientation") {
//
// console.log("the spot is", spot);
//
// var dip = null;
// var plunge = null;
//
// // do we have a dip?
// if (typeof spot.properties.dip !== 'undefined') {
// dip = spot.properties.dip;
// }
//
// // do we have a plunge?
// if (typeof spot.properties.plunge !== 'undefined') {
// plunge = spot.properties.plunge;
// }
//
// var rotation = (dip || plunge) ? dip || plunge : 0;
//
// switch(contentModel) {
// case "Contact Outcrop":
// return icon.contact_outcrop(rotation);
// case "Fault Outcrop":
// return icon.fault_outcrop(rotation);
// default:
// // TODO: do we want to put a default image when everything fails?
// break;
// }
//
//
// }
//
//
//
//
// });
// }
};
return new ol.layer.Vector({
source: new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojson, {
featureProjection: 'EPSG:3857'
})
}),
title: geojson.properties.name,
style: function(feature, resolution) {
var styles = {
'Point': [
new ol.style.Style({
image: getIconForFeature(feature)
}),
new ol.style.Style({
text: textStyle(feature.values_.name)
})
],
'LineString': [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#000000",
width: 10
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#ff0000",
width: 8
})
}),
new ol.style.Style({
text: textStyle(feature.values_.name)
})
],
'Polygon': [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#000000",
width: 10
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#035339",
width: 8
})
}),
new ol.style.Style({
text: textStyle(feature.values_.name)
})
]
};
return styles[feature.getGeometry().getType()];
}
});
};
// Loop through all spots and create ol vector layers
SpotsFactory.all().then(function(spots) {
// wipe the array because we want to avoid duplicating the feature in the ol.Collection
featureLayer.getLayers().clear();
// get distinct groups and aggregate spots by group type
var spotGroup = _.groupBy(spots, function(spot) {
return spot.properties.type;
});
// go through each group and assign all the aggregates to the geojson feature
for (var key in spotGroup) {
if (spotGroup.hasOwnProperty(key)) {
// create a geojson to hold all the spots that fit the same spot type
var spotTypeLayer = {
type: 'FeatureCollection',
features: spotGroup[key],
properties: {
name: key + ' (' + spotGroup[key].length + ')'
}
};
// add the feature collection layer to the map
featureLayer.getLayers().push(geojsonToVectorLayer(spotTypeLayer));
}
}
});
map.on('touchstart', function(event) {
console.log("touch");
console.log(event);
});
// display popup on click
map.on('click', function(evt) {
console.log("map clicked");
// are we in draw mode? If so we dont want to display any popovers during draw mode
if (!draw) {
// where the user just clicked
var coordinate = evt.coordinate;
// clear any existing popovers
popup.hide();
var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
return feature;
}, this, function(layer) {
// we only want the layer where the spots are located
return (layer instanceof ol.layer.Vector) && layer.get('name') !== 'drawLayer' && layer.get('name') !== 'geolocationLayer';
});
var layer = map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
return layer;
}, this, function(layer) {
// we only want the layer where the spots are located
return (layer instanceof ol.layer.Vector) && layer.get('name') !== 'drawLayer' && layer.get('name') !== 'geolocationLayer';
});
// we need to check that we're not clicking on the geolocation layer
if (feature && layer.get('name') != 'geolocationLayer') {
// popup content
var content = '';
content += '<a href="#/app/spots/' + feature.get('id') + '/details"><b>' + feature.get('name') + '</b></a>';
content += '<br>';
content += '<small>' + feature.get('type') + '</small>';
content += '<small> (' + feature.getGeometry().getType() + ')</small>';
if (feature.get('strike') && feature.get('dip')) {
content += '<br>';
content += '<small>' + feature.get('strike') + '° strike / ' + feature.get('dip') + '° dip</small>';
}
if (feature.get('trend') && feature.get('plunge')) {
content += '<br>';
content += '<small>' + feature.get('trend') + '° trend / ' + feature.get('plunge') + '° plunge</small>';
}
// setup the popup position
popup.show(evt.coordinate, content);
}
}
});
var geolocationWatchId;
// Get current position
$scope.toggleLocation = function() {
if ($scope.locationOn === undefined || $scope.locationOn === false) {
$scope.locationOn = true;
} else {
$scope.locationOn = false;
}
if ($scope.locationOn) {
console.log("toggleLocation is now true");
$cordovaGeolocation.getCurrentPosition({
maximumAge: 0,
timeout: 10000,
enableHighAccuracy: true
})
.then(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var altitude = position.coords.altitude;
var accuracy = position.coords.accuracy;
var heading = position.coords.heading;
var speed = position.coords.speed;
console.log("getLocation ", [lat, lng], "(accuracy: " + accuracy + ") (altitude: " + altitude + ") (heading: " + heading + ") (speed: " + speed + ")");
var newView = new ol.View({
center: ol.proj.transform([lng, lat], 'EPSG:4326', 'EPSG:3857'),
zoom: 18,
minZoom: 4
});
map.setView(newView);
}, function(err) {
$ionicPopup.alert({
title: 'Alert!',
template: "Unable to get location: " + err.message
});
});
geolocationWatchId = $cordovaGeolocation.watchPosition({
frequency: 1000,
timeout: 10000,
enableHighAccuracy: true // may cause errors if true
});
geolocationWatchId.then(
null,
function(err) {
$ionicPopup.alert({
title: 'Alert!',
template: "Unable to get location for geolocationWatchId: " + geolocationWatchId.watchID + " (" + err.message + ")"
});
// TODO: what do we do here?
},
function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var altitude = position.coords.altitude;
var accuracy = position.coords.accuracy;
var altitudeAccuracy = position.coords.altitudeAccuracy;
var heading = position.coords.heading;
var speed = position.coords.speed;
console.log("getLocation-watch ", [lat, lng], "(accuracy: " + accuracy + ") (altitude: " + altitude + ") (heading: " + heading + ") (speed: " + speed + ")");
// create a point feature and assign the lat/long to its geometry
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([lng, lat], 'EPSG:4326', 'EPSG:3857'))
});
// add addition geolocation data to the feature so we can recall it later
iconFeature.set('altitude', altitude);
iconFeature.set('accuracy', (accuracy === null) ? null : Math.floor(accuracy));
iconFeature.set('altitudeAccuracy', altitudeAccuracy);
iconFeature.set('heading', heading);
iconFeature.set('speed', (speed === null) ? null : Math.floor(speed));
var vectorSource = new ol.source.Vector({
features: [iconFeature]
});
geolocationLayer.setSource(vectorSource);
});
} else {
// locationOn must be false
console.log("toggleLocation is now false");
// clear geolocation watch
geolocationWatchId.clearWatch();
// clear the geolocation marker
geolocationLayer.setSource(new ol.source.Vector({}));
}
};
var groupSpots = function() {
// remove the layer switcher to avoid confusion with lasso and regular drawing
map.getControls().removeAt(3);
// remove the drawing tools to avoid confusion with lasso and regular drawing
map.getControls().removeAt(2);
// start the draw with freehand enabled
$scope.startDraw('Polygon', true);
};
/////////////////
// ACTIONSHEET
/////////////////
$scope.showActionsheet = function() {
$ionicActionSheet.show({
titleText: 'Map Actions',
buttons: [
{text: '<i class="icon ion-map"></i> Zoom to Extent of Spots'},
{text: '<i class="icon ion-archive"></i>Save Map for Offline Use'},
{text: '<i class="icon ion-grid"></i> Create a Grouping of Spots'}
],
cancelText: 'Cancel',
cancel: function () {
console.log('CANCELLED');
},
buttonClicked: function (index) {
console.log('BUTTON CLICKED', index);
switch(index) {
case 0:
$scope.zoomToSpotsExtent();
break;
case 1:
$scope.cacheOfflineTiles();
break;
case 2:
groupSpots();
break;
}
return true;
}
});
};
/////////////////
// MODALS
/////////////////
$ionicModal.fromTemplateUrl('templates/modals/pointModal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.pointModal = modal;
});
$ionicModal.fromTemplateUrl('templates/modals/lineModal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.lineModal = modal;
});
$ionicModal.fromTemplateUrl('templates/modals/polyModal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.polyModal = modal;
});
$scope.openModal = function(modal) {
$scope[modal].show();
};
$scope.closeModal = function() {
$scope.pointModal.hide();
$scope.lineModal.hide();
$scope.polyModal.hide();
};
//Cleanup the modal when we're done with it!
// Execute action on hide modal
$scope.$on('pointModal.hidden', function() {
$scope.pointModal.remove();
});
$scope.$on('lineModal.hidden', function() {
$scope.lineModal.remove();
});
$scope.$on('polyModal.hidden', function() {
$scope.polyModal.remove();
});
});
| www/js/controllers/map.js | Math.radians = function(deg) {
return deg * (Math.PI / 180);
};
angular.module('app')
.controller("MapCtrl", function(
$scope,
$rootScope,
$cordovaGeolocation,
$location,
$filter,
$ionicHistory,
$ionicModal,
$ionicPopup,
$ionicActionSheet,
NewSpot,
MapView,
OfflineTilesFactory,
SlippyTileNamesFactory,
SpotsFactory,
ViewExtentFactory,
ImagesFactory,
MapLayerFactory) {
// ol3 map
var map;
// draw is a ol3 drawing interaction
var draw;
// added draw controls
var drawControls = function(opt_options) {
var options = opt_options || {};
var drawPoint, drawLine, drawPoly;
drawPoint = document.createElement('a');
drawPoint.id = 'drawPointControl';
drawPoint.href = '#drawPointControl';
drawPoint.className = 'point';
drawLine = document.createElement('a');
drawLine.id = 'drawLineControl';
drawLine.href = '#drawLineControl';
drawLine.className = 'line';
drawPoly = document.createElement('a');
drawPoly.id = 'drawPolyControl';
drawPoly.href = '#drawPolyControl';
drawPoly.className = 'poly';
var handleDrawPoint = function(e) {
if (drawPoint.style.backgroundColor === '')
drawPoint.style.backgroundColor = '#DDDDDD';
else
drawPoint.style.backgroundColor = '';
drawLine.style.backgroundColor = '';
drawPoly.style.backgroundColor = '';
e.preventDefault();
$scope.startDraw("Point");
};
var handleDrawLine = function(e) {
if (drawLine.style.backgroundColor === '')
drawLine.style.backgroundColor = '#DDDDDD';
else
drawLine.style.backgroundColor = '';
drawPoint.style.backgroundColor = '';
drawPoly.style.backgroundColor = '';
e.preventDefault();
$scope.startDraw("LineString");
};
var handleDrawPoly = function(e) {
if (drawPoly.style.backgroundColor === '')
drawPoly.style.backgroundColor = '#DDDDDD';
else
drawPoly.style.backgroundColor = '';
drawPoint.style.backgroundColor = '';
drawLine.style.backgroundColor = '';
e.preventDefault();
$scope.startDraw("Polygon");
};
drawPoint.addEventListener('click', handleDrawPoint, false);
drawPoint.addEventListener('touchstart', handleDrawPoint, false);
drawLine.addEventListener('click', handleDrawLine, false);
drawLine.addEventListener('touchstart', handleDrawLine, false);
drawPoly.addEventListener('click', handleDrawPoly, false);
drawPoly.addEventListener('touchstart', handleDrawPoly, false);
var element = document.createElement('div');
element.className = 'draw-controls ol-unselectable';
element.appendChild(drawPoint);
element.appendChild(drawLine);
element.appendChild(drawPoly);
ol.control.Control.call(this, {
element: element,
target: options.target
});
};
ol.inherits(drawControls, ol.control.Control);
// initial map view, used for setting the view upon map creation
var initialMapView = new ol.View({
projection: 'EPSG:3857',
center: [-11000000, 4600000],
zoom: 4,
minZoom: 4
});
// lets create a new map
map = new ol.Map({
target: 'mapdiv',
view: initialMapView,
// remove rotate icon from controls and add drawing controls
controls: ol.control.defaults({
rotate: false
}),
// turn off ability to rotate map via keyboard+mouse and using fingers on a mobile device
interactions: ol.interaction.defaults({
altShiftDragRotate: false,
pinchRotate: false
})
});
// restricts the map constraint to these coordinates
// var mapExtent = ol.proj.transformExtent([-180,80,180,-80], 'EPSG:4326', 'EPSG:3857');
var mlf = MapLayerFactory;
// map layers
var onlineLayer = mlf.getOnlineLayer();
var onlineOverlayLayer = mlf.getOnlineOverlayLayer();
var offlineLayer = mlf.getOfflineLayer();
var offlineOverlayLayer = mlf.getOfflineOverlayLayer();
var geolocationLayer = mlf.getGeolocationLayer();
var featureLayer = mlf.getFeatureLayer();
// var drawLayer = mlf.getDrawLayer(); //bug, TODO
// layer where the drawing will go to
var drawLayer = new ol.layer.Vector({
name: 'drawLayer',
source: new ol.source.Vector(),
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
});
///////////////////////////
// map adding layers
///////////////////////////
// add the feature layer to the map first
map.addLayer(featureLayer);
// add draw layer
map.addLayer(drawLayer);
// add geolocation layer
map.addLayer(geolocationLayer);
// add draw controls
map.addControl(new drawControls());
// layer switcher
map.addControl(new ol.control.LayerSwitcher());
// Popup
var popup = new ol.Overlay.Popup();
map.addOverlay(popup);
/////////////////
// END MAP LAYERS
/////////////////
// did we come back from a map provider?
if (OfflineTilesFactory.getCurrentMapProvider()) {
// yes -- then we need to change the current visible layer
console.log("back at map, ", OfflineTilesFactory.getCurrentMapProvider());
var onlineLayerCollection = onlineLayer.getLayers().getArray();
_.each(onlineLayerCollection, function(layer) {
if (layer.get('id') == OfflineTilesFactory.getCurrentMapProvider()) {
layer.setVisible(true);
} else {
layer.setVisible(false);
}
});
}
// update the current visible layer, there is no return type as it updates the scope variable directly
var getCurrentVisibleLayer = function() {
// the first element in the layers array is our ol.layer.group that contains all the map tile layers
var mapTileLayers = map.getLayers().getArray()[0].getLayers().getArray();
// loop through and get the first layer that is visible
var mapTileId = _.find(mapTileLayers, function(layer) {
return layer.getVisible();
});
return mapTileId.get('id');
};
$scope.isOnline = function() {
return navigator.onLine;
};
// Watch whether we have internet access or not
$scope.$watch('isOnline()', function(online) {
if (!online) {
console.log("Offline");
// remove the online maps
map.removeLayer(onlineLayer);
map.removeLayer(onlineOverlayLayer);
// Add offline tile layer
map.getLayers().insertAt(0, offlineLayer);
map.getLayers().insertAt(1, offlineOverlayLayer);
// clear the tiles, because we need to redraw if tiles have already been loaded to the screen
map.getLayers().getArray()[0].getLayers().item(0).getSource().tileCache.clear();
map.getLayers().getArray()[0].getLayers().item(1).getSource().tileCache.clear();
map.getLayers().getArray()[1].getLayers().item(0).getSource().tileCache.clear();
// re-render the map, grabs "new" tiles from storage
map.render();
}
else {
console.log("Online");
// remove the offline layers
map.removeLayer(offlineLayer);
map.removeLayer(offlineOverlayLayer);
// Add online map layer
map.getLayers().insertAt(0, onlineLayer);
map.getLayers().insertAt(1, onlineOverlayLayer);
}
});
// cache the tiles in the current view but don't switch to the offline layer
$scope.cacheOfflineTiles = function() {
if (navigator.onLine) {
// get the map extent
var mapViewExtent = getMapViewExtent();
// set the extent into the ViewExtentFactory
ViewExtentFactory.setExtent(getCurrentVisibleLayer(), mapViewExtent.topRight, mapViewExtent.bottomLeft, mapViewExtent.zoom);
// we set the current map provider so if we ever come back, we should try to use that map provider instead of the default provider
OfflineTilesFactory.setCurrentMapProvider(getCurrentVisibleLayer());
$location.path("/app/map/archiveTiles");
}
else
$ionicPopup.alert({
title: 'Offline!',
template: 'You must be online to save a map!'
});
};
// drawButtonActive used to keep state of which selected drawing tool is active
$scope.drawButtonActive = null;
$scope.startDraw = function(type, isFreeHand) {
//if the type is already selected, we want to stop drawing
if ($scope.drawButtonActive === type && !isFreeHand) {
$scope.drawButtonActive = null;
$scope.cancelDraw();
return;
} else {
$scope.drawButtonActive = type;
}
console.log("isFreeHand, ", isFreeHand);
// are we in freehand mode?
if (isFreeHand) {
// yes -- then disable the map drag pan
map.getInteractions().forEach(function (interaction) {
if (interaction instanceof ol.interaction.DragPan) {
console.log(interaction);
map.getInteractions().remove(interaction);
}
});
}
// is draw already set?
if (draw !== null) {
// yes, stop and remove the drawing interaction
$scope.cancelDraw();
}
if (isFreeHand) {
draw = new ol.interaction.Draw({
source: drawLayer.getSource(),
type: type,
condition: ol.events.condition.singleClick,
freehandCondition: ol.events.condition.noModifierKeys,
snapTolerance: 96
});
} else {
draw = new ol.interaction.Draw({
source: drawLayer.getSource(),
type: type
});
}
draw.on("drawend", function(e) {
// we want a geojson object when the user finishes drawing
var geojson = new ol.format.GeoJSON;
// the actual geojson object that was drawn
var geojsonObj = JSON.parse(geojson.writeFeature(e.feature, {
featureProjection: "EPSG:3857"
}));
if (isFreeHand) {
console.log("Drawend : Freehand");
// contains all the lassoed objects
var isLassoed = [];
SpotsFactory.all().then(function(spots) {
_.each(spots, function (spot) {
// if the spot is a point, we test using turf.inside
// if the spot is a polygon or line, we test using turf.intersect
var spotType = spot.geometry.type;
if (spotType === "Point") {
// is the point inside the drawn polygon?
if (turf.inside(spot, geojsonObj)) {
isLassoed.push(spot.properties.name);
}
}
if (spotType === "LineString" || spotType === "Polygon") {
// is the line or polygon within/intersected in the drawn polygon?
if (turf.intersect(spot, geojsonObj)) {
isLassoed.push(spot.properties.name);
}
}
});
// add the regular draw controls back
map.addControl(new drawControls());
// add the layer switcher controls back
map.addControl(new ol.control.LayerSwitcher());
// add the dragging back in
map.addInteraction(new ol.interaction.DragPan());
console.log("isLassoed, ", isLassoed);
});
} else {
console.log("Drawend: Normal (not freehand)");
// Initialize new Spot
NewSpot.setNewSpot(geojsonObj);
// If we got to the map from the spot view go back to that view
var backView = $ionicHistory.backView();
if (backView) {
if (backView.stateName == "app.spot") {
$rootScope.$apply(function() {
$location.path("/app/spots/newspot");
});
}
}
else {
// Initialize new Spot
NewSpot.setNewSpot(geojsonObj);
switch ($scope.drawButtonActive) {
case "Point":
$scope.openModal("pointModal");
break;
case "LineString":
$scope.openModal("lineModal");
break;
case "Polygon":
$scope.openModal("polyModal");
break;
}
}
}
});
map.addInteraction(draw);
};
// If the map is moved save the view
map.on('moveend', function(evt) {
MapView.setMapView(map.getView());
});
// Zoom to the extent of the spots, if that fails geolocate the user
$scope.zoomToSpotsExtent = function() {
// nope, we have NO mapview set, so...
// Loop through all spots and create ol vector layers
SpotsFactory.all().then(function(spots) {
// do we even have any spots?
if (spots.length > 0) {
console.log("found spots, attempting to get the center of all spots and change the map view to that");
var cr = new CoordinateRange(spots);
var newExtent = ol.extent.boundingExtent(cr._getAllCoordinates());
var newExtentCenter = ol.extent.getCenter(newExtent);
// fly-by map animation
var duration = 2000;
var start = +new Date();
var pan = ol.animation.pan({
duration: duration,
source: map.getView().getCenter(),
start: start
});
var bounce = ol.animation.bounce({
duration: duration,
resolution: map.getView().getResolution(),
start: start
});
map.beforeRender(pan, bounce);
if (spots.length === 1) {
// we just have a single spot, so we should fixate the resolution manually
initialMapView.setCenter(ol.proj.transform([newExtentCenter[0], newExtentCenter[1]], 'EPSG:4326', 'EPSG:3857'));
initialMapView.setZoom(15);
} else {
// we have multiple spots -- need to create the new view with the new center
var newView = new ol.View({
center: ol.proj.transform([newExtentCenter[0], newExtentCenter[1]], 'EPSG:4326', 'EPSG:3857')
});
map.setView(newView);
map.getView().fitExtent(ol.proj.transformExtent(newExtent, 'EPSG:4326', 'EPSG:3857'), map.getSize());
}
}
// no spots either, then attempt to geolocate the user
else {
console.log("no spots found, attempting to geolocate");
// attempt to geolocate instead
$cordovaGeolocation.getCurrentPosition({
maximumAge: 0,
timeout: 10000,
enableHighAccuracy: true
})
.then(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log("initial getLocation ", [lat, lng]);
var newView = new ol.View({
center: ol.proj.transform([lng, lat], 'EPSG:4326', 'EPSG:3857'),
zoom: 17,
minZoom: 4
});
map.setView(newView);
}, function(err) {
// uh oh, cannot geolocate, nor have any spots
$ionicPopup.alert({
title: 'Alert!',
template: 'Could not geolocate your position. Defaulting you to 0,0'
});
var newView = new ol.View({
center: ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857'),
zoom: 4,
minZoom: 4
});
map.setView(newView);
});
}
});
};
// do we currently have mapview set? if so, we should reset the map view to that first
if (MapView.getMapView()) {
console.log("have mapview set, changing map view to that");
map.setView(MapView.getMapView());
} else {
$scope.zoomToSpotsExtent();
}
$scope.cancelDraw = function() {
if (draw === null) return;
map.removeInteraction(draw);
};
// converts blobs to base64
var blobToBase64 = function(blob, callback) {
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
base64data = reader.result;
callback(base64data);
};
};
// Point object
var Point = function(lat, lng) {
this.lat = lat;
this.lng = lng;
};
var getMapViewExtent = function() {
var extent = map.getView().calculateExtent(map.getSize());
var zoom = map.getView().getZoom();
var bottomLeft = ol.proj.transform(ol.extent.getBottomLeft(extent),
'EPSG:3857', 'EPSG:4326');
var topRight = ol.proj.transform(ol.extent.getTopRight(extent),
'EPSG:3857', 'EPSG:4326');
return {
topRight: new Point(topRight[1], topRight[0]),
bottomLeft: new Point(bottomLeft[1], bottomLeft[0]),
zoom: zoom
};
};
// we want to load all the geojson markers from the persistence storage onto the map
// creates a ol vector layer for supplied geojson object
var geojsonToVectorLayer = function(geojson) {
// textStyle is a function because each point has a different text associated
var textStyle = function(text) {
return new ol.style.Text({
font: '12px Calibri,sans-serif',
text: text,
fill: new ol.style.Fill({
color: '#000'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 3
})
});
};
var icon = {
contact_outcrop: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('contact_outcrop'),
scale: 0.05
});
},
fault_outcrop: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('fault_outcrop'),
scale: 1
});
},
shear_zone: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('shear_zone'),
scale: 0.05
});
},
fold: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('fold'),
scale: 0.05
});
},
notes: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('notes'),
scale: 0.75
});
},
orientation: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('orientation'),
scale: 1
});
},
sample: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('sample'),
scale: 0.07
});
},
group: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('group'),
scale: 0.4
});
},
default: function(rotation) {
return new ol.style.Icon({
anchorXUnits: 'pixels',
anchorYUnits: 'pixels',
opacity: 1,
rotation: Math.radians(rotation),
src: ImagesFactory.getImagePath('default'),
scale: 0.75
});
}
};
var getIconForFeature = function(feature) {
var contentModel = feature.get('type');
var dip = null;
var plunge = null;
// do we have a dip?
if (typeof feature.get('dip') !== 'undefined') {
dip = feature.get('dip');
}
// do we have a plunge?
if (typeof feature.get('plunge') !== 'undefined') {
plunge = feature.get('plunge');
}
var rotation = (dip || plunge) ? dip || plunge : 0;
switch (contentModel) {
case "Contact":
return icon.contact_outcrop(rotation);
case "Fault":
return icon.fault_outcrop(rotation);
case "Shear Zone":
return icon.shear_zone(rotation);
case "Fold":
return icon.fold(rotation);
case "Notes":
return icon.notes(rotation);
case "Orientation":
return icon.orientation(rotation);
case "Rock Description":
return icon.notes(rotation);
case "Sample Locality":
return icon.sample(rotation);
case "Spot Grouping":
return icon.group(rotation);
default:
return icon.default(rotation);
}
// if (contentModel == "Orientation") {
// // we do something else with orientation content models
// } else {
// // get the links
// // TODO: what if there's more than one relationship? What do we use then?
//
// if (feature.get('links') === undefined) {
// // TODO: what if there's NO relationship?
// return;
// } else {
// var linkedRelationshipId = feature.get('links')[0].id;
// console.log("aaa", linkedRelationshipId);
//
// // get the actual spot
// return SpotsFactory.getSpotId(linkedRelationshipId).then(function(spot) {
//
// // we only care about orientations linkages at this point
// if (spot.properties.type == "Orientation") {
//
// console.log("the spot is", spot);
//
// var dip = null;
// var plunge = null;
//
// // do we have a dip?
// if (typeof spot.properties.dip !== 'undefined') {
// dip = spot.properties.dip;
// }
//
// // do we have a plunge?
// if (typeof spot.properties.plunge !== 'undefined') {
// plunge = spot.properties.plunge;
// }
//
// var rotation = (dip || plunge) ? dip || plunge : 0;
//
// switch(contentModel) {
// case "Contact Outcrop":
// return icon.contact_outcrop(rotation);
// case "Fault Outcrop":
// return icon.fault_outcrop(rotation);
// default:
// // TODO: do we want to put a default image when everything fails?
// break;
// }
//
//
// }
//
//
//
//
// });
// }
};
return new ol.layer.Vector({
source: new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojson, {
featureProjection: 'EPSG:3857'
})
}),
title: geojson.properties.name,
style: function(feature, resolution) {
var styles = {
'Point': [
new ol.style.Style({
image: getIconForFeature(feature)
}),
new ol.style.Style({
text: textStyle(feature.values_.name)
})
],
'LineString': [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#000000",
width: 10
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#ff0000",
width: 8
})
}),
new ol.style.Style({
text: textStyle(feature.values_.name)
})
],
'Polygon': [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#000000",
width: 10
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: "#035339",
width: 8
})
}),
new ol.style.Style({
text: textStyle(feature.values_.name)
})
]
};
return styles[feature.getGeometry().getType()];
}
});
};
// Loop through all spots and create ol vector layers
SpotsFactory.all().then(function(spots) {
// wipe the array because we want to avoid duplicating the feature in the ol.Collection
featureLayer.getLayers().clear();
// get distinct groups and aggregate spots by group type
var spotGroup = _.groupBy(spots, function(spot) {
return spot.properties.type;
});
// go through each group and assign all the aggregates to the geojson feature
for (var key in spotGroup) {
if (spotGroup.hasOwnProperty(key)) {
// create a geojson to hold all the spots that fit the same spot type
var spotTypeLayer = {
type: 'FeatureCollection',
features: spotGroup[key],
properties: {
name: key + ' (' + spotGroup[key].length + ')'
}
};
// add the feature collection layer to the map
featureLayer.getLayers().push(geojsonToVectorLayer(spotTypeLayer));
}
}
});
map.on('touchstart', function(event) {
console.log("touch");
console.log(event);
});
// display popup on click
map.on('click', function(evt) {
console.log("map clicked");
// are we in draw mode? If so we dont want to display any popovers during draw mode
if (!draw) {
// where the user just clicked
var coordinate = evt.coordinate;
// clear any existing popovers
popup.hide();
var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
return feature;
}, this, function(layer) {
// we only want the layer where the spots are located
return (layer instanceof ol.layer.Vector) && layer.get('name') !== 'drawLayer' && layer.get('name') !== 'geolocationLayer';
});
var layer = map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
return layer;
}, this, function(layer) {
// we only want the layer where the spots are located
return (layer instanceof ol.layer.Vector) && layer.get('name') !== 'drawLayer' && layer.get('name') !== 'geolocationLayer';
});
// we need to check that we're not clicking on the geolocation layer
if (feature && layer.get('name') != 'geolocationLayer') {
// popup content
var content = '';
content += '<a href="#/app/spots/' + feature.get('id') + '/details"><b>' + feature.get('name') + '</b></a>';
content += '<br>';
content += '<small>' + feature.get('type') + '</small>';
content += '<small> (' + feature.getGeometry().getType() + ')</small>';
if (feature.get('strike') && feature.get('dip')) {
content += '<br>';
content += '<small>' + feature.get('strike') + '° strike / ' + feature.get('dip') + '° dip</small>';
}
if (feature.get('trend') && feature.get('plunge')) {
content += '<br>';
content += '<small>' + feature.get('trend') + '° trend / ' + feature.get('plunge') + '° plunge</small>';
}
// setup the popup position
popup.show(evt.coordinate, content);
}
}
});
var geolocationWatchId;
// Get current position
$scope.toggleLocation = function() {
if ($scope.locationOn === undefined || $scope.locationOn === false) {
$scope.locationOn = true;
} else {
$scope.locationOn = false;
}
if ($scope.locationOn) {
console.log("toggleLocation is now true");
$cordovaGeolocation.getCurrentPosition({
maximumAge: 0,
timeout: 10000,
enableHighAccuracy: true
})
.then(function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var altitude = position.coords.altitude;
var accuracy = position.coords.accuracy;
var heading = position.coords.heading;
var speed = position.coords.speed;
console.log("getLocation ", [lat, lng], "(accuracy: " + accuracy + ") (altitude: " + altitude + ") (heading: " + heading + ") (speed: " + speed + ")");
var newView = new ol.View({
center: ol.proj.transform([lng, lat], 'EPSG:4326', 'EPSG:3857'),
zoom: 18,
minZoom: 4
});
map.setView(newView);
}, function(err) {
$ionicPopup.alert({
title: 'Alert!',
template: "Unable to get location: " + err.message
});
});
geolocationWatchId = $cordovaGeolocation.watchPosition({
frequency: 1000,
timeout: 10000,
enableHighAccuracy: true // may cause errors if true
});
geolocationWatchId.then(
null,
function(err) {
$ionicPopup.alert({
title: 'Alert!',
template: "Unable to get location for geolocationWatchId: " + geolocationWatchId.watchID + " (" + err.message + ")"
});
// TODO: what do we do here?
},
function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var altitude = position.coords.altitude;
var accuracy = position.coords.accuracy;
var altitudeAccuracy = position.coords.altitudeAccuracy;
var heading = position.coords.heading;
var speed = position.coords.speed;
console.log("getLocation-watch ", [lat, lng], "(accuracy: " + accuracy + ") (altitude: " + altitude + ") (heading: " + heading + ") (speed: " + speed + ")");
// create a point feature and assign the lat/long to its geometry
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([lng, lat], 'EPSG:4326', 'EPSG:3857'))
});
// add addition geolocation data to the feature so we can recall it later
iconFeature.set('altitude', altitude);
iconFeature.set('accuracy', (accuracy === null) ? null : Math.floor(accuracy));
iconFeature.set('altitudeAccuracy', altitudeAccuracy);
iconFeature.set('heading', heading);
iconFeature.set('speed', (speed === null) ? null : Math.floor(speed));
var vectorSource = new ol.source.Vector({
features: [iconFeature]
});
geolocationLayer.setSource(vectorSource);
});
} else {
// locationOn must be false
console.log("toggleLocation is now false");
// clear geolocation watch
geolocationWatchId.clearWatch();
// clear the geolocation marker
geolocationLayer.setSource(new ol.source.Vector({}));
}
};
var groupSpots = function() {
// remove the layer switcher to avoid confusion with lasso and regular drawing
map.getControls().removeAt(3);
// remove the drawing tools to avoid confusion with lasso and regular drawing
map.getControls().removeAt(2);
// start the draw with freehand enabled
$scope.startDraw('Polygon', true);
};
/////////////////
// ACTIONSHEET
/////////////////
$scope.showActionsheet = function() {
$ionicActionSheet.show({
titleText: 'Map Actions',
buttons: [
{text: '<i class="icon ion-map"></i> Zoom to Extent of Spots'},
{text: '<i class="icon ion-archive"></i>Save Map for Offline Use'},
{text: '<i class="icon ion-grid"></i> Create a Grouping of Spots'}
],
cancelText: 'Cancel',
cancel: function () {
console.log('CANCELLED');
},
buttonClicked: function (index) {
console.log('BUTTON CLICKED', index);
switch(index) {
case 0:
$scope.zoomToSpotsExtent();
break;
case 1:
$scope.cacheOfflineTiles();
break;
case 2:
groupSpots();
break;
}
return true;
}
});
};
/////////////////
// MODALS
/////////////////
$ionicModal.fromTemplateUrl('templates/modals/pointModal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.pointModal = modal;
});
$ionicModal.fromTemplateUrl('templates/modals/lineModal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.lineModal = modal;
});
$ionicModal.fromTemplateUrl('templates/modals/polyModal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.polyModal = modal;
});
$scope.openModal = function(modal) {
$scope[modal].show();
};
$scope.closeModal = function() {
$scope.pointModal.hide();
$scope.lineModal.hide();
$scope.polyModal.hide();
};
//Cleanup the modal when we're done with it!
// Execute action on hide modal
$scope.$on('pointModal.hidden', function() {
$scope.pointModal.remove();
});
$scope.$on('lineModal.hidden', function() {
$scope.lineModal.remove();
});
$scope.$on('polyModal.hidden', function() {
$scope.polyModal.remove();
});
});
| disabled content dragging back to ionic side menu
| www/js/controllers/map.js | disabled content dragging back to ionic side menu | <ide><path>ww/js/controllers/map.js
<ide> $ionicModal,
<ide> $ionicPopup,
<ide> $ionicActionSheet,
<add> $ionicSideMenuDelegate,
<ide> NewSpot,
<ide> MapView,
<ide> OfflineTilesFactory,
<ide> ViewExtentFactory,
<ide> ImagesFactory,
<ide> MapLayerFactory) {
<add>
<add> // disable dragging back to ionic side menu because this affects drawing tools
<add> $ionicSideMenuDelegate.canDragContent(false);
<ide>
<ide> // ol3 map
<ide> var map; |
|
Java | apache-2.0 | 85fea1268c388ccde71379efa0abdfe90870b7d4 | 0 | xiaomeixw/DanmakuFlameMaster,zzuli4519/DanmakuFlameMaster,zzhopen/DanmakuFlameMaster,mowangdk/DanmakuFlameMaster,xabad/DanmakuFlameMaster,Bilibili/DanmakuFlameMaster,Jaeandroid/DanmakuFlameMaster,java02014/DanmakuFlameMaster,vfs1234/DanmakuFlameMaster,kmfish/DanmakuFlameMaster,PC-ai/DanmakuFlameMaster,tsdl2013/DanmakuFlameMaster,yoyojacky/DanmakuFlameMaster,lcj1005/DanmakuFlameMaster,winiceo/DanmakuFlameMaster,AbooJan/DanmakuFlameMaster,leerduo/DanmakuFlameMaster,ctiao/DanmakuFlameMaster,jwzhangjie/DanmakuFlameMaster,GeekHades/DanmakuFlameMaster,jackeychens/DanmakuFlameMaster,Suninus/DanmakuFlameMaster,liuyingwen/DanmakuFlameMaster,xyczero/DanmakuFlameMaster,dersoncheng/DanmakuFlameMaster,chenquanjun/DanmakuFlameMaster,happycodinggirl/DanmakuFlameMaster,wangkang0627/DanmakuFlameMaster,10045125/DanmakuFlameMaster,hgl888/DanmakuFlameMaster,cgpllx/DanmakuFlameMaster,leglars/DanmakuFlameMaster,PenguinK/DanmakuFlameMaster,chuangWu/DanmakuFlameMaster,yangpeiyong/DanmakuFlameMaster,guoxiaojun001/DanmakuFlameMaster,whstudy/DanmakuFlameMaster,bajian/DanmakuFlameMaster,msdgwzhy6/DanmakuFlameMaster,wen14148/DanmakuFlameMaster | /*
* Copyright (C) 2013 Chen Hui <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package master.flame.danmaku.danmaku.model.android;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.text.TextPaint;
import master.flame.danmaku.danmaku.model.AlphaValue;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDisplayer;
import java.util.HashMap;
import java.util.Map;
/**
* Created by ch on 13-7-5.
*/
public class AndroidDisplayer implements IDisplayer {
private Camera camera = new Camera();
private Matrix matrix = new Matrix();
private final static HashMap<Float,Float> TextHeightCache = new HashMap<Float,Float>(); // thread safe is not Necessary
private static float sLastScaleTextSize;
private static Map<Float,Float> cachedScaleSize = new HashMap<Float, Float>(10);
@SuppressWarnings("unused")
private int HIT_CACHE_COUNT = 0;
@SuppressWarnings("unused")
private int NO_CACHE_COUNT = 0;
public static TextPaint PAINT;
private static Paint ALPHA_PAINT;
private static Paint UNDERLINE_PAINT;
/**
* 下划线高度
*/
public static int UNDERLINE_HEIGHT = 4;
/**
* 开启阴影,可动态改变
*/
public static boolean CONFIG_HAS_SHADOW = true;
private static boolean HAS_SHADOW = CONFIG_HAS_SHADOW;
/**
* 开启描边,可动态改变
*/
public static boolean CONFIG_HAS_STROKE = false;
private static boolean HAS_STROKE = CONFIG_HAS_STROKE;
/**
* 开启抗锯齿,可动态改变
*/
public static boolean CONFIG_ANTI_ALIAS = true;
private static boolean ANTI_ALIAS = CONFIG_ANTI_ALIAS;
static {
PAINT = new TextPaint();
PAINT.setStrokeWidth(3.5f);
ALPHA_PAINT = new Paint();
UNDERLINE_PAINT = new Paint();
UNDERLINE_PAINT.setStrokeWidth(UNDERLINE_HEIGHT);
UNDERLINE_PAINT.setStyle(Style.STROKE);
}
public static void setTypeFace(Typeface font){
if(PAINT!=null)
PAINT.setTypeface(font);
}
public static void setPaintStorkeWidth(float s){
PAINT.setStrokeWidth(s);
}
public static void setFakeBoldText(boolean fakeBoldText){
PAINT.setFakeBoldText(fakeBoldText);
}
public Canvas canvas;
public int width;
public int height;
public float density = 1;
public int densityDpi = 160;
public float scaledDensity = 1;
public int slopPixel = 0;
public void update(Canvas c) {
canvas = c;
if (c != null) {
width = c.getWidth();
height = c.getHeight();
}
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public float getDensity() {
return density;
}
@Override
public int getDensityDpi() {
return densityDpi;
}
@Override
public void draw(BaseDanmaku danmaku) {
float top = danmaku.getTop();
float left = danmaku.getLeft();
int paintHeight = (int)danmaku.paintHeight;
if (danmaku.getType() == BaseDanmaku.TYPE_FIX_BOTTOM) {
top = height - top - paintHeight;
}
if (canvas != null) {
Paint alphaPaint = null;
boolean needRestore = false;
if (danmaku.getType() == BaseDanmaku.TYPE_SPECIAL) {
if (danmaku.getAlpha() == AlphaValue.TRANSPARENT) {
return;
}
if (danmaku.rotationZ != 0 || danmaku.rotationY != 0) {
saveCanvas(danmaku, canvas, left, top);
needRestore = true;
}
int alpha = danmaku.getAlpha();
if ( alpha != AlphaValue.MAX) {
alphaPaint = ALPHA_PAINT;
alphaPaint.setAlpha(danmaku.getAlpha());
}
}
// skip drawing when danmaku is transparent
if(alphaPaint!=null && alphaPaint.getAlpha()== AlphaValue.TRANSPARENT){
return;
}
// drawing cache
boolean cacheDrawn = false;
if (danmaku.hasDrawingCache()) {
DrawingCacheHolder holder = ((DrawingCache) danmaku.cache).get();
if (holder != null && holder.bitmap != null) {
canvas.drawBitmap(holder.bitmap, left, top, alphaPaint);
cacheDrawn = true;
}
}
if (!cacheDrawn) {
if (alphaPaint != null) {
PAINT.setAlpha(alphaPaint.getAlpha());
} else {
resetPaintAlpha(PAINT);
}
drawDanmaku(danmaku, canvas, left, top, true);
}
if (needRestore) {
restoreCanvas(canvas);
}
}
}
private void resetPaintAlpha(Paint paint) {
if (paint.getAlpha() != AlphaValue.MAX) {
paint.setAlpha(AlphaValue.MAX);
}
}
private void restoreCanvas(Canvas canvas) {
canvas.restore();
}
private int saveCanvas(BaseDanmaku danmaku, Canvas canvas, float left, float top) {
camera.save();
camera.rotateY(-danmaku.rotationY);
camera.rotateZ(-danmaku.rotationZ);
camera.getMatrix(matrix);
matrix.preTranslate(-left, -top);
matrix.postTranslate(left, top);
camera.restore();
int count = canvas.save();
canvas.concat(matrix);
return count;
}
public static void drawDanmaku(BaseDanmaku danmaku, Canvas canvas, float left, float top,
boolean quick) {
if (quick) {
HAS_STROKE = false;
HAS_SHADOW = false;
ANTI_ALIAS = false;
} else {
HAS_STROKE = CONFIG_HAS_STROKE;
HAS_SHADOW = CONFIG_HAS_SHADOW;
ANTI_ALIAS = CONFIG_ANTI_ALIAS;
}
TextPaint paint = getPaint(danmaku);
if (danmaku.lines != null) {
String[] lines = danmaku.lines;
if (lines.length == 1) {
if (HAS_STROKE){
applyPaintConfig(danmaku, paint, true);
canvas.drawText(lines[0], left, top - paint.ascent(), paint);
}
applyPaintConfig(danmaku, paint, false);
canvas.drawText(lines[0], left, top - paint.ascent(), paint);
} else {
applyPaintConfig(danmaku, paint, false);
Float textHeight = getTextHeight(paint);
for (int t = 0; t < lines.length; t++) {
if (lines[t].length() > 0) {
canvas.drawText(lines[t], left,
t * textHeight + top - paint.ascent(), paint);
}
}
}
} else {
if (HAS_STROKE){
applyPaintConfig(danmaku, paint, true);
canvas.drawText(danmaku.text, left, top - paint.ascent(), paint);
}
applyPaintConfig(danmaku, paint, false);
canvas.drawText(danmaku.text, left, top - paint.ascent(), paint);
}
// draw underline
if (danmaku.underlineColor != 0) {
Paint linePaint = getUnderlinePaint(danmaku);
float bottom = top + danmaku.paintHeight - UNDERLINE_HEIGHT;
canvas.drawLine(left, bottom, left + danmaku.paintWidth, bottom, linePaint);
}
}
public static Paint getUnderlinePaint(BaseDanmaku danmaku){
UNDERLINE_PAINT.setColor(danmaku.underlineColor);
return UNDERLINE_PAINT;
}
public static TextPaint getPaint(BaseDanmaku danmaku) {
PAINT.setTextSize(danmaku.textSize);
applyTextScaleConfig(danmaku, PAINT);
PAINT.setAntiAlias(ANTI_ALIAS);
if (HAS_SHADOW) {
PAINT.setShadowLayer(3.0f, 0, 0, danmaku.textShadowColor);
} else {
PAINT.clearShadowLayer();
}
return PAINT;
}
private static void applyPaintConfig(BaseDanmaku danmaku, Paint paint,boolean stroke) {
if (DanmakuGlobalConfig.DEFAULT.isTranslucent) {
if(stroke){
paint.setStyle(Style.STROKE);
int color = (danmaku.textShadowColor & 0x00FFFFFF) | (DanmakuGlobalConfig.DEFAULT.transparency<<24);
paint.setColor(color);
}else{
paint.setStyle(Style.FILL);
int color = (danmaku.textColor & 0x00FFFFFF) | (DanmakuGlobalConfig.DEFAULT.transparency<<24);
paint.setColor(color);
}
paint.setAlpha(DanmakuGlobalConfig.DEFAULT.transparency);
} else {
if(stroke){
paint.setStyle(Style.STROKE);
paint.setColor(danmaku.textShadowColor);
}else{
paint.setStyle(Style.FILL);
paint.setColor(danmaku.textColor);
}
paint.setAlpha(AlphaValue.MAX);
}
}
private static void applyTextScaleConfig(BaseDanmaku danmaku, Paint paint) {
if (!DanmakuGlobalConfig.DEFAULT.isTextScaled) {
return;
}
Float size = cachedScaleSize.get(danmaku.textSize);
if (size == null || sLastScaleTextSize != DanmakuGlobalConfig.DEFAULT.scaleTextSize) {
sLastScaleTextSize = DanmakuGlobalConfig.DEFAULT.scaleTextSize;
size = Float.valueOf(danmaku.textSize * DanmakuGlobalConfig.DEFAULT.scaleTextSize);
cachedScaleSize.put(danmaku.textSize, size);
}
paint.setTextSize(size.floatValue());
}
@Override
public void measure(BaseDanmaku danmaku) {
TextPaint paint = getPaint(danmaku);
if (HAS_STROKE) {
applyPaintConfig(danmaku, paint, true);
}
calcPaintWH(danmaku, paint);
if (HAS_STROKE) {
applyPaintConfig(danmaku, paint, false);
}
}
private void calcPaintWH(BaseDanmaku danmaku, TextPaint paint) {
float w = 0;
Float textHeight = getTextHeight(paint);
if (danmaku.lines == null) {
w = paint.measureText(danmaku.text);
danmaku.paintWidth = w;
danmaku.paintHeight = textHeight;
return;
}
for(String tempStr : danmaku.lines){
if (tempStr.length() > 0) {
float tr = paint.measureText(tempStr);
w = Math.max(tr, w);
}
}
danmaku.paintWidth = w;
danmaku.paintHeight = danmaku.lines.length * textHeight;
}
private static Float getTextHeight(TextPaint paint) {
Float textSize = paint.getTextSize();
Float textHeight = TextHeightCache.get(textSize);
if(textHeight == null){
Paint.FontMetrics fontMetrics = paint.getFontMetrics();
textHeight = fontMetrics.descent - fontMetrics.ascent + fontMetrics.leading;
TextHeightCache.put(textSize, textHeight);
}
return textHeight;
}
public static void clearTextHeightCache(){
TextHeightCache.clear();
cachedScaleSize.clear();
}
@Override
public float getScaledDensity() {
return scaledDensity;
}
}
| DanmakuFlameMaster/src/main/java/master/flame/danmaku/danmaku/model/android/AndroidDisplayer.java | /*
* Copyright (C) 2013 Chen Hui <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package master.flame.danmaku.danmaku.model.android;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.Log;
import master.flame.danmaku.danmaku.model.AlphaValue;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDisplayer;
import java.util.HashMap;
import java.util.Map;
/**
* Created by ch on 13-7-5.
*/
public class AndroidDisplayer implements IDisplayer {
private Camera camera = new Camera();
private Matrix matrix = new Matrix();
private final static HashMap<Float,Float> TextHeightCache = new HashMap<Float,Float>(); // thread safe is not Necessary
private static float sLastScaleTextSize;
private static Map<Float,Float> cachedScaleSize = new HashMap<Float, Float>(10);
@SuppressWarnings("unused")
private int HIT_CACHE_COUNT = 0;
@SuppressWarnings("unused")
private int NO_CACHE_COUNT = 0;
public static TextPaint PAINT;
private static Paint ALPHA_PAINT;
private static Paint UNDERLINE_PAINT;
/**
* 下划线高度
*/
public static int UNDERLINE_HEIGHT = 4;
/**
* 开启阴影,可动态改变
*/
public static boolean CONFIG_HAS_SHADOW = true;
private static boolean HAS_SHADOW = CONFIG_HAS_SHADOW;
/**
* 开启描边,可动态改变
*/
public static boolean CONFIG_HAS_STROKE = false;
private static boolean HAS_STROKE = CONFIG_HAS_STROKE;
/**
* 开启抗锯齿,可动态改变
*/
public static boolean CONFIG_ANTI_ALIAS = true;
private static boolean ANTI_ALIAS = CONFIG_ANTI_ALIAS;
static {
PAINT = new TextPaint();
PAINT.setStrokeWidth(3.5f);
ALPHA_PAINT = new Paint();
UNDERLINE_PAINT = new Paint();
UNDERLINE_PAINT.setStrokeWidth(UNDERLINE_HEIGHT);
UNDERLINE_PAINT.setStyle(Style.STROKE);
}
public static void setTypeFace(Typeface font){
if(PAINT!=null)
PAINT.setTypeface(font);
}
public static void setPaintStorkeWidth(float s){
PAINT.setStrokeWidth(s);
}
public static void setFakeBoldText(boolean fakeBoldText){
PAINT.setFakeBoldText(fakeBoldText);
}
public Canvas canvas;
public int width;
public int height;
public float density = 1;
public int densityDpi = 160;
public float scaledDensity = 1;
public int slopPixel = 0;
public void update(Canvas c) {
canvas = c;
if (c != null) {
width = c.getWidth();
height = c.getHeight();
}
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public float getDensity() {
return density;
}
@Override
public int getDensityDpi() {
return densityDpi;
}
@Override
public void draw(BaseDanmaku danmaku) {
float top = danmaku.getTop();
float left = danmaku.getLeft();
int paintHeight = (int)danmaku.paintHeight;
if (danmaku.getType() == BaseDanmaku.TYPE_FIX_BOTTOM) {
top = height - top - paintHeight;
}
if (canvas != null) {
Paint alphaPaint = null;
boolean needRestore = false;
if (danmaku.getType() == BaseDanmaku.TYPE_SPECIAL) {
if (danmaku.getAlpha() == AlphaValue.TRANSPARENT) {
return;
}
if (danmaku.rotationZ != 0 || danmaku.rotationY != 0) {
saveCanvas(danmaku, canvas, left, top);
needRestore = true;
}
int alpha = danmaku.getAlpha();
if ( alpha != AlphaValue.MAX) {
alphaPaint = ALPHA_PAINT;
alphaPaint.setAlpha(danmaku.getAlpha());
}
}
// skip drawing when danmaku is transparent
if(alphaPaint!=null && alphaPaint.getAlpha()== AlphaValue.TRANSPARENT){
return;
}
// drawing cache
boolean cacheDrawn = false;
if (danmaku.hasDrawingCache()) {
DrawingCacheHolder holder = ((DrawingCache) danmaku.cache).get();
if (holder != null && holder.bitmap != null) {
canvas.drawBitmap(holder.bitmap, left, top, alphaPaint);
cacheDrawn = true;
}
}
if (!cacheDrawn) {
if (alphaPaint != null) {
PAINT.setAlpha(alphaPaint.getAlpha());
} else {
resetPaintAlpha(PAINT);
}
drawDanmaku(danmaku, canvas, left, top, true);
}
if (needRestore) {
restoreCanvas(canvas);
}
}
}
private void resetPaintAlpha(Paint paint) {
if (paint.getAlpha() != AlphaValue.MAX) {
paint.setAlpha(AlphaValue.MAX);
}
}
private void restoreCanvas(Canvas canvas) {
canvas.restore();
}
private int saveCanvas(BaseDanmaku danmaku, Canvas canvas, float left, float top) {
camera.save();
camera.rotateY(-danmaku.rotationY);
camera.rotateZ(-danmaku.rotationZ);
camera.getMatrix(matrix);
matrix.preTranslate(-left, -top);
matrix.postTranslate(left, top);
camera.restore();
int count = canvas.save();
canvas.concat(matrix);
return count;
}
public static void drawDanmaku(BaseDanmaku danmaku, Canvas canvas, float left, float top,
boolean quick) {
if (quick) {
HAS_STROKE = false;
HAS_SHADOW = false;
ANTI_ALIAS = false;
} else {
HAS_STROKE = CONFIG_HAS_STROKE;
HAS_SHADOW = CONFIG_HAS_SHADOW;
ANTI_ALIAS = CONFIG_ANTI_ALIAS;
}
TextPaint paint = getPaint(danmaku);
if (danmaku.lines != null) {
String[] lines = danmaku.lines;
if (lines.length == 1) {
if (HAS_STROKE){
applyPaintConfig(danmaku, paint, true);
canvas.drawText(lines[0], left, top - paint.ascent(), paint);
}
applyPaintConfig(danmaku, paint, false);
canvas.drawText(lines[0], left, top - paint.ascent(), paint);
} else {
applyPaintConfig(danmaku, paint, false);
Float textHeight = getTextHeight(paint);
for (int t = 0; t < lines.length; t++) {
if (lines[t].length() > 0) {
canvas.drawText(lines[t], left,
t * textHeight + top - paint.ascent(), paint);
}
}
}
} else {
if (HAS_STROKE){
applyPaintConfig(danmaku, paint, true);
canvas.drawText(danmaku.text, left, top - paint.ascent(), paint);
}
applyPaintConfig(danmaku, paint, false);
canvas.drawText(danmaku.text, left, top - paint.ascent(), paint);
}
// draw underline
if (danmaku.underlineColor != 0) {
Paint linePaint = getUnderlinePaint(danmaku);
float bottom = top + danmaku.paintHeight - UNDERLINE_HEIGHT;
canvas.drawLine(left, bottom, left + danmaku.paintWidth, bottom, linePaint);
}
}
public static Paint getUnderlinePaint(BaseDanmaku danmaku){
UNDERLINE_PAINT.setColor(danmaku.underlineColor);
return UNDERLINE_PAINT;
}
public static TextPaint getPaint(BaseDanmaku danmaku) {
PAINT.setTextSize(danmaku.textSize);
applyTextScaleConfig(danmaku, PAINT);
PAINT.setAntiAlias(ANTI_ALIAS);
if (HAS_SHADOW) {
PAINT.setShadowLayer(3.0f, 0, 0, danmaku.textShadowColor);
} else {
PAINT.clearShadowLayer();
}
return PAINT;
}
private static void applyPaintConfig(BaseDanmaku danmaku, Paint paint,boolean stroke) {
if (DanmakuGlobalConfig.DEFAULT.isTranslucent) {
if(stroke){
paint.setStyle(Style.STROKE);
int color = (danmaku.textShadowColor & 0x00FFFFFF) | (DanmakuGlobalConfig.DEFAULT.transparency<<24);
paint.setColor(color);
}else{
paint.setStyle(Style.FILL);
int color = (danmaku.textColor & 0x00FFFFFF) | (DanmakuGlobalConfig.DEFAULT.transparency<<24);
paint.setColor(color);
}
paint.setAlpha(DanmakuGlobalConfig.DEFAULT.transparency);
} else {
if(stroke){
paint.setStyle(Style.STROKE);
paint.setColor(danmaku.textShadowColor);
}else{
paint.setStyle(Style.FILL);
paint.setColor(danmaku.textColor);
}
paint.setAlpha(AlphaValue.MAX);
}
}
private static void applyTextScaleConfig(BaseDanmaku danmaku, Paint paint) {
if (!DanmakuGlobalConfig.DEFAULT.isTextScaled) {
return;
}
Float size = cachedScaleSize.get(danmaku.textSize);
if (size == null || sLastScaleTextSize != DanmakuGlobalConfig.DEFAULT.scaleTextSize) {
sLastScaleTextSize = DanmakuGlobalConfig.DEFAULT.scaleTextSize;
size = Float.valueOf(danmaku.textSize * DanmakuGlobalConfig.DEFAULT.scaleTextSize);
cachedScaleSize.put(danmaku.textSize, size);
} else {
Log.i("====", "get size from cache");
}
paint.setTextSize(size.floatValue());
}
@Override
public void measure(BaseDanmaku danmaku) {
TextPaint paint = getPaint(danmaku);
if (HAS_STROKE) {
applyPaintConfig(danmaku, paint, true);
}
calcPaintWH(danmaku, paint);
if (HAS_STROKE) {
applyPaintConfig(danmaku, paint, false);
}
}
private void calcPaintWH(BaseDanmaku danmaku, TextPaint paint) {
float w = 0;
Float textHeight = getTextHeight(paint);
if (danmaku.lines == null) {
w = paint.measureText(danmaku.text);
danmaku.paintWidth = w;
danmaku.paintHeight = textHeight;
return;
}
for(String tempStr : danmaku.lines){
if (tempStr.length() > 0) {
float tr = paint.measureText(tempStr);
w = Math.max(tr, w);
}
}
danmaku.paintWidth = w;
danmaku.paintHeight = danmaku.lines.length * textHeight;
}
private static Float getTextHeight(TextPaint paint) {
Float textSize = paint.getTextSize();
Float textHeight = TextHeightCache.get(textSize);
if(textHeight == null){
Paint.FontMetrics fontMetrics = paint.getFontMetrics();
textHeight = fontMetrics.descent - fontMetrics.ascent + fontMetrics.leading;
TextHeightCache.put(textSize, textHeight);
}
return textHeight;
}
public static void clearTextHeightCache(){
TextHeightCache.clear();
cachedScaleSize.clear();
}
@Override
public float getScaledDensity() {
return scaledDensity;
}
}
| remove log
| DanmakuFlameMaster/src/main/java/master/flame/danmaku/danmaku/model/android/AndroidDisplayer.java | remove log | <ide><path>anmakuFlameMaster/src/main/java/master/flame/danmaku/danmaku/model/android/AndroidDisplayer.java
<ide> import android.graphics.Paint.Style;
<ide> import android.graphics.Typeface;
<ide> import android.text.TextPaint;
<del>import android.util.Log;
<ide>
<ide> import master.flame.danmaku.danmaku.model.AlphaValue;
<ide> import master.flame.danmaku.danmaku.model.BaseDanmaku;
<ide> sLastScaleTextSize = DanmakuGlobalConfig.DEFAULT.scaleTextSize;
<ide> size = Float.valueOf(danmaku.textSize * DanmakuGlobalConfig.DEFAULT.scaleTextSize);
<ide> cachedScaleSize.put(danmaku.textSize, size);
<del> } else {
<del> Log.i("====", "get size from cache");
<ide> }
<ide> paint.setTextSize(size.floatValue());
<ide> } |
|
Java | bsd-3-clause | 17f874b63ae9a70e44b65ebf92e30af09b6ef175 | 0 | zygm0nt/jcabi-github,cezarykluczynski/jcabi-github,pecko/jcabi-github,cvrebert/typed-github,shelan/jcabi-github,YamStranger/jcabi-github,prondzyn/jcabi-github | /**
* Copyright (c) 2013-2014, jcabi.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) 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. 3) Neither the name of the jcabi.com 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 HOLDER 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 com.jcabi.github.mock;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.github.Github;
import com.jcabi.github.Organizations;
import com.jcabi.github.PublicKeys;
import com.jcabi.github.User;
import com.jcabi.github.UserEmails;
import java.io.IOException;
import javax.json.JsonObject;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.xembly.Directives;
/**
* Github user.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 0.5
* @todo #2:30min Organizations of a user.
* Let's implements a new method organizations(),
* which should return a mock instance of interface Organisations.
*/
@Immutable
@Loggable(Loggable.DEBUG)
@ToString
@EqualsAndHashCode(of = { "storage", "self" })
final class MkUser implements User {
/**
* Storage.
*/
private final transient MkStorage storage;
/**
* Login of the user logged in.
*/
private final transient String self;
/**
* Public ctor.
* @param stg Storage
* @param login User to login
* @throws IOException If there is any I/O problem
*/
MkUser(
@NotNull(message = "stg can't be NULL") final MkStorage stg,
@NotNull(message = "login can't be NULL") final String login
) throws IOException {
this.storage = stg;
this.self = login;
this.storage.apply(
new Directives().xpath(
String.format("/github/users[not(user[login='%s'])]", login)
).add("user").add("login").set(login)
);
}
@Override
@NotNull(message = "github is never NULL")
public Github github() {
return new MkGithub(this.storage, this.self);
}
@Override
@NotNull(message = "login is never NULL")
public String login() {
return this.self;
}
@Override
@NotNull(message = "orgs is never NULL")
public Organizations organizations() {
try {
return new MkOrganizations(storage, self);
} catch (final IOException ex) {
throw new IllegalStateException(ex);
}
}
@Override
@NotNull(message = "public keys is never NULL")
public PublicKeys keys() {
try {
return new MkPublicKeys(this.storage, this.self);
} catch (final IOException ex) {
throw new IllegalStateException(ex);
}
}
@Override
@NotNull(message = "emails is never NULL")
public UserEmails emails() {
try {
return new MkUserEmails(this.storage, this.self);
} catch (final IOException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public void patch(
@NotNull(message = "json can't be NULL") final JsonObject json
) throws IOException {
new JsonPatch(this.storage).patch(this.xpath(), json);
}
@Override
@NotNull(message = "JSON is never NULL")
public JsonObject json() throws IOException {
return new JsonNode(
this.storage.xml().nodes(this.xpath()).get(0)
).json();
}
/**
* XPath of this element in XML tree.
* @return XPath
*/
@NotNull(message = "Xpath is never NULL")
private String xpath() {
return String.format("/github/users/user[login='%s']", this.self);
}
}
| src/main/java/com/jcabi/github/mock/MkUser.java | /**
* Copyright (c) 2013-2014, jcabi.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) 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. 3) Neither the name of the jcabi.com 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 HOLDER 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 com.jcabi.github.mock;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.github.Github;
import com.jcabi.github.Organizations;
import com.jcabi.github.PublicKeys;
import com.jcabi.github.User;
import com.jcabi.github.UserEmails;
import java.io.IOException;
import javax.json.JsonObject;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.xembly.Directives;
/**
* Github user.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 0.5
* @todo #2:30min Organizations of a user.
* Let's implements a new method organizations(),
* which should return a mock instance of interface Organisations.
*/
@Immutable
@Loggable(Loggable.DEBUG)
@ToString
@EqualsAndHashCode(of = { "storage", "self" })
final class MkUser implements User {
/**
* Storage.
*/
private final transient MkStorage storage;
/**
* Login of the user logged in.
*/
private final transient String self;
/**
* Public ctor.
* @param stg Storage
* @param login User to login
* @throws IOException If there is any I/O problem
*/
MkUser(
@NotNull(message = "stg can't be NULL") final MkStorage stg,
@NotNull(message = "login can't be NULL") final String login
) throws IOException {
this.storage = stg;
this.self = login;
this.storage.apply(
new Directives().xpath(
String.format("/github/users[not(user[login='%s'])]", login)
).add("user").add("login").set(login)
);
}
@Override
@NotNull(message = "github is never NULL")
public Github github() {
return new MkGithub(this.storage, this.self);
}
@Override
@NotNull(message = "login is never NULL")
public String login() {
return this.self;
}
@Override
@NotNull(message = "orgs is never NULL")
public Organizations organizations() {
return null;
}
@Override
@NotNull(message = "public keys is never NULL")
public PublicKeys keys() {
try {
return new MkPublicKeys(this.storage, this.self);
} catch (final IOException ex) {
throw new IllegalStateException(ex);
}
}
@Override
@NotNull(message = "emails is never NULL")
public UserEmails emails() {
try {
return new MkUserEmails(this.storage, this.self);
} catch (final IOException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public void patch(
@NotNull(message = "json can't be NULL") final JsonObject json
) throws IOException {
new JsonPatch(this.storage).patch(this.xpath(), json);
}
@Override
@NotNull(message = "JSON is never NULL")
public JsonObject json() throws IOException {
return new JsonNode(
this.storage.xml().nodes(this.xpath()).get(0)
).json();
}
/**
* XPath of this element in XML tree.
* @return XPath
*/
@NotNull(message = "Xpath is never NULL")
private String xpath() {
return String.format("/github/users/user[login='%s']", this.self);
}
}
| Implement MkUser.organizations()
| src/main/java/com/jcabi/github/mock/MkUser.java | Implement MkUser.organizations() | <ide><path>rc/main/java/com/jcabi/github/mock/MkUser.java
<ide> @Override
<ide> @NotNull(message = "orgs is never NULL")
<ide> public Organizations organizations() {
<del> return null;
<add> try {
<add> return new MkOrganizations(storage, self);
<add> } catch (final IOException ex) {
<add> throw new IllegalStateException(ex);
<add> }
<ide> }
<ide>
<ide> @Override |
|
JavaScript | apache-2.0 | 2de4d7adf1806d8126a151a3b1931d53d7ea6010 | 0 | tensorflow/tensorboard,ioeric/tensorboard,qiuminxu/tensorboard,shakedel/tensorboard,agrubb/tensorboard,qiuminxu/tensorboard,francoisluus/tensorboard-supervise,agrubb/tensorboard,ioeric/tensorboard,ioeric/tensorboard,qiuminxu/tensorboard,qiuminxu/tensorboard,ioeric/tensorboard,tensorflow/tensorboard,francoisluus/tensorboard-supervise,tensorflow/tensorboard,francoisluus/tensorboard-supervise,agrubb/tensorboard,francoisluus/tensorboard-supervise,shakedel/tensorboard,tensorflow/tensorboard,francoisluus/tensorboard-supervise,tensorflow/tensorboard,agrubb/tensorboard,tensorflow/tensorboard,shakedel/tensorboard,shakedel/tensorboard,shakedel/tensorboard,shakedel/tensorboard,ioeric/tensorboard,ioeric/tensorboard,agrubb/tensorboard,francoisluus/tensorboard-supervise,qiuminxu/tensorboard,agrubb/tensorboard,tensorflow/tensorboard,qiuminxu/tensorboard | /* Copyright 2015 The TensorFlow 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.
==============================================================================*/
var gulp = require('gulp');
var ts = require('gulp-typescript');
var typescript = require('typescript');
var gutil = require('gulp-util');
var filter = require('gulp-filter');
var merge = require('merge2');
var tsProject = ts.createProject('./tsconfig.json', {
typescript: typescript,
noExternalResolve: true, // opt-in for faster compilation!
});
module.exports = function() {
var isComponent = filter([
'components/tf-*/**/*.ts',
'components/vz-*/**/*.ts',
'typings/**/*.ts',
'components/plottable/plottable.d.ts'
]);
return tsProject.src()
.pipe(isComponent)
.pipe(ts(tsProject))
.js
.pipe(gulp.dest('.'));
}
| gulp_tasks/compile.js | /* Copyright 2015 The TensorFlow 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.
==============================================================================*/
var gulp = require('gulp');
var ts = require('gulp-typescript');
var typescript = require('typescript');
var gutil = require('gulp-util');
var filter = require('gulp-filter');
var merge = require('merge2');
var tsProject = ts.createProject('./tsconfig.json', {
typescript: typescript,
noExternalResolve: true, // opt-in for faster compilation!
});
module.exports = function() {
var isComponent = filter([
'components/tf-*/**/*.ts',
'components/vz-*/**/*.ts',
'typings/**/*.ts',
// TODO(danmane): add plottable to the typings registry after updating it
// and remove this.
'components/plottable/plottable.d.ts'
]);
return tsProject.src()
.pipe(isComponent)
.pipe(ts(tsProject))
.js
.pipe(gulp.dest('.'));
}
| Remove the plottable typings todo as it is currently a good solution
Change: 130777731
| gulp_tasks/compile.js | Remove the plottable typings todo as it is currently a good solution Change: 130777731 | <ide><path>ulp_tasks/compile.js
<ide> 'components/tf-*/**/*.ts',
<ide> 'components/vz-*/**/*.ts',
<ide> 'typings/**/*.ts',
<del> // TODO(danmane): add plottable to the typings registry after updating it
<del> // and remove this.
<ide> 'components/plottable/plottable.d.ts'
<ide> ]);
<ide> |
|
JavaScript | mit | 047b576f0f7e4d9645f5d65ad245d18275583de5 | 0 | bubbleboy14/cantools,bubbleboy14/cantools,bubbleboy14/cantools,bubbleboy14/cantools | /*
This class is used to generate a slider, which is a segmented,
directionally-constrained draggable DOM element.
The CT.slider.Slider constructor takes an options object, 'opts', which may
define any of several properties. These individual properties, as well as
the 'opts' object itself, are all optional.
### Definable properties are as follows:
- parent (default: document.body): DOM element in which to build the slider
- mode (default: 'peekaboo'): how to display each frame - 'peekaboo', 'chunk', 'menu', 'profile', or 'track'
- subMode (default: 'peekaboo'): which mode to use for chunk-mode frames ('peekaboo', 'menu', 'profile', 'track', 'custom')
- frameCb (default: null): frame generation callback ('custom' mode)
- defaultImg (default: undefined): fallback img for any frame mode
- img (default: undefined): panning background image for whole slider. also works per-chunk.
- tab (default: undefined): little thing to the side of the frame
- arrow (default: null): image for pointer arrow (falls back to pointy brackets)
- autoSlideInterval (default: 5000): how many milliseconds to wait before auto-sliding frames
- panDuration (default: autoSlideInterval): pan duration for background images
- translateDuration (default: 300): translation duration for frame advancement transition
- autoSlide (default: true): automatically proceed through frames (else, trigger later with .resume())
- visible (default: true): maps to visibility css property
- navButtons (default: true): include nav bubbles and arrows
- circular (default: false): allow shifting between 1st and last frames w/ nav buttons (arrows)
- pan (default: true): slow-pan frame background images
- translucentTeaser (default: true): translucent box around teaser text (otherwise opaque)
- startFrame (default: null): label (or index if frames are unlabeled) of frame to slide to initially (disables autoSlide)
- noStyle (default: false): if true, prevent carousel from overriding color/background rules
- bubblePosition (default: 'bottom'): where to position frame indicator bubbles ('top' or 'bottom')
- arrowPosition (default: 'middle'): where to position navigator arrows
- orientation (default: 'horizontal'): orientation for slider frames to arrange themselves
- keys (default: true): use arrow keys to navigate slider, as well as enter key for peekaboo transitions
- noEnter (default: false): disable enter key for peekaboo transitions
- frames (default: []): an array of items corresponding to the frames in the slider
The last one, 'frames', must be an array either of strings (interpreted
as image urls) or of data objects (processed in the addFrame function).
*/
CT.slider = {
other_dim: { height: "width", width: "height" },
other_orientation: { vertical: "horizontal", horizontal: "vertical" },
orientation2dim: { vertical: "height", horizontal: "width" },
orientation2abs: {
vertical: {
forward: "up",
backward: "down"
},
horizontal: {
forward: "left",
backward: "right"
}
}
};
CT.slider.Slider = CT.Class({
CLASSNAME: "CT.slider.Slider",
init: function(opts) {
this.opts = opts = CT.merge(opts, {
frames: [],
keys: true,
noEnter: false,
translateDuration: 300,
autoSlideInterval: 5000,
autoSlide: true,
visible: true,
navButtons: true,
startFrame: null,
circular: false,
pan: true,
noStyle: false,
translucentTeaser: true,
arrow: null,
parent: document.body,
frameCb: null,
mode: "peekaboo", // or 'menu' or 'profile' or 'chunk' or 'track' or 'custom'
subMode: "peekaboo", // or 'menu' or 'profile' or 'track'
orientation: "horizontal",
arrowPosition: "middle", // or "top" or "middle"
bubblePosition: "bottom" // or "top"
});
if (typeof opts.parent == "string")
opts.parent = CT.dom.id(opts.parent);
if (opts.frameCb) // only makes sense in custom mode
opts.mode = 'custom';
this.jumpers = {};
this.dimension = CT.slider.orientation2dim[opts.orientation];
this.circlesContainer = CT.dom.node("", "div",
"carousel-order-indicator " + opts.bubblePosition);
var bclass = "slider-btn hoverglow pointer sb-"
+ this.opts.arrowPosition + " sb-" + opts.orientation;
if (!opts.navButtons) {
bclass += " hider";
this.circlesContainer.classList.add("hider");
}
var pointerNode = function(forward) {
if (opts.arrow) {
var img = CT.dom.img(opts.arrow);
return forward ? img : CT.trans.invert(img);
}
return CT.dom.span(forward ? ">" : "<");
};
this.prevButton = CT.dom.div(CT.dom.div(pointerNode()),
bclass + " prv hidden");
this.nextButton = CT.dom.div(CT.dom.div(pointerNode(true)),
bclass + " nxt" + (opts.frames.length < 2 ? " hidden" : ""));
this.index = this.pos = 0;
this.container = CT.dom.div("",
"carousel-container full" + CT.slider.other_dim[this.dimension]);
var content = [
this.container,
this.circlesContainer,
this.prevButton,
this.nextButton
];
if (opts.img) {
var imgBack = CT.dom.div(CT.dom.img(opts.img, "abs"), "abs all0 noflow");
if (opts.pan) {
this.imgBackController = CT.trans.pan(imgBack.firstChild, {
duration: opts.panDuration || opts.autoSlideInterval
}, true);
} else {
CT.onload(function() {
CT.dom.cover(imgBack.firstChild);
}, imgBack.firstChild);
}
content.unshift(imgBack);
}
this.node = CT.dom.div(content, "carousel fullwidth fullheight"
+ (opts.visible ? "" : " hider") + (opts.noStyle ? " carousel-nostyle" : ""));
this.opts.parent.appendChild(this.node);
this.opts.frames.forEach(this.addFrame);
CT.gesture.listen("tap", this.prevButton, this.prevButtonCallback);
CT.gesture.listen("tap", this.nextButton, this.nextButtonCallback);
if (opts.keys) {
CT.key.on(opts.orientation == "horizontal" ?
"LEFT" : "UP", this.prevButtonCallback);
CT.key.on(opts.orientation == "horizontal" ?
"RIGHT" : "DOWN", this.nextButtonCallback);
}
if (opts.orientation == "vertical")
CT.gesture.listen("wheel", this.container, this.onWheel);
this.dragOpts = {
constraint: CT.slider.other_orientation[opts.orientation],
up: this.updatePosition,
interval: "auto"
};
CT.drag.makeDraggable(this.container, this.dragOpts);
if (opts.autoSlideInterval && opts.autoSlide && !opts.startFrame)
this.resume();
CT.gesture.listen("down", this.container, this.pause);
CT.onresize(this.trans);//, this.opts.parent);
this._reflow();
if (opts.startFrame in this.jumpers)
setTimeout(this.jumpers[opts.startFrame]); // wait one tick for inits
},
on: {
hide: function() {
this.imgBackController && this.imgBackController.pause();
this.container.childNodes[this.index].frame.on.hide();
},
show: function() {
this.imgBackController && this.imgBackController.resume();
this.container.childNodes[this.index].frame.on.show();
}
},
onWheel: function(pos, delta) {
if (delta > 0)
this.nextButtonCallback();
else
this.prevButtonCallback();
},
showNav: function() {
if (this.opts.navButtons) {
CT.trans.translate(this.prevButton, {
x: 0
});
CT.trans.translate(this.nextButton, {
x: 0
});
CT.trans.translate(this.circlesContainer, {
y: 0
});
}
if (this.opts.parent.slider)
this.opts.parent.slider.showNav();
},
hideNav: function() {
if (this.opts.navButtons) {
CT.trans.translate(this.prevButton, {
x: -200
});
CT.trans.translate(this.nextButton, {
x: 200
});
CT.trans.translate(this.circlesContainer, {
y: (this.opts.bubblePosition == "top") && -100 || 100
});
}
if (this.opts.parent.slider)
this.opts.parent.slider.hideNav();
},
show: function() {
this.node.classList.remove("hider");
this.on.show();
},
hide: function() {
this.node.classList.add("hider");
this.on.hide();
},
_reflow: function() {
CT.dom.mod({
targets: this.container.childNodes,
property: this.dimension,
value: (100 / this.container.childNodes.length) + "%"
});
this.container.style[this.dimension] = (this.opts.frames.length * 100) + "%";
},
resume: function() {
if (!this._autoSlide)
this._autoSlide = setInterval(this.autoSlideCallback, this.opts.autoSlideInterval);
},
pause: function() {
if (this._autoSlide) {
clearInterval(this._autoSlide);
this._autoSlide = null;
}
this.opts.parent.slider && this.opts.parent.slider.pause();
},
addFrame: function(frame, index) {
if (typeof frame == "string")
frame = { img: frame };
var circle = CT.dom.node(frame.label, "div",
"hoverglow pointer indicator-circle " +
(frame.label ? "labeled" : "unlabeled") + "-circle"),
jumper = this.jumpers[frame.label || index] = this.circleJump(index);
CT.gesture.listen("tap", circle, jumper);
this.circlesContainer.appendChild(circle);
this.container.appendChild((new CT.slider.Frame(frame, this)).node);
if (index == 0) {
circle.className += " active-circle";
this.activeCircle = circle;
if (!this.opts.parent.slider && !this.opts.startFrame) // exclude embedded slider
setTimeout(this.container.firstChild.frame.on.show, 500);
}
if (index == undefined) // ad-hoc frame
this._reflow();
},
circleJump: function(index) {
var f = function() {
this.pause();
this.updateIndicator(index);
this.trans();
}.bind(this);
return f;
},
updateIndicator: function(index) {
this.container.childNodes[this.index].frame.on.hide();
this.index = index;
this.container.childNodes[this.index].frame.on.show();
this.activeCircle.classList.remove('active-circle');
this.activeCircle = this.circlesContainer.childNodes[index];
this.activeCircle.classList.add('active-circle');
CT.dom[this.activeCircle.nextSibling ? "show" : "hide"](this.nextButton);
CT.dom[this.activeCircle.previousSibling ? "show" : "hide"](this.prevButton);
},
updatePosition: function(direction, force) {
var index = this.index, absdir = CT.drag._.dir2abs[direction],
cccnl = this.circlesContainer.childNodes.length;
if (CT.drag._.direction2orientation[direction] == this.opts.orientation) {
if (absdir == "forward" && (force || this.activeCircle.nextSibling))
index += 1;
else if (absdir == "backward" && (force || this.activeCircle.previousSibling))
index -= 1;
if (cccnl)
this.updateIndicator((index + cccnl) % cccnl);
} else if (this.opts.parent.slider)
this.opts.parent.slider.shift(direction, force);
},
trans: function() {
var opts = {}, axis = CT.drag._.orientation2axis[this.opts.orientation];
opts[axis] = this.container[axis + "Drag"] = -this.index
* CT.align[this.dimension](this.container) / this.container.childNodes.length;
opts.duration = this.opts.translateDuration;
CT.trans.translate(this.container, opts);
},
shift: function(direction, force) {
this.updatePosition(direction, force || this.opts.circular);
this.trans();
},
autoSlideCallback: function() {
this.shift(CT.slider.orientation2abs[this.opts.orientation].forward, true);
},
prevButtonCallback: function() {
this.pause();
this.shift(CT.slider.orientation2abs[this.opts.orientation].backward);
},
nextButtonCallback: function() {
this.pause();
this.shift(CT.slider.orientation2abs[this.opts.orientation].forward);
}
});
CT.slider.Frame = CT.Class({
CLASSNAME: "CT.slider.Frame",
on: { // overwritten by mode functions
show: function() {},
hide: function() {}
},
peekaboo: function() {
var opts = this.opts, node = this.node, slider = this.slider, pulser,
full = CT.dom.node(opts.content, "div", "big carousel-content-full"),
imageBack = CT.dom.node(CT.dom.img(opts.img || slider.opts.defaultImg, "abs"), "div", "w1 h1 noflow carousel-content-image"),
nodes = [ imageBack, full ];
var teaserTap = function() {
slider.pause();
node._retracted = !node._retracted;
if (node._retracted) {
CT.trans.resize(imageBack, {
width: "40%",
height: "30%",
cb: function() {
if (pulser) pulser.style.zIndex = 200;
}
});
CT.trans.trans({
node: teaser,
property: "left",
value: "10px"
});
CT.trans.trans({
node: teaser,
property: "top",
value: "0px"
});
slider.hideNav();
this.tab && this.tab.hide();
} else {
if (pulser) pulser.style.zIndex = 0;
CT.trans.resize(imageBack, {
width: "100%",
height: "100%"
});
CT.trans.trans({
node: teaser,
property: "left",
value: "22.5%"
});
CT.trans.trans({
node: teaser,
property: "top",
value: "100px"
});
slider.showNav();
this.tab && this.tab.show(slider.opts.parent);
}
};
if (slider.opts.pan) {
imageBack.controller = CT.trans.pan(imageBack.firstChild, {
duration: opts.panDuration || slider.opts.panDuration || slider.opts.autoSlideInterval
});
} else {
CT.onload(function() {
CT.dom.cover(imageBack.firstChild);
}, imageBack.firstChild);
}
if (opts.title || opts.blurb) {
var blurbNode = CT.dom.div(opts.blurb, "bigger"), teaser = CT.dom.div([
CT.dom.div(opts.title, "biggest"), blurbNode
], "carousel-content-teaser transparent hoverglow pointer cc-teaser-"
+ (slider.opts.translucentTeaser ? "trans" : "opaque"));
CT.dom.fit(blurbNode);
nodes.push(teaser);
}
if (opts.pulse) {
pulser = CT.dom.img(opts.pulse, "carousel-pulse pointer");
pulser.controller = CT.trans.pulse(pulser);
CT.gesture.listen("tap", pulser, teaserTap); // assume content exists
nodes.push(pulser);
}
this.on.show = function() {
if (opts.title || opts.blurb) {
CT.trans.fadeIn(teaser);
blurbNode.style.maxHeight = (teaser.parentNode.clientHeight - 200) + "px";
blurbNode.fit();
}
if (slider.opts.keys && !slider.opts.noEnter && teaser) // unreg somewhere?
CT.key.on("ENTER", teaserTap);
if (slider.opts.pan)
imageBack.controller.resume();
if (opts.pulse)
pulser.controller.resume();
if (this.tab)
this.tab.show(slider.opts.parent);
};
this.on.hide = function() {
if (opts.title || opts.blurb)
CT.trans.fadeOut(teaser);
if (node._retracted)
teaserTap();
if (slider.opts.pan)
imageBack.controller.pause();
if (opts.pulse)
pulser.controller.pause();
if (this.tab)
this.tab.hide();
};
CT.dom.addEach(node, nodes);
if (opts.content) // assume title/blurb exists
CT.gesture.listen("tap", teaser, teaserTap);
else if (opts.onclick)
CT.gesture.listen("tap", teaser, opts.onclick);
},
chunk: function() {
var slider = new CT.slider.Slider({
parent: this.node,
frames: this.opts.frames,
mode: this.opts.mode || this.slider.opts.subMode,
autoSlide: false,
img: this.opts.img,
pan: this.slider.opts.pan,
arrow: this.slider.opts.arrow,
startFrame: this.opts.startFrame,
defaultImg: this.slider.opts.defaultImg,
translucentTeaser: this.slider.opts.translucentTeaser,
orientation: CT.slider.other_orientation[this.slider.opts.orientation],
arrowPosition: "bottom"
}), parent = this.slider;
this.on.hide = slider.on.hide;
this.on.show = function() {
slider.on.show();
if (parent.opts.keys) {
CT.key.on(slider.opts.orientation == "horizontal" ?
"LEFT" : "UP", slider.prevButtonCallback);
CT.key.on(slider.opts.orientation == "horizontal" ?
"RIGHT" : "DOWN", slider.nextButtonCallback);
}
};
},
menu: function() {
var menu = new CT.modal.Modal({
transition: "slide",
noClose: true,
className: "round centered basicpopup above",
content: this.opts.buttons.map(function(d) {
var n = CT.dom.node([
CT.dom.node(d.label || d.page, "div", "biggest bold bottombordered"),
CT.dom.node(d.content)
], "div", "margined padded bordered round hoverglow pointer inline-block");
n.onclick = function() {
location = d.url || ("/" + d.page + ".html");
};
return n;
})
});
var logos = function(logo) {
var arr = [];
for (var i = 0; i < 5; i++)
arr.push(CT.dom.img(logo || this.slider.opts.defaultImg));
return arr;
};
this.node.appendChild(CT.dom.marquee(logos(this.opts.logo), "abs top0 h20p fullwidth"));
this.node.appendChild(CT.dom.marquee(logos(this.opts.logo), "abs bottom0 h20p fullwidth", "right"));
this.on.hide = menu.hide;
this.on.show = menu.show;
},
profile: function() {
var opts = CT.merge(this.opts, this.slider.opts, {
panDuration: this.slider.opts.autoSlideInterval,
controllerHook: this.on
});
opts.img = opts.img || this.slider.opts.defaultImg;
CT.dom.addContent(this.node, CT.layout.profile(opts));
},
track: function() { // add img!
var oz = this.opts, audio = CT.dom.audio(oz.src, true, false, false, function() {
playmod.hide();
}, this.slider.autoSlideCallback), playmod = CT.modal.modal("click to play!", function() {
audio.play();
}, {
noClose: true,
innerClass: "gigantic"
}, true, true), pause = function() {
audio.playing = false;
audio.pause();
playmod.hide();
}, resume = function() {
audio.playing = true;
audio.play().catch(playmod.show);
}, pauseResume = function() {
audio.playing ? pause() : resume();
};
this.on.hide = pause;
this.on.show = function() {
resume();
CT.key.on("SPACE", pauseResume);
if (oz.deepLink)
document.location.hash = encodeURI(oz.album + "|" + oz.song);
oz.onplay && oz.onplay(oz.album, oz.song);
};
CT.dom.addContent(this.node, CT.dom.div([
CT.dom.div(this.opts.song, "gigantic"),
CT.dom.div(this.opts.album, "biggerest"),
audio
], "full-center outlined"));
},
custom: function() {
CT.dom.addContent(this.node, this.slider.opts.frameCb(this.opts));
},
init: function(opts, slider) {
var mode = opts.mode || slider.opts.mode;
this.opts = opts;
this.node = CT.dom.div("", "carousel-content-container full"
+ CT.slider.other_dim[slider.dimension] + ((mode == "custom") ? " scroller" : ""));
this.node.frame = this;
this.slider = this.node.slider = slider;
if (slider.dimension == "width")
this.node.style.display = "inline-block";
var topts = opts.tab || slider.opts.tab;
if (topts) {
var tab = this.tab = new CT.modal.Modal({
content: topts.content,
center: false,
noClose: true,
className: "basicpopup abs rounder translucent above shiftall",
transition: "slide",
slide: {
origin: topts.origin
}
});
this.on.show = function() {
if (tab.isClear())
tab.set(topts.content);
tab.show(slider.opts.parent);
};
this.on.hide = tab.hide;
}
this[mode]();
}
}); | cantools/CT/slider.js | /*
This class is used to generate a slider, which is a segmented,
directionally-constrained draggable DOM element.
The CT.slider.Slider constructor takes an options object, 'opts', which may
define any of several properties. These individual properties, as well as
the 'opts' object itself, are all optional.
### Definable properties are as follows:
- parent (default: document.body): DOM element in which to build the slider
- mode (default: 'peekaboo'): how to display each frame - 'peekaboo', 'chunk', 'menu', 'profile', or 'track'
- subMode (default: 'peekaboo'): which mode to use for chunk-mode frames ('peekaboo', 'menu', 'profile', 'track', 'custom')
- frameCb (default: null): frame generation callback ('custom' mode)
- defaultImg (default: undefined): fallback img for any frame mode
- img (default: undefined): panning background image for whole slider. also works per-chunk.
- tab (default: undefined): little thing to the side of the frame
- arrow (default: null): image for pointer arrow (falls back to pointy brackets)
- autoSlideInterval (default: 5000): how many milliseconds to wait before auto-sliding frames
- panDuration (default: autoSlideInterval): pan duration for background images
- translateDuration (default: 300): translation duration for frame advancement transition
- autoSlide (default: true): automatically proceed through frames (else, trigger later with .resume())
- visible (default: true): maps to visibility css property
- navButtons (default: true): include nav bubbles and arrows
- circular (default: false): allow shifting between 1st and last frames w/ nav buttons (arrows)
- pan (default: true): slow-pan frame background images
- translucentTeaser (default: true): translucent box around teaser text (otherwise opaque)
- startFrame (default: null): label (or index if frames are unlabeled) of frame to slide to initially (disables autoSlide)
- noStyle (default: false): if true, prevent carousel from overriding color/background rules
- bubblePosition (default: 'bottom'): where to position frame indicator bubbles ('top' or 'bottom')
- arrowPosition (default: 'middle'): where to position navigator arrows
- orientation (default: 'horizontal'): orientation for slider frames to arrange themselves
- keys (default: true): use arrow keys to navigate slider, as well as enter key for peekaboo transitions
- noEnter (default: false): disable enter key for peekaboo transitions
- frames (default: []): an array of items corresponding to the frames in the slider
The last one, 'frames', must be an array either of strings (interpreted
as image urls) or of data objects (processed in the addFrame function).
*/
CT.slider = {
other_dim: { height: "width", width: "height" },
other_orientation: { vertical: "horizontal", horizontal: "vertical" },
orientation2dim: { vertical: "height", horizontal: "width" },
orientation2abs: {
vertical: {
forward: "up",
backward: "down"
},
horizontal: {
forward: "left",
backward: "right"
}
}
};
CT.slider.Slider = CT.Class({
CLASSNAME: "CT.slider.Slider",
init: function(opts) {
this.opts = opts = CT.merge(opts, {
frames: [],
keys: true,
noEnter: false,
translateDuration: 300,
autoSlideInterval: 5000,
autoSlide: true,
visible: true,
navButtons: true,
startFrame: null,
circular: false,
pan: true,
noStyle: false,
translucentTeaser: true,
arrow: null,
parent: document.body,
frameCb: null,
mode: "peekaboo", // or 'menu' or 'profile' or 'chunk' or 'track' or 'custom'
subMode: "peekaboo", // or 'menu' or 'profile' or 'track'
orientation: "horizontal",
arrowPosition: "middle", // or "top" or "middle"
bubblePosition: "bottom" // or "top"
});
if (typeof opts.parent == "string")
opts.parent = CT.dom.id(opts.parent);
if (opts.frameCb) // only makes sense in custom mode
opts.mode = 'custom';
this.jumpers = {};
this.dimension = CT.slider.orientation2dim[opts.orientation];
this.circlesContainer = CT.dom.node("", "div",
"carousel-order-indicator " + opts.bubblePosition);
var bclass = "slider-btn hoverglow pointer sb-"
+ this.opts.arrowPosition + " sb-" + opts.orientation;
if (!opts.navButtons) {
bclass += " hider";
this.circlesContainer.classList.add("hider");
}
var pointerNode = function(forward) {
if (opts.arrow) {
var img = CT.dom.img(opts.arrow);
return forward ? img : CT.trans.invert(img);
}
return CT.dom.span(forward ? ">" : "<");
};
this.prevButton = CT.dom.div(CT.dom.div(pointerNode()),
bclass + " prv hidden");
this.nextButton = CT.dom.div(CT.dom.div(pointerNode(true)),
bclass + " nxt" + (opts.frames.length < 2 ? " hidden" : ""));
this.index = this.pos = 0;
this.container = CT.dom.div("",
"carousel-container full" + CT.slider.other_dim[this.dimension]);
var content = [
this.container,
this.circlesContainer,
this.prevButton,
this.nextButton
];
if (opts.img) {
var imgBack = CT.dom.div(CT.dom.img(opts.img, "abs"), "abs all0 noflow");
if (opts.pan) {
this.imgBackController = CT.trans.pan(imgBack.firstChild, {
duration: opts.panDuration || opts.autoSlideInterval
}, true);
} else {
CT.onload(function() {
CT.dom.cover(imgBack.firstChild);
}, imgBack.firstChild);
}
content.unshift(imgBack);
}
this.node = CT.dom.div(content, "carousel fullwidth fullheight"
+ (opts.visible ? "" : " hider") + (opts.noStyle ? " carousel-nostyle" : ""));
this.opts.parent.appendChild(this.node);
this.opts.frames.forEach(this.addFrame);
CT.gesture.listen("tap", this.prevButton, this.prevButtonCallback);
CT.gesture.listen("tap", this.nextButton, this.nextButtonCallback);
if (opts.keys) {
CT.key.on(opts.orientation == "horizontal" ?
"LEFT" : "UP", this.prevButtonCallback);
CT.key.on(opts.orientation == "horizontal" ?
"RIGHT" : "DOWN", this.nextButtonCallback);
}
if (opts.orientation == "vertical")
CT.gesture.listen("wheel", this.container, this.onWheel);
this.dragOpts = {
constraint: CT.slider.other_orientation[opts.orientation],
up: this.updatePosition,
interval: "auto"
};
CT.drag.makeDraggable(this.container, this.dragOpts);
if (opts.autoSlideInterval && opts.autoSlide && !opts.startFrame)
this.resume();
CT.gesture.listen("down", this.container, this.pause);
CT.onresize(this.trans);//, this.opts.parent);
this._reflow();
if (opts.startFrame in this.jumpers)
setTimeout(this.jumpers[opts.startFrame]); // wait one tick for inits
},
on: {
hide: function() {
this.imgBackController && this.imgBackController.pause();
this.container.childNodes[this.index].frame.on.hide();
},
show: function() {
this.imgBackController && this.imgBackController.resume();
this.container.childNodes[this.index].frame.on.show();
}
},
onWheel: function(pos, delta) {
if (delta > 0)
this.nextButtonCallback();
else
this.prevButtonCallback();
},
showNav: function() {
if (this.opts.navButtons) {
CT.trans.translate(this.prevButton, {
x: 0
});
CT.trans.translate(this.nextButton, {
x: 0
});
CT.trans.translate(this.circlesContainer, {
y: 0
});
}
if (this.opts.parent.slider)
this.opts.parent.slider.showNav();
},
hideNav: function() {
if (this.opts.navButtons) {
CT.trans.translate(this.prevButton, {
x: -200
});
CT.trans.translate(this.nextButton, {
x: 200
});
CT.trans.translate(this.circlesContainer, {
y: (this.opts.bubblePosition == "top") && -100 || 100
});
}
if (this.opts.parent.slider)
this.opts.parent.slider.hideNav();
},
show: function() {
this.node.classList.remove("hider");
this.on.show();
},
hide: function() {
this.node.classList.add("hider");
this.on.hide();
},
_reflow: function() {
CT.dom.mod({
targets: this.container.childNodes,
property: this.dimension,
value: (100 / this.container.childNodes.length) + "%"
});
this.container.style[this.dimension] = (this.opts.frames.length * 100) + "%";
},
resume: function() {
if (!this._autoSlide)
this._autoSlide = setInterval(this.autoSlideCallback, this.opts.autoSlideInterval);
},
pause: function() {
if (this._autoSlide) {
clearInterval(this._autoSlide);
this._autoSlide = null;
}
this.opts.parent.slider && this.opts.parent.slider.pause();
},
addFrame: function(frame, index) {
if (typeof frame == "string")
frame = { img: frame };
var circle = CT.dom.node(frame.label, "div",
"hoverglow pointer indicator-circle " +
(frame.label ? "labeled" : "unlabeled") + "-circle"),
jumper = this.jumpers[frame.label || index] = this.circleJump(index);
CT.gesture.listen("tap", circle, jumper);
this.circlesContainer.appendChild(circle);
this.container.appendChild((new CT.slider.Frame(frame, this)).node);
if (index == 0) {
circle.className += " active-circle";
this.activeCircle = circle;
if (!this.opts.parent.slider && !this.opts.startFrame) // exclude embedded slider
setTimeout(this.container.firstChild.frame.on.show, 500);
}
if (index == undefined) // ad-hoc frame
this._reflow();
},
circleJump: function(index) {
var f = function() {
this.pause();
this.updateIndicator(index);
this.trans();
}.bind(this);
return f;
},
updateIndicator: function(index) {
this.container.childNodes[this.index].frame.on.hide();
this.index = index;
this.container.childNodes[this.index].frame.on.show();
this.activeCircle.classList.remove('active-circle');
this.activeCircle = this.circlesContainer.childNodes[index];
this.activeCircle.classList.add('active-circle');
CT.dom[this.activeCircle.nextSibling ? "show" : "hide"](this.nextButton);
CT.dom[this.activeCircle.previousSibling ? "show" : "hide"](this.prevButton);
},
updatePosition: function(direction, force) {
var index = this.index, absdir = CT.drag._.dir2abs[direction],
cccnl = this.circlesContainer.childNodes.length;
if (CT.drag._.direction2orientation[direction] == this.opts.orientation) {
if (absdir == "forward" && (force || this.activeCircle.nextSibling))
index += 1;
else if (absdir == "backward" && (force || this.activeCircle.previousSibling))
index -= 1;
if (cccnl)
this.updateIndicator((index + cccnl) % cccnl);
} else if (this.opts.parent.slider)
this.opts.parent.slider.shift(direction, force);
},
trans: function() {
var opts = {}, axis = CT.drag._.orientation2axis[this.opts.orientation];
opts[axis] = this.container[axis + "Drag"] = -this.index
* CT.align[this.dimension](this.container) / this.container.childNodes.length;
opts.duration = this.opts.translateDuration;
CT.trans.translate(this.container, opts);
},
shift: function(direction, force) {
this.updatePosition(direction, force || this.opts.circular);
this.trans();
},
autoSlideCallback: function() {
this.shift(CT.slider.orientation2abs[this.opts.orientation].forward, true);
},
prevButtonCallback: function() {
this.pause();
this.shift(CT.slider.orientation2abs[this.opts.orientation].backward);
},
nextButtonCallback: function() {
this.pause();
this.shift(CT.slider.orientation2abs[this.opts.orientation].forward);
}
});
CT.slider.Frame = CT.Class({
CLASSNAME: "CT.slider.Frame",
on: { // overwritten by mode functions
show: function() {},
hide: function() {}
},
peekaboo: function() {
var opts = this.opts, node = this.node, slider = this.slider, pulser,
full = CT.dom.node(opts.content, "div", "big carousel-content-full"),
imageBack = CT.dom.node(CT.dom.img(opts.img || slider.opts.defaultImg, "abs"), "div", "w1 h1 noflow carousel-content-image"),
nodes = [ imageBack, full ];
var teaserTap = function() {
slider.pause();
node._retracted = !node._retracted;
if (node._retracted) {
CT.trans.resize(imageBack, {
width: "40%",
height: "30%",
cb: function() {
if (pulser) pulser.style.zIndex = 200;
}
});
CT.trans.trans({
node: teaser,
property: "left",
value: "10px"
});
CT.trans.trans({
node: teaser,
property: "top",
value: "0px"
});
slider.hideNav();
this.tab && this.tab.hide();
} else {
if (pulser) pulser.style.zIndex = 0;
CT.trans.resize(imageBack, {
width: "100%",
height: "100%"
});
CT.trans.trans({
node: teaser,
property: "left",
value: "22.5%"
});
CT.trans.trans({
node: teaser,
property: "top",
value: "100px"
});
slider.showNav();
this.tab && this.tab.show(slider.opts.parent);
}
};
if (slider.opts.pan) {
imageBack.controller = CT.trans.pan(imageBack.firstChild, {
duration: opts.panDuration || slider.opts.panDuration || slider.opts.autoSlideInterval
});
} else {
CT.onload(function() {
CT.dom.cover(imageBack.firstChild);
}, imageBack.firstChild);
}
if (opts.title || opts.blurb) {
var blurbNode = CT.dom.div(opts.blurb, "bigger"), teaser = CT.dom.div([
CT.dom.div(opts.title, "biggest"), blurbNode
], "carousel-content-teaser transparent hoverglow pointer cc-teaser-"
+ (slider.opts.translucentTeaser ? "trans" : "opaque"));
CT.dom.fit(blurbNode);
nodes.push(teaser);
}
if (opts.pulse) {
pulser = CT.dom.img(opts.pulse, "carousel-pulse pointer");
pulser.controller = CT.trans.pulse(pulser);
CT.gesture.listen("tap", pulser, teaserTap); // assume content exists
nodes.push(pulser);
}
this.on.show = function() {
if (opts.title || opts.blurb) {
CT.trans.fadeIn(teaser);
blurbNode.style.maxHeight = (teaser.parentNode.clientHeight - 200) + "px";
blurbNode.fit();
}
if (slider.opts.keys && !slider.opts.noEnter && teaser) // unreg somewhere?
CT.key.on("ENTER", teaserTap);
if (slider.opts.pan)
imageBack.controller.resume();
if (opts.pulse)
pulser.controller.resume();
if (this.tab)
this.tab.show(slider.opts.parent);
};
this.on.hide = function() {
if (opts.title || opts.blurb)
CT.trans.fadeOut(teaser);
if (node._retracted)
teaserTap();
if (slider.opts.pan)
imageBack.controller.pause();
if (opts.pulse)
pulser.controller.pause();
if (this.tab)
this.tab.hide();
};
CT.dom.addEach(node, nodes);
if (opts.content) // assume title/blurb exists
CT.gesture.listen("tap", teaser, teaserTap);
else if (opts.onclick)
CT.gesture.listen("tap", teaser, opts.onclick);
},
chunk: function() {
var slider = new CT.slider.Slider({
parent: this.node,
frames: this.opts.frames,
mode: this.opts.mode || this.slider.opts.subMode,
autoSlide: false,
img: this.opts.img,
pan: this.slider.opts.pan,
arrow: this.slider.opts.arrow,
startFrame: this.opts.startFrame,
defaultImg: this.slider.opts.defaultImg,
translucentTeaser: this.slider.opts.translucentTeaser,
orientation: CT.slider.other_orientation[this.slider.opts.orientation],
arrowPosition: "bottom"
}), parent = this.slider;
this.on.hide = slider.on.hide;
this.on.show = function() {
slider.on.show();
if (parent.opts.keys) {
CT.key.on(slider.opts.orientation == "horizontal" ?
"LEFT" : "UP", slider.prevButtonCallback);
CT.key.on(slider.opts.orientation == "horizontal" ?
"RIGHT" : "DOWN", slider.nextButtonCallback);
}
};
},
menu: function() {
var menu = new CT.modal.Modal({
transition: "slide",
noClose: true,
className: "round centered basicpopup above",
content: this.opts.buttons.map(function(d) {
var n = CT.dom.node([
CT.dom.node(d.label || d.page, "div", "biggest bold bottombordered"),
CT.dom.node(d.content)
], "div", "margined padded bordered round hoverglow pointer inline-block");
n.onclick = function() {
location = d.url || ("/" + d.page + ".html");
};
return n;
})
});
var logos = function(logo) {
var arr = [];
for (var i = 0; i < 5; i++)
arr.push(CT.dom.img(logo || this.slider.opts.defaultImg));
return arr;
};
this.node.appendChild(CT.dom.marquee(logos(this.opts.logo), "abs top0 h20p fullwidth"));
this.node.appendChild(CT.dom.marquee(logos(this.opts.logo), "abs bottom0 h20p fullwidth", "right"));
this.on.hide = menu.hide;
this.on.show = menu.show;
},
profile: function() {
var opts = CT.merge(this.opts, this.slider.opts, {
panDuration: this.slider.opts.autoSlideInterval,
controllerHook: this.on
});
opts.img = opts.img || this.slider.opts.defaultImg;
CT.dom.addContent(this.node, CT.layout.profile(opts));
},
track: function() { // add img!
var oz = this.opts, audio = CT.dom.audio(oz.src, true, false, false, function() {
playmod.hide();
}, this.slider.autoSlideCallback), playmod = CT.modal.modal("click to play!", function() {
audio.play();
}, {
noClose: true,
innerClass: "gigantic"
}, true, true), pause = function() {
audio.playing = false;
audio.pause();
}, resume = function() {
audio.playing = true;
audio.play().catch(playmod.show);
}, pauseResume = function() {
audio.playing ? pause() : resume();
};
this.on.hide = pause;
this.on.show = function() {
resume();
CT.key.on("SPACE", pauseResume);
if (oz.deepLink)
document.location.hash = encodeURI(oz.album + "|" + oz.song);
oz.onplay && oz.onplay(oz.album, oz.song);
};
CT.dom.addContent(this.node, CT.dom.div([
CT.dom.div(this.opts.song, "gigantic"),
CT.dom.div(this.opts.album, "biggerest"),
audio
], "full-center outlined"));
},
custom: function() {
CT.dom.addContent(this.node, this.slider.opts.frameCb(this.opts));
},
init: function(opts, slider) {
var mode = opts.mode || slider.opts.mode;
this.opts = opts;
this.node = CT.dom.div("", "carousel-content-container full"
+ CT.slider.other_dim[slider.dimension] + ((mode == "custom") ? " scroller" : ""));
this.node.frame = this;
this.slider = this.node.slider = slider;
if (slider.dimension == "width")
this.node.style.display = "inline-block";
var topts = opts.tab || slider.opts.tab;
if (topts) {
var tab = this.tab = new CT.modal.Modal({
content: topts.content,
center: false,
noClose: true,
className: "basicpopup abs rounder translucent above shiftall",
transition: "slide",
slide: {
origin: topts.origin
}
});
this.on.show = function() {
if (tab.isClear())
tab.set(topts.content);
tab.show(slider.opts.parent);
};
this.on.hide = tab.hide;
}
this[mode]();
}
}); | CT.slider.Frame.track(), pause(): hide() playmod (especially for Frame hide)
| cantools/CT/slider.js | CT.slider.Frame.track(), pause(): hide() playmod (especially for Frame hide) | <ide><path>antools/CT/slider.js
<ide> }, true, true), pause = function() {
<ide> audio.playing = false;
<ide> audio.pause();
<add> playmod.hide();
<ide> }, resume = function() {
<ide> audio.playing = true;
<ide> audio.play().catch(playmod.show); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.