answer
stringlengths 17
10.2M
|
|---|
package io.rapidpro.sdk;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import java.util.Collections;
import io.rapidpro.sdk.chat.FcmClientChatActivity;
import io.rapidpro.sdk.chat.FcmClientChatFragment;
import io.rapidpro.sdk.chat.menu.FcmClientMenuService;
import io.rapidpro.sdk.core.models.network.FcmRegistrationResponse;
import io.rapidpro.sdk.core.models.v2.Contact;
import io.rapidpro.sdk.core.network.RapidProServices;
import io.rapidpro.sdk.listeners.SendMessageListener;
import io.rapidpro.sdk.permission.PermissionDialog;
import io.rapidpro.sdk.persistence.Preferences;
import io.rapidpro.sdk.services.FcmClientRegistrationIntentService;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@SuppressWarnings({"unused", "WeakerAccess"})
public class FcmClient {
private static Context context;
private static String token;
private static String host;
private static String channel;
private static Boolean forceRegistration = false;
private static Class<? extends FcmClientRegistrationIntentService> registrationServiceClass;
private static UiConfiguration uiConfiguration;
private static Preferences preferences;
private static RapidProServices services;
public static final String URN_PREFIX_FCM = "fcm:";
FcmClient() {}
public static void initialize(Context context) {
FcmClient.context = context;
}
public static void initialize(Builder builder) {
initialize(builder.context, builder.host, builder.token,
builder.channel, builder.registrationServiceClass, builder.uiConfiguration);
}
private static void initialize(Context context, String host, String token, String channel
, Class<? extends FcmClientRegistrationIntentService> registrationServiceClass, UiConfiguration uiConfiguration) {
FcmClient.context = context;
FcmClient.host = host;
FcmClient.token = token;
FcmClient.channel = channel;
FcmClient.registrationServiceClass = registrationServiceClass;
FcmClient.preferences = new Preferences(context);
FcmClient.services = new RapidProServices(host, getToken());
FcmClient.uiConfiguration = uiConfiguration;
}
public static UiConfiguration getUiConfiguration() {
return uiConfiguration;
}
public static void startFcmClientChatActivity(Context context) {
startFcmClientChatActivity(context, token, channel);
}
public static FcmClientChatFragment createFcmClientChatFragment() {
return new FcmClientChatFragment();
}
public static FcmClientChatFragment getFcmClientChatFragment(String token, String channel) {
FcmClient.token = token;
FcmClient.channel = channel;
FcmClient.services = new RapidProServices(host, token);
return new FcmClientChatFragment();
}
public static void startFcmClientChatActivity(Context context, String token, String channel) {
FcmClient.token = token;
FcmClient.channel = channel;
FcmClient.services = new RapidProServices(host, token);
context.startActivity(new Intent(context, FcmClientChatActivity.class));
}
public static void setUiConfiguration(UiConfiguration uiConfiguration) {
FcmClient.uiConfiguration = uiConfiguration;
}
public static void sendMessage(String message) {
services.sendReceivedMessage(channel, getPreferences().getUrn(), getPreferences().getFcmToken(), message)
.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {}
});
}
public static void sendMessage(String message, final SendMessageListener listener) {
services.sendReceivedMessage(channel, getPreferences().getUrn(), getPreferences().getFcmToken(), message)
.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
listener.onSendMessage();
} else {
listener.onError(getExceptionForErrorResponse(response), context.getString(R.string.fcm_client_error_message_send));
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable throwable) {
listener.onError(throwable, context.getString(R.string.fcm_client_error_message_send));
}
});
}
public static Contact getContact() {
Contact contact = new Contact();
contact.setUuid(getPreferences().getContactUuid());
contact.setUrns(Collections.singletonList(getPreferences().getUrn()));
return contact;
}
public static Response<FcmRegistrationResponse> saveContactWithToken(String urn, String fcmToken, String token) throws java.io.IOException {
RapidProServices rapidProServices = new RapidProServices(host, token);
return rapidProServices.registerFcmContact(channel, urn, fcmToken).execute();
}
@NonNull
private static IllegalStateException getExceptionForErrorResponse(Response response) {
return new IllegalStateException("Response not successful. HTTP Code: " + response.code() + " Response: " + response.raw());
}
public static int getUnreadMessages() {
return getPreferences().getUnreadMessages();
}
public static void refreshContactToken() {
String urn = getPreferences().getUrn();
if (!TextUtils.isEmpty(urn)) {
registerContact(urn);
}
}
public static void registerContactIfNeeded(String urn) {
if (!isContactRegistered()) {
registerContact(urn);
}
}
public static void registerContact(String urn) {
Class<? extends FcmClientRegistrationIntentService> registrationIntentService =
registrationServiceClass != null ? registrationServiceClass : FcmClientRegistrationIntentService.class;
Intent registrationIntent = new Intent(context, registrationIntentService);
registrationIntent.putExtra(FcmClientRegistrationIntentService.EXTRA_URN, urn);
context.startService(registrationIntent);
}
public static boolean isContactRegistered() {
return !TextUtils.isEmpty(getPreferences().getFcmToken()) && !TextUtils.isEmpty(getPreferences().getContactUuid());
}
public static RapidProServices getServices() {
return services;
}
public static boolean isChatVisible() {
return FcmClientChatFragment.visible || FcmClientMenuService.isExpanded();
}
public static void setPreferences(Preferences preferences) {
FcmClient.preferences = preferences;
}
public static Preferences getPreferences() {
if (preferences == null) {
preferences = new Preferences(context);
}
return preferences;
}
@DrawableRes
public static int getAppIcon() {
try {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo info = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
return info.icon;
} catch (Exception exception) {
return R.drawable.fcm_client_ic_send_message;
}
}
public static void requestFloatingPermissionsIfNeeded(Activity activity) {
if (!hasFloatingPermission()) {
requestFloatingPermissions(activity);
}
}
@TargetApi(Build.VERSION_CODES.M)
public static void requestFloatingPermissions(Activity activity) {
PermissionDialog permissionDialog = new PermissionDialog(activity);
permissionDialog.show();
}
public static void showManageOverlaySettings() {
Intent drawOverlaysSettingsIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
drawOverlaysSettingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
drawOverlaysSettingsIntent.setData(Uri.parse("package:" + context.getPackageName()));
context.startActivity(drawOverlaysSettingsIntent);
}
public static boolean hasFloatingPermission() {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M
|| (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(context));
}
public static Context getContext() {
return context;
}
public static String getToken() {
return token;
}
public static String getChannel() {
return channel;
}
public static String getHost() {
return host;
}
public static class Builder {
private Context context;
private String token;
private String host;
private String channel;
private Class<? extends FcmClientRegistrationIntentService>
registrationServiceClass = FcmClientRegistrationIntentService.class;
private UiConfiguration uiConfiguration;
public Builder(Context context) {
this.context = context;
this.uiConfiguration = new UiConfiguration();
}
public Builder setContext(Context context) {
this.context = context;
return this;
}
public Builder setToken(String token) {
this.token = token;
return this;
}
public Builder setHost(String host) {
this.host = host;
return this;
}
public Builder setChannel(String channel) {
this.channel = channel;
return this;
}
public Builder setRegistrationServiceClass(Class<? extends FcmClientRegistrationIntentService>
registrationServiceClass) {
this.registrationServiceClass = registrationServiceClass;
return this;
}
public Builder setUiConfiguration(UiConfiguration uiConfiguration) {
this.uiConfiguration = uiConfiguration;
return this;
}
}
}
|
package macbury.forge.graphics.builders;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.Pool;
import macbury.forge.blocks.Block;
import macbury.forge.utils.Vector3i;
import macbury.forge.voxel.Voxel;
public class TerrainPart implements Pool.Poolable {
public final Vector3i currentDirection = new Vector3i();
public final Vector3i voxelPosition = new Vector3i();
public final Vector3i voxelSize = new Vector3i();
public final Vector2 voxelSizeRect = new Vector2();
public Block block;
public Voxel voxel;
private final static Vector3i tempA = new Vector3i();
private final static Vector3i tempB = new Vector3i();
public Block.Side face = Block.Side.all;
@Override
public void reset() {
block = null;
voxel = null;
voxelSize.setZero();
voxelPosition.setZero();
currentDirection.setZero();
voxelSizeRect.setZero();
}
public float distanceTo(TerrainPart otherPart) {
tempA.set(this.voxelPosition).add(voxelSize);
return otherPart.voxelPosition.dst(tempA);
}
public boolean isHorizontalSimilar(TerrainPart otherPart) {
getPartDirection(otherPart.voxelPosition, tempB);
if (!voxelSize.isZero() && !currentDirection.equals(tempB)) {
return false;
}
return canBeJoined(otherPart) && tempB.isOneDirection() && distanceTo(otherPart) == 1;
}
private boolean canBeJoined(TerrainPart otherPart) {
return (block.blockShape.scalable) && otherPart.block.id == this.block.id;
}
public boolean isVeriticalSimilar(TerrainPart otherPart) {
return false;//canBeJoined(otherPart) && otherPart.voxelPosition.dst(this.voxelPosition) == 1;
}
public boolean comparedTo(TerrainPart other) {
if (this.voxelPosition.y != other.voxelPosition.y)
return this.voxelPosition.y < other.voxelPosition.y;
if (this.voxelPosition.x != other.voxelPosition.x)
return this.voxelPosition.x < other.voxelPosition.x;
if (this.voxelPosition.z != other.voxelPosition.z)
return this.voxelPosition.z < other.voxelPosition.z;
if (this.voxelSize.x != other.voxelSize.x)
return this.voxelSize.x < other.voxelSize.x;
if (this.voxelSize.y != other.voxelSize.y)
return this.voxelSize.y < other.voxelSize.y;
return this.voxelSize.z < other.voxelSize.z;
}
public void getPartDirection(Vector3i from, Vector3i out) {
out.set(this.voxelPosition).add(voxelSize).sub(from).abs();
}
public void getUVScaling(Vector2 out) {
voxelSizeRect.x = Math.max(voxelSizeRect.x, 1);
voxelSizeRect.y = Math.max(voxelSizeRect.y, 1);
out.set(voxelSizeRect);
//Gdx.app.log("voxel size", out.toString());
}
public void join(TerrainPart otherPart) {
if (voxelSize.isZero()) {
getPartDirection(otherPart.voxelPosition, tempA);
currentDirection.set(tempA);
//Gdx.app.log("Direction", currentDirection.toString());
}
voxelSize.add(currentDirection);
voxelSizeRect.set(voxelSize.x, voxelSize.y);
if (currentDirection.z == 1) {
switch (face) {
case right:
case left:
voxelSizeRect.set(voxelSize.z, voxelSize.y);
break;
case top:
voxelSizeRect.set(voxelSize.x, voxelSize.z);
break;
}
}
voxelSizeRect.add(1, 1);
}
}
|
package com.jbooktrader.platform.dialog;
import com.jbooktrader.platform.model.*;
import static com.jbooktrader.platform.model.TradingTableModel.Column.*;
import com.jbooktrader.platform.startup.JBookTrader;
import com.jbooktrader.platform.strategy.Strategy;
import com.jbooktrader.platform.util.*;
import javax.swing.*;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
/**
* Main application window.
*/
public class MainFrameDialog extends JFrame implements ModelListener {
private JMenuItem exitMenuItem, aboutMenuItem, discussionMenuItem, projectHomeMenuItem;
private JMenuItem tradeMenuItem, backTestMenuItem, forwardTestMenuItem, optimizeMenuItem, chartMenuItem, saveBookMenuItem;
private TradingTableModel tradingTableModel;
private JTable tradingTable;
private JPopupMenu popupMenu;
private final Toolkit toolkit;
public MainFrameDialog() throws JBookTraderException {
toolkit = Toolkit.getDefaultToolkit();
Dispatcher.addListener(this);
init();
populateStrategies();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void modelChanged(ModelListener.Event event, Object value) {
switch (event) {
case STRATEGY_UPDATE:
Strategy strategy = (Strategy) value;
tradingTableModel.update(strategy);
break;
case STRATEGIES_START:
Dispatcher.Mode mode = Dispatcher.getMode();
if (mode == Dispatcher.Mode.TRADE) {
forwardTestMenuItem.setEnabled(false);
}
if (mode == Dispatcher.Mode.FORWARD_TEST) {
tradeMenuItem.setEnabled(false);
}
backTestMenuItem.setEnabled(false);
optimizeMenuItem.setEnabled(false);
saveBookMenuItem.setEnabled(true);
chartMenuItem.setEnabled(true);
break;
case STRATEGIES_END:
forwardTestMenuItem.setEnabled(true);
tradeMenuItem.setEnabled(true);
backTestMenuItem.setEnabled(true);
optimizeMenuItem.setEnabled(true);
break;
}
}
public void discussionAction(ActionListener action) {
discussionMenuItem.addActionListener(action);
}
public void projectHomeAction(ActionListener action) {
projectHomeMenuItem.addActionListener(action);
}
public void tradingTableAction(MouseAdapter action) {
tradingTable.addMouseListener(action);
}
public void backTestAction(ActionListener action) {
backTestMenuItem.addActionListener(action);
}
public void optimizeAction(ActionListener action) {
optimizeMenuItem.addActionListener(action);
}
public void forwardTestAction(ActionListener action) {
forwardTestMenuItem.addActionListener(action);
}
public void tradeAction(ActionListener action) {
tradeMenuItem.addActionListener(action);
}
public void saveMarketBookAction(ActionListener action) {
saveBookMenuItem.addActionListener(action);
}
public void chartAction(ActionListener action) {
chartMenuItem.addActionListener(action);
}
public void exitAction(ActionListener action) {
exitMenuItem.addActionListener(action);
}
public void exitAction(WindowAdapter action) {
addWindowListener(action);
}
public void aboutAction(ActionListener action) {
aboutMenuItem.addActionListener(action);
}
private URL getImageURL(String imageFileName) throws JBookTraderException {
URL imgURL = ClassLoader.getSystemResource(imageFileName);
if (imgURL == null) {
String msg = "Could not locate " + imageFileName + ". Make sure the /resources directory is in the classpath.";
throw new JBookTraderException(msg);
}
return imgURL;
}
private ImageIcon getImageIcon(String imageFileName) throws JBookTraderException {
return new ImageIcon(toolkit.getImage(getImageURL(imageFileName)));
}
private void populateStrategies() throws JBookTraderException {
ClassFinder classFinder = new ClassFinder();
for (Strategy strategy : classFinder.getStrategies()) {
tradingTableModel.addStrategy(strategy);
}
}
public TradingTableModel getTradingTableModel() {
return tradingTableModel;
}
public JTable getTradingTable() {
return tradingTable;
}
public void showPopup(MouseEvent mouseEvent) {
popupMenu.show(tradingTable, mouseEvent.getX(), mouseEvent.getY());
}
private void init() throws JBookTraderException {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
// session menu
JMenu sessionMenu = new JMenu("Session");
sessionMenu.setMnemonic('S');
exitMenuItem = new JMenuItem("Exit");
exitMenuItem.setMnemonic('X');
sessionMenu.add(exitMenuItem);
// help menu
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
discussionMenuItem = new JMenuItem("Discussion Group");
discussionMenuItem.setMnemonic('D');
projectHomeMenuItem = new JMenuItem("Project Home");
projectHomeMenuItem.setMnemonic('P');
aboutMenuItem = new JMenuItem("About...");
aboutMenuItem.setMnemonic('A');
helpMenu.add(discussionMenuItem);
helpMenu.add(projectHomeMenuItem);
helpMenu.addSeparator();
helpMenu.add(aboutMenuItem);
// menu bar
JMenuBar menuBar = new JMenuBar();
menuBar.add(sessionMenu);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
// popup menu
popupMenu = new JPopupMenu();
backTestMenuItem = new JMenuItem("Back Test", getImageIcon("backTest.png"));
optimizeMenuItem = new JMenuItem("Optimize", getImageIcon("optimize.png"));
forwardTestMenuItem = new JMenuItem("Forward Test", getImageIcon("forwardTest.png"));
tradeMenuItem = new JMenuItem("Trade");
chartMenuItem = new JMenuItem("Chart", getImageIcon("chart.png"));
saveBookMenuItem = new JMenuItem("Save Book", getImageIcon("save.png"));
popupMenu.add(optimizeMenuItem);
popupMenu.add(backTestMenuItem);
popupMenu.add(forwardTestMenuItem);
popupMenu.addSeparator();
popupMenu.add(chartMenuItem);
popupMenu.add(saveBookMenuItem);
popupMenu.addSeparator();
popupMenu.add(tradeMenuItem);
JScrollPane tradingScroll = new JScrollPane();
tradingScroll.setAutoscrolls(true);
JPanel tradingPanel = new JPanel(new BorderLayout());
tradingPanel.add(tradingScroll, BorderLayout.CENTER);
tradingTableModel = new TradingTableModel();
tradingTable = new JTable(tradingTableModel);
tradingTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// set custom column renderers
TableColumnModel columnModel = tradingTable.getColumnModel();
NumberRenderer nr5 = new NumberRenderer(5);
columnModel.getColumn(Bid.ordinal()).setCellRenderer(nr5);
columnModel.getColumn(Ask.ordinal()).setCellRenderer(nr5);
NumberRenderer nr2 = new NumberRenderer(2);
columnModel.getColumn(PL.ordinal()).setCellRenderer(nr2);
columnModel.getColumn(MaxDD.ordinal()).setCellRenderer(nr2);
columnModel.getColumn(PF.ordinal()).setCellRenderer(nr2);
// Make some columns wider than the rest, so that the info fits in.
columnModel.getColumn(Strategy.ordinal()).setPreferredWidth(150);
columnModel.getColumn(MarketDepth.ordinal()).setPreferredWidth(100);
tradingScroll.getViewport().add(tradingTable);
Image appIcon = Toolkit.getDefaultToolkit().getImage(getImageURL("JBookTrader.png"));
setIconImage(appIcon);
add(tradingPanel, BorderLayout.CENTER);
setPreferredSize(new Dimension(800, 250));
setTitle(JBookTrader.APP_NAME);
pack();
}
}
|
package bisq.core.dao.state;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.BaseCurrencyNetwork;
import bisq.core.dao.DaoOptionKeys;
import org.bitcoinj.core.Coin;
import javax.inject.Inject;
import javax.inject.Named;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* Encapsulate the genesis txId and height.
* As we don't persist those data we don't want to have it in the DaoState directly and moved it to a separate class.
* Using a static final field in DaoState would not work well as we want to support that the data can be overwritten by
* program arguments for development testing and therefore it is set in the constructor via Guice.
*/
@Slf4j
public class GenesisTxInfo {
// Static
public static final Coin GENESIS_TOTAL_SUPPLY = Coin.valueOf(250_000_000); // 2.5M BSQ
private static final String MAINNET_GENESIS_TX_ID = "81855816eca165f17f0668898faa8724a105196e90ffc4993f4cac980176674e";
private static final int MAINNET_GENESIS_BLOCK_HEIGHT = 524717; // 2018-05-27
private static final String TESTNET_GENESIS_TX_ID = "09e70ce0ab7a962a82a2ca84c9ae8a89140bf1c3fb6f7efad6162e39e4b362ae";
private static final int TESTNET_GENESIS_BLOCK_HEIGHT = 1446300; // 2018-12-02
private static final String REGTEST_GENESIS_TX_ID = "30af0050040befd8af25068cc697e418e09c2d8ebd8d411d2240591b9ec203cf";
private static final int REGTEST_GENESIS_BLOCK_HEIGHT = 111;
// Instance fields
// We cannot use a static final as we want to set the txId also via program argument for development and then it
// is getting passed via Guice in the constructor.
@Getter
private final String genesisTxId;
@Getter
private final int genesisBlockHeight;
// mainnet
// this tx has a lot of outputs
// BLOCK_HEIGHT 411779
// 411812 has 693 recursions
// block 376078 has 2843 recursions and caused once a StackOverflowError, a second run worked. Took 1,2 sec.
// BTC MAIN NET
// new: --genesisBlockHeight=524717 --genesisTxId=81855816eca165f17f0668898faa8724a105196e90ffc4993f4cac980176674e
// private static final String DEFAULT_GENESIS_TX_ID = "e5c8313c4144d219b5f6b2dacf1d36f2d43a9039bb2fcd1bd57f8352a9c9809a";
// private static final int DEFAULT_GENESIS_BLOCK_HEIGHT = 477865; // 2017-07-28
// private static final String DEFAULT_GENESIS_TX_ID = "--";
// private static final int DEFAULT_GENESIS_BLOCK_HEIGHT = 499000; // recursive test 137298, 499000 dec 2017
// Constructor
@Inject
public GenesisTxInfo(@Named(DaoOptionKeys.GENESIS_TX_ID) String genesisTxId,
@Named(DaoOptionKeys.GENESIS_BLOCK_HEIGHT) Integer genesisBlockHeight) {
BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork();
boolean isMainnet = baseCurrencyNetwork.isMainnet();
boolean isTestnet = baseCurrencyNetwork.isTestnet();
boolean isRegtest = baseCurrencyNetwork.isRegtest();
if (!genesisTxId.isEmpty()) {
this.genesisTxId = genesisTxId;
} else if (isMainnet) {
this.genesisTxId = MAINNET_GENESIS_TX_ID;
} else if (isTestnet) {
this.genesisTxId = TESTNET_GENESIS_TX_ID;
} else if (isRegtest) {
this.genesisTxId = REGTEST_GENESIS_TX_ID;
} else {
this.genesisTxId = "genesisTxId is undefined";
}
if (genesisBlockHeight > -1) {
this.genesisBlockHeight = genesisBlockHeight;
} else if (isMainnet) {
this.genesisBlockHeight = MAINNET_GENESIS_BLOCK_HEIGHT;
} else if (isTestnet) {
this.genesisBlockHeight = TESTNET_GENESIS_BLOCK_HEIGHT;
} else if (isRegtest) {
this.genesisBlockHeight = REGTEST_GENESIS_BLOCK_HEIGHT;
} else {
this.genesisBlockHeight = 0;
}
}
}
|
package org.jasig.cas.event;
import java.util.Date;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.context.ApplicationEvent;
/**
* Abstract implementation of the Event interface that defines the method
* getPublishedDate so that implementing classes do not need to.
*
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.0
*/
public abstract class AbstractEvent extends ApplicationEvent {
/** The date the event was published. */
private final long publishedDate;
/**
* Constructor that passes the source object to the super class.
*
* @param o the source object.
*/
public AbstractEvent(final Object o) {
super(o);
this.publishedDate = System.currentTimeMillis();
}
/**
* Method to retrieve the date this event was published. The Date returned
* by this method is a copy - changing it will not change the Date instances
* returned by subsequent calls to this method.
*
* @return the Date this event was published.
*/
public final Date getPublishedDate() {
return new Date(this.publishedDate);
}
public final String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
package org.mwg.core.task;
import org.mwg.Callback;
import org.mwg.Graph;
import org.mwg.Node;
import org.mwg.core.utility.PrimitiveHelper;
import org.mwg.plugin.AbstractNode;
import org.mwg.task.TaskAction;
import org.mwg.task.TaskContext;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class CoreTaskContext implements TaskContext {
private final Map<String, Object> _variables;
private final boolean shouldFreeVar;
private final Graph _graph;
private final TaskAction[] _actions;
private final int _actionCursor;
private final AtomicInteger _currentTaskId;
private final TaskContext _parentContext;
private final Callback<Object> _callback;
//Mutable current result handler
private Object _result;
private long _world;
private long _time;
public CoreTaskContext(final TaskContext p_parentContext, final Object initial, final Graph p_graph, final TaskAction[] p_actions, final int p_actionCursor, final Callback<Object> p_callback) {
this._world = 0;
this._time = 0;
this._graph = p_graph;
this._parentContext = p_parentContext;
if (this._parentContext != null) {
this._variables = ((CoreTaskContext) p_parentContext)._variables;
shouldFreeVar = false;
} else {
this._variables = new ConcurrentHashMap<String, Object>();
shouldFreeVar = true;
}
this._result = initial;
this._actions = p_actions;
this._actionCursor = p_actionCursor;
this._callback = p_callback;
this._currentTaskId = new AtomicInteger(0);
}
@Override
public final Graph graph() {
return _graph;
}
@Override
public final long world() {
return this._world;
}
@Override
public final void setWorld(long p_world) {
this._world = p_world;
}
@Override
public final long time() {
return this._time;
}
@Override
public final void setTime(long p_time) {
this._time = p_time;
}
@Override
public final Object variable(String name) {
Object result = this._variables.get(name);
if (result != null) {
return result;
}
if (_parentContext != null) {
return this._parentContext.variable(name);
}
return null;
}
@Override
public final void setVariable(String name, Object value) {
final Object previous = this._variables.get(name);
if (value != null) {
Object protectedVar = CoreTask.protect(_graph, value);
this._variables.put(name, protectedVar);
} else {
this._variables.remove(name);
}
cleanObj(previous);
}
@Override
public final void addToVariable(final String name, final Object value) {
final Object result = this._variables.get(name);
final Object protectedVar = CoreTask.protect(_graph, value);
if (result == null) {
final Object[] newArr = new Object[1];
newArr[0] = protectedVar;
this._variables.put(name, newArr);
} else if (result instanceof Object[]) {
final Object[] previous = (Object[]) result;
final Object[] incArr = new Object[previous.length + 1];
System.arraycopy(previous, 0, incArr, 0, previous.length);
incArr[previous.length] = protectedVar;
this._variables.put(name, incArr);
} else {
final Object[] newArr = new Object[2];
newArr[0] = result;
newArr[1] = protectedVar;
this._variables.put(name, newArr);
}
}
@Override
public final Object result() {
return this._result;
}
@Override
public String resultAsString() {
return (String) result();
}
@Override
public String[] resultAsStringArray() {
return (String[]) result();
}
@Override
public Node resultAsNode() {
return (Node) result();
}
@Override
public Node[] resultAsNodeArray() {
return (Node[]) result();
}
@Override
public Object[] resultAsObjectArray() {
return (Object[]) result();
}
@Override
public final void setResult(Object actionResult) {
final Object previousResult = this._result;
//Optimization
if (actionResult != previousResult) {
this._result = CoreTask.protect(_graph, actionResult);
cleanObj(previousResult); //clean the previous result
}
//next step now...
int nextCursor = _currentTaskId.incrementAndGet();
TaskAction nextAction = null;
if (nextCursor < _actionCursor) {
nextAction = _actions[nextCursor];
}
if (nextAction == null) {
Object protectResult = null;
if (this._callback != null) {
protectResult = CoreTask.protect(_graph, result());
}
/* Clean */
cleanObj(this._result);
if (shouldFreeVar) {
String[] variables = _variables.keySet().toArray(new String[_variables.keySet().size()]);
for (int i = 0; i < variables.length; i++) {
cleanObj(variable(variables[i]));
}
}
this._result = null;
/* End Clean */
if (this._callback != null) {
this._callback.on(protectResult);
}
} else {
nextAction.eval(this);
}
}
private void cleanObj(Object o) {
final CoreTaskContext selfPoiner = this;
if (!PrimitiveHelper.iterate(o, new Callback<Object>() {
@Override
public void on(Object result) {
if (result instanceof AbstractNode) {
((Node) result).free();
} else {
selfPoiner.cleanObj(result);
}
}
})) {
if (o instanceof AbstractNode) {
((Node) o).free();
}
}
}
}
|
package net.mgsx.game.core.ui.widgets;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.utils.Align;
import net.mgsx.game.core.annotations.EnumType;
import net.mgsx.game.core.ui.FieldEditor;
import net.mgsx.game.core.ui.accessors.Accessor;
import net.mgsx.game.core.ui.accessors.AccessorHelper;
public class IntegerWidget implements FieldEditor
{
public static final IntegerWidget unlimited = new IntegerWidget();
public static final IntegerWidget signedByte = new IntegerWidget(8, true);
public static final IntegerWidget unsignedByte = new IntegerWidget(8, false);
public static final IntegerWidget signedShort = new IntegerWidget(16, true);
public static final IntegerWidget unsignedShort = new IntegerWidget(16, false);
public static final IntegerWidget signedInt = new IntegerWidget(32, true);
public static final IntegerWidget unsignedInt = new IntegerWidget(32, false);
public static final IntegerWidget signedLong = new IntegerWidget(64, true);
public static final IntegerWidget unsignedLong = new IntegerWidget(64, false);
private Long min, max;
public IntegerWidget() {
this(null, null);
}
public IntegerWidget(Long min, Long max) {
super();
this.min = min;
this.max = max;
}
public IntegerWidget(int bits, boolean signed){
this(signed ? -(1L<<(bits-1)) : 0L, signed ? 1L<<(bits-1)-1L : 1L<<bits-1L);
}
@Override
public Actor create(final Accessor accessor, Skin skin)
{
if(accessor.config() != null && accessor.config().readonly()){
Label label = createReadOnly(accessor, skin);
label.setAlignment(Align.center);
label.setColor(Color.CYAN);
return label;
}else{
return createEditable(accessor, skin);
}
}
private Label createReadOnly(final Accessor accessor, Skin skin){
String initText = String.valueOf(AccessorHelper.asLong(accessor));
if(accessor.config() != null && accessor.config().realtime()){
return new Label(initText, skin){
private long oldValue = AccessorHelper.asLong(accessor);
@Override
public void act(float delta) {
long newValue = AccessorHelper.asLong(accessor);
if(newValue != oldValue){
setText(String.valueOf(newValue));
oldValue = newValue;
}
super.act(delta);
}
};
}else{
return new Label(initText, skin);
}
}
private Actor createEditable(final Accessor accessor, Skin skin){
Table sub = new Table(skin);
final Label label = new Label("", skin);
final TextButton btPlus = new TextButton("+", skin);
final TextButton btMinus = new TextButton("-", skin);
final TextButton btDiv = new TextButton("/", skin);
final TextButton btMul = new TextButton("*", skin);
label.setAlignment(Align.center);
if(accessor.config().type() == EnumType.RANDOM){
label.setText(String.format("0x%x", accessor.get()));
final TextButton btRnd = new TextButton("randomize", skin);
sub.add(label).pad(4);
sub.add(btRnd);
btRnd.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
long value = MathUtils.random(Long.MAX_VALUE);
AccessorHelper.fromLong(accessor, value);
label.setText(String.format("0x%x", value));
}
});
}else{
label.setText(String.valueOf(accessor.get()));
sub.add(btDiv);
sub.add(btMinus);
sub.add(label).pad(4);
sub.add(btPlus);
sub.add(btMul);
btPlus.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
long value = 1 + AccessorHelper.asLong(accessor);
if(max == null || value <= max){
AccessorHelper.fromLong(accessor, value);
label.setText(String.valueOf(value));
}
}
});
btMinus.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
long value = -1 + AccessorHelper.asLong(accessor);
if(min == null || value >= min){
AccessorHelper.fromLong(accessor, value);
label.setText(String.valueOf(value));
}
}
});
btDiv.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
long value = AccessorHelper.asLong(accessor) / 2;
if(max == null || value <= max){
AccessorHelper.fromLong(accessor, value);
label.setText(String.valueOf(value));
}
}
});
btMul.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
long value = 2 * AccessorHelper.asLong(accessor);
if(min == null || value >= min){
AccessorHelper.fromLong(accessor, value);
label.setText(String.valueOf(value));
}
}
});
}
return sub;
}
}
|
package net.time4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static net.time4j.ClockUnit.NANOS;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
@RunWith(JUnit4.class)
public class DurationNormalizerTest {
@Test
public void withNormalizer2010_1_1() {
Duration<CalendarUnit> datePeriod =
Duration.ofCalendarUnits(2, 14, 33);
assertThat(
datePeriod.with(PlainDate.of(2010, 1, 1)),
is(Duration.ofCalendarUnits(3, 3, 2)));
}
@Test
public void withNormalizer2010_2_1() {
Duration<CalendarUnit> datePeriod =
Duration.ofCalendarUnits(2, 14, 33);
assertThat(
datePeriod.with(PlainDate.of(2010, 2, 1)),
is(Duration.ofCalendarUnits(3, 3, 3)));
}
@Test
public void withNormalizer2003_12_27() {
Duration<CalendarUnit> datePeriod =
Duration.ofCalendarUnits(2, 14, 33);
assertThat(
datePeriod.with(PlainDate.of(2003, 12, 27)),
is(Duration.ofCalendarUnits(3, 3, 5)));
}
@Test
public void withSTD_PERIOD() {
Duration<IsoUnit> test =
Duration.ofZero()
.plus(Duration.ofCalendarUnits(2, 14, 30))
.plus(Duration.ofClockUnits(47, 59, 60))
.plus(1075800000, NANOS)
.inverse();
assertThat(
test.with(Duration.STD_PERIOD),
is(
Duration.ofNegative().years(3).months(2).days(32)
.seconds(1).millis(75).micros(800).build()));
}
@Test(expected=IllegalArgumentException.class)
public void withSTD_PERIOD_unitsOfSameLength() {
Duration.ofZero()
.plus(1, CalendarUnit.weekBasedYears())
.plus(5, CalendarUnit.CENTURIES)
.with(Duration.STD_PERIOD);
}
@Test
public void withSTD_CALENDAR_PERIOD1() {
Duration<CalendarUnit> datePeriod =
Duration.ofCalendarUnits(2, 15, 3);
assertThat(
datePeriod.with(Duration.STD_CALENDAR_PERIOD),
is(Duration.ofCalendarUnits(3, 3, 3)));
}
@Test
public void withSTD_CALENDAR_PERIOD2() {
Duration<CalendarUnit> datePeriod =
Duration.ofCalendarUnits(2, 15, 3).plus(3, CalendarUnit.WEEKS);
assertThat(
datePeriod.with(Duration.STD_CALENDAR_PERIOD),
is(Duration.ofCalendarUnits(3, 3, 24)));
}
@Test
public void withSTD_CLOCK_PERIOD() {
Duration<ClockUnit> timePeriod =
Duration.ofClockUnits(2, 61, 120);
assertThat(
timePeriod.with(Duration.STD_CLOCK_PERIOD),
is(Duration.ofClockUnits(3, 3, 0)));
}
@Test
public void withMinutesOnly() {
Duration<ClockUnit> timePeriod =
Duration.ofClockUnits(2, 61, 122);
assertThat(
timePeriod.with(ClockUnit.MINUTES.only()),
is(Duration.of(183, ClockUnit.MINUTES)));
}
@Test
public void withMinutesOnlyIfEmpty() {
Duration<ClockUnit> timePeriod = Duration.ofZero();
assertThat(
timePeriod.with(ClockUnit.MINUTES.only()).isEmpty(),
is(true));
}
}
|
package org.jasig.portal.layout;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Collection;
import java.util.Vector;
import java.util.Iterator;
import java.util.Set;
import java.util.HashSet;
import org.jasig.portal.groups.IGroupMember;
import org.jasig.portal.IUserLayoutStore;
import org.jasig.portal.PortalException;
import org.jasig.portal.UserProfile;
import org.jasig.portal.layout.restrictions.IUserLayoutRestriction;
import org.jasig.portal.layout.restrictions.PriorityRestriction;
import org.jasig.portal.layout.restrictions.RestrictionTypes;
import org.jasig.portal.layout.restrictions.UserLayoutRestriction;
import org.jasig.portal.layout.restrictions.UserLayoutRestrictionFactory;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.services.LogService;
import org.jasig.portal.utils.CommonUtils;
import org.jasig.portal.utils.DocumentFactory;
import org.jasig.portal.utils.GuidGenerator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ContentHandler;
/**
* An implementation of Aggregated User Layout Manager Interface defining common operations on user layout nodes,
* that is channels and folders
*
* @author <a href="mailto:mvi@immagic.com">Michael Ivanov</a>
* @version $Revision$
*/
public class AggregatedLayoutManager implements IAggregatedUserLayoutManager {
private AggregatedUserLayoutStore layoutStore;
private AggregatedLayout layout;
private UserProfile userProfile;
private IPerson person;
private Set listeners = new HashSet();
// Boolean flags for marking nodes
//private boolean addTargetsAllowed = false;
//private boolean moveTargetsAllowed = false;
private IALNodeDescription addTargetsNodeDesc;
private String moveTargetsNodeId;
private int restrictionMask = 0;
private boolean autoCommit = false;
// The ID of the current loaded fragment
private String fragmentId;
// The IDs and names of the fragments which a user is owner of
//private Hashtable fragments;
// GUID generator
private static GuidGenerator guid = null;
private String cacheKey = null;
public AggregatedLayoutManager( IPerson person, UserProfile userProfile ) throws Exception {
this.person = person;
this.userProfile = userProfile;
layout = new AggregatedLayout ( String.valueOf(getLayoutId()), this );
autoCommit = false;
if ( guid == null )
guid = new GuidGenerator();
updateCacheKey();
}
public AggregatedLayoutManager( IPerson person, UserProfile userProfile, IUserLayoutStore layoutStore ) throws Exception {
this ( person, userProfile );
this.layoutStore = (AggregatedUserLayoutStore) layoutStore;
this.loadUserLayout();
}
private void updateCacheKey() {
cacheKey = guid.getNewGuid();
}
public IUserLayout getUserLayout() throws PortalException {
return layout;
}
public void setUserLayout(IUserLayout userLayout) throws PortalException {
if ( !(layout instanceof AggregatedLayout) )
throw new PortalException ( "The user layout instance must have AggregatedLayout type!" );
this.layout = (AggregatedLayout) layout;
updateCacheKey();
}
/**
* A factory method to create an empty <code>IUserLayoutNodeDescription</code> instance
*
* @param nodeType a node type value
* @return an <code>IUserLayoutNodeDescription</code> instance
* @exception PortalException if the error occurs.
*/
public IUserLayoutNodeDescription createNodeDescription( int nodeType ) throws PortalException {
IALNodeDescription nodeDesc = null;
switch ( nodeType ) {
case IUserLayoutNodeDescription.FOLDER:
nodeDesc = new ALFolderDescription();
break;
case IUserLayoutNodeDescription.CHANNEL:
nodeDesc = new ALChannelDescription();
break;
}
// Adding the user priority restriction
if ( nodeDesc != null ) {
int[] priorityRange = UserPriorityManager.getPriorityRange(person);
PriorityRestriction restriction = new PriorityRestriction();
restriction.setRestriction(priorityRange[0],priorityRange[1]);
nodeDesc.addRestriction(restriction);
}
return nodeDesc;
}
/**
* Sets a layout manager to auto-commit mode that allows to update the database immediately
* @param autoCommit a boolean value
*/
public void setAutoCommit (boolean autoCommit) {
this.autoCommit = autoCommit;
}
/**
* Returns an Id of the current user layout.
*
* @return a <code>int</code> value
*/
public int getLayoutId() {
return userProfile.getLayoutId();
}
/**
* Returns an Id of a parent user layout node.
* The user layout root node always has ID="root"
*
* @param nodeId a <code>String</code> value
* @return a <code>String</code> value
* @exception PortalException if an error occurs
*/
public String getParentId(String nodeId) throws PortalException {
return layout.getParentId(nodeId);
}
/**
* Returns a list of child node Ids for a given node.
*
* @param nodeId a <code>String</code> value
* @return a <code>Enumeration</code> of <code>String</code> child node Ids.
* @exception PortalException if an error occurs
*/
public Enumeration getChildIds(String nodeId) throws PortalException {
return layout.getChildIds(nodeId);
}
/**
* Determine an Id of a previous sibling node.
*
* @param nodeId a <code>String</code> node ID
* @return a <code>String</code> Id value of a previous sibling node, or <code>null</code> if this is the first sibling.
* @exception PortalException if an error occurs
*/
public String getPreviousSiblingId(String nodeId) throws PortalException {
return layout.getPreviousSiblingId(nodeId);
}
/**
* Determine an Id of a next sibling node.
*
* @param nodeId a <code>String</code> node ID
* @return a <code>String</code> Id value of a next sibling node, or <code>null</code> if this is the last sibling.
* @exception PortalException if an error occurs
*/
public String getNextSiblingId(String nodeId) throws PortalException {
return layout.getNextSiblingId(nodeId);
}
/**
* Checks the restriction specified by the parameters below
* @param nodeId a <code>String</code> node ID
* @param restrictionType a restriction type
* @param restrictionPath a <code>String</code> restriction path
* @param propertyValue a <code>String</code> property value to be checked
* @return a boolean value
* @exception PortalException if an error occurs
*/
protected boolean checkRestriction(String nodeId, int restrictionType, String restrictionPath, String propertyValue) throws PortalException {
ALNode node = getLayoutNode(nodeId);
return (node!=null)?checkRestriction(node,restrictionType,restrictionPath,propertyValue):true;
}
/**
* Checks the local restriction specified by the parameters below
* @param nodeId a <code>String</code> node ID
* @param restrictionType a restriction type
* @param propertyValue a <code>String</code> property value to be checked
* @return a boolean value
* @exception PortalException if an error occurs
*/
protected boolean checkRestriction(String nodeId, int restrictionType, String propertyValue ) throws PortalException {
return (nodeId!=null)?checkRestriction(nodeId, restrictionType, UserLayoutRestriction.LOCAL_RESTRICTION, propertyValue):true;
}
/**
* Checks the restriction specified by the parameters below
* @param node a <code>ALNode</code> node to be checked
* @param restrictionType a restriction type
* @param restrictionPath a <code>String</code> restriction path
* @param propertyValue a <code>String</code> property value to be checked
* @return a boolean value
* @exception PortalException if an error occurs
*/
protected boolean checkRestriction(ALNode node, int restrictionType, String restrictionPath, String propertyValue) throws PortalException {
IUserLayoutRestriction restriction = node.getRestriction(UserLayoutRestriction.getRestrictionName(restrictionType,restrictionPath));
if ( restriction != null )
return restriction.checkRestriction(propertyValue);
return true;
}
private void moveWrongFragmentsToLostFolder() throws PortalException {
Collection nodes = layoutStore.getIncorrectPushedFragmentNodes(person,userProfile);
for ( Iterator i = nodes.iterator(); i.hasNext(); ) {
String nodeId = (String) i.next();
ALNode node = getLayoutNode(nodeId);
if ( node != null && nodeId != null ) {
if ( !moveNodeToLostFolder(nodeId) )
LogService.log(LogService.INFO, "Unable to move the pushed fragment with ID="+node.getFragmentId()+" to the lost folder");
}
}
}
/**
* Moves the nodes to the lost folder if they don't satisfy their restrictions
* @exception PortalException if an error occurs
*/
protected void moveWrongNodesToLostFolder() throws PortalException {
moveWrongNodesToLostFolder(getRootFolderId(),0);
}
/**
* Moves the nodes to the lost folder if they don't satisfy their restrictions
* @param nodeId a <code>String</code> node ID
* @param depth a depth of the given node
* @exception PortalException if an error occurs
*/
private void moveWrongNodesToLostFolder(String nodeId, int depth) throws PortalException {
ALNode node = getLayoutNode(nodeId);
// Checking restrictions on the node
Vector restrictions = node.getRestrictionsByPath(UserLayoutRestriction.LOCAL_RESTRICTION);
for ( int i = 0; i < restrictions.size(); i++ ) {
IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i);
// check other restrictions except priority and depth
if ( ( restriction.getRestrictionType() & (RestrictionTypes.DEPTH_RESTRICTION | RestrictionTypes.PRIORITY_RESTRICTION )) == 0
&& !restriction.checkRestriction(node) ) {
moveNodeToLostFolder(nodeId);
break;
}
}
// Checking the depth restriction
if ( !checkRestriction(nodeId,RestrictionTypes.DEPTH_RESTRICTION,depth+"") ) {
moveNodeToLostFolder(nodeId);
}
// Checking children related restrictions on the children if they exist
restrictions = node.getRestrictionsByPath("children");
boolean isFolder = (node.getNodeType() == IUserLayoutNodeDescription.FOLDER );
if ( isFolder ) {
for ( int i = 0; i < restrictions.size(); i++ ) {
IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i);
for ( String nextId = ((ALFolder)node).getFirstChildNodeId(); nextId != null; ) {
ALNode nextNode = getLayoutNode(nextId);
String tmpNodeId = nextNode.getNextNodeId();
if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 &&
!restriction.checkRestriction(nextNode) ) {
moveNodeToLostFolder(nextId);
}
nextId = tmpNodeId;
}
}
}
// Checking parent related restrictions on the parent if it exists
String parentNodeId = node.getParentNodeId();
if ( parentNodeId != null ) {
restrictions = node.getRestrictionsByPath("parent");
ALNode parentNode = getLayoutNode(parentNodeId);
for ( int i = 0; i < restrictions.size(); i++ ) {
IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i);
if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 &&
!restriction.checkRestriction(parentNode) ) {
moveNodeToLostFolder(nodeId);
break;
}
}
}
if ( isFolder ) {
++depth;
ALFolder folder = (ALFolder) node;
String firstChildId = folder.getFirstChildNodeId();
if ( firstChildId != null ) {
String id = getLastSiblingNode(firstChildId).getId();
while ( id != null && !changeSiblingNodesOrder(folder.getFirstChildNodeId()) ) {
String lastNodeId = getLastSiblingNode(id).getId();
id = getLayoutNode(lastNodeId).getPreviousNodeId();
moveNodeToLostFolder(lastNodeId);
}
for ( String nextId = folder.getFirstChildNodeId(); nextId != null;
nextId = getLayoutNode(nextId).getNextNodeId() )
moveWrongNodesToLostFolder(nextId,depth);
}
}
}
// Gets the content of the lost folder
public String getLostFolderXML() throws PortalException {
Document document = DocumentFactory.getNewDocument();
layout.writeTo(ALFolderDescription.LOST_FOLDER_ID,document);
return org.jasig.portal.utils.XML.serializeNode(document);
}
/**
* Checks the local restriction specified by the parameters below
* @param node a <code>ALNode</code> node to be checked
* @param restrictionType a restriction type
* @param propertyValue a <code>String</code> property value to be checked
* @return a boolean value
* @exception PortalException if an error occurs
*/
protected boolean checkRestriction(ALNode node, int restrictionType, String propertyValue ) throws PortalException {
return checkRestriction(node, restrictionType, UserLayoutRestriction.LOCAL_RESTRICTION, propertyValue);
}
/**
* Checks the necessary restrictions while adding a new node
* @param nodeDesc a <code>IALNodeDescription</code> node description of a new node to be added
* @param parentId a <code>String</code> parent node ID
* @param nextSiblingId a <code>String</code> next sibling node ID
* @return a boolean value
* @exception PortalException if an error occurs
*/
private boolean checkAddRestrictions( IALNodeDescription nodeDesc, String parentId, String nextSiblingId ) throws PortalException {
String newNodeId = nodeDesc.getId();
ALNode newNode = null;
if ( newNodeId == null ) {
if ( nodeDesc instanceof IALChannelDescription )
newNode = new ALChannel((IALChannelDescription)nodeDesc);
else
newNode = new ALFolder((IALFolderDescription)nodeDesc);
} else
newNode = getLayoutNode(newNodeId);
ALNode parentNode = getLayoutNode(parentId);
if ( !(parentNode.getNodeType()==IUserLayoutNodeDescription.FOLDER ) )
throw new PortalException ("The target parent node should be a folder!");
//if ( checkRestriction(parentNode,RestrictionTypes.IMMUTABLE_RESTRICTION,"false") ) {
if ( !parentNode.getNodeDescription().isImmutable() ) {
// Checking children related restrictions
Vector restrictions = parentNode.getRestrictionsByPath("children");
for ( int i = 0; i < restrictions.size(); i++ ) {
IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i);
if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 &&
!restriction.checkRestriction(newNode) )
return false;
}
// Checking parent related restrictions
restrictions = newNode.getRestrictionsByPath("parent");
for ( int i = 0; i < restrictions.size(); i++ ) {
IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i);
if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 &&
!restriction.checkRestriction(parentNode) )
return false;
}
// Considering two cases if the node is new or it is already in the user layout
if ( newNodeId != null ) {
// Checking depth restrictions for the node and all its descendants (if there are any)
if ( !checkDepthRestrictions(newNodeId,parentId) )
return false;
} else
return checkRestriction(newNode,RestrictionTypes.DEPTH_RESTRICTION,(getDepth(parentId)+1)+"");
// Checking sibling nodes order
return changeSiblingNodesPriorities(newNode,parentId,nextSiblingId);
} else
return false;
}
/**
* Checks the necessary restrictions while moving a node
* @param nodeId a <code>String</code> node ID of a node to be moved
* @param newParentId a <code>String</code> new parent node ID
* @param nextSiblingId a <code>String</code> next sibling node ID
* @return a boolean value
* @exception PortalException if an error occurs
*/
private boolean checkMoveRestrictions( String nodeId, String newParentId, String nextSiblingId ) throws PortalException {
ALNode node = getLayoutNode(nodeId);
ALNode oldParentNode = getLayoutNode(node.getParentNodeId());
ALFolder newParentNode = getLayoutFolder(newParentId);
/*if ( checkRestriction(oldParentNode,RestrictionTypes.IMMUTABLE_RESTRICTION,"false") &&
checkRestriction(newParentNode,RestrictionTypes.IMMUTABLE_RESTRICTION,"false") ) {*/
if ( !oldParentNode.getNodeDescription().isImmutable() && !newParentNode.getNodeDescription().isImmutable() ) {
if ( !oldParentNode.equals(newParentNode) ) {
// Checking children related restrictions
Vector restrictions = newParentNode.getRestrictionsByPath("children");
for ( int i = 0; i < restrictions.size(); i++ ) {
IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i);
if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 &&
!restriction.checkRestriction(node) )
return false;
}
// Checking parent related restrictions
restrictions = node.getRestrictionsByPath("parent");
for ( int i = 0; i < restrictions.size(); i++ ) {
IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i);
if ( (restriction.getRestrictionType() & RestrictionTypes.DEPTH_RESTRICTION) == 0 &&
!restriction.checkRestriction(newParentNode) )
return false;
}
// Checking depth restrictions for the node and all its descendants
if ( !checkDepthRestrictions(nodeId,newParentId) )
return false;
}
// Checking sibling nodes order in the line where the node is being moved to
//String firstChildId = newParentNode.getFirstChildNodeId();
//return (firstChildId!=null)?changeSiblingNodesPriorities(firstChildId):true;
return changeSiblingNodesPriorities(node,newParentId,nextSiblingId);
} else
return false;
}
/**
* Checks the necessary restrictions while deleting a node
* @param nodeId a <code>String</code> node ID of a node to be deleted
* @return a boolean value
* @exception PortalException if an error occurs
*/
private boolean checkDeleteRestrictions( String nodeId ) throws PortalException {
ALNode node = getLayoutNode(nodeId);
if ( nodeId == null || node == null ) return true;
//if ( checkRestriction(node.getParentNodeId(),RestrictionTypes.IMMUTABLE_RESTRICTION,"false") ) {
if ( !getLayoutNode(node.getParentNodeId()).getNodeDescription().isImmutable() ) {
// Checking the unremovable restriction on the node to be deleted
//return checkRestriction(nodeId,RestrictionTypes.UNREMOVABLE_RESTRICTION,"false");
return !node.getNodeDescription().isUnremovable();
} else
return false;
}
/**
* Recursively checks the depth restrictions beginning with a given node
* @param nodeId a <code>String</code> node ID
* @param newParentId a <code>String</code> new parent node ID
* @return a boolean value
* @exception PortalException if an error occurs
*/
private boolean checkDepthRestrictions(String nodeId,String newParentId) throws PortalException {
if ( nodeId == null ) return true;
int nodeDepth = getDepth(nodeId);
int parentDepth = getDepth(newParentId);
if ( nodeDepth == parentDepth+1 ) return true;
return checkDepthRestrictions(nodeId,newParentId,nodeDepth);
}
/**
* Recursively checks the depth restrictions beginning with a given node
* @param nodeId a <code>String</code> node ID
* @param newParentId a <code>String</code> new parent node ID
* @param parentDepth a parent depth
* @return a boolean value
* @exception PortalException if an error occurs
*/
private boolean checkDepthRestrictions(String nodeId,String newParentId,int parentDepth) throws PortalException {
ALNode node = getLayoutNode(nodeId);
// Checking restrictions for the node
if ( !checkRestriction(nodeId,RestrictionTypes.DEPTH_RESTRICTION,(parentDepth+1)+"") )
return false;
if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) {
for ( String nextId = ((ALFolder)node).getFirstChildNodeId(); nextId != null; nextId = node.getNextNodeId() ) {
node = getLayoutNode(nextId);
if ( !checkDepthRestrictions(nextId,node.getParentNodeId(),parentDepth+1) )
return false;
}
}
return true;
}
/**
* Gets the tree depth for a given node
* @param nodeId a <code>String</code> node ID
* @return a depth value
* @exception PortalException if an error occurs
*/
public int getDepth(String nodeId) throws PortalException {
int depth = 0;
for ( String parentId = getParentId(nodeId); parentId != null; parentId = getParentId(parentId), depth++ );
return depth;
}
/**
* Moves the node to the lost folder
* @param nodeId a <code>String</code> node ID
* @return a boolean value
* @exception PortalException if an error occurs
*/
private boolean moveNodeToLostFolder(String nodeId) throws PortalException {
ALFolder lostFolder = getLayoutFolder(IALFolderDescription.LOST_FOLDER_ID);
if ( lostFolder == null ) {
lostFolder = ALFolder.createLostFolder();
}
// Moving the node to the lost folder
return moveNode(nodeId,IALFolderDescription.LOST_FOLDER_ID,null);
}
/**
* Gets the restriction specified by the parameters below
* @param node a <code>ALNode</code> node
* @param restrictionType a restriction type
* @param restrictionPath a <code>String</code> restriction path
* @return a <code>IUserLayoutRestriction</code> instance
* @exception PortalException if an error occurs
*/
private static IUserLayoutRestriction getRestriction( ALNode node, int restrictionType, String restrictionPath ) throws PortalException {
return node.getRestriction(UserLayoutRestriction.getRestrictionName(restrictionType,restrictionPath));
}
/**
* Return a priority restriction for the given node.
* @return a <code>PriorityRestriction</code> object
* @exception PortalException if an error occurs
*/
public static PriorityRestriction getPriorityRestriction( ALNode node ) throws PortalException {
PriorityRestriction priorRestriction = getPriorityRestriction(node,UserLayoutRestriction.LOCAL_RESTRICTION);
if ( priorRestriction == null ) {
priorRestriction = (PriorityRestriction)
UserLayoutRestrictionFactory.createRestriction(RestrictionTypes.PRIORITY_RESTRICTION,"0-"+java.lang.Integer.MAX_VALUE,UserLayoutRestriction.LOCAL_RESTRICTION);
}
return priorRestriction;
}
/**
* Return a priority restriction for the given node.
* @return a <code>PriorityRestriction</code> object
* @exception PortalException if an error occurs
*/
private static PriorityRestriction getPriorityRestriction( ALNode node, String restrictionPath ) throws PortalException {
return (PriorityRestriction) getRestriction(node,RestrictionTypes.PRIORITY_RESTRICTION,restrictionPath);
}
/**
* Change if it's possible priority values for all the sibling nodes
* @param nodeId a <code>String</code> any node ID from the sibling line to be checked
* @return a boolean value
* @exception PortalException if an error occurs
*/
protected boolean changeSiblingNodesPriorities( String nodeId ) throws PortalException {
int tmpPriority = Integer.MAX_VALUE;
String firstNodeId = getFirstSiblingNode(nodeId).getId();
// Fill out the vector by priority values
for ( String nextId = firstNodeId; nextId != null; ) {
ALNode nextNode = getLayoutNode(nextId);
int[] nextRange = getPriorityRestriction(nextNode).getRange();
int value = Math.min(nextRange[1],tmpPriority-1);
if ( value < tmpPriority && value >= nextRange[0] ) {
nextNode.setPriority(value);
tmpPriority = value;
} else
return false;
nextId = nextNode.getNextNodeId();
}
return true;
}
/**
* Change if it's possible priority values for all the sibling nodes defined by the collection
* @param nodes a <code>Vector</code> instance with ALNode objects
* @return a boolean value
* @exception PortalException if an error occurs
*/
protected boolean changeSiblingNodesPriorities( Vector nodes ) throws PortalException {
int tmpPriority = Integer.MAX_VALUE;
// Fill out the vector by priority values
int size = nodes.size();
for ( int i = 0; i < size; i++ ) {
ALNode nextNode = (ALNode) nodes.get(i);
if ( nextNode == null ) return false;
int[] nextRange = getPriorityRestriction(nextNode).getRange();
int value = Math.min(nextRange[1],tmpPriority-1);
if ( value < tmpPriority && value >= nextRange[0] ) {
nextNode.setPriority(value);
tmpPriority = value;
} else
return false;
}
return true;
}
/**
* Change priority values for all the sibling nodes when trying to add a new node
* @param node a <code>ALNode</code> a node to be added
* @param parentNodeId a <code>String</code> parent node ID
* @param nextNodeId a <code>String</code> next sibling node ID
* @return a boolean value
* @exception PortalException if an error occurs
*/
protected synchronized boolean changeSiblingNodesPriorities(ALNode node, String parentNodeId, String nextNodeId ) throws PortalException {
ALNode firstNode = null, nextNode = null;
String firstNodeId = null;
int priority = 0, nextPriority = 0, prevPriority = 0, range[] = null, prevRange[] = null, nextRange[] = null;
PriorityRestriction priorityRestriction = null;
String nodeId = node.getId();
ALFolder parent = getLayoutFolder(parentNodeId);
if ( parentNodeId != null ) {
firstNodeId = parent.getFirstChildNodeId();
// if the node is equal the first node in the sibling line we get the next node
if ( nodeId.equals(firstNodeId) )
firstNodeId = node.getNextNodeId();
if ( firstNodeId == null ) return true;
} else
return false;
firstNode = getLayoutNode(firstNodeId);
if ( nextNodeId != null ) {
nextNode = getLayoutNode(nextNodeId);
nextPriority = nextNode.getPriority();
priorityRestriction = getPriorityRestriction(nextNode);
nextRange = priorityRestriction.getRange();
}
priority = node.getPriority();
priorityRestriction = getPriorityRestriction(node);
range = priorityRestriction.getRange();
// If we add a new node to the beginning of the sibling line
if ( firstNodeId.equals(nextNodeId) ) {
if ( range[1] <= nextRange[0] ) return false;
if ( priority > nextPriority ) return true;
if ( range[1] > nextPriority ) {
node.setPriority(range[1]);
return true;
}
if ( (nextPriority+1) <= range[1] && (nextPriority+1) >= range[0] ) {
node.setPriority(nextPriority+1);
return true;
}
}
// If we add a new node to the end of the sibling line
if ( nextNode == null ) {
// Getting the last node
ALNode lastNode = getLastSiblingNode(firstNodeId);
int lastPriority = lastNode.getPriority();
PriorityRestriction lastPriorityRestriction = getPriorityRestriction(lastNode);
int[] lastRange = lastPriorityRestriction.getRange();
if ( range[0] >= lastRange[1] ) return false;
if ( priority < lastPriority ) return true;
if ( range[0] < lastPriority ) {
node.setPriority(range[0]);
return true;
}
if ( (lastPriority-1) <= range[1] && (lastPriority-1) >= range[0] ) {
node.setPriority(range[0]);
return true;
}
}
// If we add a new node in a general case
if ( nextNode != null && !nextNode.equals(firstNode) && !nodeId.equals(nextNodeId) ) {
// Getting the last node
ALNode prevNode = getLayoutNode(nextNode.getPreviousNodeId());
prevPriority = prevNode.getPriority();
PriorityRestriction lastPriorityRestriction = getPriorityRestriction(prevNode);
prevRange = lastPriorityRestriction.getRange();
if ( range[1] <= nextRange[0] || range[0] >= prevRange[1] ) return false;
if ( priority < prevPriority && priority > nextPriority ) return true;
int maxPossibleLowValue = Math.max(range[0],nextPriority+1);
int minPossibleHighValue = Math.min(range[1],prevPriority-1);
if ( minPossibleHighValue >= maxPossibleLowValue ) {
node.setPriority(minPossibleHighValue);
return true;
}
}
Vector nodes = new Vector();
for ( String nextId = firstNodeId; nextId != null; ) {
if ( !nextId.equals(nodeId) ) {
if ( nextId.equals(nextNodeId) )
nodes.add(node);
nodes.add(getLayoutNode(nextId));
}
nextId = getLayoutNode(nextId).getNextNodeId();
}
if ( nextNodeId == null )
nodes.add(node);
return changeSiblingNodesPriorities(nodes);
}
/**
* Change the sibling nodes order depending on their priority values
* @param firstNodeId a <code>String</code> first node ID in the sibling line
* @return a boolean value
* @exception PortalException if an error occurs
*/
protected boolean changeSiblingNodesOrder(String firstNodeId) throws PortalException {
if ( firstNodeId == null )
throw new PortalException ( "The first node ID in the sibling line cannot be NULL!" );
ALNode firstNode = getLayoutNode(firstNodeId);
String parentNodeId = firstNode.getParentNodeId();
boolean rightOrder = true;
ALNode node = null;
for ( String nextNodeId = firstNodeId; nextNodeId != null; ) {
node = getLayoutNode(nextNodeId);
nextNodeId = node.getNextNodeId();
if ( nextNodeId != null ) {
ALNode nextNode = getLayoutNode(nextNodeId);
if ( node.getPriority() <= nextNode.getPriority() ) {
rightOrder = false;
break;
}
}
}
if ( rightOrder ) return true;
// Check if the current order is right
if ( changeSiblingNodesPriorities(firstNodeId) ) return true;
Set movedNodes = new HashSet();
// Choosing more suitable order of the nodes in the sibling line
for ( String lastNodeId = getLastSiblingNode(firstNodeId).getId(); lastNodeId != null; ) {
for ( String curNodeId = lastNodeId; curNodeId != null; ) {
if ( !lastNodeId.equals(curNodeId) && !movedNodes.contains(lastNodeId) ) {
if ( moveNode(lastNodeId,parentNodeId,curNodeId) ) {
if ( changeSiblingNodesPriorities(getLayoutFolder(parentNodeId).getFirstChildNodeId()) )
return true;
movedNodes.add(lastNodeId);
lastNodeId = getLastSiblingNode(curNodeId).getId();
curNodeId = lastNodeId;
}
}
curNodeId = getLayoutNode(curNodeId).getPreviousNodeId();
}
if ( !movedNodes.contains(lastNodeId) ) {
if ( moveNode(lastNodeId,parentNodeId,null) ) {
if ( changeSiblingNodesPriorities(getLayoutFolder(parentNodeId).getFirstChildNodeId()) )
return true;
movedNodes.add(lastNodeId);
}
}
lastNodeId = getLayoutNode(lastNodeId).getPreviousNodeId();
}
return false;
}
/**
* Return a cache key, uniqly corresponding to the composition and the structure of the user layout.
*
* @return a <code>String</code> value
* @exception PortalException if an error occurs
*/
public String getCacheKey() throws PortalException {
return cacheKey;
}
/**
* Output a tree of a user layout (with appropriate markings) defined by a particular node into
* a <code>ContentHandler</code>
* @param contentHandler a <code>ContentHandler</code> value
* @exception PortalException if an error occurs
*/
public void getUserLayout(ContentHandler contentHandler) throws PortalException {
layout.writeTo(contentHandler);
}
/**
* Output subtree of a user layout (with appropriate markings) defined by a particular node into
* a <code>ContentHandler</code>
*
* @param nodeId a <code>String</code> a node determining a user layout subtree.
* @param contentHandler a <code>ContentHandler</code> value
* @exception PortalException if an error occurs
*/
public void getUserLayout(String nodeId, ContentHandler contentHandler) throws PortalException {
layout.writeTo(nodeId,contentHandler);
}
private ALNode getLayoutNode(String nodeId) {
return layout.getLayoutNode(nodeId);
}
private ALFolder getLayoutFolder(String folderId) {
return layout.getLayoutFolder(folderId);
}
private ALNode getLastSiblingNode ( String nodeId ) {
return layout.getLastSiblingNode(nodeId);
}
private ALNode getFirstSiblingNode ( String nodeId ) {
return layout.getFirstSiblingNode(nodeId);
}
public Document getUserLayoutDOM() throws PortalException {
Document document = DocumentFactory.getNewDocument();
layout.writeTo(document);
return document;
}
private void setUserLayoutDOM( Node n, String parentNodeId, Hashtable layoutData ) throws PortalException {
Element node = (Element) n;
NodeList childNodes = node.getChildNodes();
IALNodeDescription nodeDesc = ALNode.createUserLayoutNodeDescription(node);
String nodeId = node.getAttribute("ID");
nodeDesc.setId(nodeId);
nodeDesc.setName(node.getAttribute("name"));
nodeDesc.setFragmentId(node.getAttribute("fragmentID"));
nodeDesc.setHidden(CommonUtils.strToBool(node.getAttribute("hidden")));
nodeDesc.setImmutable(CommonUtils.strToBool(node.getAttribute("immutable")));
nodeDesc.setUnremovable(CommonUtils.strToBool(node.getAttribute("unremovable")));
nodeDesc.setHidden(CommonUtils.strToBool(node.getAttribute("hidden")));
ALNode layoutNode = null;
IALChannelDescription channelDesc = null;
if (nodeDesc instanceof IALChannelDescription)
channelDesc = (IALChannelDescription) nodeDesc;
// Getting parameters and restrictions
for ( int i = 0; i < childNodes.getLength(); i++ ) {
Node childNode = childNodes.item(i);
String nodeName = childNode.getNodeName();
NamedNodeMap attributes = childNode.getAttributes();
if ( IAggregatedLayout.PARAMETER.equals(nodeName) && channelDesc != null ) {
Node paramNameNode = attributes.getNamedItem("name");
String paramName = (paramNameNode!=null)?paramNameNode.getFirstChild().getNodeValue():null;
Node paramValueNode = attributes.getNamedItem("value");
String paramValue = (paramValueNode!=null && paramValueNode.getFirstChild()!=null)?paramValueNode.getFirstChild().getNodeValue():null;
Node overParamNode = attributes.getNamedItem("override");
String overParam = (overParamNode!=null)?overParamNode.getFirstChild().getNodeValue():"yes";
if ( paramName != null && paramValue != null ) {
channelDesc.setParameterValue(paramName, paramValue);
channelDesc.setParameterOverride(paramName, "yes".equalsIgnoreCase(overParam)?true:false);
}
} else if ( IAggregatedLayout.RESTRICTION.equals(nodeName) ) {
Node restrPathNode = attributes.getNamedItem("path");
String restrPath = (restrPathNode!=null)?restrPathNode.getFirstChild().getNodeValue():null;
Node restrValueNode = attributes.getNamedItem("value");
String restrValue = (restrValueNode!=null)?restrValueNode.getFirstChild().getNodeValue():null;
Node restrTypeNode = attributes.getNamedItem("type");
String restrType = (restrTypeNode!=null)?restrTypeNode.getFirstChild().getNodeValue():"0";
if ( restrValue != null && restrPathNode != null ) {
IUserLayoutRestriction restriction = UserLayoutRestrictionFactory.createRestriction(CommonUtils.parseInt(restrType),restrValue,restrPath);
nodeDesc.addRestriction(restriction);
}
}
}
if ( channelDesc != null ) {
channelDesc.setChannelPublishId(node.getAttribute("chanID"));
channelDesc.setChannelTypeId(node.getAttribute("typeID"));
channelDesc.setClassName(node.getAttribute("class"));
channelDesc.setDescription(node.getAttribute("description"));
channelDesc.setEditable(CommonUtils.strToBool(node.getAttribute("editable")));
channelDesc.setHasAbout(CommonUtils.strToBool(node.getAttribute("hasAbout")));
channelDesc.setHasHelp(CommonUtils.strToBool(node.getAttribute("hasHelp")));
channelDesc.setIsSecure(CommonUtils.strToBool(node.getAttribute("secure")));
channelDesc.setFunctionalName(node.getAttribute("fname"));
channelDesc.setTimeout(Long.parseLong(node.getAttribute("timeout")));
channelDesc.setTitle(node.getAttribute("title"));
// Adding to the layout
layoutNode = new ALChannel(channelDesc);
} else {
layoutNode = new ALFolder((IALFolderDescription)nodeDesc);
}
// Setting priority value
layoutNode.setPriority(CommonUtils.parseInt(node.getAttribute("priority"),0));
ALFolder parentFolder = getLayoutFolder(parentNodeId);
// Binding the current node to the parent child list and parentNodeId to the current node
if ( parentFolder != null ) {
//parentFolder.addChildNode(nodeDesc.getId());
layoutNode.setParentNodeId(parentNodeId);
}
Element nextNode = (Element) node.getNextSibling();
Element prevNode = (Element) node.getPreviousSibling();
if ( nextNode != null && isNodeFolderOrChannel(nextNode) )
layoutNode.setNextNodeId(nextNode.getAttribute("ID"));
if ( prevNode != null && isNodeFolderOrChannel(prevNode) )
layoutNode.setPreviousNodeId(prevNode.getAttribute("ID") );
// Setting the first child node ID
if ( layoutNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) {
String id = ((Element)node.getFirstChild()).getAttribute("ID");
if ( id != null && id.length() > 0 )
((ALFolder)layoutNode).setFirstChildNodeId(id);
}
// Putting the LayoutNode object into the layout
layoutData.put(nodeDesc.getId(), layoutNode);
// Recurrence for all children
for ( int i = 0; i < childNodes.getLength() && (layoutNode.getNodeType()==IUserLayoutNodeDescription.FOLDER); i++ ) {
Element childNode = (Element) childNodes.item(i);
if ( isNodeFolderOrChannel ( childNode ) )
setUserLayoutDOM ( childNode, nodeDesc.getId(), layoutData );
}
}
public void setUserLayoutDOM( Document domLayout ) throws PortalException {
Hashtable layoutData = new Hashtable();
String rootId = getRootFolderId();
Element rootNode = (Element) domLayout.getDocumentElement().getFirstChild();
ALFolder rootFolder = new ALFolder((IALFolderDescription)ALNode.createUserLayoutNodeDescription(rootNode));
rootFolder.setFirstChildNodeId(((Element)rootNode.getFirstChild()).getAttribute("ID"));
layoutData.put(rootId,rootFolder);
NodeList childNodes = rootNode.getChildNodes();
layout.setLayoutData(layoutData);
for ( int i = 0; i < childNodes.getLength(); i++ )
setUserLayoutDOM ( childNodes.item(i), rootId, layoutData );
updateCacheKey();
}
private boolean isNodeFolderOrChannel ( Element node ) {
String nodeName = node.getNodeName();
return ( IAggregatedLayout.FOLDER.equals(nodeName) || IAggregatedLayout.CHANNEL.equals(nodeName) );
}
public void setLayoutStore(IUserLayoutStore layoutStore ) {
this.layoutStore = (AggregatedUserLayoutStore) layoutStore;
}
public void loadUserLayout() throws PortalException {
try {
if ( layoutStore != null ) {
fragmentId = null;
layout = (AggregatedLayout) layoutStore.getAggregatedLayout(person,userProfile);
layout.setLayoutManager(this);
// Setting the first child node id for the root node to NULL if it does not exist in the layout
ALFolder rootFolder = getLayoutFolder(getRootFolderId());
String firstChildId = rootFolder.getFirstChildNodeId();
if ( firstChildId != null && getLayoutNode(firstChildId) == null )
rootFolder.setFirstChildNodeId(null);
// Moving the wrong pushed fragments to the lost folder
moveWrongFragmentsToLostFolder();
// Checking restrictions and move "wrong" nodes to the lost folder
moveWrongNodesToLostFolder();
// Inform layout listeners
for(Iterator i = listeners.iterator(); i.hasNext();) {
LayoutEventListener lel = (LayoutEventListener)i.next();
lel.layoutLoaded();
}
updateCacheKey();
}
} catch ( Exception e ) {
LogService.log(LogService.ERROR, e);
throw new PortalException(e.getMessage());
}
}
/**
* Returns true if any fragment is currently loaded into the layout manager,
* false - otherwise
* @return a boolean value
* @exception PortalException if an error occurs
*/
public boolean isFragmentLoaded() throws PortalException {
return isLayoutFragment();
}
public void saveUserLayout() throws PortalException {
try {
if ( !isLayoutFragment() ) {
layoutStore.setAggregatedLayout(person,userProfile,layout);
// Inform layout listeners
for(Iterator i = listeners.iterator(); i.hasNext();) {
LayoutEventListener lel = (LayoutEventListener)i.next();
lel.layoutSaved();
}
} else {
saveFragment();
}
updateCacheKey();
} catch ( Exception e ) {
throw new PortalException(e.getMessage());
}
}
public void saveFragment ( ILayoutFragment fragment ) throws PortalException {
layoutStore.setFragment(person,fragment);
}
public void deleteFragment ( String fragmentId ) throws PortalException {
layoutStore.deleteFragment(person,fragmentId);
}
/**
* Returns the list of Ids of the fragments that the user can subscribe to
* @return <code>Collection</code> a set of the fragment IDs
* @exception PortalException if an error occurs
*/
public Collection getSubscribableFragments() throws PortalException {
return layoutStore.getSubscribableFragments(person);
}
public Collection getFragments () throws PortalException {
return layoutStore.getFragments(person).keySet();
}
/**
* Returns the user group keys which the fragment is published to
* @param fragmentId a <code>String</code> value
* @return a <code>Collection</code> object containing the group keys
* @exception PortalException if an error occurs
*/
public Collection getPublishGroups (String fragmentId ) throws PortalException {
return layoutStore.getPublishGroups(person,fragmentId);
}
/**
* Persists the user groups which the fragment is published to
* @param groups an array of <code>IGroupMember</code> objects
* @param fragmentId a <code>String</code> value
* @exception PortalException if an error occurs
*/
public void setPublishGroups ( IGroupMember[] groups, String fragmentId ) throws PortalException {
layoutStore.setPublishGroups(groups,person,fragmentId);
}
public ILayoutFragment getFragment ( String fragmentId ) throws PortalException {
return layoutStore.getFragment(person,fragmentId);
}
public String createFragment( String fragmentName, String fragmentDesc, String fragmentRootName ) throws PortalException {
try {
// Creating an empty layout with a root folder
String newFragmentId = layoutStore.getNextFragmentId();
ALFragment fragment = new ALFragment (newFragmentId,this);
// Creating the layout root node
ALFolder rootFolder = ALFolder.createRootFolder();
// Creating the fragment root node
ALFolderDescription nodeDesc = (ALFolderDescription) createNodeDescription(IUserLayoutNodeDescription.FOLDER);
// Setting the root fragment ID = 1
nodeDesc.setId("1");
nodeDesc.setName(fragmentRootName);
nodeDesc.setFolderType(IUserLayoutFolderDescription.REGULAR_TYPE);
// Setting the fragment ID
nodeDesc.setFragmentId(newFragmentId);
//Creating a new folder with the folder description
ALFolder fragmentRoot = new ALFolder(nodeDesc);
//Updating the DB and getting the node ID for the new node
//fragmentRoot = layoutStore.addUserLayoutNode(person,userProfile,fragmentRoot);
// Setting the link between the layout root and the fragment root
fragmentRoot.setParentNodeId(rootFolder.getId());
rootFolder.setFirstChildNodeId(fragmentRoot.getId());
// Fill the hashtable with the new nodes
Hashtable layoutData = new Hashtable();
layoutData.put(rootFolder.getId(),rootFolder);
layoutData.put(fragmentRoot.getId(),fragmentRoot);
// Setting the layout data
fragment.setLayoutData(layoutData);
fragment.setName(fragmentName);
fragment.setDescription(fragmentDesc);
// Setting the fragment in the database
layoutStore.setFragment(person,fragment);
// Getting the list of the fragments
/*fragments = (Hashtable) layoutStore.getFragments(person);
if ( fragments != null && fragments.size() > 0 )
fragment.setFragments(fragments); */
updateCacheKey();
// Return a new fragment ID
return newFragmentId;
} catch ( Exception e ) {
e.printStackTrace();
throw new PortalException(e.getMessage());
}
}
public void loadFragment( String fragmentId ) throws PortalException {
try {
layout = (ALFragment) layoutStore.getFragment(person,fragmentId);
layout.setLayoutManager(this);
/*fragments = (Hashtable) layoutStore.getFragments(person);
if ( fragments != null && fragments.size() > 0 )
layout.setFragments(fragments);*/
this.fragmentId = fragmentId;
// Checking restrictions and move "wrong" nodes to the lost folder
//moveWrongNodesToLostFolder();
updateCacheKey();
} catch ( Exception e ) {
throw new PortalException(e.getMessage());
}
}
public void saveFragment() throws PortalException {
try {
if ( isLayoutFragment() ) {
layoutStore.setFragment(person,(ILayoutFragment)layout);
/*fragments = (Hashtable) layoutStore.getFragments(person);
if ( fragments != null && fragments.size() > 0 )
layout.setFragments(fragments);*/
}
updateCacheKey();
} catch ( Exception e ) {
throw new PortalException(e.getMessage());
}
}
/**
* Deletes the current fragment if the layout is a fragment
* @exception PortalException if an error occurs
*/
public void deleteFragment() throws PortalException {
try {
if ( isLayoutFragment() ) {
layoutStore.deleteFragment(person,fragmentId);
}
loadUserLayout();
updateCacheKey();
} catch ( Exception e ) {
throw new PortalException(e.getMessage());
}
}
private boolean isLayoutFragment() {
return ( fragmentId != null && layout != null );
}
public IUserLayoutNodeDescription getNode(String nodeId) throws PortalException {
return layout.getNodeDescription(nodeId);
}
public synchronized boolean moveNode(String nodeId, String parentId, String nextSiblingId) throws PortalException {
// if the node is being moved to itself that operation must be prevented
if ( nodeId.equals(nextSiblingId) )
return false;
ALNode node = getLayoutNode(nodeId);
// If the node is being moved to the same position
if ( parentId.equals(node.getParentNodeId()) )
if ( CommonUtils.nvl(nextSiblingId).equals(CommonUtils.nvl(node.getNextNodeId())))
return true;
// Checking restrictions if the parent is not the lost folder
if ( !parentId.equals(IALFolderDescription.LOST_FOLDER_ID) )
if ( !canMoveNode(nodeId,parentId,nextSiblingId) )
return false;
ALFolder targetFolder = getLayoutFolder(parentId);
ALFolder sourceFolder = getLayoutFolder(node.getParentNodeId());
String sourcePrevNodeId = node.getPreviousNodeId();
String sourceNextNodeId = node.getNextNodeId();
ALNode targetNextNode = getLayoutNode(nextSiblingId);
ALNode targetPrevNode = null, sourcePrevNode = null, sourceNextNode = null;
String prevSiblingId = null;
// If the nextNode != null we calculate the prev node from it otherwise we have to run to the last node in the sibling line
if ( targetNextNode != null )
targetPrevNode = getLayoutNode(targetNextNode.getPreviousNodeId());
else
targetPrevNode = getLastSiblingNode(targetFolder.getFirstChildNodeId());
if ( targetPrevNode != null ) {
targetPrevNode.setNextNodeId(nodeId);
prevSiblingId = targetPrevNode.getId();
}
// Changing the previous node id for the new next sibling node
if ( targetNextNode != null )
targetNextNode.setPreviousNodeId(nodeId);
if ( nodeId.equals(sourceFolder.getFirstChildNodeId()) ) {
// Set the new first child node ID to the source folder
sourceFolder.setFirstChildNodeId(node.getNextNodeId());
}
String firstChildId = targetFolder.getFirstChildNodeId();
if ( firstChildId == null || firstChildId.equals(nextSiblingId) ) {
// Set the new first child node ID to the target folder
targetFolder.setFirstChildNodeId(nodeId);
}
// Set the new next node ID for the source previous node
if ( sourcePrevNodeId != null ) {
sourcePrevNode = getLayoutNode(sourcePrevNodeId);
sourcePrevNode.setNextNodeId(sourceNextNodeId);
}
// Set the new previous node ID for the source next node
if ( sourceNextNodeId != null ) {
sourceNextNode = getLayoutNode(sourceNextNodeId);
sourceNextNode.setPreviousNodeId(sourcePrevNodeId);
}
node.setParentNodeId(parentId);
node.setNextNodeId(nextSiblingId);
node.setPreviousNodeId(prevSiblingId);
// TO UPDATE THE APPROPRIATE INFO IN THE DB
// TO BE DONE !!!!!!!!!!!
boolean result = true;
if ( autoCommit ) {
if ( sourcePrevNode != null ) result &= layoutStore.updateUserLayoutNode(person,userProfile,sourcePrevNode);
if ( sourceNextNode != null ) result &= layoutStore.updateUserLayoutNode(person,userProfile,sourceNextNode);
if ( targetPrevNode != null ) result &= layoutStore.updateUserLayoutNode(person,userProfile,targetPrevNode);
if ( targetNextNode != null ) result &= layoutStore.updateUserLayoutNode(person,userProfile,targetNextNode);
result &= layoutStore.updateUserLayoutNode(person,userProfile,targetFolder);
result &= layoutStore.updateUserLayoutNode(person,userProfile,sourceFolder);
// Changing the node being moved
result &= layoutStore.updateUserLayoutNode(person,userProfile,node);
}
if (result) {
// Inform the layout listeners
LayoutMoveEvent ev = new LayoutMoveEvent(this, getNode(nodeId), getParentId(nodeId));
for (Iterator i = listeners.iterator(); i.hasNext();) {
LayoutEventListener lel=(LayoutEventListener)i.next();
if (node.getNodeDescription().getType() == IUserLayoutNodeDescription.CHANNEL) {
lel.channelMoved(ev);
} else {
lel.folderMoved(ev);
}
}
}
updateCacheKey();
return result;
}
public synchronized boolean deleteNode(String nodeId) throws PortalException {
if ( nodeId == null ) return false;
ALNode node = getLayoutNode(nodeId);
if ( node == null ) return false;
// Checking restrictions
if ( !canDeleteNode(nodeId) ) {
LogService.log(LogService.DEBUG, "The node with ID = '" + nodeId + "' cannot be deleted");
return false;
}
// Inform the layout listeners
LayoutMoveEvent ev = new LayoutMoveEvent(this, node.getNodeDescription(), node.getParentNodeId());
for(Iterator i = listeners.iterator(); i.hasNext();) {
LayoutEventListener lel = (LayoutEventListener)i.next();
if(getNode(nodeId).getType() == IUserLayoutNodeDescription.CHANNEL) {
lel.channelDeleted(ev);
} else {
lel.folderDeleted(ev);
}
}
// Deleting the node from the parent
ALFolder parentFolder = getLayoutFolder(node.getParentNodeId());
boolean result = false;
if ( nodeId.equals(parentFolder.getFirstChildNodeId()) ) {
// Set the new first child node ID to the source folder
parentFolder.setFirstChildNodeId(node.getNextNodeId());
// Update it in the database
if ( autoCommit ) result = layoutStore.updateUserLayoutNode(person,userProfile,parentFolder);
}
// Changing the next node id for the previous sibling node
// and the previous node for the next sibling node
String prevSiblingId = node.getPreviousNodeId();
String nextSiblingId = node.getNextNodeId();
if ( prevSiblingId != null ) {
ALNode prevNode = getLayoutNode(prevSiblingId);
prevNode.setNextNodeId(nextSiblingId);
if ( autoCommit ) result = layoutStore.updateUserLayoutNode(person,userProfile,prevNode);
}
if ( nextSiblingId != null ) {
ALNode nextNode = getLayoutNode(nextSiblingId);
nextNode.setPreviousNodeId(prevSiblingId);
if ( autoCommit ) result = layoutStore.updateUserLayoutNode(person,userProfile,nextNode);
}
// DELETE THE NODE FROM THE DB
if ( autoCommit )
result = layoutStore.deleteUserLayoutNode(person,userProfile,node);
// Deleting the nodefrom the hashtable and returning the result value
result = (layout.getLayoutData().remove(nodeId)!=null) && ((autoCommit)?result:true);
updateCacheKey();
return result;
}
public synchronized IUserLayoutNodeDescription addNode(IUserLayoutNodeDescription nodeDesc, String parentId,String nextSiblingId) throws PortalException {
// Checking restrictions
if ( !canAddNode(nodeDesc,parentId,nextSiblingId) )
return null;
ALFolder parentFolder = getLayoutFolder(parentId);
ALNode nextNode = getLayoutNode(nextSiblingId);
ALNode prevNode = null;
// If the nextNode != null we calculate the prev node from it otherwise we have to run to the last node in the sibling line
if ( nextNode != null )
prevNode = getLayoutNode(nextNode.getPreviousNodeId());
else
prevNode = getLastSiblingNode( parentFolder.getFirstChildNodeId());
// If currently a fragment is loaded the node desc should have a fragment ID
if ( isFragmentLoaded() )
((IALNodeDescription)nodeDesc).setFragmentId(fragmentId);
ALNode layoutNode=ALNode.createALNode(nodeDesc);
// Setting the parent node ID
layoutNode.setParentNodeId(parentId);
if ( prevNode != null )
layoutNode.setPreviousNodeId(prevNode.getId());
if ( nextNode != null )
layoutNode.setNextNodeId(nextSiblingId);
// Add the new node to the database and get the node with a new node ID
if ( autoCommit )
layoutNode = layoutStore.addUserLayoutNode(person,userProfile,layoutNode);
else {
IALNodeDescription desc = layoutNode.getNodeDescription();
desc.setId(layoutStore.getNextNodeId(person));
if ( desc.getType() == IUserLayoutNodeDescription.CHANNEL )
layoutStore.fillChannelDescription((IALChannelDescription)desc);
}
String nodeId = layoutNode.getId();
// Putting the new node into the hashtable
layout.getLayoutData().put(nodeId,layoutNode);
if ( prevNode != null )
prevNode.setNextNodeId(nodeId);
if ( nextNode != null )
nextNode.setPreviousNodeId(nodeId);
// Setting new child node ID to the parent node
if ( prevNode == null )
parentFolder.setFirstChildNodeId(nodeId);
if ( autoCommit ) {
// TO UPDATE ALL THE NEIGHBOR NODES IN THE DATABASE
if ( nextNode != null )
layoutStore.updateUserLayoutNode(person,userProfile,nextNode);
if ( prevNode != null )
layoutStore.updateUserLayoutNode(person,userProfile,prevNode);
// Update the parent node
layoutStore.updateUserLayoutNode(person,userProfile,parentFolder);
}
// Inform the layout listeners
LayoutEvent ev = new LayoutEvent(this, layoutNode.getNodeDescription());
for (Iterator i = listeners.iterator(); i.hasNext();) {
LayoutEventListener lel = (LayoutEventListener)i.next();
if (layoutNode.getNodeDescription().getType() == IUserLayoutNodeDescription.CHANNEL) {
lel.channelAdded(ev);
} else {
lel.folderAdded(ev);
}
}
updateCacheKey();
return layoutNode.getNodeDescription();
}
private void changeDescendantsBooleanProperties (IALNodeDescription nodeDesc,IALNodeDescription oldNodeDesc, String nodeId) throws PortalException {
changeDescendantsBooleanProperties(nodeDesc.isHidden()==oldNodeDesc.isHidden(),nodeDesc.isImmutable()==oldNodeDesc.isImmutable(),
nodeDesc.isUnremovable()==oldNodeDesc.isUnremovable(),nodeDesc,nodeId);
updateCacheKey();
}
private void changeDescendantsBooleanProperties (boolean hiddenValuesMatch, boolean immutableValuesMatch, boolean unremovableValuesMatch,
IALNodeDescription nodeDesc, String nodeId) throws PortalException {
ALNode node = getLayoutNode(nodeId);
if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) {
// Loop for all children
String firstChildId = ((ALFolder)node).getFirstChildNodeId();
for ( String nextNodeId = firstChildId; nextNodeId != null; ) {
ALNode currentNode = getLayoutNode(nextNodeId);
// Checking the hidden property if it's changed
if ( !hiddenValuesMatch ) {
// Checking the hidden node restriction
boolean canChange = checkRestriction(currentNode,RestrictionTypes.HIDDEN_RESTRICTION,CommonUtils.boolToStr(nodeDesc.isHidden()));
// Checking the hidden parent node related restriction
canChange &= checkRestriction(currentNode.getParentNodeId(),RestrictionTypes.HIDDEN_RESTRICTION,"children",CommonUtils.boolToStr(nodeDesc.isHidden()));
// Checking the hidden children node related restrictions
if ( currentNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) {
ALFolder folder = (ALFolder) node;
//Loop for all children
for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() )
canChange &= checkRestriction(nextId,RestrictionTypes.HIDDEN_RESTRICTION,"parent",CommonUtils.boolToStr(nodeDesc.isHidden()));
}
// Changing the hidden value if canChange is true
if ( canChange )
currentNode.getNodeDescription().setHidden(nodeDesc.isHidden());
}
// Checking the immutable property if it's changed
if ( !immutableValuesMatch ) {
// Checking the immutable node restriction
boolean canChange = checkRestriction(currentNode,RestrictionTypes.IMMUTABLE_RESTRICTION,CommonUtils.boolToStr(nodeDesc.isImmutable()));
// Checking the immutable parent node related restriction
canChange &= checkRestriction(currentNode.getParentNodeId(),RestrictionTypes.IMMUTABLE_RESTRICTION,"children",CommonUtils.boolToStr(nodeDesc.isImmutable()));
// Checking the immutable children node related restrictions
if ( currentNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) {
ALFolder folder = (ALFolder) node;
//Loop for all children
for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() )
canChange &= checkRestriction(nextId,RestrictionTypes.IMMUTABLE_RESTRICTION,"parent",CommonUtils.boolToStr(nodeDesc.isImmutable()));
}
// Changing the immutable value if canChange is true
if ( canChange )
currentNode.getNodeDescription().setImmutable(nodeDesc.isImmutable());
}
// Checking the unremovable property if it's changed
if ( !unremovableValuesMatch ) {
// Checking the unremovable node restriction
boolean canChange = checkRestriction(currentNode,RestrictionTypes.UNREMOVABLE_RESTRICTION,CommonUtils.boolToStr(nodeDesc.isUnremovable()));
// Checking the unremovable parent node related restriction
canChange &= checkRestriction(currentNode.getParentNodeId(),RestrictionTypes.UNREMOVABLE_RESTRICTION,"children",CommonUtils.boolToStr(nodeDesc.isUnremovable()));
// Checking the unremovable children node related restrictions
if ( currentNode.getNodeType() == IUserLayoutNodeDescription.FOLDER ) {
ALFolder folder = (ALFolder) node;
//Loop for all children
for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() )
canChange &= checkRestriction(nextId,RestrictionTypes.UNREMOVABLE_RESTRICTION,"parent",CommonUtils.boolToStr(nodeDesc.isImmutable()));
}
// Changing the unremovable value if canChange is true
if ( canChange )
currentNode.getNodeDescription().setUnremovable(nodeDesc.isUnremovable());
}
/// Recurrence
changeDescendantsBooleanProperties(hiddenValuesMatch,immutableValuesMatch,unremovableValuesMatch,nodeDesc,nextNodeId);
nextNodeId = currentNode.getNextNodeId();
}
}
}
public synchronized boolean updateNode(IUserLayoutNodeDescription nodeDesc) throws PortalException {
// Checking restrictions
if ( !canUpdateNode(nodeDesc) )
return false;
ALNode node = getLayoutNode(nodeDesc.getId());
IALNodeDescription oldNodeDesc = node.getNodeDescription();
// We have to change all the boolean properties on descendants
changeDescendantsBooleanProperties((IALNodeDescription)nodeDesc,oldNodeDesc,nodeDesc.getId());
node.setNodeDescription((IALNodeDescription)nodeDesc);
// Inform the layout listeners
LayoutEvent ev = new LayoutEvent(this, nodeDesc);
for (Iterator i = listeners.iterator(); i.hasNext();) {
LayoutEventListener lel = (LayoutEventListener)i.next();
if (nodeDesc.getType() == IUserLayoutNodeDescription.CHANNEL) {
lel.channelUpdated(ev);
} else {
lel.folderUpdated(ev);
}
}
updateCacheKey();
// Update the node into the database
if ( autoCommit )
return layoutStore.updateUserLayoutNode(person,userProfile,node);
else
return true;
}
public boolean canAddNode(IUserLayoutNodeDescription nodeDesc, String parentId, String nextSiblingId) throws PortalException {
return checkAddRestrictions((IALNodeDescription)nodeDesc,parentId,nextSiblingId);
}
public boolean canMoveNode(String nodeId, String parentId, String nextSiblingId) throws PortalException {
return checkMoveRestrictions(nodeId,parentId,nextSiblingId);
}
public boolean canDeleteNode(String nodeId) throws PortalException {
return checkDeleteRestrictions(nodeId);
}
public boolean canUpdateNode(IUserLayoutNodeDescription nodeDescription) throws PortalException {
IALNodeDescription nodeDesc=(IALNodeDescription)nodeDescription;
String nodeId = nodeDesc.getId();
if ( nodeId == null ) return false;
ALNode node = getLayoutNode(nodeId);
IALNodeDescription currentNodeDesc = node.getNodeDescription();
// If the node Ids do no match to each other then return false
if ( !nodeId.equals(currentNodeDesc.getId()) ) return false;
// Checking the immutable node restriction
//if ( checkRestriction(node,RestrictionTypes.IMMUTABLE_RESTRICTION,"true") )
if ( currentNodeDesc.isImmutable() )
return false;
// Checking the immutable parent node related restriction
if ( getRestriction(getLayoutNode(node.getParentNodeId()),RestrictionTypes.IMMUTABLE_RESTRICTION,"children") != null &&
checkRestriction(node.getParentNodeId(),RestrictionTypes.IMMUTABLE_RESTRICTION,"children","true") )
return false;
// Checking the immutable children node related restrictions
if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) {
ALFolder folder = (ALFolder) node;
//Loop for all children
for ( String nextId = folder.getFirstChildNodeId(); nextId != null; nextId = getLayoutNode(nextId).getNextNodeId() )
if ( getRestriction(getLayoutNode(nextId),RestrictionTypes.IMMUTABLE_RESTRICTION,"parent") != null &&
checkRestriction(nextId,RestrictionTypes.IMMUTABLE_RESTRICTION,"parent","true") )
return false;
}
// if a new node description doesn't contain any restrictions the old restrictions will be used
if ( nodeDesc.getRestrictions() == null )
nodeDesc.setRestrictions(currentNodeDesc.getRestrictions());
Hashtable rhash = nodeDesc.getRestrictions();
// Setting the new node description to the node
node.setNodeDescription(nodeDesc);
// Checking restrictions for the node
if ( rhash != null ) {
for ( Enumeration enum = rhash.elements(); enum.hasMoreElements(); )
if ( !((IUserLayoutRestriction)enum.nextElement()).checkRestriction(node) ) {
node.setNodeDescription(currentNodeDesc);
return false;
}
}
// Checking parent related restrictions for the children
Vector restrictions = getLayoutNode(node.getParentNodeId()).getRestrictionsByPath("children");
for ( int i = 0; i < restrictions.size(); i++ ) {
IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i);
if ( !restriction.checkRestriction(node) ) {
node.setNodeDescription(currentNodeDesc);
return false;
}
}
// Checking child related restrictions for the parent
if ( node.getNodeType() == IUserLayoutNodeDescription.FOLDER ) {
for ( String nextId = ((ALFolder)node).getFirstChildNodeId(); nextId != null; ) {
ALNode child = getLayoutNode(nextId);
restrictions = child.getRestrictionsByPath("parent");
for ( int i = 0; i < restrictions.size(); i++ ) {
IUserLayoutRestriction restriction = (IUserLayoutRestriction)restrictions.get(i);
if ( !restriction.checkRestriction(node) ) {
node.setNodeDescription(currentNodeDesc);
return false;
}
}
nextId = child.getNextNodeId();
}
}
return true;
}
public void markAddTargets(IUserLayoutNodeDescription nodeDesc) throws PortalException {
if ( nodeDesc != null && !( nodeDesc instanceof IALNodeDescription ) )
throw new PortalException ( "The given argument is not a node description!" );
addTargetsNodeDesc = (IALNodeDescription)nodeDesc;
updateCacheKey();
}
public void markMoveTargets(String nodeId) throws PortalException {
if ( nodeId != null && getLayoutNode(nodeId) == null )
throw new PortalException ( "The node with nodeID="+nodeId+" does not exist in the layout!" );
moveTargetsNodeId = nodeId;
updateCacheKey();
}
/**
* Returns the description of the node currently being added to the layout
*
* @return node an <code>IALNodeDescription</code> object
* @exception PortalException if an error occurs
*/
public IALNodeDescription getNodeBeingAdded() throws PortalException {
return addTargetsNodeDesc;
}
/**
* Returns the description of the node currently being moved in the layout
*
* @return node an <code>IALNodeDescription</code> object
* @exception PortalException if an error occurs
*/
public IALNodeDescription getNodeBeingMoved() throws PortalException {
if ( moveTargetsNodeId != null ) {
ALNode node = getLayoutNode(moveTargetsNodeId);
return (node != null ) ? node.getNodeDescription() : null;
}
return null;
}
/**
* Sets a restriction mask that logically multiplies one of the types from <code>RestrictionTypes</code> and
* is responsible for filtering restrictions for the layout output to ContentHandler or DOM
* @param restrictionMask a restriction mask
*/
public void setRestrictionMask (int restrictionMask) {
this.restrictionMask = restrictionMask;
}
/**
* Gets a restriction mask that logically multiplies one of the types from <code>RestrictionTypes</code> and
* is responsible for filtering restrictions for the layout output to ContentHandler or DOM
* @return a restriction mask
*/
public int getRestrictionMask () {
return restrictionMask;
}
public boolean addLayoutEventListener(LayoutEventListener l){
return listeners.add(l);
}
public boolean removeLayoutEventListener(LayoutEventListener l){
return listeners.remove(l);
}
/**
* Returns an id of the root folder.
*
* @return a <code>String</code> value
*/
public String getRootFolderId() {
return layout.getRootId();
}
/**
* Returns a subscription id given a functional name.
* @param fname the functional name to lookup.
* @return a <code>String</code> subscription id.
*/
public String getSubscribeId (String fname) throws PortalException {
return layout.getNodeId(fname);
}
}
|
package org.springframework.roo.classpath.javaparser;
import japa.parser.ParseException;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.body.BodyDeclaration;
import japa.parser.ast.body.EnumConstantDeclaration;
import japa.parser.ast.body.TypeDeclaration;
import japa.parser.ast.expr.AnnotationExpr;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.roo.classpath.PhysicalTypeMetadataProvider;
import org.springframework.roo.classpath.details.FieldMetadata;
import org.springframework.roo.classpath.details.MemberFindingUtils;
import org.springframework.roo.classpath.details.MethodMetadata;
import org.springframework.roo.classpath.details.MutableClassOrInterfaceTypeDetails;
import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadata;
import org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder;
import org.springframework.roo.classpath.javaparser.details.JavaParserAnnotationMetadata;
import org.springframework.roo.classpath.javaparser.details.JavaParserFieldMetadata;
import org.springframework.roo.classpath.javaparser.details.JavaParserMethodMetadata;
import org.springframework.roo.metadata.MetadataService;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.process.manager.FileManager;
import org.springframework.roo.process.manager.MutableFile;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.FileCopyUtils;
/**
* Java Parser implementation of {@link MutableClassOrInterfaceTypeDetails}.
*
* <p>
* This class is immutable once constructed.
*
* @author Ben Alex
* @author James Tyrrell
* @since 1.0
*/
public class JavaParserMutableClassOrInterfaceTypeDetails extends JavaParserClassOrInterfaceTypeDetails implements MutableClassOrInterfaceTypeDetails {
private FileManager fileManager;
private String fileIdentifier;
public JavaParserMutableClassOrInterfaceTypeDetails(CompilationUnit compilationUnit, TypeDeclaration typeDeclaration, String declaredByMetadataId, JavaType typeName, MetadataService metadataService, PhysicalTypeMetadataProvider physicalTypeMetadataProvider, FileManager fileManager, String fileIdentifier) throws ParseException, CloneNotSupportedException, IOException {
super(compilationUnit, typeDeclaration, declaredByMetadataId, typeName, metadataService, physicalTypeMetadataProvider);
Assert.notNull(fileManager, "File manager required");
Assert.hasText(fileIdentifier, "File identifier required");
this.fileManager = fileManager;
this.fileIdentifier = fileIdentifier;
}
public void addTypeAnnotation(AnnotationMetadata annotation) {
doAddTypeAnnotation(annotation);
flush();
}
private void doAddTypeAnnotation(AnnotationMetadata annotation) {
List<AnnotationExpr> annotations = clazz == null ? enumClazz.getAnnotations() : clazz.getAnnotations();
if (annotations == null) {
annotations = new ArrayList<AnnotationExpr>();
if (clazz == null) {
enumClazz.setAnnotations(annotations);
} else {
clazz.setAnnotations(annotations);
}
}
JavaParserAnnotationMetadata.addAnnotationToList(this, annotations, annotation);
}
public boolean updateTypeAnnotation(AnnotationMetadata annotation, Set<JavaSymbolName> attributesToDeleteIfPresent) {
boolean writeChangesToDisk = false;
// We are going to build a replacement AnnotationMetadata.
// This variable tracks the new attribute values the replacement will hold.
Map<JavaSymbolName, AnnotationAttributeValue<?>> replacementAttributeValues = new LinkedHashMap<JavaSymbolName, AnnotationAttributeValue<?>>();
AnnotationMetadata existing = MemberFindingUtils.getTypeAnnotation(this, annotation.getAnnotationType());
if (existing == null) {
// Not already present, so just go and add it
for (JavaSymbolName incomingAttributeName : annotation.getAttributeNames()) {
// Do not copy incoming attributes which exist in the attributesToDeleteIfPresent Set
if (attributesToDeleteIfPresent == null || !attributesToDeleteIfPresent.contains(incomingAttributeName)) {
AnnotationAttributeValue<?> incomingValue = annotation.getAttribute(incomingAttributeName);
replacementAttributeValues.put(incomingAttributeName, incomingValue);
}
}
AnnotationMetadataBuilder replacement = new AnnotationMetadataBuilder(annotation.getAnnotationType(), new ArrayList<AnnotationAttributeValue<?>>(replacementAttributeValues.values()));
addTypeAnnotation(replacement.build());
return true;
}
// Copy the existing attributes into the new attributes
for (JavaSymbolName existingAttributeName : existing.getAttributeNames()) {
if (attributesToDeleteIfPresent != null && attributesToDeleteIfPresent.contains(existingAttributeName)) {
writeChangesToDisk = true;
} else {
AnnotationAttributeValue<?> existingValue = existing.getAttribute(existingAttributeName);
replacementAttributeValues.put(existingAttributeName, existingValue);
}
}
// Now we ensure every incoming attribute replaces the existing
for (JavaSymbolName incomingAttributeName : annotation.getAttributeNames()) {
AnnotationAttributeValue<?> incomingValue = annotation.getAttribute(incomingAttributeName);
// Add this attribute to the end of the list if the attribute is not already present
if (replacementAttributeValues.keySet().contains(incomingAttributeName)) {
// There was already an attribute. Need to determine if this new attribute value is materially different
AnnotationAttributeValue<?> existingValue = replacementAttributeValues.get(incomingAttributeName);
Assert.notNull(existingValue, "Existing value should have been provided by earlier loop");
if (!existingValue.equals(incomingValue)) {
replacementAttributeValues.put(incomingAttributeName, incomingValue);
writeChangesToDisk = true;
}
} else if (attributesToDeleteIfPresent != null && !attributesToDeleteIfPresent.contains(incomingAttributeName)) {
// This is a new attribute that does not already exist, so add it to the end of the replacement attributes
replacementAttributeValues.put(incomingAttributeName, incomingValue);
writeChangesToDisk = true;
}
}
// Were there any material changes?
if (!writeChangesToDisk) {
return false;
}
// Make a new AnnotationMetadata representing the replacement
AnnotationMetadataBuilder replacement = new AnnotationMetadataBuilder(annotation.getAnnotationType(), new ArrayList<AnnotationAttributeValue<?>>(replacementAttributeValues.values()));
doRemoveTypeAnnotation(replacement.getAnnotationType());
doAddTypeAnnotation(replacement.build());
flush();
return true;
}
public void removeTypeAnnotation(JavaType annotationType) {
doRemoveTypeAnnotation(annotationType);
flush();
}
private void doRemoveTypeAnnotation(JavaType annotationType) {
List<AnnotationExpr> annotations = clazz.getAnnotations();
if (annotations == null) {
annotations = new ArrayList<AnnotationExpr>();
clazz.setAnnotations(annotations);
}
JavaParserAnnotationMetadata.removeAnnotationFromList(this, annotations, annotationType);
}
public void addField(FieldMetadata fieldMetadata) {
List<BodyDeclaration> members = clazz == null ? enumClazz.getMembers() : clazz.getMembers();
if (members == null) {
members = new ArrayList<BodyDeclaration>();
if (clazz == null) {
enumClazz.setMembers(members);
} else {
clazz.setMembers(members);
}
}
JavaParserFieldMetadata.addField(this, members, fieldMetadata);
flush();
}
public void addEnumConstant(JavaSymbolName name) {
Assert.notNull(name, "Name required");
Assert.isTrue(this.enumClazz != null, "Enum constants can only be added to an enum class");
List<EnumConstantDeclaration> constants = this.enumClazz.getEntries();
if (constants == null) {
constants = new ArrayList<EnumConstantDeclaration>();
this.enumClazz.setEntries(constants);
}
addEnumConstant(this, constants, name);
flush();
}
public void removeField(JavaSymbolName fieldName) {
List<BodyDeclaration> members = clazz == null ? enumClazz.getMembers() : clazz.getMembers();
if (members == null) {
members = new ArrayList<BodyDeclaration>();
if (clazz == null) {
enumClazz.setMembers(members);
} else {
clazz.setMembers(members);
}
}
JavaParserFieldMetadata.removeField(this, members, fieldName);
flush();
}
public void addMethod(MethodMetadata methodMetadata) {
List<BodyDeclaration> members = clazz == null ? enumClazz.getMembers() : clazz.getMembers();
if (members == null) {
members = new ArrayList<BodyDeclaration>();
if (clazz == null) {
enumClazz.setMembers(members);
} else {
clazz.setMembers(members);
}
}
JavaParserMethodMetadata.addMethod(this, members, methodMetadata, typeParameterNames);
flush();
}
private void flush() {
Reader compilationUnitInputStream = new StringReader(compilationUnit.toString());
MutableFile mutableFile = fileManager.updateFile(fileIdentifier);
try {
FileCopyUtils.copy(compilationUnitInputStream, new OutputStreamWriter(mutableFile.getOutputStream()));
} catch (IOException ioe) {
throw new IllegalStateException("Could not update '" + fileIdentifier + "'", ioe);
}
}
}
|
package com.intellij.ide;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Conditions;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.copy.CopyHandler;
import com.intellij.refactoring.move.MoveCallback;
import com.intellij.refactoring.move.MoveHandler;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.JBIterable;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.util.List;
public class CopyPasteDelegator implements CopyPasteSupport {
private static final ExtensionPointName<PasteProvider> EP_NAME = ExtensionPointName.create("com.intellij.filePasteProvider");
public static final Key<Boolean> SHOW_CHOOSER_KEY = Key.create("show.dirs.chooser");
private final Project myProject;
private final JComponent myKeyReceiver;
private final MyEditable myEditable;
public CopyPasteDelegator(@NotNull Project project, @NotNull JComponent keyReceiver) {
myProject = project;
myKeyReceiver = keyReceiver;
myEditable = new MyEditable();
}
/** @deprecated no replacement needed,
* {@code LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext)} is used instead. */
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
protected PsiElement @NotNull [] getSelectedElements() {
return PsiElement.EMPTY_ARRAY;
}
protected PsiElement @NotNull [] getSelectedElements(@NotNull DataContext dataContext) {
return ObjectUtils.notNull(LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext), getSelectedElements());
}
private static PsiElement @NotNull [] validate(PsiElement @Nullable [] selectedElements) {
if (selectedElements == null) return PsiElement.EMPTY_ARRAY;
for (PsiElement element : selectedElements) {
if (element == null || !element.isValid()) {
return PsiElement.EMPTY_ARRAY;
}
}
return selectedElements;
}
private void updateView() {
myKeyReceiver.repaint();
}
@Override
public CopyProvider getCopyProvider() {
return myEditable;
}
@Override
public CutProvider getCutProvider() {
return myEditable;
}
@Override
public PasteProvider getPasteProvider() {
return myEditable;
}
class MyEditable implements CutProvider, CopyProvider, PasteProvider {
@Override
public void performCopy(@NotNull DataContext dataContext) {
PsiElement[] elements = validate(getSelectedElements(dataContext));
PsiCopyPasteManager.getInstance().setElements(elements, true);
updateView();
}
@Override
public boolean isCopyEnabled(@NotNull DataContext dataContext) {
PsiElement[] elements = validate(getSelectedElements(dataContext));
return CopyHandler.canCopy(elements) ||
JBIterable.of(elements).filter(Conditions.instanceOf(PsiNamedElement.class)).isNotEmpty();
}
@Override
public boolean isCopyVisible(@NotNull DataContext dataContext) {
return true;
}
@Override
public void performCut(@NotNull DataContext dataContext) {
PsiElement[] elements = validate(getSelectedElements(dataContext));
if (MoveHandler.adjustForMove(myProject, elements, null) == null) {
return;
}
// 'elements' passed instead of result of 'adjustForMove' because otherwise ProjectView would
// not recognize adjusted elements when graying them
PsiCopyPasteManager.getInstance().setElements(elements, false);
updateView();
}
@Override
public boolean isCutEnabled(@NotNull DataContext dataContext) {
final PsiElement[] elements = validate(getSelectedElements(dataContext));
return elements.length != 0 && MoveHandler.canMove(elements, null);
}
@Override
public boolean isCutVisible(@NotNull DataContext dataContext) {
return true;
}
@Override
public void performPaste(@NotNull DataContext dataContext) {
if (!performDefaultPaste(dataContext)) {
for(PasteProvider provider: EP_NAME.getExtensionList()) {
if (provider.isPasteEnabled(dataContext)) {
provider.performPaste(dataContext);
break;
}
}
}
}
boolean performDefaultPaste(@NotNull DataContext dataContext) {
final boolean[] isCopied = new boolean[1];
final PsiElement[] elements = PsiCopyPasteManager.getInstance().getElements(isCopied);
if (elements == null) return false;
return DumbService.getInstance(myProject).computeWithAlternativeResolveEnabled(() -> {
try {
final Module module = LangDataKeys.MODULE.getData(dataContext);
PsiElement target = getPasteTarget(dataContext, module);
if (isCopied[0]) {
pasteAfterCopy(elements, module, target, true);
}
else if (MoveHandler.canMove(elements, target)) {
pasteAfterCut(dataContext, elements, target);
}
else {
return false;
}
}
finally {
updateView();
}
return true;
});
}
private PsiElement getPasteTarget(@NotNull DataContext dataContext, @Nullable Module module) {
PsiElement target = LangDataKeys.PASTE_TARGET_PSI_ELEMENT.getData(dataContext);
if (module != null && target instanceof PsiDirectoryContainer) {
final PsiDirectory[] directories = ((PsiDirectoryContainer)target).getDirectories(GlobalSearchScope.moduleScope(module));
if (directories.length == 1) {
return directories[0];
}
}
return target;
}
@Nullable
private PsiDirectory getTargetDirectory(@Nullable Module module, @Nullable PsiElement target) {
PsiDirectory targetDirectory = target instanceof PsiDirectory ? (PsiDirectory)target : null;
if (targetDirectory == null && target instanceof PsiDirectoryContainer) {
final PsiDirectory[] directories = module == null ? ((PsiDirectoryContainer)target).getDirectories()
: ((PsiDirectoryContainer)target).getDirectories(GlobalSearchScope.moduleScope(module));
if (directories.length > 0) {
targetDirectory = directories[0];
targetDirectory.putCopyableUserData(SHOW_CHOOSER_KEY, directories.length > 1);
}
}
if (targetDirectory == null && target != null) {
final PsiFile containingFile = target.getContainingFile();
if (containingFile != null) {
targetDirectory = containingFile.getContainingDirectory();
}
}
return targetDirectory;
}
private void pasteAfterCopy(PsiElement[] elements, Module module, PsiElement target, boolean tryFromFiles) {
PsiDirectory targetDirectory = elements.length == 1 && elements[0] == target ? null : getTargetDirectory(module, target);
try {
if (CopyHandler.canCopy(elements)) {
CopyHandler.doCopy(elements, targetDirectory);
}
else if (tryFromFiles) {
List<File> files = PsiCopyPasteManager.asFileList(elements);
if (files != null) {
PsiManager manager = elements[0].getManager();
PsiFileSystemItem[] items = files.stream()
.map(file -> LocalFileSystem.getInstance().findFileByIoFile(file))
.map(file -> {
if (file != null) {
return file.isDirectory() ? manager.findDirectory(file)
: manager.findFile(file);
}
return null;
})
.filter(file -> file != null)
.toArray(PsiFileSystemItem[]::new);
pasteAfterCopy(items, module, target, false);
}
}
}
finally {
if (targetDirectory != null) {
targetDirectory.putCopyableUserData(SHOW_CHOOSER_KEY, null);
}
}
}
private void pasteAfterCut(DataContext dataContext, PsiElement[] elements, PsiElement target) {
MoveHandler.doMove(myProject, elements, target, dataContext, new MoveCallback() {
@Override
public void refactoringCompleted() {
PsiCopyPasteManager.getInstance().clear();
}
});
}
@Override
public boolean isPastePossible(@NotNull DataContext dataContext) {
return true;
}
@Override
public boolean isPasteEnabled(@NotNull DataContext dataContext){
if (isDefaultPasteEnabled(dataContext)) {
return true;
}
for(PasteProvider provider: EP_NAME.getExtensionList()) {
if (provider.isPasteEnabled(dataContext)) {
return true;
}
}
return false;
}
private boolean isDefaultPasteEnabled(final DataContext dataContext) {
Project project = CommonDataKeys.PROJECT.getData(dataContext);
if (project == null) {
return false;
}
if (DumbService.isDumb(project)) return false;
Object target = LangDataKeys.PASTE_TARGET_PSI_ELEMENT.getData(dataContext);
if (target == null) {
return false;
}
PsiElement[] elements = PsiCopyPasteManager.getInstance().getElements(new boolean[]{false});
if (elements == null) {
return false;
}
// disable cross-project paste
for (PsiElement element : elements) {
PsiManager manager = element.getManager();
if (manager == null || manager.getProject() != project) {
return false;
}
}
return true;
}
}
}
|
//$HeadURL: svn+ssh://mschneider@svn.wald.intevation.org/deegree/deegree3/trunk/deegree-core/deegree-core-metadata/src/main/java/org/deegree/metadata/iso/persistence/TransactionHelper.java $
package org.deegree.metadata.iso.persistence;
import static org.deegree.commons.utils.JDBCUtils.close;
import static org.slf4j.LoggerFactory.getLogger;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLStreamException;
import org.deegree.commons.jdbc.ConnectionManager.Type;
import org.deegree.commons.jdbc.InsertRow;
import org.deegree.commons.jdbc.TableName;
import org.deegree.commons.jdbc.TransactionRow;
import org.deegree.commons.jdbc.UpdateRow;
import org.deegree.commons.utils.JDBCUtils;
import org.deegree.cs.CRSUtils;
import org.deegree.geometry.Envelope;
import org.deegree.geometry.Geometries;
import org.deegree.geometry.Geometry;
import org.deegree.geometry.GeometryFactory;
import org.deegree.geometry.utils.GeometryParticleConverter;
import org.deegree.metadata.i18n.Messages;
import org.deegree.metadata.iso.ISORecord;
import org.deegree.metadata.iso.parsing.QueryableProperties;
import org.deegree.metadata.iso.persistence.queryable.Queryable;
import org.deegree.metadata.iso.types.BoundingBox;
import org.deegree.metadata.iso.types.CRS;
import org.deegree.metadata.iso.types.Constraint;
import org.deegree.metadata.iso.types.Format;
import org.deegree.metadata.iso.types.Keyword;
import org.deegree.metadata.iso.types.OperatesOnData;
import org.deegree.metadata.persistence.iso19115.jaxb.ISOMetadataStoreConfig.AnyText;
import org.deegree.protocol.csw.MetadataStoreException;
import org.deegree.sqldialect.SQLDialect;
import org.deegree.sqldialect.filter.AbstractWhereBuilder;
import org.deegree.sqldialect.filter.expression.SQLArgument;
import org.slf4j.Logger;
class TransactionHelper extends SqlHelper {
private static final Logger LOG = getLogger( TransactionHelper.class );
private AnyText anyTextConfig;
TransactionHelper( SQLDialect dialect, List<Queryable> queryables, AnyText anyTextConfig ) {
super( dialect, queryables );
this.anyTextConfig = anyTextConfig;
}
/**
* Generates and inserts the maindatabasetable that is needed for the queryable properties databasetables to derive
* from.
* <p>
* BE AWARE: the "modified" attribute is get from the first position in the list. The backend has the possibility to
* add one such attribute. In the xsd-file there are more possible...
*
* @param conn
* the SQL connection
* @return the primarykey of the inserted dataset which is the foreignkey for the queryable properties
* databasetables
* @throws MetadataStoreException
* @throws XMLStreamException
*/
int executeInsert( Connection conn, ISORecord rec )
throws MetadataStoreException, XMLStreamException {
int internalId = 0;
InsertRow ir = new InsertRow( new TableName( mainTable ), null );
try {
internalId = getLastDatasetId( conn, mainTable );
internalId++;
ir.addPreparedArgument( idColumn, internalId );
ir.addPreparedArgument( recordColumn, rec.getAsByteArray() );
ir.addPreparedArgument( "fileidentifier", rec.getIdentifier() );
ir.addPreparedArgument( "version", null );
ir.addPreparedArgument( "status", null );
appendValues( rec, ir );
LOG.debug( ir.getSql() );
ir.performInsert( conn );
QueryableProperties qp = rec.getParsedElement().getQueryableProperties();
insertNewValues( conn, internalId, qp );
} catch ( SQLException e ) {
String msg = Messages.getMessage( "ERROR_SQL", ir.getSql(), e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
}
return internalId;
}
public int executeDelete( Connection connection, AbstractWhereBuilder builder )
throws MetadataStoreException {
LOG.debug( Messages.getMessage( "INFO_EXEC", "delete-statement" ) );
PreparedStatement stmt = null;
ResultSet rs = null;
List<Integer> deletableDatasets;
int deleted = 0;
try {
StringBuilder header = getPreparedStatementDatasetIDs( builder );
getPSBody( builder, header );
stmt = connection.prepareStatement( header.toString() );
int i = 1;
if ( builder.getWhere() != null ) {
for ( SQLArgument o : builder.getWhere().getArguments() ) {
o.setArgument( stmt, i++ );
}
}
if ( builder.getOrderBy() != null ) {
for ( SQLArgument o : builder.getOrderBy().getArguments() ) {
o.setArgument( stmt, i++ );
}
}
LOG.debug( Messages.getMessage( "INFO_TA_DELETE_FIND", stmt.toString() ) );
rs = stmt.executeQuery();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append( "DELETE FROM " );
stringBuilder.append( mainTable );
stringBuilder.append( " WHERE " ).append( idColumn );
stringBuilder.append( " = ?" );
deletableDatasets = new ArrayList<Integer>();
if ( rs != null ) {
while ( rs.next() ) {
deletableDatasets.add( rs.getInt( 1 ) );
}
rs.close();
close( stmt );
stmt = connection.prepareStatement( stringBuilder.toString() );
for ( int d : deletableDatasets ) {
stmt.setInt( 1, d );
LOG.debug( Messages.getMessage( "INFO_TA_DELETE_DEL", stmt.toString() ) );
deleted = deleted + stmt.executeUpdate();
}
}
} catch ( SQLException e ) {
String msg = Messages.getMessage( "ERROR_SQL", stmt.toString(), e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} finally {
close( rs, stmt, null, LOG );
}
return deleted;
}
/**
*
* @param conn
* the database connection
* @param rec
* the record to update
* @param fileIdentifier
* the fileIdentifer of the record to update, can be <code>null</code> when the identifer of the record
* is the one to use for updating
* @return the database id of the updated record
* @throws MetadataStoreException
* if updating fails
*/
int executeUpdate( Connection conn, ISORecord rec, String fileIdentifier )
throws MetadataStoreException {
PreparedStatement stmt = null;
ResultSet rs = null;
StringWriter s = new StringWriter( 150 );
int requestedId = -1;
String idToUpdate = ( fileIdentifier == null ? rec.getIdentifier() : fileIdentifier );
try {
s.append( "SELECT " ).append( idColumn );
s.append( " FROM " ).append( mainTable );
s.append( " WHERE " ).append( fileIdColumn ).append( " = ?" );
LOG.debug( s.toString() );
stmt = conn.prepareStatement( s.toString() );
stmt.setObject( 1, idToUpdate );
rs = stmt.executeQuery();
while ( rs.next() ) {
requestedId = rs.getInt( 1 );
LOG.debug( "resultSet: " + rs.getInt( 1 ) );
}
if ( requestedId > -1 ) {
UpdateRow ur = new UpdateRow( new TableName( mainTable ) );
ur.addPreparedArgument( "version", null );
ur.addPreparedArgument( "status", null );
ur.addPreparedArgument( recordColumn, rec.getAsByteArray() );
appendValues( rec, ur );
ur.setWhereClause( idColumn + " = " + Integer.toString( requestedId ) );
LOG.debug( stmt.toString() );
ur.performUpdate( conn );
QueryableProperties qp = rec.getParsedElement().getQueryableProperties();
deleteOldValues( conn, requestedId );
insertNewValues( conn, requestedId, qp );
}
} catch ( SQLException e ) {
String msg = Messages.getMessage( "ERROR_SQL", s.toString(), e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} catch ( FactoryConfigurationError e ) {
LOG.debug( "error: " + e.getMessage(), e );
throw new MetadataStoreException( e.getMessage() );
} finally {
JDBCUtils.close( rs, stmt, null, LOG );
}
return requestedId;
}
private void insertNewValues( Connection conn, int requestedId, QueryableProperties qp )
throws MetadataStoreException {
LOG.debug( "Insert values in referenced tables for dataset with id {}", requestedId );
insertInCRSTable( conn, requestedId, qp );
insertInKeywordTable( conn, requestedId, qp );
insertInOperatesOnTable( conn, requestedId, qp );
insertInConstraintTable( conn, requestedId, qp );
}
private void deleteOldValues( Connection conn, int requestedId )
throws MetadataStoreException {
LOG.debug( "Delete existing values in referenced tables for dataset with id {}", requestedId );
deleteExistingRows( conn, requestedId, crsTable );
deleteExistingRows( conn, requestedId, keywordTable );
deleteExistingRows( conn, requestedId, opOnTable );
deleteExistingRows( conn, requestedId, constraintTable );
}
private void appendValues( ISORecord rec, TransactionRow tr )
throws SQLException {
tr.addPreparedArgument( "abstract", concatenate( Arrays.asList( rec.getAbstract() ) ) );
tr.addPreparedArgument( "anytext", AnyTextHelper.getAnyText( rec, anyTextConfig ) );
tr.addPreparedArgument( "language", rec.getLanguage() );
Timestamp modified = null;
if ( rec.getModified() != null ) {
modified = new Timestamp( rec.getModified().getTimeInMilliseconds() );
}
tr.addPreparedArgument( "modified", modified );
tr.addPreparedArgument( "parentid", rec.getParentIdentifier() );
tr.addPreparedArgument( "type", rec.getType() );
tr.addPreparedArgument( "title", concatenate( Arrays.asList( rec.getTitle() ) ) );
tr.addPreparedArgument( "hassecurityconstraints", rec.isHasSecurityConstraints() );
QueryableProperties qp = rec.getParsedElement().getQueryableProperties();
tr.addPreparedArgument( "topiccategories", concatenate( qp.getTopicCategory() ) );
tr.addPreparedArgument( "alternateTitles", concatenate( qp.getAlternateTitle() ) );
Timestamp revDate = null;
if ( qp.getRevisionDate() != null ) {
revDate = new Timestamp( qp.getRevisionDate().getTimeInMilliseconds() );
}
tr.addPreparedArgument( "revisiondate", revDate );
Timestamp createDate = null;
if ( qp.getCreationDate() != null ) {
createDate = new Timestamp( qp.getCreationDate().getTimeInMilliseconds() );
}
tr.addPreparedArgument( "creationdate", createDate );
Timestamp pubDate = null;
if ( qp.getPublicationDate() != null ) {
pubDate = new Timestamp( qp.getPublicationDate().getTimeInMilliseconds() );
}
tr.addPreparedArgument( "publicationdate", pubDate );
tr.addPreparedArgument( "organisationname", qp.getOrganisationName() );
tr.addPreparedArgument( "resourceid", qp.getResourceIdentifier() );
tr.addPreparedArgument( "resourcelanguage", qp.getResourceLanguage() );
tr.addPreparedArgument( "geographicdescriptioncode", concatenate( qp.getGeographicDescriptionCode_service() ) );
tr.addPreparedArgument( "denominator", qp.getDenominator() );
tr.addPreparedArgument( "distancevalue", qp.getDistanceValue() );
tr.addPreparedArgument( "distanceuom", qp.getDistanceUOM() );
Timestamp begTmpExten = null;
if ( qp.getTemporalExtentBegin() != null ) {
begTmpExten = new Timestamp( qp.getTemporalExtentBegin().getTimeInMilliseconds() );
}
tr.addPreparedArgument( "tempextent_begin", begTmpExten );
Timestamp endTmpExten = null;
if ( qp.getTemporalExtentEnd() != null ) {
endTmpExten = new Timestamp( qp.getTemporalExtentEnd().getTimeInMilliseconds() );
}
tr.addPreparedArgument( "tempextent_end", endTmpExten );
tr.addPreparedArgument( "servicetype", qp.getServiceType() );
tr.addPreparedArgument( "servicetypeversion", concatenate( qp.getServiceTypeVersion() ) );
tr.addPreparedArgument( "couplingtype", qp.getCouplingType() );
tr.addPreparedArgument( "formats", getFormats( qp.getFormat() ) );
tr.addPreparedArgument( "operations", concatenate( qp.getOperation() ) );
tr.addPreparedArgument( "degree", qp.isDegree() );
tr.addPreparedArgument( "lineage", concatenate( qp.getLineages() ) );
tr.addPreparedArgument( "resppartyrole", qp.getRespPartyRole() );
tr.addPreparedArgument( "spectitle", concatenate( qp.getSpecificationTitle() ) );
Timestamp specDate = null;
if ( qp.getSpecificationDate() != null ) {
specDate = new Timestamp( qp.getSpecificationDate().getTimeInMilliseconds() );
}
tr.addPreparedArgument( "specdate", specDate );
tr.addPreparedArgument( "specdatetype", qp.getSpecificationDateType() );
Envelope env = calculateMainBBox( qp.getBoundingBox() );
Geometry geom = null;
if ( env != null ) {
geom = Geometries.getAsGeometry( env );
}
String bboxColumn = "bbox";
String srid = null;
// TODO: srid
if ( dialect.getDBType() == Type.Oracle ) {
srid = "4326";
}
GeometryParticleConverter converter = dialect.getGeometryConverter( bboxColumn, null, srid, true );
tr.addPreparedArgument( bboxColumn, geom, converter );
for ( Queryable queryable : queryables ) {
String value;
if ( queryable.isMultiple() ) {
value = concatenate( queryable.getConvertedValues( rec ) );
} else {
value = queryable.getConvertedValue( rec );
}
tr.addPreparedArgument( queryable.getColumn(), value );
}
}
private String getFormats( List<Format> list ) {
StringBuffer sb = new StringBuffer();
if ( list != null && list.size() > 0 ) {
sb.append( '\'' );
for ( Format f : list ) {
sb.append( '|' ).append( f.getName() );
}
if ( !list.isEmpty() ) {
sb.append( "|" );
}
sb.append( "'," );
}
return ( sb.toString() != null && sb.length() > 0 ) ? sb.toString() : null;
}
private Envelope calculateMainBBox( List<BoundingBox> bbox ) {
if ( bbox == null || bbox.isEmpty() )
return null;
double west = bbox.get( 0 ).getWestBoundLongitude();
double east = bbox.get( 0 ).getEastBoundLongitude();
double south = bbox.get( 0 ).getSouthBoundLatitude();
double north = bbox.get( 0 ).getNorthBoundLatitude();
for ( BoundingBox b : bbox ) {
west = Math.min( west, b.getWestBoundLongitude() );
east = Math.max( east, b.getEastBoundLongitude() );
south = Math.min( south, b.getSouthBoundLatitude() );
north = Math.max( north, b.getNorthBoundLatitude() );
}
GeometryFactory gf = new GeometryFactory();
return gf.createEnvelope( west, south, east, north, CRSUtils.EPSG_4326 );
}
private void insertInConstraintTable( Connection conn, int operatesOnId, QueryableProperties qp )
throws MetadataStoreException {
List<Constraint> constraintss = qp.getConstraints();
if ( constraintss != null && constraintss.size() > 0 ) {
final StringWriter sw = new StringWriter( 300 );
sw.append( "INSERT INTO " ).append( constraintTable );
sw.append( '(' ).append( idColumn ).append( ',' ).append( fk_main ).append( ",conditionapptoacc,accessconstraints,otherconstraints,classification)" );
sw.append( "VALUES( ?,?,?,?,?,? )" );
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement( sw.toString() );
stmt.setInt( 2, operatesOnId );
for ( Constraint constraint : constraintss ) {
int localId = getNewIdentifier( conn, constraintTable );
stmt.setInt( 1, localId );
stmt.setString( 3, concatenate( constraint.getLimitations() ) );
stmt.setString( 4, concatenate( constraint.getAccessConstraints() ) );
stmt.setString( 5, concatenate( constraint.getOtherConstraints() ) );
stmt.setString( 6, constraint.getClassification() );
stmt.executeUpdate();
}
} catch ( SQLException e ) {
String msg = Messages.getMessage( "ERROR_SQL", sw, e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} finally {
close( null, stmt, null, LOG );
}
}
}
private void insertInCRSTable( Connection conn, int operatesOnId, QueryableProperties qp )
throws MetadataStoreException {
List<CRS> crss = qp.getCrs();
if ( crss != null && crss.size() > 0 ) {
for ( CRS crs : crss ) {
InsertRow ir = new InsertRow( new TableName( crsTable ), null );
try {
int localId = getNewIdentifier( conn, crsTable );
ir.addPreparedArgument( idColumn, localId );
ir.addPreparedArgument( fk_main, operatesOnId );
ir.addPreparedArgument( "authority",
( crs.getAuthority() != null && crs.getAuthority().length() > 0 ) ? crs.getAuthority()
: null );
ir.addPreparedArgument( "crsid",
( crs.getCrsId() != null && crs.getCrsId().length() > 0 ) ? crs.getCrsId()
: null );
ir.addPreparedArgument( "version",
( crs.getVersion() != null && crs.getVersion().length() > 0 ) ? crs.getVersion()
: null );
LOG.debug( ir.getSql() );
ir.performInsert( conn );
} catch ( SQLException e ) {
String msg = Messages.getMessage( "ERROR_SQL", ir.getSql(), e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
}
}
}
}
private void insertInKeywordTable( Connection conn, int operatesOnId, QueryableProperties qp )
throws MetadataStoreException {
List<Keyword> keywords = qp.getKeywords();
if ( keywords != null && keywords.size() > 0 ) {
for ( Keyword keyword : keywords ) {
InsertRow ir = new InsertRow( new TableName( keywordTable ), null );
try {
int localId = getNewIdentifier( conn, keywordTable );
ir.addPreparedArgument( idColumn, localId );
ir.addPreparedArgument( fk_main, operatesOnId );
ir.addPreparedArgument( "keywordtype", keyword.getKeywordType() );
ir.addPreparedArgument( "keywords", concatenate( keyword.getKeywords() ) );
LOG.debug( ir.getSql() );
ir.performInsert( conn );
} catch ( SQLException e ) {
String msg = Messages.getMessage( "ERROR_SQL", ir.getSql(), e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
}
}
}
}
private void insertInOperatesOnTable( Connection conn, int operatesOnId, QueryableProperties qp )
throws MetadataStoreException {
List<OperatesOnData> opOns = qp.getOperatesOnData();
if ( opOns != null && opOns.size() > 0 ) {
for ( OperatesOnData opOn : opOns ) {
InsertRow ir = new InsertRow( new TableName( opOnTable ), null );
try {
int localId = getNewIdentifier( conn, opOnTable );
ir.addPreparedArgument( idColumn, localId );
ir.addPreparedArgument( fk_main, operatesOnId );
ir.addPreparedArgument( "operateson", opOn.getOperatesOnId() );
ir.addPreparedArgument( "operatesonid", opOn.getOperatesOnIdentifier() );
ir.addPreparedArgument( "operatesonname", opOn.getOperatesOnName() );
LOG.debug( ir.getSql() );
ir.performInsert( conn );
} catch ( SQLException e ) {
String msg = Messages.getMessage( "ERROR_SQL", ir.getSql(), e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
}
}
}
}
private int getNewIdentifier( Connection connection, String databaseTable )
throws MetadataStoreException {
int localId = getLastDatasetId( connection, databaseTable );
return ++localId;
}
private void deleteExistingRows( Connection connection, int operatesOnId, String databaseTable )
throws MetadataStoreException {
PreparedStatement stmt = null;
StringWriter sqlStatement = new StringWriter();
try {
sqlStatement.append( "DELETE FROM " + databaseTable + " WHERE " + fk_main + " = ?" );
stmt = connection.prepareStatement( sqlStatement.toString() );
stmt.setInt( 1, operatesOnId );
LOG.debug( stmt.toString() );
stmt.executeUpdate();
} catch ( SQLException e ) {
String msg = Messages.getMessage( "ERROR_SQL", sqlStatement.toString(), e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} finally {
close( null, stmt, null, LOG );
}
}
/**
* Provides the last known id in the databaseTable. So it is possible to insert new datasets into this table come
* from this id.
*
* @param conn
* @param databaseTable
* the databaseTable that is requested.
* @return the last Primary Key ID of the databaseTable.
* @throws MetadataStoreException
*/
private int getLastDatasetId( Connection conn, String databaseTable )
throws MetadataStoreException {
int result = 0;
String selectIDRows = null;
// TODO: use SQLDialect
if ( dialect.getDBType() == Type.PostgreSQL ) {
selectIDRows = "SELECT " + idColumn + " from " + databaseTable + " ORDER BY " + idColumn + " DESC LIMIT 1";
}
if ( dialect.getDBType() == Type.MSSQL ) {
selectIDRows = "SELECT TOP 1 " + idColumn + " from " + databaseTable + " ORDER BY " + idColumn + " DESC";
}
if ( dialect.getDBType() == Type.Oracle ) {
String inner = "SELECT " + idColumn + " from " + databaseTable + " ORDER BY " + idColumn + " DESC";
selectIDRows = "SELECT * FROM (" + inner + ") WHERE rownum = 1";
}
Statement stmt = null;
ResultSet rsBrief = null;
try {
stmt = conn.createStatement();
rsBrief = stmt.executeQuery( selectIDRows );
while ( rsBrief.next() ) {
result = rsBrief.getInt( 1 );
}
} catch ( SQLException e ) {
String msg = Messages.getMessage( "ERROR_SQL", selectIDRows, e.getMessage() );
LOG.debug( msg );
throw new MetadataStoreException( msg );
} finally {
close( rsBrief, stmt, null, LOG );
}
return result;
}
private String concatenate( List<String> values ) {
if ( values == null || values.isEmpty() )
return null;
String s = "";
for ( String value : values ) {
if ( value != null ) {
s = s + '|' + value.replace( "\'", "\'\'" );
}
}
if ( !values.isEmpty() )
s = s + '|';
return s;
}
}
|
package org.opennms.netmgt.provision;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.MissingFormatArgumentException;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import org.opennms.core.utils.LogUtils;
import org.opennms.core.utils.PropertiesUtils;
import org.opennms.core.utils.ThreadCategory;
import org.opennms.netmgt.EventConstants;
import org.opennms.netmgt.config.SnmpAssetAdapterConfig;
import org.opennms.netmgt.config.snmpAsset.adapter.AssetField;
import org.opennms.netmgt.config.snmpAsset.adapter.MibObj;
import org.opennms.netmgt.config.snmpAsset.adapter.MibObjs;
import org.opennms.netmgt.dao.NodeDao;
import org.opennms.netmgt.dao.SnmpAgentConfigFactory;
import org.opennms.netmgt.model.OnmsAssetRecord;
import org.opennms.netmgt.model.OnmsIpInterface;
import org.opennms.netmgt.model.OnmsNode;
import org.opennms.netmgt.model.events.EventBuilder;
import org.opennms.netmgt.model.events.EventForwarder;
import org.opennms.netmgt.model.events.annotations.EventHandler;
import org.opennms.netmgt.model.events.annotations.EventListener;
import org.opennms.netmgt.snmp.SnmpAgentConfig;
import org.opennms.netmgt.snmp.SnmpObjId;
import org.opennms.netmgt.snmp.SnmpUtils;
import org.opennms.netmgt.snmp.SnmpValue;
import org.opennms.netmgt.xml.event.Event;
import org.opennms.netmgt.xml.event.Parm;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.util.Assert;
@EventListener(name="SnmpAssetProvisioningAdapter")
public class SnmpAssetProvisioningAdapter extends SimplerQueuedProvisioningAdapter implements InitializingBean {
private NodeDao m_nodeDao;
// private AssetRecordDao m_assetRecordDao;
private EventForwarder m_eventForwarder;
private SnmpAssetAdapterConfig m_config;
private SnmpAgentConfigFactory m_snmpConfigDao;
private static final String MESSAGE_PREFIX = "SNMP asset provisioning failed: ";
/**
* Constant <code>NAME="SnmpAssetProvisioningAdapter"</code>
*/
public static final String NAME = "SnmpAssetProvisioningAdapter";
private final ConcurrentMap<Integer, InetAddress> m_onmsNodeIpMap = new ConcurrentHashMap<Integer, InetAddress>();
public SnmpAssetProvisioningAdapter() {
super(NAME);
}
@Override
AdapterOperationSchedule createScheduleForNode(final int nodeId, AdapterOperationType adapterOperationType) {
log().debug("Scheduling: " + adapterOperationType + " for nodeid: " + nodeId);
if (adapterOperationType.equals(AdapterOperationType.CONFIG_CHANGE)) {
if (log().isDebugEnabled()) {
InetAddress ipaddress = m_onmsNodeIpMap.get(nodeId);
log().debug("Found suitable IP address: " + ipaddress);
}
return new AdapterOperationSchedule(10, 5, 3, TimeUnit.SECONDS);
} else {
return new AdapterOperationSchedule(0, 5, 3, TimeUnit.SECONDS);
}
}
/**
* <p>afterPropertiesSet</p>
*
* @throws java.lang.Exception if any.
*/
public void afterPropertiesSet() throws Exception {
Assert.notNull(m_config, "SNMP Asset Provisioning Adapter requires config property to be set.");
Assert.notNull(m_nodeDao, "SNMP Asset Provisioning Adapter requires nodeDao property to be set.");
Assert.notNull(m_eventForwarder, "SNMP Asset Provisioning Adapter requires eventForwarder property to be set.");
Assert.notNull(m_template, "SNMP Asset Provisioning Adapter requires template property to be set.");
m_template.execute(new TransactionCallback<Object>() {
public Object doInTransaction(TransactionStatus arg0) {
buildNodeIpMap();
return null;
}
});
}
private void buildNodeIpMap() {
List<OnmsNode> nodes = m_nodeDao.findAllProvisionedNodes();
for (OnmsNode onmsNode : nodes) {
InetAddress ipaddr = getIpForNode(onmsNode);
if (ipaddr != null) {
m_onmsNodeIpMap.putIfAbsent(onmsNode.getId(), ipaddr);
}
}
}
/**
* <p>doAdd</p>
*
* @param nodeId a int.
* @param retry a boolean.
* @throws org.opennms.netmgt.provision.ProvisioningAdapterException if any.
*/
@Override
public void doAddNode(int nodeId) throws ProvisioningAdapterException {
log().debug("doAdd: adding nodeid: " + nodeId);
final OnmsNode node = m_nodeDao.get(nodeId);
Assert.notNull(node, "doAdd: failed to return node for given nodeId:"+nodeId);
InetAddress ipaddress = m_template.execute(new TransactionCallback<InetAddress>() {
public InetAddress doInTransaction(TransactionStatus arg0) {
return getIpForNode(node);
}
});
try {
m_onmsNodeIpMap.putIfAbsent(nodeId, ipaddress);
} catch (ProvisioningAdapterException ae) {
sendAndThrow(nodeId, ae);
} catch (Throwable e) {
sendAndThrow(nodeId, e);
}
SnmpAgentConfig agentConfig = null;
agentConfig = m_snmpConfigDao.getAgentConfig(ipaddress);
OnmsAssetRecord asset = node.getAssetRecord();
AssetField[] fields = m_config.getAssetFieldsForAddress(ipaddress, node.getSysObjectId());
for (AssetField field : fields) {
String value = fetchSnmpAssetString(agentConfig, field.getMibObjs(), field.getFormatString());
if (log().isDebugEnabled()) {
log().debug("doAdd: Setting asset field \"" + field.getName() + "\" to value: " + value);
}
// Use Spring bean-accessor classes to set the field value
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(asset);
try {
wrapper.setPropertyValue(field.getName(), value);
} catch (BeansException e) {
log().warn("doAdd: Could not set property \"" + field.getName() + "\" on asset object: " + e.getMessage(), e);
}
}
node.setAssetRecord(asset);
m_nodeDao.saveOrUpdate(node);
}
private static String fetchSnmpAssetString(SnmpAgentConfig agentConfig, MibObjs mibObjs, String formatString) {
List<String> aliases = new ArrayList<String>();
List<SnmpObjId> objs = new ArrayList<SnmpObjId>();
for (MibObj mibobj : mibObjs.getMibObj()) {
aliases.add(mibobj.getAlias());
objs.add(SnmpObjId.get(mibobj.getOid()));
}
// Fetch the values from the SNMP agent
SnmpValue[] values = SnmpUtils.get(agentConfig, objs.toArray(new SnmpObjId[0]));
if (values.length == aliases.size()) {
Properties substitutions = new Properties();
for (int i = 0; i < values.length; i++) {
substitutions.setProperty(aliases.get(i), values[i].toString());
}
if (objs.size() != substitutions.size()) {
StringBuffer propertyValues = new StringBuffer();
for (Map.Entry<Object, Object> entry : substitutions.entrySet()) {
propertyValues.append(" ");
propertyValues.append(entry.getKey().toString());
propertyValues.append(" => ");
propertyValues.append(entry.getValue().toString());
propertyValues.append("\n");
}
log().warn("fetchSnmpAssetString: Unexpected number of properties returned from SNMP GET: \n" + propertyValues.toString());
}
try {
return PropertiesUtils.substitute(formatString, substitutions);
} catch (MissingFormatArgumentException e) {
log().warn("fetchSnmpAssetString: Insufficient SNMP parameters returned to satisfy format string: " + formatString);
return formatString;
}
} else {
log().warn("fetchSnmpAssetString: Invalid number of SNMP parameters returned: " + values.length + " != " + aliases.size());
return formatString;
}
}
/**
* <p>doUpdate</p>
*
* @param nodeId a int.
* @param retry a boolean.
* @throws org.opennms.netmgt.provision.ProvisioningAdapterException if any.
*/
@Override
public void doUpdateNode(int nodeId) throws ProvisioningAdapterException {
log().debug("doUpdate: updating nodeid: " + nodeId);
final OnmsNode node = m_nodeDao.get(nodeId);
Assert.notNull(node, "doUpdate: failed to return node for given nodeId:"+nodeId);
InetAddress ipaddress = m_template.execute(new TransactionCallback<InetAddress>() {
public InetAddress doInTransaction(TransactionStatus arg0) {
return getIpForNode(node);
}
});
m_onmsNodeIpMap.put(nodeId, ipaddress);
SnmpAgentConfig agentConfig = null;
agentConfig = m_snmpConfigDao.getAgentConfig(ipaddress);
OnmsAssetRecord asset = node.getAssetRecord();
AssetField[] fields = m_config.getAssetFieldsForAddress(ipaddress, node.getSysObjectId());
for (AssetField field : fields) {
String value = fetchSnmpAssetString(agentConfig, field.getMibObjs(), field.getFormatString());
if (log().isDebugEnabled()) {
log().debug("doUpdate: Setting asset field \"" + field.getName() + "\" to value: " + value);
}
// Use Spring bean-accessor classes to set the field value
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(asset);
try {
wrapper.setPropertyValue(field.getName(), value);
} catch (BeansException e) {
log().warn("doUpdate: Could not set property \"" + field.getName() + "\" on asset object: " + e.getMessage(), e);
}
}
node.setAssetRecord(asset);
m_nodeDao.saveOrUpdate(node);
}
/**
* <p>doDelete</p>
*
* @param nodeId a int.
* @param retry a boolean.
* @throws org.opennms.netmgt.provision.ProvisioningAdapterException if any.
*/
@Override
public void doDeleteNode(int nodeId) throws ProvisioningAdapterException {
log().debug("doDelete: deleting nodeid: " + nodeId);
/*
* The work to maintain the hashmap boils down to needing to do deletes, so
* here we go.
*/
try {
m_onmsNodeIpMap.remove(Integer.valueOf(nodeId));
} catch (Throwable e) {
sendAndThrow(nodeId, e);
}
}
/**
* <p>doNodeConfigChanged</p>
*
* @param nodeId a int.
* @param retry a boolean.
* @throws org.opennms.netmgt.provision.ProvisioningAdapterException if any.
*/
@Override
public void doNotifyConfigChange(int nodeId) throws ProvisioningAdapterException {
log().debug("doNodeConfigChanged: nodeid: " + nodeId);
}
private void sendAndThrow(int nodeId, Throwable e) {
log().debug("sendAndThrow: error working on Dao nodeid: " + nodeId);
log().debug("sendAndThrow: Exception: " + e.getMessage());
Event event = buildEvent(EventConstants.PROVISIONING_ADAPTER_FAILED, nodeId).addParam("reason", MESSAGE_PREFIX+e.getLocalizedMessage()).getEvent();
m_eventForwarder.sendNow(event);
throw new ProvisioningAdapterException(MESSAGE_PREFIX, e);
}
private EventBuilder buildEvent(String uei, int nodeId) {
EventBuilder builder = new EventBuilder(uei, "Provisioner", new Date());
builder.setNodeid(nodeId);
return builder;
}
/**
* <p>getNodeDao</p>
*
* @return a {@link org.opennms.netmgt.dao.NodeDao} object.
*/
public NodeDao getNodeDao() {
return m_nodeDao;
}
/**
* <p>setNodeDao</p>
*
* @param dao a {@link org.opennms.netmgt.dao.NodeDao} object.
*/
public void setNodeDao(NodeDao dao) {
m_nodeDao = dao;
}
/**
* @return the assetRecordDao
*/
/*
public AssetRecordDao getAssetRecordDao() {
return m_assetRecordDao;
}
*/
/**
* @param assetRecordDao the assetRecordDao to set
*/
/*
public void setAssetRecordDao(AssetRecordDao assetRecordDao) {
this.m_assetRecordDao = assetRecordDao;
}
*/
/**
* <p>getEventForwarder</p>
*
* @return a {@link org.opennms.netmgt.model.events.EventForwarder} object.
*/
public EventForwarder getEventForwarder() {
return m_eventForwarder;
}
/**
* <p>setEventForwarder</p>
*
* @param eventForwarder a {@link org.opennms.netmgt.model.events.EventForwarder} object.
*/
public void setEventForwarder(EventForwarder eventForwarder) {
m_eventForwarder = eventForwarder;
}
/**
* @return the snmpConfigDao
*/
public SnmpAgentConfigFactory getSnmpPeerFactory() {
return m_snmpConfigDao;
}
/**
* @param snmpConfigDao the snmpConfigDao to set
*/
public void setSnmpPeerFactory(SnmpAgentConfigFactory snmpConfigDao) {
this.m_snmpConfigDao = snmpConfigDao;
}
/**
* @return the m_config
*/
public SnmpAssetAdapterConfig getSnmpAssetAdapterConfig() {
return m_config;
}
/**
* @param mConfig the m_config to set
*/
public void setSnmpAssetAdapterConfig(SnmpAssetAdapterConfig mConfig) {
m_config = mConfig;
}
private static ThreadCategory log() {
return ThreadCategory.getInstance(SnmpAssetProvisioningAdapter.class);
}
/**
* <p>getName</p>
*
* @return a {@link java.lang.String} object.
*/
public String getName() {
return NAME;
}
private InetAddress getIpForNode(OnmsNode node) {
log().debug("getIpForNode: node: " + node.getNodeId() + " Foreign Source: " + node.getForeignSource());
OnmsIpInterface primaryInterface = node.getPrimaryInterface();
InetAddress ipaddr = null;
try {
ipaddr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// Can this even happen?
log().error("Could not fetch localhost address", e);
}
if (primaryInterface == null) {
log().debug("getIpForNode: found null Snmp Primary Interface, getting interfaces");
Set<OnmsIpInterface> ipInterfaces = node.getIpInterfaces();
for (OnmsIpInterface onmsIpInterface : ipInterfaces) {
log().debug("getIpForNode: trying Interface with id: " + onmsIpInterface.getId());
if (onmsIpInterface.getIpAddress() != null)
ipaddr = onmsIpInterface.getInetAddress();
else
log().debug("getIpForNode: found null ip address on Interface with id: " + onmsIpInterface.getId());
}
} else {
log().debug("getIpForNode: found Snmp Primary Interface");
if (primaryInterface.getIpAddress() != null )
ipaddr = primaryInterface.getInetAddress();
else
log().debug("getIpForNode: found null ip address on Primary Interface");
}
return ipaddr;
}
/** {@inheritDoc} */
@Override
public boolean isNodeReady(final AdapterOperation op) {
boolean ready = true;
log().debug("isNodeReady: " + ready + " For Operation " + op.getType() + " for node: " + op.getNodeId());
return ready;
}
/**
* <p>handleReloadConfigEvent</p>
*
* @param event a {@link org.opennms.netmgt.xml.event.Event} object.
*/
@EventHandler(uei = EventConstants.RELOAD_DAEMON_CONFIG_UEI)
public void handleReloadConfigEvent(Event event) {
if (isReloadConfigEventTarget(event)) {
LogUtils.debugf(this, "Reloading the snmp asset adapter configuration");
try {
m_config.update();
m_template.execute(new TransactionCallback<Object>() {
public Object doInTransaction(TransactionStatus arg0) {
buildNodeIpMap();
return null;
}
});
} catch (Throwable e) {
LogUtils.infof(this, e, "Unable to reload snmp asset adapter configuration");
}
}
}
private boolean isReloadConfigEventTarget(Event event) {
boolean isTarget = false;
List<Parm> parmCollection = event.getParms().getParmCollection();
for (Parm parm : parmCollection) {
if (EventConstants.PARM_DAEMON_NAME.equals(parm.getParmName()) && ("Provisiond." + NAME).equalsIgnoreCase(parm.getValue().getContent())) {
isTarget = true;
break;
}
}
log().debug("isReloadConfigEventTarget: Provisiond." + NAME + " was target of reload event: " + isTarget);
return isTarget;
}
}
|
package org.eclipse.birt.report.engine.emitter.excel;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.birt.report.engine.content.IHyperlinkAction;
import org.eclipse.birt.report.engine.content.IReportContent;
import org.eclipse.birt.report.engine.css.engine.value.css.CSSConstants;
import org.eclipse.birt.report.engine.emitter.XMLWriter;
import org.eclipse.birt.report.engine.emitter.excel.layout.ExcelContext;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.core.IModuleModel;
public class ExcelXmlWriter implements IExcelWriter
{
private boolean isRTLSheet = false; // bidi_acgc added
public static final int rightToLeftisTrue = 1; // bidi_acgc added
private final XMLWriterXLS writer = new XMLWriterXLS( );
public XMLWriterXLS getWriter( )
{
return writer;
}
private String pageHeader, pageFooter, orientation;
private int sheetIndex = 1;
public class XMLWriterXLS extends XMLWriter
{
public PrintWriter getPrint( )
{
return printWriter;
}
@Override
protected String getEscapedStr( String s, boolean whitespace )
{
s = super.getEscapedStr( s, whitespace );
StringBuffer buffer = new StringBuffer();
for ( int i = 0, max = s.length( ); i < max; i++ )
{
char c = s.charAt( i );
if ( c == '\n' || c == '\r' )
{
buffer.append( " " ); //$NON-NLS-1$
if ( c == '\r' && i + 1 < max && s.charAt( i + 1 ) == '\n')
{
i++;
}
}
else
{
buffer.append( c );
}
}
return buffer.toString( );
}
}
protected static Logger logger = Logger.getLogger( ExcelXmlWriter.class
.getName( ) );
ExcelContext context = null;
public ExcelXmlWriter( OutputStream out , ExcelContext context )
{
this( out, "UTF-8" , context);
}
public ExcelXmlWriter( OutputStream out )
{
writer.open( out, "UTF-8" );
}
public ExcelXmlWriter( OutputStream out, String encoding, ExcelContext context )
{
this.context = context;
writer.open( out, encoding );
}
/**
* @author bidi_acgc
* @param isRTLSheet:
* represents the direction of the excel sheet.
*/
public ExcelXmlWriter( OutputStream out, boolean isRTLSheet )
{
this.isRTLSheet = isRTLSheet;
writer.open( out, "UTF-8" );
}
/**
* @author bidi_acgc
* @param orientation
* @param pageFooter
* @param pageHeader
* @param isRTLSheet
* : represents the direction of the excel sheet.
*/
public ExcelXmlWriter( OutputStream out, ExcelContext context,
boolean isRTLSheet )
{
this( out, "UTF-8", context );
this.isRTLSheet = isRTLSheet;
}
/**
* @author bidi_acgc
* @param isRTLSheet:
* represents the direction of the excel sheet.
*/
public ExcelXmlWriter( OutputStream out, String encoding,
ExcelContext context, boolean isRTLSheet )
{
this.context = context;
this.isRTLSheet = isRTLSheet;
writer.open( out, encoding );
}
private void writeDocumentProperties( IReportContent reportContent )
{
ReportDesignHandle reportDesign = reportContent.getDesign( )
.getReportDesign( );
writer.openTag( "DocumentProperties" );
writer.attribute( "xmlns", "urn:schemas-microsoft-com:office:office" );
writer.openTag( "Author" );
writer
.text( reportDesign
.getStringProperty( IModuleModel.AUTHOR_PROP ) );
writer.closeTag( "Author" );
writer.openTag( "Title" );
writer.text( reportDesign.getStringProperty( IModuleModel.TITLE_PROP ) );
writer.closeTag( "Title" );
writer.openTag( "Description" );
writer.text( reportDesign
.getStringProperty( IModuleModel.DESCRIPTION_PROP ) );
writer.closeTag( "Description" );
writer.closeTag( "DocumentProperties" );
}
// If possible, we can pass a format according the data type
private void writeText( Data d )
{
writer.openTag( "Data" );
int type = d.getDatatype( );
if ( type == SheetData.NUMBER )
{
if ( d.isNaN( ) || d.isBigNumber( ) || d.isInfility( ) )
{
writer.attribute( "ss:Type", "String" );
}
else
{
writer.attribute( "ss:Type", "Number" );
}
}
else if ( type == SheetData.DATE )
{
writer.attribute( "ss:Type", "DateTime" );
}
else
{
writer.attribute( "ss:Type", "String" );
}
d.formatTxt( );
String txt = d.getText( ).toString( );
if ( CSSConstants.CSS_CAPITALIZE_VALUE.equalsIgnoreCase( d.getStyle( )
.getProperty( StyleConstant.TEXT_TRANSFORM ) ) )
{
txt = capitalize( txt );
}
else if ( CSSConstants.CSS_UPPERCASE_VALUE.equalsIgnoreCase( d
.getStyle( ).getProperty( StyleConstant.TEXT_TRANSFORM ) ) )
{
txt = txt.toUpperCase( );
}
else if ( CSSConstants.CSS_LOWERCASE_VALUE.equalsIgnoreCase( d
.getStyle( ).getProperty( StyleConstant.TEXT_TRANSFORM ) ) )
{
txt = txt.toLowerCase( );
}
writer.text( txt );
writer.closeTag( "Data" );
}
private String capitalize( String text )
{
boolean capitalizeNextChar = true;
char[] array = text.toCharArray( );
for ( int i = 0; i < array.length; i++ )
{
char c = text.charAt( i );
if ( c == ' ' || c == '\n' || c == '\r' )
capitalizeNextChar = true;
else if ( capitalizeNextChar )
{
array[i] = Character.toUpperCase( array[i] );
capitalizeNextChar = false;
}
}
return new String( array );
}
public void startRow( double rowHeight )
{
writer.openTag( "Row" );
}
public void endRow( )
{
writer.closeTag( "Row" );
}
private void startCell( int cellindex, int colspan, int rowspan,
int styleid, HyperlinkDef hyperLink ,BookmarkDef linkedBookmark)
{
writer.openTag( "Cell" );
writer.attribute( "ss:Index", cellindex );
writer.attribute( "ss:StyleID", styleid );
if ( hyperLink != null )
{
String urlAddress = hyperLink.getUrl( );
if ( hyperLink.getType( ) == IHyperlinkAction.ACTION_BOOKMARK )
{
if ( linkedBookmark != null )
urlAddress = "#" + linkedBookmark.getValidName( );
else
{
logger.log( Level.WARNING, "The bookmark: {" + urlAddress
+ "} is not defined!" );
}
}
if ( urlAddress != null && urlAddress.length( ) >= 255 )
{
logger.log( Level.WARNING, "The URL: {" + urlAddress
+ "} is too long!" );
urlAddress = urlAddress.substring( 0, 254 );
}
writer.attribute( "ss:HRef", urlAddress );
}
writer.attribute( "ss:MergeAcross", colspan );
writer.attribute( "ss:MergeDown", rowspan );
}
public void writeDefaultCell( Data d )
{
writer.openTag( "Cell" );
if ( d.getStyleId( ) != 0 )
{
writer.attribute( "ss:StyleID", d.getStyleId( ) );
}
writeText( d );
writer.closeTag( "Cell" );
}
public void outputData( SheetData sheetData )
{
if ( sheetData.getDatatype( ) == SheetData.IMAGE )
return;
Data d = (Data) sheetData;
startCell( d.span.getCol( ), d.span.getColSpan( ), d.getRowSpan( ),
d.styleId, d.hyperLink, d.getLinkedBookmark( ) );
writeText( d );
if(d.hyperLink != null && d.hyperLink.getToolTip( ) != null)
{
writeComments(d.hyperLink);
}
endCell( );
}
protected void writeComments(HyperlinkDef linkDef)
{
String toolTip = linkDef.getToolTip( );
writer.openTag( "Comment" );
writer.openTag( "ss:Data" );
writer.attribute( "xmlns", "http:
writer.openTag( "Font" );
// writer.attribute( "html:Face", "Tahoma" );
// writer.attribute( "x:CharSet", "1" );
// writer.attribute( "html:Size", "8" );
// writer.attribute( "html:Color", "#000000" );
writer.text( toolTip );
writer.closeTag( "Font" );
writer.closeTag( "ss:Data" );
writer.closeTag( "Comment" );
}
protected void writeFormulaData( Data d )
{
writer.openTag( "Cell" );
writer.attribute( "ss:Index", d.span.getCol( ) );
writer.attribute( "ss:Formula", d.txt.toString( ) );
writer.attribute( "ss:MergeAcross", d.span.getColSpan( ) );
writer.attribute( "ss:StyleID", d.styleId );
writer.closeTag( "Cell" );
}
private void endCell( )
{
writer.closeTag( "Cell" );
}
private void writeAlignment( String horizontal, String vertical,
String direction, boolean wrapText )
{
writer.openTag( "Alignment" );
if ( isValid( horizontal ) )
{
writer.attribute( "ss:Horizontal", horizontal );
}
if ( isValid( vertical ) )
{
writer.attribute( "ss:Vertical", vertical );
}
if ( isValid( direction ) )
{
if ( CSSConstants.CSS_RTL_VALUE.equals( direction ) )
writer.attribute( "ss:ReadingOrder", "RightToLeft" );
else
writer.attribute( "ss:ReadingOrder", "LeftToRight" );
}
if(wrapText)
{
writer.attribute( "ss:WrapText", "1" );
}
writer.closeTag( "Alignment" );
}
private void writeBorder( String position, String lineStyle, String weight,
String color )
{
writer.openTag( "Border" );
writer.attribute( "ss:Position", position );
if ( isValid( lineStyle ) )
{
writer.attribute( "ss:LineStyle", lineStyle );
}
if ( isValid( weight ) )
{
writer.attribute( "ss:Weight", weight );
}
if ( isValid( color ) )
{
writer.attribute( "ss:Color", color );
}
writer.closeTag( "Border" );
}
private void writeFont( String fontName, String size, String bold,
String italic, String strikeThrough, String underline, String color )
{
writer.openTag( "Font" );
if ( isValid( fontName ) )
{
writer.attribute( "ss:FontName", fontName );
}
if ( isValid( size ) )
{
writer.attribute( "ss:Size", size );
}
if ( isValid( bold ) )
{
writer.attribute( "ss:Bold", bold );
}
if ( isValid( italic ) )
{
writer.attribute( "ss:Italic", italic );
}
if ( isValid( strikeThrough ) )
{
writer.attribute( "ss:StrikeThrough", strikeThrough );
}
if ( isValid( underline ) && !"0".equalsIgnoreCase( underline ) )
{
writer.attribute( "ss:Underline", "Single" );
}
if ( isValid( color ) )
{
writer.attribute( "ss:Color", color );
}
writer.closeTag( "Font" );
}
private void writeBackGroudColor( String bgColor )
{
if ( isValid( bgColor ) )
{
writer.openTag( "Interior" );
writer.attribute( "ss:Color", bgColor );
writer.attribute( "ss:Pattern", "Solid" );
writer.closeTag( "Interior" );
}
}
private boolean isValid( String value )
{
return !StyleEntry.isNull( value );
}
private void declareStyle( StyleEntry style, int id )
{
boolean wrapText = context.getWrappingText( );
String whiteSpace = style.getProperty( StyleConstant.WHITE_SPACE );
if ( CSSConstants.CSS_NOWRAP_VALUE.equals( whiteSpace ) )
{
wrapText = false;
}
writer.openTag( "Style" );
writer.attribute( "ss:ID", id );
if ( id >= StyleEngine.RESERVE_STYLE_ID )
{
String direction = style.getProperty( StyleConstant.DIRECTION_PROP ); // bidi_hcg
String horizontalAlign = style
.getProperty( StyleConstant.H_ALIGN_PROP );
String verticalAlign = style
.getProperty( StyleConstant.V_ALIGN_PROP );
writeAlignment( horizontalAlign, verticalAlign, direction, wrapText );
writer.openTag( "Borders" );
String bottomColor = style
.getProperty( StyleConstant.BORDER_BOTTOM_COLOR_PROP );
String bottomLineStyle = style
.getProperty( StyleConstant.BORDER_BOTTOM_STYLE_PROP );
String bottomWeight = style
.getProperty( StyleConstant.BORDER_BOTTOM_WIDTH_PROP );
writeBorder( "Bottom", bottomLineStyle, bottomWeight, bottomColor );
String topColor = style
.getProperty( StyleConstant.BORDER_TOP_COLOR_PROP );
String topLineStyle = style
.getProperty( StyleConstant.BORDER_TOP_STYLE_PROP );
String topWeight = style
.getProperty( StyleConstant.BORDER_TOP_WIDTH_PROP );
writeBorder( "Top", topLineStyle, topWeight, topColor );
String leftColor = style
.getProperty( StyleConstant.BORDER_LEFT_COLOR_PROP );
String leftLineStyle = style
.getProperty( StyleConstant.BORDER_LEFT_STYLE_PROP );
String leftWeight = style
.getProperty( StyleConstant.BORDER_LEFT_WIDTH_PROP );
writeBorder( "Left", leftLineStyle, leftWeight, leftColor );
String rightColor = style
.getProperty( StyleConstant.BORDER_RIGHT_COLOR_PROP );
String rightLineStyle = style
.getProperty( StyleConstant.BORDER_RIGHT_STYLE_PROP );
String rightWeight = style
.getProperty( StyleConstant.BORDER_RIGHT_WIDTH_PROP );
writeBorder( "Right", rightLineStyle, rightWeight, rightColor );
writer.closeTag( "Borders" );
String fontName = style
.getProperty( StyleConstant.FONT_FAMILY_PROP );
String size = style.getProperty( StyleConstant.FONT_SIZE_PROP );
String fontStyle = style
.getProperty( StyleConstant.FONT_STYLE_PROP );
String fontWeight = style
.getProperty( StyleConstant.FONT_WEIGHT_PROP );
String strikeThrough = style
.getProperty( StyleConstant.TEXT_LINE_THROUGH_PROP );
String underline = style
.getProperty( StyleConstant.TEXT_UNDERLINE_PROP );
String color = style.getProperty( StyleConstant.COLOR_PROP );
writeFont( fontName, size, fontWeight, fontStyle, strikeThrough,
underline, color );
String bgColor = style
.getProperty( StyleConstant.BACKGROUND_COLOR_PROP );
writeBackGroudColor( bgColor );
}
writeDataFormat( style );
writer.closeTag( "Style" );
}
private void writeDataFormat( StyleEntry style )
{
String typeString = style.getProperty( StyleConstant.DATA_TYPE_PROP );
if ( typeString == null )
return;
int type = Integer.parseInt( typeString );
if ( type == SheetData.DATE
&& style.getProperty( StyleConstant.DATE_FORMAT_PROP ) != null )
{
writer.openTag( "NumberFormat" );
writer.attribute( "ss:Format", style
.getProperty( StyleConstant.DATE_FORMAT_PROP ) );
writer.closeTag( "NumberFormat" );
}
if ( type == Data.NUMBER
&& style.getProperty( StyleConstant.NUMBER_FORMAT_PROP ) != null )
{
writer.openTag( "NumberFormat" );
String numberStyle = style
.getProperty( StyleConstant.NUMBER_FORMAT_PROP );
writer.attribute( "ss:Format", numberStyle );
writer.closeTag( "NumberFormat" );
}
}
// here the user input can be divided into two cases :
// the case in the birt input like G and the Currency
// the case in excel format : like 0.00E00
private void writeDeclarations( )
{
writer.startWriter( );
writer.getPrint( ).println( );
writer.getPrint( ).println(
"<?mso-application progid=\"Excel.Sheet\"?>" );
writer.openTag( "Workbook" );
writer.attribute( "xmlns",
"urn:schemas-microsoft-com:office:spreadsheet" );
writer.attribute( "xmlns:o", "urn:schemas-microsoft-com:office:office" );
writer.attribute( "xmlns:x", "urn:schemas-microsoft-com:office:excel" );
writer.attribute( "xmlns:ss",
"urn:schemas-microsoft-com:office:spreadsheet" );
writer.attribute( "xmlns:html", "http:
}
private void declareStyles( Map<StyleEntry, Integer> style2id )
{
writer.openTag( "Styles" );
Set<Entry<StyleEntry, Integer>> entrySet = style2id.entrySet( );
for ( Map.Entry<StyleEntry, Integer> entry : entrySet )
{
declareStyle( entry.getKey( ), entry.getValue( ) );
}
writer.closeTag( "Styles" );
}
private void defineNames( Entry<String, BookmarkDef> bookmarkEntry )
{
BookmarkDef bookmark = bookmarkEntry.getValue( );
String name = bookmark.getValidName( );
String refer = getRefer( bookmark.getSheetIndex( ), bookmark );
defineName( name, refer );
}
private String getRefer( int sheetIndex, BookmarkDef bookmark )
{
StringBuffer sb = new StringBuffer( "=Sheet" );
sb.append( sheetIndex );
sb.append( "!R" );
sb.append( bookmark.getRowNo( ) );
sb.append( "C" );
sb.append( bookmark.getColumnNo( ) );
return sb.toString( );
}
private void defineName( String name, String refer )
{
writer.openTag( "NamedRange" );
writer.attribute( "ss:Name", name );
writer.attribute( "ss:RefersTo", refer );
writer.closeTag( "NamedRange" );
}
public void startSheet( String name )
{
writer.openTag( "Worksheet" );
writer.attribute( "ss:Name", name );
// Set the Excel Sheet RightToLeft attribute according to Report
//if Report Bidi-Orientation is RTL, then Sheet is RTL.
if ( isRTLSheet )
writer.attribute( "ss:RightToLeft", rightToLeftisTrue );
// else : do nothing i.e. LTR
}
public void closeSheet( )
{
writer.closeTag( "Worksheet" );
writer.endWriter( );
}
public void ouputColumns( int[] width )
{
writer.openTag( "ss:Table" );
if ( width == null )
{
logger.log( Level.SEVERE, "Invalid columns width" );
return;
}
for ( int i = 0; i < width.length; i++ )
{
writer.openTag( "ss:Column" );
writer.attribute( "ss:Width", width[i] );
writer.closeTag( "ss:Column" );
}
}
public void endTable( )
{
writer.closeTag( "ss:Table" );
}
public void insertHorizontalMargin( int height, int span )
{
writer.openTag( "Row" );
writer.attribute( "ss:AutoFitHeight", 0 );
writer.attribute( "ss:Height", height );
writer.openTag( "Cell" );
writer.attribute( " ss:MergeAcross", span );
writer.closeTag( "Cell" );
writer.closeTag( "Row" );
}
public void insertVerticalMargin( int start, int end, int length )
{
writer.openTag( "Row" );
writer.attribute( "ss:AutoFitHeight", 0 );
writer.attribute( "ss:Height", 1 );
writer.openTag( "Cell" );
writer.attribute( "ss:Index", start );
writer.attribute( " ss:MergeDown", length );
writer.closeTag( "Cell" );
writer.openTag( "Cell" );
writer.attribute( "ss:Index", end );
writer.attribute( " ss:MergeDown", length );
writer.closeTag( "Cell" );
writer.closeTag( "Row" );
}
private void declareWorkSheetOptions( String orientation,
String pageHeader, String pageFooter )
{
writer.openTag( "WorksheetOptions" );
writer.attribute( "xmlns", "urn:schemas-microsoft-com:office:excel" );
writer.openTag( "PageSetup" );
if(orientation!=null)
{
writer.openTag( "Layout" );
writer.attribute( "x:Orientation", orientation );
writer.closeTag( "Layout" );
}
if(pageHeader!=null)
{
writer.openTag( "Header" );
writer.attribute( "x:Data", pageHeader );
writer.closeTag( "Header" );
}
if(pageFooter!=null)
{
writer.openTag( "Footer" );
writer.attribute( "x:Data", pageFooter );
writer.closeTag( "Footer" );
}
writer.closeTag( "PageSetup" );
writer.closeTag( "WorksheetOptions" );
}
private void startSheet( int sheetIndex )
{
startSheet( "Sheet" + String.valueOf( sheetIndex ) );
}
public void startSheet( int[] coordinates, String pageHeader,
String pageFooter )
{
this.pageHeader = pageHeader;
this.pageFooter = pageFooter;
startSheet( sheetIndex );
ouputColumns( coordinates );
sheetIndex += 1;
}
public void endSheet( String orientaion )
{
endTable( );
declareWorkSheetOptions( orientation, pageHeader, pageFooter );
closeSheet( );
}
public void start( IReportContent report, Map<StyleEntry, Integer> styles,
HashMap<String, BookmarkDef> bookmarkList )
{
writeDeclarations( );
writeDocumentProperties( report );
declareStyles( styles);
outputBookmarks( bookmarkList );
}
private void outputBookmarks( HashMap<String, BookmarkDef> bookmarkList )
{
if ( !bookmarkList.isEmpty( ) )
{
writer.openTag( "Names" );
Set<Entry<String, BookmarkDef>> bookmarkEntry = bookmarkList
.entrySet( );
for ( Entry<String, BookmarkDef> bookmark : bookmarkEntry )
defineNames( bookmark );
writer.closeTag( "Names" );
}
}
public void end( )
{
writer.closeTag( "Workbook" );
close( );
}
public void close( )
{
writer.endWriter( );
writer.close( );
}
public void setSheetIndex( int sheetIndex )
{
this.sheetIndex = sheetIndex;
}
}
|
package org.xwiki.refactoring;
import org.xwiki.rendering.block.XDOM;
/**
* Represents an in-memory wiki page used by the {@link org.xwiki.refactoring.splitter.DocumentSplitter} interface.
*
* @version $Id$
* @since 1.9M1
*/
public class WikiDocument
{
/**
* Full name of the target wiki page.
*/
private String fullName;
/**
* The {@link XDOM} of the target wiki page.
*/
private XDOM xdom;
/**
* The parent {@link WikiDocument} of this document.
*/
private WikiDocument parent;
/**
* Constructs a new {@link WikiDocument}.
*
* @param fullName full name of the target wiki page.
* @param xdom {@link XDOM} for the target wiki page.
* @param parent the parent {@link WikiDocument} of this document.
*/
public WikiDocument(String fullName, XDOM xdom, WikiDocument parent)
{
this.fullName = fullName;
this.xdom = xdom;
this.parent = parent;
}
/**
* @return full name of the target wiki page.
*/
public String getFullName()
{
return fullName;
}
/**
* @return the {@link XDOM} of the target wiki page.
*/
public XDOM getXdom()
{
return xdom;
}
/**
* @return the parent {@link WikiDocument} of this document.
*/
public WikiDocument getParent()
{
return parent;
}
@Override
public boolean equals(Object obj)
{
boolean equals = false;
if (obj instanceof WikiDocument) {
equals = ((WikiDocument) obj).getFullName().equals(getFullName());
}
return equals;
}
@Override
public int hashCode()
{
return getFullName().hashCode();
}
}
|
package nl.mpi.arbil.ui.applet;
import java.net.URI;
import nl.mpi.arbil.ArbilDesktopInjector;
import nl.mpi.arbil.data.DataNodeLoader;
import nl.mpi.arbil.ui.ArbilSplitPanel;
import nl.mpi.arbil.ui.ArbilTable;
import nl.mpi.arbil.ui.ArbilTableModel;
import nl.mpi.arbil.ui.ImageBoxRenderer;
import nl.mpi.arbil.util.BugCatcherManager;
public class ArbilTableApplet extends javax.swing.JApplet {
private DataNodeLoader dataNodeLoader;
@Override
public void init() {
final ArbilDesktopInjector injector = new ArbilDesktopInjector();
// TODO: test if this suffices
injector.injectHandlers();
dataNodeLoader = injector.getDataNodeLoader();
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents(injector.getImageBoxRenderer());
addNodesToTable(getParameter("ImdiFileList"));
addShowOnlyColumnsToTable(getParameter("ShowOnlyColumns"));
addChildNodesToTable(getParameter("ChildNodeColumns"));
addHighlightToTable(getParameter("HighlightText"));
}
});
} catch (Exception ex) {
BugCatcherManager.getBugCatcher().logError(ex);
}
}
private void addNodesToTable(String nodeURLsString) {
if (nodeURLsString != null) {
for (String currentUrlString : nodeURLsString.split(",")) {
try {
arbilTableModel.addSingleArbilDataNode(dataNodeLoader.getArbilDataNode(rootPane, new URI(currentUrlString)));
} catch (Exception ex) {
BugCatcherManager.getBugCatcher().logError(ex);
}
}
}
}
private void addShowOnlyColumnsToTable(String showColumnsString) {
if (showColumnsString != null && showColumnsString.trim().length() > 0) {
for (String currentshowColumns : showColumnsString.split(",")) {
arbilTableModel.getFieldView().addShowOnlyColumn(currentshowColumns.trim());
}
}
}
private void addChildNodesToTable(String childNodesString) {
if (childNodesString != null && childNodesString.trim().length() > 0) {
for (String currentChildNode : childNodesString.split(",")) {
arbilTableModel.addChildTypeToDisplay(currentChildNode.trim());
}
}
}
private void addHighlightToTable(String highlightableTextString) {
if (highlightableTextString != null && highlightableTextString.length() > 0) {
for (String highlightText : highlightableTextString.split(",")) {
arbilTableModel.highlightMatchingText(highlightText);
}
}
}
private void initComponents(ImageBoxRenderer imageBoxRenderer) {
arbilTableModel = new ArbilTableModel(imageBoxRenderer);
ArbilTable arbilTable = new ArbilTable(arbilTableModel, tableTitle);
ArbilSplitPanel arbilSplitPanel = new ArbilSplitPanel(arbilTable);
arbilTableModel.hideContextMenuAndStatusBar = true;
arbilSplitPanel.setSplitDisplay();
getContentPane().add(arbilSplitPanel, java.awt.BorderLayout.CENTER);
}
private String tableTitle = "Arbil Table Demo";
private ArbilTableModel arbilTableModel;
}
|
package org.atlasapi;
import java.net.UnknownHostException;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.atlasapi.channel.ChannelGroupResolver;
import org.atlasapi.channel.ChannelResolver;
import org.atlasapi.content.CassandraEquivalentContentStore;
import org.atlasapi.content.ContentIndex;
import org.atlasapi.content.ContentStore;
import org.atlasapi.content.EquivalentContentStore;
import org.atlasapi.content.EsContentTitleSearcher;
import org.atlasapi.content.EsContentTranslator;
import org.atlasapi.equivalence.EquivalenceGraphStore;
import org.atlasapi.event.EventResolver;
import org.atlasapi.event.EventWriter;
import org.atlasapi.media.channel.CachingChannelGroupStore;
import org.atlasapi.media.channel.CachingChannelStore;
import org.atlasapi.media.channel.ChannelGroupStore;
import org.atlasapi.media.channel.MongoChannelGroupStore;
import org.atlasapi.media.channel.MongoChannelStore;
import org.atlasapi.media.channel.ServiceChannelStore;
import org.atlasapi.media.segment.MongoSegmentResolver;
import org.atlasapi.messaging.EquivalentContentUpdatedMessage;
import org.atlasapi.messaging.KafkaMessagingModule;
import org.atlasapi.messaging.MessagingModule;
import org.atlasapi.messaging.v3.ScheduleUpdateMessage;
import org.atlasapi.organisation.OrganisationResolver;
import org.atlasapi.organisation.OrganisationStore;
import org.atlasapi.persistence.audit.NoLoggingPersistenceAuditLog;
import org.atlasapi.persistence.audit.PersistenceAuditLog;
import org.atlasapi.persistence.content.DefaultEquivalentContentResolver;
import org.atlasapi.persistence.content.EquivalentContentResolver;
import org.atlasapi.persistence.content.KnownTypeContentResolver;
import org.atlasapi.persistence.content.LookupResolvingContentResolver;
import org.atlasapi.persistence.content.mongo.MongoContentResolver;
import org.atlasapi.persistence.content.mongo.MongoPlayerStore;
import org.atlasapi.persistence.content.mongo.MongoServiceStore;
import org.atlasapi.persistence.content.mongo.MongoTopicStore;
import org.atlasapi.persistence.content.organisation.MongoOrganisationStore;
import org.atlasapi.persistence.content.schedule.mongo.MongoScheduleStore;
import org.atlasapi.persistence.event.MongoEventStore;
import org.atlasapi.persistence.ids.MongoSequentialIdGenerator;
import org.atlasapi.persistence.lookup.TransitiveLookupWriter;
import org.atlasapi.persistence.lookup.mongo.MongoLookupEntryStore;
import org.atlasapi.persistence.player.CachingPlayerResolver;
import org.atlasapi.persistence.player.PlayerResolver;
import org.atlasapi.persistence.service.CachingServiceResolver;
import org.atlasapi.persistence.service.ServiceResolver;
import org.atlasapi.schedule.EquivalentScheduleStore;
import org.atlasapi.schedule.ScheduleResolver;
import org.atlasapi.schedule.ScheduleStore;
import org.atlasapi.schedule.ScheduleWriter;
import org.atlasapi.segment.SegmentStore;
import org.atlasapi.system.MetricsModule;
import org.atlasapi.system.legacy.ContentListerResourceListerAdapter;
import org.atlasapi.system.legacy.LegacyChannelGroupResolver;
import org.atlasapi.system.legacy.LegacyChannelGroupTransformer;
import org.atlasapi.system.legacy.LegacyChannelResolver;
import org.atlasapi.system.legacy.LegacyChannelTransformer;
import org.atlasapi.system.legacy.LegacyContentLister;
import org.atlasapi.system.legacy.LegacyContentResolver;
import org.atlasapi.system.legacy.LegacyContentTransformer;
import org.atlasapi.system.legacy.LegacyEventResolver;
import org.atlasapi.system.legacy.LegacyLookupResolvingContentLister;
import org.atlasapi.system.legacy.LegacyOrganisationResolver;
import org.atlasapi.system.legacy.LegacyOrganisationTransformer;
import org.atlasapi.system.legacy.LegacyScheduleResolver;
import org.atlasapi.system.legacy.LegacySegmentMigrator;
import org.atlasapi.system.legacy.LegacyTopicLister;
import org.atlasapi.system.legacy.LegacyTopicResolver;
import org.atlasapi.system.legacy.PaTagMap;
import org.atlasapi.topic.EsPopularTopicIndex;
import org.atlasapi.topic.EsTopicIndex;
import org.atlasapi.topic.TopicStore;
import org.atlasapi.util.CassandraSecondaryIndex;
import com.metabroadcast.common.health.HealthProbe;
import com.metabroadcast.common.ids.IdGeneratorBuilder;
import com.metabroadcast.common.ids.SubstitutionTableNumberCodec;
import com.metabroadcast.common.persistence.cassandra.DatastaxCassandraService;
import com.metabroadcast.common.persistence.mongo.DatabasedMongo;
import com.metabroadcast.common.persistence.mongo.health.MongoConnectionPoolProbe;
import com.metabroadcast.common.properties.Configurer;
import com.metabroadcast.common.properties.Parameter;
import com.metabroadcast.common.queue.MessageSender;
import com.metabroadcast.common.queue.MessageSenders;
import com.google.common.base.Predicates;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Ints;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
import com.netflix.astyanax.AstyanaxContext;
import com.netflix.astyanax.Keyspace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
@Configuration
@Import({ KafkaMessagingModule.class })
public class AtlasPersistenceModule {
private static final String MONGO_COLLECTION_LOOKUP = "lookup";
private static final String MONGO_COLLECTION_TOPICS = "topics";
private static final PersistenceAuditLog persistenceAuditLog = new NoLoggingPersistenceAuditLog();
private final String mongoWriteHost = Configurer.get("mongo.write.host").get();
private final Integer mongoWritePort = Configurer.get("mongo.write.port").toInt();
private final String mongoWriteDbName = Configurer.get("mongo.write.name").get();
private final String mongoReadHost = Configurer.get("mongo.read.host").get();
private final Integer mongoReadPort = Configurer.get("mongo.read.port").toInt();
private final String mongoReadDbName = Configurer.get("mongo.read.name").get();
private final String cassandraCluster = Configurer.get("cassandra.cluster").get();
private final String cassandraKeyspace = Configurer.get("cassandra.keyspace").get();
private final String cassandraSeeds = Configurer.get("cassandra.seeds").get();
private final String cassandraPort = Configurer.get("cassandra.port").get();
private final String cassandraConnectionTimeout = Configurer.get("cassandra.connectionTimeout")
.get();
private final String cassandraClientThreads = Configurer.get("cassandra.clientThreads").get();
private final Integer cassandraConnectionsPerHostLocal = Configurer.get(
"cassandra.connectionsPerHost.local").toInt();
private final Integer cassandraConnectionsPerHostRemote = Configurer.get(
"cassandra.connectionsPerHost.remote").toInt();
private final Integer cassandraDatastaxConnectionTimeout = Configurer.get(
"cassandra.datastax.timeouts.connections").toInt();
private final Integer cassandraDatastaxReadTimeout = Configurer.get(
"cassandra.datastax.timeouts.read").toInt();
private final String esSeeds = Configurer.get("elasticsearch.seeds").get();
private final int port = Ints.saturatedCast(Configurer.get("elasticsearch.port").toLong());
private final boolean ssl = Configurer.get("elasticsearch.ssl").toBoolean();
private final String esCluster = Configurer.get("elasticsearch.cluster").get();
private final String esIndex = Configurer.get("elasticsearch.index").get();
private final String esRequestTimeout = Configurer.get("elasticsearch.requestTimeout").get();
private final Parameter processingConfig = Configurer.get("processing.config");
private String equivalentContentChanges = Configurer.get(
"messaging.destination.equivalent.content.changes").get();
private @Autowired MessagingModule messaging;
private @Autowired MetricsModule metricsModule;
@PostConstruct
public void init() {
persistenceModule().startAsync().awaitRunning();
// This is required to initialise the BackgroundComputingValue in the CachingChannelStore
// otherwise we will get NPEs
channelStore().start();
}
@PreDestroy
public void tearDown() {
channelStore().shutdown();
}
@Bean
public CassandraPersistenceModule persistenceModule() {
Iterable<String> seeds = Splitter.on(",").split(cassandraSeeds);
ConfiguredAstyanaxContext contextSupplier = new ConfiguredAstyanaxContext(cassandraCluster,
cassandraKeyspace,
seeds,
Integer.parseInt(cassandraPort),
Integer.parseInt(cassandraClientThreads),
Integer.parseInt(cassandraConnectionTimeout),
metricsModule.metrics()
);
AstyanaxContext<Keyspace> context = contextSupplier.get();
context.start();
DatastaxCassandraService cassandraService = DatastaxCassandraService.builder()
.withNodes(seeds)
.withConnectionsPerHostLocal(cassandraConnectionsPerHostLocal)
.withConnectionsPerHostRemote(cassandraConnectionsPerHostRemote)
.withConnectTimeoutMillis(cassandraDatastaxConnectionTimeout)
.withReadTimeoutMillis(cassandraDatastaxReadTimeout)
.build();
cassandraService.startAsync().awaitRunning();
return new CassandraPersistenceModule(
messaging.messageSenderFactory(),
context,
cassandraService,
cassandraKeyspace,
idGeneratorBuilder(),
content -> UUID.randomUUID().toString(),
eventV2 -> UUID.randomUUID().toString(),
seeds,
metricsModule.metrics()
);
}
@Bean
public ContentStore contentStore() {
return persistenceModule().contentStore();
}
public ContentStore nullMessageSendingContentStore() {
return persistenceModule().nullMessageSendingContentStore();
}
public EquivalenceGraphStore nullMessageSendingGraphStore() {
return persistenceModule().nullMessageSendingGraphStore();
}
@Bean
public TopicStore topicStore() {
return persistenceModule().topicStore();
}
@Bean
public ScheduleStore scheduleStore() {
return persistenceModule().scheduleStore();
}
@Bean
public SegmentStore segmentStore() {
return persistenceModule().segmentStore();
}
@Bean
public EventWriter eventWriter() {
return persistenceModule().eventStore();
}
@Bean
public EventResolver eventResolver() {
return persistenceModule().eventStore();
}
@Bean
public OrganisationStore organisationStore() {
return persistenceModule().organisationStore();
}
@Bean
public OrganisationStore idSettingOrganisationStore() {
return persistenceModule().idSettingOrganisationStore();
}
@Bean
public EquivalenceGraphStore getContentEquivalenceGraphStore() {
return persistenceModule().contentEquivalenceGraphStore();
}
@Bean
public EquivalenceGraphStore nullMessageSendingEquivalenceGraphStore() {
return persistenceModule().nullMessageSendingEquivalenceGraphStore();
}
@Bean
public EquivalentContentStore getEquivalentContentStore() {
return new CassandraEquivalentContentStore(
persistenceModule().contentStore(),
legacyContentResolver(),
persistenceModule().contentEquivalenceGraphStore(),
persistenceModule().sender(
equivalentContentChanges,
EquivalentContentUpdatedMessage.class
),
persistenceModule().getSession(),
persistenceModule().getReadConsistencyLevel(),
persistenceModule().getWriteConsistencyLevel()
);
}
@Bean
public EquivalentContentStore nullMessageSendingEquivalentContentStore() {
return new CassandraEquivalentContentStore(
persistenceModule().contentStore(),
legacyContentResolver(),
persistenceModule().contentEquivalenceGraphStore(),
persistenceModule().nullMessageSender(EquivalentContentUpdatedMessage.class),
persistenceModule().getSession(),
persistenceModule().getReadConsistencyLevel(),
persistenceModule().getWriteConsistencyLevel()
);
}
@Bean
public EquivalentScheduleStore getEquivalentScheduleStore() {
return persistenceModule().equivalentScheduleStore();
}
@Bean
public ElasticSearchContentIndexModule esContentIndexModule() {
ElasticSearchContentIndexModule module =
new ElasticSearchContentIndexModule(
esSeeds,
port,
ssl,
esCluster,
esIndex,
Long.parseLong(esRequestTimeout),
persistenceModule().contentStore(),
metricsModule.metrics(),
channelGroupResolver(),
new CassandraSecondaryIndex(
persistenceModule().getSession(),
CassandraEquivalentContentStore.EQUIVALENT_CONTENT_INDEX,
persistenceModule().getReadConsistencyLevel()
)
);
module.init();
return module;
}
@Bean
@Primary
public DatabasedMongo databasedReadMongo() {
return new DatabasedMongo(mongo(mongoReadHost, mongoReadPort), mongoReadDbName);
}
@Bean
public DatabasedMongo databasedWriteMongo() {
return new DatabasedMongo(mongo(mongoWriteHost, mongoWritePort), mongoWriteDbName);
}
public Mongo mongo(String mongoHost, Integer mongoPort) {
Mongo mongo = new MongoClient(
mongoHosts(mongoHost, mongoPort),
MongoClientOptions.builder()
.connectionsPerHost(1000)
.connectTimeout(10000)
.build()
);
if (processingConfig == null || !processingConfig.toBoolean()) {
mongo.setReadPreference(ReadPreference.secondaryPreferred());
}
return mongo;
}
public IdGeneratorBuilder idGeneratorBuilder() {
return sequenceIdentifier -> new MongoSequentialIdGenerator(
databasedWriteMongo(),
sequenceIdentifier
);
}
@Bean
@Primary
public ContentIndex contentIndex() {
return esContentIndexModule().equivContentIndex();
}
@Bean
@Primary
public EsContentTranslator esContentTranslator() {
return esContentIndexModule().translator();
}
@Bean
@Primary
public EsTopicIndex topicIndex() {
return esContentIndexModule().topicIndex();
}
@Bean
@Primary
public EsPopularTopicIndex popularTopicIndex() {
return esContentIndexModule().topicSearcher();
}
@Bean
@Primary
public EsContentTitleSearcher contentSearcher() {
return esContentIndexModule().contentTitleSearcher();
}
@Bean
@Primary
public ServiceChannelStore channelStore() {
MongoChannelStore rawStore = new MongoChannelStore(
databasedReadMongo(),
channelGroupStore(),
channelGroupStore()
);
return new CachingChannelStore(rawStore);
}
@Bean
@Primary
public ChannelGroupStore channelGroupStore() {
return new CachingChannelGroupStore(
new MongoChannelGroupStore(databasedReadMongo())
);
}
private List<ServerAddress> mongoHosts(String mongoHost, final Integer mongoPort) {
Splitter splitter = Splitter.on(",").omitEmptyStrings().trimResults();
return ImmutableList.copyOf(Iterables.filter(Iterables.transform(
splitter.split(mongoHost),
input -> {
try {
return new ServerAddress(input, mongoPort);
} catch (UnknownHostException e) {
return null;
}
}
), Predicates.notNull()));
}
@Bean
HealthProbe mongoConnectionProbe() {
return new MongoConnectionPoolProbe();
}
@Bean
public ChannelResolver channelResolver() {
return new LegacyChannelResolver(channelStore(), new LegacyChannelTransformer());
}
@Bean
public ChannelGroupResolver channelGroupResolver() {
return new LegacyChannelGroupResolver(
channelGroupStore(),
new LegacyChannelGroupTransformer()
);
}
@Bean
public PlayerResolver playerResolver() {
return new CachingPlayerResolver(new MongoPlayerStore(databasedReadMongo()));
}
@Bean
public ServiceResolver serviceResolver() {
return new CachingServiceResolver(new MongoServiceStore(databasedReadMongo()));
}
public LegacyContentResolver legacyContentResolver() {
DatabasedMongo mongoDb = databasedReadMongo();
KnownTypeContentResolver contentResolver = new MongoContentResolver(
mongoDb,
legacyEquivalenceStore()
);
return new LegacyContentResolver(
legacyEquivalenceStore(),
contentResolver,
legacyContentTransformer()
);
}
public MongoLookupEntryStore legacyEquivalenceStore() {
return new MongoLookupEntryStore(
databasedReadMongo().collection(MONGO_COLLECTION_LOOKUP),
persistenceAuditLog,
ReadPreference.primaryPreferred()
);
}
public LegacySegmentMigrator legacySegmentMigrator() {
return new LegacySegmentMigrator(legacySegmentResolver(), segmentStore());
}
public org.atlasapi.media.segment.SegmentResolver legacySegmentResolver() {
return new MongoSegmentResolver(databasedReadMongo(), new SubstitutionTableNumberCodec());
}
public ScheduleWriter v2ScheduleStore() {
return persistenceModule().v2ScheduleStore();
}
@Bean
@Qualifier("legacy")
public EventResolver legacyEventResolver() {
return new LegacyEventResolver(new MongoEventStore(databasedReadMongo()), idSettingOrganisationStore());
}
@Bean
@Qualifier("legacy")
public ContentListerResourceListerAdapter legacyContentLister() {
DatabasedMongo mongoDb = databasedReadMongo();
LegacyContentLister contentLister = new LegacyLookupResolvingContentLister(
new MongoLookupEntryStore(
mongoDb.collection(MONGO_COLLECTION_LOOKUP),
persistenceAuditLog,
ReadPreference.secondary()
),
new MongoContentResolver(mongoDb, legacyEquivalenceStore())
);
return new ContentListerResourceListerAdapter(
contentLister,
legacyContentTransformer()
);
}
@Bean
@Qualifier("legacy")
public LegacyContentTransformer legacyContentTransformer() {
return new LegacyContentTransformer(
channelStore(),
legacySegmentMigrator(),
new PaTagMap(
legacyTopicStore(),
new MongoSequentialIdGenerator(databasedWriteMongo(),
MONGO_COLLECTION_TOPICS
)));
}
@Bean
@Qualifier("legacy")
public LegacyTopicLister legacyTopicLister() {
return new LegacyTopicLister(legacyTopicStore());
}
@Bean
@Qualifier("legacy")
public MongoTopicStore legacyTopicStore() {
return new MongoTopicStore(databasedReadMongo(), persistenceAuditLog);
}
// disable Bean as this breaks API spring construction
public LegacyTopicResolver legacyTopicResolver() {
return new LegacyTopicResolver(legacyTopicStore(), legacyTopicStore());
}
@Bean
@Qualifier("legacy")
public OrganisationResolver legacyOrganisationResolver() {
TransitiveLookupWriter lookupWriter = TransitiveLookupWriter.generatedTransitiveLookupWriter(
legacyEquivalenceStore());
MongoOrganisationStore store = new MongoOrganisationStore(databasedReadMongo(),
lookupWriter,
legacyEquivalenceStore(),
persistenceAuditLog);
LegacyOrganisationTransformer transformer = new LegacyOrganisationTransformer();
return new LegacyOrganisationResolver(store, transformer);
}
@Bean
@Qualifier("legacy")
public ScheduleResolver legacyScheduleStore() {
DatabasedMongo db = databasedReadMongo();
KnownTypeContentResolver contentResolver = new MongoContentResolver(
db,
legacyEquivalenceStore()
);
LookupResolvingContentResolver resolver = new LookupResolvingContentResolver(
contentResolver,
legacyEquivalenceStore()
);
EquivalentContentResolver equivalentContentResolver = new DefaultEquivalentContentResolver(
contentResolver,
legacyEquivalenceStore()
);
MessageSender<ScheduleUpdateMessage> sender = MessageSenders.noopSender();
return new LegacyScheduleResolver(
new MongoScheduleStore(
db,
channelStore(),
resolver,
equivalentContentResolver,
sender
),
legacyContentTransformer()
);
}
}
|
package edu.umd.cs.findbugs;
public class FilterBugReporter extends DelegatingBugReporter {
private static final boolean DEBUG = Boolean.getBoolean("filter.debug");
private Matcher filter;
private boolean include;
public FilterBugReporter(BugReporter realBugReporter, Matcher filter, boolean include) {
super(realBugReporter);
this.filter = filter;
this.include = include;
}
public void reportBug(BugInstance bugInstance) {
if (DEBUG) System.out.print("Match ==> ");
boolean match = filter.match(bugInstance);
if (DEBUG) System.out.println(match ? "YES" : "NO");
if ((include && match) || (!include && !match))
getRealBugReporter().reportBug(bugInstance);
}
}
// vim:ts=4
|
package edu.umd.cs.findbugs;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Iterator;
/**
* Base class for BugReporters which provides convenient formatting and
* reporting of warnings and analysis errors.
*
* <p>
* "TextUIBugReporter" is a bit of a misnomer, since this class is useful in
* GUIs, too.
* </p>
*
* @author David Hovemeyer
*/
public abstract class TextUIBugReporter extends AbstractBugReporter {
private boolean reportStackTrace;
private boolean useLongBugCodes = false;
private boolean showRank = false;
private boolean reportHistory = false;
private boolean reportUserDesignations = false;
private boolean applySuppressions = false;
static final String OTHER_CATEGORY_ABBREV = "X";
protected PrintWriter outputStream = new PrintWriter(System.out,true);
public TextUIBugReporter() {
reportStackTrace = true;
}
/**
* Set the PrintStream to write bug output to.
*
* @param outputStream
* the PrintStream to write bug output to
*/
public void setOutputStream(PrintStream outputStream) {
this.outputStream = new PrintWriter(outputStream);
}
public void setWriter(PrintWriter writer) {
this.outputStream = writer;
}
/**
* Set whether or not stack traces should be reported in error output.
*
* @param reportStackTrace
* true if stack traces should be reported, false if not
*/
public void setReportStackTrace(boolean reportStackTrace) {
this.reportStackTrace = reportStackTrace;
}
/**
* Print bug in one-line format.
*
* @param bugInstance
* the bug to print
*/
protected void printBug(BugInstance bugInstance) {
if (showRank) {
int rank = BugRanker.findRank(bugInstance);
outputStream.printf("%2d ", rank);
}
switch (bugInstance.getPriority()) {
case Priorities.EXP_PRIORITY:
outputStream.print("E ");
break;
case Priorities.LOW_PRIORITY:
outputStream.print("L ");
break;
case Priorities.NORMAL_PRIORITY:
outputStream.print("M ");
break;
case Priorities.HIGH_PRIORITY:
outputStream.print("H ");
break;
}
BugPattern pattern = bugInstance.getBugPattern();
if (pattern != null) {
String categoryAbbrev = null;
BugCategory bcat = DetectorFactoryCollection.instance().getBugCategory(pattern.getCategory());
if (bcat != null)
categoryAbbrev = bcat.getAbbrev();
if (categoryAbbrev == null)
categoryAbbrev = OTHER_CATEGORY_ABBREV;
outputStream.print(categoryAbbrev);
outputStream.print(" ");
}
if (useLongBugCodes) {
outputStream.print(bugInstance.getType());
outputStream.print(" ");
}
if (reportUserDesignations) {
outputStream.print(bugInstance.getUserDesignationKey());
outputStream.print(" ");
}
if (reportHistory) {
long first = bugInstance.getFirstVersion();
long last = bugInstance.getLastVersion();
outputStream.print(first);
outputStream.print(" ");
outputStream.print(last);
outputStream.print(" ");
}
SourceLineAnnotation line = bugInstance.getPrimarySourceLineAnnotation();
if (line == null)
outputStream.println(bugInstance.getMessage().replace('\n', ' '));
else
outputStream.println(bugInstance.getMessage().replace('\n', ' ') + " " + line.toString());
}
private boolean analysisErrors;
private boolean missingClasses;
@Override
public void reportQueuedErrors() {
analysisErrors = missingClasses = false;
super.reportQueuedErrors();
}
@Override
public void reportAnalysisError(AnalysisError error) {
if (!analysisErrors) {
emitLine("The following errors occurred during analysis:");
analysisErrors = true;
}
emitLine("\t" + error.getMessage());
if (error.getExceptionMessage() != null) {
emitLine("\t\t" + error.getExceptionMessage());
if (reportStackTrace) {
String[] stackTrace = error.getStackTrace();
if (stackTrace != null) {
for (String aStackTrace : stackTrace) {
emitLine("\t\t\tAt " + aStackTrace);
}
}
}
}
}
@Override
public void reportMissingClass(String message) {
if (!missingClasses) {
emitLine("The following classes needed for analysis were missing:");
missingClasses = true;
}
emitLine("\t" + message);
}
/**
* Emit one line of the error message report. By default, error messages are
* printed to System.err. Subclasses may override.
*
* @param line
* one line of the error report
*/
protected void emitLine(String line) {
line = line.replaceAll("\t", " ");
System.err.println(line);
}
public boolean getUseLongBugCodes() {
return useLongBugCodes;
}
public void setReportHistory(boolean reportHistory) {
this.reportHistory = reportHistory;
}
public void setUseLongBugCodes(boolean useLongBugCodes) {
this.useLongBugCodes = useLongBugCodes;
}
public void setShowRank(boolean showRank) {
this.showRank = showRank;
}
public void setApplySuppressions(boolean applySuppressions) {
this.applySuppressions = applySuppressions;
}
public void setReportUserDesignations(boolean reportUserDesignations) {
this.reportUserDesignations = reportUserDesignations;
}
/*
* (non-Javadoc)
*
* @see edu.umd.cs.findbugs.BugReporter#getRealBugReporter()
*/
public BugReporter getRealBugReporter() {
return this;
}
/**
* For debugging: check a BugInstance to make sure it is valid.
*
* @param bugInstance
* the BugInstance to check
*/
protected void checkBugInstance(BugInstance bugInstance) {
for (Iterator<BugAnnotation> i = bugInstance.annotationIterator(); i.hasNext();) {
BugAnnotation bugAnnotation = i.next();
if (bugAnnotation instanceof PackageMemberAnnotation) {
PackageMemberAnnotation pkgMember = (PackageMemberAnnotation) bugAnnotation;
if (pkgMember.getSourceLines() == null) {
throw new IllegalStateException("Package member " + pkgMember + " reported without source lines!");
}
}
}
}
public boolean isApplySuppressions() {
return applySuppressions;
}
}
// vim:ts=4
|
package edu.umd.cs.findbugs.detect;
import java.util.Set;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.ConstantNameAndType;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.ClassAnnotation;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.MethodAnnotation;
import edu.umd.cs.findbugs.Priorities;
import edu.umd.cs.findbugs.StatelessDetector;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.PruneUnconditionalExceptionThrowerEdges;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.ch.Subtypes2;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
public class CloneIdiom extends DismantleBytecode implements Detector, StatelessDetector {
private ClassDescriptor cloneDescriptor = DescriptorFactory.createClassDescriptor(java.lang.Cloneable.class);
boolean isCloneable, hasCloneMethod;
boolean cloneIsDeprecated;
MethodAnnotation cloneMethodAnnotation;
boolean referencesCloneMethod;
boolean invokesSuperClone;
boolean isFinal;
boolean cloneOnlyThrowsException;
boolean check;
// boolean throwsExceptions;
boolean implementsCloneableDirectly;
private BugReporter bugReporter;
public CloneIdiom(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
public void visitClassContext(ClassContext classContext) {
classContext.getJavaClass().accept(this);
}
@Override
public void visit(Code obj) {
if (getMethodName().equals("clone") && getMethodSig().startsWith("()"))
super.visit(obj);
}
@Override
public void sawOpcode(int seen) {
if (seen == INVOKESPECIAL && getNameConstantOperand().equals("clone") && getSigConstantOperand().startsWith("()")) {
/*
* System.out.println("Saw call to " + nameConstant + ":" +
* sigConstant + " in " + betterMethodName);
*/
invokesSuperClone = true;
}
}
@Override
public void visit(JavaClass obj) {
implementsCloneableDirectly = false;
invokesSuperClone = false;
cloneOnlyThrowsException = false;
isCloneable = false;
check = false;
isFinal = obj.isFinal();
if (obj.isInterface())
return;
if (obj.isAbstract())
return;
// Does this class directly implement Cloneable?
String[] interface_names = obj.getInterfaceNames();
for (String interface_name : interface_names) {
if (interface_name.equals("java.lang.Cloneable")) {
implementsCloneableDirectly = true;
isCloneable = true;
break;
}
}
Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2();
try {
if (subtypes2.isSubtype(getClassDescriptor(), cloneDescriptor))
isCloneable = true;
if (subtypes2.isSubtype(DescriptorFactory.createClassDescriptorFromDottedClassName(obj.getSuperclassName()),
cloneDescriptor))
implementsCloneableDirectly = false;
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
hasCloneMethod = false;
referencesCloneMethod = false;
check = true;
super.visit(obj);
}
@Override
public void visitAfter(JavaClass obj) {
if (!check)
return;
if (cloneOnlyThrowsException)
return;
if (implementsCloneableDirectly && !hasCloneMethod) {
if (!referencesCloneMethod)
bugReporter.reportBug(new BugInstance(this, "CN_IDIOM", NORMAL_PRIORITY).addClass(this));
}
if (hasCloneMethod && isCloneable && !invokesSuperClone && !isFinal && obj.isPublic()) {
int priority = LOW_PRIORITY;
if (obj.isPublic() || obj.isProtected())
priority = NORMAL_PRIORITY;
try {
Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2();
Set<ClassDescriptor> directSubtypes = subtypes2.getDirectSubtypes(getClassDescriptor());
if (!directSubtypes.isEmpty())
priority
BugInstance bug = new BugInstance(this, "CN_IDIOM_NO_SUPER_CALL", priority).addClass(this).addMethod(
cloneMethodAnnotation);
for (ClassDescriptor d : directSubtypes)
bug.addClass(d).describe(ClassAnnotation.SUBCLASS_ROLE);
bugReporter.reportBug(bug);
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
} else if (hasCloneMethod && !isCloneable && !cloneOnlyThrowsException && !cloneIsDeprecated && !obj.isAbstract()) {
int priority = Priorities.NORMAL_PRIORITY;
if (referencesCloneMethod)
priority
bugReporter.reportBug(new BugInstance(this, "CN_IMPLEMENTS_CLONE_BUT_NOT_CLONEABLE", priority).addClass(this)
.addMethod(cloneMethodAnnotation));
}
}
@Override
public void visit(ConstantNameAndType obj) {
String methodName = obj.getName(getConstantPool());
String methodSig = obj.getSignature(getConstantPool());
if (!methodName.equals("clone"))
return;
if (!methodSig.startsWith("()"))
return;
referencesCloneMethod = true;
}
@Override
public void visit(Method obj) {
if (obj.isAbstract() || obj.isSynthetic())
return;
if (!obj.isPublic())
return;
if (!getMethodName().equals("clone"))
return;
if (!getMethodSig().startsWith("()"))
return;
hasCloneMethod = true;
cloneIsDeprecated = getXMethod().isDeprecated();
cloneMethodAnnotation = MethodAnnotation.fromVisitedMethod(this);
cloneOnlyThrowsException = PruneUnconditionalExceptionThrowerEdges.doesMethodUnconditionallyThrowException(XFactory
.createXMethod(this));
// ExceptionTable tbl = obj.getExceptionTable();
// throwsExceptions = tbl != null && tbl.getNumberOfExceptions() > 0;
}
/*
* (non-Javadoc)
*
* @see edu.umd.cs.findbugs.Detector#report()
*/
public void report() {
// do nothing
}
}
|
package edu.umd.cs.findbugs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
/**
* Starting from an Eclipse plugin, finds all required plugins
* (in an Eclipse installation) and recursively finds the classpath
* required to compile the original plugin. Different Eclipse
* releases will generally have different version numbers on the
* plugins they contain, which makes this task slightly difficult.
*
* @author David Hovemeyer
*/
public class EclipseClasspath {
public static class EclipseClasspathException extends Exception {
public EclipseClasspathException(String msg) {
super(msg);
}
}
/**
* A customized Reader for Eclipse plugin descriptor files.
* The problem is that Eclipse uses invalid XML in the form of
* directives like
* <pre>
* <?eclipse version="3.0"?>
* </pre>
* outside of the root element. This Reader class
* filters out this crap.
*/
private static class EclipseXMLReader extends Reader {
private BufferedReader reader;
private LinkedList<String> lineList;
public EclipseXMLReader(Reader reader) {
this.reader = new BufferedReader(reader);
this.lineList = new LinkedList<String>();
}
public int read(char[] cbuf, int off, int len) throws IOException {
if (!fill())
return -1;
String line = lineList.getFirst();
if (len > line.length())
len = line.length();
for (int i = 0; i < len; ++i)
cbuf[i+off] = line.charAt(i);
if (len == line.length())
lineList.removeFirst();
else
lineList.set(0, line.substring(len));
return len;
}
public void close() throws IOException {
reader.close();
}
private boolean fill() throws IOException {
if (!lineList.isEmpty())
return true;
String line;
do {
line = reader.readLine();
if (line == null)
return false;
} while (isIllegal(line));
lineList.add(line+"\n");
return true;
}
private boolean isIllegal(String line) {
return line.startsWith("<?eclipse");
}
}
private static class Plugin {
private Document document;
private String pluginId;
private List<String> requiredPluginIdList;
public Plugin(Document document) throws DocumentException, EclipseClasspathException {
this.document = document;
// Get the plugin id
Node plugin = document.selectSingleNode("/plugin");
if (plugin == null)
throw new EclipseClasspathException("No plugin node in plugin descriptor");
pluginId = plugin.valueOf("@id");
if (pluginId.equals(""))
throw new EclipseClasspathException("Cannot determine plugin id");
System.out.println("Plugin id is " + pluginId);
// Extract required plugins
requiredPluginIdList = new LinkedList<String>();
List requiredPluginNodeList = document.selectNodes("/plugin/requires/import");
for (Iterator i = requiredPluginNodeList.iterator(); i.hasNext(); ) {
Node node = (Node) i.next();
String requiredPluginId = node.valueOf("@plugin");
if (requiredPluginId.equals(""))
throw new EclipseClasspathException("Import has no plugin id");
System.out.println(" Required plugin ==> " + requiredPluginId);
requiredPluginIdList.add(requiredPluginId);
}
}
public String getId() {
return pluginId;
}
public Iterator<String> requiredPluginIdIterator() {
return requiredPluginIdList.iterator();
}
}
private static final Pattern pluginDirPattern = Pattern.compile("^(\\w+(\\.\\w+)*)_(\\w+(\\.\\w+)*)$");
private static final int PLUGIN_ID_GROUP = 1;
private String eclipseDir;
private String pluginFile;
private Map<String, File> pluginDirectoryMap;
public EclipseClasspath(String eclipseDir, String pluginFile) {
this.eclipseDir = eclipseDir;
this.pluginFile = pluginFile;
this.pluginDirectoryMap = new HashMap<String, File>();
}
public void addRequiredPlugin(String pluginId, String pluginDir) {
pluginDirectoryMap.put(pluginId, new File(pluginDir));
}
public EclipseClasspath execute() throws EclipseClasspathException, DocumentException, IOException {
// Build plugin directory map
File pluginDir = new File(eclipseDir, "plugins");
File[] dirList = pluginDir.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
if (dirList == null)
throw new EclipseClasspathException("Could not list plugins in directory " + pluginDir);
for (int i = 0; i < dirList.length; ++i) {
String pluginId = getPluginId(dirList[i].getName());
if (pluginId != null) {
//System.out.println(pluginId + " ==> " + dirList[i]);
pluginDirectoryMap.put(pluginId, dirList[i]);
}
}
Map<String, Plugin> requiredPluginMap = new HashMap<String, Plugin>();
LinkedList<String> workList = new LinkedList<String>();
workList.add(pluginFile);
while (!workList.isEmpty()) {
String descriptor = workList.removeFirst();
// Read the plugin file
SAXReader reader = new SAXReader();
Document doc = reader.read(new EclipseXMLReader(new FileReader(descriptor)));
// Add to the map
Plugin plugin = new Plugin(doc);
requiredPluginMap.put(plugin.getId(), plugin);
// Add unresolved required plugins to the worklist
for (Iterator<String> i = plugin.requiredPluginIdIterator(); i.hasNext(); ) {
String requiredPluginId = i.next();
if (requiredPluginMap.get(requiredPluginId) == null) {
// Find the plugin in the Eclipse directory
File requiredPluginDir = pluginDirectoryMap.get(requiredPluginId);
if (requiredPluginDir == null)
throw new EclipseClasspathException("Unable to find plugin " + requiredPluginId);
workList.add(new File(requiredPluginDir, "plugin.xml").getPath());
}
}
}
System.out.println("Found " + requiredPluginMap.size() + " required plugins");
return this;
}
/**
* Get the plugin id for given directory name.
* Returns null if the directory name does not seem to
* be a plugin.
*/
private String getPluginId(String dirName) {
Matcher m = pluginDirPattern.matcher(dirName);
return m.matches() ? m.group(PLUGIN_ID_GROUP) : null;
}
public static void main(String[] argv) throws Exception {
if (argv.length < 2 || (argv.length % 2 != 0)) {
System.err.println("Usage: " + EclipseClasspath.class.getName() +
" <eclipse dir> <plugin file> [<required plugin id> <required plugin dir> ...]");
System.exit(1);
}
EclipseClasspath ec = new EclipseClasspath(argv[0], argv[1]);
for (int i = 2; i < argv.length; i += 2) {
ec.addRequiredPlugin(argv[i], argv[i+1]);
}
ec.execute();
}
}
// vim:ts=4
|
package play.test;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.function.Function;
import akka.stream.Materializer;
import akka.util.ByteString;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import play.Application;
import play.Play;
import play.api.test.Helpers$;
import play.core.j.JavaContextComponents;
import play.core.j.JavaHandler;
import play.core.j.JavaHandlerComponents;
import play.core.j.JavaHelpers$;
import play.http.HttpEntity;
import play.inject.guice.GuiceApplicationBuilder;
import play.libs.Scala;
import play.mvc.Call;
import play.mvc.Http;
import play.mvc.Result;
import play.routing.Router;
import play.twirl.api.Content;
import scala.compat.java8.FutureConverters;
import scala.compat.java8.OptionConverters;
import static play.libs.Scala.asScala;
import static play.mvc.Http.Context;
import static play.mvc.Http.Request;
import static play.mvc.Http.RequestBuilder;
/**
* Helper functions to run tests.
*/
public class Helpers implements play.mvc.Http.Status, play.mvc.Http.HeaderNames {
/**
* Default Timeout (milliseconds) for fake requests issued by these Helpers.
* This value is determined from System property <b>test.timeout</b>.
* The default value is <b>30000</b> (30 seconds).
*/
public static final long DEFAULT_TIMEOUT = Long.getLong("test.timeout", 30000L);
public static String GET = "GET";
public static String POST = "POST";
public static String PUT = "PUT";
public static String DELETE = "DELETE";
public static String HEAD = "HEAD";
public static Class<? extends WebDriver> HTMLUNIT = HtmlUnitDriver.class;
public static Class<? extends WebDriver> FIREFOX = FirefoxDriver.class;
@SuppressWarnings(value = "unchecked")
private static Result invokeHandler(play.api.Application app, play.api.mvc.Handler handler, Request requestBuilder, long timeout) {
if (handler instanceof play.api.mvc.Action) {
play.api.mvc.Action action = (play.api.mvc.Action) handler;
return wrapScalaResult(action.apply(requestBuilder._underlyingRequest()), timeout);
} else if (handler instanceof JavaHandler) {
final play.api.inject.Injector injector = app.injector();
final JavaHandlerComponents handlerComponents = injector.instanceOf(JavaHandlerComponents.class);
return invokeHandler(
app,
((JavaHandler) handler).withComponents(handlerComponents),
requestBuilder, timeout
);
} else {
throw new RuntimeException("This is not a JavaAction and can't be invoked this way.");
}
}
private static Result wrapScalaResult(scala.concurrent.Future<play.api.mvc.Result> result, long timeout) {
if (result == null) {
return null;
} else {
try {
final play.api.mvc.Result scalaResult = FutureConverters.toJava(result).toCompletableFuture().get(timeout, TimeUnit.MILLISECONDS);
return scalaResult.asJava();
} catch (ExecutionException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
} else {
throw new RuntimeException(e.getCause());
}
} catch (InterruptedException | TimeoutException e) {
throw new RuntimeException(e);
}
}
}
/**
* Calls a Callable which invokes a Controller or some other method with a Context.
*
* @param requestBuilder the request builder to invoke in this context.
* @param contextComponents the context components to run.
* @param callable the callable block to run.
* @param <V> the return type.
* @return the value from {@code callable}.
*/
public static <V> V invokeWithContext(RequestBuilder requestBuilder, JavaContextComponents contextComponents, Callable<V> callable) {
try {
Context.current.set(new Context(requestBuilder, contextComponents));
return callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
Context.current.remove();
}
}
/**
* Builds a new "GET /" fake request.
* @return the request builder.
*/
public static RequestBuilder fakeRequest() {
return fakeRequest("GET", "/");
}
/**
* Builds a new fake request.
* @param method the request method.
* @param uri the relative URL.
* @return the request builder.
*/
public static RequestBuilder fakeRequest(String method, String uri) {
return new RequestBuilder().host("localhost").method(method).uri(uri);
}
/**
* Builds a new fake request corresponding to a given route call.
* @param call the route call.
* @return the request builder.
*/
public static RequestBuilder fakeRequest(Call call) {
return fakeRequest(call.method(), call.url());
}
/**
* Builds a new Http.Context from a new request
* @return a new Http.Context using the default request
*/
public static Http.Context httpContext() {
return httpContext(new Http.RequestBuilder().build());
}
/**
* Builds a new Http.Context for a specific request
* @param request the Request you want to use for this Context
* @return a new Http.Context for this request
*/
public static Http.Context httpContext(Http.Request request) {
return new Http.Context(request, contextComponents());
}
/**
* Creates a new JavaContextComponents using Configuration.reference and Enviroment.simple as defaults
* @return the newly created JavaContextComponents
*/
public static JavaContextComponents contextComponents() {
return JavaHelpers$.MODULE$.createContextComponents();
}
/**
* Builds a new fake application, using GuiceApplicationBuilder.
*
* @return an application from the current path with no additional configuration.
*/
public static Application fakeApplication() {
return new GuiceApplicationBuilder().build();
}
/**
* Constructs a in-memory (h2) database configuration to add to a fake application.
*
* @return a map of String containing database config info.
*/
public static Map<String, String> inMemoryDatabase() {
return inMemoryDatabase("default");
}
/**
* Constructs a in-memory (h2) database configuration to add to a fake application.
*
* @param name the database name.
* @return a map of String containing database config info.
*/
public static Map<String, String> inMemoryDatabase(String name) {
return inMemoryDatabase(name, Collections.<String, String>emptyMap());
}
/**
* Constructs a in-memory (h2) database configuration to add to a fake application.
*
* @param name the database name.
* @param options the database options.
* @return a map of String containing database config info.
*/
public static Map<String, String> inMemoryDatabase(String name, Map<String, String> options) {
return Scala.asJava(play.api.test.Helpers.inMemoryDatabase(name, Scala.asScala(options)));
}
/**
* Build a new fake application. Uses GuiceApplicationBuilder.
*
* @param additionalConfiguration map containing config info for the app.
* @return an application from the current path with additional configuration.
*/
public static Application fakeApplication(Map<String, ? extends Object> additionalConfiguration) {
//noinspection unchecked
Map<String, Object> conf = (Map<String, Object>) additionalConfiguration;
return new GuiceApplicationBuilder().configure(conf).build();
}
/**
* Extracts the content as a {@link akka.util.ByteString}.
* <p>
* This method is only capable of extracting the content of results with strict entities. To extract the content of
* results with streamed entities, use {@link Helpers#contentAsBytes(Result, Materializer)}.
*
* @param result The result to extract the content from.
* @return The content of the result as a ByteString.
* @throws UnsupportedOperationException if the result does not have a strict entity.
*/
public static ByteString contentAsBytes(Result result) {
if (result.body() instanceof HttpEntity.Strict) {
return ((HttpEntity.Strict) result.body()).data();
} else {
throw new UnsupportedOperationException("Tried to extract body from a non strict HTTP entity without a materializer, use the version of this method that accepts a materializer instead");
}
}
/**
* Extracts the content as a {@link akka.util.ByteString}.
*
* @param result The result to extract the content from.
* @param mat The materializer to use to extract the body from the result stream.
* @return The content of the result as a ByteString.
*/
public static ByteString contentAsBytes(Result result, Materializer mat) {
return contentAsBytes(result, mat, DEFAULT_TIMEOUT);
}
/**
* Extracts the content as a {@link akka.util.ByteString}.
*
* @param result The result to extract the content from.
* @param mat The materializer to use to extract the body from the result stream.
* @param timeout The amount of time, in milliseconds, to wait for the body to be produced.
* @return The content of the result as a ByteString.
*/
public static ByteString contentAsBytes(Result result, Materializer mat, long timeout) {
try {
return result.body().consumeData(mat).thenApply(Function.identity()).toCompletableFuture().get(timeout, TimeUnit.MILLISECONDS);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Extracts the content as bytes.
*
* @param content the content to be turned into bytes.
* @return the body of the content as a byte string.
*/
public static ByteString contentAsBytes(Content content) {
return ByteString.fromString(content.body());
}
/**
* Extracts the content as a String.
*
* @param content the content.
* @return the body of the content as a String.
*/
public static String contentAsString(Content content) {
return content.body();
}
/**
* Extracts the content as a String.
* <p>
* This method is only capable of extracting the content of results with strict entities. To extract the content of
* results with streamed entities, use {@link Helpers#contentAsString(Result, Materializer)}.
*
* @param result The result to extract the content from.
* @return The content of the result as a String.
* @throws UnsupportedOperationException if the result does not have a strict entity.
*/
public static String contentAsString(Result result) {
return contentAsBytes(result)
.decodeString(result.charset().orElse("utf-8"));
}
/**
* Extracts the content as a String.
*
* @param result The result to extract the content from.
* @param mat The materializer to use to extract the body from the result stream.
* @return The content of the result as a String.
*/
public static String contentAsString(Result result, Materializer mat) {
return contentAsBytes(result, mat, DEFAULT_TIMEOUT)
.decodeString(result.charset().orElse("utf-8"));
}
/**
* Extracts the content as a String.
*
* @param result The result to extract the content from.
* @param mat The materializer to use to extract the body from the result stream.
* @param timeout The amount of time, in milliseconds, to wait for the body to be produced.
* @return The content of the result as a String.
*/
public static String contentAsString(Result result, Materializer mat, long timeout) {
return contentAsBytes(result, mat, timeout)
.decodeString(result.charset().orElse("utf-8"));
}
/**
* @param requestBuilder the request builder
* @param timeout the timeout
* @deprecated as of 2.6.0. Use {@link Helpers#routeAndCall(Application, RequestBuilder, long)}.
* @see GuiceApplicationBuilder
* @return the result
*/
@Deprecated
@SuppressWarnings(value = "unchecked")
public static Result routeAndCall(RequestBuilder requestBuilder, long timeout) {
Application app = Play.application();
return routeAndCall(app, requestBuilder, timeout);
}
/**
* Route and call the request, respecting the given timeout.
*
* @param app The application used while routing and executing the request
* @param requestBuilder The request builder
* @param timeout The amount of time, in milliseconds, to wait for the body to be produced.
* @return the result
*/
public static Result routeAndCall(Application app, RequestBuilder requestBuilder, long timeout) {
try {
return routeAndCall(app, (Class<? extends Router>) RequestBuilder.class.getClassLoader().loadClass("Routes"), requestBuilder, timeout);
} catch (RuntimeException e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
/**
* @param router the router
* @param requestBuilder the request builder
* @param timeout the timeout
* @deprecated as of 2.6.0. Use {@link Helpers#routeAndCall(Application, Class, RequestBuilder, long)}.
* @see GuiceApplicationBuilder
* @return the result
*/
@Deprecated
public static Result routeAndCall(Class<? extends Router> router, RequestBuilder requestBuilder, long timeout) {
Application app = Play.application();
return routeAndCall(app, router, requestBuilder, timeout);
}
/**
* Route and call the request, respecting the given timeout.
*
* @param app The application used while routing and executing the request
* @param router The router type
* @param requestBuilder The request builder
* @param timeout The amount of time, in milliseconds, to wait for the body to be produced.
* @return the result
*/
public static Result routeAndCall(Application app, Class<? extends Router> router, RequestBuilder requestBuilder, long timeout) {
try {
Request request = requestBuilder.build();
Router routes = (Router) router.getClassLoader().loadClass(router.getName() + "$").getDeclaredField("MODULE$").get(null);
return routes.route(request).map(handler ->
invokeHandler(app.getWrappedApplication(), handler, request, timeout)
).orElse(null);
} catch (RuntimeException e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
/**
* @param router the router
* @param requestBuilder the request builder
* @deprecated as of 2.6.0. Use {@link Helpers#routeAndCall(Application, Router, RequestBuilder)}.
* @see GuiceApplicationBuilder
* @return the result
*/
@Deprecated
public static Result routeAndCall(Router router, RequestBuilder requestBuilder) {
Application app = Play.application();
return routeAndCall(app, router, requestBuilder);
}
/**
* Route and call the request.
*
* @param app The application used while routing and executing the request
* @param router The router
* @param requestBuilder The request builder
* @return the result
*/
public static Result routeAndCall(Application app, Router router, RequestBuilder requestBuilder) {
return routeAndCall(app, router, requestBuilder, DEFAULT_TIMEOUT);
}
/**
* @param router the router
* @param requestBuilder the request builder
* @param timeout the timeout
* @deprecated as of 2.6.0. Use {@link Helpers#routeAndCall(Application, RequestBuilder, long)}.
* @see GuiceApplicationBuilder
* @return the result
*/
@Deprecated
public static Result routeAndCall(Router router, RequestBuilder requestBuilder, long timeout) {
Application application = Play.application();
return routeAndCall(application, router, requestBuilder, timeout);
}
/**
* Route and call the request, respecting the given timeout.
*
* @param app The application used while routing and executing the request
* @param router The router
* @param requestBuilder The request builder
* @param timeout The amount of time, in milliseconds, to wait for the body to be produced.
* @return the result
*/
public static Result routeAndCall(Application app, Router router, RequestBuilder requestBuilder, long timeout) {
try {
Request request = requestBuilder.build();
return router.route(request).map(handler ->
invokeHandler(app.getWrappedApplication(), handler, request, timeout)
).orElse(null);
} catch (RuntimeException e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
/**
*
* @param call the call to route
* @deprecated as of 2.6.0. Use {@link Helpers#route(Application, Call)}.
* @see GuiceApplicationBuilder
* @return the result
*/
@Deprecated
public static Result route(Call call) {
return route(fakeRequest(call));
}
public static Result route(Application app, Call call) {
return route(app, fakeRequest(call));
}
/**
* @param call the call to route
* @param timeout the time out
* @deprecated as of 2.6.0. Use {@link Helpers#route(Application, Call, long)}.
* @see GuiceApplicationBuilder
* @return the result
*/
@Deprecated
public static Result route(Call call, long timeout) {
return route(fakeRequest(call), timeout);
}
public static Result route(Application app, Call call, long timeout) {
return route(app, fakeRequest(call), timeout);
}
/**
* @param requestBuilder the request builder the request builder
* @deprecated as of 2.6.0. Use {@link Helpers#route(Application, RequestBuilder)}.
* @see GuiceApplicationBuilder
* @return the result
*/
@Deprecated
public static Result route(RequestBuilder requestBuilder) {
return route(requestBuilder, DEFAULT_TIMEOUT);
}
/**
* Route a request.
*
* @param app The application used while routing and executing the request
* @param requestBuilder the request builder
* @return the result.
*/
public static Result route(Application app, RequestBuilder requestBuilder) {
return route(app, requestBuilder, DEFAULT_TIMEOUT);
}
/**
* @param requestBuilder the request builder
* @param timeout the timeout
* @deprecated as of 2.6.0. Use {@link Helpers#route(Application, RequestBuilder, long)}.
* @see GuiceApplicationBuilder
* @return the result
*/
@Deprecated
public static Result route(RequestBuilder requestBuilder, long timeout) {
Application application = Play.application();
return route(application, requestBuilder, timeout);
}
/**
* Route the request considering the given timeout.
*
* @param app The application used while routing and executing the request
* @param requestBuilder the request builder
* @param timeout the amount of time, in milliseconds, to wait for the body to be produced.
* @return the result
*/
@SuppressWarnings("unchecked")
public static Result route(Application app, RequestBuilder requestBuilder, long timeout) {
final scala.Option<scala.concurrent.Future<play.api.mvc.Result>> opt = play.api.test.Helpers.jRoute(
app.getWrappedApplication(),
requestBuilder.build()._underlyingRequest(),
requestBuilder.body()
);
return wrapScalaResult(Scala.orNull(opt), timeout);
}
/**
* Starts a new application.
*
* @param application the application to start.
*/
public static void start(Application application) {
play.api.Play.start(application.getWrappedApplication());
}
/**
* Stops an application.
*
* @param application the application to stop.
*/
public static void stop(Application application) {
play.api.Play.stop(application.getWrappedApplication());
}
/**
* Executes a block of code in a running application.
*
* @param application the application context.
* @param block the block to run after the Play app is started.
*/
public static void running(Application application, final Runnable block) {
Helpers$.MODULE$.running(application.getWrappedApplication(), asScala(() -> { block.run(); return null; }));
}
/**
* Creates a new Test server listening on port defined by configuration setting "testserver.port" (defaults to 19001).
*
* @return the test server.
*/
public static TestServer testServer() {
return testServer(play.api.test.Helpers.testServerPort());
}
/**
* Creates a new Test server listening on port defined by configuration setting "testserver.port" (defaults to 19001) and using the given Application.
*
* @param app the application.
* @return the test server.
*/
public static TestServer testServer(Application app) {
return testServer(play.api.test.Helpers.testServerPort(), app);
}
/**
* Creates a new Test server.
*
* @param port the port to run the server on.
* @return the test server.
*/
public static TestServer testServer(int port) {
return new TestServer(port, fakeApplication());
}
/**
* Creates a new Test server.
*
*
* @param port the port to run the server on.
* @param app the Play application.
* @return the test server.
*/
public static TestServer testServer(int port, Application app) {
return new TestServer(port, app);
}
/**
* Starts a Test server.
* @param server the test server to start.
*/
public static void start(TestServer server) {
server.start();
}
/**
* Stops a Test server.
* @param server the test server to stop.a
*/
public static void stop(TestServer server) {
server.stop();
}
/**
* Executes a block of code in a running server.
* @param server the server to start.
* @param block the block of code to run after the server starts.
*/
public static void running(TestServer server, final Runnable block) {
Helpers$.MODULE$.running(server, asScala(() -> { block.run(); return null; }));
}
/**
* Executes a block of code in a running server, with a test browser.
*
* @param server the test server.
* @param webDriver the web driver class.
* @param block the block of code to execute.
*/
public static void running(TestServer server, Class<? extends WebDriver> webDriver, final Consumer<TestBrowser> block) {
running(server, play.api.test.WebDriverFactory.apply(webDriver), block);
}
/**
* Executes a block of code in a running server, with a test browser.
*
* @param server the test server.
* @param webDriver the web driver instance.
* @param block the block of code to execute.
*/
public static void running(TestServer server, WebDriver webDriver, final Consumer<TestBrowser> block) {
Helpers$.MODULE$.runSynchronized(server.application(), asScala(() -> {
TestBrowser browser = null;
TestServer startedServer = null;
try {
start(server);
startedServer = server;
browser = testBrowser(webDriver, (Integer) OptionConverters.toJava(server.config().port()).get());
block.accept(browser);
} finally {
if (browser != null) {
browser.quit();
}
if (startedServer != null) {
stop(startedServer);
}
}
return null;
}));
}
/**
* Creates a Test Browser.
*
* @return the test browser.
*/
public static TestBrowser testBrowser() {
return testBrowser(HTMLUNIT);
}
/**
* Creates a Test Browser.
*
* @param port the local port.
* @return the test browser.
*/
public static TestBrowser testBrowser(int port) {
return testBrowser(HTMLUNIT, port);
}
/**
* Creates a Test Browser.
*
* @param webDriver the class of webdriver.
* @return the test browser.
*/
public static TestBrowser testBrowser(Class<? extends WebDriver> webDriver) {
return testBrowser(webDriver, Helpers$.MODULE$.testServerPort());
}
/**
* Creates a Test Browser.
*
* @param webDriver the class of webdriver.
* @param port the local port to test against.
* @return the test browser.
*/
public static TestBrowser testBrowser(Class<? extends WebDriver> webDriver, int port) {
try {
return new TestBrowser(webDriver, "http://localhost:" + port);
} catch (RuntimeException e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
public static TestBrowser testBrowser(WebDriver of, int port) {
return new TestBrowser(of, "http://localhost:" + port);
}
/**
* Creates a Test Browser.
*
* @param of the web driver to run the browser with.
* @return the test browser.
*/
public static TestBrowser testBrowser(WebDriver of) {
return testBrowser(of, Helpers$.MODULE$.testServerPort());
}
}
|
package net.fortuna.ical4j.model.component;
import java.util.Iterator;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.ComponentList;
import net.fortuna.ical4j.model.Date;
import net.fortuna.ical4j.model.DateList;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Dur;
import net.fortuna.ical4j.model.Parameter;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.PeriodList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.parameter.Value;
import net.fortuna.ical4j.model.property.Clazz;
import net.fortuna.ical4j.model.property.Created;
import net.fortuna.ical4j.model.property.Description;
import net.fortuna.ical4j.model.property.DtEnd;
import net.fortuna.ical4j.model.property.DtStamp;
import net.fortuna.ical4j.model.property.DtStart;
import net.fortuna.ical4j.model.property.Duration;
import net.fortuna.ical4j.model.property.ExDate;
import net.fortuna.ical4j.model.property.ExRule;
import net.fortuna.ical4j.model.property.Geo;
import net.fortuna.ical4j.model.property.LastModified;
import net.fortuna.ical4j.model.property.Location;
import net.fortuna.ical4j.model.property.Organizer;
import net.fortuna.ical4j.model.property.Priority;
import net.fortuna.ical4j.model.property.RDate;
import net.fortuna.ical4j.model.property.RRule;
import net.fortuna.ical4j.model.property.RecurrenceId;
import net.fortuna.ical4j.model.property.Sequence;
import net.fortuna.ical4j.model.property.Status;
import net.fortuna.ical4j.model.property.Summary;
import net.fortuna.ical4j.model.property.Transp;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Url;
import net.fortuna.ical4j.util.CompatibilityHints;
import net.fortuna.ical4j.util.Dates;
import net.fortuna.ical4j.util.PropertyValidator;
import net.fortuna.ical4j.util.Strings;
/**
* Defines an iCalendar VEVENT component.
*
* <pre>
* 4.6.1 Event Component
*
* Component Name: "VEVENT"
*
* Purpose: Provide a grouping of component properties that describe an
* event.
*
* Format Definition: A "VEVENT" calendar component is defined by the
* following notation:
*
* eventc = "BEGIN" ":" "VEVENT" CRLF
* eventprop *alarmc
* "END" ":" "VEVENT" CRLF
*
* eventprop = *(
*
* ; the following are optional,
* ; but MUST NOT occur more than once
*
* class / created / description / dtstart / geo /
* last-mod / location / organizer / priority /
* dtstamp / seq / status / summary / transp /
* uid / url / recurid /
*
* ; either 'dtend' or 'duration' may appear in
* ; a 'eventprop', but 'dtend' and 'duration'
* ; MUST NOT occur in the same 'eventprop'
*
* dtend / duration /
*
* ; the following are optional,
* ; and MAY occur more than once
*
* attach / attendee / categories / comment /
* contact / exdate / exrule / rstatus / related /
* resources / rdate / rrule / x-prop
*
* )
* </pre>
*
* Example 1 - Creating a new all-day event:
*
* <pre><code>
* java.util.Calendar cal = java.util.Calendar.getInstance();
* cal.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER);
* cal.set(java.util.Calendar.DAY_OF_MONTH, 25);
*
* VEvent christmas = new VEvent(cal.getTime(), "Christmas Day");
*
* // initialise as an all-day event..
* christmas.getProperties().getProperty(Property.DTSTART).getParameters().add(Value.DATE);
*
* // add timezone information..
* VTimeZone tz = VTimeZone.getDefault();
* TzId tzParam = new TzId(tz.getProperties().getProperty(Property.TZID).getValue());
* christmas.getProperties().getProperty(Property.DTSTART).getParameters().add(tzParam);
* </code></pre>
*
* Example 2 - Creating an event of one (1) hour duration:
*
* <pre><code>
* java.util.Calendar cal = java.util.Calendar.getInstance();
* // tomorrow..
* cal.add(java.util.Calendar.DAY_OF_MONTH, 1);
* cal.set(java.util.Calendar.HOUR_OF_DAY, 9);
* cal.set(java.util.Calendar.MINUTE, 30);
*
* VEvent meeting = new VEvent(cal.getTime(), 1000 * 60 * 60, "Progress Meeting");
*
* // add timezone information..
* VTimeZone tz = VTimeZone.getDefault();
* TzId tzParam = new TzId(tz.getProperties().getProperty(Property.TZID).getValue());
* meeting.getProperties().getProperty(Property.DTSTART).getParameters().add(tzParam);
* </code></pre>
*
* Example 3 - Retrieve a list of periods representing a recurring event in a
* specified range:
*
* <pre><code>
* Calendar weekday9AM = Calendar.getInstance();
* weekday9AM.set(2005, Calendar.MARCH, 7, 9, 0, 0);
* weekday9AM.set(Calendar.MILLISECOND, 0);
*
* Calendar weekday5PM = Calendar.getInstance();
* weekday5PM.set(2005, Calendar.MARCH, 7, 17, 0, 0);
* weekday5PM.set(Calendar.MILLISECOND, 0);
*
* // Do the recurrence until December 31st.
* Calendar untilCal = Calendar.getInstance();
* untilCal.set(2005, Calendar.DECEMBER, 31);
* untilCal.set(Calendar.MILLISECOND, 0);
*
* // 9:00AM to 5:00PM Rule
* Recur recur = new Recur(Recur.WEEKLY, untilCal.getTime());
* recur.getDayList().add(WeekDay.MO);
* recur.getDayList().add(WeekDay.TU);
* recur.getDayList().add(WeekDay.WE);
* recur.getDayList().add(WeekDay.TH);
* recur.getDayList().add(WeekDay.FR);
* recur.setInterval(3);
* recur.setWeekStartDay(WeekDay.MO.getDay());
* RRule rrule = new RRule(recur);
*
* Summary summary = new Summary("TEST EVENTS THAT HAPPEN 9-5 MON-FRI");
*
* weekdayNineToFiveEvents = new VEvent();
* weekdayNineToFiveEvents.getProperties().add(rrule);
* weekdayNineToFiveEvents.getProperties().add(summary);
* weekdayNineToFiveEvents.getProperties().add(
* new DtStart(weekday9AM.getTime()));
* weekdayNineToFiveEvents.getProperties().add(
* new DtEnd(weekday5PM.getTime()));
*
* // Test Start 04/01/2005, End One month later.
* // Query Calendar Start and End Dates.
* Calendar queryStartDate = Calendar.getInstance();
* queryStartDate.set(2005, Calendar.APRIL, 1, 14, 47, 0);
* queryStartDate.set(Calendar.MILLISECOND, 0);
* Calendar queryEndDate = Calendar.getInstance();
* queryEndDate.set(2005, Calendar.MAY, 1, 11, 15, 0);
* queryEndDate.set(Calendar.MILLISECOND, 0);
*
* // This range is monday to friday every three weeks, starting from
* // March 7th 2005, which means for our query dates we need
* // April 18th through to the 22nd.
* PeriodList periods =
* weekdayNineToFiveEvents.getPeriods(queryStartDate.getTime(),
* queryEndDate.getTime());
* </code></pre>
*
* @author Ben Fortuna
*/
public class VEvent extends CalendarComponent {
private static final long serialVersionUID = 2547948989200697335L;
private ComponentList alarms;
/**
* Default constructor.
*/
public VEvent() {
super(VEVENT);
this.alarms = new ComponentList();
getProperties().add(new DtStamp());
}
/**
* Constructor.
*
* @param properties
* a list of properties
*/
public VEvent(final PropertyList properties) {
super(VEVENT, properties);
this.alarms = new ComponentList();
}
/**
* Constructor.
*
* @param properties
* a list of properties
* @param alarms
* a list of alarms
*/
public VEvent(final PropertyList properties, final ComponentList alarms) {
super(VEVENT, properties);
this.alarms = alarms;
}
/**
* Constructs a new VEVENT instance starting at the specified
* time with the specified summary.
* @param start the start date of the new event
* @param summary the event summary
*/
public VEvent(final Date start, final String summary) {
this();
getProperties().add(new DtStart(start));
getProperties().add(new Summary(summary));
}
/**
* Constructs a new VEVENT instance starting and ending at the specified
* times with the specified summary.
* @param start the start date of the new event
* @param end the end date of the new event
* @param summary the event summary
*/
public VEvent(final Date start, final Date end, final String summary) {
this();
getProperties().add(new DtStart(start));
getProperties().add(new DtEnd(end));
getProperties().add(new Summary(summary));
}
/**
* Constructs a new VEVENT instance starting at the specified
* times, for the specified duration, with the specified summary.
* @param start the start date of the new event
* @param duration the duration of the new event
* @param summary the event summary
*/
public VEvent(final Date start, final Dur duration, final String summary) {
this();
getProperties().add(new DtStart(start));
getProperties().add(new Duration(duration));
getProperties().add(new Summary(summary));
}
/**
* Returns the list of alarms for this event.
* @return a component list
*/
public final ComponentList getAlarms() {
return alarms;
}
/**
* @see java.lang.Object#toString()
*/
public final String toString() {
StringBuffer b = new StringBuffer();
b.append(BEGIN);
b.append(':');
b.append(getName());
b.append(Strings.LINE_SEPARATOR);
b.append(getProperties());
b.append(getAlarms());
b.append(END);
b.append(':');
b.append(getName());
b.append(Strings.LINE_SEPARATOR);
return b.toString();
}
/**
* @see net.fortuna.ical4j.model.Component#validate(boolean)
*/
public final void validate(final boolean recurse) throws ValidationException {
// validate that getAlarms() only contains VAlarm components
Iterator iterator = getAlarms().iterator();
while (iterator.hasNext()) {
Component component = (Component) iterator.next();
if (!(component instanceof VAlarm)) {
throw new ValidationException(
"Component [" + component.getName() + "] may not occur in VEVENT");
}
}
if (!CompatibilityHints.isHintEnabled(
CompatibilityHints.KEY_RELAXED_VALIDATION)) {
// From "4.8.4.7 Unique Identifier":
// Conformance: The property MUST be specified in the "VEVENT", "VTODO",
// "VJOURNAL" or "VFREEBUSY" calendar components.
PropertyValidator.getInstance().assertOne(Property.UID,
getProperties());
// From "4.8.7.2 Date/Time Stamp":
// Conformance: This property MUST be included in the "VEVENT", "VTODO",
// "VJOURNAL" or "VFREEBUSY" calendar components.
PropertyValidator.getInstance().assertOne(Property.DTSTAMP,
getProperties());
}
/*
* ; the following are optional, ; but MUST NOT occur more than once
*
* class / created / description / dtstart / geo / last-mod / location /
* organizer / priority / dtstamp / seq / status / summary / transp /
* uid / url / recurid /
*/
PropertyValidator.getInstance().assertOneOrLess(Property.CLASS,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.CREATED,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.DESCRIPTION,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.DTSTART,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.GEO,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.LAST_MODIFIED,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.LOCATION,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.ORGANIZER,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.PRIORITY,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.DTSTAMP,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.SEQUENCE,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.STATUS,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.SUMMARY,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.TRANSP,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.UID,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.URL,
getProperties());
PropertyValidator.getInstance().assertOneOrLess(Property.RECURRENCE_ID,
getProperties());
Status status = (Status) getProperty(Property.STATUS);
if (status != null
&& !Status.VEVENT_TENTATIVE.equals(status)
&& !Status.VEVENT_CONFIRMED.equals(status)
&& !Status.VEVENT_CANCELLED.equals(status)) {
throw new ValidationException(
"Status property [" + status.toString() + "] is not applicable for VEVENT");
}
/*
* ; either 'dtend' or 'duration' may appear in ; a 'eventprop', but
* 'dtend' and 'duration' ; MUST NOT occur in the same 'eventprop'
*
* dtend / duration /
*/
try {
PropertyValidator.getInstance().assertNone(Property.DTEND, getProperties());
}
catch (ValidationException ve) {
PropertyValidator.getInstance().assertNone(Property.DURATION, getProperties());
}
if (getProperty(Property.DTEND) != null) {
/*
* The "VEVENT" is also the calendar component used to specify an
* anniversary or daily reminder within a calendar. These events have a
* DATE value type for the "DTSTART" property instead of the default
* data type of DATE-TIME. If such a "VEVENT" has a "DTEND" property, it
* MUST be specified as a DATE value also. The anniversary type of
* "VEVENT" can span more than one date (i.e, "DTEND" property value is
* set to a calendar date after the "DTSTART" property value).
*/
DtStart start = (DtStart) getProperty(Property.DTSTART);
DtEnd end = (DtEnd) getProperty(Property.DTEND);
if (start != null) {
Parameter value = start.getParameter(Parameter.VALUE);
if (value != null && !value.equals(end.getParameter(Parameter.VALUE))) {
throw new ValidationException("Property ["
+ Property.DTEND + "] must have the same ["
+ Parameter.VALUE + "] as [" + Property.DTSTART + "]");
}
}
}
/*
* ; the following are optional, ; and MAY occur more than once
*
* attach / attendee / categories / comment / contact / exdate / exrule /
* rstatus / related / resources / rdate / rrule / x-prop
*/
if (recurse) {
validateProperties();
}
}
/**
* Returns a normalised list of periods representing the consumed time for this
* event.
* @param rangeStart
* @param rangeEnd
* @return a normalised list of periods representing consumed time for this event
* @see VEvent#getConsumedTime(Date, Date, boolean)
*/
public final PeriodList getConsumedTime(final Date rangeStart, final Date rangeEnd) {
return getConsumedTime(rangeStart, rangeEnd, true);
}
/**
* Returns a list of periods representing the consumed time for this event
* in the specified range. Note that the returned list may contain a single
* period for non-recurring components or multiple periods for recurring
* components. If no time is consumed by this event an empty list is returned.
* @param rangeStart the start of the range to check for consumed time
* @param rangeEnd the end of the range to check for consumed time
* @param normalise indicate whether the returned list of periods should be
* normalised
* @return a list of periods representing consumed time for this event
*/
public final PeriodList getConsumedTime(final Date rangeStart, final Date rangeEnd, final boolean normalise) {
PeriodList periods = new PeriodList();
// if component is transparent return empty list..
if (Transp.TRANSPARENT.equals(getProperty(Property.TRANSP))) {
return periods;
}
DtStart start = (DtStart) getProperty(Property.DTSTART);
DtEnd end = (DtEnd) getProperty(Property.DTEND);
Duration duration = (Duration) getProperty(Property.DURATION);
// if no start date or duration specified return empty list..
if (start == null || (duration == null && end == null)) {
return periods;
}
// if an explicit event duration is not specified, derive a value for recurring
// periods from the end date..
Dur rDuration;
if (duration == null) {
rDuration = new Dur(start.getDate(), end.getDate());
}
else {
rDuration = duration.getDuration();
}
// adjust range start back by duration to allow for recurrences that
// start before the range but finish inside..
// FIXME: See bug #1325558..
Date adjustedRangeStart = new DateTime(rangeStart);
adjustedRangeStart.setTime(rDuration.negate().getTime(rangeStart).getTime());
// if start/end specified as anniversary-type (i.e. uses DATE values
// rather than DATE-TIME), return empty list..
if (Value.DATE.equals(start.getParameter(Parameter.VALUE))) {
return periods;
}
// recurrence dates..
PropertyList rDates = getProperties(Property.RDATE);
for (Iterator i = rDates.iterator(); i.hasNext();) {
RDate rdate = (RDate) i.next();
// only period-based rdates are applicable..
// FIXME: ^^^ not true - date-time/date also applicable..
if (Value.PERIOD.equals(rdate.getParameter(Parameter.VALUE))) {
for (Iterator j = rdate.getPeriods().iterator(); j.hasNext();) {
Period period = (Period) j.next();
if (period.getStart().before(rangeEnd) && period.getEnd().after(rangeStart)) {
periods.add(period);
}
}
}
}
// recurrence rules..
PropertyList rRules = getProperties(Property.RRULE);
for (Iterator i = rRules.iterator(); i.hasNext();) {
RRule rrule = (RRule) i.next();
DateList startDates = rrule.getRecur().getDates(start.getDate(), adjustedRangeStart, rangeEnd, (Value) start.getParameter(Parameter.VALUE));
// DateList startDates = rrule.getRecur().getDates(start.getDate(), rangeStart, rangeEnd, (Value) start.getParameters().getParameter(Parameter.VALUE));
for (int j = 0; j < startDates.size(); j++) {
Date startDate = (Date) startDates.get(j);
periods.add(new Period(new DateTime(startDate), rDuration));
}
}
// add first instance if included in range..
if (start.getDate().before(rangeEnd)) {
if (end != null && end.getDate().after(rangeStart)) {
periods.add(new Period(new DateTime(start.getDate()), new DateTime(end.getDate())));
}
else if (duration != null) {
Period period = new Period(new DateTime(start.getDate()), duration.getDuration());
if (period.getEnd().after(rangeStart)) {
periods.add(period);
}
}
}
// exception dates..
PropertyList exDates = getProperties(Property.EXDATE);
for (Iterator i = exDates.iterator(); i.hasNext();) {
ExDate exDate = (ExDate) i.next();
for (Iterator j = periods.iterator(); j.hasNext();) {
Period period = (Period) j.next();
// for DATE-TIME instances check for DATE-based exclusions also..
if (exDate.getDates().contains(period.getStart())
|| exDate.getDates().contains(new Date(period.getStart()))) {
j.remove();
}
}
}
// exception rules..
// FIXME: exception rules should be consistent with exception dates (i.e. not use periods?)..
PropertyList exRules = getProperties(Property.EXRULE);
PeriodList exPeriods = new PeriodList();
for (Iterator i = exRules.iterator(); i.hasNext();) {
ExRule exrule = (ExRule) i.next();
// DateList startDates = exrule.getRecur().getDates(start.getDate(), adjustedRangeStart, rangeEnd, (Value) start.getParameters().getParameter(Parameter.VALUE));
DateList startDates = exrule.getRecur().getDates(start.getDate(), rangeStart, rangeEnd, (Value) start.getParameter(Parameter.VALUE));
for (Iterator j = startDates.iterator(); j.hasNext();) {
Date startDate = (Date) j.next();
exPeriods.add(new Period(new DateTime(startDate), rDuration));
}
}
// apply exceptions..
if (!exPeriods.isEmpty()) {
periods = periods.subtract(exPeriods);
}
// if periods already specified through recurrence, return..
// ..also normalise before returning.
if (!periods.isEmpty() && normalise) {
return periods.normalise();
}
return periods;
}
/**
* @return the optional access classification property for an event
*/
public final Clazz getClassification() {
return (Clazz) getProperty(Property.CLASS);
}
/**
* @return the optional creation-time property for an event
*/
public final Created getCreated() {
return (Created) getProperty(Property.CREATED);
}
/**
* @return the optional description property for an event
*/
public final Description getDescription() {
return (Description) getProperty(Property.DESCRIPTION);
}
/**
* Convenience method to pull the DTSTART out of the property list.
* @return The DtStart object representation of the start Date
*/
public final DtStart getStartDate() {
return (DtStart) getProperty(Property.DTSTART);
}
/**
* @return the optional geographic position property for an event
*/
public final Geo getGeographicPos() {
return (Geo) getProperty(Property.GEO);
}
/**
* @return the optional last-modified property for an event
*/
public final LastModified getLastModified() {
return (LastModified) getProperty(Property.LAST_MODIFIED);
}
/**
* @return the optional location property for an event
*/
public final Location getLocation() {
return (Location) getProperty(Property.LOCATION);
}
/**
* @return the optional organizer property for an event
*/
public final Organizer getOrganizer() {
return (Organizer) getProperty(Property.ORGANIZER);
}
/**
* @return the optional priority property for an event
*/
public final Priority getPriority() {
return (Priority) getProperty(Property.PRIORITY);
}
/**
* @return the optional date-stamp property
*/
public final DtStamp getDateStamp() {
return (DtStamp) getProperty(Property.DTSTAMP);
}
/**
* @return the optional sequence number property for an event
*/
public final Sequence getSequence() {
return (Sequence) getProperty(Property.SEQUENCE);
}
/**
* @return the optional status property for an event
*/
public final Status getStatus() {
return (Status) getProperty(Property.STATUS);
}
/**
* @return the optional summary property for an event
*/
public final Summary getSummary() {
return (Summary) getProperty(Property.SUMMARY);
}
/**
* @return the optional time transparency property for an event
*/
public final Transp getTransparency() {
return (Transp) getProperty(Property.TRANSP);
}
/**
* @return the optional URL property for an event
*/
public final Url getUrl() {
return (Url) getProperty(Property.URL);
}
/**
* @return the optional recurrence identifier property for an event
*/
public final RecurrenceId getRecurrenceId() {
return (RecurrenceId) getProperty(Property.RECURRENCE_ID);
}
/**
* Returns the end date of this event. Where an end date is not
* available it will be derived from the event duration.
* @return a DtEnd instance, or null if one cannot be derived
*/
public final DtEnd getEndDate() {
return getEndDate(true);
}
/**
* Convenience method to pull the DTEND out of the property list. If
* DTEND was not specified, use the DTSTART + DURATION to calculate it.
* @param deriveFromDuration specifies whether to derive an end date from
* the event duration where an end date is not found
* @return The end for this VEVENT.
*/
public final DtEnd getEndDate(final boolean deriveFromDuration) {
DtEnd dtEnd = (DtEnd) getProperty(Property.DTEND);
if (deriveFromDuration) {
// No DTEND? No problem, we'll use the DURATION.
if (dtEnd == null) {
DtStart dtStart = getStartDate();
Duration vEventDuration = getDuration();
if (vEventDuration != null) {
dtEnd = new DtEnd(Dates.getInstance(vEventDuration.getDuration().getTime(dtStart.getDate()),
(Value) dtStart.getParameter(Parameter.VALUE)));
if (dtStart.isUtc()) {
dtEnd.setUtc(true);
}
}
}
}
return dtEnd;
}
/**
* @return the optional Duration property
*/
public final Duration getDuration() {
return (Duration) getProperty(Property.DURATION);
}
/**
* Returns the UID property of this component if available.
* @return a Uid instance, or null if no UID property exists
*/
public final Uid getUid() {
return (Uid) getProperty(Property.UID);
}
}
|
package gov.nih.nci.cabig.report2caaers;
import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.CAAERS_WS_INVOCATION_COMPLETED;
import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.CAAERS_WS_INVOCATION_INITIATED;
import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.CAAERS_WS_IN_TRANSFORMATION;
import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.CAAERS_WS_OUT_TRANSFORMATION;
import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.POST_PROCESS_EDI_MSG;
import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.PRE_PROCESS_EDI_MSG;
import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.REQUEST_RECEIVED;
import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.ROUTED_TO_CAAERS_RESPONSE_SINK;
import static gov.nih.nci.cabig.caaers2adeers.track.IntegrationLog.Stage.ROUTED_TO_CAAERS_WS_INVOCATION_CHANNEL;
import static gov.nih.nci.cabig.caaers2adeers.track.Tracker.track;
import java.util.HashMap;
import java.util.Map;
import gov.nih.nci.cabig.caaers2adeers.Caaers2AdeersRouteBuilder;
public class ToCaaersReportWSRouteBuilder {
private static String caAERSSafetyReportJBIURL = "jbi:service:http:
private static String requestXSLBase = "xslt/e2b/request/";
private static String responseXSLBase = "xslt/e2b/response/";
private String inputEDIDir;
private String outputEDIDir;
private Caaers2AdeersRouteBuilder routeBuilder;
public void configure(Caaers2AdeersRouteBuilder rb){
this.routeBuilder = rb;
routeBuilder.from("file://"+inputEDIDir+"?preMove=inprogress&move=done&moveFailed=movefailed")
.to("log:gov.nih.nci.cabig.report2caaers.caaers-ws-request?showHeaders=true&level=TRACE")
.processRef("removeEDIHeadersAndFootersProcessor")
.process(track(REQUEST_RECEIVED))
.to(routeBuilder.getFileTracker().fileURI(REQUEST_RECEIVED))
.process(track(PRE_PROCESS_EDI_MSG))
.to(routeBuilder.getFileTracker().fileURI(PRE_PROCESS_EDI_MSG))
.to("direct:caaers-reportSubmit-sync");
Map<String, String> nss = new HashMap<String, String>();
nss.put("soap", "http://schemas.xmlsoap.org/soap/envelope/");
nss.put("ns1", "http://schema.integration.caaers.cabig.nci.nih.gov/aereport");
nss.put("ns3", "http://schema.integration.caaers.cabig.nci.nih.gov/common");
//content based router
//if it is saveSafetyReportResponse, then E2B ack will not be sent
//also, if submit safety report is processed successfully to indicate succesfully submitted to AdEERS, then E2B ack will not be sent
routeBuilder.from("direct:processedE2BMessageSink")
.to("log:gov.nih.nci.cabig.report2caaers.caaers-ws-request?showHeaders=true&level=TRACE")
.choice()
.when().xpath("/soap:Envelope/soap:Body/ns1:saveSafetyReportResponse", nss)
.to("direct:morgue")
.when().xpath("/ichicsrack/acknowledgment/messageacknowledgment", nss)
.to("direct:morgue")
.otherwise()
.to("direct:sendE2BAckSink");
routeBuilder.from("direct:sendE2BAckSink")
.process(track(ROUTED_TO_CAAERS_WS_INVOCATION_CHANNEL))
.processRef("addEDIHeadersAndFootersProcessor")
.process(track(POST_PROCESS_EDI_MSG))
.to(routeBuilder.getFileTracker().fileURI(POST_PROCESS_EDI_MSG))
.to("file://"+outputEDIDir);
//caAERS - createParticipant
configureWSCallRoute("direct:caaers-reportSubmit-sync", "safetyreport_e2b_sync.xsl", caAERSSafetyReportJBIURL + "submitSafetyReport" );
}
private void configureWSCallRoute(String fromSink, String xslFileName, String serviceURI){
this.routeBuilder.configureWSCallRoute(fromSink,
requestXSLBase + xslFileName,
serviceURI,
responseXSLBase + xslFileName,
"direct:processedE2BMessageSink",
CAAERS_WS_IN_TRANSFORMATION, CAAERS_WS_INVOCATION_INITIATED, CAAERS_WS_INVOCATION_COMPLETED, CAAERS_WS_OUT_TRANSFORMATION, ROUTED_TO_CAAERS_RESPONSE_SINK);
}
public String getInputEDIDir() {
return inputEDIDir;
}
public void setInputEDIDir(String inputEDIDir) {
this.inputEDIDir = inputEDIDir;
}
public String getOutputEDIDir() {
return outputEDIDir;
}
public void setOutputEDIDir(String outputEDIDir) {
this.outputEDIDir = outputEDIDir;
}
}
|
package com.theah64.xrob.api.database.tables;
import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import com.theah64.xrob.api.database.Connection;
import com.theah64.xrob.api.models.Contact;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Contacts extends BaseTable<Contact> {
private static final String COLUMN_PHONE_NUMBER = "phone_number";
private static final String COLUMN_PHONE_TYPE = "phone_type";
private static final String COLUMN_VICTIM_ID = "victim_id";
private static final String KEY_PHONE_NUMBERS = "phone_numbers";
private static final String COLUMN_ANDROID_CONTACT_ID = "android_contact_id";
private static final String TABLE_NAME_CONTACTS = "contacts";
private static Contacts instance = new Contacts();
private Contacts() {
}
public static Contacts getInstance() {
return instance;
}
protected boolean isPhoneNumberExist(Contact.PhoneNumber phoneNumber) {
boolean isExist = false;
final String query = "SELECT id FROM phone_numbers WHERE contact_id = ? AND phone = ? AND phone_type = ? LIMIT 1";
final java.sql.Connection con = Connection.getConnection();
try {
final PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, phoneNumber.getContactId());
ps.setString(2, phoneNumber.getPhone());
ps.setString(3, phoneNumber.getType());
final ResultSet rs = ps.executeQuery();
isExist = rs.first();
System.out.println("isPhoneNumberExist : " + isExist + ", Contact : " + phoneNumber);
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return isExist;
}
@Override
protected List<Contact> parse(@Nullable String victimId, @NotNull JSONArray jaContacts) throws JSONException {
final List<Contact> contactList = new ArrayList<>();
for (int i = 0; i < jaContacts.length(); i++) {
final JSONObject joContact = jaContacts.getJSONObject(i);
final String androidContactId = joContact.getString(COLUMN_ANDROID_CONTACT_ID);
final String name = joContact.getString(COLUMN_NAME);
List<Contact.PhoneNumber> phoneNumbers = null;
if (joContact.has(KEY_PHONE_NUMBERS)) {
final JSONArray jaPhoneNumbers = joContact.getJSONArray(KEY_PHONE_NUMBERS);
phoneNumbers = parsePhoneNumbers(null, jaPhoneNumbers);
}
contactList.add(new Contact(victimId, androidContactId, null, name, phoneNumbers));
}
return contactList;
}
/**
* Used parse phone numbers and their types from the JSONArray received via JSONPOSTServlet.
*/
private List<Contact.PhoneNumber> parsePhoneNumbers(final String contactId, JSONArray jaPhoneNumbers) {
if (jaPhoneNumbers != null) {
final List<Contact.PhoneNumber> phoneNumbers = new ArrayList<>(jaPhoneNumbers.length());
try {
for (int i = 0; i < jaPhoneNumbers.length(); i++) {
final JSONObject jaPhoneNumber = jaPhoneNumbers.getJSONObject(i);
final String phoneNumber = jaPhoneNumber.getString(COLUMN_PHONE_NUMBER);
final String phoneType = jaPhoneNumber.getString(COLUMN_PHONE_TYPE);
phoneNumbers.add(new Contact.PhoneNumber(contactId, phoneNumber, phoneType));
}
return phoneNumbers;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
@Override
public Contact get(String column1, String value1, String column2, String value2) {
Contact contact = null;
final String query = String.format("SELECT id,name FROM contacts WHERE %s = ? AND %s = ? LIMIT 1", column1, column2);
final java.sql.Connection con = Connection.getConnection();
try {
final PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, value1);
ps.setString(2, value2);
final ResultSet rs = ps.executeQuery();
if (rs.first()) {
final String id = rs.getString(COLUMN_ID);
final String name = rs.getString(COLUMN_NAME);
contact = new Contact(null, null, id, name, null);
}
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return contact;
}
/**
* Adding contacts from JSONArray
*
* @param victimId
* @param jsonArray
* @throws RuntimeException
* @throws JSONException
*/
@Override
public void addv2(@Nullable String victimId, @NotNull JSONArray jsonArray) throws RuntimeException, JSONException {
boolean isAdded = true;
//Preparing list
final List<Contact> contactList = parse(victimId, jsonArray);
final String insertContactQuery = "INSERT INTO contacts (victim_id,android_contact_id, name) VALUES (?,?,?);";
final java.sql.Connection con = Connection.getConnection();
try {
final PreparedStatement psAddContact = con.prepareStatement(insertContactQuery, PreparedStatement.RETURN_GENERATED_KEYS);
psAddContact.setString(1, victimId);
for (final Contact contact : contactList) {
String contactId = null;
final Contact exContact = get(Contacts.COLUMN_VICTIM_ID, victimId, Contacts.COLUMN_ANDROID_CONTACT_ID, contact.getAndroidContactId());
if (exContact == null) {
//Adding new contact
psAddContact.setString(2, contact.getAndroidContactId());
psAddContact.setString(3, contact.getName());
isAdded = isAdded && psAddContact.executeUpdate() == 1;
if (isAdded) {
final ResultSet genRs = psAddContact.getGeneratedKeys();
if (genRs.first()) {
contactId = genRs.getString(1);
}
genRs.close();
}
} else {
if (!exContact.getName().equals(contact.getName())) {
System.out.println(exContact);
//Name changed, so update the contacts table
final boolean isUpdated = update(COLUMN_ANDROID_CONTACT_ID, contact.getAndroidContactId(), COLUMN_NAME, contact.getName());
if (!isUpdated) {
throw new RuntimeException("Failed to edit the contact name");
}
}
contactId = exContact.getId();
}
if (contactId != null) {
if (contact.getPhone() != null && contact.getPhone().size() > 0) {
final String insertPhoneNumberQuery = "INSERT INTO phone_numbers (contact_id, phone,phone_type) VALUES (?,?,?);";
final PreparedStatement ps = con.prepareStatement(insertPhoneNumberQuery);
//Looping through each phone number and add it to the database.
for (final Contact.PhoneNumber phoneNumber : contact.getPhone()) {
//Setting phone number's contact id
phoneNumber.setContactId(contactId);
if (!isPhoneNumberExist(phoneNumber)) {
ps.setString(1, phoneNumber.getContactId());
ps.setString(2, phoneNumber.getPhone());
ps.setString(3, phoneNumber.getType());
isAdded = isAdded && ps.executeUpdate() == 1;
}
}
ps.close();
}
}
}
} catch (SQLException e) {
e.printStackTrace();
isAdded = false;
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (!isAdded) {
throw new RuntimeException("Error occured while adding contacts to database");
}
}
@Override
public boolean update(String whereColumn, String whereColumnValue, String updateColumn, String newUpdateColumnValue) {
return update(TABLE_NAME_CONTACTS, whereColumn, whereColumnValue, updateColumn, newUpdateColumnValue);
}
}
|
package org.datavec.spark.transform;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.datavec.api.transform.TransformProcess;
import org.datavec.image.transform.ImageTransformProcess;
import org.datavec.spark.transform.model.*;
import org.datavec.spark.transform.service.DataVecTransformService;
import org.nd4j.shade.jackson.databind.ObjectMapper;
import play.Mode;
import play.libs.Json;
import play.routing.RoutingDsl;
import play.server.Server;
import java.io.File;
import java.io.IOException;
import static play.mvc.Controller.request;
import static play.mvc.Results.*;
/**
* A rest server for using an
* {@link TransformProcess} based on simple
* csv values and a schema via REST.
*
* The input values are an {@link SingleCSVRecord}
* which (based on the input schema) will automatically
* have their values transformed.
*
* @author Adam Gibson
*/
@Slf4j
@Data
public class CSVSparkTransformServer extends SparkTransformServer {
private CSVSparkTransform transform;
public void runMain(String[] args) throws Exception {
JCommander jcmdr = new JCommander(this);
try {
jcmdr.parse(args);
} catch (ParameterException e) {
//User provides invalid input -> print the usage info
jcmdr.usage();
if (jsonPath == null)
System.err.println("Json path parameter is missing.");
try {
Thread.sleep(500);
} catch (Exception e2) {
}
System.exit(1);
}
RoutingDsl routingDsl = new RoutingDsl();
if(jsonPath != null) {
String json = FileUtils.readFileToString(new File(jsonPath));
TransformProcess transformProcess = TransformProcess.fromJson(json);
transform = new CSVSparkTransform(transformProcess);
}
else {
log.warn("Server started with no json for transform process. Please ensure you specify a transform process via sending a post request with raw json" +
"to /transformprocess");
}
//return the host information for a given id
routingDsl.GET("/transformprocess").routeTo(FunctionUtil.function0((() -> {
try {
if(transform == null)
return badRequest();
log.info("Transform process initialized");
return ok(Json.toJson(transform.getTransformProcess()));
} catch (Exception e) {
e.printStackTrace();
return internalServerError();
}
})));
//return the host information for a given id
routingDsl.POST("/transformprocess").routeTo(FunctionUtil.function0((() -> {
try {
TransformProcess transformProcess = TransformProcess.fromJson(getJsonText());
setCSVTransformProcess(transformProcess);
log.info("Transform process initialized");
return ok(Json.toJson(transformProcess));
} catch (Exception e) {
e.printStackTrace();
return internalServerError();
}
})));
//return the host information for a given id
routingDsl.POST("/transformincremental").routeTo(FunctionUtil.function0((() -> {
try {
SingleCSVRecord record = objectMapper.readValue(getJsonText(),SingleCSVRecord.class);
if (record == null)
return badRequest();
return ok(Json.toJson(transformIncremental(record)));
} catch (Exception e) {
e.printStackTrace();
return internalServerError();
}
})));
//return the host information for a given id
routingDsl.POST("/transform").routeTo(FunctionUtil.function0((() -> {
try {
BatchCSVRecord batch = transform(objectMapper.readValue(getJsonText(),BatchCSVRecord.class));
if (batch == null)
return badRequest();
return ok(Json.toJson(batch));
} catch (Exception e) {
e.printStackTrace();
return internalServerError();
}
})));
routingDsl.POST("/transformincrementalarray").routeTo(FunctionUtil.function0((() -> {
try {
SingleCSVRecord record = objectMapper.readValue(getJsonText(),SingleCSVRecord.class);
if (record == null)
return badRequest();
return ok(Json.toJson(transformArrayIncremental(record)));
} catch (Exception e) {
return internalServerError();
}
})));
routingDsl.POST("/transformarray").routeTo(FunctionUtil.function0((() -> {
try {
BatchCSVRecord batchCSVRecord = objectMapper.readValue(getJsonText(),BatchCSVRecord.class);
if (batchCSVRecord == null)
return badRequest();
return ok(Json.toJson(transformArray(batchCSVRecord)));
} catch (Exception e) {
return internalServerError();
}
})));
server = Server.forRouter(routingDsl.build(), Mode.DEV, port);
}
public static void main(String[] args) throws Exception {
new CSVSparkTransformServer().runMain(args);
}
/**
* @param transformProcess
*/
@Override
public void setCSVTransformProcess(TransformProcess transformProcess) {
this.transform = new CSVSparkTransform(transformProcess);
}
@Override
public void setImageTransformProcess(ImageTransformProcess imageTransformProcess) {
throw new UnsupportedOperationException("Invalid operation for " + this.getClass());
}
/**
* @return
*/
@Override
public TransformProcess getCSVTransformProcess() {
return transform.getTransformProcess();
}
@Override
public ImageTransformProcess getImageTransformProcess() {
throw new UnsupportedOperationException("Invalid operation for " + this.getClass());
}
/**
* @param transform
* @return
*/
@Override
public SingleCSVRecord transformIncremental(SingleCSVRecord transform) {
return this.transform.transform(transform);
}
/**
* @param batchCSVRecord
* @return
*/
@Override
public BatchCSVRecord transform(BatchCSVRecord batchCSVRecord) {
return transform.transform(batchCSVRecord);
}
/**
* @param batchCSVRecord
* @return
*/
@Override
public Base64NDArrayBody transformArray(BatchCSVRecord batchCSVRecord) {
try {
return this.transform.toArray(batchCSVRecord);
} catch (IOException e) {
throw new IllegalStateException("Transform array shouldn't throw exception");
}
}
/**
* @param singleCsvRecord
* @return
*/
@Override
public Base64NDArrayBody transformArrayIncremental(SingleCSVRecord singleCsvRecord) {
try {
return this.transform.toArray(singleCsvRecord);
} catch (IOException e) {
throw new IllegalStateException("Transform array shouldn't throw exception");
}
}
@Override
public Base64NDArrayBody transformIncrementalArray(SingleImageRecord singleImageRecord) throws IOException {
throw new UnsupportedOperationException("Invalid operation for " + this.getClass());
}
@Override
public Base64NDArrayBody transformArray(BatchImageRecord batchImageRecord) throws IOException {
throw new UnsupportedOperationException("Invalid operation for " + this.getClass());
}
}
|
package org.spine3.server.entity;
import org.spine3.server.BoundedContext;
import org.spine3.server.reflect.Classes;
import org.spine3.server.storage.StorageFactory;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Throwables.propagate;
import static java.lang.reflect.Modifier.isPrivate;
import static java.lang.reflect.Modifier.isPublic;
/**
* Abstract base class for repositories.
*
* @param <I> the type of IDs of entities managed by the repository
* @param <E> the entity type
*
* @author Alexander Yevsyukov
*/
public abstract class Repository<I, E extends Entity<I, ?>> implements AutoCloseable {
/**
* The index of the declaration of the generic type {@code I} in this class.
*/
private static final int ID_CLASS_GENERIC_INDEX = 0;
/**
* The index of the declaration of the generic type {@code E} in this class.
*/
private static final int ENTITY_CLASS_GENERIC_INDEX = 1;
protected static final String ERR_MSG_STORAGE_NOT_ASSIGNED = "Storage is not assigned.";
/**
* The {@code BoundedContext} in which this repository works.
*/
private final BoundedContext boundedContext;
/**
* The constructor for creating entity instances.
*/
private final Constructor<E> entityConstructor;
/**
* The data storage for this repository.
*/
private AutoCloseable storage;
/**
* Creates the repository in the passed {@link BoundedContext}.
*
* @param boundedContext the {@link BoundedContext} in which this repository works
*/
protected Repository(BoundedContext boundedContext) {
this.boundedContext = boundedContext;
this.entityConstructor = getEntityConstructor();
this.entityConstructor.setAccessible(true);
}
private Constructor<E> getEntityConstructor() {
final Class<E> entityClass = getEntityClass();
final Class<I> idClass = getIdClass();
try {
final Constructor<E> result = entityClass.getDeclaredConstructor(idClass);
checkConstructorAccessModifier(result.getModifiers(), entityClass.getName());
return result;
} catch (NoSuchMethodException ignored) {
throw noSuchConstructorException(entityClass.getName(), idClass.getName());
}
}
private static void checkConstructorAccessModifier(int modifiers, String entityClass) {
if (!isPublic(modifiers)) {
final String constructorModifier = isPrivate(modifiers) ? "private." : "protected.";
final String message = "Constructor must be public in the " + entityClass + " class, found: " + constructorModifier;
throw propagate(new IllegalAccessException(message));
}
}
private static RuntimeException noSuchConstructorException(String entityClass, String idClass) {
final String message = entityClass + " class must declare a constructor with a single " + idClass + " ID parameter.";
return propagate(new NoSuchMethodException(message));
}
/**
* @return the {@link BoundedContext} in which this repository works
*/
protected BoundedContext getBoundedContext() {
return boundedContext;
}
/**
* @return the class of IDs used by this repository
*/
@CheckReturnValue
protected Class<I> getIdClass() {
return Classes.getGenericParameterType(getClass(), ID_CLASS_GENERIC_INDEX);
}
/**
* @return the class of entities managed by this repository
*/
@CheckReturnValue
protected Class<E> getEntityClass() {
return Classes.getGenericParameterType(getClass(), ENTITY_CLASS_GENERIC_INDEX);
}
/**
* Create a new entity instance with its default state.
*
* @param id the id of the entity
* @return new entity instance
*/
@CheckReturnValue
public E create(I id) {
try {
final E result = entityConstructor.newInstance(id);
result.setDefault();
return result;
} catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw propagate(e);
}
}
/**
* Stores the passed object.
*
* <p>The storage must be assigned before calling this method.
*
* @param obj an instance to store
*/
protected abstract void store(E obj);
/**
* Loads the entity with the passed ID.
*
* <p>The storage must be assigned before calling this method.
*
* @param id the id of the entity to load
* @return the entity or {@code null} if there's no entity with such id
*/
@CheckReturnValue
@Nullable
protected abstract E load(I id);
/**
* @return the storage assigned to this repository or {@code null} if the storage is not assigned yet
*/
@CheckReturnValue
@Nullable
protected AutoCloseable getStorage() {
return this.storage;
}
/**
* @return true if the storage is assigned, false otherwise
*/
public boolean storageAssigned() {
return this.storage != null;
}
protected static <S extends AutoCloseable> S checkStorage(@Nullable S storage) {
checkState(storage != null, ERR_MSG_STORAGE_NOT_ASSIGNED);
return storage;
}
public void initStorage(StorageFactory factory) {
if (this.storage != null) {
throw new IllegalStateException(String.format(
"The repository %s already has storage %s.", this, this.storage));
}
this.storage = createStorage(factory);
}
/**
* Creates the storage using the passed factory.
*
* <p>Implementations are responsible for properly calling the factory
* for creating the storage, which is compatible with the repository.
*
* @param factory the factory to create the storage
* @return the created storage instance
*/
protected abstract AutoCloseable createStorage(StorageFactory factory);
/**
* Closes the repository by closing the underlying storage.
*
* <p>The reference to the storage becomes null after this call.
*
* @throws Exception which occurred during closing of the storage
*/
@Override
public void close() throws Exception {
if (this.storage != null) {
this.storage.close();
this.storage = null;
}
}
}
|
package ru.semiot.platform.drivers.narodmon.temperature;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import ru.semiot.platform.deviceproxyservice.api.drivers.Device;
public class ScheduledDevice implements Runnable {
private DeviceDriverImpl ddi;
private static final int FNV_32_INIT = 0x811c9dc5;
private static final int FNV_32_PRIME = 0x01000193;
private static String API_KEY = "21a2qYKfbqzyU";
private static String UUID = "41e99f715d97f740cf34cdf146882fa9";
private static String CMD_SENSOR_NEARBY = "sensorsNearby";
private static final String templateTopic = "${DEVICE_HASH}";
private static final String templateOnState = "prefix saref: <http://ontology.tno.nl/saref
+ "<http://${DOMAIN}/${SYSTEM_PATH}/${DEVICE_HASH}> saref:hasState saref:OnState.";
/* String templateSubsystem = "ssn:hasSubSystem [ a ssn:SensingDevice ; "
+ "ssn:observes qudt-quantity:ThermodynamicTemperature ; ssn:hasMeasurementCapability ["
+ " a ssn:MeasurementCapability ; ssn:forProperty qudt-quantity:ThermodynamicTemperature ; "
+ "ssn:hasMeasurementProperty [ a qudt:Unit ; ssn:hasValue [ a qudt:Quantity ; "
+ "ssn:hasValue qudt-unit:DegreeCelsius ; ] ; ] ; ] ; ]"; */
public ScheduledDevice(DeviceDriverImpl ddi) {
this.ddi = ddi;
}
public void run() {
long currentTimestamp = System.currentTimeMillis();
try {
List<Device> list = new ArrayList<Device>();
URI uri = new URI(ddi.getUrl() + "/api");
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(uri);
JSONObject json = new JSONObject();
json.put("cmd", CMD_SENSOR_NEARBY).put("lat", "55.75").put("lng", "37.62")
.put("radius", "20").put("types", "1").put("uuid", UUID).put("api_key", API_KEY);
post.setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));
HttpResponse response = client.execute(post);
json = new JSONObject(EntityUtils.toString(response.getEntity()));
JSONArray array = null;
if (json.has("devices")) {
array = new JSONArray((json.get("devices")).toString());
for (int i = 0; i < array.length(); i++){
// list sensors in device
JSONObject jDevice = (JSONObject) array.get(i);
JSONArray a = new JSONArray(((JSONObject)array.get(i)).get("sensors").toString());
for(int j = 0; j< a.length(); j++){
// one sensor
JSONObject jSensor = a.getJSONObject(j);
String hash = getHash(String.valueOf(jDevice.get("id")));
String value = String.valueOf(jSensor.get("value"));
Device device = new Device(hash, "");
list.add(device);
System.out.println(hash + " " + value);
if(ddi.contains(device)) {
int index = ddi.listDevices().indexOf(device);
if(index > 0)
{
Device deviceOld = ddi.listDevices().get(index);
if(deviceOld != null && !deviceOld.getTurnOn()) {
deviceOld.setTurnOn(true);
ddi.inactiveDevice(templateOnState
.replace("${DEVICE_HASH}", deviceOld.getID())
.replace("${SYSTEM_PATH}", ddi.getPathSystemUri())
.replace("${DOMAIN}", ddi.getDomain()));
}
}
sendMessage(value, currentTimestamp, hash);
}
else {
device.setRDFDescription(ddi.getTemplateDescription().replace(
"${DEVICE_HASH}", hash).replace("${SYSTEM_PATH}", ddi.getPathSystemUri())
.replace("${SENSOR_PATH}", ddi.getPathSensorUri())
.replace("${SENSOR_ID}", "1")
.replace("${DOMAIN}", ddi.getDomain())
.replace("${LATITUDE}", String.valueOf(jDevice.get("lat")))
.replace("${LONGITUDE}", String.valueOf(jDevice.get("lng"))));
ddi.addDevice(device);
sendMessage(value, currentTimestamp, hash);
}
break;
}
}
for(Device dev : ddi.listDevices()) {
if(!list.contains(dev) && dev.getTurnOn()) {
dev.setTurnOn(false);
ddi.inactiveDevice(DeviceDriverImpl.templateOffState
.replace("${DEVICE_HASH}", dev.getID())
.replace("${SYSTEM_PATH}", ddi.getPathSystemUri())
.replace("${DOMAIN}", ddi.getDomain()));
}
}
}
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
private void sendMessage(String value, long timestamp, String hash) {
if(value != null) {
String topic = templateTopic.replace("${DEVICE_HASH}", hash);
final String date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
.format(new Date(timestamp));
String message = ddi
.getTemplateObservation()
.replace("${DOMAIN}", ddi.getDomain())
.replace("${SYSTEM_PATH}", ddi.getPathSystemUri())
.replace("${SENSOR_PATH}", ddi.getPathSensorUri())
.replace("${DEVICE_HASH}", hash)
.replace("${SENSOR_ID}", "1")
.replace("${TIMESTAMP}", String.valueOf(timestamp))
.replace("${DATETIME}", date)
.replace("${VALUE}", value);
ddi.publish(topic, message);
} else {
System.err.println(hash + " has unknown value (null)");
}
}
private String getHash(String id) {
String name = id + ddi.getDriverName();
int h = FNV_32_INIT;
final int len = name.length();
for(int i = 0; i < len; i++) {
h ^= name.charAt(i);
h *= FNV_32_PRIME;
}
long longHash = h & 0xffffffffl;
return String.valueOf(longHash);
}
}
|
package dk.aau.kah.bits.database;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.jena.query.Dataset;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ReadWrite;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.tdb.TDBFactory;
import da.aau.kah.bits.config.DatabaseConfig;
import da.aau.kah.bits.config.GeneralConfig;
import da.aau.kah.bits.exceptions.InvalidDatabaseConfig;
public class DatabaseHandler {
private DatabaseConfig databaseConfig;
private Dataset dataset;
private GeneralConfig config;
public DatabaseHandler(DatabaseConfig databaseConfig) throws IOException, InvalidDatabaseConfig {
this.config = GeneralConfig.getInstance();
databaseConfig.validate();
this.databaseConfig = databaseConfig;
createTDBDirectoryIfNotExist();
if (this.databaseConfig.isFreshLoad()) {
clearTDBDatabase();
}
if (this.databaseConfig.getDatasetType().equals("TPC-H")) {
if (!doesTDBExist(databaseConfig.getTDBPath())) {
dataset = TDBFactory.createDataset(databaseConfig.getTDBPath());
TDBFactory.release(dataset);
loadTPCHDataset();
}
}
else if (this.databaseConfig.getDatasetType().equals("TPC-DS")) {
//TODO
}
else {
throw new InvalidDatabaseConfig("The Experiment Dataset "+this.databaseConfig.getDatasetType()+" is not known, implementation is missing.");
}
dataset = TDBFactory.createDataset(databaseConfig.getTDBPath());
}
private void createTDBDirectoryIfNotExist() {
File theDir = new File(databaseConfig.getDatasetPath());
// if the directory does not exist, create it
if (!theDir.exists()) {
try{
theDir.mkdir();
}
catch(SecurityException se){
se.printStackTrace();
}
}
}
private void loadTPCHDataset() throws IOException {
String directory = databaseConfig.getTDBPath();
String tdbloader = config.getTdbLoaderPath();
String ontologyPath = "src/main/resources/"+databaseConfig.getDatasetType()+"/onto/tpc-h-qb4o-delivered-version.ttl";
executeBashCommand(tdbloader+" --loc="+directory+" --graph="+databaseConfig.getOntologyModelURL()+" "+ontologyPath , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph="+databaseConfig.getFactModelURL()+" "+getTPCHPath()+"/lineitem.ttl" , config.isVerbose());
if (databaseConfig.getDimensionModelName().equals("
executeBashCommand(tdbloader+" --loc="+directory+" --graph=http://lod2.eu/schemas/rdfh#has_customer "+getTPCHPath()+"/customer.ttl" , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph=http://lod2.eu/schemas/rdfh#has_nation "+getTPCHPath()+"/nation.ttl" , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph=http://lod2.eu/schemas/rdfh#has_order "+getTPCHPath()+"/order.ttl" , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph=http://lod2.eu/schemas/rdfh#has_part "+getTPCHPath()+"/part.ttl" , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph=http://lod2.eu/schemas/rdfh#has_partsupp "+getTPCHPath()+"/partsupplier.ttl" , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph=http://lod2.eu/schemas/rdfh#has_region "+getTPCHPath()+"/region.ttl" , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph=http://lod2.eu/schemas/rdfh#has_supplier "+getTPCHPath()+"/supplier.ttl" , config.isVerbose());
} else {
executeBashCommand(tdbloader+" --loc="+directory+" --graph="+databaseConfig.getDimensionModelURL()+" "+getTPCHPath()+"/customer.ttl" , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph="+databaseConfig.getDimensionModelURL()+" "+getTPCHPath()+"/nation.ttl" , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph="+databaseConfig.getDimensionModelURL()+" "+getTPCHPath()+"/order.ttl" , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph="+databaseConfig.getDimensionModelURL()+" "+getTPCHPath()+"/part.ttl" , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph="+databaseConfig.getDimensionModelURL()+" "+getTPCHPath()+"/partsupplier.ttl" , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph="+databaseConfig.getDimensionModelURL()+" "+getTPCHPath()+"/region.ttl" , config.isVerbose());
executeBashCommand(tdbloader+" --loc="+directory+" --graph="+databaseConfig.getDimensionModelURL()+" "+getTPCHPath()+"/supplier.ttl" , config.isVerbose());
}
}
private String getTPCHPath(){
return databaseConfig.getDatasetPath();
}
public Model getDefaultModel() {
this.dataset.begin(ReadWrite.READ) ;
Model model = this.dataset.getDefaultModel();
this.dataset.commit() ;
return model;
}
public Model getOntologyModel()
{
return getModel(databaseConfig.getOntologyModelURL());
}
public String getOntologyModelURI()
{
return databaseConfig.getOntologyModelURL();
}
public Model getFactModel()
{
return getModel(databaseConfig.getFactModelURL());
}
public String getFactModelURI() {
return databaseConfig.getFactModelURL();
}
public List<String> getAllDimensionModelURI() {
List<String> modelURIs = getAllModelNames();
modelURIs.remove(getFactModelURI());
modelURIs.remove(getOntologyModelURI());
return modelURIs;
}
public String getDimensionModelURI()
{
if (databaseConfig.getDimensionModelName().equals("
return null;
}
return databaseConfig.getDimensionModelURL();
}
public Model getModel(String modelName) {
this.dataset.begin(ReadWrite.READ) ;
Model model = this.dataset.getNamedModel(modelName);
this.dataset.commit() ;
return model;
}
public List<String> getAllModelNames() {
dataset.begin(ReadWrite.READ) ;
String qiry = "select distinct ?g { graph ?g { ?s ?p ?o } }";
Query query = QueryFactory.create(qiry);
QueryExecution qexec = QueryExecutionFactory.create(query, this.dataset);
/*Execute the Query*/
ResultSet results = qexec.execSelect();
List<String> models = new ArrayList<String>();
while (results.hasNext()) {
QuerySolution row=results.nextSolution();
models.add(row.get("g").toString());
}
qexec.close();
dataset.commit();
return models;
}
public void clearTDBDatabase() throws IOException {
FileUtils.cleanDirectory(new File(databaseConfig.getTDBPath()));
}
public ResultSet executeQuery(Query query) {
dataset.begin(ReadWrite.READ);
QueryExecution qexec = QueryExecutionFactory.create(query, dataset);
ResultSet resultSet = qexec.execSelect();
dataset.commit();
return resultSet;
}
public HashSet<Resource> getDistinctLevelProperties()
{
HashSet<Resource> levelProperties = new HashSet<Resource>();
Model ontologyModel = getOntologyModel();
Property a = ResourceFactory.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
RDFNode levelProperty = ResourceFactory.createResource("http://publishing-multidimensional-data.googlecode.com/git/index.html#ref_qbplus_LevelProperty");
levelProperties.addAll(ontologyModel.listSubjectsWithProperty(a, levelProperty).toList());
return levelProperties;
}
private void executeBashCommand(String command, Boolean verbose) {
String s = null;
try {
// using the Runtime exec method:
//"/usr/local/apache-jena-2.12.1/bin/tdbloader --help"
Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command});
// read the output from the command
if (verbose) {
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
}
if (verbose) {
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
}
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
}
}
public void closeConnection() {
dataset.close();
}
private int countNumberOfFilesInFolder(String folder){
return new File(folder).list().length;
}
private boolean doesTDBExist(String folder) {
//The number five is selected by random. I know that there can be some random files remaining in the folders.
if (countNumberOfFilesInFolder(folder) > 5) {
return true;
}
else {
return false;
}
}
public List<File> getQueries() {
return databaseConfig.getQueries();
}
}
|
package edu.umd.cs.findbugs.ba;
import java.util.BitSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import javax.annotation.CheckForNull;
import org.apache.bcel.Constants;
import org.apache.bcel.generic.CodeExceptionGen;
import org.apache.bcel.generic.InstructionHandle;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.graph.AbstractVertex;
/**
* Simple basic block abstraction for BCEL.
*
* @author David Hovemeyer
* @see CFG
*/
public class BasicBlock extends AbstractVertex<Edge, BasicBlock> implements Debug {
/**
* Set of instruction opcodes that have an implicit null check.
*/
private static final BitSet nullCheckInstructionSet = new BitSet();
static {
nullCheckInstructionSet.set(Constants.GETFIELD);
nullCheckInstructionSet.set(Constants.PUTFIELD);
nullCheckInstructionSet.set(Constants.INVOKESPECIAL);
nullCheckInstructionSet.set(Constants.INVOKEVIRTUAL);
nullCheckInstructionSet.set(Constants.INVOKEINTERFACE);
nullCheckInstructionSet.set(Constants.AALOAD);
nullCheckInstructionSet.set(Constants.AASTORE);
nullCheckInstructionSet.set(Constants.BALOAD);
nullCheckInstructionSet.set(Constants.BASTORE);
nullCheckInstructionSet.set(Constants.CALOAD);
nullCheckInstructionSet.set(Constants.CASTORE);
nullCheckInstructionSet.set(Constants.DALOAD);
nullCheckInstructionSet.set(Constants.DASTORE);
nullCheckInstructionSet.set(Constants.FALOAD);
nullCheckInstructionSet.set(Constants.FASTORE);
nullCheckInstructionSet.set(Constants.IALOAD);
nullCheckInstructionSet.set(Constants.IASTORE);
nullCheckInstructionSet.set(Constants.LALOAD);
nullCheckInstructionSet.set(Constants.LASTORE);
nullCheckInstructionSet.set(Constants.SALOAD);
nullCheckInstructionSet.set(Constants.SASTORE);
nullCheckInstructionSet.set(Constants.MONITORENTER);
nullCheckInstructionSet.set(Constants.ARRAYLENGTH);
// nullCheckInstructionSet.set(Constants.MONITOREXIT);
nullCheckInstructionSet.set(Constants.ATHROW);
// Any others?
}
private InstructionHandle firstInstruction;
private InstructionHandle lastInstruction;
private InstructionHandle exceptionThrower; // instruction for which this
// block is the ETB
private CodeExceptionGen exceptionGen; // set if this block is the entry
// point of an exception handler
private boolean inJSRSubroutine;
private int numNonExceptionSuccessors;
/**
* Constructor.
*/
public BasicBlock() {
this.firstInstruction = null;
this.lastInstruction = null;
this.exceptionThrower = null;
this.exceptionGen = null;
this.inJSRSubroutine = false;
this.numNonExceptionSuccessors = -1;
}
public boolean isInJSRSubroutine() {
return inJSRSubroutine;
}
void setInJSRSubroutine(boolean inJSRSubroutine) {
this.inJSRSubroutine = inJSRSubroutine;
}
/**
* Get the basic block's integer label.
*
* @deprecated call getLabel() instead
* @return the BasicBlock's integer label
*/
@Deprecated
public int getId() {
return getLabel();
}
@Override
public String toString() {
return "block " + String.valueOf(getLabel());
}
/**
* Set the instruction for which this block is the ETB.
*
* @param exceptionThrower
* the instruction
*/
public void setExceptionThrower(InstructionHandle exceptionThrower) {
this.exceptionThrower = exceptionThrower;
}
/**
* Return whether or not this block is an exception thrower.
*/
public boolean isExceptionThrower() {
return exceptionThrower != null;
}
/**
* Get the instruction for which this block is an exception thrower.
*
* @return the instruction, or null if this block is not an exception
* thrower
*/
public InstructionHandle getExceptionThrower() {
return exceptionThrower;
}
/**
* Return whether or not this block is a null check.
*/
public boolean isNullCheck() {
// Null check blocks must be exception throwers,
// and are always empty. (The only kind of non-empty
// exception throwing block is one terminated by an ATHROW).
if (!isExceptionThrower() || getFirstInstruction() != null)
return false;
short opcode = exceptionThrower.getInstruction().getOpcode();
return nullCheckInstructionSet.get(opcode);
}
/**
* Get the first instruction in the basic block.
*/
public InstructionHandle getFirstInstruction() {
return firstInstruction;
}
/**
* Get the last instruction in the basic block.
*/
public InstructionHandle getLastInstruction() {
return lastInstruction;
}
/**
* Get the successor of given instruction within the basic block.
*
* @param handle
* the instruction
* @return the instruction's successor, or null if the instruction is the
* last in the basic block
*/
public @CheckForNull
InstructionHandle getSuccessorOf(InstructionHandle handle) {
if (VERIFY_INTEGRITY) {
if (!containsInstruction(handle))
throw new IllegalStateException();
}
return handle == lastInstruction ? null : handle.getNext();
}
/**
* Get the predecessor of given instruction within the basic block.
*
* @param handle
* the instruction
* @return the instruction's predecessor, or null if the instruction is the
* first in the basic block
*/
public InstructionHandle getPredecessorOf(InstructionHandle handle) {
if (VERIFY_INTEGRITY) {
if (!containsInstruction(handle))
throw new IllegalStateException();
}
return handle == firstInstruction ? null : handle.getPrev();
}
/**
* Add an InstructionHandle to the basic block.
*
* @param handle
* the InstructionHandle
*/
public void addInstruction(InstructionHandle handle) {
if (firstInstruction == null) {
firstInstruction = lastInstruction = handle;
} else {
if (VERIFY_INTEGRITY && handle != lastInstruction.getNext())
throw new IllegalStateException("Adding non-consecutive instruction");
lastInstruction = handle;
}
}
/**
* A forward Iterator over the instructions of a basic block. The
* duplicate() method can be used to make an exact copy of this iterator.
* Calling next() on the duplicate will not affect the original, and vice
* versa.
*/
public class InstructionIterator implements Iterator<InstructionHandle> {
private InstructionHandle next, last;
public InstructionIterator(InstructionHandle first, InstructionHandle last) {
this.next = first;
this.last = last;
}
public boolean hasNext() {
return next != null;
}
public InstructionHandle next() {
if (!hasNext())
throw new NoSuchElementException();
InstructionHandle result = next;
next = (result == last) ? null : next.getNext();
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
public InstructionIterator duplicate() {
return new InstructionIterator(next, last);
}
@Override
public boolean equals(Object o) {
if (!(o instanceof InstructionIterator))
return false;
InstructionIterator other = (InstructionIterator) o;
return this.next == other.next && this.last == other.last;
}
@Override
public int hashCode() {
int code = getBasicBlock().hashCode() * 227;
if (next != null)
code += next.getPosition() + 1;
return code;
}
private BasicBlock getBasicBlock() {
return BasicBlock.this;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("[basicBlock=");
buf.append(getBasicBlock().getLabel());
if (next != null) {
buf.append(", next=" + next);
} else if (getBasicBlock().isExceptionThrower()) {
buf.append(", check for" + getBasicBlock().getExceptionThrower());
} else {
buf.append(", end");
}
buf.append(']');
return buf.toString();
}
}
/**
* Get an Iterator over the instructions in the basic block.
*/
public InstructionIterator instructionIterator() {
return new InstructionIterator(firstInstruction, lastInstruction);
}
/**
* A reverse Iterator over the instructions in a basic block.
*/
private static class InstructionReverseIterator implements Iterator<InstructionHandle> {
private InstructionHandle next, first;
public InstructionReverseIterator(InstructionHandle last, InstructionHandle first) {
this.next = last;
this.first = first;
}
public boolean hasNext() {
return next != null;
}
public InstructionHandle next() throws NoSuchElementException {
if (!hasNext())
throw new NoSuchElementException();
InstructionHandle result = next;
next = (result == first) ? null : next.getPrev();
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* Get an Iterator over the instructions in the basic block in reverse
* order. This is useful for backwards dataflow analyses.
*/
public Iterator<InstructionHandle> instructionReverseIterator() {
return new InstructionReverseIterator(lastInstruction, firstInstruction);
}
/**
* Return true if there are no Instructions in this basic block.
*/
public boolean isEmpty() {
return firstInstruction == null;
}
public int pos() {
if (isEmpty())
return getExceptionThrower().getPosition();
return firstInstruction.getPosition();
}
/**
* Is this block an exception handler?
*/
public boolean isExceptionHandler() {
return exceptionGen != null;
}
/**
* Get CodeExceptionGen object; returns null if this basic block is not the
* entry point of an exception handler.
*
* @return the CodeExceptionGen object, or null
*/
public CodeExceptionGen getExceptionGen() {
return exceptionGen;
}
/**
* Set the CodeExceptionGen object. Marks this basic block as the entry
* point of an exception handler.
*
* @param exceptionGen
* the CodeExceptionGen object for the block
*/
public void setExceptionGen(CodeExceptionGen exceptionGen) {
this.exceptionGen = exceptionGen;
}
/**
* Return whether or not the basic block contains the given instruction.
*
* @param handle
* the instruction
* @return true if the block contains the instruction, false otherwise
*/
public boolean containsInstruction(InstructionHandle handle) {
Iterator<InstructionHandle> i = instructionIterator();
while (i.hasNext()) {
if (i.next() == handle)
return true;
}
return false;
}
/**
* Return whether or not the basic block contains the instruction with the
* given bytecode offset.
*
* @param offset
* the bytecode offset
* @return true if the block contains an instruction with the given offset,
* false if it does not
*/
public boolean containsInstructionWithOffset(int offset) {
Iterator<InstructionHandle> i = instructionIterator();
while (i.hasNext()) {
if (i.next().getPosition() == offset)
return true;
}
return false;
}
/**
* @return Returns the numNonExceptionSuccessors.
*/
int getNumNonExceptionSuccessors() {
return numNonExceptionSuccessors;
}
/**
* @param numNonExceptionSuccessors
* The numNonExceptionSuccessors to set.
*/
void setNumNonExceptionSuccessors(int numNonExceptionSuccessors) {
this.numNonExceptionSuccessors = numNonExceptionSuccessors;
}
}
// vim:ts=4
|
package com.intellij.psi.formatter.java;
import com.intellij.codeFormatting.general.FormatterUtil;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.formatter.common.AbstractBlock;
import com.intellij.psi.impl.source.SourceTreeToPsiMap;
import com.intellij.psi.impl.source.parsing.ChameleonTransforming;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.impl.source.tree.java.ClassElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlock {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.formatter.java.AbstractJavaBlock");
protected final CodeStyleSettings mySettings;
protected Indent myIndent;
protected Indent myChildIndent;
protected Alignment myChildAlignment;
protected boolean myUseChildAttributes = false;
private boolean myIsAfterClassKeyword = false;
private Wrap myAnnotationWrap = null;
public AbstractJavaBlock(final ASTNode node,
final Wrap wrap,
final Alignment alignment,
final Indent indent,
final CodeStyleSettings settings) {
super(node, wrap, alignment);
mySettings = settings;
myIndent = indent;
}
public static Block createJavaBlock(final ASTNode child,
final CodeStyleSettings settings,
final Indent indent,
Wrap wrap,
Alignment alignment) {
Indent actualIndent = indent == null ? getDefaultSubtreeIndent(child) : indent;
final IElementType elementType = child.getElementType();
if (child.getPsi() instanceof PsiWhiteSpace) {
String text = child.getText();
int start = CharArrayUtil.shiftForward(text, 0, " \t\n");
int end = CharArrayUtil.shiftBackward(text, text.length() - 1, " \t\n") + 1;
LOG.assertTrue(start < end);
return new PartialWhitespaceBlock(child, new TextRange(start + child.getStartOffset(), end + child.getStartOffset()),
wrap, alignment, actualIndent, settings);
}
if (child.getPsi() instanceof PsiClass) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings);
}
if (isBlockType(elementType)) {
return new BlockContainingJavaBlock(child, wrap, alignment, actualIndent, settings);
}
if (isStatement(child, child.getTreeParent())) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings);
}
if (child instanceof LeafElement) {
return new LeafBlock(child, wrap, alignment, actualIndent);
}
else if (isLikeExtendsList(elementType)) {
return new ExtendsListBlock(child, wrap, alignment, settings);
}
else if (elementType == ElementType.CODE_BLOCK) {
return new CodeBlockBlock(child, wrap, alignment, actualIndent, settings);
}
else if (elementType == ElementType.LABELED_STATEMENT) {
return new LabeledJavaBlock(child, wrap, alignment, actualIndent, settings);
}
else if (elementType == JavaDocElementType.DOC_COMMENT) {
return new DocCommentBlock(child, wrap, alignment, actualIndent, settings);
}
else {
return new SimpleJavaBlock(child, wrap, alignment, actualIndent, settings);
}
}
private static boolean isLikeExtendsList(final IElementType elementType) {
return elementType == ElementType.EXTENDS_LIST
|| elementType == ElementType.IMPLEMENTS_LIST
|| elementType == ElementType.THROWS_LIST;
}
private static boolean isBlockType(final IElementType elementType) {
return elementType == ElementType.SWITCH_STATEMENT
|| elementType == ElementType.FOR_STATEMENT
|| elementType == ElementType.WHILE_STATEMENT
|| elementType == ElementType.DO_WHILE_STATEMENT
|| elementType == ElementType.TRY_STATEMENT
|| elementType == ElementType.CATCH_SECTION
|| elementType == ElementType.IF_STATEMENT
|| elementType == ElementType.METHOD
|| elementType == ElementType.ARRAY_INITIALIZER_EXPRESSION
|| elementType == ElementType.CLASS_INITIALIZER
|| elementType == ElementType.SYNCHRONIZED_STATEMENT
|| elementType == ElementType.FOREACH_STATEMENT;
}
public static Block createJavaBlock(final ASTNode child, final CodeStyleSettings settings) {
return createJavaBlock(child, settings, getDefaultSubtreeIndent(child), null, null);
}
@Nullable
private static Indent getDefaultSubtreeIndent(final ASTNode child) {
final ASTNode parent = child.getTreeParent();
if (child.getElementType() == ElementType.ANNOTATION) return Indent.getNoneIndent();
final ASTNode prevElement = getPrevElement(child);
if (prevElement != null && prevElement.getElementType() == ElementType.MODIFIER_LIST) {
return Indent.getNoneIndent();
}
if (child.getElementType() == ElementType.DOC_TAG) return Indent.getNoneIndent();
if (child.getElementType() == ElementType.DOC_COMMENT_LEADING_ASTERISKS) return Indent.getSpaceIndent(1);
if (child.getPsi() instanceof PsiFile) return Indent.getNoneIndent();
if (parent != null) {
final Indent defaultChildIndent = getChildIndent(parent);
if (defaultChildIndent != null) return defaultChildIndent;
}
return null;
}
@Nullable
private static Indent getChildIndent(final ASTNode parent) {
if (parent.getElementType() == ElementType.MODIFIER_LIST) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.JSP_CODE_BLOCK) return Indent.getNormalIndent();
if (parent.getElementType() == ElementType.DUMMY_HOLDER) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.CLASS) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.IF_STATEMENT) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.TRY_STATEMENT) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.CATCH_SECTION) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.FOR_STATEMENT) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.FOREACH_STATEMENT) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.BLOCK_STATEMENT) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.DO_WHILE_STATEMENT) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.WHILE_STATEMENT) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.SWITCH_STATEMENT) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.METHOD) return Indent.getNoneIndent();
if (parent.getElementType() == JavaDocElementType.DOC_COMMENT) return Indent.getNoneIndent();
if (parent.getElementType() == JavaDocElementType.DOC_TAG) return Indent.getNoneIndent();
if (parent.getElementType() == JavaDocElementType.DOC_INLINE_TAG) return Indent.getNoneIndent();
if (parent.getElementType() == ElementType.IMPORT_LIST) return Indent.getNoneIndent();
if (SourceTreeToPsiMap.treeElementToPsi(parent) instanceof PsiFile) {
return Indent.getNoneIndent();
}
else {
return null;
}
}
public Spacing getSpacing(Block child1, Block child2) {
return new JavaSpacePropertyProcessor(AbstractJavaBlock.getTreeNode(child2), mySettings).getResult();
}
public ASTNode getFirstTreeNode() {
return myNode;
}
public Indent getIndent() {
return myIndent;
}
protected static boolean isStatement(final ASTNode child, final ASTNode parentNode) {
if (parentNode != null) {
if (parentNode.getElementType() == ElementType.CODE_BLOCK) return false;
final int role = ((CompositeElement)parentNode).getChildRole(child);
if (parentNode.getElementType() == ElementType.IF_STATEMENT) return role == ChildRole.THEN_BRANCH || role == ChildRole.ELSE_BRANCH;
if (parentNode.getElementType() == ElementType.FOR_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentNode.getElementType() == ElementType.WHILE_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentNode.getElementType() == ElementType.DO_WHILE_STATEMENT) return role == ChildRole.LOOP_BODY;
if (parentNode.getElementType() == ElementType.FOREACH_STATEMENT) return role == ChildRole.LOOP_BODY;
}
return false;
}
protected abstract List<Block> buildChildren();
@Nullable
protected Wrap createChildWrap() {
if (myNode.getElementType() == ElementType.EXTENDS_LIST || myNode.getElementType() == ElementType.IMPLEMENTS_LIST) {
return Wrap.createWrap(getWrapType(mySettings.EXTENDS_LIST_WRAP), false);
}
else if (myNode.getElementType() == ElementType.BINARY_EXPRESSION) {
Wrap actualWrap = myWrap != null ? myWrap : getReservedWrap();
if (actualWrap == null) {
return Wrap.createWrap(getWrapType(mySettings.BINARY_OPERATION_WRAP), false);
}
else {
if (!hasTheSamePriority(myNode.getTreeParent())) {
return Wrap.createChildWrap(actualWrap, getWrapType(mySettings.BINARY_OPERATION_WRAP), false);
}
else {
return actualWrap;
}
}
}
else if (myNode.getElementType() == ElementType.CONDITIONAL_EXPRESSION) {
return Wrap.createWrap(getWrapType(mySettings.TERNARY_OPERATION_WRAP), false);
}
else if (myNode.getElementType() == ElementType.ASSERT_STATEMENT) {
return Wrap.createWrap(getWrapType(mySettings.ASSERT_STATEMENT_WRAP), false);
}
else if (myNode.getElementType() == ElementType.FOR_STATEMENT) {
return Wrap.createWrap(getWrapType(mySettings.FOR_STATEMENT_WRAP), false);
}
else if (myNode.getElementType() == ElementType.THROWS_LIST) {
return Wrap.createWrap(getWrapType(mySettings.THROWS_LIST_WRAP), true);
}
else if (myNode.getElementType() == ElementType.CODE_BLOCK) {
return Wrap.createWrap(Wrap.NONE, false);
}
else if (isAssignment()) {
return Wrap.createWrap(getWrapType(mySettings.ASSIGNMENT_WRAP), true);
}
else {
return null;
}
}
private boolean isAssignment() {
return myNode.getElementType() == ElementType.ASSIGNMENT_EXPRESSION || myNode.getElementType() == ElementType.LOCAL_VARIABLE
|| myNode.getElementType() == ElementType.FIELD;
}
@Nullable
protected Alignment createChildAlignment() {
if (myNode.getElementType() == ElementType.ASSIGNMENT_EXPRESSION) {
if (myNode.getTreeParent() != null
&& myNode.getTreeParent().getElementType() == ElementType.ASSIGNMENT_EXPRESSION
&& myAlignment != null) {
return myAlignment;
}
else {
return createAlignment(mySettings.ALIGN_MULTILINE_ASSIGNMENT, null);
}
}
else if (myNode.getElementType() == ElementType.PARENTH_EXPRESSION) {
return createAlignment(mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION, null);
}
else if (myNode.getElementType() == ElementType.CONDITIONAL_EXPRESSION) {
return createAlignment(mySettings.ALIGN_MULTILINE_TERNARY_OPERATION, null);
}
else if (myNode.getElementType() == ElementType.FOR_STATEMENT) {
return createAlignment(mySettings.ALIGN_MULTILINE_FOR, null);
}
else if (myNode.getElementType() == ElementType.EXTENDS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null);
}
else if (myNode.getElementType() == ElementType.IMPLEMENTS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_EXTENDS_LIST, null);
}
else if (myNode.getElementType() == ElementType.THROWS_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_THROWS_LIST, null);
}
else if (myNode.getElementType() == ElementType.PARAMETER_LIST) {
return createAlignment(mySettings.ALIGN_MULTILINE_PARAMETERS, null);
}
else if (myNode.getElementType() == ElementType.BINARY_EXPRESSION) {
Alignment defaultAlignment = null;
if (shouldInheritAlignment()) {
defaultAlignment = myAlignment;
}
return createAlignment(mySettings.ALIGN_MULTILINE_BINARY_OPERATION, defaultAlignment);
}
else if (myNode.getElementType() == ElementType.CLASS) {
return Alignment.createAlignment();
}
else if (myNode.getElementType() == ElementType.METHOD) {
return Alignment.createAlignment();
}
else {
return null;
}
}
private boolean shouldInheritAlignment() {
if (myNode.getElementType() == ElementType.BINARY_EXPRESSION) {
final ASTNode treeParent = myNode.getTreeParent();
if (treeParent != null && treeParent.getElementType() == ElementType.BINARY_EXPRESSION) {
return hasTheSamePriority(treeParent);
}
}
return false;
}
protected ASTNode processChild(final ArrayList<Block> result,
ASTNode child,
Alignment defaultAlignment,
final Wrap defaultWrap,
final Indent childIndent) {
if (child.getElementType() == ElementType.CLASS_KEYWORD || child.getElementType() == ElementType.INTERFACE_KEYWORD) {
myIsAfterClassKeyword = true;
}
if (child.getElementType() == ElementType.METHOD_CALL_EXPRESSION) {
result.add(createMethodCallExpressiobBlock(child,
arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment)));
}
else if (child.getElementType() == ElementType.LBRACE && myNode.getElementType() == ElementType.ARRAY_INITIALIZER_EXPRESSION) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.ARRAY_INITIALIZER_WRAP), false);
child = processParenBlock(ElementType.LBRACE,
ElementType.RBRACE,
result,
child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_ARRAY_INITIALIZER_EXPRESSION);
}
else if (child.getElementType() == ElementType.LPARENTH && myNode.getElementType() == ElementType.EXPRESSION_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false);
if (mySettings.PREFER_PARAMETERS_WRAP) {
wrap.ignoreParentWraps();
}
child = processParenBlock(result,
child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
}
else if (child.getElementType() == ElementType.LPARENTH && myNode.getElementType() == ElementType.PARAMETER_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.METHOD_PARAMETERS_WRAP), false);
child = processParenBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS);
}
else if (child.getElementType() == ElementType.LPARENTH && myNode.getElementType() == ElementType.ANNOTATION_PARAMETER_LIST) {
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.CALL_PARAMETERS_WRAP), false);
child = processParenBlock(result, child,
WrappingStrategy.createDoNotWrapCommaStrategy(wrap),
mySettings.ALIGN_MULTILINE_PARAMETERS_IN_CALLS);
}
else if (child.getElementType() == ElementType.LPARENTH && myNode.getElementType() == ElementType.PARENTH_EXPRESSION) {
child = processParenBlock(result, child,
WrappingStrategy.DO_NOT_WRAP,
mySettings.ALIGN_MULTILINE_PARENTHESIZED_EXPRESSION);
}
else if (child.getElementType() == ElementType.ENUM_CONSTANT && myNode instanceof ClassElement) {
child = processEnumBlock(result, child, ((ClassElement)myNode).findEnumConstantListDelimiterPlace());
}
else if (mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE && isTernaryOperationSign(child)) {
child = processTernaryOperationRange(result, child, defaultAlignment, defaultWrap, childIndent);
}
else if (child.getElementType() == ElementType.FIELD) {
child = processField(result, child, defaultAlignment, defaultWrap, childIndent);
}
else {
final Block block =
createJavaBlock(child, mySettings, childIndent, arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment));
if (child.getElementType() == ElementType.MODIFIER_LIST && containsAnnotations(child)) {
myAnnotationWrap = Wrap.createWrap(getWrapType(getAnnotationWrapType()), true);
}
if (block instanceof AbstractJavaBlock) {
final AbstractJavaBlock javaBlock = ((AbstractJavaBlock)block);
if (myNode.getElementType() == ElementType.METHOD_CALL_EXPRESSION && child.getElementType() == ElementType.REFERENCE_EXPRESSION) {
javaBlock.setReservedWrap(getReservedWrap());
}
else if (myNode.getElementType() == ElementType.REFERENCE_EXPRESSION &&
child.getElementType() == ElementType.METHOD_CALL_EXPRESSION) {
javaBlock.setReservedWrap(getReservedWrap());
}
else if (myNode.getElementType() == ElementType.BINARY_EXPRESSION) {
javaBlock.setReservedWrap(defaultWrap);
}
else if (child.getElementType() == ElementType.MODIFIER_LIST) {
javaBlock.setReservedWrap(myAnnotationWrap);
if (!lastChildIsAnnotation(child)) {
myAnnotationWrap = null;
}
}
}
result.add(block);
}
return child;
}
private ASTNode processField(final ArrayList<Block> result, ASTNode child, final Alignment defaultAlignment, final Wrap defaultWrap,
final Indent childIndent) {
ASTNode lastFieldInGroup = findLastFieldInGroup(child);
if (lastFieldInGroup == child) {
result.add(createJavaBlock(child, getSettings(), childIndent, arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment)));
return child;
}
else {
final ArrayList<Block> localResult = new ArrayList<Block>();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
localResult.add(createJavaBlock(child, getSettings(), Indent.getContinuationWithoutFirstIndent(), arrangeChildWrap(child, defaultWrap),
arrangeChildAlignment(child, defaultAlignment)));
}
if (child == lastFieldInGroup) break;
child = child.getTreeNext();
}
if (!localResult.isEmpty()) {
result.add(new SyntheticCodeBlock(localResult, null, getSettings(), childIndent, null));
}
return lastFieldInGroup;
}
}
@NotNull private static ASTNode findLastFieldInGroup(final ASTNode child) {
final PsiTypeElement typeElement = ((PsiVariable)child.getPsi()).getTypeElement();
if (typeElement == null) return child;
ASTNode lastChildNode = child.getLastChildNode();
if (lastChildNode == null) return child;
if (lastChildNode.getElementType() == ElementType.SEMICOLON) return child;
ASTNode currentResult = child;
ASTNode currentNode = child.getTreeNext();
while (currentNode != null) {
if (currentNode.getElementType() == ElementType.WHITE_SPACE
|| currentNode.getElementType() == ElementType.COMMA
|| ElementType.COMMENT_BIT_SET.contains(currentNode.getElementType())) {
}
else if (currentNode.getElementType() == ElementType.FIELD) {
if (((PsiVariable)currentNode.getPsi()).getTypeElement() != typeElement) {
return currentResult;
}
else {
currentResult = currentNode;
}
}
else {
return currentResult;
}
currentNode = currentNode.getTreeNext();
}
return currentResult;
}
private ASTNode processTernaryOperationRange(final ArrayList<Block> result,
final ASTNode child,
final Alignment defaultAlignment,
final Wrap defaultWrap, final Indent childIndent) {
final ArrayList<Block> localResult = new ArrayList<Block>();
final Wrap wrap = arrangeChildWrap(child, defaultWrap);
final Alignment alignment = arrangeChildAlignment(child, defaultAlignment);
localResult.add(new LeafBlock(child, wrap, alignment, childIndent));
ASTNode current = child.getTreeNext();
while (current != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(current) && current.getTextLength() > 0) {
if (isTernaryOperationSign(current)) break;
current = processChild(localResult, current, defaultAlignment, defaultWrap, childIndent);
}
if (current != null) {
current = current.getTreeNext();
}
}
result.add(new SyntheticCodeBlock(localResult, alignment, getSettings(), null, wrap));
if (current == null) {
return null;
}
else {
return current.getTreePrev();
}
}
private boolean isTernaryOperationSign(final ASTNode child) {
if (myNode.getElementType() != ElementType.CONDITIONAL_EXPRESSION) return false;
final int role = ((CompositeElement)child.getTreeParent()).getChildRole(child);
return role == ChildRole.OPERATION_SIGN || role == ChildRole.COLON;
}
private Block createMethodCallExpressiobBlock(final ASTNode node, final Wrap blockWrap, final Alignment alignment) {
final ArrayList<ASTNode> nodes = new ArrayList<ASTNode>();
final ArrayList<Block> subBlocks = new ArrayList<Block>();
collectNodes(nodes, node);
final Wrap wrap = Wrap.createWrap(getWrapType(mySettings.METHOD_CALL_CHAIN_WRAP), false);
while (!nodes.isEmpty()) {
ArrayList<ASTNode> subNodes = readToNextDot(nodes);
subBlocks.add(createSynthBlock(subNodes, wrap));
}
return new SyntheticCodeBlock(subBlocks, alignment, mySettings, Indent.getContinuationWithoutFirstIndent(),
blockWrap);
}
private Block createSynthBlock(final ArrayList<ASTNode> subNodes, final Wrap wrap) {
final ArrayList<Block> subBlocks = new ArrayList<Block>();
final ASTNode firstNode = subNodes.get(0);
if (firstNode.getElementType() == ElementType.DOT) {
subBlocks.add(createJavaBlock(firstNode, getSettings(), Indent.getNoneIndent(),
null,
null));
subNodes.remove(0);
if (!subNodes.isEmpty()) {
subBlocks.add(createSynthBlock(subNodes, wrap));
}
return new SyntheticCodeBlock(subBlocks, null, mySettings, Indent.getContinuationIndent(), wrap);
}
else {
return new SyntheticCodeBlock(createJavaBlocks(subNodes), null, mySettings,
Indent.getContinuationWithoutFirstIndent(), null);
}
}
private List<Block> createJavaBlocks(final ArrayList<ASTNode> subNodes) {
final ArrayList<Block> result = new ArrayList<Block>();
for (ASTNode node : subNodes) {
result.add(createJavaBlock(node, getSettings(), Indent.getContinuationWithoutFirstIndent(), null, null));
}
return result;
}
private static ArrayList<ASTNode> readToNextDot(final ArrayList<ASTNode> nodes) {
final ArrayList<ASTNode> result = new ArrayList<ASTNode>();
result.add(nodes.remove(0));
for (Iterator<ASTNode> iterator = nodes.iterator(); iterator.hasNext();) {
ASTNode node = iterator.next();
if (node.getElementType() == ElementType.DOT) return result;
result.add(node);
iterator.remove();
}
return result;
}
private static void collectNodes(List<ASTNode> nodes, ASTNode node) {
ChameleonTransforming.transformChildren(node);
ASTNode child = node.getFirstChildNode();
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child)) {
if (child.getElementType() == ElementType.METHOD_CALL_EXPRESSION || child.getElementType() == ElementType.REFERENCE_EXPRESSION) {
collectNodes(nodes, child);
}
else {
nodes.add(child);
}
}
child = child.getTreeNext();
}
}
private static boolean lastChildIsAnnotation(final ASTNode child) {
ASTNode current = child.getLastChildNode();
while (current != null && current.getElementType() == ElementType.WHITE_SPACE) {
current = current.getTreePrev();
}
if (current == null) return false;
return current.getElementType() == ElementType.ANNOTATION;
}
private static boolean containsAnnotations(final ASTNode child) {
return ((PsiModifierList)child.getPsi()).getAnnotations().length > 0;
}
private int getAnnotationWrapType() {
if (myNode.getElementType() == ElementType.METHOD) {
return mySettings.METHOD_ANNOTATION_WRAP;
}
if (myNode.getElementType() == ElementType.CLASS) {
return mySettings.CLASS_ANNOTATION_WRAP;
}
if (myNode.getElementType() == ElementType.FIELD) {
return mySettings.FIELD_ANNOTATION_WRAP;
}
if (myNode.getElementType() == ElementType.PARAMETER) {
return mySettings.PARAMETER_ANNOTATION_WRAP;
}
if (myNode.getElementType() == ElementType.LOCAL_VARIABLE) {
return mySettings.VARIABLE_ANNOTATION_WRAP;
}
return CodeStyleSettings.DO_NOT_WRAP;
}
@Nullable
protected Alignment arrangeChildAlignment(final ASTNode child, final Alignment defaultAlignment) {
int role = ((CompositeElement)child.getTreeParent()).getChildRole(child);
if (myNode.getElementType() == ElementType.FOR_STATEMENT) {
if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) {
return defaultAlignment;
}
else {
return null;
}
}
else if (myNode.getElementType() == ElementType.EXTENDS_LIST || myNode.getElementType() == ElementType.IMPLEMENTS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST || role == ChildRole.IMPLEMENTS_KEYWORD) {
return defaultAlignment;
}
else {
return null;
}
}
else if (myNode.getElementType() == ElementType.THROWS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST) {
return defaultAlignment;
}
else {
return null;
}
}
else if (myNode.getElementType() == ElementType.CLASS) {
if (role == ChildRole.CLASS_OR_INTERFACE_KEYWORD) return defaultAlignment;
if (myIsAfterClassKeyword) return null;
if (role == ChildRole.MODIFIER_LIST) return defaultAlignment;
if (role == ChildRole.DOC_COMMENT) return defaultAlignment;
return null;
}
else if (myNode.getElementType() == ElementType.METHOD) {
if (role == ChildRole.MODIFIER_LIST) return defaultAlignment;
if (role == ChildRole.TYPE) return defaultAlignment;
return null;
}
else if (myNode.getElementType() == ElementType.ASSIGNMENT_EXPRESSION) {
if (role == ChildRole.LOPERAND) return defaultAlignment;
if (role == ChildRole.ROPERAND && child.getElementType() == ElementType.ASSIGNMENT_EXPRESSION) {
return defaultAlignment;
}
else {
return null;
}
}
else {
return defaultAlignment;
}
}
/*
private boolean isAfterClassKeyword(final ASTNode child) {
ASTNode treePrev = child.getTreePrev();
while (treePrev != null) {
if (treePrev.getElementType() == ElementType.CLASS_KEYWORD ||
treePrev.getElementType() == ElementType.INTERFACE_KEYWORD) {
return true;
}
treePrev = treePrev.getTreePrev();
}
return false;
}
*/
private static Alignment createAlignment(final boolean alignOption, final Alignment defaultAlignment) {
return alignOption ?
(createAlignmentOrDefault(defaultAlignment)) : defaultAlignment;
}
@Nullable
protected Wrap arrangeChildWrap(final ASTNode child, Wrap defaultWrap) {
if (myAnnotationWrap != null) {
try {
return myAnnotationWrap;
}
finally {
myAnnotationWrap = null;
}
}
final ASTNode parent = child.getTreeParent();
int role = ((CompositeElement)parent).getChildRole(child);
if (myNode.getElementType() == ElementType.BINARY_EXPRESSION) {
if (role == ChildRole.OPERATION_SIGN && !mySettings.BINARY_OPERATION_SIGN_ON_NEXT_LINE) return null;
if (role == ChildRole.ROPERAND && mySettings.BINARY_OPERATION_SIGN_ON_NEXT_LINE) return null;
return defaultWrap;
}
else if (child.getElementType() == ElementType.EXTENDS_LIST || child.getElementType() == ElementType.IMPLEMENTS_LIST) {
return Wrap.createWrap(getWrapType(mySettings.EXTENDS_KEYWORD_WRAP), true);
}
else if (child.getElementType() == ElementType.THROWS_LIST) {
return Wrap.createWrap(getWrapType(mySettings.THROWS_KEYWORD_WRAP), true);
}
else if (myNode.getElementType() == ElementType.EXTENDS_LIST || myNode.getElementType() == ElementType.IMPLEMENTS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST) {
return defaultWrap;
}
else {
return null;
}
}
else if (myNode.getElementType() == ElementType.THROWS_LIST) {
if (role == ChildRole.REFERENCE_IN_LIST) {
return defaultWrap;
}
else {
return null;
}
}
else if (myNode.getElementType() == ElementType.CONDITIONAL_EXPRESSION) {
if (role == ChildRole.COLON && !mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null;
if (role == ChildRole.QUEST && !mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null;
if (role == ChildRole.THEN_EXPRESSION && mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null;
if (role == ChildRole.ELSE_EXPRESSION && mySettings.TERNARY_OPERATION_SIGNS_ON_NEXT_LINE) return null;
return defaultWrap;
}
else if (isAssignment()) {
if (role == ChildRole.INITIALIZER_EQ && mySettings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE) return defaultWrap;
if (role == ChildRole.OPERATION_SIGN && mySettings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE) return defaultWrap;
if (role == ChildRole.INITIALIZER && !mySettings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE) return defaultWrap;
if (role == ChildRole.ROPERAND && !mySettings.PLACE_ASSIGNMENT_SIGN_ON_NEXT_LINE) return defaultWrap;
return null;
}
else if (myNode.getElementType() == ElementType.REFERENCE_EXPRESSION) {
if (role == ChildRole.DOT) {
return getReservedWrap();
}
else {
return defaultWrap;
}
}
else if (myNode.getElementType() == ElementType.FOR_STATEMENT) {
if (role == ChildRole.FOR_INITIALIZATION || role == ChildRole.CONDITION || role == ChildRole.FOR_UPDATE) {
return defaultWrap;
}
if (role == ChildRole.LOOP_BODY) {
return Wrap.createWrap(WrapType.NORMAL, true);
}
else {
return null;
}
}
else if (myNode.getElementType() == ElementType.METHOD) {
if (role == ChildRole.THROWS_LIST) {
return defaultWrap;
}
else {
return null;
}
}
else if (myNode.getElementType() == ElementType.MODIFIER_LIST) {
if (child.getElementType() == ElementType.ANNOTATION) {
return getReservedWrap();
}
ASTNode prevElement = getPrevElement(child);
if (prevElement != null && prevElement.getElementType() == ElementType.ANNOTATION) {
return getReservedWrap();
}
else {
return null;
}
}
else if (myNode.getElementType() == ElementType.ASSERT_STATEMENT) {
if (role == ChildRole.CONDITION) {
return defaultWrap;
}
if (role == ChildRole.ASSERT_DESCRIPTION && !mySettings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE) {
return defaultWrap;
}
if (role == ChildRole.COLON && mySettings.ASSERT_STATEMENT_COLON_ON_NEXT_LINE) {
return defaultWrap;
}
return null;
}
else if (myNode.getElementType() == ElementType.CODE_BLOCK) {
if (role == ChildRole.STATEMENT_IN_BLOCK) {
return defaultWrap;
}
else {
return null;
}
}
else if (myNode.getElementType() == ElementType.IF_STATEMENT) {
if (role == ChildRole.THEN_BRANCH || role == ChildRole.ELSE_BRANCH) {
if (child.getElementType() == ElementType.BLOCK_STATEMENT) {
return null;
}
else {
return Wrap.createWrap(WrapType.NORMAL, true);
}
}
}
else if (myNode.getElementType() == ElementType.FOREACH_STATEMENT || myNode.getElementType() == ElementType.WHILE_STATEMENT) {
if (role == ChildRole.LOOP_BODY) {
if (child.getElementType() == ElementType.BLOCK_STATEMENT) {
return null;
}
else {
return Wrap.createWrap(WrapType.NORMAL, true);
}
}
}
else if (myNode.getElementType() == ElementType.DO_WHILE_STATEMENT) {
if (role == ChildRole.LOOP_BODY) {
return Wrap.createWrap(WrapType.NORMAL, true);
} else if (role == ChildRole.WHILE_KEYWORD) {
return Wrap.createWrap(WrapType.NORMAL, true);
}
}
return defaultWrap;
}
private static ASTNode getPrevElement(final ASTNode child) {
ASTNode result = child.getTreePrev();
while (result != null && result.getElementType() == ElementType.WHITE_SPACE) {
result = result.getTreePrev();
}
return result;
}
private boolean hasTheSamePriority(final ASTNode node) {
if (node == null) return false;
if (node.getElementType() != ElementType.BINARY_EXPRESSION) {
return false;
}
else {
final PsiBinaryExpression expr1 = (PsiBinaryExpression)SourceTreeToPsiMap.treeElementToPsi(myNode);
final PsiBinaryExpression expr2 = (PsiBinaryExpression)SourceTreeToPsiMap.treeElementToPsi(node);
final PsiJavaToken op1 = expr1.getOperationSign();
final PsiJavaToken op2 = expr2.getOperationSign();
return op1.getTokenType() == op2.getTokenType();
}
}
protected static WrapType getWrapType(final int wrap) {
switch (wrap) {
case CodeStyleSettings.WRAP_ALWAYS:
return WrapType.ALWAYS;
case CodeStyleSettings.WRAP_AS_NEEDED:
return WrapType.NORMAL;
case CodeStyleSettings.DO_NOT_WRAP:
return WrapType.NONE;
default:
return WrapType.CHOP_DOWN_IF_LONG;
}
}
private ASTNode processParenBlock(List<Block> result,
ASTNode child,
WrappingStrategy wrappingStrategy,
final boolean doAlign) {
myUseChildAttributes = true;
final IElementType from = ElementType.LPARENTH;
final IElementType to = ElementType.RPARENTH;
return processParenBlock(from, to, result, child, wrappingStrategy, doAlign);
}
private ASTNode processParenBlock(final IElementType from,
final IElementType to, final List<Block> result, ASTNode child,
final WrappingStrategy wrappingStrategy, final boolean doAlign
) {
final Indent externalIndent = Indent.getNoneIndent();
final Indent internalIndent = Indent.getContinuationIndent();
AlignmentStrategy alignmentStrategy = AlignmentStrategy.createDoNotAlingCommaStrategy(createAlignment(doAlign, null));
setChildIndent(internalIndent);
setChildAlignment(alignmentStrategy.getAlignment(null));
boolean isAfterIncomplete = false;
ASTNode prev = child;
while (child != null) {
isAfterIncomplete = isAfterIncomplete || child.getElementType() == ElementType.ERROR_ELEMENT ||
child.getElementType() == ElementType.EMPTY_EXPRESSION;
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
if (child.getElementType() == from) {
result.add(createJavaBlock(child, mySettings, externalIndent, null, null));
}
else if (child.getElementType() == to) {
result.add(createJavaBlock(child, mySettings,
isAfterIncomplete ? internalIndent : externalIndent,
null,
isAfterIncomplete ? alignmentStrategy.getAlignment(null) : null));
return child;
}
else {
final IElementType elementType = child.getElementType();
result.add(createJavaBlock(child, mySettings, internalIndent,
wrappingStrategy.getWrap(elementType),
alignmentStrategy.getAlignment(elementType)));
if (to == null) {//process only one statement
return child;
}
}
isAfterIncomplete = false;
}
prev = child;
child = child.getTreeNext();
}
return prev;
}
@Nullable
private ASTNode processEnumBlock(List<Block> result,
ASTNode child,
ASTNode last) {
final WrappingStrategy wrappingStrategy = WrappingStrategy.createDoNotWrapCommaStrategy(Wrap
.createWrap(getWrapType(mySettings.ENUM_CONSTANTS_WRAP), true));
while (child != null) {
if (!FormatterUtil.containsWhiteSpacesOnly(child) && child.getTextLength() > 0) {
result.add(createJavaBlock(child, mySettings, Indent.getNormalIndent(),
wrappingStrategy.getWrap(child.getElementType()), null));
if (child == last) return child;
}
child = child.getTreeNext();
}
return null;
}
private void setChildAlignment(final Alignment alignment) {
myChildAlignment = alignment;
}
private void setChildIndent(final Indent internalIndent) {
myChildIndent = internalIndent;
}
private static Alignment createAlignmentOrDefault(final Alignment defaultAlignment) {
return defaultAlignment == null ? Alignment.createAlignment() : defaultAlignment;
}
private int getBraceStyle() {
final PsiElement psiNode = SourceTreeToPsiMap.treeElementToPsi(myNode);
if (psiNode instanceof PsiClass) {
return mySettings.CLASS_BRACE_STYLE;
}
else if (psiNode instanceof PsiMethod) {
return mySettings.METHOD_BRACE_STYLE;
}
else if (psiNode instanceof PsiCodeBlock && psiNode.getParent() != null && psiNode.getParent() instanceof PsiMethod) {
return mySettings.METHOD_BRACE_STYLE;
}
else {
return mySettings.BRACE_STYLE;
}
}
protected Indent getCodeBlockInternalIndent(final int baseChildrenIndent) {
if (isTopLevelClass() && mySettings.DO_NOT_INDENT_TOP_LEVEL_CLASS_MEMBERS) {
return Indent.getNoneIndent();
}
final int braceStyle = getBraceStyle();
return braceStyle == CodeStyleSettings.NEXT_LINE_SHIFTED ?
createNormalIndent(baseChildrenIndent - 1)
: createNormalIndent(baseChildrenIndent);
}
protected static Indent createNormalIndent(final int baseChildrenIndent) {
if (baseChildrenIndent == 1) {
return Indent.getNormalIndent();
}
else if (baseChildrenIndent <= 0) {
return Indent.getNoneIndent();
}
else {
LOG.assertTrue(false);
return Indent.getNormalIndent();
}
}
private boolean isTopLevelClass() {
if (myNode.getElementType() != ElementType.CLASS) return false;
return SourceTreeToPsiMap.treeElementToPsi(myNode.getTreeParent()) instanceof PsiFile;
}
protected Indent getCodeBlockExternalIndent() {
final int braceStyle = getBraceStyle();
if (braceStyle == CodeStyleSettings.END_OF_LINE || braceStyle == CodeStyleSettings.NEXT_LINE ||
braceStyle == CodeStyleSettings.NEXT_LINE_IF_WRAPPED) {
return Indent.getNoneIndent();
}
else {
return Indent.getNormalIndent();
}
}
protected abstract Wrap getReservedWrap();
protected abstract void setReservedWrap(final Wrap reservedWrap);
@Nullable
protected static ASTNode getTreeNode(final Block child2) {
if (child2 instanceof JavaBlock) {
return ((JavaBlock)child2).getFirstTreeNode();
}
else if (child2 instanceof LeafBlock) {
return ((LeafBlock)child2).getTreeNode();
}
else {
return null;
}
}
@Override
@NotNull
public ChildAttributes getChildAttributes(final int newChildIndex) {
if (myUseChildAttributes) {
return new ChildAttributes(myChildIndent, myChildAlignment);
}
else if (isAfter(newChildIndex, new IElementType[]{JavaDocElementType.DOC_COMMENT})) {
return new ChildAttributes(Indent.getNoneIndent(), myChildAlignment);
}
else {
return super.getChildAttributes(newChildIndex);
}
}
@Nullable
protected Indent getChildIndent() {
return getChildIndent(myNode);
}
public CodeStyleSettings getSettings() {
return mySettings;
}
protected boolean isAfter(final int newChildIndex, final IElementType[] elementTypes) {
if (newChildIndex == 0) return false;
final Block previousBlock = getSubBlocks().get(newChildIndex - 1);
if (!(previousBlock instanceof AbstractBlock)) return false;
final IElementType previousElementType = ((AbstractBlock)previousBlock).getNode().getElementType();
for (IElementType elementType : elementTypes) {
if (previousElementType == elementType) return true;
}
return false;
}
protected Alignment getUsedAlignment(final int newChildIndex) {
final List<Block> subBlocks = getSubBlocks();
for (int i = 0; i < newChildIndex; i++) {
if (i >= subBlocks.size()) return null;
final Block block = subBlocks.get(i);
final Alignment alignment = block.getAlignment();
if (alignment != null) return alignment;
}
return null;
}
}
|
package core.framework.api.redis;
import core.framework.api.log.ActionLogContext;
import core.framework.api.util.StopWatch;
import core.framework.impl.resource.Pool;
import core.framework.impl.resource.PoolItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.exceptions.JedisConnectionException;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author neo
*/
public final class Redis {
private final Logger logger = LoggerFactory.getLogger(Redis.class);
private final String host;
public final Pool<Jedis> pool;
public long slowQueryThresholdInMs = 100;
public Duration timeout = Duration.ofSeconds(2);
public Redis(String host) {
this.host = host;
pool = new Pool<>(this::createRedis, Jedis::close);
pool.name("redis");
pool.configure(5, 50, Duration.ofMinutes(30));
}
private Jedis createRedis() {
Jedis jedis = new Jedis(host, Protocol.DEFAULT_PORT, (int) timeout.toMillis());
jedis.connect();
return jedis;
}
public void shutdown() {
logger.info("shutdown redis client, host={}", host);
pool.close();
}
public String get(String key) {
StopWatch watch = new StopWatch();
PoolItem<Jedis> item = pool.borrowItem();
try {
return item.resource.get(key);
} catch (JedisConnectionException e) {
item.broken = true;
throw e;
} finally {
pool.returnItem(item);
long elapsedTime = watch.elapsedTime();
ActionLogContext.track("redis", elapsedTime);
logger.debug("get, key={}, elapsedTime={}", key, elapsedTime);
checkSlowQuery(elapsedTime);
}
}
public void set(String key, String value) {
StopWatch watch = new StopWatch();
PoolItem<Jedis> item = pool.borrowItem();
try {
item.resource.set(key, value);
} catch (JedisConnectionException e) {
item.broken = true;
throw e;
} finally {
pool.returnItem(item);
long elapsedTime = watch.elapsedTime();
ActionLogContext.track("redis", elapsedTime);
logger.debug("set, key={}, value={}, elapsedTime={}", key, value, elapsedTime);
checkSlowQuery(elapsedTime);
}
}
public void expire(String key, Duration duration) {
StopWatch watch = new StopWatch();
PoolItem<Jedis> item = pool.borrowItem();
try {
item.resource.expire(key, (int) duration.getSeconds());
} catch (JedisConnectionException e) {
item.broken = true;
throw e;
} finally {
pool.returnItem(item);
long elapsedTime = watch.elapsedTime();
ActionLogContext.track("redis", elapsedTime);
logger.debug("expire, key={}, duration={}, elapsedTime={}", key, duration, elapsedTime);
checkSlowQuery(elapsedTime);
}
}
public void setExpire(String key, String value, Duration duration) {
StopWatch watch = new StopWatch();
PoolItem<Jedis> item = pool.borrowItem();
try {
item.resource.setex(key, (int) duration.getSeconds(), value);
} catch (JedisConnectionException e) {
item.broken = true;
throw e;
} finally {
pool.returnItem(item);
long elapsedTime = watch.elapsedTime();
ActionLogContext.track("redis", elapsedTime);
logger.debug("setExpire, key={}, value={}, duration={}, elapsedTime={}", key, value, duration, elapsedTime);
checkSlowQuery(elapsedTime);
}
}
public void del(String... keys) {
StopWatch watch = new StopWatch();
PoolItem<Jedis> item = pool.borrowItem();
try {
item.resource.del(keys);
} catch (JedisConnectionException e) {
item.broken = true;
throw e;
} finally {
pool.returnItem(item);
long elapsedTime = watch.elapsedTime();
ActionLogContext.track("redis", elapsedTime);
logger.debug("del, keys={}, elapsedTime={}", keys, elapsedTime);
checkSlowQuery(elapsedTime);
}
}
public Map<String, String> hgetAll(String key) {
StopWatch watch = new StopWatch();
PoolItem<Jedis> item = pool.borrowItem();
try {
return item.resource.hgetAll(key);
} catch (JedisConnectionException e) {
item.broken = true;
throw e;
} finally {
pool.returnItem(item);
long elapsedTime = watch.elapsedTime();
ActionLogContext.track("redis", elapsedTime);
logger.debug("hgetAll, key={}, elapsedTime={}", key, elapsedTime);
checkSlowQuery(elapsedTime);
}
}
public void hmset(String key, Map<String, String> value) {
StopWatch watch = new StopWatch();
PoolItem<Jedis> item = pool.borrowItem();
try {
item.resource.hmset(key, value);
} catch (JedisConnectionException e) {
item.broken = true;
throw e;
} finally {
pool.returnItem(item);
long elapsedTime = watch.elapsedTime();
ActionLogContext.track("redis", elapsedTime);
logger.debug("hmset, key={}, value={}, elapsedTime={}", key, value, elapsedTime);
checkSlowQuery(elapsedTime);
}
}
public Set<String> keys(String pattern) {
StopWatch watch = new StopWatch();
PoolItem<Jedis> item = pool.borrowItem();
try {
return item.resource.keys(pattern);
} catch (JedisConnectionException e) {
item.broken = true;
throw e;
} finally {
pool.returnItem(item);
long elapsedTime = watch.elapsedTime();
ActionLogContext.track("redis", elapsedTime);
logger.debug("keys, pattern={}, elapsedTime={}", pattern, elapsedTime);
checkSlowQuery(elapsedTime);
}
}
public void lpush(String key, String value) {
StopWatch watch = new StopWatch();
PoolItem<Jedis> item = pool.borrowItem();
try {
item.resource.lpush(key, value);
} catch (JedisConnectionException e) {
item.broken = true;
throw e;
} finally {
pool.returnItem(item);
long elapsedTime = watch.elapsedTime();
ActionLogContext.track("redis", elapsedTime);
logger.debug("lpush, key={}, value={}, elapsedTime={}", key, value, elapsedTime);
checkSlowQuery(elapsedTime);
}
}
// blocking right pop
public String brpop(String key) {
StopWatch watch = new StopWatch();
PoolItem<Jedis> item = pool.borrowItem();
try {
List<String> result = item.resource.brpop(key, "0");
return result.get(1); // result[0] is key, result[1] is popped value
} catch (JedisConnectionException e) {
item.broken = true;
throw e;
} finally {
pool.returnItem(item);
long elapsedTime = watch.elapsedTime();
ActionLogContext.track("redis", elapsedTime);
logger.debug("brpop, key={}, elapsedTime={}", key, elapsedTime);
}
}
private void checkSlowQuery(long elapsedTime) {
if (elapsedTime > slowQueryThresholdInMs) {
logger.warn("slow query detected");
}
}
}
|
package txtfnnl.pipelines;
import org.apache.commons.cli.*;
import org.apache.uima.UIMAException;
import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.resource.ExternalResourceDescription;
import org.apache.uima.resource.ResourceInitializationException;
import txtfnnl.uima.ConfigurationBuilder;
import txtfnnl.uima.analysis_component.*;
import txtfnnl.uima.analysis_component.opennlp.SentenceAnnotator;
import txtfnnl.uima.analysis_component.opennlp.TokenAnnotator;
import txtfnnl.uima.collection.AnnotationLineWriter;
import txtfnnl.uima.collection.OutputWriter;
import txtfnnl.uima.collection.XmiWriter;
import txtfnnl.uima.resource.*;
import java.io.*;
import java.util.LinkedList;
import java.util.logging.Logger;
public
class GeneNormalization extends Pipeline {
static final String DEFAULT_DATABASE = "gnamed";
static final String DEFAULT_JDBC_DRIVER = "org.postgresql.Driver";
static final String DEFAULT_DB_PROVIDER = "postgresql";
// default: all known gene and protein symbols
static final String SQL_QUERY = "SELECT g.id, g.species_id, ps.value FROM genes AS g " +
"INNER JOIN genes2proteins AS g2p ON (g.id = g2p.gene_id) " +
"INNER JOIN protein_strings AS ps ON (g2p.protein_id = ps.id) " +
"WHERE ps.cat = 'symbol' " +
"UNION SELECT g.id, g.species_id, gs.value FROM genes AS g " +
"INNER JOIN gene_strings AS gs USING (id) WHERE gs.cat = 'symbol' ";
private
GeneNormalization() {
throw new AssertionError("n/a");
}
public static
void main(String[] arguments) {
final CommandLineParser parser = new PosixParser();
final Options opts = new Options();
final String geneAnnotationNamespace = "gene";
CommandLine cmd = null;
// standard pipeline options
Pipeline.addLogHelpAndInputOptions(opts);
Pipeline.addTikaOptions(opts);
Pipeline.addJdbcResourceOptions(
opts, DEFAULT_JDBC_DRIVER, DEFAULT_DB_PROVIDER, DEFAULT_DATABASE
);
Pipeline.addOutputOptions(opts);
Pipeline.addSentenceAnnotatorOptions(opts);
// tokenizer options setup
opts.addOption(
"G", "genia", true, "use GENIA (with the dir containing 'morphdic/') instead of OpenNLP"
);
// query options
opts.addOption("Q", "query", true, "SQL query that produces gene ID, tax ID, name triplets");
// gazetteer matching options
opts.addOption("boundary", false, "disable matching names at token boundaries only");
opts.addOption("expansions", false, "do not allow list expansions ('gene A-Z')");
opts.addOption(
"mapgreek", false, "do not map Greek letter names ('alpha' -> '\u03b1')"
);
opts.addOption(
"separators", false, "do not allow variable token-separators ('', '-', and ' ')"
);
opts.addOption("idmatch", false, "do not match the IDs of the genes themselves");
// gene annotator options
opts.addOption("f", "filter-matches", true, "a blacklist (file) of exact matches");
opts.addOption(
"F", "whitelist-matches", false, "invert filter matches to behave as a whitelist"
);
opts.addOption(
"c", "cutoff-similarity", true, "min. string similarity required to annotate [0.0]"
);
// filter options
opts.addOption("p", "pos-tags", true, "a whitelist (file) of required PoS tags");
opts.addOption("t", "filter-tokens", true, "a two-column (file) list of filter matches");
opts.addOption("T", "whitelist-tokens", false, "invert token filter to behave as a whitelist");
// species mapping option
opts.addOption(
"l", "linnaeus", true,
"set a Linnaeus property file path to use Linnaeus for species normalization"
);
opts.addOption(
"L", "species-map", true,
"a map of taxonomic IDs to another, applied to both gene and species anntoations"
);
try {
cmd = parser.parse(opts, arguments);
} catch (final ParseException e) {
System.err.println(e.getLocalizedMessage());
System.exit(1); // == EXIT ==
}
final Logger l = Pipeline.loggingSetup(
cmd, opts, "txtfnnl norm [options] <directory|files...>\n"
);
// (GENIA) tokenizer
final File geniaDir = cmd.getOptionValue('G') == null ? null : new File(
cmd.getOptionValue('G')
);
// DB query used to fetch the gazetteer's entities
final String querySql = cmd.hasOption('Q') ? cmd.getOptionValue('Q') : SQL_QUERY;
// DB gazetteer resource setup
final String dbUrl = Pipeline.getJdbcUrl(cmd, l, DEFAULT_DB_PROVIDER, DEFAULT_DATABASE);
String dbDriverClassName = null;
try {
dbDriverClassName = Pipeline.getJdbcDriver(cmd, DEFAULT_JDBC_DRIVER);
} catch (final ClassNotFoundException e) {
System.err.println("JDBC driver class unknown:");
System.err.println(e.toString());
System.exit(1); // == EXIT ==
}
GnamedGazetteerResource.Builder gazetteer = null;
// create builder
gazetteer = GnamedGazetteerResource.configure(dbUrl, dbDriverClassName, querySql);
if (!cmd.hasOption("boundary")) gazetteer.boundaryMatch();
if (cmd.hasOption("expansions")) gazetteer.disableExpansions();
if (cmd.hasOption("mapgreek")) gazetteer.disableGreekMapping();
if (!cmd.hasOption("separators")) gazetteer.generateVariants();
if (!cmd.hasOption("idmatch")) gazetteer.idMatching();
Pipeline.configureAuthentication(cmd, gazetteer);
// Taxon ID mapping resource
ExternalResourceDescription taxIdMap = null;
if (cmd.hasOption('L')) {
try {
taxIdMap = QualifiedStringResource.configure("file:" + cmd.getOptionValue('L')).create();
} catch (ResourceInitializationException e) {
l.severe(e.toString());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
System.exit(1); // == EXIT ==
}
}
// Gene Annotator setup
GeneAnnotator.Builder geneAnnotator = null;
try {
geneAnnotator = GeneAnnotator.configure(geneAnnotationNamespace, gazetteer.create());
} catch (ResourceInitializationException e) {
l.severe(e.toString());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
System.exit(1); // == EXIT ==
}
double cutoff = cmd.hasOption('c') ? Double.parseDouble(cmd.getOptionValue('c')) : 0.0;
String[] blacklist = cmd.hasOption('f') ? makeList(cmd.getOptionValue('f'), l) : null;
geneAnnotator.setTextNamespace(SentenceAnnotator.NAMESPACE).setTextIdentifier(
SentenceAnnotator.IDENTIFIER
).setMinimumSimilarity(cutoff);
geneAnnotator.setTaxIdMappingResource(taxIdMap);
if (blacklist != null) {
if (cmd.hasOption('F')) geneAnnotator.setWhitelist(blacklist);
else geneAnnotator.setBlacklist(blacklist);
}
// Linnaeus setup
ConfigurationBuilder<AnalysisEngineDescription> linnaeus;
if (cmd.hasOption('l')) {
linnaeus = LinnaeusAnnotator.configure(new File(cmd.getOptionValue('l')))
.setIdMappingResource(taxIdMap);
geneAnnotator.setTaxaAnnotatorUri(LinnaeusAnnotator.URI);
geneAnnotator.setTaxaNamespace(LinnaeusAnnotator.DEFAULT_NAMESPACE);
} else {
linnaeus = NOOPAnnotator.configure();
}
// Token Surrounding Filter setup
ConfigurationBuilder<AnalysisEngineDescription> filterSurrounding;
if (cmd.hasOption('p') || cmd.hasOption('t')) {
TokenBasedSemanticAnnotationFilter.Builder tokenFilter = TokenBasedSemanticAnnotationFilter
.configure();
if (cmd.hasOption('p')) tokenFilter.setPosTags(makeList(cmd.getOptionValue('p'), l));
if (cmd.hasOption('t')) {
if (cmd.hasOption('T')) tokenFilter.whitelist();
try {
tokenFilter.setSurroundingTokens(
QualifiedStringSetResource.configure(
"file:" + cmd.getOptionValue('t')
).create()
);
} catch (ResourceInitializationException e) {
l.severe(e.toString());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
System.exit(1); // == EXIT ==
}
}
tokenFilter.setAnnotatorUri(GeneAnnotator.URI);
tokenFilter.setNamespace(geneAnnotationNamespace);
filterSurrounding = tokenFilter;
} else {
// no filter parameters have been specified - nothing to do
filterSurrounding = NOOPAnnotator.configure();
}
// Gene ID mapping setup
GnamedRefAnnotator.Builder entityMapper = null;
try {
entityMapper = GnamedRefAnnotator.configure(
JdbcConnectionResourceImpl.configure(dbUrl, dbDriverClassName).create()
);
} catch (ResourceInitializationException e) {
l.severe(e.toString());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
System.exit(1); // == EXIT ==
}
entityMapper.setAnnotatorUri(GeneAnnotator.URI);
// output
OutputWriter.Builder writer;
if (Pipeline.rawXmi(cmd)) {
writer = Pipeline.configureWriter(
cmd, XmiWriter.configure(Pipeline.ensureOutputDirectory(cmd))
);
} else {
writer = Pipeline.configureWriter(cmd, AnnotationLineWriter.configure())
.setAnnotatorUri(GeneAnnotator.URI)
.setAnnotationNamespace(geneAnnotationNamespace).printSurroundings()
.printPosTag();
}
// Gene Ranking setup
ConfigurationBuilder<AnalysisEngineDescription> ranker;
if (cmd.hasOption("rankermodel")) {
try {
GeneRankAnnotator.Builder geneRanker = GeneRankAnnotator
.configure(RankLibRanker.configure("file:" + cmd.getOptionValue("rankermodel")).create());
geneRanker.setGeneLinkCounts(CounterResource.configure("file:" + cmd.getOptionValue("generefs")).create());
geneRanker.setGeneSymbolCounts(StringCounterResource.configure("file" + cmd.getOptionValue("genesymbols")).create());
geneRanker.setSymbolCounts(CounterResource.configure("file:" + cmd.getOptionValue("symbols")).create());
geneRanker.setNamespace(geneAnnotationNamespace);
geneRanker.setAnnotatorUri(GeneAnnotator.URI);
geneRanker.setTaxaAnnotatorUri(LinnaeusAnnotator.URI);
ranker = geneRanker;
} catch (ResourceInitializationException e) {
ranker = null;
l.severe(e.toString());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
System.exit(1); // == EXIT ==
}
} else {
ranker = NOOPAnnotator.configure();
}
try {
// 0:tika, 1:splitter, 2:tokenizer, 3:linnaeus, 4:gazetteer, 5:filter, 6: mapIDs, 7: rank
final Pipeline gn = new Pipeline(8);
gn.setReader(cmd);
gn.configureTika(cmd);
gn.set(1, Pipeline.textEngine(Pipeline.getSentenceAnnotator(cmd)));
if (geniaDir == null) {
gn.set(2, Pipeline.textEngine(TokenAnnotator.configure().create()));
} else {
GeniaTaggerAnnotator.Builder tagger = GeniaTaggerAnnotator.configure();
tagger.setDirectory(geniaDir);
gn.set(2, Pipeline.textEngine(tagger.create()));
}
gn.set(3, Pipeline.textEngine(linnaeus.create()));
gn.set(4, Pipeline.textEngine(geneAnnotator.create()));
gn.set(5, Pipeline.textEngine(filterSurrounding.create()));
gn.set(6, Pipeline.textEngine(entityMapper.create()));
gn.set(7, Pipeline.textEngine(ranker.create()));
gn.setConsumer(Pipeline.textEngine(writer.create()));
gn.run();
gn.destroy();
} catch (final UIMAException e) {
l.severe(e.toString());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
System.exit(1); // == EXIT ==
} catch (final IOException e) {
l.severe(e.toString());
System.err.println(e.getLocalizedMessage());
e.printStackTrace();
System.exit(1); // == EXIT ==
}
System.exit(0);
}
private static
String[] makeList(String filename, final Logger l) {
String[] theList;
BufferedReader reader;
LinkedList<String> list = new LinkedList<String>();
String line;
int idx = 0;
try {
reader = new BufferedReader(new FileReader(new File(filename)));
while ((line = reader.readLine()) != null) list.add(line);
} catch (FileNotFoundException e) {
l.severe(e.toString());
System.err.println(e.getLocalizedMessage());
System.exit(1); // == EXIT ==
} catch (IOException e) {
l.severe(e.toString());
System.err.println(e.getLocalizedMessage());
System.exit(1); // == EXIT ==
}
theList = new String[list.size()];
for (String name : list)
theList[idx++] = name;
return theList;
}
}
|
package net.cserny.videosmover;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import net.cserny.videosmover.controller.MainController;
import net.cserny.videosmover.error.GlobalExceptionCatcher;
import net.cserny.videosmover.helper.InMemoryVideoFileSystemInitializer;
import net.cserny.videosmover.model.Video;
import net.cserny.videosmover.provider.MainStageProvider;
import net.cserny.videosmover.service.ScanService;
import net.cserny.videosmover.service.VideoMover;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.testfx.framework.junit.ApplicationTest;
import javax.annotation.PostConstruct;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Mockito.verify;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationConfig.class)
public class MainUserInterfaceTest extends ApplicationTest {
private InMemoryVideoFileSystemInitializer videoFileSystemInitializer;
@Autowired
private ConfigurableApplicationContext context;
@SpyBean
private ScanService scanService;
@SpyBean
private VideoMover videoMover;
@SpyBean
private MainController mainController;
@PostConstruct
public void initFilesystem() {
videoFileSystemInitializer = new InMemoryVideoFileSystemInitializer();
}
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
loader.setControllerFactory(context::getBean);
stage.setScene(new Scene(loader.load()));
stage.setTitle(MainApplication.TITLE);
stage.setResizable(false);
stage.getIcons().add(new Image(getClass().getResourceAsStream("/images/application.png")));
stage.centerOnScreen();
stage.show();
Thread.setDefaultUncaughtExceptionHandler(context.getBean(GlobalExceptionCatcher.class));
context.getBean(MainStageProvider.class).setStage(stage);
}
@BeforeClass
public static void setupHeadlessMode() {
if (!Boolean.getBoolean("headless")) {
System.setProperty("testfx.robot", "glass");
System.setProperty("testfx.headless", "true");
System.setProperty("prism.order", "sw");
System.setProperty("prism.text", "t2k");
System.setProperty("java.awt.headless", "true");
}
}
@Before
public void setUp() throws Exception {
videoFileSystemInitializer.setUp();
}
@After
public void tearDown() throws Exception {
videoFileSystemInitializer.tearDown();
}
@Test
public void whenSearchButtonThenRunScanService() throws Exception {
clickOn("#scanButton");
verify(scanService).scan(any(String.class));
}
@Test
public void whenMoveVideoThenVideoMover() throws Exception {
clickOn("#scanButton");
Thread.sleep(250);
Node movieCheckOnFirstRow = lookup("#tableView").lookup(".table-row-cell").nth(0).lookup(".table-cell").nth(1).query();
clickOn(movieCheckOnFirstRow);
clickOn("#moveButton");
verify(videoMover).moveAll(anyListOf(Video.class));
}
@Test
public void whenConfigDownloadsButtonThenControllerSetDownloads() throws Exception {
clickOn("#settingsPane");
Thread.sleep(150);
clickOn("#setDownloadsButton");
verify(mainController).setDownloadsPath(any(ActionEvent.class));
}
@Test
public void whenConfigMoviesButtonThenControllerSetMovies() throws Exception {
clickOn("#settingsPane");
Thread.sleep(150);
clickOn("#setMoviesButton");
verify(mainController).setMoviesPath(any(ActionEvent.class));
}
@Test
public void whenConfigTvShowsButtonThenControllerSetTvShows() throws Exception {
clickOn("#settingsPane");
Thread.sleep(150);
clickOn("#setTvShowsButton");
verify(mainController).setTvShowsPath(any(ActionEvent.class));
}
}
|
package com.gamestudio24.cityescape.utils;
import com.badlogic.gdx.math.Vector2;
public class Constants {
public static final String GAME_NAME = "Martian Run!";
public static final int APP_WIDTH = 800;
public static final int APP_HEIGHT = 480;
public static final float WORLD_TO_SCREEN = 32;
public static final Vector2 WORLD_GRAVITY = new Vector2(0, -10);
public static final float GROUND_X = 0;
public static final float GROUND_Y = 0;
public static final float GROUND_WIDTH = 25f;
public static final float GROUND_HEIGHT = 2f;
public static final float GROUND_DENSITY = 0f;
public static final float RUNNER_X = 2;
public static final float RUNNER_Y = GROUND_Y + GROUND_HEIGHT;
public static final float RUNNER_WIDTH = 1f;
public static final float RUNNER_HEIGHT = 2f;
public static final float RUNNER_GRAVITY_SCALE = 3f;
public static final float RUNNER_DENSITY = 0.5f;
public static final float RUNNER_DODGE_X = 2f;
public static final float RUNNER_DODGE_Y = 1.5f;
public static final Vector2 RUNNER_JUMPING_LINEAR_IMPULSE = new Vector2(0, 13f);
public static final float RUNNER_HIT_ANGULAR_IMPULSE = 10f;
public static final float ENEMY_X = 25f;
public static final float ENEMY_DENSITY = RUNNER_DENSITY;
public static final float RUNNING_SHORT_ENEMY_Y = 1.5f;
public static final float RUNNING_LONG_ENEMY_Y = 2f;
public static final float FLYING_ENEMY_Y = 3f;
public static final Vector2 ENEMY_LINEAR_VELOCITY = new Vector2(-10f, 0);
public static final String BACKGROUND_ASSETS_ID = "background";
public static final String GROUND_ASSETS_ID = "ground";
public static final String RUNNER_RUNNING_ASSETS_ID = "runner_running";
public static final String RUNNER_DODGING_ASSETS_ID = "runner_dodging";
public static final String RUNNER_HIT_ASSETS_ID = "runner_hit";
public static final String RUNNER_JUMPING_ASSETS_ID = "runner_jumping";
public static final String RUNNING_SMALL_ENEMY_ASSETS_ID = "running_small_enemy";
public static final String RUNNING_LONG_ENEMY_ASSETS_ID = "running_long_enemy";
public static final String RUNNING_BIG_ENEMY_ASSETS_ID = "running_big_enemy";
public static final String RUNNING_WIDE_ENEMY_ASSETS_ID = "running_wide_enemy";
public static final String FLYING_SMALL_ENEMY_ASSETS_ID = "flying_small_enemy";
public static final String FLYING_WIDE_ENEMY_ASSETS_ID = "flying_wide_enemy";
public static final String BACKGROUND_IMAGE_PATH = "background.png";
public static final String GROUND_IMAGE_PATH = "ground.png";
public static final String SPRITES_ATLAS_PATH = "sprites.txt";
public static final String[] RUNNER_RUNNING_REGION_NAMES = new String[] {"alienBeige_run1", "alienBeige_run2"};
public static final String RUNNER_DODGING_REGION_NAME = "alienBeige_dodge";
public static final String RUNNER_HIT_REGION_NAME = "alienBeige_hit";
public static final String RUNNER_JUMPING_REGION_NAME = "alienBeige_jump";
public static final String[] RUNNING_SMALL_ENEMY_REGION_NAMES = new String[] {"ladyBug_walk1", "ladyBug_walk2"};
public static final String[] RUNNING_LONG_ENEMY_REGION_NAMES = new String[] {"barnacle_bite1", "barnacle_bite2"};
public static final String[] RUNNING_BIG_ENEMY_REGION_NAMES = new String[] {"spider_walk1", "spider_walk2"};
public static final String[] RUNNING_WIDE_ENEMY_REGION_NAMES = new String[] {"worm_walk1", "worm_walk2"};
public static final String[] FLYING_SMALL_ENEMY_REGION_NAMES = new String[] {"bee_fly1", "bee_fly2"};
public static final String[] FLYING_WIDE_ENEMY_REGION_NAMES = new String[] {"fly_fly1", "fly_fly2"};
public static final String SOUND_ON_REGION_NAME = "sound_on";
public static final String SOUND_OFF_REGION_NAME = "sound_off";
public static final String MUSIC_ON_REGION_NAME = "music_on";
public static final String MUSIC_OFF_REGION_NAME = "music_off";
public static final String PAUSE_REGION_NAME = "pause";
public static final String PLAY_REGION_NAME = "play";
public static final String BIG_PLAY_REGION_NAME = "play_big";
public static final String LEADERBOARD_REGION_NAME = "leaderboard";
public static final String ABOUT_REGION_NAME = "about";
public static final String CLOSE_REGION_NAME = "close";
public static final String RUNNER_JUMPING_SOUND = "jump.wav";
public static final String RUNNER_HIT_SOUND = "hit.wav";
public static final String GAME_MUSIC = "fun_in_a_bottle.mp3";
public static final String FONT_NAME = "roboto_bold.ttf";
public static final String ABOUT_TEXT = "Developed by: @gamestudio24\nPowered by: @libgdx\nGraphics: @kenneywings"
+ "\nMusic: @kmacleod";
}
|
package com.kehxstudios.atlas.managers;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.Vector3;
import com.kehxstudios.atlas.components.ClickableComponent;
import com.kehxstudios.atlas.tools.DebugTool;
import java.util.ArrayList;
public class InputManager extends Manager {
private static InputManager instance;
public static InputManager getInstance() {
if (instance == null) {
instance = new InputManager();
}
return instance;
}
private ArrayList<ClickableComponent> clickableComponents;
public InputManager() {
super();
setup();
}
private void setup() {
clickableComponents = new ArrayList<ClickableComponent>();
}
public void tick(float delta) {
if (Gdx.input.justTouched() && clickableComponents.size() > 0) {
checkClickable();
}
}
private void checkClickable() {
float x = screen.getWidth() - Gdx.input.getX() / screen.getScaleWidth() + screen.getCamera().position.x -
screen.getCamera().viewportWidth/2;
float y = screen.getHeight() - Gdx.input.getY() / screen.getScaleHeight() + screen.getCamera().position.y -
screen.getCamera().viewportHeight/2;
for (ClickableComponent clickable : clickableComponents) {
if (clickable.isEnabled()) {
if (x > clickable.getPosition().x - clickable.getWidth() / 2 &&
x < clickable.getPosition().x + clickable.getWidth() / 2 &&
y > clickable.getPosition().y - clickable.getHeight() / 2 &&
y < clickable.getPosition().y + clickable.getHeight() / 2) {
clickable.trigger();
}
}
}
}
public void add(ClickableComponent component) {
if (!clickableComponents.contains(component)) {
clickableComponents.add(component);
}
}
public void remove(ClickableComponent component) {
if (clickableComponents.contains(component)) {
clickableComponents.remove(component);
}
}
@Override
protected void loadScreenSettings() {
setup();
}
@Override
protected void removeScreenSettings() {
}
}
|
package com.spaceproject.systems;
import com.badlogic.ashley.core.Engine;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.EntitySystem;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.utils.ImmutableArray;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.math.Vector3;
import com.spaceproject.SpaceProject;
import com.spaceproject.components.CameraFocusComponent;
import com.spaceproject.components.ControlFocusComponent;
import com.spaceproject.components.ControllableComponent;
import com.spaceproject.components.DashComponent;
import com.spaceproject.components.HyperDriveComponent;
import com.spaceproject.components.ShieldComponent;
import com.spaceproject.components.TransformComponent;
import com.spaceproject.config.EngineConfig;
import com.spaceproject.config.KeyConfig;
import com.spaceproject.math.MyMath;
import com.spaceproject.screens.GameScreen;
import com.spaceproject.screens.MyScreenAdapter;
import com.spaceproject.utility.Mappers;
public class DesktopInputSystem extends EntitySystem implements InputProcessor {
private final KeyConfig keyCFG = SpaceProject.configManager.getConfig(KeyConfig.class);
private ImmutableArray<Entity> players;
private final Vector3 tempVec = new Vector3();
public boolean controllerHasFocus = false;
@Override
public void addedToEngine(Engine engine) {
players = engine.getEntitiesFor(Family.all(ControlFocusComponent.class, ControllableComponent.class).get());
MyScreenAdapter.getInputMultiplexer().addProcessor(this);
}
@Override
public void update(float delta) {
if (!controllerHasFocus) {
facePosition(Gdx.input.getX(), Gdx.input.getY());
}
debugCameraControls(delta);
}
private boolean playerControls(int keycode, boolean keyDown) {
if (players.size() == 0)
return false;
boolean handled = false;
Entity player = players.first();
ControllableComponent control = Mappers.controllable.get(player);
//movement
control.movementMultiplier = 1; // set multiplier to full power because a key switch is on or off
if (keycode == keyCFG.forward) {
control.moveForward = keyDown;
handled = true;
}
if (keycode == keyCFG.right) {
control.moveRight = keyDown;
handled = true;
}
if (keycode == keyCFG.left) {
control.moveLeft = keyDown;
handled = true;
}
if (keycode == keyCFG.back) {
control.moveBack = keyDown;
handled = true;
}
if (keycode == keyCFG.alter) {
control.alter = keyDown;
handled = true;
}
if (keycode == keyCFG.changeVehicle) {
control.changeVehicle = keyDown;
handled = true;
}
if (keycode == keyCFG.land) {
control.transition = keyDown;
handled = true;
}
if (keycode == keyCFG.dash) {
DashComponent dash = Mappers.dash.get(player);
if (dash != null) {
dash.activate = keyDown;
handled = true;
}
}
if (keycode == keyCFG.activateShield) {
ShieldComponent shield = Mappers.shield.get(player);
if (shield != null) {
shield.defend = keyDown;
handled = true;
}
}
if (keycode == keyCFG.activateHyperDrive) {
HyperDriveComponent hyperDrive = Mappers.hyper.get(player);
if (hyperDrive != null) {
hyperDrive.activate = keyDown;
handled = true;
}
}
return handled;
}
private boolean facePosition(int x, int y) {
if (players.size() == 0)
return false;
TransformComponent transform = Mappers.transform.get(players.first());
ControllableComponent control = Mappers.controllable.get(players.first());
Vector3 playerPos = GameScreen.cam.project(tempVec.set(transform.pos, 0));
float angle = MyMath.angleTo(x, Gdx.graphics.getHeight() - y, playerPos.x, playerPos.y);
control.angleTargetFace = angle;
return true;
}
private void debugCameraControls(float delta) {
if (players.size() == 0) {
return;
}
Entity player = players.first();
CameraFocusComponent cameraFocus = Mappers.camFocus.get(player);
if (cameraFocus == null) {
return;
}
float zoomSpeed = 2f * delta;
float angle = 5f * delta;
if (Gdx.input.isKeyPressed(keyCFG.resetZoom)) {
cameraFocus.zoomTarget = 1;
}
if (Gdx.input.isKeyPressed(keyCFG.zoomOut)) {
cameraFocus.zoomTarget = MyScreenAdapter.cam.zoom + zoomSpeed;
}
if (Gdx.input.isKeyPressed(keyCFG.zoomIn)) {
cameraFocus.zoomTarget = MyScreenAdapter.cam.zoom - zoomSpeed;
}
if (Gdx.input.isKeyPressed(keyCFG.rotateRight)) {
MyScreenAdapter.cam.rotate(angle);
}
if (Gdx.input.isKeyPressed(keyCFG.rotateLeft)) {
MyScreenAdapter.cam.rotate(-angle);
}
}
@Override
public boolean scrolled(float amountX, float amountY) {
if (players.size() != 0) {
Entity player = players.first();
CameraFocusComponent cameraFocus = Mappers.camFocus.get(player);
if (cameraFocus != null) {
float scrollAmount = amountY * cameraFocus.zoomTarget * 0.5f;
// a += Math.round(b * a * 0.5f);
// go nicely between 0.25, 0.5, 1, 2, 3, 5, 8, 12, 18, 27... but not quite 13, 21?
// it turns out to be strangely close to fib unintentionally,
// but also feels like a really nice spacing between zooms
// iter: 0, 1, 2, 3, 4, 5, 6, 7, 8...
// fib: 0, 1, 1, 2, 3, 5, 8, 13, 21..
// out: 0.25, 0.5, 1, 2, 3, 5, 8, 13, 21..
//todo: do it intentionally with fib, move it to camera class so controller input and mobile input set same targets
//for (int i = 0; i < 10; i++ ) { Gdx.app.debug("iter: " + i, MyMath.fibonacci(i) + ""); }
//if (amountY > 0) { iter++; } else { iter--; }
//cameraFocus.zoomTarget = getZoom(iter);
if (amountY <= 0) {
//zoom in
if (cameraFocus.zoomTarget == 0.5f) {
cameraFocus.zoomTarget = 0.25f;
} else if (cameraFocus.zoomTarget == 1f) {
cameraFocus.zoomTarget = 0.5f;
} else {
cameraFocus.zoomTarget += Math.round(scrollAmount);
}
} else {
//zoom out
if (cameraFocus.zoomTarget == 0.25f) {
cameraFocus.zoomTarget = 0.5f;
} else if (cameraFocus.zoomTarget == 0.5f) {
cameraFocus.zoomTarget = 1f;
} else {
cameraFocus.zoomTarget += Math.max(1, Math.round(scrollAmount));
}
}
}
}
return false;
}
static byte iter = 0;//126;test out of bound and negative
private static float getZoom(byte iter) {
switch (iter) {
case 0: return 0.25f;
case 1: return 0.5f; //default character zoom
case 2: return 1.0f; //default vehicle zoom
default: return MyMath.fibonacci(iter);
}
}
@Override
public boolean keyDown(int keycode) {
return playerControls(keycode, true);
}
@Override
public boolean keyUp(int keycode) {
return playerControls(keycode, false);
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
if (players.size() == 0) {
return false;
}
if (button == Input.Buttons.LEFT) {
ControllableComponent control = Mappers.controllable.get(players.first());
control.attack = true;
return true;
}
if (button == Input.Buttons.MIDDLE) {
Entity player = players.first();
CameraFocusComponent cameraFocus = Mappers.camFocus.get(player);
if (cameraFocus != null) {
GameScreen.resetRotation();
EngineConfig engineConfig = SpaceProject.configManager.getConfig(EngineConfig.class);
if (Mappers.vehicle.get(player) != null) {
cameraFocus.zoomTarget = engineConfig.defaultZoomVehicle;
} else {
cameraFocus.zoomTarget = engineConfig.defaultZoomCharacter;
}
return true;
}
}
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if (players.size() != 0) {
ControllableComponent control = Mappers.controllable.get(players.first());
control.attack = false;
return true;
}
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return facePosition(screenX, screenY);
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
controllerHasFocus = false;
return false;
}
}
|
package bisq.core.btc;
import org.libdohj.params.DashMainNetParams;
import org.libdohj.params.DashRegTestParams;
import org.libdohj.params.DashTestNet3Params;
import org.libdohj.params.LitecoinMainNetParams;
import org.libdohj.params.LitecoinRegTestParams;
import org.libdohj.params.LitecoinTestNet3Params;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.RegTestParams;
import org.bitcoinj.params.TestNet3Params;
import lombok.Getter;
public enum BaseCurrencyNetwork {
BTC_MAINNET(MainNetParams.get(), "BTC", "MAINNET", "Bitcoin"),
BTC_TESTNET(TestNet3Params.get(), "BTC", "TESTNET", "Bitcoin"),
BTC_REGTEST(RegTestParams.get(), "BTC", "REGTEST", "Bitcoin"),
LTC_MAINNET(LitecoinMainNetParams.get(), "LTC", "MAINNET", "Litecoin"),
LTC_TESTNET(LitecoinTestNet3Params.get(), "LTC", "TESTNET", "Litecoin"),
LTC_REGTEST(LitecoinRegTestParams.get(), "LTC", "REGTEST", "Litecoin"),
DASH_MAINNET(DashMainNetParams.get(), "DASH", "MAINNET", "Dash"),
DASH_TESTNET(DashTestNet3Params.get(), "DASH", "TESTNET", "Dash"),
DASH_REGTEST(DashRegTestParams.get(), "DASH", "REGTEST", "Dash");
@Getter
private final NetworkParameters parameters;
@Getter
private final String currencyCode;
@Getter
private final String network;
@Getter
private String currencyName;
BaseCurrencyNetwork(NetworkParameters parameters, String currencyCode, String network, String currencyName) {
this.parameters = parameters;
this.currencyCode = currencyCode;
this.network = network;
this.currencyName = currencyName;
}
public boolean isMainnet() {
return "MAINNET".equals(network);
}
public boolean isTestnet() {
return "TESTNET".equals(network);
}
public boolean isRegtest() {
return "REGTEST".equals(network);
}
public boolean isBitcoin() {
return "BTC".equals(currencyCode);
}
public boolean isLitecoin() {
return "LTC".equals(currencyCode);
}
public boolean isDash() {
return "DASH".equals(currencyCode);
}
public long getDefaultMinFeePerByte() {
return 1;
}
}
|
package hudson.console;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.model.Computer;
import hudson.model.Item;
import hudson.model.Label;
import hudson.model.ModelObject;
import hudson.model.Node;
import hudson.model.Run;
import hudson.model.User;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import org.jenkinsci.Symbol;
/**
* {@link HyperlinkNote} that links to a {@linkplain ModelObject model object},
* which in the UI gets rendered with context menu and etc.
*
* @author Kohsuke Kawaguchi
* @since 1.464
*/
public class ModelHyperlinkNote extends HyperlinkNote {
public ModelHyperlinkNote(String url, int length) {
super(url, length);
}
@Override
protected String extraAttributes() {
return " class='jenkins-table__link model-link model-link--float'";
}
public static String encodeTo(@NonNull User u) {
return encodeTo(u, u.getDisplayName());
}
public static String encodeTo(User u, String text) {
return encodeTo('/' + u.getUrl(), text);
}
public static String encodeTo(Item item) {
return encodeTo(item, item.getFullDisplayName());
}
public static String encodeTo(Item item, String text) {
return encodeTo('/' + item.getUrl(), text);
}
public static String encodeTo(Run r) {
return encodeTo('/' + r.getUrl(), r.getDisplayName());
}
public static String encodeTo(Node node) {
Computer c = node.toComputer();
if (c != null) {
return encodeTo("/" + c.getUrl(), node.getDisplayName());
}
String nodePath = node == Jenkins.get() ? "(built-in)" : node.getNodeName();
return encodeTo("/computer/" + nodePath, node.getDisplayName());
}
/**
* @since 2.230
*/
public static String encodeTo(Label label) {
return encodeTo("/" + label.getUrl(), label.getName());
}
public static String encodeTo(String url, String text) {
return HyperlinkNote.encodeTo(url, text, ModelHyperlinkNote::new);
}
@Extension @Symbol("hyperlinkToModels")
public static class DescriptorImpl extends HyperlinkNote.DescriptorImpl {
@NonNull
@Override
public String getDisplayName() {
return "Hyperlinks to models";
}
}
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(ModelHyperlinkNote.class.getName());
}
|
package com.example.pluginmain;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Space;
import android.widget.TextView;
import android.widget.Toast;
import com.example.pluginsharelib.SharePOJO;
import com.plugin.content.PluginDescriptor;
import com.plugin.content.PluginIntentFilter;
import com.plugin.core.PluginLoader;
import com.plugin.util.FragmentHelper;
import com.plugin.util.LogUtil;
public class PluginDetailActivity extends Activity {
private ViewGroup mRoot;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_activity);
setTitle("");
mRoot = (ViewGroup) findViewById(R.id.root);
String pluginId = getIntent().getStringExtra("plugin_id");
if (pluginId == null) {
Toast.makeText(this, "plugin_id", Toast.LENGTH_LONG).show();
return;
}
PluginDescriptor pluginDescriptor = PluginLoader.getPluginDescriptorByPluginId(pluginId);
initViews(pluginDescriptor);
}
private void initViews(PluginDescriptor pluginDescriptor) {
if (pluginDescriptor != null) {
TextView pluginIdView = (TextView) mRoot.findViewById(R.id.plugin_id);
pluginIdView.setText("Id" + pluginDescriptor.getPackageName());
TextView pluginVerView = (TextView) mRoot.findViewById(R.id.plugin_version);
pluginVerView.setText("Version" + pluginDescriptor.getVersion());
TextView pluginDescipt = (TextView) mRoot.findViewById(R.id.plugin_description);
pluginDescipt.setText("Description" + pluginDescriptor.getDescription());
TextView pluginInstalled = (TextView) mRoot.findViewById(R.id.plugin_installedPath);
pluginInstalled.setText("" + pluginDescriptor.getInstalledPath());
TextView pluginStandalone = (TextView) mRoot.findViewById(R.id.isstandalone);
pluginStandalone.setText("" + (pluginDescriptor.isStandalone()?"":""));
LinearLayout pluginView = (LinearLayout) mRoot.findViewById(R.id.plugin_items);
Iterator<Entry<String, String>> fragment = pluginDescriptor.getFragments().entrySet().iterator();
while (fragment.hasNext()) {
final Entry<String, String> entry = fragment.next();
TextView tv = new TextView(this);
tv.append("Fragment");
pluginView.addView(tv);
tv = new TextView(this);
tv.setText("ClassId" + entry.getKey());
pluginView.addView(tv);
tv = new TextView(this);
tv.append("ClassName " + entry.getValue());
pluginView.addView(tv);
Button btn = new Button(this);
btn.setText("");
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Fragment
// ActivityFragment
// ActivityFragmentfragment
FragmentHelper.startFragmentWithBuildInActivity(PluginDetailActivity.this, entry.getKey());
}
});
pluginView.addView(btn);
Space space = new Space(this);
space.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 25));
pluginView.addView(space);
}
addButton(pluginView, pluginDescriptor.getActivitys(), "Activity");
addButton(pluginView, pluginDescriptor.getServices(), "Service");
addButton(pluginView, pluginDescriptor.getReceivers(), "Receiver");
}
}
private void addButton(LinearLayout pluginView, HashMap<String, ArrayList<PluginIntentFilter>> map, final String type) {
Iterator<String> components = map.keySet().iterator();
while (components.hasNext()) {
final String entry = components.next();
TextView tv = new TextView(this);
// debug
tv.append("" + type);
pluginView.addView(tv);
tv = new TextView(this);
tv.append("ClassName " + entry);
pluginView.addView(tv);
Button btn = new Button(this);
btn.setText("");
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// debug
if (type.equals("Service")) {
Intent intent = new Intent();
intent.setClassName(PluginDetailActivity.this, entry);
intent.putExtra("testParam", "testParam");
startService(intent);
// stopService(intent);
} else if (type.equals("Receiver")) {// debug
Intent intent = new Intent();
intent.setClassName(PluginDetailActivity.this, entry);
intent.putExtra("testParam", "testParam");
sendBroadcast(intent);
} else if (type.equals("Activity")) {
// ClassName
Intent intent = new Intent();
intent.setClassName(PluginDetailActivity.this, entry);
intent.putExtra("testParam", "testParam");
intent.putExtra("paramVO", new SharePOJO("VO"));
startActivity(intent);
// action
if (entry.equals("com.example.plugintest.activity.PluginNotInManifestActivity")) {
intent = new Intent("test.xyz1");
intent.putExtra("testParam", "testParam");
startActivity(intent);
}
// url
if (entry.equals("com.example.plugintest.activity.PluginNotInManifestActivity")) {
intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("testscheme://testhost"));
intent.putExtra("testParam", "testParam");
startActivity(intent);
}
}
}
});
pluginView.addView(btn);
if (Build.VERSION.SDK_INT >=14) {
Space space = new Space(this);
space.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 25));
pluginView.addView(space);
}
}
}
}
|
package org.javarosa.core.model;
import org.javarosa.core.model.instance.TreeReference;
import java.util.Vector;
/**
* A Form Index is an immutable index into a specific question definition that
* will appear in an interaction with a user.
*
* An index is represented by different levels into hierarchical groups.
*
* Indices can represent both questions and groups.
*
* It is absolutely essential that there be no circularity of reference in
* FormIndex's, IE, no form index's ancestor can be itself.
*
* Datatype Productions:
* FormIndex = BOF | EOF | CompoundIndex(nextIndex:FormIndex,Location)
* Location = Empty | Simple(localLevel:int) | WithMult(localLevel:int, multiplicity:int)
*
* @author Clayton Sims
*/
public class FormIndex {
private boolean beginningOfForm = false;
private boolean endOfForm = false;
/**
* The index of the questiondef in the current context
*/
private final int localIndex;
/**
* The multiplicity of the current instance of a repeated question or group
*/
private int instanceIndex = -1;
/**
* The next level of this index
*/
private FormIndex nextLevel;
private TreeReference reference;
public static FormIndex createBeginningOfFormIndex() {
FormIndex begin = new FormIndex(-1, null);
begin.beginningOfForm = true;
return begin;
}
public static FormIndex createEndOfFormIndex() {
FormIndex end = new FormIndex(-1, null);
end.endOfForm = true;
return end;
}
/**
* Constructs a simple form index that references a specific element in
* a list of elements.
*
* @param localIndex An integer index into a flat list of elements
* @param reference A reference to the instance element identified by this index;
*/
public FormIndex(int localIndex, TreeReference reference) {
this.localIndex = localIndex;
this.reference = reference;
}
/**
* Constructs a simple form index that references a specific element in
* a list of elements.
*
* @param localIndex An integer index into a flat list of elements
* @param instanceIndex An integer index expressing the multiplicity
* of the current level
* @param reference A reference to the instance element identified by this index;
*/
public FormIndex(int localIndex, int instanceIndex, TreeReference reference) {
this.localIndex = localIndex;
this.instanceIndex = instanceIndex;
this.reference = reference;
}
/**
* Constructs an index which indexes an element, and provides an index
* into that elements children
*
* @param nextLevel An index into the referenced element's index
* @param localIndex An index to an element at the current level, a child
* element of which will be referenced by the nextLevel index.
* @param reference A reference to the instance element identified by this index;
*/
public FormIndex(FormIndex nextLevel, int localIndex, TreeReference reference) {
this(localIndex, reference);
this.nextLevel = nextLevel;
}
/**
* Constructs an index which references an element past the level of
* specificity of the current context, founded by the currentLevel
* index.
* (currentLevel, (nextLevel...))
*/
public FormIndex(FormIndex nextLevel, FormIndex currentLevel) {
if (currentLevel == null) {
this.nextLevel = nextLevel.nextLevel;
this.localIndex = nextLevel.localIndex;
this.instanceIndex = nextLevel.instanceIndex;
this.reference = nextLevel.reference;
} else {
this.nextLevel = nextLevel;
this.localIndex = currentLevel.getLocalIndex();
this.instanceIndex = currentLevel.getInstanceIndex();
this.reference = currentLevel.reference;
}
}
/**
* Constructs an index which indexes an element, and provides an index
* into that elements children, along with the current index of a
* repeated instance.
*
* @param nextLevel An index into the referenced element's index
* @param localIndex An index to an element at the current level, a child
* element of which will be referenced by the nextLevel index.
* @param instanceIndex How many times the element referenced has been
* repeated.
* @param reference A reference to the instance element identified by this index;
*/
public FormIndex(FormIndex nextLevel, int localIndex, int instanceIndex, TreeReference reference) {
this(nextLevel, localIndex, reference);
this.instanceIndex = instanceIndex;
}
public boolean isInForm() {
return !beginningOfForm && !endOfForm;
}
/**
* @return The index of the element in the current context
*/
public int getLocalIndex() {
return localIndex;
}
/**
* @return The multiplicity of the current instance of a repeated question or group
*/
public int getInstanceIndex() {
return instanceIndex;
}
/**
* For the fully qualified element, get the multiplicity of the element's reference
*
* @return The terminal element (fully qualified)'s instance index
*/
public int getElementMultiplicity() {
return getTerminal().instanceIndex;
}
/**
* @return An index into the next level of specificity past the current context. An
* example would be an index into an element that is a child of the element referenced
* by the local index.
*/
public FormIndex getNextLevel() {
return nextLevel;
}
public TreeReference getLocalReference() {
return reference;
}
/**
* @return The TreeReference of the fully qualified element described by this
* FormIndex.
*/
public TreeReference getReference() {
return getTerminal().reference;
}
public FormIndex getTerminal() {
FormIndex walker = this;
while (walker.nextLevel != null) {
walker = walker.nextLevel;
}
return walker;
}
/**
* Identifies whether this is a terminal index, in other words whether this
* index references with more specificity than the current context
*/
public boolean isTerminal() {
return nextLevel == null;
}
public boolean isEndOfFormIndex() {
return endOfForm;
}
public boolean isBeginningOfFormIndex() {
return beginningOfForm;
}
@Override
public int hashCode() {
return (beginningOfForm ? 0 : 31)
^ (endOfForm ? 0 : 31)
^ localIndex
^ instanceIndex
^ (nextLevel == null ? 0 : nextLevel.hashCode());
}
@Override
public boolean equals(Object o) {
if (!(o instanceof FormIndex))
return false;
FormIndex a = this;
FormIndex b = (FormIndex)o;
return (a.compareTo(b) == 0);
}
public int compareTo(Object o) {
if (!(o instanceof FormIndex))
throw new IllegalArgumentException("Attempt to compare Object of type " + o.getClass().getName() + " to a FormIndex");
FormIndex a = this;
FormIndex b = (FormIndex)o;
if (a.beginningOfForm) {
return (b.beginningOfForm ? 0 : -1);
} else if (a.endOfForm) {
return (b.endOfForm ? 0 : 1);
} else {
//a is in form
if (b.beginningOfForm) {
return 1;
} else if (b.endOfForm) {
return -1;
}
}
if (a.localIndex != b.localIndex) {
return (a.localIndex < b.localIndex ? -1 : 1);
} else if (a.instanceIndex != b.instanceIndex) {
return (a.instanceIndex < b.instanceIndex ? -1 : 1);
} else if ((a.getNextLevel() == null) != (b.getNextLevel() == null)) {
return (a.getNextLevel() == null ? -1 : 1);
} else if (a.getNextLevel() != null) {
return a.getNextLevel().compareTo(b.getNextLevel());
} else {
return 0;
}
}
/**
* @return Only the local component of this Form Index.
*/
public FormIndex snip() {
return new FormIndex(localIndex, instanceIndex, reference);
}
/**
* Takes in a form index which is a subset of this index, and returns the
* total difference between them. This is useful for stepping up the level
* of index specificty. If the subIndex is not a valid subIndex of this index,
* null is returned. Since the FormIndex represented by null is always a subset,
* if null is passed in as a subIndex, the full index is returned
*
* For example:
* Indices
* a = 1_0,2,1,3
* b = 1,3
*
* a.diff(b) = 1_0,2
*/
public FormIndex diff(FormIndex subIndex) {
if (subIndex == null) {
return this;
}
if (!isSubIndex(this, subIndex)) {
return null;
}
if (subIndex.equals(this)) {
return null;
}
return new FormIndex(nextLevel.diff(subIndex), this.snip());
}
@Override
public String toString() {
StringBuilder ret = new StringBuilder();
FormIndex ref = this;
while (ref != null) {
ret.append(ref.getLocalIndex())
.append(ref.getInstanceIndex() == -1 ? "," : "_" + ref.getInstanceIndex() + ",");
ref = ref.nextLevel;
}
return ret.toString().substring(0, ret.lastIndexOf(","));
}
/**
* @return the level of this index relative to the top level of the form
*/
public int getDepth() {
int depth = 0;
FormIndex ref = this;
while (ref != null) {
ref = ref.nextLevel;
depth++;
}
return depth;
}
private static boolean isSubIndex(FormIndex parent, FormIndex child) {
return child.equals(parent) ||
(parent != null && isSubIndex(parent.nextLevel, child));
}
public static boolean isSubElement(FormIndex parent, FormIndex child) {
while (!parent.isTerminal() && !child.isTerminal()) {
if (parent.getLocalIndex() != child.getLocalIndex()) {
return false;
}
if (parent.getInstanceIndex() != child.getInstanceIndex()) {
return false;
}
parent = parent.nextLevel;
child = child.nextLevel;
}
//If we've gotten this far, at least one of the two is terminal
if (!parent.isTerminal() && child.isTerminal()) {
//can't be the parent if the child is earlier on
return false;
} else if (parent.getLocalIndex() != child.getLocalIndex()) {
//Either they're at the same level, in which case only
//identical indices should match, or they should have
//the same root
return false;
} else if (parent.getInstanceIndex() != -1 && (parent.getInstanceIndex() != child.getInstanceIndex())) {
return false;
}
//Barring all of these cases, it should be true.
return true;
}
/**
* @return Do all the entries of two FormIndexes match except for the last instance index?
*/
public static boolean areSiblings(FormIndex a, FormIndex b) {
if (a.isTerminal() && b.isTerminal() && a.getLocalIndex() == b.getLocalIndex()) {
return true;
}
if (!a.isTerminal() && !b.isTerminal()) {
return a.getLocalIndex() == b.getLocalIndex() &&
areSiblings(a.nextLevel, b.nextLevel);
}
return false;
}
/**
* @return Do all the local indexes in the 'parent' FormIndex match the
* corresponding ones in 'child'?
*/
public static boolean overlappingLocalIndexesMatch(FormIndex parent, FormIndex child) {
if (parent.getDepth() > child.getDepth()) {
return false;
}
while (!parent.isTerminal()) {
if (parent.getLocalIndex() != child.getLocalIndex()) {
return false;
}
parent = parent.nextLevel;
child = child.nextLevel;
}
return parent.getLocalIndex() == child.getLocalIndex();
}
/**
* Used by Touchforms
*/
@SuppressWarnings("unused")
public void assignRefs(FormDef f) {
FormIndex cur = this;
Vector<Integer> indexes = new Vector<Integer>();
Vector<Integer> multiplicities = new Vector<Integer>();
Vector<IFormElement> elements = new Vector<IFormElement>();
f.collapseIndex(this, indexes, multiplicities, elements);
Vector<Integer> curMults = new Vector<Integer>();
Vector<IFormElement> curElems = new Vector<IFormElement>();
int i = 0;
while (cur != null) {
curMults.addElement(multiplicities.elementAt(i));
curElems.addElement(elements.elementAt(i));
cur.reference = f.getChildInstanceRef(curElems, curMults);
cur = cur.getNextLevel();
i++;
}
}
}
|
package dr.app.beauti.taxonsetspanel;
import dr.app.beauti.BeautiApp;
import dr.app.beauti.BeautiFrame;
import dr.app.beauti.BeautiPanel;
import dr.app.beauti.options.BeautiOptions;
import dr.evolution.util.Taxa;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import org.virion.jam.framework.Exportable;
import org.virion.jam.panels.ActionPanel;
import org.virion.jam.table.TableRenderer;
import org.virion.jam.util.IconUtils;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.BorderUIResource;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
* @version $Id: TaxaPanel.java,v 1.1 2006/09/05 13:29:34 rambaut Exp $
*/
public class TaxaPanel extends BeautiPanel implements Exportable {
private static final long serialVersionUID = -3138832889782090814L;
private final String TAXON_SET_DEFAULT = "taxon set...";
BeautiFrame frame = null;
BeautiOptions options = null;
private TaxonList taxa = null;
private JTable taxonSetsTable = null;
private TaxonSetsTableModel taxonSetsTableModel = null;
private JPanel taxonSetEditingPanel = null;
private Taxa currentTaxonSet = null;
private final List<Taxon> includedTaxa = new ArrayList<Taxon>();
private final List<Taxon> excludedTaxa = new ArrayList<Taxon>();
private JTable excludedTaxaTable = null;
private TaxaTableModel excludedTaxaTableModel = null;
private JComboBox excludedTaxonSetsComboBox = null;
private boolean excludedSelectionChanging = false;
private JTable includedTaxaTable = null;
private TaxaTableModel includedTaxaTableModel = null;
private JComboBox includedTaxonSetsComboBox = null;
private boolean includedSelectionChanging = false;
private static int taxonSetCount = 0;
public TaxaPanel(BeautiFrame parent) {
this.frame = parent;
Icon includeIcon = null, excludeIcon = null;
try {
includeIcon = new ImageIcon(IconUtils.getImage(BeautiApp.class, "images/include.png"));
excludeIcon = new ImageIcon(IconUtils.getImage(BeautiApp.class, "images/exclude.png"));
} catch (Exception e) {
// do nothing
}
// Taxon Sets
taxonSetsTableModel = new TaxonSetsTableModel();
taxonSetsTable = new JTable(taxonSetsTableModel);
final TableColumnModel model = taxonSetsTable.getColumnModel();
final TableColumn tableColumn0 = model.getColumn(0);
tableColumn0.setCellRenderer(new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
tableColumn0.setMinWidth(20);
//final TableColumn tableColumn1 = model.getColumn(1);
taxonSetsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
taxonSetsTableSelectionChanged();
}
});
JScrollPane scrollPane1 = new JScrollPane(taxonSetsTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
ActionPanel actionPanel1 = new ActionPanel(false);
actionPanel1.setAddAction(addTaxonSetAction);
actionPanel1.setRemoveAction(removeTaxonSetAction);
addTaxonSetAction.setEnabled(false);
removeTaxonSetAction.setEnabled(false);
JPanel controlPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
controlPanel1.add(actionPanel1);
// Excluded Taxon List
excludedTaxaTableModel = new TaxaTableModel(false);
excludedTaxaTable = new JTable(excludedTaxaTableModel);
excludedTaxaTable.getColumnModel().getColumn(0).setCellRenderer(
new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
excludedTaxaTable.getColumnModel().getColumn(0).setMinWidth(20);
excludedTaxaTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
excludedTaxaTableSelectionChanged();
}
});
JScrollPane scrollPane2 = new JScrollPane(excludedTaxaTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Box panel1 = new Box(BoxLayout.X_AXIS);
panel1.add(new JLabel("Select: "));
panel1.setOpaque(false);
excludedTaxonSetsComboBox = new JComboBox(new String[]{TAXON_SET_DEFAULT});
excludedTaxonSetsComboBox.setOpaque(false);
panel1.add(excludedTaxonSetsComboBox);
JPanel buttonPanel = createAddRemoveButtonPanel(includeTaxonAction, includeIcon, "Include selected taxa in the taxon set",
excludeTaxonAction, excludeIcon, "Exclude selected taxa from the taxon set",
javax.swing.BoxLayout.Y_AXIS);
// Included Taxon List
includedTaxaTableModel = new TaxaTableModel(true);
includedTaxaTable = new JTable(includedTaxaTableModel);
includedTaxaTable.getColumnModel().getColumn(0).setCellRenderer(
new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
includedTaxaTable.getColumnModel().getColumn(0).setMinWidth(20);
includedTaxaTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
includedTaxaTableSelectionChanged();
}
});
includedTaxaTable.doLayout();
JScrollPane scrollPane3 = new JScrollPane(includedTaxaTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Box panel2 = new Box(BoxLayout.X_AXIS);
panel2.add(new JLabel("Select: "));
panel2.setOpaque(false);
includedTaxonSetsComboBox = new JComboBox(new String[]{TAXON_SET_DEFAULT});
includedTaxonSetsComboBox.setOpaque(false);
panel2.add(includedTaxonSetsComboBox);
taxonSetEditingPanel = new JPanel();
taxonSetEditingPanel.setBorder(BorderFactory.createTitledBorder("Taxon Set: none selected"));
taxonSetEditingPanel.setOpaque(false);
taxonSetEditingPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.5;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(12, 12, 4, 0);
taxonSetEditingPanel.add(scrollPane2, c);
c.gridx = 0;
c.gridy = 1;
c.weightx = 0.5;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(0, 12, 12, 0);
taxonSetEditingPanel.add(panel1, c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 0;
c.weighty = 1;
c.gridheight = 2;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(12, 2, 12, 4);
taxonSetEditingPanel.add(buttonPanel, c);
c.gridx = 2;
c.gridy = 0;
c.weightx = 0.5;
c.weighty = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(12, 0, 4, 12);
taxonSetEditingPanel.add(scrollPane3, c);
c.gridx = 2;
c.gridy = 1;
c.weightx = 0.5;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(0, 0, 12, 12);
taxonSetEditingPanel.add(panel2, c);
JPanel panel3 = new JPanel();
panel3.setOpaque(false);
panel3.setLayout(new GridBagLayout());
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.4;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(0, 0, 2, 12);
panel3.add(scrollPane1, c);
c.gridx = 0;
c.gridy = 1;
c.weightx = 0;
c.weighty = 0;
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.WEST;
c.insets = new Insets(2, 0, 0, 12);
panel3.add(actionPanel1, c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 0.6;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(0, 0, 0, 0);
panel3.add(taxonSetEditingPanel, c);
setOpaque(false);
setBorder(new BorderUIResource.EmptyBorderUIResource(new Insets(12, 12, 12, 12)));
setLayout(new BorderLayout(0, 0));
add(panel3, BorderLayout.CENTER);
// taxonSetsTable.addMouseListener(new MouseAdapter() {
// public void mouseClicked(MouseEvent e) {
// if (e.getClickCount() == 2) {
// JTable target = (JTable)e.getSource();
// int row = target.getSelectedRow();
// taxonSetsTableDoubleClicked(row);
includedTaxaTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
includeSelectedTaxa();
}
}
});
excludedTaxaTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
excludeSelectedTaxa();
}
}
});
includedTaxaTable.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent focusEvent) {
excludedTaxaTable.clearSelection();
}
});
excludedTaxaTable.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent focusEvent) {
includedTaxaTable.clearSelection();
}
});
includedTaxaTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!includedSelectionChanging && includedTaxonSetsComboBox.getSelectedIndex() != 0) {
includedTaxonSetsComboBox.setSelectedIndex(0);
}
}
});
includedTaxonSetsComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
includedSelectionChanging = true;
includedTaxaTable.clearSelection();
if (includedTaxonSetsComboBox.getSelectedIndex() > 0) {
Taxa taxa = (Taxa) includedTaxonSetsComboBox.getSelectedItem();
for (int i = 0; i < taxa.getTaxonCount(); i++) {
Taxon taxon = taxa.getTaxon(i);
int index = includedTaxa.indexOf(taxon);
includedTaxaTable.getSelectionModel().addSelectionInterval(index, index);
}
}
includedSelectionChanging = false;
}
});
excludedTaxaTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (!excludedSelectionChanging && excludedTaxonSetsComboBox.getSelectedIndex() != 0) {
excludedTaxonSetsComboBox.setSelectedIndex(0);
}
}
});
excludedTaxonSetsComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
excludedSelectionChanging = true;
excludedTaxaTable.clearSelection();
if (excludedTaxonSetsComboBox.getSelectedIndex() > 0) {
Taxa taxa = (Taxa) excludedTaxonSetsComboBox.getSelectedItem();
for (int i = 0; i < taxa.getTaxonCount(); i++) {
Taxon taxon = taxa.getTaxon(i);
int index = excludedTaxa.indexOf(taxon);
excludedTaxaTable.getSelectionModel().addSelectionInterval(index, index);
}
}
excludedSelectionChanging = false;
}
});
taxonSetsTable.doLayout();
includedTaxaTable.doLayout();
excludedTaxaTable.doLayout();
}
private void taxonSetChanged() {
currentTaxonSet.removeAllTaxa();
for (Taxon anIncludedTaxa : includedTaxa) {
currentTaxonSet.addTaxon(anIncludedTaxa);
}
setupTaxonSetsComboBoxes();
if (options.taxonSetsMono.get(currentTaxonSet) != null &&
options.taxonSetsMono.get(currentTaxonSet) &&
!checkCompatibility(currentTaxonSet)) {
options.taxonSetsMono.put(currentTaxonSet, Boolean.FALSE);
}
frame.setDirty();
}
private void resetPanel() {
if (!options.hasData()) {
includedTaxa.clear();
excludedTaxa.clear();
}
}
public void setOptions(BeautiOptions options) {
this.options = options;
resetPanel();
taxa = options.taxonList;
if (taxa == null) {
addTaxonSetAction.setEnabled(false);
removeTaxonSetAction.setEnabled(false);
} else {
addTaxonSetAction.setEnabled(true);
}
taxonSetsTableSelectionChanged();
taxonSetsTableModel.fireTableDataChanged();
validateTaxonSets();
}
private void validateTaxonSets() {
if (taxonSetsTable.getRowCount() > 0) {
for (Taxa taxonSet : options.taxonSets) {
if (taxonSet.getTaxonCount() < 1) {
JOptionPane.showMessageDialog(this, "Taxon set " + taxonSet.getId() + " is empty, "
+ "\nplease go back to Taxon Sets panel to select included taxa.",
"Empty taxon set error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
public void getOptions(BeautiOptions options) {
// options.datesUnits = unitsCombo.getSelectedIndex();
// options.datesDirection = directionCombo.getSelectedIndex();
// options.translation = translationCombo.getSelectedIndex();
}
public JComponent getExportableComponent() {
return taxonSetsTable;
}
private void taxonSetsTableSelectionChanged() {
int[] rows = taxonSetsTable.getSelectedRows();
if (rows.length == 0) {
removeTaxonSetAction.setEnabled(false);
} else if (rows.length == 1) {
currentTaxonSet = options.taxonSets.get(rows[0]);
setCurrentTaxonSet(currentTaxonSet);
removeTaxonSetAction.setEnabled(true);
} else {
setCurrentTaxonSet(null);
removeTaxonSetAction.setEnabled(true);
}
}
// private void taxonSetsTableDoubleClicked(int row) {
// currentTaxonSet = (Taxa)taxonSets.get(row);
// Collections.sort(taxonSets);
// taxonSetsTableModel.fireTableDataChanged();
// setCurrentTaxonSet(currentTaxonSet);
// int sel = taxonSets.indexOf(currentTaxonSet);
// taxonSetsTable.setRowSelectionInterval(sel, sel);
Action addTaxonSetAction = new AbstractAction("+") {
private static final long serialVersionUID = 20273987098143413L;
public void actionPerformed(ActionEvent ae) {
taxonSetCount++;
currentTaxonSet = new Taxa("untitled" + taxonSetCount);
options.taxonSets.add(currentTaxonSet);
Collections.sort(options.taxonSets);
options.taxonSetsMono.put(currentTaxonSet, Boolean.FALSE);
taxonSetsTableModel.fireTableDataChanged();
int sel = options.taxonSets.indexOf(currentTaxonSet);
taxonSetsTable.setRowSelectionInterval(sel, sel);
taxonSetChanged();
}
};
Action removeTaxonSetAction = new AbstractAction("-") {
private static final long serialVersionUID = 6077578872870122265L;
public void actionPerformed(ActionEvent ae) {
int row = taxonSetsTable.getSelectedRow();
if (row != -1) {
Taxa taxa = options.taxonSets.remove(row);
options.taxonSetsMono.remove(taxa);
}
taxonSetChanged();
taxonSetsTableModel.fireTableDataChanged();
if (row >= options.taxonSets.size()) {
row = options.taxonSets.size() - 1;
}
if (row >= 0) {
taxonSetsTable.setRowSelectionInterval(row, row);
} else {
setCurrentTaxonSet(null);
}
}
};
private void setCurrentTaxonSet(Taxa taxonSet) {
this.currentTaxonSet = taxonSet;
includedTaxa.clear();
excludedTaxa.clear();
if (currentTaxonSet != null) {
for (int i = 0; i < taxonSet.getTaxonCount(); i++) {
includedTaxa.add(taxonSet.getTaxon(i));
}
Collections.sort(includedTaxa);
for (int i = 0; i < taxa.getTaxonCount(); i++) {
excludedTaxa.add(taxa.getTaxon(i));
}
excludedTaxa.removeAll(includedTaxa);
Collections.sort(excludedTaxa);
}
setTaxonSetTitle();
setupTaxonSetsComboBoxes();
includedTaxaTableModel.fireTableDataChanged();
excludedTaxaTableModel.fireTableDataChanged();
}
private void setTaxonSetTitle() {
if (currentTaxonSet == null) {
taxonSetEditingPanel.setBorder(BorderFactory.createTitledBorder(""));
taxonSetEditingPanel.setEnabled(false);
} else {
taxonSetEditingPanel.setEnabled(true);
taxonSetEditingPanel.setBorder(BorderFactory.createTitledBorder("Taxon Set: " + currentTaxonSet.getId()));
}
}
private void setupTaxonSetsComboBoxes() {
setupTaxonSetsComboBox(excludedTaxonSetsComboBox, excludedTaxa);
excludedTaxonSetsComboBox.setSelectedIndex(0);
setupTaxonSetsComboBox(includedTaxonSetsComboBox, includedTaxa);
includedTaxonSetsComboBox.setSelectedIndex(0);
}
private void setupTaxonSetsComboBox(JComboBox comboBox, List<Taxon> availableTaxa) {
comboBox.removeAllItems();
comboBox.addItem(TAXON_SET_DEFAULT);
for (Taxa taxa : options.taxonSets) {
if (taxa != currentTaxonSet) {
if (isCompatible(taxa, availableTaxa)) {
comboBox.addItem(taxa);
}
}
}
}
/**
* Returns true if taxa are all found in availableTaxa
*
* @param taxa a set of taxa
* @param availableTaxa a potential superset of taxa
* @return true if the taxa are all found in availableTaxa
*/
private boolean isCompatible(Taxa taxa, List<Taxon> availableTaxa) {
for (int i = 0; i < taxa.getTaxonCount(); i++) {
Taxon taxon = taxa.getTaxon(i);
if (!availableTaxa.contains(taxon)) {
return false;
}
}
return true;
}
private boolean checkCompatibility(Taxa taxa) {
for (Taxa taxa2 : options.taxonSets) {
if (taxa2 != taxa && options.taxonSetsMono.get(taxa2)) {
if (taxa.containsAny(taxa2) && !taxa.containsAll(taxa2) && !taxa2.containsAll(taxa)) {
JOptionPane.showMessageDialog(frame,
"You cannot enforce monophyly on this taxon set \n" +
"because it is not compatible with another taxon \n" +
"set, " + taxa2.getId() + ", for which monophyly is\n" +
"enforced.",
"Warning",
JOptionPane.WARNING_MESSAGE);
return false;
}
}
}
return true;
}
class TaxonSetsTableModel extends AbstractTableModel {
private static final long serialVersionUID = 3318461381525023153L;
public TaxonSetsTableModel() {
}
public int getColumnCount() {
return 2;
}
public int getRowCount() {
if (options == null) return 0;
return options.taxonSets.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
Taxa taxonSet = options.taxonSets.get(rowIndex);
switch (columnIndex) {
case 0:
return taxonSet.getId();
case 1:
return options.taxonSetsMono.get(taxonSet);
}
return null;
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Taxa taxonSet = options.taxonSets.get(rowIndex);
switch (columnIndex) {
case 0: {
taxonSet.setId(aValue.toString());
setTaxonSetTitle();
break;
}
case 1: {
if ((Boolean) aValue) {
Taxa taxa = options.taxonSets.get(rowIndex);
if (checkCompatibility(taxa)) {
options.taxonSetsMono.put(taxonSet, (Boolean) aValue);
}
} else {
options.taxonSetsMono.put(taxonSet, (Boolean) aValue);
}
break;
}
}
}
public boolean isCellEditable(int row, int col) {
return true;
}
public String getColumnName(int column) {
switch (column) {
case 0:
return "Taxon Sets";
case 1:
return "Monophyletic?";
}
return null;
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
}
private JPanel createAddRemoveButtonPanel(Action addAction, Icon addIcon, String addToolTip,
Action removeAction, Icon removeIcon, String removeToolTip, int axis) {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, axis));
buttonPanel.setOpaque(false);
JButton addButton = new JButton(addAction);
if (addIcon != null) {
addButton.setIcon(addIcon);
addButton.setText(null);
}
addButton.setToolTipText(addToolTip);
addButton.putClientProperty("JButton.buttonType", "roundRect");
// addButton.putClientProperty("JButton.buttonType", "toolbar");
addButton.setOpaque(false);
addAction.setEnabled(false);
JButton removeButton = new JButton(removeAction);
if (removeIcon != null) {
removeButton.setIcon(removeIcon);
removeButton.setText(null);
}
removeButton.setToolTipText(removeToolTip);
removeButton.putClientProperty("JButton.buttonType", "roundRect");
// removeButton.putClientProperty("JButton.buttonType", "toolbar");
removeButton.setOpaque(false);
removeAction.setEnabled(false);
buttonPanel.add(addButton);
buttonPanel.add(new JToolBar.Separator(new Dimension(6, 6)));
buttonPanel.add(removeButton);
return buttonPanel;
}
private void excludedTaxaTableSelectionChanged() {
if (excludedTaxaTable.getSelectedRowCount() == 0) {
includeTaxonAction.setEnabled(false);
} else {
includeTaxonAction.setEnabled(true);
}
}
private void includedTaxaTableSelectionChanged() {
if (includedTaxaTable.getSelectedRowCount() == 0) {
excludeTaxonAction.setEnabled(false);
} else {
excludeTaxonAction.setEnabled(true);
}
}
private void includeSelectedTaxa() {
int[] rows = excludedTaxaTable.getSelectedRows();
List<Taxon> transfer = new ArrayList<Taxon>();
for (int r : rows) {
transfer.add(excludedTaxa.get(r));
}
includedTaxa.addAll(transfer);
Collections.sort(includedTaxa);
excludedTaxa.removeAll(includedTaxa);
includedTaxaTableModel.fireTableDataChanged();
excludedTaxaTableModel.fireTableDataChanged();
includedTaxaTable.getSelectionModel().clearSelection();
for (Taxon taxon : transfer) {
int row = includedTaxa.indexOf(taxon);
includedTaxaTable.getSelectionModel().addSelectionInterval(row, row);
}
taxonSetChanged();
}
private void excludeSelectedTaxa() {
int[] rows = includedTaxaTable.getSelectedRows();
List<Taxon> transfer = new ArrayList<Taxon>();
for (int r : rows) {
transfer.add(includedTaxa.get(r));
}
excludedTaxa.addAll(transfer);
Collections.sort(excludedTaxa);
includedTaxa.removeAll(excludedTaxa);
includedTaxaTableModel.fireTableDataChanged();
excludedTaxaTableModel.fireTableDataChanged();
excludedTaxaTable.getSelectionModel().clearSelection();
for (Taxon taxon : transfer) {
int row = excludedTaxa.indexOf(taxon);
excludedTaxaTable.getSelectionModel().addSelectionInterval(row, row);
}
taxonSetChanged();
}
Action includeTaxonAction = new AbstractAction("->") {
private static final long serialVersionUID = 7510299673661594128L;
public void actionPerformed(ActionEvent ae) {
includeSelectedTaxa();
}
};
Action excludeTaxonAction = new AbstractAction("<-") {
private static final long serialVersionUID = 449692708602410206L;
public void actionPerformed(ActionEvent ae) {
excludeSelectedTaxa();
}
};
class TaxaTableModel extends AbstractTableModel {
private static final long serialVersionUID = -8027482229525938010L;
boolean included;
public TaxaTableModel(boolean included) {
this.included = included;
}
public int getColumnCount() {
return 1;
}
public int getRowCount() {
if (currentTaxonSet == null) return 0;
if (included) {
return includedTaxa.size();
} else {
return excludedTaxa.size();
}
}
public Object getValueAt(int row, int col) {
if (included) {
return includedTaxa.get(row).getId();
} else {
return excludedTaxa.get(row).getId();
}
}
public boolean isCellEditable(int row, int col) {
return false;
}
public String getColumnName(int column) {
if (included) return "Included Taxa";
else return "Excluded Taxa";
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
}
}
|
package org.javarosa.core.model;
import org.javarosa.core.model.instance.TreeReference;
import java.util.Vector;
/**
* A Form Index is an immutable index into a specific question definition that
* will appear in an interaction with a user.
*
* An index is represented by different levels into hierarchical groups.
*
* Indices can represent both questions and groups.
*
* It is absolutely essential that there be no circularity of reference in
* FormIndex's, IE, no form index's ancestor can be itself.
*
* Datatype Productions:
* FormIndex = BOF | EOF | CompoundIndex(nextIndex:FormIndex,Location)
* Location = Empty | Simple(localLevel:int) | WithMult(localLevel:int, multiplicity:int)
*
* @author Clayton Sims
*/
public class FormIndex {
private boolean beginningOfForm = false;
private boolean endOfForm = false;
/**
* The index of the questiondef in the current context
*/
private int localIndex;
/**
* The multiplicity of the current instance of a repeated question or group
*/
private int instanceIndex = -1;
/**
* The next level of this index
*/
private FormIndex nextLevel;
private TreeReference reference;
public static FormIndex createBeginningOfFormIndex() {
FormIndex begin = new FormIndex(-1, null);
begin.beginningOfForm = true;
return begin;
}
public static FormIndex createEndOfFormIndex() {
FormIndex end = new FormIndex(-1, null);
end.endOfForm = true;
return end;
}
/**
* Constructs a simple form index that references a specific element in
* a list of elements.
*
* @param localIndex An integer index into a flat list of elements
* @param reference A reference to the instance element identified by this index;
*/
public FormIndex(int localIndex, TreeReference reference) {
this.localIndex = localIndex;
this.reference = reference;
}
/**
* Constructs a simple form index that references a specific element in
* a list of elements.
*
* @param localIndex An integer index into a flat list of elements
* @param instanceIndex An integer index expressing the multiplicity
* of the current level
* @param reference A reference to the instance element identified by this index;
*/
public FormIndex(int localIndex, int instanceIndex, TreeReference reference) {
this.localIndex = localIndex;
this.instanceIndex = instanceIndex;
this.reference = reference;
}
/**
* Constructs an index which indexes an element, and provides an index
* into that elements children
*
* @param nextLevel An index into the referenced element's index
* @param localIndex An index to an element at the current level, a child
* element of which will be referenced by the nextLevel index.
* @param reference A reference to the instance element identified by this index;
*/
public FormIndex(FormIndex nextLevel, int localIndex, TreeReference reference) {
this(localIndex, reference);
this.nextLevel = nextLevel;
}
/**
* Constructs an index which references an element past the level of
* specificity of the current context, founded by the currentLevel
* index.
* (currentLevel, (nextLevel...))
*/
public FormIndex(FormIndex nextLevel, FormIndex currentLevel) {
if (currentLevel == null) {
this.nextLevel = nextLevel.nextLevel;
this.localIndex = nextLevel.localIndex;
this.instanceIndex = nextLevel.instanceIndex;
this.reference = nextLevel.reference;
} else {
this.nextLevel = nextLevel;
this.localIndex = currentLevel.getLocalIndex();
this.instanceIndex = currentLevel.getInstanceIndex();
this.reference = currentLevel.reference;
}
}
/**
* Constructs an index which indexes an element, and provides an index
* into that elements children, along with the current index of a
* repeated instance.
*
* @param nextLevel An index into the referenced element's index
* @param localIndex An index to an element at the current level, a child
* element of which will be referenced by the nextLevel index.
* @param instanceIndex How many times the element referenced has been
* repeated.
* @param reference A reference to the instance element identified by this index;
*/
public FormIndex(FormIndex nextLevel, int localIndex, int instanceIndex, TreeReference reference) {
this(nextLevel, localIndex, reference);
this.instanceIndex = instanceIndex;
}
public boolean isInForm() {
return !beginningOfForm && !endOfForm;
}
/**
* @return The index of the element in the current context
*/
public int getLocalIndex() {
return localIndex;
}
/**
* @return The multiplicity of the current instance of a repeated question or group
*/
public int getInstanceIndex() {
return instanceIndex;
}
/**
* For the fully qualified element, get the multiplicity of the element's reference
*
* @return The terminal element (fully qualified)'s instance index
*/
public int getElementMultiplicity() {
return getTerminal().instanceIndex;
}
/**
* @return An index into the next level of specificity past the current context. An
* example would be an index into an element that is a child of the element referenced
* by the local index.
*/
public FormIndex getNextLevel() {
return nextLevel;
}
public TreeReference getLocalReference() {
return reference;
}
/**
* @return The TreeReference of the fully qualified element described by this
* FormIndex.
*/
public TreeReference getReference() {
return getTerminal().reference;
}
public FormIndex getTerminal() {
FormIndex walker = this;
while (walker.nextLevel != null) {
walker = walker.nextLevel;
}
return walker;
}
/**
* Identifies whether this is a terminal index, in other words whether this
* index references with more specificity than the current context
*/
public boolean isTerminal() {
return nextLevel == null;
}
public boolean isEndOfFormIndex() {
return endOfForm;
}
public boolean isBeginningOfFormIndex() {
return beginningOfForm;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof FormIndex))
return false;
FormIndex a = this;
FormIndex b = (FormIndex)o;
return (a.compareTo(b) == 0);
}
public int compareTo(Object o) {
if (!(o instanceof FormIndex))
throw new IllegalArgumentException("Attempt to compare Object of type " + o.getClass().getName() + " to a FormIndex");
FormIndex a = this;
FormIndex b = (FormIndex)o;
if (a.beginningOfForm) {
return (b.beginningOfForm ? 0 : -1);
} else if (a.endOfForm) {
return (b.endOfForm ? 0 : 1);
} else {
//a is in form
if (b.beginningOfForm) {
return 1;
} else if (b.endOfForm) {
return -1;
}
}
if (a.localIndex != b.localIndex) {
return (a.localIndex < b.localIndex ? -1 : 1);
} else if (a.instanceIndex != b.instanceIndex) {
return (a.instanceIndex < b.instanceIndex ? -1 : 1);
} else if ((a.getNextLevel() == null) != (b.getNextLevel() == null)) {
return (a.getNextLevel() == null ? -1 : 1);
} else if (a.getNextLevel() != null) {
return a.getNextLevel().compareTo(b.getNextLevel());
} else {
return 0;
}
}
/**
* @return Only the local component of this Form Index.
*/
public FormIndex snip() {
return new FormIndex(localIndex, instanceIndex, reference);
}
/**
* Takes in a form index which is a subset of this index, and returns the
* total difference between them. This is useful for stepping up the level
* of index specificty. If the subIndex is not a valid subIndex of this index,
* null is returned. Since the FormIndex represented by null is always a subset,
* if null is passed in as a subIndex, the full index is returned
*
* For example:
* Indices
* a = 1_0,2,1,3
* b = 1,3
*
* a.diff(b) = 1_0,2
*/
public FormIndex diff(FormIndex subIndex) {
if (subIndex == null) {
return this;
}
if (!isSubIndex(this, subIndex)) {
return null;
}
if (subIndex.equals(this)) {
return null;
}
return new FormIndex(nextLevel.diff(subIndex), this.snip());
}
@Override
public String toString() {
String ret = "";
FormIndex ref = this;
while (ref != null) {
ret += ref.getLocalIndex();
ret += ref.getInstanceIndex() == -1 ? ", " : "_" + ref.getInstanceIndex() + ", ";
ref = ref.nextLevel;
}
return ret;
}
/**
* @return the level of this index relative to the top level of the form
*/
public int getDepth() {
int depth = 0;
FormIndex ref = this;
while (ref != null) {
ref = ref.nextLevel;
depth++;
}
return depth;
}
public static boolean isSubIndex(FormIndex parent, FormIndex child) {
if (child.equals(parent)) {
return true;
} else {
if (parent == null) {
return false;
}
return isSubIndex(parent.nextLevel, child);
}
}
public static boolean isSubElement(FormIndex parent, FormIndex child) {
while (!parent.isTerminal() && !child.isTerminal()) {
if (parent.getLocalIndex() != child.getLocalIndex()) {
return false;
}
if (parent.getInstanceIndex() != child.getInstanceIndex()) {
return false;
}
parent = parent.nextLevel;
child = child.nextLevel;
}
//If we've gotten this far, at least one of the two is terminal
if (!parent.isTerminal() && child.isTerminal()) {
//can't be the parent if the child is earlier on
return false;
} else if (parent.getLocalIndex() != child.getLocalIndex()) {
//Either they're at the same level, in which case only
//identical indices should match, or they should have
//the same root
return false;
} else if (parent.getInstanceIndex() != -1 && (parent.getInstanceIndex() != child.getInstanceIndex())) {
return false;
}
//Barring all of these cases, it should be true.
return true;
}
/**
* @return Do all the entries of two FormIndexes match except for the last instance index?
*/
public static boolean areSiblings(FormIndex a, FormIndex b) {
if (a.isTerminal() && b.isTerminal() && a.getLocalIndex() == b.getLocalIndex()) {
return true;
}
if (!a.isTerminal() && !b.isTerminal()) {
if (a.getLocalIndex() != b.getLocalIndex()) {
return false;
}
return areSiblings(a.nextLevel, b.nextLevel);
}
return false;
}
/**
* @return Do all the local indexes in the 'parent' FormIndex match the
* corresponding ones in 'child'?
*/
public static boolean overlappingLocalIndexesMatch(FormIndex parent, FormIndex child) {
if (parent.getDepth() > child.getDepth()) {
return false;
}
while (!parent.isTerminal()) {
if (parent.getLocalIndex() != child.getLocalIndex()) {
return false;
}
parent = parent.nextLevel;
child = child.nextLevel;
}
return parent.getLocalIndex() == child.getLocalIndex();
}
/**
* Used by Touchforms
*/
@SuppressWarnings("unused")
public void assignRefs(FormDef f) {
FormIndex cur = this;
Vector<Integer> indexes = new Vector<Integer>();
Vector<Integer> multiplicities = new Vector<Integer>();
Vector<IFormElement> elements = new Vector<IFormElement>();
f.collapseIndex(this, indexes, multiplicities, elements);
Vector<Integer> curMults = new Vector<Integer>();
Vector<IFormElement> curElems = new Vector<IFormElement>();
int i = 0;
while (cur != null) {
curMults.addElement(multiplicities.elementAt(i));
curElems.addElement(elements.elementAt(i));
cur.reference = f.getChildInstanceRef(curElems, curMults);
cur = cur.getNextLevel();
i++;
}
}
}
|
package dr.inference.operators;
import dr.xml.*;
import dr.inference.model.Parameter;
import dr.inference.model.Statistic;
import dr.inference.distribution.MixedDistributionLikelihood;
import dr.math.MathUtils;
/**
* Given a values vector (data) and an indicators vector (boolean vector indicating wheather the corrosponding value
* is used or ignored), this operator explores all possible positions for the used data points while preserving their
* order.
* The distribition is uniform on all possible data positions.
*
* For example, if data values A and B are used in a vector of dimension 4, each of the following states is visited 1/6
* of the time.
*
* ABcd 1100
* AcBd 1010
* AcdB 1001
* cABd 0110
* cAdB 0101
* cdAB 0011
*
* The operator works by picking a 1 bit in the indicators and swapping it with a neighbour 0, with the appropriate
* adjustment to the hastings ratio since a pair of 1,1 and 0,0 are never swapped, and the ends can be swapped in one
* direction only.
*
* @author Joseph Heled
* @version $Id$
*/
public class BitSwapOperator extends SimpleMCMCOperator {
public static final String BIT_SWAP_OPERATOR = "bitSwapOperator";
public static final String RADIUS = "radius";
private Parameter data;
private Parameter indicators;
private final boolean impliedOne;
private int radious;
public BitSwapOperator(Parameter data, Parameter indicators, int radius, int weight) {
this.data = data;
this.indicators = indicators;
this.radious = radius;
setWeight(weight);
final int iDim = indicators.getDimension();
final int dDim = data.getDimension();
if (iDim == dDim -1) {
impliedOne = true;
} else if (iDim == dDim) {
impliedOne = false;
} else {
throw new IllegalArgumentException();
}
}
public String getPerformanceSuggestion() {
return "";
}
public String getOperatorName() {
return BIT_SWAP_OPERATOR; // todo is that right, seems to conflict with bitSwap
}
// private boolean allZeros(int start, int stop) {
// for (int i = start; i < stop; i++) {
// if( indicators.getStatisticValue(i) > 0 ) {
// return false;
// return true;
public double doOperation() throws OperatorFailedException {
final int dim = indicators.getDimension();
if( dim < 2 ) {
throw new OperatorFailedException("no swaps possible");
}
int nLoc = 0;
int[] loc = new int[2*dim];
double hastingsRatio;
int pos;
int direction;
int nOnes = 0;
if( radious > 0 ) {
for (int i = 0; i < dim; i++) {
final double value = indicators.getStatisticValue(i);
if( value > 0 ) {
++nOnes;
loc[nLoc] = i;
++nLoc;
}
}
if( nOnes == 0 || nOnes == dim ) {
throw new OperatorFailedException("no swaps possible");
//return 0;
}
hastingsRatio = 0.0;
final int rand = MathUtils.nextInt(nLoc);
pos = loc[rand];
direction = MathUtils.nextInt(2*radious);
direction -= radious - (direction < radious ? 0 : 1);
for (int i = direction > 0 ? pos+1 : pos + direction; i < (direction > 0 ? pos + direction + 1 : pos); i++) {
if( i < 0 || i >= dim || indicators.getStatisticValue(i) > 0 ) {
throw new OperatorFailedException("swap faild");
}
}
} else {
double prev = -1;
for (int i = 0; i < dim; i++) {
final double value = indicators.getStatisticValue(i);
if( value > 0 ) {
++nOnes;
if( i > 0 && prev == 0 ) {
loc[nLoc] = -(i+1);
++nLoc;
}
if( i < dim-1 && indicators.getStatisticValue(i+1) == 0 ) {
loc[nLoc] = (i+1);
++nLoc;
}
}
prev = value;
}
if( nOnes == 0 || nOnes == dim ) {
return 0;
}
if( ! (nLoc > 0) ) {
// System.out.println(indicators);
assert false : indicators;
}
final int rand = MathUtils.nextInt(nLoc);
pos = loc[rand];
direction = pos < 0 ? -1 : 1;
pos = (pos < 0 ? -pos : pos) - 1;
final int maxOut = 2 * nOnes;
hastingsRatio = (maxOut == nLoc) ? 0.0 : Math.log((double)nLoc/maxOut);
}
// System.out.println("swap " + pos + "<->" + nto + " " +
// indicators.getParameterValue(pos) + "<->" + indicators.getParameterValue(nto) +
// " " + data.getParameterValue(pos) + "<->" + data.getParameterValue(nto));
final int nto = pos + direction;
double vto = indicators.getStatisticValue(nto);
indicators.setParameterValue(nto, indicators.getParameterValue(pos));
indicators.setParameterValue(pos, vto);
final int dataOffset = impliedOne ? 1 : 0;
final int ntodata = nto + dataOffset;
final int posdata = pos + dataOffset;
vto = data.getStatisticValue(ntodata);
data.setParameterValue(ntodata, data.getParameterValue(posdata));
data.setParameterValue(posdata, vto);
// System.out.println("after " + pos + "<->" + nto + " " +
// indicators.getParameterValue(pos) + "<->" + indicators.getParameterValue(nto) +
// " " + data.getParameterValue(pos) + "<->" + data.getParameterValue(nto));
return hastingsRatio;
}
private static final String DATA = MixedDistributionLikelihood.DATA;
private static final String INDICATORS = MixedDistributionLikelihood.INDICATORS;
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() { return BIT_SWAP_OPERATOR; }
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final int weight = xo.getIntegerAttribute(WEIGHT);
Parameter data = (Parameter )((XMLObject)xo.getChild(DATA)).getChild(Parameter.class);
Parameter indicators = (Parameter)((XMLObject)xo.getChild(INDICATORS)).getChild(Parameter.class);
int radius = -1;
if( xo.hasAttribute(RADIUS) ) {
double rd = xo.getDoubleAttribute(RADIUS);
if( rd > 0 ) {
if( rd < 1 ) {
rd = Math.round(rd * indicators.getDimension());
}
radius = (int)Math.round(rd);
if( ! (radius >= 1 && radius < indicators.getDimension()-1) ) {
radius = -1;
}
}
if( radius < 1 ) {
throw new XMLParseException("invalid radius " + rd);
}
}
return new BitSwapOperator(data, indicators, radius, weight);
}
|
package edu.iu.grid.oim.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import com.divrep.DivRep;
import com.divrep.DivRepEvent;
import com.divrep.common.DivRepButton;
import com.divrep.common.DivRepStaticContent;
import com.divrep.common.DivRepToggler;
import edu.iu.grid.oim.lib.StaticConfig;
import edu.iu.grid.oim.model.db.ContactModel;
import edu.iu.grid.oim.model.db.DNModel;
import edu.iu.grid.oim.model.db.ResourceContactModel;
import edu.iu.grid.oim.model.db.ResourceModel;
import edu.iu.grid.oim.model.db.SCContactModel;
import edu.iu.grid.oim.model.db.SCModel;
import edu.iu.grid.oim.model.db.VOContactModel;
import edu.iu.grid.oim.model.db.VOModel;
import edu.iu.grid.oim.model.db.record.DNRecord;
import edu.iu.grid.oim.model.db.record.ContactRecord;
import edu.iu.grid.oim.model.db.record.ResourceContactRecord;
import edu.iu.grid.oim.model.db.record.ResourceRecord;
import edu.iu.grid.oim.model.db.record.SCContactRecord;
import edu.iu.grid.oim.model.db.record.SCRecord;
import edu.iu.grid.oim.model.db.record.VOContactRecord;
import edu.iu.grid.oim.model.db.record.VORecord;
import edu.iu.grid.oim.view.BreadCrumbView;
import edu.iu.grid.oim.view.ContactAssociationView;
import edu.iu.grid.oim.view.ContentView;
import edu.iu.grid.oim.view.DivRepWrapper;
import edu.iu.grid.oim.view.GenericView;
import edu.iu.grid.oim.view.HtmlView;
import edu.iu.grid.oim.view.ItemTableView;
import edu.iu.grid.oim.view.MenuView;
import edu.iu.grid.oim.view.Page;
import edu.iu.grid.oim.view.RecordTableView;
import edu.iu.grid.oim.view.SideContentView;
import edu.iu.grid.oim.view.divrep.ViewWrapper;
public class ContactServlet extends ServletBase implements Servlet {
private static final long serialVersionUID = 1L;
static Logger log = Logger.getLogger(ContactServlet.class);
public ContactServlet() {
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
auth.check("edit_my_contact");
try {
//construct view
//MenuView menuview = new MenuView(context, "contact");
//ContentView contentview = createContentView();
MenuView menuview = new MenuView(context, "contact");
ContentView contentview = null;
//display either list, or a single resource
ContactRecord rec = null;
String contact_id_str = request.getParameter("id");
if(contact_id_str != null) {
Integer contact_id = Integer.parseInt(contact_id_str);
ContactModel model = new ContactModel(context);
rec = model.get(contact_id);
contentview = new ContentView();
// setup crumbs
BreadCrumbView bread_crumb = new BreadCrumbView();
// bread_crumb.addCrumb("Administration", "admin");
bread_crumb.addCrumb("Contact", "contact");
bread_crumb.addCrumb(rec.name, null);
contentview.setBreadCrumb(bread_crumb);
contentview.add(new HtmlView("<h2>"+StringEscapeUtils.escapeHtml(rec.name)+"</h2>"));
contentview.add(createContent(rec, false)); //false = no edit button
} else {
//pull list of all contacts
contentview = createContentView();
}
Page page = new Page(context, menuview, contentview, createSideView(rec));
page.render(response.getWriter());
} catch (SQLException e) {
log.error(e);
throw new ServletException(e);
}
}
protected ContentView createContentView()
throws ServletException, SQLException
{
ContactModel model = new ContactModel(context);
ArrayList<ContactRecord> contacts = model.getAll();
Collections.sort(contacts, new Comparator<ContactRecord> (){
public int compare(ContactRecord a, ContactRecord b) {
return a.getName().compareToIgnoreCase(b.getName()); // We are comparing based on name
}
});
Collections.sort(contacts, new Comparator<ContactRecord> (){
public int compare(ContactRecord a, ContactRecord b) {
return a.isPerson().compareTo(b.isPerson()); // We are comparing based on bool person
}
});
Collections.sort(contacts, new Comparator<ContactRecord> (){
public int compare(ContactRecord a, ContactRecord b) {
return a.isDisabled().compareTo(b.isDisabled()); // We are comparing based on bool disable (disabled ones will go in the end)
}
});
ContentView contentview = new ContentView();
ArrayList<ContactRecord> editable_contacts = new ArrayList<ContactRecord>();
ArrayList<ContactRecord> editable_disabled_contacts = new ArrayList<ContactRecord>();
ArrayList<ContactRecord> readonly_contacts = new ArrayList<ContactRecord>();
for(ContactRecord rec : contacts) {
if(model.canEdit(rec.id)) {
if (rec.isDisabled()) {
editable_disabled_contacts.add(rec);
} else {
editable_contacts.add(rec);
}
} else {
readonly_contacts.add(rec);
}
}
return createContentViewHelper (contentview, editable_contacts, editable_disabled_contacts, readonly_contacts);
}
protected ContentView createContentViewHelper (ContentView contentview,
Collection<ContactRecord> editable_contacts,
Collection<ContactRecord> editable_disabled_contacts,
Collection<ContactRecord> readonly_contacts)
throws ServletException, SQLException
{
contentview.add(new HtmlView("<h2>My Contacts</h2>"));
if(editable_contacts.size() == 0) {
contentview.add(new HtmlView("<p>There are currently no contacts that you submitted (and therefore would have been able to edit).</p>"));
} else {
contentview.add(new HtmlView("<p>Here are the contacts you submitted, and therefore are able to edit.</p>"));
}
ItemTableView table = new ItemTableView(4);
for(ContactRecord rec : editable_contacts) {
table.add(new HtmlView(getContactHeader(rec, true)));
//contentview.add(showContact(rec, true)); //true = show edit button
}
contentview.add(table);
if(auth.allows("admin") && editable_disabled_contacts.size() != 0) {
contentview.add(new HtmlView("<h2>Disabled Contacts (Admin Only)</h2>"));
contentview.add(new HtmlView("<p>Following are the contacts that are currently disabled.</p>"));
table = new ItemTableView(4);
for(ContactRecord rec : editable_disabled_contacts) {
table.add(new HtmlView(getContactHeader(rec, true)));
//contentview.add(showContact(rec, true)); //true = show edit button
}
contentview.add(table);
}
if(readonly_contacts.size() != 0) {
contentview.add(new HtmlView("<h2>Read-Only Contacts</h2>"));
contentview.add(new HtmlView("<p>Following are the contact that are currently registered at OIM that you do not have edit access.</p>"));
table = new ItemTableView(4);
for(ContactRecord rec : readonly_contacts) {
table.add(new HtmlView(getContactHeader(rec, false)));
//contentview.add(showContact(rec, false)); //false = no edit button
}
contentview.add(table);
}
return contentview;
}
private String getContactHeader(ContactRecord rec, boolean edit)
{
String image, name_to_display;
if(rec.person == true) {
image = "<img align=\"top\" src=\""+StaticConfig.getApplicationBase()+"/images/user.png\"/> ";
} else {
image = "<img align=\"top\" src=\""+StaticConfig.getApplicationBase()+"/images/group.png\"/> ";
}
String url = "";
if(edit) {
url = StaticConfig.getApplicationBase()+"/contactedit?id="+rec.id;
} else {
url = StaticConfig.getApplicationBase()+"/contact?id="+rec.id;
}
if(rec.disable == false) {
name_to_display = image+"<a href=\""+url+"\">"+StringEscapeUtils.escapeHtml(rec.name)+"</a>";
} else {
name_to_display = image+"<a href=\""+url+"\" class=\"disabled\">"+StringEscapeUtils.escapeHtml(rec.name)+"</a>";
}
return name_to_display;
}
public DivRep createContent(final ContactRecord rec, final boolean show_edit_button) {
RecordTableView table = new RecordTableView();
try {
table.addRow("Primary Email", new HtmlView("<a class=\"mailto\" href=\"mailto:"+rec.primary_email+"\">"+StringEscapeUtils.escapeHtml(rec.primary_email)+"</a>"));
table.addRow("Secondary Email", rec.secondary_email);
table.addRow("Primary Phone", rec.primary_phone);
table.addRow("Primary Phone Ext", rec.primary_phone_ext);
table.addRow("Secondary Phone", rec.secondary_phone);
table.addRow("Secondary Phone Ext", rec.secondary_phone_ext);
table.addRow("SMS Address", rec.sms_address);
if(rec.person == false) {
table.addRow("Personal Information", new HtmlView("(Not a personal contact)"));
} else {
RecordTableView personal_table = new RecordTableView("inner_table");
table.addRow("Personal Information", personal_table);
personal_table.addRow("Address Line 1", rec.address_line_1);
personal_table.addRow("Address Line 2", rec.address_line_2);
personal_table.addRow("City", rec.city);
personal_table.addRow("State", rec.state);
personal_table.addRow("ZIP Code", rec.zipcode);
personal_table.addRow("Country", rec.country);
personal_table.addRow("Instant Messaging", rec.im);
String img = rec.photo_url;
if(rec.photo_url == null || rec.photo_url.length() == 0) {
img = StaticConfig.getApplicationBase() + "/images/noavatar.gif";
}
personal_table.addRow("Photo", new HtmlView("<img class=\"avatar\" src=\""+img+"\"/>"));
personal_table.addRow("Contact Preference", rec.contact_preference);
personal_table.addRow("Time Zone", rec.timezone);
personal_table.addRow("Profile", new HtmlView("<div>"+StringEscapeUtils.escapeHtml(rec.profile)+"</div>"));
personal_table.addRow("Use TWiki", rec.use_twiki);
personal_table.addRow("TWiki ID", rec.twiki_id);
}
table.addRow("Contact Associations", new ContactAssociationView(context, rec.id));
//table.addRow("Active", rec.active);
table.addRow("Disable", rec.disable);
DNModel dnmodel = new DNModel(context);
if(auth.allows("admin")) {
String submitter_dn = null;
if(rec.submitter_dn_id != null) {
DNRecord dn = dnmodel.get(rec.submitter_dn_id);
submitter_dn = dn.dn_string;
}
table.addRow("Submitter DN", submitter_dn);
}
if(auth.allows("admin")) {
String dn_string = null;
DNRecord dnrec = dnmodel.getByContactID(rec.id);
if(dnrec != null) {
dn_string = dnrec.dn_string;
}
table.addRow("Associated DN", dn_string);
}
if(show_edit_button) {
class EditButtonDE extends DivRepButton
{
String url;
public EditButtonDE(DivRep parent, String _url)
{
super(parent, "Edit");
url = _url;
}
protected void onEvent(DivRepEvent e) {
redirect(url);
}
};
table.add(new DivRepWrapper(new EditButtonDE(context.getPageRoot(), StaticConfig.getApplicationBase()+"/contactedit?id=" + rec.id)));
}
} catch (SQLException e) {
return new DivRepStaticContent(context.getPageRoot(), e.toString());
}
return new ViewWrapper(context.getPageRoot(), table);
}
private SideContentView createSideView(ContactRecord rec)
{
SideContentView view = new SideContentView();
if(rec == null) {
view.add(new HtmlView("<h3>Other Actions</h3>"));
view.add(new HtmlView("<div class=\"indent\">"));
view.add(new HtmlView("<p><a href=\""+StaticConfig.getApplicationBase()+"/contactedit\">Register New Contact</a></p>"));
view.add(new HtmlView("</div>"));
view.add("About", new HtmlView("This page shows a list of contacts on OIM. Contacts can be a person or a mailing list or a service that needs to be registered on OIM to access privileged information on other OSG services. <p><br/> You as a registered OIM user will be able to edit any contact you added. GOC staff are able to edit all contacts including previous de-activated ones. <p><br/> If you want to map a certain person or group contact (and their email/phone number) to a resource, VO, SC, etc. but cannot find that contact already in OIM, then you can add a new contact. <p><br/> Note that if you add a person as a new contact, that person will still not be able to perform any actions inside OIM until they register their X509 certificate on OIM."));
view.addContactGroupFlagLegend();
} else {
//view.addContactLegend();
}
return view;
}
}
|
package edu.mit.streamjit.impl.compiler2;
import com.google.common.base.Function;
import static com.google.common.base.Preconditions.*;
import com.google.common.collect.Collections2;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Range;
import edu.mit.streamjit.util.ReflectionUtils;
import java.lang.invoke.MethodHandle;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* The compiler IR for a Worker or Token.
* @author Jeffrey Bosboom <jeffreybosboom@gmail.com>
* @since 9/21/2013
*/
public abstract class Actor implements Comparable<Actor> {
private ActorGroup group;
/**
* The upstream and downstream Storage, one for each input or output of this
* Actor. TokenActors will have either inputs xor outputs.
*/
private final List<Storage> upstream = new ArrayList<>(), downstream = new ArrayList<>();
/**
* Index functions (int -> int) that transform a nominal index
* (iteration * rate + popCount/pushCount (+ peekIndex)) into a physical
* index (subject to further adjustment if circular buffers are in use).
* One for each input or output of this actor.
*/
private final List<MethodHandle> upstreamIndex = new ArrayList<>(),
downstreamIndex = new ArrayList<>();
protected Actor() {
}
public abstract int id();
public ActorGroup group() {
return group;
}
void setGroup(ActorGroup group) {
assert ReflectionUtils.calledDirectlyFrom(ActorGroup.class);
this.group = group;
}
public final boolean isPeeking() {
for (int i = 0; i < inputs().size(); ++i)
if (peek(i) > pop(i))
return true;
return false;
}
public abstract Class<?> inputType();
public abstract Class<?> outputType();
public List<Storage> inputs() {
return upstream;
}
public List<Storage> outputs() {
return downstream;
}
public List<MethodHandle> inputIndexFunctions() {
return upstreamIndex;
}
public int translateInputIndex(int input, int logicalIndex) {
checkArgument(logicalIndex >= 0);
MethodHandle idxFxn = inputIndexFunctions().get(input);
try {
return (int)idxFxn.invokeExact(logicalIndex);
} catch (Throwable ex) {
throw new AssertionError(String.format("index functions should not throw; translateInputIndex(%d, %d)", input, logicalIndex), ex);
}
}
public ImmutableSortedSet<Integer> translateInputIndices(final int input, Set<Integer> logicalIndices) {
return ImmutableSortedSet.copyOf(Collections2.transform(logicalIndices, new Function<Integer, Integer>() {
@Override
public Integer apply(Integer index) {
return translateInputIndex(input, index);
}
}));
}
public ImmutableSortedSet<Integer> translateInputIndices(final int input, Range<Integer> logicalIndices) {
return translateInputIndices(input, ContiguousSet.create(logicalIndices, DiscreteDomain.integers()));
}
public List<MethodHandle> outputIndexFunctions() {
return downstreamIndex;
}
public int translateOutputIndex(int output, int logicalIndex) {
checkArgument(logicalIndex >= 0);
MethodHandle idxFxn = outputIndexFunctions().get(output);
try {
return (int)idxFxn.invokeExact(logicalIndex);
} catch (Throwable ex) {
throw new AssertionError(String.format("index functions should not throw; translateOutputtIndex(%d, %d)", output, logicalIndex), ex);
}
}
public ImmutableSortedSet<Integer> translateOutputIndices(final int input, Set<Integer> logicalIndices) {
return ImmutableSortedSet.copyOf(Collections2.transform(logicalIndices, new Function<Integer, Integer>() {
@Override
public Integer apply(Integer index) {
return translateOutputIndex(input, index);
}
}));
}
public ImmutableSortedSet<Integer> translateOutputIndices(final int input, Range<Integer> logicalIndices) {
return translateOutputIndices(input, ContiguousSet.create(logicalIndices, DiscreteDomain.integers()));
}
public abstract int peek(int input);
public abstract int pop(int input);
public abstract int push(int output);
/**
* Returns the number of items peeked at but not popped from the given input
* in a single iteration.
* @param input the input index
* @return the number of items peeked but not popped
*/
public int excessPeeks(int input) {
return Math.max(0, peek(input) - pop(input));
}
/**
* Returns the logical indices peeked or popped on the given input during
* the given iteration. Note that this method may return a nonempty set
* even if peeks(input) returns 0 and isPeeking() returns false.
* @param input the input index
* @param iteration the iteration number
* @return the logical indices peeked or popped on the given input during
* the given iteration
*/
public ContiguousSet<Integer> peeks(int input, int iteration) {
return ContiguousSet.create(Range.closedOpen(iteration * pop(input), (iteration + 1) * pop(input) + excessPeeks(input)), DiscreteDomain.integers());
}
/**
* Returns the logical indices peeked or popped on the given input during
* the given iterations. Note that this method may return a nonempty set
* even if peeks(input) returns 0 and isPeeking() returns false.
* @param input the input index
* @param iterations the iteration numbers
* @return the logical indices peeked or popped on the given input during
* the given iterations
*/
public ImmutableSortedSet<Integer> peeks(int input, Set<Integer> iterations) {
if (iterations instanceof ContiguousSet)
return peeks(input, (ContiguousSet<Integer>)iterations);
ImmutableSortedSet.Builder<Integer> builder = ImmutableSortedSet.naturalOrder();
for (int i : iterations)
builder.addAll(peeks(input, i));
return builder.build();
}
/**
* Returns the logical indices peeked or popped on the given input during
* the given iterations. Note that this method may return a nonempty set
* even if peeks(input) returns 0 and isPeeking() returns false.
* @param input the input index
* @param iterations the iteration numbers
* @return the logical indices peeked or popped on the given input during
* the given iterations
*/
public ContiguousSet<Integer> peeks(int input, ContiguousSet<Integer> iterations) {
return ContiguousSet.create(Range.closedOpen(iterations.first() * pop(input), (iterations.last() + 1) * pop(input) + excessPeeks(input)), DiscreteDomain.integers());
}
/**
* Returns the logical indices peeked or popped on the given input during
* the given iterations. Note that this method may return a nonempty set
* even if peeks(input) returns 0 and isPeeking() returns false.
* @param input the input index
* @param iterations the iteration numbers
* @return the logical indices peeked or popped on the given input during
* the given iterations
*/
public ContiguousSet<Integer> peeks(int input, Range<Integer> iterations) {
return peeks(input, ContiguousSet.create(iterations, DiscreteDomain.integers()));
}
//TODO: popped()? (would exclude peeks) Would we ever use it?
/**
* Returns the logical indices pushed to the given output during the given
* iteration.
* @param output the output index
* @param iteration the iteration number
* @return the logical indices pushed to the given input during the given
* iteration
*/
public ContiguousSet<Integer> pushes(int output, int iteration) {
return ContiguousSet.create(Range.closedOpen(iteration * push(output), (iteration + 1) * push(output)), DiscreteDomain.integers());
}
/**
* Returns the logical indices pushed to the given output during the given
* iterations.
* @param output the output index
* @param iterations the iteration numbers
* @return the logical indices pushed to the given input during the given
* iterations
*/
public ImmutableSortedSet<Integer> pushes(int output, Set<Integer> iterations) {
if (iterations instanceof ContiguousSet)
return pushes(output, (ContiguousSet<Integer>)iterations);
ImmutableSortedSet.Builder<Integer> builder = ImmutableSortedSet.naturalOrder();
for (int i : iterations)
builder.addAll(pushes(output, i));
return builder.build();
}
/**
* Returns the logical indices pushed to the given output during the given
* iterations.
* @param output the output index
* @param iterations the iteration numbers
* @return the logical indices pushed to the given input during the given
* iterations
*/
public ContiguousSet<Integer> pushes(int output, ContiguousSet<Integer> iterations) {
return ContiguousSet.create(Range.closedOpen(iterations.first() * push(output), (iterations.last() + 1) * push(output)), DiscreteDomain.integers());
}
/**
* Returns the logical indices pushed to the given output during the given
* iterations.
* @param output the output index
* @param iterations the iteration numbers
* @return the logical indices pushed to the given input during the given
* iterations
*/
public ContiguousSet<Integer> pushes(int output, Range<Integer> iterations) {
return pushes(output, ContiguousSet.create(iterations, DiscreteDomain.integers()));
}
public ImmutableSortedSet<Integer> reads(int input, int iteration) {
return translateInputIndices(input, peeks(input, iteration));
}
public ImmutableSortedSet<Integer> reads(int input, Set<Integer> iterations) {
return translateInputIndices(input, peeks(input, iterations));
}
public ImmutableSortedSet<Integer> reads(int input, Range<Integer> iterations) {
return translateInputIndices(input, peeks(input, iterations));
}
public ImmutableSortedSet<Integer> writes(int output, int iteration) {
return translateOutputIndices(output, pushes(output, iteration));
}
public ImmutableSortedSet<Integer> writes(int output, Set<Integer> iterations) {
return translateOutputIndices(output, pushes(output, iterations));
}
public ImmutableSortedSet<Integer> writes(int output, Range<Integer> iterations) {
return translateOutputIndices(output, pushes(output, iterations));
}
@Override
public final int compareTo(Actor o) {
return Integer.compare(id(), o.id());
}
@Override
public final boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Actor other = (Actor)obj;
if (id() != other.id())
return false;
return true;
}
@Override
public final int hashCode() {
return id();
}
}
|
package edu.wheaton.simulator.statistics;
/**
* This class will save PrototypeSnapshots and AgentSnapshots to a file.
* To be used by other classes that will load and place the appropriate values.
*
* @author Grant Hensel, Nico Lasta
*/
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import edu.wheaton.simulator.entity.Agent;
import edu.wheaton.simulator.entity.Prototype;
import edu.wheaton.simulator.simulation.end.SimulationEnder;
public class Saver {
public void saveSimulation(String filename, Set<Agent> agents, ImmutableSet<Prototype> prototypes,
Map<String, String> globalFields, int width, int height, SimulationEnder simEnder){
StringBuilder sb = new StringBuilder();
//Name the file, first
filename = filename + ".txt";
//Create AgentSnapshots
HashSet<AgentSnapshot> agentSnaps = new HashSet<AgentSnapshot>();
for(Agent a : agents)
agentSnaps.add(SnapshotFactory.makeAgentSnapshot(a, null, 0));
//Create PrototypeSnapshots
HashSet<PrototypeSnapshot> protoSnaps = new HashSet<PrototypeSnapshot>();
for(Prototype p : prototypes)
protoSnaps.add(SnapshotFactory.makePrototypeSnapshot(p));
//Save the Grid dimensions
sb.append(width + "\n");
sb.append(height + "\n");
//Serialize and write all PrototypeSnapshots to file
for(PrototypeSnapshot proto : protoSnaps)
sb.append(proto.serialize() + "\n");
//Serialize and write all AgentSnapshots to file
for(AgentSnapshot snap : agentSnaps)
sb.append(snap.serialize() + "\n");
//Save the Global Fields
sb.append("GlobalVariables");
for (Map.Entry<String, String> entry : globalFields.entrySet())
sb.append("GLOBAL~" + entry.getKey() + "~" + entry.getValue() + "\n");
//Save the Ending Conditions
sb.append(simEnder.serialize());
//Create BufferedWriter and BufferedReader
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(sb.toString());
writer.close();
} catch (IOException e) {
System.err.println("Saver.java: IOException");
e.printStackTrace();
}
//Debugging: What just got saved to file?
System.out.println("The following text was just saved to SimulationState.txt: \n" + sb);
}
/**
* Create a save file for an individual prototype
* @param proto
*/
public void savePrototype(Prototype proto){
StringBuilder sb = new StringBuilder();
PrototypeSnapshot protoSnap = SnapshotFactory.makePrototypeSnapshot(proto);
sb.append(protoSnap.serialize());
String filename = proto.getName() + ".txt";
//Create BufferedWriter and BufferedReader
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(sb.toString());
writer.close();
// if (directory)
// System.out.println("File path: " + file.getAbsolutePath()); // TODO Delete
} catch (IOException e) {
System.err.println("Saver.java: IOException");
e.printStackTrace();
}
//Debugging: What just got saved to file?
System.out.println("The following text was just saved to " + filename + ": \n" + sb);
}
}
|
package es.deusto.deustotech.model;
public interface ICapability {
static enum CAPABILITY {
//USER
USER_BRIGHTNESS, USER_CONTRAST, USER_IMAGES,
USER_INPUT, USER_LANGUAGE, USER_MAX_TEXT_SIZE,
USER_MIN_TEXT_SIZE, USER_OUTPUT, USER_BACKGROUND_COLOR,
USER_TEXT_COLOR, USER_EXPERIENCE, USER_VOLUME,
USER_LOCATION, USER_ACTIVITY, USER_RELATIONSHIP,
//DEVICE
DEVICE_RESOLUTION_WIDTH, DEVICE_RESOLUTION_HEIGTH,
DEVICE_SCREEN_WIDTH, DEVICE_SCREEN_HEIGTH,
DEVICE_BATTERY_LEVEL, DEVICE_ORIENTATION_MODE,
DEVICE_AVAILABLE_NETWORKS, DEVICE_BRIGHTNESS,
DEVICE_VOLUME, DEVICE_ACCELERATION,
//CONTEXT
CONTEXT_LIGHTNING, CONTEXT_NOISE,
CONTEXT_PRESSURE, CONTEXT_TEMPERATURE,
CONTEXT_CALENDAR, CONTEXT_TIME
};
//User
static enum LOCATION {
HOME, STREET, PUBLIC_BUILDING,
WORK
};
static enum BRIGHTNESS {
DEFAULT, LOW, HIGH, VERY_HIGH,
ONLY_LOW, ONLY_HIGH, ONLY_VERY_HIGH
};
static enum VOLUME {
DEFAULT, LOW, HIGHT, VERY_HIGH
};
static enum ACTIVITIES {
NONE, RESTING, RUNNING
};
static enum RELATIONSHIP {
NONE, SOCIAL, WORK
}
//Context
static enum ILLUMINANCE {
MOONLESS_OVERCAST_NIGHT, // Moonless, overcast night sky (starlight)
MOONLESS_CLEAR_NIGHT, // Moonless clear night sky with airglow
FULL_MOON_CLEAR_NIGHT, // Full moon on a clear night
TWILIGHT_SKY, // Dark limit of civil twilight under a clear sky
LIVING_ROOM, // Family living room lights (Australia, 1998)
TOILET, // Office building hallway/toilet lighting
VERY_DARK_OVERCAST_DAY, // Very dark overcast day
OFFICE, // Office lighting
SUNRISE_CLEAR_DAY, // Sunrise or sunset on a clear day
OVERCAST_DAY, // Overcast day
TV_STUDIO, // typical TV studio lighting
DAYLIGHT, // Full daylight (not direct sun)
SUNLIGHT, // Direct sunlight
COMPARISON_UNAVAILABLE // None of the above
}
static enum NOISE {
VERY_NOISY, // x >= 110 dB
NOISY, // 70 <= x < 110 dB
STREET, // 50 <= x < 70 dB
NOT_NOISY // 0 <= x < 50 dB
};
public Object getCapabilityValue(final CAPABILITY capabilityName);
public void setCapabilityValue(final CAPABILITY capabilityName, final Object value);
}
|
package org.voltcore.zk;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.WatchedEvent;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.voltcore.utils.CoreUtils;
import org.voltdb.VoltZK;
import com.google.common.collect.ImmutableSet;
import org.voltcore.zk.ZKUtil.CancellableWatcher;
public class LeaderElector {
// The root is always created as INITIALIZING until the first participant is added,
// then it's changed to INITIALIZED.
public static final byte INITIALIZING = 0;
public static final byte INITIALIZED = 1;
private final ZooKeeper zk;
private final String dir;
private final String prefix;
private final byte[] data;
private final LeaderNoticeHandler cb;
private String node = null;
private Set<String> knownChildren = null;
private volatile String leader = null;
private volatile boolean isLeader = false;
private final ExecutorService es;
private final AtomicBoolean m_done = new AtomicBoolean(false);
private final Runnable electionEventHandler = new Runnable() {
@Override
public void run() {
try {
leader = watchNextLowerNode();
} catch (KeeperException.SessionExpiredException e) {
// lost the full connection. some test cases do this...
// means zk shutdown without the elector being shutdown.
// ignore.
e.printStackTrace();
} catch (KeeperException.ConnectionLossException e) {
// lost the full connection. some test cases do this...
// means shutdoown without the elector being
// shutdown; ignore.
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
org.voltdb.VoltDB.crashLocalVoltDB(
"Unexepected failure in LeaderElector.", true, e);
}
if (node != null && node.equals(leader)) {
// become the leader
isLeader = true;
if (cb != null) {
cb.becomeLeader();
}
}
}
};
private final Runnable childrenEventHandler = new Runnable() {
@Override
public void run() {
try {
checkForChildChanges();
} catch (KeeperException.SessionExpiredException e) {
// lost the full connection. some test cases do this...
// means zk shutdown without the elector being shutdown.
// ignore.
e.printStackTrace();
} catch (KeeperException.ConnectionLossException e) {
// lost the full connection. some test cases do this...
// means shutdoown without the elector being
// shutdown; ignore.
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
org.voltdb.VoltDB.crashLocalVoltDB(
"Unexepected failure in LeaderElector.", true, e);
}
}
};
//Cancellable Children watcher cancelled at shutdown time
private class ChildrenCancellableWatcher extends CancellableWatcher {
public ChildrenCancellableWatcher(ExecutorService es) {
super(es);
}
@Override
protected void pProcess(WatchedEvent event) {
try {
if (!m_done.get()) {
es.submit(childrenEventHandler);
}
} catch (RejectedExecutionException e) {
}
}
}
private final ChildrenCancellableWatcher childWatcher;
//Cancellable Election watcher cancelled at shutdown time
private class ElectionCancellableWatcher extends CancellableWatcher {
public ElectionCancellableWatcher(ExecutorService es) {
super(es);
}
@Override
protected void pProcess(WatchedEvent event) {
try {
if (!m_done.get()) {
es.submit(electionEventHandler);
}
} catch (RejectedExecutionException e) {
}
}
}
private final ElectionCancellableWatcher electionWatcher;
public LeaderElector(ZooKeeper zk, String dir, String prefix, byte[] data,
LeaderNoticeHandler cb) {
this.zk = zk;
this.dir = dir;
this.prefix = prefix;
this.data = data;
this.cb = cb;
es = CoreUtils.getCachedSingleThreadExecutor("Leader elector-" + dir, 15000);
electionWatcher = new ElectionCancellableWatcher(es);
childWatcher = new ChildrenCancellableWatcher(es);
}
/**
* Provide a way for clients to create nodes which comply with the leader election
* format without participating in a leader election
* @throws InterruptedException
* @throws KeeperException
*/
public static String createParticipantNode(ZooKeeper zk, String dir, String prefix, byte[] data)
throws KeeperException, InterruptedException
{
createRootIfNotExist(zk, dir);
String node = zk.create(ZKUtil.joinZKPath(dir, prefix + "_"), data,
Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
// Unlock the dir as initialized
zk.setData(dir, new byte[] {INITIALIZED}, -1);
return node;
}
public static void createRootIfNotExist(ZooKeeper zk, String dir)
throws KeeperException, InterruptedException
{
// create the election root node if it doesn't exist.
try {
zk.create(dir, new byte[] {INITIALIZING}, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (KeeperException.NodeExistsException e) {
// expected on all nodes that don't start() first.
}
}
public void start(boolean block) throws KeeperException, InterruptedException, ExecutionException
{
node = createParticipantNode(zk, dir, prefix, data);
Future<?> task = es.submit(electionEventHandler);
if (block) {
task.get();
}
//Only do the extra work for watching children if a callback is registered
if (cb != null) {
task = es.submit(childrenEventHandler);
if (block) {
task.get();
}
}
}
public boolean isLeader() {
return isLeader;
}
/**
* Get the current leader node
* @return
*/
public String leader() {
return leader;
}
public String getNode() {
return node;
}
/**
* Deletes the ephemeral node. Make sure that no future watches will fire.
*
* @throws InterruptedException
* @throws KeeperException
*/
synchronized public void shutdown() throws InterruptedException, KeeperException {
m_done.set(true);
childWatcher.cancel();
electionWatcher.cancel();
es.shutdown();
zk.delete(node, -1);
}
/**
* Set a watch on the node that comes before the specified node in the
* directory.
* @return The lowest sequential node
* @throws Exception
*/
private String watchNextLowerNode() throws KeeperException, InterruptedException {
/*
* Iterate through the sorted list of children and find the given node,
* then setup a electionWatcher on the previous node if it exists, otherwise the
* previous of the previous...until we reach the beginning, then we are
* the lowest node.
*/
List<String> children = zk.getChildren(dir, false);
Collections.sort(children);
String lowest = null;
String previous = null;
ListIterator<String> iter = children.listIterator();
while (iter.hasNext()) {
String child = ZKUtil.joinZKPath(dir, iter.next());
if (lowest == null) {
lowest = child;
previous = child;
continue;
}
if (child.equals(node)) {
while (zk.exists(previous, electionWatcher) == null) {
if (previous.equals(lowest)) {
/*
* If the leader disappeared, and we follow the leader, we
* become the leader now
*/
lowest = child;
break;
} else {
// reverse the direction of iteration
previous = ZKUtil.joinZKPath(dir, iter.previous());
}
}
break;
}
previous = child;
}
return lowest;
}
/*
* Check for a change in present nodes
*/
private void checkForChildChanges() throws KeeperException, InterruptedException {
/*
* Iterate through the sorted list of children and find the given node,
* then setup a electionWatcher on the previous node if it exists, otherwise the
* previous of the previous...until we reach the beginning, then we are
* the lowest node.
*/
Set<String> children = ImmutableSet.copyOf(zk.getChildren(dir, childWatcher));
boolean topologyChange = false;
if (knownChildren != null) {
if (!knownChildren.equals(children)) {
topologyChange = true;
}
}
knownChildren = children;
if (topologyChange && cb != null) {
cb.noticedTopologyChange();
}
}
public static String electionDirForPartition(int partition) {
return ZKUtil.path(VoltZK.leaders_initiators, "partition_" + partition);
}
public static int getPartitionFromElectionDir(String partitionDir) {
return Integer.parseInt(partitionDir.substring("partition_".length()));
}
public static String getPrefixFromChildName(String childName) {
return childName.split("_")[0];
}
}
|
package org.croudtrip.places;
import com.google.inject.AbstractModule;
import org.croudtrip.app.CroudTripConfig;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.converter.JacksonConverter;
public class PlacesModule extends AbstractModule {
private final String googleApiKey;
public PlacesModule(CroudTripConfig config) {
this.googleApiKey = config.getGoogleAPIKey();
}
@Override
protected void configure() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint("https://maps.googleapis.com/maps/api/place/")
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addQueryParam("key", googleApiKey);
request.addQueryParam("types", "bus_station|parking|train_station|store|gas_station");
}
})
.setConverter(new JacksonConverter())
.build();
bind(PlacesApi.class).toInstance(adapter.create(PlacesApi.class));
}
}
|
package de.gurkenlabs.utiliti;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.GameData;
import de.gurkenlabs.litiengine.Resources;
import de.gurkenlabs.litiengine.SpriteSheetInfo;
import de.gurkenlabs.litiengine.annotation.ScreenInfo;
import de.gurkenlabs.litiengine.environment.tilemap.IImageLayer;
import de.gurkenlabs.litiengine.environment.tilemap.ITileset;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Blueprint;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Map;
import de.gurkenlabs.litiengine.environment.tilemap.xml.Tileset;
import de.gurkenlabs.litiengine.graphics.ImageCache;
import de.gurkenlabs.litiengine.graphics.ImageFormat;
import de.gurkenlabs.litiengine.graphics.RenderEngine;
import de.gurkenlabs.litiengine.graphics.Spritesheet;
import de.gurkenlabs.litiengine.graphics.particles.xml.CustomEmitter;
import de.gurkenlabs.litiengine.graphics.particles.xml.EmitterData;
import de.gurkenlabs.litiengine.gui.screens.Screen;
import de.gurkenlabs.litiengine.input.Input;
import de.gurkenlabs.litiengine.util.MathUtilities;
import de.gurkenlabs.litiengine.util.io.FileUtilities;
import de.gurkenlabs.litiengine.util.io.XmlUtilities;
import de.gurkenlabs.utiliti.components.EditorComponent;
import de.gurkenlabs.utiliti.components.EditorComponent.ComponentType;
import de.gurkenlabs.utiliti.components.MapComponent;
import de.gurkenlabs.utiliti.swing.XmlImportDialog;
import de.gurkenlabs.utiliti.swing.dialogs.SpritesheetImportPanel;
import de.gurkenlabs.utiliti.swing.panels.MapObjectPanel;
@ScreenInfo(name = "Editor")
public class EditorScreen extends Screen {
private static final Logger log = Logger.getLogger(EditorScreen.class.getName());
private static final int STATUS_DURATION = 5000;
private static final String DEFAULT_GAME_NAME = "game";
private static final String NEW_GAME_STRING = "NEW GAME *";
private static final String GAME_FILE_NAME = "Game Resource File";
private static final String SPRITE_FILE_NAME = "Sprite Info File";
private static final String SPRITESHEET_FILE_NAME = "Spritesheet Image";
public static final Color COLLISION_COLOR = new Color(255, 0, 0, 125);
public static final Color BOUNDINGBOX_COLOR = new Color(0, 0, 255, 125);
public static final Color COMPONENTBACKGROUND_COLOR = new Color(100, 100, 100, 125);
private static EditorScreen instance;
private final List<EditorComponent> comps;
private double padding;
private MapComponent mapComponent;
private GameData gameFile = new GameData();
private EditorComponent current;
private String projectPath;
private String currentResourceFile;
private MapObjectPanel mapEditorPanel;
private MapSelectionPanel mapSelectionPanel;
private long statusTick;
private String currentStatus;
private boolean loading;
private EditorScreen() {
this.comps = new ArrayList<>();
}
public static EditorScreen instance() {
if (instance != null) {
return instance;
}
instance = new EditorScreen();
return instance;
}
public boolean fileLoaded() {
return this.currentResourceFile != null;
}
@Override
public void prepare() {
padding = this.getWidth() / 50;
// init components
this.mapComponent = new MapComponent(this);
this.comps.add(this.mapComponent);
super.prepare();
}
@Override
public void render(final Graphics2D g) {
Game.getCamera().updateFocus();
if (Game.getEnvironment() != null) {
Game.getEnvironment().render(g);
}
if (ImageCache.IMAGES.size() > 200) {
ImageCache.IMAGES.clear();
log.log(Level.INFO, "cache cleared!");
}
if (this.currentResourceFile != null) {
Game.getScreenManager().setTitle(Game.getInfo().getName() + " " + Game.getInfo().getVersion() + " - " + this.currentResourceFile);
String mapName = Game.getEnvironment() != null && Game.getEnvironment().getMap() != null ? "\nMap: " + Game.getEnvironment().getMap().getName() : "";
Program.getTrayIcon().setToolTip(Game.getInfo().getName() + " " + Game.getInfo().getVersion() + "\n" + this.currentResourceFile + mapName);
} else if (this.getProjectPath() != null) {
Game.getScreenManager().setTitle(Game.getInfo().toString() + " - " + NEW_GAME_STRING);
Program.getTrayIcon().setToolTip(Game.getInfo().toString() + "\n" + NEW_GAME_STRING);
} else {
Game.getScreenManager().setTitle(Game.getInfo().toString());
}
super.render(g);
// render mouse/zoom and fps
g.setFont(g.getFont().deriveFont(11f));
g.setColor(Color.WHITE);
Point tile = Input.mouse().getTile();
RenderEngine.drawText(g, "x: " + (int) Input.mouse().getMapLocation().getX() + " y: " + (int) Input.mouse().getMapLocation().getY() + " tile: [" + tile.x + ", " + tile.y + "]" + " zoom: " + (int) (Game.getCamera().getRenderScale() * 100) + " %", 10,
Game.getScreenManager().getResolution().getHeight() - 40);
RenderEngine.drawText(g, Game.getMetrics().getFramesPerSecond() + " FPS", 10, Game.getScreenManager().getResolution().getHeight() - 20);
// render status
if (this.currentStatus != null && !this.currentStatus.isEmpty()) {
long deltaTime = Game.getLoop().getDeltaTime(this.statusTick);
if (deltaTime > STATUS_DURATION) {
this.currentStatus = null;
}
// fade out status color
final double fadeOutTime = 0.75 * STATUS_DURATION;
if (deltaTime > fadeOutTime) {
double fade = deltaTime - fadeOutTime;
int alpha = (int) (255 - (fade / (STATUS_DURATION - fadeOutTime)) * 255);
g.setColor(new Color(255, 255, 255, MathUtilities.clamp(alpha, 0, 255)));
}
Font old = g.getFont();
g.setFont(g.getFont().deriveFont(20.0f));
RenderEngine.drawText(g, this.currentStatus, 10, Game.getScreenManager().getResolution().getHeight() - 60);
g.setFont(old);
}
}
public GameData getGameFile() {
return this.gameFile;
}
public String getProjectPath() {
return projectPath;
}
public double getPadding() {
return this.padding;
}
public void setProjectPath(String projectPath) {
this.projectPath = projectPath;
}
public void changeComponent(EditorComponent.ComponentType type) {
if (this.current != null) {
this.current.suspend();
this.getComponents().remove(this.current);
}
for (EditorComponent comp : this.comps) {
if (comp.getComponentType() == type) {
this.current = comp;
this.current.prepare();
this.getComponents().add(this.current);
break;
}
}
}
public void create() {
JFileChooser chooser;
try {
chooser = new JFileChooser(new File(".").getCanonicalPath());
chooser.setDialogTitle(Resources.get("input_select_project_folder"));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (chooser.showOpenDialog(Game.getScreenManager().getRenderComponent()) != JFileChooser.APPROVE_OPTION) {
return;
}
if (Game.getEnvironment() != null) {
Game.loadEnvironment(null);
}
// set up project settings
this.setProjectPath(chooser.getSelectedFile().getCanonicalPath());
// load all maps in the directory
this.mapComponent.loadMaps(this.getProjectPath());
this.currentResourceFile = null;
this.gameFile = new GameData();
// add sprite sheets by tile sets of all maps in the project director
for (Map map : this.mapComponent.getMaps()) {
this.loadSpriteSheets(map);
}
Program.getAssetTree().forceUpdate();
// load custom emitter files
this.loadCustomEmitters(this.getGameFile().getEmitters());
// update new game file by the loaded information
this.updateGameFileMaps();
// display first available map after loading all stuff
if (!this.mapComponent.getMaps().isEmpty()) {
this.mapComponent.loadEnvironment(this.mapComponent.getMaps().get(0));
this.changeComponent(ComponentType.MAP);
}
} catch (IOException e) {
log.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
this.setCurrentStatus("created new project");
}
public void load() {
JFileChooser chooser;
try {
chooser = new JFileChooser(new File(".").getCanonicalPath());
FileFilter filter = new FileNameExtensionFilter(GAME_FILE_NAME, GameData.FILE_EXTENSION);
chooser.setFileFilter(filter);
chooser.addChoosableFileFilter(filter);
if (chooser.showOpenDialog(Game.getScreenManager().getRenderComponent()) == JFileChooser.APPROVE_OPTION) {
this.load(chooser.getSelectedFile());
}
} catch (IOException e) {
log.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
}
public void load(File gameFile) {
boolean proceedLoading = Program.notifyPendingChanges();
if (!proceedLoading) {
return;
}
final long currentTime = System.nanoTime();
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR_LOAD, 0, 0);
Game.getScreenManager().getRenderComponent().setCursorOffsetX(0);
Game.getScreenManager().getRenderComponent().setCursorOffsetY(0);
this.loading = true;
try {
if (!FileUtilities.getExtension(gameFile).equals(GameData.FILE_EXTENSION)) {
log.log(Level.SEVERE, "unsupported file format {0}", FileUtilities.getExtension(gameFile));
return;
}
if (!gameFile.exists()) {
log.log(Level.SEVERE, "gameFile {0} does not exist", gameFile);
return;
}
UndoManager.clearAll();
// set up project settings
this.currentResourceFile = gameFile.getPath();
this.gameFile = GameData.load(gameFile.getPath());
Program.getUserPreferences().setLastGameFile(gameFile.getPath());
Program.getUserPreferences().addOpenedFile(this.currentResourceFile);
Program.loadRecentFiles();
this.setProjectPath(FileUtilities.getParentDirPath(gameFile.getAbsolutePath()));
// load maps from game file
this.mapComponent.loadMaps(this.getGameFile().getMaps());
ImageCache.clearAll();
Spritesheet.getSpritesheets().clear();
// load sprite sheets from different sources:
// 1. add sprite sheets from game file
// 2. add sprite sheets by tile sets of all maps in the game file
this.loadSpriteSheets(this.getGameFile().getSpriteSheets(), true);
log.log(Level.INFO, "{0} spritesheets loaded from {1}", new Object[] { this.getGameFile().getSpriteSheets().size(), this.currentResourceFile });
for (Map map : this.mapComponent.getMaps()) {
this.loadSpriteSheets(map);
}
// load custom emitter files
this.loadCustomEmitters(this.getGameFile().getEmitters());
Program.getAssetTree().forceUpdate();
// display first available map after loading all stuff
// also switch to map component
if (!this.mapComponent.getMaps().isEmpty()) {
this.mapComponent.loadEnvironment(this.mapComponent.getMaps().get(0));
} else {
Game.loadEnvironment(null);
}
this.changeComponent(ComponentType.MAP);
this.setCurrentStatus(Resources.get("status_gamefile_loaded"));
} finally {
Game.getScreenManager().getRenderComponent().setCursor(Program.CURSOR, 0, 0);
log.log(Level.INFO, "Loading gamefile {0} took: {1} ms", new Object[] { gameFile, (System.nanoTime() - currentTime) / 1000000.0 });
this.loading = false;
}
}
public void importSpriteFile() {
JFileChooser chooser;
try {
chooser = new JFileChooser(new File(this.getProjectPath()).getCanonicalPath());
FileFilter filter = new FileNameExtensionFilter(SPRITE_FILE_NAME, SpriteSheetInfo.PLAIN_TEXT_FILE_EXTENSION);
chooser.setFileFilter(filter);
chooser.addChoosableFileFilter(filter);
if (chooser.showOpenDialog(Game.getScreenManager().getRenderComponent()) == JFileChooser.APPROVE_OPTION) {
File spriteFile = chooser.getSelectedFile();
if (spriteFile == null) {
return;
}
List<Spritesheet> loaded = Spritesheet.load(spriteFile.toString());
List<SpriteSheetInfo> infos = new ArrayList<>();
for (Spritesheet sprite : loaded) {
SpriteSheetInfo info = new SpriteSheetInfo(sprite);
infos.add(info);
this.gameFile.getSpriteSheets().add(info);
}
this.loadSpriteSheets(infos, true);
}
} catch (IOException e) {
log.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
}
public void importSpritesheets() {
JFileChooser chooser;
try {
chooser = new JFileChooser(new File(this.getProjectPath()).getCanonicalPath());
FileFilter filter = new FileNameExtensionFilter(SPRITESHEET_FILE_NAME, ImageFormat.getAllExtensions());
chooser.setFileFilter(filter);
chooser.addChoosableFileFilter(filter);
chooser.setMultiSelectionEnabled(true);
if (chooser.showOpenDialog(Game.getScreenManager().getRenderComponent()) == JFileChooser.APPROVE_OPTION) {
SpritesheetImportPanel spritePanel = new SpritesheetImportPanel(chooser.getSelectedFiles());
int option = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), spritePanel, Resources.get("menu_assets_editSprite"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (option != JOptionPane.OK_OPTION) {
return;
}
final Collection<SpriteSheetInfo> sprites = spritePanel.getSpriteSheets();
for (SpriteSheetInfo spriteFile : sprites) {
this.getGameFile().getSpriteSheets().removeIf(x -> x.getName().equals(spriteFile.getName()));
this.getGameFile().getSpriteSheets().add(spriteFile);
log.log(Level.INFO, "imported spritesheet {0}", new Object[] { spriteFile.getName() });
}
this.loadSpriteSheets(sprites, true);
}
} catch (
IOException e) {
log.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
}
public void importEmitters() {
XmlImportDialog.importXml("Emitter", files -> {
for (File file : files) {
EmitterData emitter = XmlUtilities.readFromFile(EmitterData.class, file.toString());
if (emitter == null) {
continue;
}
if (this.gameFile.getEmitters().stream().anyMatch(x -> x.getName().equals(emitter.getName()))) {
int result = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), Resources.get("import_emitter_question", emitter.getName()), Resources.get("import_emitter_title"), JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.NO_OPTION) {
continue;
}
this.gameFile.getEmitters().removeIf(x -> x.getName().equals(emitter.getName()));
}
this.gameFile.getEmitters().add(emitter);
log.log(Level.INFO, "imported emitter {0} from {1}", new Object[] { emitter.getName(), file });
}
});
}
public void importBlueprints() {
XmlImportDialog.importXml("Blueprint", files -> {
for (File file : files) {
Blueprint blueprint = XmlUtilities.readFromFile(Blueprint.class, file.toString());
if (blueprint == null) {
continue;
}
if (this.gameFile.getBluePrints().stream().anyMatch(x -> x.getName().equals(blueprint.getName()))) {
int result = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), Resources.get("import_blueprint_question", blueprint.getName()), Resources.get("import_blueprint_title"), JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.NO_OPTION) {
continue;
}
this.gameFile.getBluePrints().removeIf(x -> x.getName().equals(blueprint.getName()));
}
this.gameFile.getBluePrints().add(blueprint);
log.log(Level.INFO, "imported blueprint {0} from {1}", new Object[] { blueprint.getName(), file });
}
});
}
public void importTilesets() {
XmlImportDialog.importXml("Tilesets", Tileset.FILE_EXTENSION, files -> {
for (File file : files) {
Tileset tileset = XmlUtilities.readFromFile(Tileset.class, file.toString());
if (tileset == null) {
continue;
}
if (this.gameFile.getTilesets().stream().anyMatch(x -> x.getName().equals(tileset.getName()))) {
int result = JOptionPane.showConfirmDialog(Game.getScreenManager().getRenderComponent(), Resources.get("import_tileset_title", tileset.getName()), Resources.get("import_tileset_title"), JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.NO_OPTION) {
continue;
}
Spritesheet sprite = Spritesheet.find(tileset.getImage().getSource());
if (sprite != null) {
this.getGameFile().getSpriteSheets().removeIf(x -> x.getName().equals(sprite.getName()));
}
this.gameFile.getTilesets().removeIf(x -> x.getName().equals(tileset.getName()));
}
String path = FileUtilities.getParentDirPath(file.getPath());
tileset.setMapPath(path);
Spritesheet sprite = Spritesheet.load(tileset);
this.gameFile.getTilesets().add(tileset);
this.loadSpriteSheets(Arrays.asList(new SpriteSheetInfo(sprite)), true);
log.log(Level.INFO, "imported tileset {0} from {1}", new Object[] { tileset.getName(), file });
}
});
}
public boolean isLoading() {
return this.loading;
}
public void loadSpriteSheets(Collection<SpriteSheetInfo> infos, boolean forceAssetTreeUpdate) {
infos.parallelStream().forEach(info -> {
Spritesheet.remove(info.getName());
if (info.getHeight() == 0 && info.getWidth() == 0) {
return;
}
Spritesheet.load(info);
});
if (this.loading) {
return;
}
ImageCache.clearAll();
this.getMapComponent().reloadEnvironment();
if (forceAssetTreeUpdate) {
Program.getAssetTree().forceUpdate();
}
}
public void save(boolean selectFile) {
this.updateGameFileMaps();
if (this.getGameFile() == null) {
return;
}
if (this.currentResourceFile == null || selectFile) {
JFileChooser chooser;
try {
final String source = this.getProjectPath();
chooser = new JFileChooser(source != null ? source : new File(".").getCanonicalPath());
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
FileFilter filter = new FileNameExtensionFilter(GAME_FILE_NAME, GameData.FILE_EXTENSION);
chooser.setFileFilter(filter);
chooser.addChoosableFileFilter(filter);
chooser.setSelectedFile(new File(DEFAULT_GAME_NAME + "." + GameData.FILE_EXTENSION));
int result = chooser.showSaveDialog(Game.getScreenManager().getRenderComponent());
if (result == JFileChooser.APPROVE_OPTION) {
String newFile = this.saveGameFile(chooser.getSelectedFile().toString());
this.currentResourceFile = newFile;
}
} catch (IOException e1) {
log.log(Level.SEVERE, e1.getLocalizedMessage(), e1);
}
} else {
this.saveGameFile(this.currentResourceFile);
}
}
public MapObjectPanel getMapObjectPanel() {
return mapEditorPanel;
}
public MapComponent getMapComponent() {
return this.mapComponent;
}
public String getCurrentResourceFile() {
return this.currentResourceFile;
}
public void setMapEditorPanel(MapObjectPanel mapEditorPanel) {
this.mapEditorPanel = mapEditorPanel;
}
public MapSelectionPanel getMapSelectionPanel() {
return mapSelectionPanel;
}
public void setMapSelectionPanel(MapSelectionPanel mapSelectionPanel) {
this.mapSelectionPanel = mapSelectionPanel;
}
public String getCurrentStatus() {
return currentStatus;
}
public List<Map> getChangedMaps() {
return this.getMapComponent().getMaps().stream().filter(UndoManager::hasChanges).distinct().collect(Collectors.toList());
}
public void setCurrentStatus(String currentStatus) {
this.currentStatus = currentStatus;
this.statusTick = Game.getLoop().getTicks();
}
public void updateGameFileMaps() {
this.getGameFile().getMaps().clear();
for (Map map : this.mapComponent.getMaps()) {
this.getGameFile().getMaps().add(map);
}
Program.getAssetTree().forceUpdate();
}
private String saveGameFile(String target) {
String saveFile = this.getGameFile().save(target, Program.getUserPreferences().isCompressFile());
Program.getUserPreferences().setLastGameFile(this.currentResourceFile);
Program.getUserPreferences().addOpenedFile(this.currentResourceFile);
Program.loadRecentFiles();
log.log(Level.INFO, "saved {0} maps and {1} tilesets to {2}", new Object[] { this.getGameFile().getMaps().size(), this.getGameFile().getSpriteSheets().size(), this.currentResourceFile });
this.setCurrentStatus(Resources.get("status_gamefile_saved"));
if (Program.getUserPreferences().isSyncMaps()) {
this.saveMaps();
}
this.getMapSelectionPanel().bind(this.getMapComponent().getMaps());
return saveFile;
}
private void saveMaps() {
for (Map map : this.getChangedMaps()) {
UndoManager.save(map);
for (String file : FileUtilities.findFilesByExtension(new ArrayList<>(), Paths.get(this.getProjectPath(), "maps"), map.getName() + "." + Map.FILE_EXTENSION)) {
String newFile = XmlUtilities.save(map, file, Map.FILE_EXTENSION);
log.log(Level.INFO, "synchronized map {0}", new Object[] { newFile });
}
}
}
private void loadCustomEmitters(List<EmitterData> emitters) {
for (EmitterData emitter : emitters) {
CustomEmitter.load(emitter);
}
}
private void loadSpriteSheets(Map map) {
List<SpriteSheetInfo> infos = new ArrayList<>();
int cnt = 0;
for (ITileset tileSet : map.getTilesets()) {
if (tileSet.getImage() == null || Spritesheet.find(tileSet.getName()) != null) {
continue;
}
Spritesheet sprite = Spritesheet.find(tileSet.getImage().getSource());
if (sprite == null) {
sprite = Spritesheet.load(tileSet);
if (sprite == null) {
continue;
}
}
infos.add(new SpriteSheetInfo(sprite));
cnt++;
}
for (IImageLayer imageLayer : map.getImageLayers()) {
Spritesheet sprite = Spritesheet.find(imageLayer.getImage().getSource());
if (sprite == null) {
BufferedImage img = Resources.getImage(imageLayer.getImage().getAbsoluteSourcePath(), true);
sprite = Spritesheet.load(img, imageLayer.getImage().getSource(), img.getWidth(), img.getHeight());
if (sprite == null) {
continue;
}
}
infos.add(new SpriteSheetInfo(sprite));
cnt++;
}
this.loadSpriteSheets(infos, false);
for (SpriteSheetInfo info : infos) {
if (!this.getGameFile().getSpriteSheets().stream().anyMatch(x -> x.getName().equals(info.getName()))) {
this.getGameFile().getSpriteSheets().add(info);
}
}
if (cnt > 0) {
log.log(Level.INFO, "{0} tilesets loaded from {1}", new Object[] { cnt, map.getFileName() });
}
}
}
|
package org.mg.server;
import static org.jboss.netty.channel.Channels.pipeline;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.util.CharsetUtil;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.ChatState;
import org.jivesoftware.smackx.ChatStateListener;
import org.mg.common.MessagePropertyKeys;
import org.mg.common.MgUtils;
import org.mg.common.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class for listening for messages for a specific chat.
*/
public class ChatMessageListener implements ChatStateListener {
private final Logger log = LoggerFactory.getLogger(getClass());
private final Collection<String> removedConnections =
new HashSet<String>();
private final Map<String, ChannelFuture> proxyConnections;
private final String MAC_ADDRESS;
private final ChannelFactory channelFactory;
private final ConcurrentHashMap<String, AtomicLong> channelsToSequenceNumbers =
new ConcurrentHashMap<String, AtomicLong>();
private final XMPPConnection conn;
private final Chat chat;
//private final Queue<Pair<Chat, XMPPConnection>> chatsAndConnections;
private long lastResourceConstraintMessage = 0L;
public ChatMessageListener(
final Map<String, ChannelFuture> proxyConnections,
final Queue<Pair<Chat, XMPPConnection>> chatsAndConnections,
final String macAddress, final ChannelFactory channelFactory,
final Chat chat, final XMPPConnection conn) {
this.proxyConnections = proxyConnections;
//this.chatsAndConnections = chatsAndConnections;
this.MAC_ADDRESS = macAddress;
this.channelFactory = channelFactory;
this.chat = chat;
this.conn = conn;
}
private Queue<Message> rejected = new LinkedBlockingQueue<Message>();
public void processMessage(final Chat ch, final Message msg) {
log.info("Got message!!");
log.info("Property names: {}", msg.getPropertyNames());
final long seq = (Long) msg.getProperty(MessagePropertyKeys.SEQ);
log.info("SEQUENCE #: {}", seq);
log.info("HASHCODE
msg.getProperty(MessagePropertyKeys.HASHCODE));
log.info("FROM: {}",msg.getFrom());
log.info("TO: {}",msg.getTo());
final String smac =
(String) msg.getProperty(MessagePropertyKeys.SERVER_MAC);
log.info("SMAC: {}", smac);
if (StringUtils.isNotBlank(smac) &&
smac.trim().equals(MAC_ADDRESS)) {
log.error("MESSAGE FROM OURSELVES!! AN ERROR?");
final XMPPError error = msg.getError();
if (error != null) {
final int code = msg.getError().getCode();
if (code == 500) {
// Something's up on the server -- we're probably sending
// bytes too fast. Slow down.
lastResourceConstraintMessage = System.currentTimeMillis();
rejected.add(msg);
}
}
MgUtils.printMessage(msg);
return;
}
final String closeString =
(String) msg.getProperty(MessagePropertyKeys.CLOSE);
log.info("Close value: {}", closeString);
final boolean close;
if (StringUtils.isNotBlank(closeString) &&
closeString.trim().equalsIgnoreCase("true")) {
log.info("Got close true");
close = true;
}
else {
close = false;
final String data =
(String) msg.getProperty(MessagePropertyKeys.HTTP);
if (StringUtils.isBlank(data)) {
log.warn("HTTP IS BLANK?? IGNORING...");
return;
}
}
final String key = messageKey(msg);
if (close) {
log.info("Received close from client...closing " +
"connection to the proxy for HASHCODE: {}",
msg.getProperty(MessagePropertyKeys.HASHCODE));
final ChannelFuture cf = proxyConnections.get(key);
if (cf != null) {
log.info("Closing connection");
cf.getChannel().close();
removedConnections.add(key);
proxyConnections.remove(key);
}
else {
log.error("Got close for connection we don't " +
"know about! Removed keys are: {}",
removedConnections);
}
return;
}
log.info("Getting channel future...");
final ChannelFuture cf = getChannelFuture(msg, close, ch);
log.info("Got channel: {}", cf);
if (cf == null) {
log.info("Null channel future! Returning");
return;
}
final ChannelBuffer cb = unwrap(msg);
final AtomicLong expected = getExpectedSequenceNumber(key);
if (seq != expected.get()) {
log.error("GOT UNEXPECTED REQUEST SEQUENCE NUMBER. EXPECTED " +
expected.get()+" BUT WAS "+seq);
}
expected.incrementAndGet();
if (cf.getChannel().isConnected()) {
cf.getChannel().write(cb);
}
else {
cf.addListener(new ChannelFutureListener() {
public void operationComplete(
final ChannelFuture future)
throws Exception {
cf.getChannel().write(cb);
}
});
}
}
private AtomicLong getExpectedSequenceNumber(final String key) {
final AtomicLong zero = new AtomicLong(0);
final AtomicLong existing =
channelsToSequenceNumbers.putIfAbsent(key, zero);
if (existing != null) {
return existing;
}
return zero;
}
public void stateChanged(final Chat monitoredChat, final ChatState state) {
log.info("Got chat state changed: {}", state);
}
private ChannelBuffer unwrap(final Message msg) {
final String data = (String) msg.getProperty(MessagePropertyKeys.HTTP);
final byte[] raw =
Base64.decodeBase64(data.getBytes(CharsetUtil.UTF_8));
return ChannelBuffers.wrappedBuffer(raw);
}
/**
* This gets a channel to connect to the local HTTP proxy on. This is
* slightly complex, as we're trying to mimic the state as if this HTTP
* request is coming in to a "normal" LittleProxy instance instead of
* having the traffic tunneled through XMPP. So we create a separate
* connection to the proxy just as those separate connections were made
* from the browser to the proxy originally on the remote end.
*
* If there's already an existing connection mimicking the original
* connection, we use that.
*
*
* @return The {@link ChannelFuture} that will connect to the local
* LittleProxy instance.
*/
private ChannelFuture getChannelFuture(final Message message,
final boolean close, final Chat requestChat) {
// The other side will also need to know where the
// request came from to differentiate incoming HTTP
// connections.
log.info("Getting properties...");
// Note these will fail if the original properties were not set as
// strings.
final String key = messageKey(message);
if (StringUtils.isBlank(key)) {
log.error("Could not create key");
return null;
}
log.info("Getting channel future for key: {}", key);
synchronized (this.proxyConnections) {
if (proxyConnections.containsKey(key)) {
log.info("Using existing connection");
return proxyConnections.get(key);
}
if (close) {
// We've likely already closed the connection in this case.
log.warn("Returning null channel on close call");
return null;
}
if (removedConnections.contains(key)) {
log.warn("KEY IS IN REMOVED CONNECTIONS: "+key);
}
// Configure the client.
final ClientBootstrap cb = new ClientBootstrap(this.channelFactory);
final ChannelPipelineFactory cpf = new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
final ChannelPipeline pipeline = pipeline();
final class HttpChatRelay extends SimpleChannelUpstreamHandler {
private long sequenceNumber = 0L;
@Override
public void messageReceived(
final ChannelHandlerContext ctx,
final MessageEvent me) {
//log.info("HTTP message received from proxy on " +
// "relayer: {}", me.getMessage());
final Message msg = new Message();
final ByteBuffer buf =
((ChannelBuffer) me.getMessage()).toByteBuffer();
final byte[] raw = toRawBytes(buf);
final String base64 =
Base64.encodeBase64URLSafeString(raw);
msg.setProperty(MessagePropertyKeys.HTTP, base64);
msg.setProperty(MessagePropertyKeys.MD5, toMd5(raw));
sendMessage(msg);
}
@Override
public void channelClosed(final ChannelHandlerContext ctx,
final ChannelStateEvent cse) {
// We need to send the CLOSE directive to the other
// side VIA google talk to simulate the proxy
// closing the connection to the browser.
log.info("Got channel closed on C in A->B->C->D chain...");
log.info("Sending close message");
final Message msg = new Message();
msg.setProperty(MessagePropertyKeys.CLOSE, "true");
sendMessage(msg);
removedConnections.add(key);
proxyConnections.remove(key);
}
private void sendMessage(final Message msg) {
sendRejects();
// We set the sequence number so the client knows
// how many total messages to expect. This is
// necessary because the XMPP server can deliver
// messages out of order.
msg.setProperty(MessagePropertyKeys.SEQ,
sequenceNumber);
msg.setProperty(MessagePropertyKeys.HASHCODE,
message.getProperty(MessagePropertyKeys.HASHCODE));
msg.setProperty(MessagePropertyKeys.MAC,
message.getProperty(MessagePropertyKeys.MAC));
// This is the server-side MAC address. This is
// useful because there are odd cases where XMPP
// servers echo back our own messages, and we
// want to ignore them.
log.info("Setting SMAC to: {}", MAC_ADDRESS);
msg.setProperty(MessagePropertyKeys.SERVER_MAC,
MAC_ADDRESS);
log.info("Sending SEQUENCE #: "+sequenceNumber);
//sentMessages.put(sequenceNumber, msg);
log.info("Received from: {}",
requestChat.getParticipant());
sendWithChat(msg);
}
private void sendRejects() {
final long now = System.currentTimeMillis();
final long elapsed =
now - lastResourceConstraintMessage;
final long sleepTime;
if (elapsed < 5000) {
sleepTime = 10000;
}
else if (elapsed < 10000) {
sleepTime = 5000;
}
else if (elapsed < 30000) {
sleepTime = 1000;
}
else {
sleepTime = 0;
}
if (sleepTime > 0) {
log.info("Waiting before sending message");
try {
Thread.sleep(sleepTime);
} catch (final InterruptedException e) {
log.error("Error while sleeping?");
}
}
if (!rejected.isEmpty()) {
while (!rejected.isEmpty()) {
final Message reject = rejected.poll();
sendWithChat(makeCopy(reject));
log.info("Waiting before sending message");
try {
Thread.sleep(2000);
} catch (final InterruptedException e) {
log.error("Error while sleeping?");
}
}
}
}
private void sendWithChat(final Message msg) {
//final Pair<Chat, XMPPConnection> pair =
// chatsAndConnections.poll();
//final Chat chat = pair.getFirst();
log.info("Sending to: {}", chat.getParticipant());
msg.setTo(chat.getParticipant());
//final XMPPConnection conn = pair.getSecond();
final String from = conn.getUser();
msg.setFrom(from);
try {
chat.sendMessage(msg);
sequenceNumber++;
// Note we don't do this in a finally block.
// if an exception happens, it's likely there's
// something wrong with the chat, and we don't
// want to add it back.
//chatsAndConnections.offer(pair);
} catch (final XMPPException e) {
log.error("Could not send chat message", e);
}
}
private Message makeCopy(final Message reject) {
final Message msg = new Message();
msg.setProperty(MessagePropertyKeys.SEQ,
reject.getProperty(MessagePropertyKeys.SEQ));
msg.setProperty(MessagePropertyKeys.HASHCODE,
reject.getProperty(MessagePropertyKeys.HASHCODE));
msg.setProperty(MessagePropertyKeys.MAC,
reject.getProperty(MessagePropertyKeys.MAC));
msg.setProperty(MessagePropertyKeys.SERVER_MAC,
MAC_ADDRESS);
//msg.setTo(chat.getParticipant());
//msg.setFrom(conn.getUser());
final String http =
(String) reject.getProperty(MessagePropertyKeys.HTTP);
if (StringUtils.isNotBlank(http)) {
msg.setProperty(MessagePropertyKeys.HTTP, http);
msg.setProperty(MessagePropertyKeys.MD5,
reject.getProperty(MessagePropertyKeys.MD5));
}
return msg;
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx,
final ExceptionEvent e) throws Exception {
log.error("Caught exception on C in A->B->C->D " +
"chain...", e.getCause());
if (e.getChannel().isOpen()) {
log.warn("Closing open connection");
closeOnFlush(e.getChannel());
}
else {
// We've seen odd cases where channels seem to
// continually attempt connections. Make sure
// we explicitly close the connection here.
log.info("Channel is not open...ignoring");
//log.warn("Closing connection even though " +
// "isOpen is false");
//e.getChannel().close();
}
}
}
pipeline.addLast("handler", new HttpChatRelay());
return pipeline;
}
};
// Set up the event pipeline factory.
cb.setPipelineFactory(cpf);
cb.setOption("connectTimeoutMillis", 40*1000);
log.info("Connecting to localhost proxy");
final ChannelFuture future =
cb.connect(new InetSocketAddress("127.0.0.1", 7777));
proxyConnections.put(key, future);
return future;
}
}
private String messageKey(final Message message) {
final String mac =
(String) message.getProperty(MessagePropertyKeys.MAC);
final String hc =
(String) message.getProperty(MessagePropertyKeys.HASHCODE);
// We can sometimes get messages back that were not intended for us.
// Just ignore them.
if (mac == null || hc == null) {
log.error("Message not intended for us?!?!?\n" +
"Null MAC and/or HASH and to: "+message.getTo());
return null;
}
final String key = mac + hc;
return key;
}
/**
* Closes the specified channel after all queued write requests are flushed.
*/
private void closeOnFlush(final Channel ch) {
log.info("Closing channel on flush: {}", ch);
if (ch.isConnected()) {
ch.write(ChannelBuffers.EMPTY_BUFFER).addListener(
ChannelFutureListener.CLOSE);
}
}
private String toMd5(final byte[] raw) {
try {
final MessageDigest md = MessageDigest.getInstance("MD5");
final byte[] digest = md.digest(raw);
return Base64.encodeBase64URLSafeString(digest);
} catch (final NoSuchAlgorithmException e) {
log.error("No MD5 -- will never happen", e);
return "NO MD5";
}
}
public static byte[] toRawBytes(final ByteBuffer buf) {
final int mark = buf.position();
final byte[] bytes = new byte[buf.remaining()];
buf.get(bytes);
buf.position(mark);
return bytes;
}
}
|
package org.yakindu.sct.model.sexec.interpreter.test;
import static junit.framework.Assert.assertEquals;
import org.eclipse.xtext.junit4.InjectWith;
import org.eclipse.xtext.junit4.XtextRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.yakindu.sct.model.sexec.interpreter.stext.StextStatementInterpreter;
import org.yakindu.sct.model.sgraph.Scope;
import org.yakindu.sct.model.sgraph.Statement;
import org.yakindu.sct.model.stext.stext.Expression;
import org.yakindu.sct.model.stext.test.util.AbstractSTextTest;
import org.yakindu.sct.model.stext.test.util.STextInjectorProvider;
import org.yakindu.sct.simulation.core.runtime.IExecutionContext;
import org.yakindu.sct.simulation.core.runtime.impl.ExecutionContextImpl;
import org.yakindu.sct.simulation.core.runtime.impl.ExecutionEvent;
import org.yakindu.sct.simulation.core.runtime.impl.ExecutionVariable;
import com.google.inject.Inject;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
@RunWith(XtextRunner.class)
@InjectWith(STextInjectorProvider.class)
public class STextInterpreterTest extends AbstractSTextTest {
@Inject
private ExecutionContextImpl context;
@Inject
private StextStatementInterpreter interpreter;
@Test
public void testIntVariableAssignment() {
executeWithDefaultScope("myInt = 42");
assertEquals(42, getIntValue());
}
@Test
public void testHexVariableAssignment() {
executeWithDefaultScope("myInt = 0xFF");
assertEquals(0xFF, getIntValue());
}
@Test
public void testBoolTrueVariableAssignment() {
executeWithDefaultScope("myBool = true");
assertEquals(true, getBoolValue());
}
@Test
public void testBoolFalseVariableAssignment() {
executeWithDefaultScope("myBool = false");
assertEquals(false, getContext().getVariable("myBool").getValue());
}
@Test
public void testFloatVariableAssignment() {
executeWithDefaultScope("myReal = 42.0");
assertEquals(42.0f, getContext().getVariable("myReal").getValue());
}
@Test
public void testStringVariableAssignment() {
executeWithDefaultScope("myString = 'fortytwo'");
assertEquals("fortytwo", getStringValue());
}
@Test
public void testConditionalTrue() {
executeWithDefaultScope("myInt = true ? 42 : 1");
assertEquals(42, getIntValue());
}
@Test
public void testConditionalFalse() {
executeWithDefaultScope("myInt = false ? 42 : 1");
assertEquals(1, getIntValue());
}
@Test
public void testNestedExpression() {
executeWithDefaultScope("myInt = (1 + 1) * 2");
assertEquals(4, getIntValue());
}
@Test
public void testBooleanOr() {
executeWithDefaultScope("myBool = true || false");
assertEquals(true, getBoolValue());
}
@Test
public void testBooleanAnd() {
executeWithDefaultScope("myBool = true && false");
assertEquals(false, getContext().getVariable("myBool").getValue());
}
@Test
public void testBitwiseXor() {
executeWithDefaultScope("myInt = 0xF0F0 ^ 0xFF00");
assertEquals(0x0FF0, getContext().getVariable("myInt").getValue());
}
@Test
public void testBitwiseOr() {
executeWithDefaultScope("myInt = 0xF0F0 | 0xFFFF");
assertEquals(0xFFFF, getContext().getVariable("myInt").getValue());
}
@Test
public void testBitwiseAnd() {
executeWithDefaultScope("myInt = 0xF0F0 & 0xFFFF");
assertEquals(0x0F0F0, getContext().getVariable("myInt").getValue());
}
@Test
public void testBoolEqual() {
executeWithDefaultScope("myBool = false == false");
assertEquals(true, getBoolValue());
}
@Test
public void testIntEqual() {
executeWithDefaultScope("myBool = 1 == 1");
assertEquals(true, getBoolValue());
}
@Test
public void testFloatEqual() {
executeWithDefaultScope("myBool = 1.0f == 1.0f");
assertEquals(true, getBoolValue());
}
@Test
public void testStringEqual() {
executeWithDefaultScope("myBool = 'string' == 'string'");
assertEquals(true, getBoolValue());
}
@Test
public void testBoolNotEqual() {
executeWithDefaultScope("myBool = true != false");
assertEquals(true, getBoolValue());
}
@Test
public void testIntNotEqual() {
executeWithDefaultScope("myBool = 1 != 2");
assertEquals(true, getBoolValue());
}
@Test
public void testFloatNotEqual() {
executeWithDefaultScope("myBool = 1.0f != 2.0f");
assertEquals(true, getBoolValue());
}
@Test
public void testStringNotEqual() {
executeWithDefaultScope("myBool = 'string' != 'string2'");
assertEquals(true, getBoolValue());
}
@Test
public void testIntGreaterEqual() {
executeWithDefaultScope("myBool = 2 >= 1");
assertEquals(true, getBoolValue());
}
@Test
public void testFloatGreaterEqual() {
executeWithDefaultScope("myBool = 2.0f >= 2.0f");
assertEquals(true, getBoolValue());
}
@Test
public void testIntSmallerEqual() {
executeWithDefaultScope("myBool = 1 <= 2");
assertEquals(true, getBoolValue());
}
@Test
public void testFloatSmallerEqual() {
executeWithDefaultScope("myBool = 2.0f <= 2.0f");
assertEquals(true, getBoolValue());
}
@Test
public void testIntGreater() {
executeWithDefaultScope("myBool = 2 > 1");
assertEquals(true, getBoolValue());
}
@Test
public void testFloatGreater() {
executeWithDefaultScope("myBool = 2.1f > 2.0f");
assertEquals(true, getBoolValue());
}
@Test
public void testIntSmaller() {
executeWithDefaultScope("myBool = 1 < 2");
assertEquals(true, getBoolValue());
}
@Test
public void testFloatSmaller() {
executeWithDefaultScope("myBool = 2.0f < 2.1f");
assertEquals(true, getBoolValue());
}
@Test
public void testIntPositive() {
executeWithDefaultScope("myInt = + 1");
assertEquals(1, getIntValue());
executeWithDefaultScope("myInt = +2");
assertEquals(2, getIntValue());
}
@Test
public void testFloatPositive() {
executeWithDefaultScope("myReal = +1.0");
assertEquals(1.0f, getFloatValue());
}
@Test
public void testIntNegative() {
executeWithDefaultScope("myInt = - 1");
assertEquals(-1, getIntValue());
executeWithDefaultScope("myInt = -2");
assertEquals(-2, getIntValue());
}
// @Test
// public void testIntNegativeVar() {
// RTVariable a = new RTVariable("a");
// scope.addVariable(a);
// scope.setVariableValue(a, 42);
// executeWithDefaultScope("a = -a;");
// stmt.execute(scope);
// assertEquals(-42, scope.getValue("a"));
@Test
public void testFloatNegative() {
executeWithDefaultScope("myReal = -1.0f");
assertEquals(-1.0f, getFloatValue());
}
@Test
public void testIntPlus() {
executeWithDefaultScope("myInt = 42 + 1");
assertEquals(43, getIntValue());
}
@Test
public void testFloatPlus() {
executeWithDefaultScope("myReal = 42.0 + 1.0");
assertEquals(43.0f, getFloatValue());
}
@Test
public void testIntMinus() {
executeWithDefaultScope("myInt = 42 - 1");
assertEquals(41, getIntValue());
}
@Test
public void testFloatMinus() {
executeWithDefaultScope("myReal = 42.0f - 1.0f");
assertEquals(41.0f, getFloatValue());
}
@Test
public void testIntMultiply() {
executeWithDefaultScope("myInt = 42 * 2");
assertEquals(84, getIntValue());
}
@Test
public void testFloatMultiply() {
executeWithDefaultScope("myReal = 42.0f * 2.0f");
assertEquals(84.0f, getFloatValue());
}
@Test
public void testIntDivide() {
executeWithDefaultScope("myInt = 42 / 2");
assertEquals(21, getIntValue());
}
@Test
public void testFloatDivide() {
executeWithDefaultScope("myReal = 42.0f / 2.0f");
assertEquals(21.0f, getFloatValue());
}
@Test
public void testIntModulo() {
executeWithDefaultScope("myInt = 42 % 2");
assertEquals(0, getIntValue());
}
@Test
public void testFloatModulo() {
executeWithDefaultScope("myReal = 42.0f % 2.0f");
assertEquals(0.0f, getFloatValue());
}
@Test
public void testIntLeft() {
executeWithDefaultScope("myInt = 42 << 2");
assertEquals(168, getIntValue());
}
// @Test
// public void testFloatLeft() {
// try {
// executeWithDefaultScope("a = 42.0f << 2.0f;");
// scope.addVariable(new RTVariable("a"));
// stmt.execute(scope);
// assertEquals(168, scope.getValue("a"));
// fail("EvaluationException expected");
// } catch (EvaluationException e) {
@Test
public void testIntRight() {
executeWithDefaultScope("myInt = 42 >> 2");
assertEquals(10, getIntValue());
}
// @Test
// public void testFloatRight() {
// try {
// executeWithDefaultScope("a = 42.0f >> 2.0f;");
// scope.addVariable(new RTVariable("a"));
// stmt.execute(scope);
// assertEquals(168, scope.getValue("a"));
// fail("EvaluationException expected");
// } catch (EvaluationException e) {
@Test
public void testIntAnd() {
executeWithDefaultScope("myInt= 9 & 12");
assertEquals(8, getIntValue());
}
// @Test
// public void testFloatAnd() {
// try {
// executeWithDefaultScope("a= 9.0f & 12.0f;");
// scope.addVariable(new RTVariable("a"));
// stmt.execute(scope);
// assertEquals(8.0f, scope.getValue("a"));
// fail("EvaluationException expected");
// } catch (EvaluationException e) {
@Test
public void testIntXor() {
executeWithDefaultScope("myInt= 9 ^ 12");
assertEquals(5, getIntValue());
}
// @Test
// public void testFloatXor() {
// try {
// executeWithDefaultScope("a= 9.0f ^ 12.0f;");
// scope.addVariable(new RTVariable("a"));
// stmt.execute(scope);
// assertEquals(5.0f, scope.getValue("a"));
// fail("EvaluationException expected");
// } catch (EvaluationException e) {
@Test
public void testIntOr() {
executeWithDefaultScope("myInt= 9 | 12");
assertEquals(13, getIntValue());
}
// @Test
// public void testFloatOr() {
// try {
// executeWithDefaultScope("a= 9.0f | 12.0f;");
// scope.addVariable(new RTVariable("a"));
// stmt.execute(scope);
// assertEquals(13.0f, scope.getValue("a"));
// fail("EvaluationException expected");
// } catch (EvaluationException e) {
@Test
public void testIntBitComplement() {
executeWithDefaultScope("myInt= ~9");
assertEquals(-10, getIntValue());
}
// @Test
// public void testFloatBitComplement() {
// try {
// executeWithDefaultScope("a= ~9.0f;");
// scope.addVariable(new RTVariable("a"));
// stmt.execute(scope);
// assertEquals(-10.0f, scope.getValue("a"));
// fail("EvaluationException expected");
// } catch (EvaluationException e) {
@Test
public void testNot() {
executeWithDefaultScope("myBool = ! true");
assertEquals(false, getBoolValue());
}
@Test
public void testPrirority() {
executeWithDefaultScope("myInt = 1 + 2 * 3");
assertEquals(7, getIntValue());
}
@Test
public void testNested() {
executeWithDefaultScope("myInt = (1 + 2) * 3");
assertEquals(9, getIntValue());
}
@Test
public void testIntPlusAssign() {
executeWithDefaultScope("myInt=42");
executeWithDefaultScope("myInt+=42");
assertEquals(84, getIntValue());
}
@Test
public void testFloatPlusAssign() {
executeWithDefaultScope("myReal = 42.0");
System.out.println(getFloatValue());
executeWithDefaultScope("myReal+=42.0");
assertEquals(84.0f, getFloatValue());
}
@Test
public void testIntMinusAssign() {
executeWithDefaultScope("myInt=42");
executeWithDefaultScope("myInt-=10");
assertEquals(32, getIntValue());
}
@Test
public void testFloatMinusAssign() {
executeWithDefaultScope("myReal=42.0f");
executeWithDefaultScope("myReal-=10.0");
assertEquals(32.0f, getFloatValue());
}
@Test
public void testIntMultAssign() {
executeWithDefaultScope("myInt=42");
executeWithDefaultScope("myInt*=1");
assertEquals(42, getIntValue());
}
@Test
public void testFloatMultAssign() {
executeWithDefaultScope("myReal=42.0f");
executeWithDefaultScope("myReal*=1.0");
assertEquals(42.0f, getFloatValue());
}
@Test
public void testIntDivAssign() {
executeWithDefaultScope("myInt=42");
executeWithDefaultScope("myInt/=1");
assertEquals(42, getIntValue());
}
@Test
public void testFloatDivAssign() {
executeWithDefaultScope("myReal=42.0f");
executeWithDefaultScope("myReal/=1.0f");
assertEquals(42.0f, getFloatValue());
}
@Test
public void testIntModAssign() {
executeWithDefaultScope("myInt=42");
executeWithDefaultScope("myInt%=1");
assertEquals(0, getIntValue());
}
@Test
public void testFloatModAssign() {
executeWithDefaultScope("myReal=42.0f");
executeWithDefaultScope("myReal%=1.0f");
assertEquals(0.0f, getFloatValue());
}
@Test
public void testIntLeftAssign() {
executeWithDefaultScope("myInt=42");
executeWithDefaultScope("myInt<<=1");
assertEquals(84, getIntValue());
}
// @Test
// public void testFloatLeftAssign() {
// try {
// executeWithDefaultScope("a=42.0f; a<<=1.0f;");
// scope.addVariable(new RTVariable("a"));
// stmt.execute(scope);
// assertEquals(168, scope.getValue("a"));
// fail("EvaluationException expected");
// } catch (EvaluationException e) {
// @Test
// public void testIntRightAssign() {
// executeWithDefaultScope("a=42; a>>=1;");
// assertEquals(21, scope.getValue("a"));
// @Test
// public void testFloatRightAssign() {
// try {
// executeWithDefaultScope("a=42.0f; a>>=1.0f;");
// scope.addVariable(new RTVariable("a"));
// stmt.execute(scope);
// assertEquals(168, scope.getValue("a"));
// fail("EvaluationException expected");
// } catch (EvaluationException e) {
// @Test
// public void testIntAndAssign() {
// executeWithDefaultScope("a=9; a&=12;");
// assertEquals(8, scope.getValue("a"));
// @Test
// public void testFloatAndAssign() {
// try {
// executeWithDefaultScope("a=42.0f; a&=1.0f;");
// scope.addVariable(new RTVariable("a"));
// stmt.execute(scope);
// assertEquals(168, scope.getValue("a"));
// fail("EvaluationException expected");
// } catch (EvaluationException e) {
// @Test
// public void testIntXorAssign() {
// executeWithDefaultScope("a=9; a^=12;");
// assertEquals(5, scope.getValue("a"));
// @Test
// public void testFloatXorAssign() {
// try {
// executeWithDefaultScope("a=42.0f; a^=1.0f;");
// scope.addVariable(new RTVariable("a"));
// stmt.execute(scope);
// assertEquals(168, scope.getValue("a"));
// fail("EvaluationException expected");
// } catch (EvaluationException e) {
// @Test
// public void testIntOrAssign() {
// executeWithDefaultScope("a=9; a|=12;");
// assertEquals(13, scope.getValue("a"));
// @Test
// public void testFloatOrAssign() {
// try {
// executeWithDefaultScope("a=42.0; a|=1.0;");
// scope.addVariable(new RTVariable("a"));
// stmt.execute(scope);
// assertEquals(168, scope.getValue("a"));
// fail("EvaluationException expected");
// } catch (EvaluationException e) {
@Test
public void testPlainTrue() {
assertEquals(true, executeExpression("", "true"));
}
@Test
public void testPlainFalse() {
assertEquals(false, executeExpression("", "false"));
}
// Convenience...
@Before
public void setup() {
initContext();
}
private void initContext() {
// "event abc operation foo() var myInt : integer var MyBool : boolean
// var myReal : real
ExecutionVariable myInt = new ExecutionVariable("myInt", Integer.class,
0);
context.declareVariable(myInt);
ExecutionVariable myBool = new ExecutionVariable("myBool",
Boolean.class, false);
context.declareVariable(myBool);
ExecutionVariable myReal = new ExecutionVariable("myReal", Float.class,
0.0f);
context.declareVariable(myReal);
ExecutionVariable myString = new ExecutionVariable("myString",
String.class, "");
context.declareVariable(myString);
ExecutionEvent event = new ExecutionEvent("abc", Integer.class);
context.declareEvent(event);
}
protected Object getBoolValue() {
return context.getVariable("myBool").getValue();
}
protected Object getIntValue() {
return context.getVariable("myInt").getValue();
}
protected Object getFloatValue() {
return context.getVariable("myReal").getValue();
}
protected Object getStringValue() {
return context.getVariable("myString").getValue();
}
protected Object executeWithDefaultScope(String expression) {
Scope defaultScope = internalScope();
Expression statement = (Expression) parseExpression(expression,
defaultScope, Expression.class.getSimpleName());
return interpreter.evaluateStatement(statement, context);
}
protected Object execute(String scope, String expression) {
Scope defaultScope = createInternalScope(scope);
Expression statement = (Expression) parseExpression(expression,
defaultScope, Expression.class.getSimpleName());
return interpreter.evaluateStatement(statement, context);
}
protected Object executeExpression(String scope, String expression) {
Scope defaultScope = createInternalScope(scope);
Statement statement = (Statement) parseExpression(expression,
defaultScope, Expression.class.getSimpleName());
return interpreter.evaluateStatement(statement, context);
}
public IExecutionContext getContext() {
return context;
}
@After
public void tearDown() {
context = null;
}
protected static final class TestExecutionContext extends
ExecutionContextImpl {
public String lastProcedureId;
@Override
public void call(String procedureId) {
super.call(procedureId);
lastProcedureId = procedureId;
}
}
}
|
package com.example.viewpager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.TextView;
import android.widget.Toast;
public class MessageActivity extends Fragment {
TextView tv_message;
//view
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.activity_message, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
initView();
}
private void initView() {
// TODO Auto-generated method stub
tv_message=(TextView) getView().findViewById(R.id.message_tv_message);
tv_message.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "message", Toast.LENGTH_SHORT).show();
}
});
}
}
|
package app.abhijit.iter;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import app.abhijit.iter.data.Cache;
import app.abhijit.iter.models.Student;
import app.abhijit.iter.models.Subject;
public class AttendanceActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private Context mContext;
private SharedPreferences mSharedPreferences;
private Cache mCache;
private Student mNewStudent;
private Student mOldStudent;
private boolean mPrefExtendedStats;
private int mPrefMinimumAttendance;
private ArrayList<SubjectView> mSubjectViews;
private SubjectAdapter mSubjectAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
mContext = this;
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
mCache = new Cache(mContext);
try {
mNewStudent = new Gson().fromJson(getIntent().getStringExtra("student"), Student.class);
} catch (Exception ignored) { }
mOldStudent = mCache.getStudent(mSharedPreferences.getString("pref_student", null));
if (mNewStudent == null && mOldStudent == null) {
startActivity(new Intent(AttendanceActivity.this, LoginActivity.class));
finish();
}
if (mNewStudent == null) mNewStudent = mOldStudent;
if (mOldStudent == null) mOldStudent = mNewStudent;
mPrefExtendedStats = mSharedPreferences.getBoolean("pref_extended_stats", true);
mPrefMinimumAttendance = Integer.parseInt(mSharedPreferences.getString("pref_minimum_attendance", "75"));
setupToolbar();
setupDrawer();
setupFab();
setupListView();
processAndDisplayAttendance();
}
@Override
public void onResume() {
super.onResume();
boolean prefExtendedStats = mSharedPreferences.getBoolean("pref_extended_stats", true);
int prefMinimumAttendance = Integer.parseInt(mSharedPreferences.getString("pref_minimum_attendance", "75"));
if (mPrefExtendedStats != prefExtendedStats
|| mPrefMinimumAttendance != prefMinimumAttendance) {
mPrefExtendedStats = prefExtendedStats;
mPrefMinimumAttendance = prefMinimumAttendance;
processAndDisplayAttendance();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.three_dots, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView imageView = (ImageView) inflater.inflate(R.layout.action_refresh, null);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.rotate);
animation.setRepeatCount(1);
imageView.startAnimation(animation);
item.setActionView(imageView);
animation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation) {
item.getActionView().clearAnimation();
item.setActionView(null);
}
@Override
public void onAnimationRepeat(Animation animation) { }
});
} else if (id == R.id.action_logout) {
mCache.setStudent(mSharedPreferences.getString("pref_student", null), null);
Toast.makeText(mContext, "Logged out", Toast.LENGTH_SHORT).show();
startActivity(new Intent(AttendanceActivity.this, LoginActivity.class));
finish();
}
return true;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_about) {
startActivity(new Intent(AttendanceActivity.this, AboutActivity.class));
} else if (id == R.id.nav_settings) {
startActivity(new Intent(AttendanceActivity.this, SettingsActivity.class));
}
return true;
}
@Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
private void setupDrawer() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View navigationViewHeader = navigationView.getHeaderView(0);
((TextView) navigationViewHeader.findViewById(R.id.name)).setText(mNewStudent.name);
((TextView) navigationViewHeader.findViewById(R.id.username)).setText(mNewStudent.username);
String prompts[] = {"open source?", "coding?", "programming?", "code+coffee?"};
TextView opensource = drawer.findViewById(R.id.opensource);
opensource.setText(prompts[new Random().nextInt(prompts.length)]);
TextView github = drawer.findViewById(R.id.github);
github.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
github.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.github_url))));
}
});
}
private void setupFab() {
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mSharedPreferences.edit().putString("pref_student", null).apply();
startActivity(new Intent(AttendanceActivity.this, LoginActivity.class));
finish();
}
});
}
private void setupListView() {
ListView subjectsList = findViewById(R.id.subjects);
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
subjectsList.addFooterView(layoutInflater.inflate(R.layout.listview_footer, null, false));
mSubjectViews = new ArrayList<>();
mSubjectAdapter = new SubjectAdapter(mSubjectViews);
subjectsList.setAdapter(mSubjectAdapter);
}
private void processAndDisplayAttendance() {
ArrayList<SubjectView> subjectViews = new ArrayList<>();
Boolean updated = false;
for (Subject subject : mNewStudent.subjects.values()) {
SubjectView subjectView = new SubjectView();
subjectView.avatar = subjectAvatar(subject.code);
subjectView.name = subject.name;
subjectView.attendance = String.format(Locale.US, "%.2f%%", subject.attendance());
subjectView.theory = String.format(Locale.US, "%d/%d classes", subject.theoryPresent, subject.theoryTotal);
subjectView.lab = String.format(Locale.US, "%d/%d classes", subject.labPresent, subject.labTotal);
subjectView.absent = String.format(Locale.US, "%d classes", subject.absent());
if (mOldStudent.subjects.containsKey(subject.code)) {
Subject oldSubject = mOldStudent.subjects.get(subject.code);
if (subject.theoryPresent != oldSubject.theoryPresent
|| subject.theoryTotal != oldSubject.theoryTotal
|| subject.labPresent != oldSubject.labPresent
|| subject.labTotal != oldSubject.labTotal) {
updated = true;
subjectView.oldTheory = String.format(Locale.US, "%d/%d classes", oldSubject.theoryPresent, oldSubject.theoryTotal);
subjectView.oldLab = String.format(Locale.US, "%d/%d classes", oldSubject.labPresent, oldSubject.labTotal);
subjectView.oldAbsent = String.format(Locale.US, "%d classes", oldSubject.absent());
subjectView.lastUpdatedBadge = R.drawable.bg_badge_blue;
subjectView.updated = true;
if (subject.attendance() >= oldSubject.attendance()) {
subjectView.status = R.drawable.ic_status_up;
} else {
subjectView.status = R.drawable.ic_status_down;
}
} else {
subject.lastUpdated = oldSubject.lastUpdated;
}
}
if (subject.attendance() > mPrefMinimumAttendance + 10.0) {
subjectView.attendanceBadge = R.drawable.bg_badge_green;
} else if (subject.attendance() > mPrefMinimumAttendance) {
subjectView.attendanceBadge = R.drawable.bg_badge_yellow;
} else {
subjectView.attendanceBadge = R.drawable.bg_badge_red;
}
subjectView.bunkStats = subject.bunkStats(mPrefMinimumAttendance, mPrefExtendedStats);
if (subjectView.updated) {
subjectView.lastUpdated = "just now";
} else {
subjectView.lastUpdated = DateUtils.getRelativeTimeSpanString(subject.lastUpdated, new Date().getTime(), 0).toString();
}
subjectViews.add(subjectView);
}
mCache.setStudent(mNewStudent.username, mNewStudent);
if (updated) {
Toast.makeText(mContext, "Attendance updated", Toast.LENGTH_SHORT).show();
Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
}
findViewById(R.id.no_attendance).setVisibility(subjectViews.isEmpty() ? View.VISIBLE : View.GONE);
findViewById(R.id.subjects).setVisibility(subjectViews.isEmpty() ? View.GONE : View.VISIBLE);
mSubjectViews.clear();
mSubjectViews.addAll(subjectViews);
mSubjectAdapter.notifyDataSetChanged();
}
private int subjectAvatar(String subjectCode) {
switch (subjectCode) {
case "CHM1002": return R.drawable.ic_subject_environmental_studies;
case "CSE1002": return R.drawable.ic_subject_maths;
case "CSE1011": return R.drawable.ic_subject_electrical;
case "CSE2031": return R.drawable.ic_subject_maths;
case "CSE3151": return R.drawable.ic_subject_database;
case "CSE4042": return R.drawable.ic_subject_network;
case "CSE4043": return R.drawable.ic_subject_security;
case "CSE4044": return R.drawable.ic_subject_security;
case "CSE4051": return R.drawable.ic_subject_database;
case "CSE4052": return R.drawable.ic_subject_database;
case "CSE4053": return R.drawable.ic_subject_database;
case "CSE4054": return R.drawable.ic_subject_database;
case "CSE4102": return R.drawable.ic_subject_html;
case "CSE4141": return R.drawable.ic_subject_android;
case "CSE4151": return R.drawable.ic_subject_server;
case "CVL3071": return R.drawable.ic_subject_traffic;
case "CVL3241": return R.drawable.ic_subject_water;
case "CVL4031": return R.drawable.ic_subject_earth;
case "CVL4032": return R.drawable.ic_subject_soil;
case "CVL4041": return R.drawable.ic_subject_water;
case "CVL4042": return R.drawable.ic_subject_water;
case "EET1001": return R.drawable.ic_subject_matlab;
case "EET3041": return R.drawable.ic_subject_electromagnetic_waves;
case "EET3061": return R.drawable.ic_subject_communication;
case "EET3062": return R.drawable.ic_subject_communication;
case "EET4014": return R.drawable.ic_subject_renewable_energy;
case "EET4041": return R.drawable.ic_subject_electromagnetic_waves;
case "EET4061": return R.drawable.ic_subject_wifi;
case "EET4063": return R.drawable.ic_subject_communication;
case "EET4161": return R.drawable.ic_subject_communication;
case "HSS1001": return R.drawable.ic_subject_effective_speech;
case "HSS1021": return R.drawable.ic_subject_economics;
case "HSS2021": return R.drawable.ic_subject_economics;
case "MEL3211": return R.drawable.ic_subject_water;
case "MTH2002": return R.drawable.ic_subject_probability_statistics;
case "MTH4002": return R.drawable.ic_subject_matlab;
}
switch (subjectCode.substring(0, Math.min(subjectCode.length(), 3))) {
case "CHM": return R.drawable.ic_subject_chemistry;
case "CSE": return R.drawable.ic_subject_computer;
case "CVL": return R.drawable.ic_subject_civil;
case "EET": return R.drawable.ic_subject_electrical;
case "HSS": return R.drawable.ic_subject_humanities;
case "MEL": return R.drawable.ic_subject_mechanical;
case "MTH": return R.drawable.ic_subject_maths;
case "PHY": return R.drawable.ic_subject_physics;
}
return R.drawable.ic_subject_generic;
}
private class SubjectView {
private boolean updated;
private int avatar;
private String attendance;
private int attendanceBadge;
private String name;
private String lastUpdated;
private int lastUpdatedBadge;
private int status;
private String oldLab;
private String lab;
private String oldTheory;
private String theory;
private String oldAbsent;
private String absent;
private String bunkStats;
}
private class SubjectAdapter extends ArrayAdapter<SubjectView> {
private final LayoutInflater mLayoutInflater;
SubjectAdapter(ArrayList<SubjectView> subjectViews) {
super(mContext, R.layout.item_subject, subjectViews);
mLayoutInflater = LayoutInflater.from(mContext);
}
private class ViewHolder {
private ImageView avatar;
private TextView attendance;
private TextView name;
private TextView lastUpdated;
private ImageView status;
private TextView oldLab;
private TextView lab;
private TextView oldTheory;
private TextView theory;
private TextView oldAbsent;
private TextView absent;
private TextView bunkStats;
}
@Override
public @NonNull View getView(int position, View convertView, @NonNull ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.item_subject, parent, false);
viewHolder.avatar = convertView.findViewById(R.id.subject_avatar);
viewHolder.attendance = convertView.findViewById(R.id.subject_attendance);
viewHolder.name = convertView.findViewById(R.id.subject_name);
viewHolder.lastUpdated = convertView.findViewById(R.id.subject_last_updated);
viewHolder.status = convertView.findViewById(R.id.subject_status);
viewHolder.oldLab = convertView.findViewById(R.id.subject_old_lab);
viewHolder.lab = convertView.findViewById(R.id.subject_lab);
viewHolder.oldTheory = convertView.findViewById(R.id.subject_old_theory);
viewHolder.theory = convertView.findViewById(R.id.subject_theory);
viewHolder.oldAbsent = convertView.findViewById(R.id.subject_old_absent);
viewHolder.absent = convertView.findViewById(R.id.subject_absent);
viewHolder.bunkStats = convertView.findViewById(R.id.subject_bunk_stats);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final SubjectView subjectView = getItem(position);
viewHolder.avatar.setImageResource(subjectView.avatar);
viewHolder.attendance.setText(subjectView.attendance);
viewHolder.attendance.setBackgroundResource(subjectView.attendanceBadge);
viewHolder.name.setText(subjectView.name);
viewHolder.lastUpdated.setText(subjectView.lastUpdated);
viewHolder.lastUpdated.setBackgroundResource(subjectView.lastUpdatedBadge);
viewHolder.status.setImageResource(subjectView.status);
viewHolder.oldLab.setText(subjectView.oldLab);
viewHolder.lab.setText(subjectView.lab);
viewHolder.oldTheory.setText(subjectView.oldTheory);
viewHolder.theory.setText(subjectView.theory);
viewHolder.oldAbsent.setText(subjectView.oldAbsent);
viewHolder.absent.setText(subjectView.absent);
viewHolder.bunkStats.setText(subjectView.bunkStats);
viewHolder.oldLab.setVisibility(View.GONE);
viewHolder.oldTheory.setVisibility(View.GONE);
viewHolder.oldAbsent.setVisibility(View.GONE);
if (subjectView.updated) {
if (!StringUtils.equals(subjectView.lab, subjectView.oldLab)) {
viewHolder.oldLab.setVisibility(View.VISIBLE);
viewHolder.oldLab.setPaintFlags(viewHolder.oldLab.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
if (!StringUtils.equals(subjectView.theory, subjectView.oldTheory)) {
viewHolder.oldTheory.setVisibility(View.VISIBLE);
viewHolder.oldTheory.setPaintFlags(viewHolder.oldTheory.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
if (!StringUtils.equals(subjectView.absent, subjectView.oldAbsent)) {
viewHolder.oldAbsent.setVisibility(View.VISIBLE);
viewHolder.oldAbsent.setPaintFlags(viewHolder.oldAbsent.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
}
return convertView;
}
}
}
|
package org.splevo.jamopp.vpm.analyzer.clonedchange;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.common.util.EList;
import org.emftext.language.java.commons.Commentable;
import org.graphstream.graph.Node;
import org.splevo.jamopp.algorithm.clones.baxtor.CloneDetector;
import org.splevo.jamopp.vpm.software.JaMoPPSoftwareElement;
import org.splevo.vpm.analyzer.AbstractVPMAnalyzer;
import org.splevo.vpm.analyzer.VPMAnalyzerException;
import org.splevo.vpm.analyzer.VPMAnalyzerResult;
import org.splevo.vpm.analyzer.VPMEdgeDescriptor;
import org.splevo.vpm.analyzer.config.VPMAnalyzerConfigurationSet;
import org.splevo.vpm.analyzer.graph.VPMGraph;
import org.splevo.vpm.software.SoftwareElement;
import org.splevo.vpm.variability.Variant;
import org.splevo.vpm.variability.VariationPoint;
/**
* Variation Point Analyzer identifying variation points containing cloned changes.
*/
public class ClonedChangeAnalyzer extends AbstractVPMAnalyzer {
private static final String ANALYZER_NAME = "Cloned Change Analyzer";
private static final String RELATIONSHIP_LABEL = "ClonedChange";
/**
* Specifies how many software elements must be equal to consider two variation points to
* contain clones.
*/
private static final int THRESHOLD = 0;
/**
* Analyze variation point relationship based on cloned changes between them.
*
* {@inheritDoc}
*
* @see org.splevo.vpm.analyzer.VPMAnalyzer#analyze(org.splevo.vpm.analyzer.graph.VPMGraph)
*/
@Override
public VPMAnalyzerResult analyze(VPMGraph vpmGraph) throws VPMAnalyzerException {
VPMAnalyzerResult result = new VPMAnalyzerResult(this);
List<VPMEdgeDescriptor> edges = findEdgesBetweenClonedChanges(vpmGraph);
result.getEdgeDescriptors().addAll(edges);
return result;
}
private List<VPMEdgeDescriptor> findEdgesBetweenClonedChanges(VPMGraph vpmGraph) {
VPMEdgeDescriptor edge;
CloneDetector cloneDetector = new CloneDetector();
List<VPMEdgeDescriptor> descriptors = new ArrayList<VPMEdgeDescriptor>();
List<String> edgeRegistry = new ArrayList<String>();
int numNodes = vpmGraph.getNodeCount();
for (int i = 0; i < numNodes; i++) {
for (int j = i + 1; j < numNodes; j++) {
Node node1 = vpmGraph.getNode(i);
Node node2 = vpmGraph.getNode(j);
VariationPoint vp1 = node1.getAttribute(VPMGraph.VARIATIONPOINT, VariationPoint.class);
VariationPoint vp2 = node2.getAttribute(VPMGraph.VARIATIONPOINT, VariationPoint.class);
edge = null;
int numClones = countClonesInVariationPoints(vp1, vp2, cloneDetector);
String subLabel = String.valueOf(numClones);
if (numClones > THRESHOLD) {
edge = buildEdgeDescriptor(node1, node2, subLabel, edgeRegistry);
}
if (edge != null) {
descriptors.add(edge);
}
}
}
return descriptors;
}
private int countClonesInVariationPoints(VariationPoint vp1, VariationPoint vp2, CloneDetector cloneDetector) {
int numClones = 0;
EList<Variant> vp1Variants = vp1.getVariants();
EList<Variant> vp2Variants = vp2.getVariants();
for (Variant vp1Variant : vp1Variants) {
for (Variant vp2Variant : vp2Variants) {
numClones += countClonesInVariants(vp1Variant, vp2Variant, cloneDetector);
}
}
return numClones;
}
private int countClonesInVariants(Variant vp1Variant, Variant vp2Variant, CloneDetector cloneDetector) {
int numClones = 0;
EList<SoftwareElement> vp1VariantElements = vp1Variant.getImplementingElements();
EList<SoftwareElement> vp2VariantElements = vp2Variant.getImplementingElements();
for (SoftwareElement vp1VariantElement : vp1VariantElements) {
for (SoftwareElement vp2VariantElement : vp2VariantElements) {
if (vp1VariantElement instanceof JaMoPPSoftwareElement
&& vp2VariantElement instanceof JaMoPPSoftwareElement) {
Commentable commentable1 = ((JaMoPPSoftwareElement) vp1VariantElement).getJamoppElement();
Commentable commentable2 = ((JaMoPPSoftwareElement) vp2VariantElement).getJamoppElement();
if (cloneDetector.isClone(commentable1, commentable2)) {
numClones++;
}
}
}
}
return numClones;
}
@Override
public String getName() {
return ANALYZER_NAME;
}
@Override
public String getRelationshipLabel() {
return RELATIONSHIP_LABEL;
}
@Override
public VPMAnalyzerConfigurationSet getConfigurations() {
return new VPMAnalyzerConfigurationSet();
}
}
|
package org.zkoss.ganttz;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.LocalDate;
import org.zkoss.ganttz.adapters.IDisabilityConfiguration;
import org.zkoss.ganttz.data.GanttDate;
import org.zkoss.ganttz.data.ITaskFundamentalProperties.IModifications;
import org.zkoss.ganttz.data.ITaskFundamentalProperties.IUpdatablePosition;
import org.zkoss.ganttz.data.Task;
import org.zkoss.ganttz.util.ComponentsFinder;
import org.zkoss.util.Locales;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.KeyEvent;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Treecell;
import org.zkoss.zul.api.Div;
import org.zkoss.zul.api.Hlayout;
import org.zkoss.zul.api.Label;
import org.zkoss.zul.api.Treerow;
public class LeftTasksTreeRow extends GenericForwardComposer {
public interface ILeftTasksTreeNavigator {
LeftTasksTreeRow getBelowRow();
LeftTasksTreeRow getAboveRow();
}
private static final Log LOG = LogFactory.getLog(LeftTasksTreeRow.class);
private final Task task;
private Label nameLabel;
private Textbox nameBox;
private Label startDateLabel;
private Textbox startDateTextBox;
private Label endDateLabel;
private Textbox endDateTextBox;
private Datebox openedDateBox = null;
private DateFormat dateFormat;
private Planner planner;
private Div hoursStatusDiv;
private Div budgetStatusDiv;
private final ILeftTasksTreeNavigator leftTasksTreeNavigator;
private final IDisabilityConfiguration disabilityConfiguration;
public static LeftTasksTreeRow create(
IDisabilityConfiguration disabilityConfiguration, Task bean,
ILeftTasksTreeNavigator taskDetailnavigator, Planner planner) {
return new LeftTasksTreeRow(disabilityConfiguration, bean,
taskDetailnavigator, planner);
}
private LeftTasksTreeRow(IDisabilityConfiguration disabilityConfiguration,
Task task, ILeftTasksTreeNavigator leftTasksTreeNavigator,
Planner planner) {
this.disabilityConfiguration = disabilityConfiguration;
this.task = task;
this.dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locales
.getCurrent());
this.leftTasksTreeNavigator = leftTasksTreeNavigator;
this.planner = planner;
}
public Task getTask() {
return task;
}
public Textbox getNameBox() {
return nameBox;
}
public void setNameBox(Textbox nameBox) {
this.nameBox = nameBox;
}
public Task getData() {
return task;
}
/**
* When a text box associated to a datebox is requested to show the datebox,
* the corresponding datebox is shown
* @param component
* the component that has received focus
*/
public void userWantsDateBox(Component component) {
if (component == startDateTextBox) {
if (canChangeStartDate()) {
createDateBox(startDateTextBox);
}
}
if (component == endDateTextBox) {
if (canChangeEndDate()) {
createDateBox(endDateTextBox);
}
}
}
public void createDateBox(Textbox textbox) {
openedDateBox = new Datebox();
openedDateBox.setFormat("short");
openedDateBox.setButtonVisible(false);
try {
openedDateBox.setValue(dateFormat.parse(textbox.getValue()));
} catch (ParseException e) {
return;
}
registerOnEnterOpenDateBox(openedDateBox);
registerBlurListener(openedDateBox);
registerOnChangeDatebox(openedDateBox, textbox);
textbox.setVisible(false);
textbox.getParent().appendChild(openedDateBox);
openedDateBox.setFocus(true);
openedDateBox.setOpen(true);
}
private enum Navigation {
LEFT, UP, RIGHT, DOWN;
public static Navigation getIntentFrom(KeyEvent keyEvent) {
return values()[keyEvent.getKeyCode() - 37];
}
}
public void focusGoUp(int position) {
LeftTasksTreeRow aboveDetail = leftTasksTreeNavigator.getAboveRow();
if (aboveDetail != null) {
aboveDetail.receiveFocus(position);
}
}
public void receiveFocus() {
receiveFocus(0);
}
public void receiveFocus(int position) {
this.getTextBoxes().get(position).focus();
}
public void focusGoDown(int position) {
LeftTasksTreeRow belowDetail = leftTasksTreeNavigator.getBelowRow();
if (belowDetail != null) {
belowDetail.receiveFocus(position);
} else {
getListDetails().getGoingDownInLastArrowCommand().doAction();
}
}
private LeftTasksTree getListDetails() {
Component current = nameBox;
while (!(current instanceof LeftTasksTree)) {
current = current.getParent();
}
return (LeftTasksTree) current;
}
public void userWantsToMove(Textbox textbox, KeyEvent keyEvent) {
Navigation navigation = Navigation.getIntentFrom(keyEvent);
List<Textbox> textBoxes = getTextBoxes();
int position = textBoxes.indexOf(textbox);
switch (navigation) {
case UP:
focusGoUp(position);
break;
case DOWN:
focusGoDown(position);
break;
default:
throw new RuntimeException("case not covered: " + navigation);
}
}
private List<Textbox> getTextBoxes() {
return Arrays.asList(nameBox, startDateTextBox, endDateTextBox);
}
/**
* When the dateBox loses focus the corresponding textbox is shown instead.
* @param dateBox
* the component that has lost focus
*/
public void dateBoxHasLostFocus(Datebox dateBox) {
dateBox.getPreviousSibling().setVisible(true);
dateBox.setParent(null);
}
@Override
public void doAfterCompose(Component component) throws Exception {
super.doAfterCompose(component);
findComponents((Treerow) component);
registerTextboxesListeners();
updateComponents();
task
.addFundamentalPropertiesChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateComponents();
}
});
}
private void registerTextboxesListeners() {
if (disabilityConfiguration.isTreeEditable()) {
registerKeyboardListener(nameBox);
registerOnChange(nameBox);
registerKeyboardListener(startDateTextBox);
registerKeyboardListener(endDateTextBox);
registerOnEnterListener(startDateTextBox);
registerOnEnterListener(endDateTextBox);
registerOnChange(startDateTextBox);
registerOnChange(endDateTextBox);
}
}
public void registerDateboxListeners(Datebox datebox) {
}
private void findComponents(Treerow row) {
List<Object> rowChildren = row.getChildren();
List<Treecell> treeCells = ComponentsFinder.findComponentsOfType(Treecell.class,
rowChildren);
assert treeCells.size() == 4;
findComponentsForNameCell(treeCells.get(0));
findComponentsForStartDateCell(treeCells.get(1));
findComponentsForEndDateCell(treeCells.get(2));
findComponentsForStatusCell(treeCells.get(3));
}
private static Textbox findTextBoxOfCell(Treecell treecell) {
List<Object> children = treecell.getChildren();
return ComponentsFinder.findComponentsOfType(Textbox.class, children)
.get(0);
}
private void findComponentsForNameCell(Treecell treecell) {
if (disabilityConfiguration.isTreeEditable()) {
nameBox = (Textbox) treecell.getChildren().get(0);
} else {
nameLabel = (Label) treecell.getChildren().get(0);
}
}
private void registerKeyboardListener(final Textbox textBox) {
textBox.addEventListener("onCtrlKey", new EventListener() {
@Override
public void onEvent(Event event) {
userWantsToMove(textBox, (KeyEvent) event);
}
});
}
private void registerOnChange(final Component component) {
component.addEventListener("onChange", new EventListener() {
@Override
public void onEvent(Event event) {
updateBean(component);
}
});
}
private void registerOnChangeDatebox(final Datebox datebox,
final Textbox textbox) {
datebox.addEventListener("onChange", new EventListener() {
@Override
public void onEvent(Event event) {
textbox.setValue(dateFormat.format(datebox.getValue()));
updateBean(textbox);
}
});
}
private void registerOnEnterListener(final Textbox textBox) {
textBox.addEventListener("onOK", new EventListener() {
@Override
public void onEvent(Event event) {
userWantsDateBox(textBox);
}
});
}
private void registerOnEnterOpenDateBox(final Datebox datebox) {
datebox.addEventListener("onOK", new EventListener() {
@Override
public void onEvent(Event event) {
datebox.setOpen(true);
}
});
}
private void findComponentsForStartDateCell(Treecell treecell) {
if (disabilityConfiguration.isTreeEditable()) {
startDateTextBox = findTextBoxOfCell(treecell);
} else {
startDateLabel = (Label) treecell.getChildren().get(0);
}
}
private void findComponentsForEndDateCell(Treecell treecell) {
if (disabilityConfiguration.isTreeEditable()) {
endDateTextBox = findTextBoxOfCell(treecell);
} else {
endDateLabel = (Label) treecell.getChildren().get(0);
}
}
private void findComponentsForStatusCell(Treecell treecell) {
List<Object> children = treecell.getChildren();
Hlayout hlayout = ComponentsFinder.findComponentsOfType(Hlayout.class,
children).get(0);
hoursStatusDiv = (Div) hlayout.getChildren().get(0);
budgetStatusDiv = (Div) hlayout.getChildren().get(1);
}
private void registerBlurListener(final Datebox datebox) {
datebox.addEventListener("onBlur", new EventListener() {
@Override
public void onEvent(Event event) {
dateBoxHasLostFocus(datebox);
}
});
}
public void updateBean(Component updatedComponent) {
if (updatedComponent == getNameBox()) {
task.setName(getNameBox().getValue());
if (StringUtils.isEmpty(getNameBox().getValue())) {
getNameBox().setValue(task.getName());
}
} else if (updatedComponent == getStartDateTextBox()) {
try {
final Date begin = dateFormat.parse(getStartDateTextBox()
.getValue());
task.doPositionModifications(new IModifications() {
@Override
public void doIt(IUpdatablePosition position) {
position.moveTo(GanttDate.createFrom(begin));
}
});
} catch (ParseException e) {
// Do nothing as textbox is rested in the next sentence
}
getStartDateTextBox().setValue(
dateFormat.format(task.getBeginDate().toDayRoundedDate()));
} else if (updatedComponent == getEndDateTextBox()) {
try {
Date newEnd = dateFormat.parse(getEndDateTextBox().getValue());
task.resizeTo(LocalDate.fromDateFields(newEnd));
} catch (ParseException e) {
// Do nothing as textbox is rested in the next sentence
}
getEndDateTextBox().setValue(
asString(task.getEndDate().toDayRoundedDate()));
}
planner.updateTooltips();
}
private void updateComponents() {
if (disabilityConfiguration.isTreeEditable()) {
getNameBox().setValue(task.getName());
getNameBox().setDisabled(!canRenameTask());
getNameBox().setTooltiptext(task.getName());
getStartDateTextBox().setDisabled(!canChangeStartDate());
getEndDateTextBox().setDisabled(!canChangeEndDate());
getStartDateTextBox().setValue(
asString(task.getBeginDate().toDayRoundedDate()));
getEndDateTextBox().setValue(
asString(task.getEndDate().toDayRoundedDate()));
} else {
nameLabel.setValue(task.getName());
nameLabel.setTooltiptext(task.getName());
nameLabel.setSclass("clickable-rows");
nameLabel.addEventListener(Events.ON_CLICK, new EventListener() {
@Override
public void onEvent(Event arg0) throws Exception {
Executions.getCurrent().sendRedirect(
"/planner/index.zul;order="
+ task.getProjectCode());
}
});
startDateLabel.setValue(asString(task.getBeginDate()
.toDayRoundedDate()));
endDateLabel.setValue(asString(task.getEndDate()
.toDayRoundedDate()));
}
setHoursStatus(task.getProjectHoursStatus(),
task.getTooltipTextForProjectHoursStatus());
setBudgetStatus(task.getProjectBudgetStatus(),
task.getTooltipTextForProjectBudgetStatus());
}
private boolean canChangeStartDate() {
return disabilityConfiguration.isMovingTasksEnabled()
&& task.canBeExplicitlyMoved();
}
private boolean canChangeEndDate() {
return disabilityConfiguration.isResizingTasksEnabled()
&& task.canBeExplicitlyResized();
}
private boolean canRenameTask() {
return disabilityConfiguration.isRenamingTasksEnabled();
}
private String asString(Date date) {
return dateFormat.format(date);
}
public Textbox getStartDateTextBox() {
return startDateTextBox;
}
public void setStartDateTextBox(Textbox startDateTextBox) {
this.startDateTextBox = startDateTextBox;
}
public Textbox getEndDateTextBox() {
return endDateTextBox;
}
public void setEndDateTextBox(Textbox endDateTextBox) {
this.endDateTextBox = endDateTextBox;
}
private void setHoursStatus(ProjectStatusEnum status, String tooltipText) {
hoursStatusDiv.setSclass(getProjectStatusSclass(status));
hoursStatusDiv.setTooltiptext(tooltipText);
onProjectStatusClick(hoursStatusDiv);
}
private void setBudgetStatus(ProjectStatusEnum status, String tooltipText) {
budgetStatusDiv.setSclass(getProjectStatusSclass(status));
budgetStatusDiv.setTooltiptext(tooltipText);
onProjectStatusClick(budgetStatusDiv);
}
private String getProjectStatusSclass(ProjectStatusEnum status) {
String cssClass;
switch (status) {
case MARGIN_EXCEEDED:
cssClass = "status-red";
break;
case WITHIN_MARGIN:
cssClass = "status-orange";
break;
case AS_PLANNED:
default:
cssClass = "status-green";
}
return cssClass;
}
private void onProjectStatusClick(Component statucComp) {
if (!disabilityConfiguration.isTreeEditable()) {
statucComp.addEventListener(Events.ON_CLICK, new EventListener() {
@Override
public void onEvent(Event arg0) throws Exception {
Executions.getCurrent()
.sendRedirect(
"/planner/index.zul;order="
+ task.getProjectCode());
}
});
}
}
}
|
package galileo.graph;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import galileo.dataset.feature.Feature;
/**
* Tracks a {@link galileo.query.Query} as it traverses through a graph
* hierarchy.
*
* @author malensek
*/
public class HierarchicalQueryTracker<T> {
public List<List<Path<Feature, T>>> results = new ArrayList<>();
private int farthestEvaluatedExpression = 0;
private int currentLevel = 0;
private Path<Feature, T> rootPath;
public HierarchicalQueryTracker(Vertex<Feature, T> root, int numFeatures) {
int size = numFeatures + 1;
results = new ArrayList<>(size);
for (int i = 0; i < size; ++i) {
results.add(new ArrayList<Path<Feature, T>>());
}
rootPath = new Path<Feature, T>(root);
List<Path<Feature, T>> l = new ArrayList<>(1);
l.add(rootPath);
results.get(0).add(rootPath);
}
public void addResults(Path<Feature, T> previousPath,
Collection<Vertex<Feature, T>> results) {
for (Vertex<Feature, T> vertex : results) {
Path<Feature, T> path = new Path<>(previousPath);
path.add(vertex);
/* Copy over the payload */
if (vertex.getValues().size() > 0) {
path.setPayload(new HashSet<>(vertex.getValues()));
}
this.results.get(getCurrentLevel()).add(path);
}
}
public void nextLevel() {
++currentLevel;
}
/**
* Retrieves the current level being processed.
*/
public int getCurrentLevel() {
return currentLevel;
}
/**
* Retrieves the results that are currently being processed. In other words,
* get the results from the last level in the hierarchy.
*/
public List<Path<Feature, T>> getCurrentResults() {
return results.get(getCurrentLevel() - 1);
}
public void markEvaluated() {
farthestEvaluatedExpression = getCurrentLevel();
}
public List<Path<Feature, T>> getQueryResults() {
List<Path<Feature, T>> paths = new ArrayList<>();
for (int i = farthestEvaluatedExpression; i < results.size(); ++i) {
for (Path<Feature, T> path : results.get(i)) {
if (path.hasPayload()) {
paths.add(path);
}
}
}
return paths;
}
@Override
public String toString() {
return "";
}
}
|
/*
* $Id$
* $URL$
*/
package org.subethamail.core.admin;
import java.io.UnsupportedEncodingException;
import javax.annotation.EJB;
import javax.annotation.security.RunAs;
import javax.mail.internet.InternetAddress;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.annotation.ejb.Depends;
import org.jboss.annotation.ejb.Service;
import org.jboss.annotation.security.SecurityDomain;
import org.subethamail.common.NotFoundException;
import org.subethamail.core.admin.i.Admin;
import org.subethamail.entity.Config;
import org.subethamail.entity.dao.DAO;
@Service(objectName="subetha:service=Bootstrapper")
// This depends annotation can be removed when JBoss fixes dependency bug.
@Depends("jboss.j2ee:ear=subetha.ear,jar=entity.jar,name=DAO,service=EJB3")
@SecurityDomain("subetha")
@RunAs("siteAdmin")
public class BootstrapperBean implements BootstrapperManagement
{
private static Log log = LogFactory.getLog(BootstrapperBean.class);
private static final String DEFAULT_EMAIL = "root@localhost";
private static final String DEFAULT_NAME = "Administrator";
private static final String DEFAULT_PASSWORD = "password";
private static final String DEFAULT_SITE_POSTMASTER = "postmaster@localhost";
private static final String DEFAULT_SITE_URL = "{Needs Configuration - Alert SubEtha Administrator}";
/**
* The config id of a Boolean that lets us know if we've run or not.
*/
public static final String BOOTSTRAPPED_CONFIG_ID = "bootstrapped";
@EJB DAO dao;
@EJB Admin admin;
/**
* @see BootstrapperManagement#start()
*/
public void start() throws Exception
{
// If we haven't been bootstrapped, we need to run.
try
{
Config cfg = this.dao.findConfig(BOOTSTRAPPED_CONFIG_ID);
// Might as well sanity check it
String value = (String)cfg.getValue();
if (value == null || value.length() == 0)
{
this.bootstrap();
cfg.setValue("1.0");
}
}
catch (NotFoundException ex)
{
this.bootstrap();
Config cfg = new Config(BOOTSTRAPPED_CONFIG_ID, "1.0");
this.dao.persist(cfg);
}
}
/**
* Creates the appropriate username and password
*/
public void bootstrap()
{
log.debug("Bootstrapping - establishing default site administrator");
this.bootstrapRoot();
log.debug("Bootstrapping - establishing default site settings");
this.bootstrapSiteSettings();
}
/**
* Sets up the root account
*/
protected void bootstrapRoot()
{
InternetAddress addy;
try
{
addy = new InternetAddress(DEFAULT_EMAIL, DEFAULT_NAME);
}
catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); }
Long id = this.admin.establishPerson(addy, DEFAULT_PASSWORD);
try
{
this.admin.setSiteAdmin(id, true);
}
catch (NotFoundException ex)
{
log.error("Impossible to establish person and then not find!", ex);
throw new RuntimeException(ex);
}
}
/**
* Sets up the initial site settings
*/
protected void bootstrapSiteSettings()
{
try
{
Config cfg = this.dao.findConfig(Config.ConfigKey.ID_SITE_POSTMASTER.getKey());
if (cfg.getValue() == null)
cfg.setValue(DEFAULT_SITE_POSTMASTER);
}
catch (NotFoundException ex)
{
Config cfg = new Config(Config.ConfigKey.ID_SITE_POSTMASTER.getKey(), DEFAULT_SITE_POSTMASTER);
this.dao.persist(cfg);
}
try
{
Config cfg = this.dao.findConfig(Config.ConfigKey.ID_SITE_URL.getKey());
if (cfg.getValue() == null)
cfg.setValue(DEFAULT_SITE_URL);
}
catch (NotFoundException ex)
{
Config cfg = new Config(Config.ConfigKey.ID_SITE_URL.getKey(), DEFAULT_SITE_URL);
this.dao.persist(cfg);
}
}
}
|
package com.facebook.react.flat;
import javax.annotation.Nullable;
import android.text.BoringLayout;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import com.facebook.csslayout.CSSNode;
import com.facebook.csslayout.MeasureOutput;
import com.facebook.csslayout.Spacing;
import com.facebook.fbui.widget.text.staticlayouthelper.StaticLayoutHelper;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.ViewDefaults;
import com.facebook.react.uimanager.ViewProps;
import com.facebook.react.uimanager.annotations.ReactProp;
/**
* RCTText is a top-level node for text. It extends {@link RCTVirtualText} because it can contain
* styling information, but has the following differences:
*
* a) RCTText is not a virtual node, and can be measured and laid out.
* b) when no font size is specified, a font size of ViewDefaults#FONT_SIZE_SP is assumed.
*/
/* package */ final class RCTText extends RCTVirtualText implements CSSNode.MeasureFunction {
private static final boolean INCLUDE_PADDING = true;
private static final TextPaint PAINT = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
// this is optional, and helps saving a few BoringLayout.Metrics allocations during measure().
private static @Nullable BoringLayout.Metrics sBoringLayoutMetrics;
private @Nullable CharSequence mText;
private @Nullable DrawTextLayout mDrawCommand;
private @Nullable BoringLayout.Metrics mBoringLayoutMetrics;
private float mSpacingMult = 1.0f;
private float mSpacingAdd = 0.0f;
private int mNumberOfLines = Integer.MAX_VALUE;
private Layout.Alignment mAlignment = Layout.Alignment.ALIGN_NORMAL;
public RCTText() {
setMeasureFunction(this);
getSpan().setFontSize(getDefaultFontSize());
}
@Override
public boolean isVirtual() {
return false;
}
@Override
public boolean isVirtualAnchor() {
return true;
}
@Override
public void measure(CSSNode node, float width, float height, MeasureOutput measureOutput) {
CharSequence text = getText();
if (TextUtils.isEmpty(text)) {
// to indicate that we don't have anything to display
mText = null;
measureOutput.width = 0;
measureOutput.height = 0;
return;
}
mText = text;
BoringLayout.Metrics metrics = BoringLayout.isBoring(text, PAINT, sBoringLayoutMetrics);
if (metrics != null) {
sBoringLayoutMetrics = mBoringLayoutMetrics;
if (sBoringLayoutMetrics != null) {
// make sure it's always empty, reported metrics can be incorrect otherwise
sBoringLayoutMetrics.top = 0;
sBoringLayoutMetrics.ascent = 0;
sBoringLayoutMetrics.descent = 0;
sBoringLayoutMetrics.bottom = 0;
sBoringLayoutMetrics.leading = 0;
}
mBoringLayoutMetrics = metrics;
float measuredWidth = (float) metrics.width;
if (Float.isNaN(width) || measuredWidth <= width) {
measureOutput.width = measuredWidth;
measureOutput.height = getMetricsHeight(metrics, INCLUDE_PADDING);
// to indicate that text layout was not created during the measure pass
mDrawCommand = null;
return;
}
// width < measuredWidth -> more that a single line -> not boring
}
int maximumWidth = Float.isNaN(width) ? Integer.MAX_VALUE : (int) width;
// Make sure we update the paint's text size. If we don't do this, ellipsis might be measured
// incorrecly (but drawn correctly, which almost feels like an Android bug, because width of the
// created layout may exceed the requested width). This is safe to do without making a copy per
// RCTText instance because that size is ONLY used to measure the ellipsis but not to draw it.
PAINT.setTextSize(getFontSize());
// at this point we need to create a StaticLayout to measure the text
StaticLayout layout = StaticLayoutHelper.make(
text,
0,
text.length(),
PAINT,
maximumWidth,
mAlignment,
mSpacingMult,
mSpacingAdd,
INCLUDE_PADDING,
TextUtils.TruncateAt.END,
maximumWidth,
mNumberOfLines,
false);
if (mDrawCommand != null && !mDrawCommand.isFrozen()) {
mDrawCommand.setLayout(layout);
} else {
mDrawCommand = new DrawTextLayout(layout);
}
measureOutput.width = mDrawCommand.getLayoutWidth();
measureOutput.height = mDrawCommand.getLayoutHeight();
}
@Override
protected void collectState(
StateBuilder stateBuilder,
float left,
float top,
float right,
float bottom,
float clipLeft,
float clipTop,
float clipRight,
float clipBottom) {
super.collectState(
stateBuilder,
left,
top,
right,
bottom,
clipLeft,
clipTop,
clipRight,
clipBottom);
if (mText == null) {
// nothing to draw (empty text).
return;
}
if (mDrawCommand == null) {
// Layout was not created during the measure pass, must be Boring, create it now
mDrawCommand = new DrawTextLayout(new BoringLayout(
mText,
PAINT,
(int) (right - left),
mAlignment,
mSpacingMult,
mSpacingAdd,
mBoringLayoutMetrics,
INCLUDE_PADDING));
}
Spacing padding = getPadding();
left += padding.get(Spacing.LEFT);
top += padding.get(Spacing.TOP);
// these are actual right/bottom coordinates where this DrawCommand will draw.
right = left + mDrawCommand.getLayoutWidth();
bottom = top + mDrawCommand.getLayoutHeight();
mDrawCommand = (DrawTextLayout) mDrawCommand.updateBoundsAndFreeze(
left,
top,
right,
bottom,
clipLeft,
clipTop,
clipRight,
clipBottom);
stateBuilder.addDrawCommand(mDrawCommand);
performCollectAttachDetachListeners(stateBuilder);
}
@ReactProp(name = ViewProps.LINE_HEIGHT, defaultDouble = Double.NaN)
public void setLineHeight(double lineHeight) {
if (Double.isNaN(lineHeight)) {
mSpacingMult = 1.0f;
mSpacingAdd = 0.0f;
} else {
mSpacingMult = 0.0f;
mSpacingAdd = PixelUtil.toPixelFromSP((float) lineHeight);
}
notifyChanged(true);
}
@ReactProp(name = ViewProps.NUMBER_OF_LINES, defaultInt = Integer.MAX_VALUE)
public void setNumberOfLines(int numberOfLines) {
mNumberOfLines = numberOfLines;
notifyChanged(true);
}
@Override
/* package */ void updateNodeRegion(float left, float top, float right, float bottom) {
if (mDrawCommand == null) {
super.updateNodeRegion(left, top, right, bottom);
return;
}
NodeRegion nodeRegion = getNodeRegion();
Layout layout = null;
if (nodeRegion instanceof TextNodeRegion) {
layout = ((TextNodeRegion) nodeRegion).getLayout();
}
Layout newLayout = mDrawCommand.getLayout();
if (nodeRegion.mLeft != left || nodeRegion.mTop != top ||
nodeRegion.mRight != right || nodeRegion.mBottom != bottom ||
layout != newLayout) {
setNodeRegion(new TextNodeRegion(left, top, right, bottom, getReactTag(), newLayout));
}
}
@Override
protected int getDefaultFontSize() {
// top-level <Text /> should always specify font size.
return fontSizeFromSp(ViewDefaults.FONT_SIZE_SP);
}
@Override
protected void notifyChanged(boolean shouldRemeasure) {
// Future patch: should only recreate Layout if shouldRemeasure is false
dirty();
}
@ReactProp(name = ViewProps.TEXT_ALIGN)
public void setTextAlign(@Nullable String textAlign) {
if (textAlign == null || "auto".equals(textAlign)) {
mAlignment = Layout.Alignment.ALIGN_NORMAL;
} else if ("left".equals(textAlign)) {
// left and right may yield potentially different results (relative to non-nodes) in cases
// when supportsRTL="true" in the manifest.
mAlignment = Layout.Alignment.ALIGN_NORMAL;
} else if ("right".equals(textAlign)) {
mAlignment = Layout.Alignment.ALIGN_OPPOSITE;
} else if ("center".equals(textAlign)) {
mAlignment = Layout.Alignment.ALIGN_CENTER;
} else {
throw new JSApplicationIllegalArgumentException("Invalid textAlign: " + textAlign);
}
notifyChanged(false);
}
/**
* Returns measured line height according to an includePadding flag.
*/
private static int getMetricsHeight(BoringLayout.Metrics metrics, boolean includePadding) {
if (includePadding) {
return metrics.bottom - metrics.top;
} else {
return metrics.descent - metrics.ascent;
}
}
}
|
package org.jasig.cas.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.inspektr.common.ioc.annotation.GreaterThan;
import org.inspektr.common.ioc.annotation.NotNull;
import org.springframework.util.Assert;
import org.springframework.beans.factory.DisposableBean;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
/**
* @author Scott Battaglia
* @version $Revision$ $Date$
* @since 3.1
*/
public final class HttpClient implements Serializable, DisposableBean {
/** Unique Id for serialization. */
private static final long serialVersionUID = -5306738686476129516L;
/** The default status codes we accept. */
private static final int[] DEFAULT_ACCEPTABLE_CODES = new int[] {
HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_MODIFIED,
HttpURLConnection.HTTP_MOVED_TEMP, HttpURLConnection.HTTP_MOVED_PERM,
HttpURLConnection.HTTP_ACCEPTED};
private static final Log log = LogFactory.getLog(HttpClient.class);
private static ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(100);
/** List of HTTP status codes considered valid by this AuthenticationHandler. */
@NotNull
private int[] acceptableCodes = DEFAULT_ACCEPTABLE_CODES;
@GreaterThan(0)
private int connectionTimeout = 5000;
@GreaterThan(0)
private int readTimeout = 5000;
/**
* Note that changing this executor will affect all httpClients. While not ideal, this change was made because certain ticket registries
* were persisting the HttpClient and thus getting serializable exceptions.
* @param executorService
*/
public void setExecutorService(final ExecutorService executorService) {
Assert.notNull(executorService);
EXECUTOR_SERVICE = executorService;
}
/**
* Sends a message to a particular endpoint. Option of sending it without waiting to ensure a response was returned.
* <p>
* This is useful when it doesn't matter about the response as you'll perform no action based on the response.
*
* @param url the url to send the message to
* @param message the message itself
* @param async true if you don't want to wait for the response, false otherwise.
* @return boolean if the message was sent, or async was used. false if the message failed.
*/
public boolean sendMessageToEndPoint(final String url, final String message, final boolean async) {
final Future<Boolean> result = EXECUTOR_SERVICE.submit(new MessageSender(url, message, this.readTimeout, this.connectionTimeout));
if (async) {
return true;
}
try {
return result.get();
} catch (final Exception e) {
return false;
}
}
public boolean isValidEndPoint(final String url) {
try {
final URL u = new URL(url);
return isValidEndPoint(u);
} catch (final MalformedURLException e) {
log.error(e.getMessage(),e);
return false;
}
}
public boolean isValidEndPoint(final URL url) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(this.connectionTimeout);
connection.setReadTimeout(this.readTimeout);
connection.connect();
final int responseCode = connection.getResponseCode();
for (final int acceptableCode : this.acceptableCodes) {
if (responseCode == acceptableCode) {
if (log.isDebugEnabled()) {
log.debug("Response code from server matched " + responseCode + ".");
}
return true;
}
}
if (log.isDebugEnabled()) {
log.debug("Response Code did not match any of the acceptable response codes. Code returned was " + responseCode);
}
} catch (final IOException e) {
log.error(e.getMessage(),e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
return false;
}
/**
* Set the acceptable HTTP status codes that we will use to determine if the
* response from the URL was correct.
*
* @param acceptableCodes an array of status code integers.
*/
public final void setAcceptableCodes(final int[] acceptableCodes) {
this.acceptableCodes = acceptableCodes;
}
public void setConnectionTimeout(final int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public void setReadTimeout(final int readTimeout) {
this.readTimeout = readTimeout;
}
public void destroy() throws Exception {
EXECUTOR_SERVICE.shutdown();
}
private static final class MessageSender implements Callable<Boolean> {
private String url;
private String message;
private int readTimeout;
private int connectionTimeout;
public MessageSender(final String url, final String message, final int readTimeout, final int connectionTimeout) {
this.url = url;
this.message = message;
this.readTimeout = readTimeout;
this.connectionTimeout = connectionTimeout;
}
public Boolean call() throws Exception {
HttpURLConnection connection = null;
BufferedReader in = null;
try {
if (log.isDebugEnabled()) {
log.debug("Attempting to access " + url);
}
final URL logoutUrl = new URL(url);
final String output = "logoutRequest=" + URLEncoder.encode(message, "UTF-8");
connection = (HttpURLConnection) logoutUrl.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setReadTimeout(readTimeout);
connection.setConnectTimeout(connectionTimeout);
connection.setRequestProperty("Content-Length", Integer.toString(output.getBytes().length));
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
final DataOutputStream printout = new DataOutputStream(connection.getOutputStream());
printout.writeBytes(output);
printout.flush();
printout.close();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while (in.readLine() != null) {
// nothing to do
}
if (log.isDebugEnabled()) {
log.debug("Finished sending message to" + url);
}
return true;
} catch (final SocketTimeoutException e) {
log.warn("Socket Timeout Detected while attempting to send message to [" + url + "].");
return false;
} catch (final Exception e) {
log.warn(e.getMessage());
return false;
} finally {
if (in != null) {
try {
in.close();
} catch (final IOException e) {
// can't do anything
}
}
if (connection != null) {
connection.disconnect();
}
}
}
}
}
|
package org.gluu.oxauth.service;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.gluu.oxauth.model.common.SessionId;
import org.gluu.oxauth.model.config.ConfigurationFactory;
import org.gluu.oxauth.model.configuration.AppConfiguration;
import org.gluu.persist.exception.EntryPersistenceException;
import org.gluu.service.cdi.util.CdiUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.slf4j.Logger;
import javax.ejb.Stateless;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Set;
import static org.gluu.oxauth.model.util.StringUtils.toList;
/**
* @author Yuriy Zabrovarnyy
*/
@Stateless
@Named
public class CookieService {
private static final String SESSION_STATE_COOKIE_NAME = "session_state";
public static final String OP_BROWSER_STATE = "opbs";
public static final String SESSION_ID_COOKIE_NAME = "session_id";
private static final String RP_ORIGIN_ID_COOKIE_NAME = "rp_origin_id";
private static final String UMA_SESSION_ID_COOKIE_NAME = "uma_session_id";
public static final String CONSENT_SESSION_ID_COOKIE_NAME = "consent_session_id";
public static final String CURRENT_SESSIONS_COOKIE_NAME = "current_sessions";
@Inject
private Logger log;
@Inject
private FacesContext facesContext;
@Inject
private ExternalContext externalContext;
@Inject
private ConfigurationFactory configurationFactory;
@Inject
private AppConfiguration appConfiguration;
public String getSessionIdFromCookie(HttpServletRequest request) {
return getValueFromCookie(request, SESSION_ID_COOKIE_NAME);
}
public String getUmaSessionIdFromCookie(HttpServletRequest request) {
return getValueFromCookie(request, UMA_SESSION_ID_COOKIE_NAME);
}
public String getConsentSessionIdFromCookie(HttpServletRequest request) {
return getValueFromCookie(request, CONSENT_SESSION_ID_COOKIE_NAME);
}
public String getSessionStateFromCookie(HttpServletRequest request) {
return getValueFromCookie(request, SESSION_STATE_COOKIE_NAME);
}
public Set<String> getCurrentSessions() {
try {
if (facesContext == null) {
return null;
}
final HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
if (request != null) {
return getCurrentSessions(request);
} else {
log.trace("Faces context returns null for http request object.");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
public Set<String> getCurrentSessions(HttpServletRequest request) {
final String valueFromCookie = getValueFromCookie(request, CURRENT_SESSIONS_COOKIE_NAME);
if (StringUtils.isBlank(valueFromCookie)) {
return Sets.newHashSet();
}
try {
return Sets.newHashSet(toList(new JSONArray(valueFromCookie)));
} catch (JSONException e) {
log.error("Failed to parse current_sessions, value: " + valueFromCookie, e);
return Sets.newHashSet();
}
}
public void addCurrentSessionCookie(SessionId sessionId, HttpServletRequest request, HttpServletResponse httpResponse) {
final Set<String> currentSessions = getCurrentSessions(request);
removeOutdatedCurrentSessions(currentSessions);
currentSessions.add(sessionId.getId());
String header = CURRENT_SESSIONS_COOKIE_NAME + "=" + new JSONArray(currentSessions).toString();
header += "; Path=/";
header += "; Secure";
header += "; HttpOnly";
createCookie(header, httpResponse);
}
private void removeOutdatedCurrentSessions(Set<String> currentSessions) {
if (currentSessions.isEmpty()) {
return;
}
SessionIdService sessionIdService = CdiUtil.bean(SessionIdService.class); // avoid cycle dependency
Set<String> toRemove = Sets.newHashSet();
for (String sessionId : currentSessions) {
SessionId sessionIdObject = null;
try {
sessionIdObject = sessionIdService.getSessionId(sessionId, true);
} catch (EntryPersistenceException e) {
// ignore - valid case if session is outdated
}
if (sessionIdObject == null) {
toRemove.add(sessionId);
}
}
currentSessions.removeAll(toRemove);
}
public String getValueFromCookie(HttpServletRequest request, String cookieName) {
try {
final Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(cookieName) /*&& cookie.getSecure()*/) {
log.trace("Found cookie: '{}'", cookie.getValue());
return cookie.getValue();
}
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return "";
}
public String getRpOriginIdCookie() {
return getValueFromCookie(RP_ORIGIN_ID_COOKIE_NAME);
}
public String getValueFromCookie(String cookieName) {
try {
if (facesContext == null) {
return null;
}
final HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
if (request != null) {
return getValueFromCookie(request, cookieName);
} else {
log.trace("Faces context returns null for http request object.");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
public String getSessionIdFromCookie() {
try {
if (facesContext == null) {
return null;
}
final HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
if (request != null) {
return getSessionIdFromCookie(request);
} else {
log.trace("Faces context returns null for http request object.");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
public void creatRpOriginIdCookie(String rpOriginId) {
try {
final Object response = externalContext.getResponse();
if (response instanceof HttpServletResponse) {
final HttpServletResponse httpResponse = (HttpServletResponse) response;
creatRpOriginIdCookie(rpOriginId, httpResponse);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public void creatRpOriginIdCookie(String rpOriginId, HttpServletResponse httpResponse) {
String header = RP_ORIGIN_ID_COOKIE_NAME + "=" + rpOriginId;
header += "; Path=" + configurationFactory.getContextPath();
header += "; Secure";
header += "; HttpOnly";
createCookie(header, httpResponse);
}
public void createCookieWithState(String sessionId, String sessionState, String opbs, HttpServletRequest request, HttpServletResponse httpResponse, String cookieName) {
String header = cookieName + "=" + sessionId;
header += "; Path=/";
header += "; Secure";
header += "; HttpOnly";
createCookie(header, httpResponse);
createSessionStateCookie(sessionState, httpResponse);
createOPBrowserStateCookie(opbs, httpResponse);
}
public void createSessionIdCookie(SessionId sessionId, HttpServletRequest request, HttpServletResponse httpResponse, boolean isUma) {
String cookieName = isUma ? UMA_SESSION_ID_COOKIE_NAME : SESSION_ID_COOKIE_NAME;
if (!isUma) {
addCurrentSessionCookie(sessionId, request, httpResponse);
}
createCookieWithState(sessionId.getId(), sessionId.getSessionState(), sessionId.getOPBrowserState(), request, httpResponse, cookieName);
}
public void createSessionIdCookie(SessionId sessionId, boolean isUma) {
try {
final Object response = externalContext.getResponse();
final Object request = externalContext.getRequest();
if (response instanceof HttpServletResponse && request instanceof HttpServletRequest) {
final HttpServletResponse httpResponse = (HttpServletResponse) response;
final HttpServletRequest httpRequest = (HttpServletRequest) request;
createSessionIdCookie(sessionId, httpRequest, httpResponse, isUma);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
public void createSessionStateCookie(String sessionState, HttpServletResponse httpResponse) {
// Create the special cookie header with secure flag but not HttpOnly because the session_state
// needs to be read from the OP iframe using JavaScript
String header = SESSION_STATE_COOKIE_NAME + "=" + sessionState;
header += "; Path=/";
header += "; Secure";
createCookie(header, httpResponse);
}
public void createOPBrowserStateCookie(String opbs, HttpServletResponse httpResponse) {
// Create the special cookie header with secure flag but not HttpOnly because the opbs
// needs to be read from the OP iframe using JavaScript
String header = OP_BROWSER_STATE + "=" + opbs;
header += "; Path=/";
header += "; Secure";
Integer sessionStateLifetime = appConfiguration.getSessionIdLifetime();
if (sessionStateLifetime != null && sessionStateLifetime > 0) {
DateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
Calendar expirationDate = Calendar.getInstance();
expirationDate.add(Calendar.SECOND, sessionStateLifetime);
header += "; Expires=" + formatter.format(expirationDate.getTime()) + ";";
if (StringUtils.isNotBlank(appConfiguration.getCookieDomain())) {
header += "Domain=" + appConfiguration.getCookieDomain() + ";";
}
}
httpResponse.addHeader("Set-Cookie", header);
}
protected void createCookie(String header, HttpServletResponse httpResponse) {
Integer sessionStateLifetime = appConfiguration.getSessionIdLifetime();
if (sessionStateLifetime != null && sessionStateLifetime > 0) {
DateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
Calendar expirationDate = Calendar.getInstance();
expirationDate.add(Calendar.SECOND, sessionStateLifetime);
header += "; Expires=" + formatter.format(expirationDate.getTime()) + ";";
if (StringUtils.isNotBlank(appConfiguration.getCookieDomain())) {
header += "Domain=" + appConfiguration.getCookieDomain() + ";";
}
}
httpResponse.addHeader("Set-Cookie", header);
}
public void removeSessionIdCookie(HttpServletResponse httpResponse) {
removeCookie(SESSION_ID_COOKIE_NAME, httpResponse);
}
public void removeOPBrowserStateCookie(HttpServletResponse httpResponse) {
removeCookie(OP_BROWSER_STATE, httpResponse);
}
public void removeUmaSessionIdCookie(HttpServletResponse httpResponse) {
removeCookie(UMA_SESSION_ID_COOKIE_NAME, httpResponse);
}
public void removeConsentSessionIdCookie(HttpServletResponse httpResponse) {
removeCookie(CONSENT_SESSION_ID_COOKIE_NAME, httpResponse);
}
public void removeCookie(String cookieName, HttpServletResponse httpResponse) {
final Cookie cookie = new Cookie(cookieName, null); // Not necessary, but saves bandwidth.
cookie.setPath("/");
cookie.setMaxAge(0); // Don't set to -1 or it will become a session cookie!
if (StringUtils.isNotBlank(appConfiguration.getCookieDomain())) {
cookie.setDomain(appConfiguration.getCookieDomain());
}
httpResponse.addCookie(cookie);
}
}
|
package org.jboss.as.clustering.infinispan.subsystem.remote;
import static org.jboss.as.clustering.infinispan.subsystem.remote.HotRodStoreResourceDefinition.Attribute.CACHE_CONFIGURATION;
import static org.jboss.as.clustering.infinispan.subsystem.remote.HotRodStoreResourceDefinition.Attribute.REMOTE_CACHE_CONTAINER;
import org.jboss.as.clustering.infinispan.subsystem.StoreServiceConfigurator;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceBuilder;
import org.wildfly.clustering.infinispan.client.InfinispanClientRequirement;
import org.wildfly.clustering.infinispan.client.RemoteCacheContainer;
import org.wildfly.clustering.service.ServiceConfigurator;
import org.wildfly.clustering.service.ServiceSupplierDependency;
import org.wildfly.clustering.service.SupplierDependency;
/**
* @author Radoslav Husar
*/
public class HotRodStoreServiceConfigurator extends StoreServiceConfigurator<HotRodStoreConfiguration, HotRodStoreConfigurationBuilder> {
private volatile SupplierDependency<RemoteCacheContainer> remoteCacheContainer;
private volatile String cacheConfiguration;
HotRodStoreServiceConfigurator(PathAddress address) {
super(address, HotRodStoreConfigurationBuilder.class);
}
@Override
public ServiceConfigurator configure(OperationContext context, ModelNode model) throws OperationFailedException {
this.cacheConfiguration = CACHE_CONFIGURATION.resolveModelAttribute(context, model).asStringOrNull();
String remoteCacheContainerName = REMOTE_CACHE_CONTAINER.resolveModelAttribute(context, model).asString();
this.remoteCacheContainer = new ServiceSupplierDependency<>(InfinispanClientRequirement.REMOTE_CONTAINER.getServiceName(context, remoteCacheContainerName));
return super.configure(context, model);
}
@Override
public <T> ServiceBuilder<T> register(ServiceBuilder<T> builder) {
return super.register(this.remoteCacheContainer.register(builder));
}
@Override
public void accept(HotRodStoreConfigurationBuilder builder) {
builder.segmented(true)
.cacheConfiguration(this.cacheConfiguration)
.remoteCacheContainer(this.remoteCacheContainer.get())
;
}
}
|
package com.example.shiftindicator;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import com.openxc.VehicleManager;
import com.openxc.measurements.AcceleratorPedalPosition;
import com.openxc.measurements.EngineSpeed;
import com.openxc.measurements.Measurement;
import com.openxc.measurements.UnrecognizedMeasurementTypeException;
import com.openxc.measurements.VehicleSpeed;
import com.openxc.remote.VehicleServiceException;
import com.openxc.sources.DataSourceException;
import com.openxc.sources.trace.TraceVehicleDataSource;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.text.Layout;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private static String TAG = "ShiftIndicator";
private VehicleManager mVehicleManager;
private boolean mIsBound;
private TextView mVehicleSpeedView;
private TextView mEngineSpeedView;
private TextView mShiftIndicator;
private TextView mShiftCalc;
private TextView mPedalView;
private TextView mGearPosition;
private View mLayout;
private TraceVehicleDataSource mTraceSource;
private int engine_speed;
private double vehicle_speed;
private double pedal_pos;
private long shiftTime;
private int currentGear;
private double base_pedal_position = 15.0;
private int min_rpm = 1300;
// FIGO RATIOS rpm/speed
private int ratio1 = 140;
private int ratio2 = 75;
private int ratio3 = 50;
private int ratio4 = 37;
private int ratio5 = 30;
private int ratio6 = 1; // does not exist in Figo
// Focus ST RATIOS rpm/speed:
/* private int ratio1 = 114;
private int ratio2 = 69;
private int ratio3 = 46;
private int ratio4 = 36;
private int ratio5 = 28;
private int ratio6 = 23;*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "Shift Indicator created");
Intent intent = new Intent(this, VehicleManager.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
mVehicleSpeedView = (TextView) findViewById(R.id.vehicle_speed);
mEngineSpeedView = (TextView) findViewById(R.id.engine_speed);
mShiftIndicator = (TextView) findViewById(R.id.shift_indicator);
mShiftCalc = (TextView) findViewById(R.id.shift_calculated);
mPedalView = (TextView) findViewById(R.id.pedal_position);
mGearPosition = (TextView) findViewById(R.id.gear_position);
mLayout = findViewById(R.id.layout);
mLayout.setBackgroundColor(Color.BLACK);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onPause() {
super.onPause();
Log.i("openxc", "Unbinding from vehicle service");
unbindService(mConnection);
mVehicleManager.removeSource(mTraceSource);
}
private ServiceConnection mConnection = new ServiceConnection() {
// Called when the connection with the service is established
public void onServiceConnected(ComponentName className,
IBinder service) {
Log.i(TAG, "Bound to VehicleManager");
mVehicleManager = ((VehicleManager.VehicleBinder)service).getService();
try {
mVehicleManager.addListener(VehicleSpeed.class, mSpeedListener);
mVehicleManager.addListener(EngineSpeed.class, mEngineListener);
mVehicleManager.addListener(AcceleratorPedalPosition.class, mPedalListener);
mVehicleManager.addListener(ShiftRecommendation.class, mShiftRecommendation);
} catch(VehicleServiceException e) {
Log.w(TAG, "Couldn't add listeners for measurements", e);
} catch(UnrecognizedMeasurementTypeException e) {
Log.w(TAG, "Couldn't add listeners for measurements", e);
}
URI mTraceFile;
try {
mTraceFile = new URI("file:///sdcard/com.openxc/shiftIndicateTraceboolean.json");
mTraceSource = new TraceVehicleDataSource(MainActivity.this, mTraceFile);
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DataSourceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//mVehicleManager.addSource(mTraceSource);
mIsBound = true;
}
// Called when the connection with the service disconnects unexpectedly
public void onServiceDisconnected(ComponentName className) {
Log.w(TAG, "VehicleService disconnected unexpectedly");
mVehicleManager = null;
mIsBound = false;
}
};
VehicleSpeed.Listener mSpeedListener = new VehicleSpeed.Listener() {
public void receive(Measurement measurement) {
final VehicleSpeed updated_value = (VehicleSpeed) measurement;
vehicle_speed = updated_value.getValue().doubleValue();
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
// send vehicle speed with 1 decimal point
mVehicleSpeedView.setText(""+Math.round(vehicle_speed*10)/10);
}
});
}
};
EngineSpeed.Listener mEngineListener = new EngineSpeed.Listener() {
public void receive(Measurement measurement) {
final EngineSpeed updated_value = (EngineSpeed) measurement;
engine_speed = updated_value.getValue().intValue();
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
mEngineSpeedView.setText(""+engine_speed);
}
});
// Gear position calculation
// First calculate gear based on ratio of rpm to speed
if(vehicle_speed==0) vehicle_speed = 1;
double ratio = engine_speed/vehicle_speed;
int next_ratio=1;
long currentTime = new Date().getTime();
if((ratio1*1.04) > ratio && (ratio1*.96) < ratio){
next_ratio=ratio2;
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
mGearPosition.setText("1");
}
});
}
else if((ratio2*1.04) > ratio && (ratio2*.96) < ratio){
next_ratio=ratio3;
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
mGearPosition.setText("2");
}
});
}
else if((ratio3*1.04) > ratio && (ratio3*.96) < ratio){
next_ratio=ratio4;
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
mGearPosition.setText("3");
}
});
}
else if((ratio4*1.04) > ratio && (ratio4*.96) < ratio){
next_ratio=ratio5;
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
mGearPosition.setText("4");
}
});
}
else if((ratio5*1.04) > ratio && (ratio5*.96) < ratio){
next_ratio=ratio6;
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
mGearPosition.setText("5");
}
});
}
else if((ratio6*1.04) > ratio && (ratio6*.96) < ratio){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
mGearPosition.setText("6");
}
});
cancelShift(currentTime);
}
else {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
mGearPosition.setText("N");
}
});
cancelShift(currentTime);
return;
}
//if the pedal_pos is less than 10 then the driver is probably
//shifting or slowing down so no shift indication is needed
if (pedal_pos < 10) {
cancelShift(currentTime);
return;
}
//check if the pedal position is above the minimum threshold.
//if the pedal position is above the minimum threshold, then the
//driver is thought to be accelerating heavily and thus the shift indication
//should be sent at a higher RPM:
double next_rpm;
if (pedal_pos >= base_pedal_position){
//algorithm based on particular vehicle. requires tweeking for best performance
next_rpm = 1.2*(pedal_pos)*(pedal_pos)-30*pedal_pos+1480;
}
else next_rpm=min_rpm;
if (next_rpm < vehicle_speed*next_ratio){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
mShiftCalc.setText("Shift!!");
}
});
shiftTime = new Date().getTime();
}
else cancelShift(currentTime);
}
private void cancelShift(long t) {
// only cancel the shift indication after it's been on the screen for 1000ms
if (t-shiftTime>1000){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
mShiftCalc.setText("");
}
});
}
return;
}
};
AcceleratorPedalPosition.Listener mPedalListener = new AcceleratorPedalPosition.Listener() {
public void receive(Measurement measurement) {
final AcceleratorPedalPosition updated_value = (AcceleratorPedalPosition) measurement;
pedal_pos = updated_value.getValue().doubleValue();
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
mPedalView.setText(""+(int)pedal_pos);
}
});
}
};
ShiftRecommendation.Listener mShiftRecommendation = new ShiftRecommendation.Listener() {
public void receive(Measurement measurement) {
final ShiftRecommendation updated_value = (ShiftRecommendation) measurement;
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
if (updated_value.getValue().booleanValue() == true) {
mShiftIndicator.setText("SHIFT!");
//mLayout.setBackgroundColor(Color.WHITE); // flash the background when the driver should shift
}
else {
//mLayout.setBackgroundColor(Color.BLACK);
mShiftIndicator.setText("");
}
}
});
}
};
}
|
package com.pigtutorial.ch01;
import java.io.File;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.pig.pigunit.PigTest;
import org.apache.pig.tools.parameters.ParseException;
import org.junit.Test;
public class TestSimpleLoadStore extends TestCase {
private static final String EXPECTED_OUTPUT_FILE_PATH = "src/resources/data/expected_output/simple_load_store_output";
@Test
public void testSimpleLoadStoreUsingFiles() {
String[] args = {};
// Specify the expected output file path and create file object
File file = new File(EXPECTED_OUTPUT_FILE_PATH);
PigTest test = null;
try {
test = new PigTest("src/resources/pig/simple_load_store.pig", args);
} catch (IOException e) {
System.err.println("Caught exception while reading pig script");
e.printStackTrace();
}
try {
test.assertOutput("data_alias", file);
test.unoverride("STORE");
test.runScript();
} catch (IOException e) {
System.err.println("Caught exception while reading file");
e.printStackTrace();
} catch (ParseException e) {
System.err.println("Caught exception while parsing script");
e.printStackTrace();
}
}
@Test
public void testSimpleLoadStoreUsingVariables() {
String[] args = {};
PigTest test = null;
try {
test = new PigTest("src/resources/pig/simple_load_store.pig", args);
} catch (IOException e) {
System.err.println("Caught exception while reading pig script");
e.printStackTrace();
}
String[] input = { "STUD0001\tMarita\t29", "STUD0002\tShannon\t21",
"STUD0003\tGayle\t24", "STUD0004\tStephen\t32" };
String[] output = { "(STUD0001,Marita,29)", "(STUD0002,Shannon,21)",
"(STUD0003,Gayle,24)", "(STUD0004,Stephen,32)" };
try {
test.assertOutput("data_alias", input, "data_alias", output);
} catch (IOException e) {
System.err.println("Caught exception while reading file");
e.printStackTrace();
} catch (ParseException e) {
System.err.println("Caught exception while parsing script");
e.printStackTrace();
}
}
}
|
package by.vorokhobko.Exception;
/**
* StubInput.
*
* Class StubInput the creation of the input as the user part 002, lesson 5.
* @author Evgeny Vorokhobko (vorokhobko2011@yandex.ru).
* @since 20.03.2017.
* @version 1.
*/
public class StubInput implements Input {
private String[] answers;
private int position = 0;
public StubInput(String[] answers) {
this.answers = answers;
}
/**
* The implementation of polymorphism from class Input.
*
* @param question - question.
* @return tag.
*/
public String ask(String question) {
return answers[position++];
}
/**
* The overloading from method ask.
*
* @param question - question.
* @param range - range.
* @return tag.
*/
public int ask(String question, int[] range) {
for (int value = 0; value < range.length; value++) {
range[value] = value;
if (range[value] == value) {
return range[value];
} else {
throw new UnsupportedOperationException("Unsupported operation");
}
}
return range[position++];
}
}
|
package fr.neamar.kiss.result;
import android.content.Context;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import fr.neamar.kiss.R;
import fr.neamar.kiss.pojo.TogglesPojo;
import fr.neamar.kiss.toggles.TogglesHandler;
public class TogglesResult extends Result {
private final TogglesPojo togglePojo;
/**
* Handler for all toggle-related queries
*/
private TogglesHandler togglesHandler = null;
public TogglesResult(TogglesPojo togglePojo) {
super();
this.pojo = this.togglePojo = togglePojo;
}
@SuppressWarnings({"ResourceType", "deprecation"})
@Override
public View display(Context context, int position, View v) {
// On first run, initialize handler
if (togglesHandler == null)
togglesHandler = new TogglesHandler(context);
if (v == null)
v = inflateFromId(context, R.layout.item_toggle);
String togglePrefix = "<small><small>" + context.getString(R.string.toggles_prefix) + "</small></small>";
TextView toggleName = (TextView) v.findViewById(R.id.item_toggle_name);
toggleName.setText(TextUtils.concat(Html.fromHtml(togglePrefix), enrichText(togglePojo.displayName, context)));
ImageView toggleIcon = (ImageView) v.findViewById(R.id.item_toggle_icon);
toggleIcon.setImageDrawable(context.getResources().getDrawable(togglePojo.icon));
toggleIcon.setColorFilter(getThemeFillColor(context), Mode.SRC_IN);
// Use the handler to check or un-check button
final CompoundButton toggleButton = (CompoundButton) v
.findViewById(R.id.item_toggle_action_toggle);
//set listener to null to avoid calling the listener of the older toggle item
//(due to recycling)
toggleButton.setOnCheckedChangeListener(null);
Boolean state = togglesHandler.getState(togglePojo);
if (state != null)
toggleButton.setChecked(togglesHandler.getState(togglePojo));
else
toggleButton.setEnabled(false);
toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!togglesHandler.getState(togglePojo).equals(toggleButton.isChecked())) {
// record launch manually
recordLaunch(buttonView.getContext());
togglesHandler.setState(togglePojo, toggleButton.isChecked());
toggleButton.setEnabled(false);
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
toggleButton.setEnabled(true);
}
}.execute();
}
}
});
return v;
}
@SuppressWarnings("deprecation")
@Override
public Drawable getDrawable(Context context) {
return context.getResources().getDrawable(togglePojo.icon);
}
@Override
public void doLaunch(Context context, View v) {
CompoundButton toggleButton = null;
if (v != null) {
toggleButton = (CompoundButton) v.findViewById(R.id.item_toggle_action_toggle);
}
if (toggleButton != null) {
// Use the handler to check or un-check button
if (toggleButton.isEnabled()) {
toggleButton.performClick();
}
} else {
//in case it is pinned on kissbar
if (togglesHandler == null) {
togglesHandler = new TogglesHandler(context);
}
//get message based on current state of toggle
String msg = context.getResources().getString(togglesHandler.getState(togglePojo) ? R.string.toggles_off : R.string.toggles_on);
//toggle state
togglesHandler.setState(togglePojo, !togglesHandler.getState(togglePojo));
//show toast to inform user what the state is
Toast.makeText(context, String.format(msg, " " + this.pojo.displayName), Toast.LENGTH_SHORT).show();
}
}
}
|
package us.kbase.userandjobstate.test.kbase;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import org.ini4j.Ini;
import org.ini4j.Profile.Section;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import us.kbase.auth.AuthException;
import us.kbase.auth.AuthService;
import us.kbase.common.service.ServerException;
import us.kbase.common.service.Tuple14;
import us.kbase.common.service.Tuple5;
import us.kbase.common.service.Tuple7;
import us.kbase.common.service.UObject;
import us.kbase.common.test.TestException;
import us.kbase.userandjobstate.InitProgress;
import us.kbase.userandjobstate.Results;
import us.kbase.userandjobstate.UserAndJobStateClient;
import us.kbase.userandjobstate.UserAndJobStateServer;
import us.kbase.userandjobstate.test.FakeJob;
import us.kbase.userandjobstate.test.UserJobStateTestCommon;
/*
* These tests are specifically for testing the JSON-RPC communications between
* the client, up to the invocation of the {@link us.kbase.userandjobstate.userstate.UserState}
* and {@link us.kbase.userandjobstate.jobstate.JobState}
* methods. As such they do not test the full functionality of the methods;
* {@link us.kbase.userandjobstate.userstate.test.UserStateTests} and
* {@link us.kbase.userandjobstate.jobstate.test.JobStateTests} handles that.
*/
public class JSONRPCLayerTest {
private static UserAndJobStateServer SERVER = null;
private static UserAndJobStateClient CLIENT1 = null;
private static String USER1 = null;
private static UserAndJobStateClient CLIENT2 = null;
private static String USER2 = null;
private static String TOKEN1;
private static String TOKEN2;
private static class ServerThread extends Thread {
public void run() {
try {
SERVER.startupServer();
} catch (Exception e) {
System.err.println("Can't start server:");
e.printStackTrace();
}
}
}
@SuppressWarnings("unchecked")
public static Map<String, String> getenv() throws NoSuchFieldException,
SecurityException, IllegalArgumentException, IllegalAccessException {
Map<String, String> unmodifiable = System.getenv();
Class<?> cu = unmodifiable.getClass();
Field m = cu.getDeclaredField("m");
m.setAccessible(true);
return (Map<String, String>) m.get(unmodifiable);
}
@BeforeClass
public static void setUpClass() throws Exception {
USER1 = System.getProperty("test.user1");
USER2 = System.getProperty("test.user2");
String p1 = System.getProperty("test.pwd1");
String p2 = System.getProperty("test.pwd2");
UserJobStateTestCommon.destroyAndSetupDB();
//write the server config file:
File iniFile = File.createTempFile("test", ".cfg", new File("./"));
iniFile.deleteOnExit();
System.out.println("Created temporary config file: " + iniFile.getAbsolutePath());
Ini ini = new Ini();
Section ws = ini.add("UserAndJobState");
ws.add("mongodb-host", UserJobStateTestCommon.getHost());
ws.add("mongodb-database", UserJobStateTestCommon.getDB());
ws.add("mongodb-user", UserJobStateTestCommon.getMongoUser());
ws.add("mongodb-pwd", UserJobStateTestCommon.getMongoPwd());
ini.store(iniFile);
//set up env
Map<String, String> env = getenv();
env.put("KB_DEPLOYMENT_CONFIG", iniFile.getAbsolutePath());
env.put("KB_SERVICE_NAME", "UserAndJobState");
SERVER = new UserAndJobStateServer();
new ServerThread().start();
System.out.println("Main thread waiting for server to start up");
while(SERVER.getServerPort() == null) {
Thread.sleep(1000);
}
int port = SERVER.getServerPort();
System.out.println("Started test server on port " + port);
System.out.println("Starting tests");
CLIENT1 = new UserAndJobStateClient(new URL("http://localhost:" + port), USER1, p1);
CLIENT2 = new UserAndJobStateClient(new URL("http://localhost:" + port), USER2, p2);
CLIENT1.setAuthAllowedForHttp(true);
CLIENT2.setAuthAllowedForHttp(true);
try {
TOKEN1 = AuthService.login(USER1, p1).getTokenString();
} catch (AuthException ae) {
throw new TestException("Unable to login with test.user1: " + USER1 +
"\nPlease check the credentials in the test configuration.", ae);
}
try {
TOKEN2 = AuthService.login(USER2, p2).getTokenString();
} catch (AuthException ae) {
throw new TestException("Unable to login with test.user2: " + USER2 +
"\nPlease check the credentials in the test configuration.", ae);
}
}
@AfterClass
public static void tearDownClass() throws Exception {
if (SERVER != null) {
System.out.print("Killing server... ");
SERVER.stopServer();
System.out.println("Done");
}
}
@Test
public void unicode() throws Exception {
int[] char1 = {11614};
String uni = new String(char1, 0, 1);
CLIENT1.setState("uni", "key", new UObject(uni));
assertThat("get unicode back",
CLIENT1.getState("uni", "key", 0L)
.asClassInstance(Object.class),
is((Object) uni));
CLIENT1.removeState("uni", "key");
}
@Test
public void getSetListStateService() throws Exception {
List<Integer> data = Arrays.asList(1, 2, 3, 5, 8, 13);
List<Integer> data2 = Arrays.asList(42);
CLIENT1.setState("serv1", "key1", new UObject(data));
CLIENT2.setState("serv1", "2key1", new UObject(data2));
CLIENT1.setStateAuth(TOKEN2, "akey1", new UObject(data));
CLIENT2.setStateAuth(TOKEN1, "2akey1", new UObject(data2));
assertThat("get correct data back",
CLIENT1.getState("serv1", "key1", 0L)
.asClassInstance(Object.class),
is((Object) data));
assertThat("get correct data back",
CLIENT2.getState("serv1", "2key1", 0L)
.asClassInstance(Object.class),
is((Object) data2));
assertThat("get correct data back",
CLIENT1.getState(USER2, "akey1", 1L)
.asClassInstance(Object.class),
is((Object) data));
assertThat("get correct data back",
CLIENT2.getState(USER1, "2akey1", 1L)
.asClassInstance(Object.class),
is((Object) data2));
CLIENT1.setState("serv1", "key2", new UObject(data));
CLIENT1.setState("serv2", "key", new UObject(data));
CLIENT1.setStateAuth(TOKEN2, "akey2", new UObject(data));
CLIENT1.setStateAuth(TOKEN1, "akey", new UObject(data));
assertThat("get correct keys",
new HashSet<String>(CLIENT1.listState("serv1", 0L)),
is(new HashSet<String>(Arrays.asList("key1", "key2"))));
assertThat("get correct keys",
new HashSet<String>(CLIENT1.listState("serv2", 0L)),
is(new HashSet<String>(Arrays.asList("key"))));
assertThat("get correct keys",
new HashSet<String>(CLIENT1.listState(USER2, 1L)),
is(new HashSet<String>(Arrays.asList("akey1", "akey2"))));
assertThat("get correct keys",
new HashSet<String>(CLIENT1.listState(USER1, 1L)),
is(new HashSet<String>(Arrays.asList("akey"))));
assertThat("get correct services",
new HashSet<String>(CLIENT1.listStateServices(0L)),
is(new HashSet<String>(Arrays.asList("serv1", "serv2"))));
assertThat("get correct services",
new HashSet<String>(CLIENT1.listStateServices(1L)),
is(new HashSet<String>(Arrays.asList(USER1, USER2))));
CLIENT1.removeState("serv1", "key1");
CLIENT1.removeStateAuth(TOKEN2, "akey1");
try {
CLIENT1.getState("serv1", "key1", 0L);
fail("got deleted state");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("There is no key key1 for the unauthorized service serv1"));
}
try {
CLIENT1.getState(USER2, "akey1", 1L);
fail("got deleted state");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("There is no key akey1 for the authorized service " + USER2));
}
}
@Test
public void badToken() throws Exception {
try {
CLIENT1.setStateAuth(null, "key", new UObject("foo"));
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Service token cannot be null or the empty string"));
}
try {
CLIENT1.setStateAuth("", "key", new UObject("foo"));
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Service token cannot be null or the empty string"));
}
try {
CLIENT1.setStateAuth("boogabooga", "key", new UObject("foo"));
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Auth token is in the incorrect format, near 'boogabooga'"));
}
try {
CLIENT1.setStateAuth(TOKEN2 + "a", "key", new UObject("foo"));
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Service token is invalid"));
}
try {
CLIENT1.removeStateAuth(null, "key");
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Service token cannot be null or the empty string"));
}
try {
CLIENT1.removeStateAuth("", "key");
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Service token cannot be null or the empty string"));
}
try {
CLIENT1.removeStateAuth("boogabooga", "key");
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Auth token is in the incorrect format, near 'boogabooga'"));
}
try {
CLIENT1.removeStateAuth(TOKEN2 + "a", "key");
fail("set state w/ bad token");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is("Service token is invalid"));
}
}
private String[] getNearbyTimes() {
SimpleDateFormat dateform = getDateFormat();
SimpleDateFormat dateformutc =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
dateformutc.setTimeZone(TimeZone.getTimeZone("UTC"));
Date nf = new Date(new Date().getTime() + 10000);
Date np = new Date(new Date().getTime() - 10);
String[] nearfuture = new String[3];
nearfuture[0] = dateform.format(nf);
nearfuture[1] = dateformutc.format(nf);
nearfuture[2] = dateform.format(np);
return nearfuture;
}
@Test
public void createAndStartJob() throws Exception {
String[] nearfuture = getNearbyTimes();
String jobid = CLIENT1.createJob();
checkJob(jobid, "created",null, null, null, null,
null, null, null, null, null, null, null);
CLIENT1.startJob(jobid, TOKEN2, "new stat", "ne desc",
new InitProgress().withPtype("none"), null);
checkJob(jobid, "started", "new stat", USER2,
"ne desc", "none", null, null, null, 0L, 0L, null, null);
jobid = CLIENT1.createJob();
CLIENT1.startJob(jobid, TOKEN2, "new stat2", "ne desc2",
new InitProgress().withPtype("percent"), nearfuture[0]);
checkJob(jobid, "started", "new stat2", USER2,
"ne desc2", "percent", 0L, 100L, nearfuture[1], 0L, 0L, null,
null);
jobid = CLIENT1.createJob();
CLIENT1.startJob(jobid, TOKEN2, "new stat3", "ne desc3",
new InitProgress().withPtype("task").withMax(5L), null);
checkJob(jobid, "started", "new stat3", USER2,
"ne desc3", "task", 0L, 5L, null, 0L, 0L, null, null);
startJobBadArgs(null, TOKEN2, "s", "d", new InitProgress().withPtype("none"),
null, "id cannot be null or the empty string", true);
startJobBadArgs("", TOKEN2, "s", "d", new InitProgress().withPtype("none"),
null, "id cannot be null or the empty string", true);
startJobBadArgs("aaaaaaaaaaaaaaaaaaaa", TOKEN2, "s", "d",
new InitProgress().withPtype("none"),
null, "Job ID aaaaaaaaaaaaaaaaaaaa is not a legal ID", true);
jobid = CLIENT1.createJob();
startJobBadArgs(jobid, null, "s", "d", new InitProgress().withPtype("none"),
null, "Service token cannot be null or the empty string");
startJobBadArgs(jobid, "foo", "s", "d", new InitProgress().withPtype("none"),
null, "Auth token is in the incorrect format, near 'foo'");
startJobBadArgs(jobid, TOKEN2 + "a", "s", "d", new InitProgress().withPtype("none"),
null, "Service token is invalid");
startJobBadArgs(jobid, TOKEN2, "s", "d",
new InitProgress().withPtype("none"),
nearfuture[2], "The estimated completion date must be in the future", true);
startJobBadArgs(jobid, TOKEN2, "s", "d",
new InitProgress().withPtype("none"),
"2200-12-30T23:30:54-8000", "Unparseable date: \"2200-12-30T23:30:54-8000\"", true);
startJobBadArgs(jobid, TOKEN2, "s", "d",
new InitProgress().withPtype("none"),
"2200-12-30T123:30:54-0800", "Unparseable date: \"2200-12-30T123:30:54-0800\"", true);
startJobBadArgs(jobid, TOKEN2, "s", "d", null,
null, "InitProgress cannot be null");
InitProgress ip = new InitProgress().withPtype("none");
ip.setAdditionalProperties("foo", "bar");
startJobBadArgs(jobid, TOKEN2, "s", "d", ip,
null, "Unexpected arguments in InitProgress: foo");
startJobBadArgs(jobid, TOKEN2, "s", "d", new InitProgress().withPtype(null),
null, "Progress type cannot be null");
startJobBadArgs(jobid, TOKEN2, "s", "d", new InitProgress().withPtype("foo"),
null, "No such progress type: foo");
startJobBadArgs(jobid, TOKEN2, "s", "d", new InitProgress().withPtype("task")
.withMax(null),
null, "Max progress cannot be null for task based progress");
startJobBadArgs(jobid, TOKEN2, "s", "d", new InitProgress().withPtype("task")
.withMax(-1L),
null, "The maximum progress for the job must be > 0");
startJobBadArgs(jobid, TOKEN2, "s", "d", new InitProgress().withPtype("task")
.withMax(((long) Integer.MAX_VALUE) + 1),
null, "Max progress can be no greater than " + Integer.MAX_VALUE);
jobid = CLIENT1.createAndStartJob(TOKEN2, "cs stat", "cs desc",
new InitProgress().withPtype("none"), nearfuture[0]);
checkJob(jobid, "started", "cs stat", USER2,
"cs desc", "none", null, null, nearfuture[1], 0L, 0L, null,
null);
jobid = CLIENT1.createAndStartJob(TOKEN2, "cs stat2", "cs desc2",
new InitProgress().withPtype("percent"), null);
checkJob( jobid, "started", "cs stat2", USER2,
"cs desc2", "percent", 0L, 100L, null, 0L, 0L, null, null);
jobid = CLIENT1.createAndStartJob(TOKEN2, "cs stat3", "cs desc3",
new InitProgress().withPtype("task").withMax(5L), null);
checkJob(jobid, "started", "cs stat3", USER2,
"cs desc3", "task", 0L, 5L, null, 0L, 0L, null, null);
}
private void startJobBadArgs(String jobid, String token, String stat, String desc,
InitProgress prog, String estCompl, String exception) throws Exception {
startJobBadArgs(jobid, token, stat, desc, prog, estCompl, exception, false);
}
private void startJobBadArgs(String jobid, String token, String stat, String desc,
InitProgress prog, String estCompl, String exception, boolean badid)
throws Exception {
try {
CLIENT1.startJob(jobid, token, stat, desc, prog, estCompl);
fail("started job w/ bad args");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
if (badid) {
return;
}
try {
CLIENT1.createAndStartJob(token, stat, desc, prog, estCompl);
fail("started job w/ bad args");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
private SimpleDateFormat getDateFormat() {
SimpleDateFormat dateform =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
dateform.setLenient(false);
return dateform;
}
private void checkJob(String id, String stage, String status,
String service, String desc, String progtype, Long prog,
Long maxprog, String estCompl, Long complete, Long error,
String errormsg, Results results)
throws Exception {
SimpleDateFormat dateform = getDateFormat();
Tuple14<String, String, String, String, String, String,
Long, Long, String, String, Long, Long, String,
Results> ret = CLIENT1.getJobInfo(id);
assertThat("job id ok", ret.getE1(), is(id));
assertThat("job stage ok", ret.getE3(), is(stage));
if (ret.getE4() != null) {
dateform.parse(ret.getE4()); //should throw error if bad format
}
assertThat("job est compl ok", ret.getE10(), is(estCompl));
assertThat("job service ok", ret.getE2(), is(service));
assertThat("job desc ok", ret.getE13(), is(desc));
assertThat("job progtype ok", ret.getE9(), is(progtype));
assertThat("job prog ok", ret.getE7(), is(prog));
assertThat("job maxprog ok", ret.getE8(), is(maxprog));
assertThat("job status ok", ret.getE5(), is(status));
dateform.parse(ret.getE6()); //should throw error if bad format
assertThat("job complete ok", ret.getE11(), is(complete));
assertThat("job error ok", ret.getE12(), is(error));
checkResults(ret.getE14(), results);
Tuple5<String, String, Long, String, String> jobdesc =
CLIENT1.getJobDescription(id);
assertThat("job service ok", jobdesc.getE1(), is(service));
assertThat("job progtype ok", jobdesc.getE2(), is(progtype));
assertThat("job maxprog ok", jobdesc.getE3(), is(maxprog));
assertThat("job desc ok", jobdesc.getE4(), is(desc));
if (jobdesc.getE5() != null) {
dateform.parse(jobdesc.getE5()); //should throw error if bad format
}
Tuple7<String, String, String, Long, String, Long, Long>
jobstat = CLIENT1.getJobStatus(id);
dateform.parse(jobstat.getE1()); //should throw error if bad format
assertThat("job stage ok", jobstat.getE2(), is(stage));
assertThat("job status ok", jobstat.getE3(), is(status));
assertThat("job progress ok", jobstat.getE4(), is(prog));
assertThat("job est compl ok", jobstat.getE5(), is(estCompl));
assertThat("job complete ok", jobstat.getE6(), is(complete));
assertThat("job error ok", jobstat.getE7(), is(error));
checkResults(CLIENT1.getResults(id), results);
assertThat("job error msg ok", CLIENT1.getDetailedError(id),
is(errormsg));
}
private void checkResults(Results got, Results expected) throws Exception {
if (got == null & expected == null) {
return;
}
if (got == null ^ expected == null) {
fail("got null for results when expected real results or vice versa: "
+ got + " " + expected);
}
assertThat("shock ids same", got.getShocknodes(), is(expected.getShocknodes()));
assertThat("shock url same", got.getShockurl(), is(expected.getShockurl()));
assertThat("ws ids same", got.getWorkspaceids(), is(expected.getWorkspaceids()));
assertThat("ws url same", got.getWorkspaceurl(), is(expected.getWorkspaceurl()));
}
@Test
public void getJobInfoBadArgs() throws Exception {
testGetJobBadArgs(null, "id cannot be null or the empty string");
testGetJobBadArgs("", "id cannot be null or the empty string");
testGetJobBadArgs("foo", "Job ID foo is not a legal ID");
String jobid = CLIENT1.createJob();
if (jobid.charAt(0) == 'a') {
jobid = "b" + jobid.substring(1);
} else {
jobid = "a" + jobid.substring(1);
}
testGetJobBadArgs(jobid, String.format(
"There is no job %s for user kbasetest", jobid));
}
private void testGetJobBadArgs(String jobid, String exception)
throws Exception {
try {
CLIENT1.getJobInfo(jobid);
fail("got job with bad id");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
try {
CLIENT1.getJobDescription(jobid);
fail("got job with bad id");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
try {
CLIENT1.getJobStatus(jobid);
fail("got job with bad id");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
try {
CLIENT1.getResults(jobid);
fail("got job with bad id");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
@Test
public void updateJob() throws Exception {
String[] nearfuture = getNearbyTimes();
String jobid = CLIENT1.createAndStartJob(TOKEN2, "up stat", "up desc",
new InitProgress().withPtype("none"), null);
CLIENT1.updateJob(jobid, TOKEN2, "up stat2", null);
checkJob(jobid, "started", "up stat2", USER2,
"up desc", "none", null, null, null, 0L, 0L, null, null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "up stat3", 40L, null);
checkJob(jobid, "started", "up stat3", USER2,
"up desc", "none", null, null, null, 0L, 0L, null, null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "up stat3", null, nearfuture[0]);
checkJob(jobid, "started", "up stat3", USER2,
"up desc", "none", null, null, nearfuture[1], 0L, 0L, null,
null);
jobid = CLIENT1.createAndStartJob(TOKEN2, "up2 stat", "up2 desc",
new InitProgress().withPtype("percent"), null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "up2 stat2", 40L, null);
checkJob(jobid, "started", "up2 stat2", USER2,
"up2 desc", "percent", 40L, 100L, null, 0L, 0L, null, null);
CLIENT1.updateJob(jobid, TOKEN2, "up2 stat3", nearfuture[0]);
checkJob(jobid, "started", "up2 stat3", USER2,
"up2 desc", "percent", 40L, 100L, nearfuture[1], 0L, 0L, null,
null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "up2 stat4", 70L, null);
checkJob(jobid, "started", "up2 stat4", USER2,
"up2 desc", "percent", 100L, 100L, nearfuture[1], 0L, 0L, null,
null);
jobid = CLIENT1.createAndStartJob(TOKEN2, "up3 stat", "up3 desc",
new InitProgress().withPtype("task").withMax(42L), null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "up3 stat2", 30L, nearfuture[0]);
checkJob(jobid, "started", "up3 stat2", USER2,
"up3 desc", "task", 30L, 42L, nearfuture[1], 0L, 0L, null, null);
CLIENT1.updateJob(jobid, TOKEN2, "up3 stat3", null);
checkJob( jobid, "started", "up3 stat3", USER2,
"up3 desc", "task", 30L, 42L, nearfuture[1], 0L, 0L, null,
null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "up3 stat4", 15L, null);
checkJob(jobid, "started", "up3 stat4", USER2,
"up3 desc", "task", 42L, 42L, nearfuture[1], 0L, 0L, null,
null);
jobid = CLIENT1.createAndStartJob(TOKEN2, "up4 stat", "up4 desc",
new InitProgress().withPtype("none"), null);
updateJobBadArgs(jobid, TOKEN2, "up4 stat2", -1L, null, "progress cannot be negative");
updateJobBadArgs(jobid, TOKEN2, "up4 stat2",
(long) Integer.MAX_VALUE + 1, null,
"Max progress can be no greater than " + Integer.MAX_VALUE);
updateJobBadArgs(null, TOKEN2, "s", null,
"id cannot be null or the empty string");
updateJobBadArgs("", TOKEN2, "s", null,
"id cannot be null or the empty string");
updateJobBadArgs("aaaaaaaaaaaaaaaaaaaa", TOKEN2, "s", null,
"Job ID aaaaaaaaaaaaaaaaaaaa is not a legal ID");
updateJobBadArgs(jobid, TOKEN2, "s", nearfuture[2],
"The estimated completion date must be in the future");
updateJobBadArgs(jobid, TOKEN2, "s", "2200-12-30T23:30:54-8000",
"Unparseable date: \"2200-12-30T23:30:54-8000\"");
updateJobBadArgs(jobid, TOKEN2, "s", "2200-12-30T123:30:54-0800",
"Unparseable date: \"2200-12-30T123:30:54-0800\"");
updateJobBadArgs(jobid, null, "s", null,
"Service token cannot be null or the empty string");
updateJobBadArgs(jobid, "foo", "s", null,
"Auth token is in the incorrect format, near 'foo'");
updateJobBadArgs(jobid, TOKEN1, "s", null, String.format(
"There is no uncompleted job %s for user kbasetest started by service kbasetest",
jobid, USER1, USER1));
updateJobBadArgs(jobid, TOKEN2 + "a", "s", null,
"Service token is invalid");
}
private void updateJobBadArgs(String jobid, String token, String status,
Long prog, String estCompl, String exception) throws Exception {
try {
CLIENT1.updateJobProgress(jobid, token, status, prog, estCompl);
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
private void updateJobBadArgs(String jobid, String token, String status,
String estCompl, String exception) throws Exception {
try {
CLIENT1.updateJob(jobid, token, status, estCompl);
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
try {
CLIENT1.updateJobProgress(jobid, token, status, 1L, estCompl);
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
@Test
public void completeJob() throws Exception {
String[] nearfuture = getNearbyTimes();
String jobid = CLIENT1.createAndStartJob(TOKEN2, "c stat", "c desc",
new InitProgress().withPtype("none"), null);
CLIENT1.completeJob(jobid, TOKEN2, "c stat2", null, null);
checkJob(jobid, "complete", "c stat2", USER2, "c desc", "none", null,
null, null, 1L, 0L, null, null);
jobid = CLIENT1.createAndStartJob(TOKEN2, "c2 stat", "c2 desc",
new InitProgress().withPtype("percent"), null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "c2 stat2", 40L, null);
CLIENT1.completeJob(jobid, TOKEN2, "c2 stat3", "omg err",
new Results());
checkJob(jobid, "error", "c2 stat3", USER2, "c2 desc", "percent",
100L, 100L, null, 1L, 1L, "omg err", new Results());
jobid = CLIENT1.createAndStartJob(TOKEN2, "c3 stat", "c3 desc",
new InitProgress().withPtype("task").withMax(37L), null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "c3 stat2", 15L, nearfuture[0]);
Results res = new Results()
.withShocknodes(Arrays.asList("node1", "node3"))
.withShockurl("surl")
.withWorkspaceids(Arrays.asList("ws1", "ws3"))
.withWorkspaceurl("wurl");
CLIENT1.completeJob(jobid, TOKEN2, "c3 stat3", null, res);
checkJob(jobid, "complete", "c3 stat3", USER2, "c3 desc", "task",
37L, 37L, nearfuture[1], 1L, 0L, null, res);
testCompleteJob(null, TOKEN2, "s", null, null,
"id cannot be null or the empty string");
testCompleteJob("", TOKEN2, "s", null, null,
"id cannot be null or the empty string");
testCompleteJob("aaaaaaaaaaaaaaaaaaaa", TOKEN2, "s", null, null,
"Job ID aaaaaaaaaaaaaaaaaaaa is not a legal ID");
testCompleteJob(jobid, null, "s", null, null,
"Service token cannot be null or the empty string");
testCompleteJob(jobid, "foo", "s", null, null,
"Auth token is in the incorrect format, near 'foo'");
testCompleteJob(jobid, TOKEN2 + "w", "s", null, null,
"Service token is invalid");
testCompleteJob(jobid, TOKEN1, "s", null, null, String.format(
"There is no uncompleted job %s for user kbasetest started by service kbasetest",
jobid, USER1, USER1));
Results badres = new Results();
badres.setAdditionalProperties("foo", "bar");
testCompleteJob(jobid, TOKEN1, "s", null, badres,
"Unexpected arguments in Results: foo");
}
private void testCompleteJob(String jobid, String token, String status,
String error, Results res, String exception) throws Exception {
try {
CLIENT1.completeJob(jobid, token, status, error, res);
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
@Test
public void deleteJob() throws Exception {
InitProgress noprog = new InitProgress().withPtype("none");
String jobid = CLIENT1.createAndStartJob(TOKEN2, "d stat", "d desc", noprog, null);
CLIENT1.completeJob(jobid, TOKEN2, "d stat2", null, null);
CLIENT1.deleteJob(jobid);
testGetJobBadArgs(jobid, String.format("There is no job %s for user %s",
jobid, USER1));
jobid = CLIENT1.createAndStartJob(TOKEN2, "e stat", "e desc", noprog, null);
CLIENT1.completeJob(jobid, TOKEN2, "e stat2", "err", null);
CLIENT1.deleteJob(jobid);
testGetJobBadArgs(jobid, String.format("There is no job %s for user %s",
jobid, USER1));
jobid = CLIENT1.createAndStartJob(TOKEN2, "d2 stat", "d2 desc", noprog, null);
CLIENT1.forceDeleteJob(TOKEN2, jobid);
testGetJobBadArgs(jobid, String.format("There is no job %s for user %s",
jobid, USER1));
jobid = CLIENT1.createAndStartJob(TOKEN2, "d3 stat", "d3 desc", noprog, null);
CLIENT1.updateJobProgress(jobid, TOKEN2, "d3 stat2", 3L, null);
CLIENT1.forceDeleteJob(TOKEN2, jobid);
testGetJobBadArgs(jobid, String.format("There is no job %s for user %s",
jobid, USER1));
jobid = CLIENT1.createAndStartJob(TOKEN2, "d4 stat", "d4 desc", noprog, null);
CLIENT1.completeJob(jobid, TOKEN2, "d4 stat2", null, null);
CLIENT1.forceDeleteJob(TOKEN2, jobid);
testGetJobBadArgs(jobid, String.format("There is no job %s for user %s",
jobid, USER1));
jobid = CLIENT1.createAndStartJob(TOKEN2, "d5 stat", "d5 desc", noprog, null);
CLIENT1.completeJob(jobid, TOKEN2, "d5 stat2", "err", null);
CLIENT1.forceDeleteJob(TOKEN2, jobid);
testGetJobBadArgs(jobid, String.format("There is no job %s for user %s",
jobid, USER1));
jobid = CLIENT1.createJob();
failToDeleteJob(jobid, String.format(
"There is no completed job %s for user %s", jobid, USER1));
failToDeleteJob(jobid, TOKEN2, String.format(
"There is no job %s for user %s and service %s",
jobid, USER1, USER2));
CLIENT1.startJob(jobid, TOKEN2, "d6 stat", "d6 desc", noprog, null);
failToDeleteJob(jobid, String.format(
"There is no completed job %s for user %s", jobid, USER1));
CLIENT1.updateJobProgress(jobid, TOKEN2, "d6 stat2", 3L, null);
failToDeleteJob(jobid, String.format(
"There is no completed job %s for user %s", jobid, USER1));
failToDeleteJob(null, "id cannot be null or the empty string");
failToDeleteJob("", "id cannot be null or the empty string");
failToDeleteJob("aaaaaaaaaaaaaaaaaaaa",
"Job ID aaaaaaaaaaaaaaaaaaaa is not a legal ID");
failToDeleteJob(null, TOKEN2,
"id cannot be null or the empty string");
failToDeleteJob("", TOKEN2,
"id cannot be null or the empty string");
failToDeleteJob("aaaaaaaaaaaaaaaaaaaa", TOKEN2,
"Job ID aaaaaaaaaaaaaaaaaaaa is not a legal ID");
failToDeleteJob(jobid, null,
"Service token cannot be null or the empty string", true);
failToDeleteJob(jobid, "foo",
"Auth token is in the incorrect format, near 'foo'");
failToDeleteJob(jobid, TOKEN2 + 'w',
"Service token is invalid");
failToDeleteJob(jobid, TOKEN1, String.format(
"There is no job %s for user kbasetest and service kbasetest",
jobid, USER1, USER1));
}
private void failToDeleteJob(String jobid, String exception)
throws Exception {
failToDeleteJob(jobid, null, exception, false);
}
private void failToDeleteJob(String jobid, String token, String exception)
throws Exception {
failToDeleteJob(jobid, token, exception, false);
}
private void failToDeleteJob(String jobid, String token, String exception,
boolean usenulltoken)
throws Exception {
try {
if (!usenulltoken && token == null) {
CLIENT1.deleteJob(jobid);
} else {
CLIENT1.forceDeleteJob(token, jobid);
}
fail("deleted job with bad args");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
@Test
public void listServices() throws Exception {
checkListServices(CLIENT2, new HashSet<String>());
InitProgress noprog = new InitProgress().withPtype("none");
CLIENT1.createAndStartJob(TOKEN2, "ls stat", "ls desc", noprog, null);
checkListServices(CLIENT1, new HashSet<String>(Arrays.asList(USER2)));
String jobid = CLIENT1.createAndStartJob(TOKEN1, "ls2 stat",
"ls2 desc", noprog, null);
checkListServices(CLIENT1, new HashSet<String>(Arrays.asList(USER1, USER2)));
CLIENT1.forceDeleteJob(TOKEN1, jobid);
}
private void checkListServices(UserAndJobStateClient client,
Set<String> service) throws Exception {
assertThat("got correct services", new HashSet<String>(client.listJobServices()),
is(service));
}
@Test
public void listJobs() throws Exception {
//NOTE: all jobs must be deleted from CLIENT2 or other tests may fail
InitProgress noprog = new InitProgress().withPtype("none");
Set<FakeJob> empty = new HashSet<FakeJob>();
checkListJobs(USER1, null, empty);
checkListJobs(USER1, "", empty);
checkListJobs(USER1, "R", empty);
checkListJobs(USER1, "C", empty);
checkListJobs(USER1, "E", empty);
checkListJobs(USER1, "RC", empty);
checkListJobs(USER1, "CE", empty);
checkListJobs(USER1, "RE", empty);
checkListJobs(USER1, "RCE", empty);
checkListJobs(USER1, "RCEX", empty);
String jobid = CLIENT2.createJob();
checkListJobs(USER1, null, empty);
checkListJobs(USER1, "", empty);
checkListJobs(USER1, "R", empty);
checkListJobs(USER1, "C", empty);
checkListJobs(USER1, "E", empty);
checkListJobs(USER1, "RC", empty);
checkListJobs(USER1, "CE", empty);
checkListJobs(USER1, "RE", empty);
checkListJobs(USER1, "RCE", empty);
checkListJobs(USER1, "RXCE", empty);
CLIENT2.startJob(jobid, TOKEN1, "lj stat", "lj desc", noprog, null);
FakeJob started = new FakeJob(jobid, null, USER1, "started", null, "lj desc",
"none", null, null, "lj stat", false, false, null, null);
Set<FakeJob> setstarted = new HashSet<FakeJob>(Arrays.asList(started));
checkListJobs(USER1, null, setstarted);
checkListJobs(USER1, "", setstarted);
checkListJobs(USER1, "R", setstarted);
checkListJobs(USER1, "C", empty);
checkListJobs(USER1, "E", empty);
checkListJobs(USER1, "RC", setstarted);
checkListJobs(USER1, "CE", empty);
checkListJobs(USER1, "RE", setstarted);
checkListJobs(USER1, "RCE", setstarted);
checkListJobs(USER1, "!RCE", setstarted);
jobid = CLIENT2.createAndStartJob(TOKEN1, "lj2 stat", "lj2 desc",
new InitProgress().withPtype("percent"), null);
CLIENT2.updateJobProgress(jobid, TOKEN1, "lj2 stat2", 42L, null);
FakeJob started2 = new FakeJob(jobid, null, USER1, "started", null,
"lj2 desc", "percent", 42, 100, "lj2 stat2", false, false, null,
null);
setstarted.add(started2);
checkListJobs(USER1, null, setstarted);
checkListJobs(USER1, "", setstarted);
checkListJobs(USER1, "R", setstarted);
checkListJobs(USER1, "C", empty);
checkListJobs(USER1, "E", empty);
checkListJobs(USER1, "RC", setstarted);
checkListJobs(USER1, "CE", empty);
checkListJobs(USER1, "RE", setstarted);
checkListJobs(USER1, "RCE", setstarted);
checkListJobs(USER1, "RCwE", setstarted);
CLIENT2.completeJob(jobid, TOKEN1, "lj2 stat3", null,
new Results().withShocknodes(Arrays.asList("node1", "node2")));
setstarted.remove(started2);
started2 = null;
Map<String, Object> res = new HashMap<String, Object>();
res.put("shocknodes", Arrays.asList("node1", "node2"));
res.put("shockurl", null);
res.put("workspaceids", null);
res.put("workspaceurl", null);
FakeJob complete = new FakeJob(jobid, null, USER1, "complete", null,
"lj2 desc", "percent", 100, 100, "lj2 stat3", true, false,
null, res);
Set<FakeJob> setcomplete = new HashSet<FakeJob>(Arrays.asList(complete));
Set<FakeJob> setstartcomp = new HashSet<FakeJob>();
setstartcomp.addAll(setstarted);
setstartcomp.addAll(setcomplete);
checkListJobs(USER1, null, setstartcomp);
checkListJobs(USER1, "", setstartcomp);
checkListJobs(USER1, "R", setstarted);
checkListJobs(USER1, "C", setcomplete);
checkListJobs(USER1, "C0", setcomplete);
checkListJobs(USER1, "E", empty);
checkListJobs(USER1, "RC", setstartcomp);
checkListJobs(USER1, "CE", setcomplete);
checkListJobs(USER1, "RE", setstarted);
checkListJobs(USER1, "RCE", setstartcomp);
jobid = CLIENT2.createAndStartJob(TOKEN1, "lj3 stat", "lj3 desc",
new InitProgress().withPtype("task").withMax(55L), null);
CLIENT2.updateJobProgress(jobid, TOKEN1, "lj3 stat2", 40L, null);
started2 = new FakeJob(jobid, null, USER1, "started", null,
"lj3 desc", "task", 40, 55, "lj3 stat2", false, false, null,
null);
setstarted.add(started2);
setstartcomp.add(started2);
checkListJobs(USER1, null, setstartcomp);
checkListJobs(USER1, "", setstartcomp);
checkListJobs(USER1, "R", setstarted);
checkListJobs(USER1, "C", setcomplete);
checkListJobs(USER1, "E", empty);
checkListJobs(USER1, "RC", setstartcomp);
checkListJobs(USER1, "CE", setcomplete);
checkListJobs(USER1, "C#E", setcomplete);
checkListJobs(USER1, "RE", setstarted);
checkListJobs(USER1, "RCE", setstartcomp);
CLIENT2.completeJob(jobid, TOKEN1, "lj3 stat3", "omg err",
new Results().withWorkspaceids(Arrays.asList("wss1", "wss2")));
setstarted.remove(started2);
setstartcomp.remove(started2);
started2 = null;
Map<String, Object> res2 = new HashMap<String, Object>();
res2.put("shocknodes", null);
res2.put("shockurl", null);
res2.put("workspaceids", Arrays.asList("wss1", "wss2"));
res2.put("workspaceurl", null);
FakeJob error = new FakeJob(jobid, null, USER1, "error", null,
"lj3 desc", "task", 55, 55, "lj3 stat3", true, true, null,
res2);
Set<FakeJob> seterr = new HashSet<FakeJob>(Arrays.asList(error));
Set<FakeJob> all = new HashSet<FakeJob>(
Arrays.asList(started, complete, error));
checkListJobs(USER1, null, all);
checkListJobs(USER1, "", all);
checkListJobs(USER1, "x", all);
checkListJobs(USER1, "R", setstarted);
checkListJobs(USER1, "C", setcomplete);
checkListJobs(USER1, "E", seterr);
checkListJobs(USER1, "RC", setstartcomp);
checkListJobs(USER1, "CE", new HashSet<FakeJob>(
Arrays.asList(complete, error)));
checkListJobs(USER1, "RE", new HashSet<FakeJob>(
Arrays.asList(started, error)));
checkListJobs(USER1, "RCE", all);
CLIENT2.forceDeleteJob(TOKEN1, started.getID());
all.remove(started);
checkListJobs(USER1, null, all);
checkListJobs(USER1, "", all);
checkListJobs(USER1, "goodness this is odd input", all);
checkListJobs(USER1, "R", empty);
checkListJobs(USER1, "C", setcomplete);
checkListJobs(USER1, "E", seterr);
checkListJobs(USER1, "cE", seterr);
checkListJobs(USER1, "RC", setcomplete);
checkListJobs(USER1, "CE", new HashSet<FakeJob>(
Arrays.asList(complete, error)));
checkListJobs(USER1, "RE", seterr);
checkListJobs(USER1, "RCE", all);
CLIENT2.deleteJob(complete.getID());
checkListJobs(USER1, null, seterr);
checkListJobs(USER1, "", seterr);
checkListJobs(USER1, "R", empty);
checkListJobs(USER1, "C", empty);
checkListJobs(USER1, "E", seterr);
checkListJobs(USER1, "e", seterr);
checkListJobs(USER1, "RC", empty);
checkListJobs(USER1, "CE", seterr);
checkListJobs(USER1, "RE", seterr);
checkListJobs(USER1, "RCE", seterr);
CLIENT2.deleteJob(error.getID());
checkListJobs(USER1, null, empty);
checkListJobs(USER1, "", empty);
checkListJobs(USER1, "R", empty);
checkListJobs(USER1, "C", empty);
checkListJobs(USER1, "E", empty);
checkListJobs(USER1, "RC", empty);
checkListJobs(USER1, "CE", empty);
checkListJobs(USER1, "RE", empty);
checkListJobs(USER1, "RCE", empty);
testListJobsWithBadArgs(null,
"service cannot be null or the empty string");
testListJobsWithBadArgs("",
"service cannot be null or the empty string");
testListJobsWithBadArgs("abcdefghijklmnopqrst" + "abcdefghijklmnopqrst"
+ "abcdefghijklmnopqrst" + "abcdefghijklmnopqrst" +
"abcdefghijklmnopqrst" + "a",
"service exceeds the maximum length of 100");
}
private void checkListJobs(String service, String filter,
Set<FakeJob> expected) throws Exception {
Set<FakeJob> got = new HashSet<FakeJob>();
for (Tuple14<String, String, String, String, String, String, Long,
Long, String, String, Long, Long, String, Results> ji:
CLIENT2.listJobs(Arrays.asList(service), filter)) {
got.add(new FakeJob(ji));
}
assertThat("got the correct jobs", got, is(expected));
}
public void testListJobsWithBadArgs(String service, String exception)
throws Exception{
try {
CLIENT2.listJobs(Arrays.asList(service), "RCE");
fail("list jobs worked w/ bad service");
} catch (ServerException se) {
assertThat("correct exception", se.getLocalizedMessage(),
is(exception));
}
}
}
|
package io.linksoft.schedules.data;
import java.util.ArrayList;
import java.util.Date;
import io.linksoft.schedules.R;
public class Schedule {
private String code;
private boolean enabled, synced;
private Date syncTime;
private ArrayList<Class> classes = new ArrayList<>();
public Schedule(String code, boolean enabled, Date syncTime) {
this.code = code;
this.enabled = enabled;
this.syncTime = syncTime;
synced = false;
}
public Schedule(String code, boolean enabled) {
this(code, enabled, new Date(0));
}
public int getToggleIcon() {
return enabled ? R.drawable.ic_toggle_active : R.drawable.ic_toggle_inactive;
}
public String getCode() {
return code;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isSynced() {
return synced;
}
public void setSynced(boolean synced) {
this.synced = synced;
}
public Date getSyncTime() {
return syncTime;
}
public void setSyncTime(Date syncTime) {
this.syncTime = syncTime;
}
public ArrayList<Class> getClasses() {
return classes;
}
public void setClasses(ArrayList<Class> classes) {
this.classes = classes;
}
@Override
public String toString() {
return String.format("%s, classes: %s, enabled: %b, synced: %b", code, classes.size(), enabled, synced);
}
}
|
package ru.pravvich.start;
import ru.pravvich.models.*;
/**
* @since Pavel Ravvich
* @since 04.11.2016
* @see #add() addition task
* @see #updateItem() replace task on new
* @see #findByHeader()
* @see #findById()
* @see #deleteTask()
* @see #addCommit()
* @see #editionCommit()
* @see #viewAllTasks()
* @see #addDescription()
*/
public class StartUI {
private Input input;
private Tracker tracker = new Tracker();
// only for tests!
public void setInput(Input input) {
this.input = input;
}
public Tracker getTracker() {
return this.tracker;
}
public StartUI(Input input) {
this.input = input;
}
public void addDescription() {
int id = this.input.askInt("Enter Id need task:");
String description = this.input.ask("Enter description");
this.tracker.addDescription(id, description);
System.out.println(this.tracker.getMessage());
System.out.println("=========================================================");
}
public void editionCommit() {
String oldCommit = this.input.ask("Enter old commit for edit");
String newCommit = this.input.ask("Enter new commit");
this.tracker.editionCommit(oldCommit, newCommit);
System.out.println(this.tracker.getMessage());
System.out.println("=========================================================");
}
public void addCommit() {
int id = this.input.askInt("Enter ID task for commit.");
String commit = this.input.ask("Enter commit for this task.");
this.tracker.addCommit(this.tracker.findById(id), commit);
System.out.println(this.tracker.getMessage());
System.out.println("=========================================================");
}
// init new task
public void add() {
String header = this.input.ask("Please enter the task name");
this.tracker.add(new Task(header));
System.out.println(this.tracker.getMessage());
System.out.println("=========================================================");
}
public void updateItem() {
String header = this.input.ask("Enter new name for task.");
int id = this.input.askInt("Enter task ID for replace");
Item item = new Item(header, id);
this.tracker.updateItem(item);
System.out.println(tracker.getMessage());
System.out.println("=========================================================");
}
public void findById () {
int id = this.input.askInt("Enter ID number");
this.tracker.findById(id);
System.out.println(tracker.getMessage());
System.out.println("=========================================================");
}
public void findByHeader() {
String header = this.input.ask("Enter task name for search.");
this.tracker.findByHeader(header);
System.out.println(tracker.getMessage());
System.out.println("=========================================================");
}
public void deleteTask() {
String header = this.input.ask("Please enter the task name for delete");
int id = this.tracker.findByHeader(header).getId();
Item itemForDelete = this.tracker.findById(id);
this.tracker.delete(itemForDelete);
System.out.println(tracker.getMessage());
System.out.println("=========================================================");
}
public void viewAllTasks() {
String answer = this.input.ask(String.format("%s\n%s","View all tasks : view -a",
"View all tasks with revers filter : view -f"));
if (answer.equals("view -a")) {
Item[] print = this.tracker.getPrintArray();
System.out.println(this.tracker.getMessage());
for (Item item : print) {
System.out.println(String.format("%s %s %s",item.getHeader(),"ID:",item.getId()));
}
System.out.println("=========================================================");
} else if (answer.equals("view -f")) {
Item[] print = this.tracker.getArrPrintFilter();
System.out.println(this.tracker.getMessage());
for (Item item : print) {
System.out.println(String.format("%s %s %s",item.getHeader(),"ID:",item.getId()));
}
System.out.println("=========================================================");
} else {
System.out.println("Error: command not found");
System.out.println("=========================================================");
}
}
public void startApp() {
viewMenu();
while (this.start) {
String answer = this.input.ask("Enter the command: ");
if (answer.equals("n -t")) {
add();
} else if (answer.equals("v")) {
viewAllTasks();
} else if (answer.equals("n -c")) {
addCommit();
} else if (answer.equals("e -c")) {
editionCommit();
} else if (answer.equals("e -t")) {
updateItem();
} else if (answer.equals("f -id")) {
findById();
} else if (answer.equals("f -h")) {
findByHeader();
} else if (answer.equals("d -t")) {
deleteTask();
} else if (answer.equals("n -d")) {
addDescription();
}else if (answer.equals("q")) {
this.start = false;
} else if (answer.equals("help")) {
viewMenu();
} else {
System.out.println("command not found");
}
}
}
private boolean start = true;
public void viewMenu() {
System.out.println("It supports the possibility: ");
System.out.printf("%-40s%-1s%n","1. Add task:","n -t");
System.out.printf("%-40s%-1s%n","2. View all tasks:","v");
System.out.printf("%-40s%-1s%n","3. Add comment:","n -c");
System.out.printf("%-40s%-1s%n","4. Edition comment:","e -c");
System.out.printf("%-40s%-1s%n","5. Edition task:","e -t");
System.out.printf("%-40s%-1s%n","6. Find by ID:","f -id");
System.out.printf("%-40s%-1s%n","7. Find by header:","f -h");
System.out.printf("%-40s%-1s%n","8. Add description:","n -d");
System.out.printf("%-40s%-1s%n","9. Delete task:","d -t");
System.out.printf("%-40s%-1s%n","10. Quit:","q");
}
public static void main(String[] args) {
System.out.println("Welcome to task manager! \nFor view manual enter: help");
Input input = new ConsoleInput();
StartUI startUI = new StartUI(input);
startUI.startApp();
}
}
|
package ru.job4j.map;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* Class User.
*
* @author Ayuzyak
* @since 20.06.2017
* @version 1.0
*/
public class User {
/**
* User name.
*/
private String name;
/**
* Number of children.
*/
private int children;
/**
* Date of birthday.
*/
private Calendar birthday;
/**
* User constructor.
* @param name - User name.
* @param children - number of children.
* @param birthday - date of birthday.
*/
public User(String name, int children, Calendar birthday) {
this.name = name;
this.children = children;
this.birthday = birthday;
}
/**
* Overriding method equals().
* @param o - object for compare.
* @return true if objects are same.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return children == user.children
&& Objects.equals(name, user.name)
&& Objects.equals(birthday, user.birthday);
}
/**
* Return hash code value for object.
* @return int value.
*/
@Override
public int hashCode() {
return Objects.hash(name, children, birthday);
}
/**
* Main method.
* @param args is empty.
*/
public static void main(String[] args) {
Calendar firstBirth = new GregorianCalendar(1900, 0, 10);
Calendar secondBirth = new GregorianCalendar(1900, 0, 10);
User firstUser = new User("Andr", 2, firstBirth);
User secondUser = new User("Andr", 2, secondBirth);
Map<User, Object> map = new HashMap<>();
map.put(firstUser, null);
map.put(secondUser, null);
System.out.println(map);
}
}
|
package org.eclipse.birt.report.engine.emitter.excel;
import java.math.RoundingMode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NumberFormatValue
{
private int fractionDigits;
private String format;
private RoundingMode roundingMode;
private static Pattern pattern = Pattern.compile( "^(.*?)\\{RoundingMode=(.*?)\\}",
Pattern.CASE_INSENSITIVE );
private NumberFormatValue( )
{
}
public static NumberFormatValue getInstance( String numberFormat )
{
if ( numberFormat != null )
{
NumberFormatValue value = new NumberFormatValue( );
Matcher matcher = pattern.matcher( numberFormat );
if ( matcher.matches( ) )
{
String f = matcher.group( 1 );
if ( f != null && f.length( ) > 0 )
{
value.format = f;
int index = f.lastIndexOf( '.' );
if ( index > 0 )
{
int end = f.length( );
for ( int i = index + 1; i < f.length( ); i++ )
{
if ( f.charAt( i ) != '0' )
{
end = i;
break;
}
}
value.fractionDigits = end - 1 - index;
}
char lastChar = f.charAt( f.length( ) - 1 );
switch ( lastChar )
{
case '%' :
value.fractionDigits += 2;
break;
case '‰' :
value.fractionDigits += 3;
break;
case '‱' :
value.fractionDigits += 4;
break;
}
}
String m = matcher.group( 2 );
if ( m != null )
{
value.roundingMode = RoundingMode.valueOf( m );
}
}
else
{
value.format = numberFormat;
}
return value;
}
return null;
}
public int getFractionDigits( )
{
return fractionDigits;
}
public void setFractionDigits( int fractionDigits )
{
this.fractionDigits = fractionDigits;
}
public String getFormat( )
{
return format;
}
public void setFormat( String format )
{
this.format = format;
}
public RoundingMode getRoundingMode( )
{
return roundingMode;
}
public void setRoundingMode( RoundingMode roundingMode )
{
this.roundingMode = roundingMode;
}
public int hashCode()
{
return ( format == null ? 0 : format.hashCode( ) )
+ ( roundingMode == null ? 0 : roundingMode.hashCode( ) );
}
public boolean equals( Object o )
{
NumberFormatValue v = (NumberFormatValue) o;
boolean formatEqual = true;
boolean roundingModeEqual = true;
if ( v == null )
{
return false;
}
if ( format != null )
{
formatEqual = format.equals( v.format );
}
else if ( v.format != null )
{
return false;
}
if ( roundingMode != null )
{
roundingModeEqual = roundingMode.equals( v.roundingMode );
}
else if ( v.roundingMode != null )
{
return false;
}
return formatEqual && roundingModeEqual;
}
}
|
package jp.ddo.masm11.cplayer;
import android.app.Service;
import android.media.MediaPlayer;
import android.net.Uri;
import android.content.Intent;
import android.os.IBinder;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class PlayerService extends Service {
private String topDir;
private String playingPath, nextPath;
private MediaPlayer curPlayer, nextPlayer;
@Override
public void onCreate() {
Log.init(getExternalCacheDir());
topDir = "/sdcard/Music";
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent != null ? intent.getAction() : null;
if (action != null) {
String path;
switch (action) {
case "PLAY":
path = intent.getStringExtra("path");
if (path == null)
break;
play(path);
enqueueNext();
break;
case "SET_TOPDIR":
path = intent.getStringExtra("path");
if (path == null)
break;
setTopDir(path);
break;
}
}
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void play(String path) {
Log.i("path=%s", path);
playingPath = path;
try {
if (curPlayer != null) {
curPlayer.release();
curPlayer = null;
}
} catch (Exception e) {
Log.e(e, "exception");
}
try {
if (nextPlayer != null) {
nextPlayer.release();
nextPlayer = null;
}
} catch (Exception e) {
Log.e(e, "exception");
}
Object[] ret = createMediaPlayer(playingPath);
if (ret == null) {
Log.w("No audio file found.");
return;
}
curPlayer = (MediaPlayer) ret[0];
playingPath = (String) ret[1];
try {
curPlayer.start();
} catch (Exception e) {
Log.e(e, "exception");
}
}
private void enqueueNext() {
try {
if (nextPlayer != null) {
nextPlayer.release();
nextPlayer = null;
}
} catch (Exception e) {
Log.e(e, "exception");
}
Object[] ret = createMediaPlayer(selectNext(playingPath));
if (ret == null) {
Log.w("No audio file found.");
return;
}
nextPlayer = (MediaPlayer) ret[0];
nextPath = (String) ret[1];
try {
curPlayer.setNextMediaPlayer(nextPlayer);
} catch (Exception e) {
Log.e(e, "exception");
}
}
private Object[] createMediaPlayer(String path) {
HashSet<String> tested = new HashSet<>();
MediaPlayer player = null;
while (true) {
try {
if (path == null || tested.contains(path)) {
return null;
}
tested.add(path);
player = MediaPlayer.create(this, Uri.parse("file://" + path));
if (player == null) {
Log.w("MediaPlayer.create() failed: %s", path);
path = selectNext(path);
continue;
}
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
playingPath = nextPath;
curPlayer = nextPlayer;
mp.release();
nextPath = null;
nextPlayer = null;
enqueueNext();
}
});
return new Object[] { player, path };
} catch (Exception e) {
Log.e(e, "exception");
}
return null;
}
}
private String selectNext(String nextOf) {
// fixme:
ArrayList<String> list = new ArrayList<>();
scan(new File(topDir), list);
Collections.sort(list);
for (String path: list) {
if (path.compareTo(nextOf) > 0)
return path;
}
try {
// loop.
return list.get(0);
} catch (IndexOutOfBoundsException e) {
return null;
}
}
private void scan(File dir, ArrayList<String> scanResult) {
for (File file: dir.listFiles()) {
if (file.isDirectory())
scan(file, scanResult);
else
scanResult.add(file.getAbsolutePath());
}
}
private void setTopDir(String path) {
topDir = path;
// enqueue
if (curPlayer != null)
enqueueNext();
}
}
|
package org.eclipse.persistence.testing.tests.jpa.timestamptz;
import java.util.Calendar;
import java.util.TimeZone;
import javax.persistence.EntityManager;
import junit.framework.*;
import org.eclipse.persistence.testing.framework.junit.JUnitTestCase;
import org.eclipse.persistence.testing.models.jpa.timestamptz.*;
public class TimeStampTZJUnitTestSuite extends JUnitTestCase {
public TimeStampTZJUnitTestSuite() {
super();
}
public TimeStampTZJUnitTestSuite(String name) {
super(name);
}
public static Test suite() {
TestSuite suite = new TestSuite();
suite.setName("TimeStampTZJUnitTestSuite");
suite.addTest(new TimeStampTZJUnitTestSuite("testSetup"));
suite.addTest(new TimeStampTZJUnitTestSuite("testNoZone"));
suite.addTest(new TimeStampTZJUnitTestSuite("testTimeStampTZ"));
suite.addTest(new TimeStampTZJUnitTestSuite("testTimeStampLTZ"));
suite.addTest(new TimeStampTZJUnitTestSuite("testTimeStampTZDST"));
return suite;
}
public void testSetup() {
new TimestampTableCreator().replaceTables(JUnitTestCase.getServerSession());
}
/* Test TimeStampTZ with no zone set */
public void testNoZone() {
int year = 2000, month = 1, date = 10, hour = 11, minute = 21, second = 31;
Integer tsId = null;
java.util.Calendar originalCal = null, dbCal = null;
EntityManager em = createEntityManager();
beginTransaction(em);
try {
TStamp ts = new TStamp();
originalCal = java.util.Calendar.getInstance();
originalCal.set(year, month, date, hour, minute, second);
ts.setNoZone(originalCal);
em.persist(ts);
em.flush();
tsId = ts.getId();
commitTransaction(em);
} catch (Exception e) {
e.printStackTrace();
rollbackTransaction(em);
} finally {
clearCache();
dbCal = em.find(TStamp.class, tsId).getNoZone();
closeEntityManager(em);
}
assertEquals("The date retrived from db is not the one set to the child ", dbCal, originalCal);
assertTrue("The year is not macth", year == dbCal.get(java.util.Calendar.YEAR));
assertTrue("The month is not match", month == dbCal.get(java.util.Calendar.MONTH));
assertTrue("The date is not match", date == dbCal.get(java.util.Calendar.DATE));
assertTrue("The hour is not match", hour == dbCal.get(java.util.Calendar.HOUR));
assertTrue("The minute is not match", minute == dbCal.get(java.util.Calendar.MINUTE));
assertTrue("The second is not match", second == dbCal.get(java.util.Calendar.SECOND));
}
/* Test TimeStampTZ with time zone set with midnight time*/
public void testTimeStampTZ() {
int year = 2000, month = 1, date = 10, hour = 0, minute = 0, second = 0;
Integer tsId = null;
Calendar originalCal = null, dbCal = null;
String zoneId = "Europe/London";
EntityManager em = createEntityManager();
beginTransaction(em);
try {
TStamp ts = new TStamp();
originalCal = Calendar.getInstance(TimeZone.getTimeZone(zoneId));
originalCal.set(Calendar.AM_PM, Calendar.AM);
originalCal.set(year, month, date, 0, 0, 0);
originalCal.set(Calendar.MILLISECOND, 0);
ts.setTsTZ(originalCal);
em.persist(ts);
em.flush();
tsId = ts.getId();
commitTransaction(em);
} catch (Exception e) {
e.printStackTrace();
rollbackTransaction(em);
} finally {
clearCache();
dbCal = em.find(TStamp.class, tsId).getTsTZ();
closeEntityManager(em);
}
assertEquals("The timezone id is not the one set to the field", dbCal.getTimeZone().getID(), zoneId);
assertTrue("The AM is not match", Calendar.AM == dbCal.get(java.util.Calendar.AM_PM));
assertTrue("The year is not macth", year == dbCal.get(java.util.Calendar.YEAR));
assertTrue("The month is not match", month == dbCal.get(java.util.Calendar.MONTH));
assertTrue("The date is not match", date == dbCal.get(java.util.Calendar.DATE));
assertTrue("The hour is not match", hour == dbCal.get(java.util.Calendar.HOUR));
assertTrue("The minute is not match", minute == dbCal.get(java.util.Calendar.MINUTE));
assertTrue("The second is not match", second == dbCal.get(java.util.Calendar.SECOND));
}
/* Test TimeStampLTZ */
public void testTimeStampLTZ() {
int year = 2000, month = 3, date = 21, hour = 11, minute = 45, second = 50;
Integer tsId = null;
Calendar originalCal = null, dbCal = null;
String zoneId = "America/Los_Angeles";
EntityManager em = createEntityManager();
beginTransaction(em);
try {
TStamp ts = new TStamp();
originalCal = Calendar.getInstance(TimeZone.getTimeZone(zoneId));
originalCal.set(Calendar.AM_PM, Calendar.AM);
originalCal.set(year, month, date, hour, minute, second);
originalCal.set(Calendar.MILLISECOND, 0);
ts.setTsLTZ(originalCal);
em.persist(ts);
em.flush();
tsId = ts.getId();
commitTransaction(em);
} catch (Exception e) {
e.printStackTrace();
rollbackTransaction(em);
} finally {
clearCache();
dbCal = em.find(TStamp.class, tsId).getTsLTZ();
closeEntityManager(em);
}
assertTrue("The year is not macth", year == dbCal.get(java.util.Calendar.YEAR));
assertTrue("The month is not match", month == dbCal.get(java.util.Calendar.MONTH));
assertTrue("The date is not match", date == dbCal.get(java.util.Calendar.DATE));
int hourDiffFromDB = dbCal.get(Calendar.HOUR_OF_DAY) - originalCal.get(Calendar.HOUR_OF_DAY);
int hourDiffFromZone = (dbCal.get(Calendar.ZONE_OFFSET) - originalCal.get(Calendar.ZONE_OFFSET))/ 3600000;
assertTrue("The hour is not match", hourDiffFromDB == hourDiffFromZone);
assertTrue("The minute is not match", minute == dbCal.get(java.util.Calendar.MINUTE));
assertTrue("The second is not match", second == dbCal.get(java.util.Calendar.SECOND));
}
/* Test TimeStampTZ with daylightsaving time*/
public void testTimeStampTZDST() {
int year = 2008, month = 2, date = 10, hour = 11, minute = 0, second = 0;
Integer tsId = null;
Calendar originalCal = null, dbCal = null;
String zoneIdRemote = "Europe/London";
EntityManager em = createEntityManager();
beginTransaction(em);
try {
TStamp ts = new TStamp();
originalCal = Calendar.getInstance(TimeZone.getTimeZone(zoneIdRemote));
originalCal.set(Calendar.AM_PM, Calendar.AM);
originalCal.set(year, month, date, hour, minute, second);
originalCal.set(Calendar.MILLISECOND, 0);
ts.setTsLTZ(originalCal);
em.persist(ts);
em.flush();
tsId = ts.getId();
commitTransaction(em);
} catch (Exception e) {
e.printStackTrace();
rollbackTransaction(em);
} finally {
clearCache();
closeEntityManager(em);
}
dbCal = em.find(TStamp.class, tsId).getTsLTZ();
int hourDiffFromDB = dbCal.get(Calendar.HOUR_OF_DAY) - originalCal.get(Calendar.HOUR_OF_DAY);
int hourDiffFromZone = (dbCal.get(Calendar.ZONE_OFFSET) - originalCal.get(Calendar.ZONE_OFFSET))/ 3600000;
assertTrue("The yhour is not macth", (hourDiffFromZone + dbCal.get(Calendar.DST_OFFSET)/3600000) == hourDiffFromDB);
}
}
|
package me.cvhc.equationsolver;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
public class MainActivity extends AppCompatActivity {
TextView textViewEquation;
ListView listViewIDs;
ArrayAdapter<String> adapterVariables;
ArrayList<String> listVariables = new ArrayList<String>();
ArrayList<Character> listIDs = new ArrayList<>();
Character variable = '\0';
private static final List<Character> VARIALBE_CHARS = Arrays.asList('x', 'y', 'z');
private final String LOG_TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewEquation = (TextView) findViewById(R.id.textViewEquation);
listViewIDs = (ListView) findViewById(R.id.listViewVariables);
adapterVariables = new ArrayAdapter<String>(this,
R.layout.list_view_variables, listVariables);
listViewIDs.setAdapter(adapterVariables);
listViewIDs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_SHORT).show();
if (position == 0) {
AlertDialog.Builder selector = new AlertDialog.Builder(MainActivity.this);
ArrayList<String> items = new ArrayList<>();
for (char c : listIDs) {
items.add(c + " as variable");
}
String[] arr = items.toArray(new String[items.size()]);
selector.setSingleChoiceItems(arr, listIDs.indexOf(variable), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int position) {
Character selection = listIDs.get(position);
if (selection != variable) {
variable = selection;
onChangeVariable(variable);
}
Log.d(LOG_TAG, "User chose " + selection + " as variable");
dialog.dismiss();
}
});
selector.setTitle("Variable of the equation");
selector.show();
}
else {
int id_index = position - 1;
char id = listIDs.get(id_index);
// TODO: Implement ID assignment
}
}
});
textViewEquation.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
String eq = s.toString();
String[] part = eq.split("=", 2);
Log.d(LOG_TAG, "Equation: " + eq);
if (part.length != 2) {
return;
}
ExpressionEvaluator left = new ExpressionEvaluator(part[0]);
ExpressionEvaluator right = new ExpressionEvaluator(part[1]);
Log.d(LOG_TAG, "left part: " + part[0]);
Log.d(LOG_TAG, "right part: " + part[1]);
if (left.isError() || right.isError()) {
textViewEquation.setBackgroundResource(R.color.red);
} else {
textViewEquation.setBackgroundResource(android.R.color.transparent);
HashSet<Character> ids = new HashSet<>(left.getProperty().Variables);
ids.addAll(right.getProperty().Variables);
if (ids.isEmpty()) { ids.add(VARIALBE_CHARS.get(0)); }
for (Character c : VARIALBE_CHARS) {
if (ids.contains(c)) {
variable = c;
break;
}
}
listIDs = new ArrayList<>(ids);
Collections.sort(listIDs);
if (variable == '\0') { variable = listIDs.get(0); }
onChangeVariable(variable);
}
}
});
}
protected void onChangeVariable(char variable) {
listVariables.clear();
listVariables.add("Variable " + variable);
for (Character id: listIDs) {
if (id != variable)
listVariables.add("Constant " + id);
}
adapterVariables.notifyDataSetChanged();
}
}
|
package net.fourbytes.shadow;
import java.util.Vector;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.IntMap.Entry;
public class LightSystem {
public Level level;
public static boolean inview = true;
public int speed = 10;
public boolean canUpdate = false;
public int tick = 0;
public boolean clearLight = false;
protected static Rectangle viewport = new Rectangle();
protected static Rectangle objrec = new Rectangle();
public LightSystem(Level level) {
this.level = level;
}
public void tick() {
canUpdate = tick >= speed;
if (canUpdate) {
clearLight = true;
for (Entity e : level.mainLayer.entities) {
setLight(e, level.mainLayer);
}
for (Block b : level.mainLayer.blocks) {
setLight(b, level.mainLayer);
}
clearLight = false;
for (Entity e : level.mainLayer.entities) {
setLight(e, level.mainLayer);
}
for (Block b : level.mainLayer.blocks) {
setLight(b, level.mainLayer);
}
tick = 0;
}
tick++;
viewport.set(Shadow.cam.camrec);
float f = 15f;
viewport.x -= f;
viewport.y -= f;
viewport.width += f*2;
viewport.height += f*2;
}
protected final static Color sun = new Color(1f, 1f, 1f, 1f);
protected final static Color dark = new Color(1f, 1f, 1f, 1f);
protected final static Color emit = new Color(1f, 1f, 1f, 1f);
protected final static Color tmpc = new Color(1f, 1f, 1f, 1f);
public void setLight(GameObject go, Layer ll) {
if (!canUpdate) {
return;
}
if (level.tickid < speed*2) {
return;
}
if (inview) {
objrec.set(go.pos.x, go.pos.y, go.rec.width, go.rec.height);
if (!viewport.overlaps(objrec)) {
return;
}
}
if (clearLight) {
go.lightTint.set(ll.level.globalLight).mul(0.15f, 0.15f, 0.15f, 1f);
return;
}
boolean primaryLight = !(go instanceof Entity);
boolean secondaryLight = go.light.a == 0 || go instanceof Entity;
int cx = (int)go.pos.x;
int cy = (int)go.pos.y;
float r = 6.5f;
float rsq = MathHelper.sq(r);
float rp = 4f;
float rpsq = MathHelper.sq(rp);
float avgsun = (ll.level.globalLight.r + ll.level.globalLight.g + ll.level.globalLight.a) / 3f;
for (float x = cx-r; x <= cx+r; x++) {
for (float y = cy-r; y <= cy+r; y++) {
float tmpradsq = MathHelper.distsq(cx, cy, x, y);
if (tmpradsq <= rsq) {
float tmprad = (float) Math.sqrt(tmpradsq);
Array<Block> al = ll.get(Coord.get(x, y));
if (secondaryLight && tmpradsq <= rpsq) {
float fsun = (1f/rpsq)*avgsun*0.6275f;
float fdark = 1f/rpsq;
float femit = 1f/rp;
if (!primaryLight) {
//If not affected by primaryLight make light strength be dependent to the distance.
femit= 1f-tmpradsq/rpsq;
}
//Passive lighting - X checks for light source and adapts to it.
//If go is entity it uses it to adapt to light as active lighting can't light entities.
//If go is block AND go.color.a is 0 this is used to check for sun.
int bs = 0;
int es = 0;
int ps = 0;
//sun.set(1f, 1f, 1f, 1f);
sun.set(ll.level.globalLight);
dark.set(0f, 0f, 0f, 1f);
emit.set(1f, 1f, 1f, 1f);
if (al != null && al.size != 0) {
for (Block bb : al) {
if (bb.light.a > 0f) {
es++;
if (es == 1) {
emit.set(bb.light);
} else {
emit.add(bb.light);
}
}
if (bb.passSunlight) {
ps++;
if (ps == 1) {
sun.set(tmpc.set(ll.level.globalLight).mul(bb.tintSunlight));
} else {
sun.add(tmpc.set(ll.level.globalLight).mul(bb.tintSunlight));
}
} else {
bs++;
if (bs == 1) {
dark.set(bb.tintDarklight);
} else {
dark.add(bb.tintDarklight);
}
}
}
} else {
ps = 0;
}
if (es != 0 && !primaryLight) {
go.lightTint.add(emit.mul(1f/es).mul(femit));
}
if (bs == 0) {
go.lightTint.add(sun.mul(1f/ps).mul(fsun));
} else {
go.lightTint.add(dark.mul(1f/bs).mul(fdark));
}
}
//Sidenote: No, I didn't forget the if-check. Entities cast light but don't get lighted by blocks via primaryLight.
//Active lighting - Light source casts light to blocks around itself, strength of light being dependent of the radius.
//If go is block it uses it as primary lighting, casting it's light to other blocks.
//If go is entity it uses it to cast it's light to blocks.
//Unfournately it does NOT cast light to entities so entities use the secondary lighting method.
if (go.light.a > 0f && al != null && al.size != 0) {
go.lightTint.set(1f, 1f, 1f, 1f);
for (Block bb : al) {
if (bb.light.a > 0f) {
continue;
}
emit.set(go.light);
bb.lightTint.add(emit.mul((1f-tmpradsq/rsq)*go.light.a));
}
}
}
}
}
go.lightTint.a = 1f;
go.cantint = true;
}
}
|
package me.devsaki.hentoid.util;
import com.annimon.stream.Stream;
import java.util.List;
import me.devsaki.hentoid.database.CollectionDAO;
import me.devsaki.hentoid.database.domains.Attribute;
import me.devsaki.hentoid.database.domains.Content;
import me.devsaki.hentoid.database.domains.Group;
import me.devsaki.hentoid.database.domains.GroupItem;
import me.devsaki.hentoid.enums.Grouping;
/**
* Utility class for Content-related operations
*/
public final class GroupHelper {
private GroupHelper() {
throw new IllegalStateException("Utility class");
}
public static final int FLAG_UNCATEGORIZED = 99;
public static List<Grouping> getGroupingsToProcess() {
return Stream.of(Grouping.values()).filter(Grouping::canReorderBooks).toList();
}
public static Group getOrCreateUncategorizedGroup(CollectionDAO dao) {
Group result = dao.selectGroupByFlag(Grouping.CUSTOM.getId(), FLAG_UNCATEGORIZED);
if (null == result) {
result = new Group(Grouping.CUSTOM, "Uncategorized", 0);
result.flag = GroupHelper.FLAG_UNCATEGORIZED;
result.id = dao.insertGroup(result);
}
return result;
}
public static void insertContent(CollectionDAO dao, Group group, Attribute attribute, Content newContent) {
insertContent(dao, group, attribute, Stream.of(newContent).toList());
}
public static void insertContent(CollectionDAO dao, Group group, Attribute attribute, List<Content> newContents) {
int nbContents;
// Create group if it doesn't exist
if (0 == group.id) {
dao.insertGroup(group);
if (attribute != null) attribute.group.setAndPutTarget(group);
nbContents = 0;
} else {
nbContents = group.getItems().size();
}
for (Content book : newContents) {
GroupItem item = new GroupItem(book, group, nbContents++);
dao.insertGroupItem(item);
}
}
}
|
package org.genericsystem.cv;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.genericsystem.cv.LinesDetector.Damper;
import org.genericsystem.cv.utils.NativeLibraryLoader;
import org.genericsystem.cv.utils.Ransac;
import org.genericsystem.cv.utils.Ransac.Model;
import org.genericsystem.cv.utils.Tools;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.utils.Converters;
import org.opencv.videoio.VideoCapture;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
public class LinesDetector3 extends AbstractApp {
static {
NativeLibraryLoader.load();
}
public static void main(String[] args) {
launch(args);
}
private final VideoCapture capture = new VideoCapture(0);
private ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
private Damper vpxDamper = new Damper(1);
private Damper vpyDamper = new Damper(1);
@Override
protected void fillGrid(GridPane mainGrid) {
vpxDamper.pushNewValue(0);
vpyDamper.pushNewValue(0);
Mat frame = new Mat();
capture.read(frame);
ImageView frameView = new ImageView(Tools.mat2jfxImage(frame));
mainGrid.add(frameView, 0, 0);
ImageView deskiewedView = new ImageView(Tools.mat2jfxImage(frame));
mainGrid.add(deskiewedView, 0, 1);
Mat dePerspectived = frame.clone();
timer.scheduleAtFixedRate(() -> {
try {
capture.read(frame);
Img grad = new Img(frame, false).morphologyEx(Imgproc.MORPH_GRADIENT, Imgproc.MORPH_RECT, new Size(2, 2)).otsu();
// Img grad = new Img(frame, false).canny(60, 180);
// Img grad = new Img(frame, false).bilateralFilter(20, 80, 80).bgr2Gray().adaptativeThresHold(255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY_INV, 11, 3).morphologyEx(Imgproc.MORPH_CLOSE, Imgproc.MORPH_RECT, new Size(11,
Lines lines = new Lines(grad.houghLinesP(1, Math.PI / 180, 10, 100, 10));
System.out.println("Average angle: " + lines.getMean() / Math.PI * 180);
if (lines.size() > 10) {
lines.draw(frame, new Scalar(0, 0, 255));
frameView.setImage(Tools.mat2jfxImage(frame));
// Mat dePerspectived = new Mat(frame.size(), CvType.CV_8UC3, new Scalar(255, 255, 255));
Ransac<Line> ransac = lines.vanishingPointRansac(frame.width(), frame.height());
Point vp = (Point) ransac.getBestModel().getParams()[0];
vpxDamper.pushNewValue(vp.x);
vpyDamper.pushNewValue(vp.y);
Point bary = new Point(frame.width() / 2, frame.height() / 2);
Mat homography = findHomography(new Point(vpxDamper.getMean(), vpyDamper.getMean()), bary, frame.width(), frame.height());
lines = new Lines(ransac.getBestDataSet().values()).perspectivTransform(homography);
Mat mask = new Mat(frame.size(), CvType.CV_8UC1, new Scalar(255));
Mat maskWarpped = new Mat();
Imgproc.warpPerspective(mask, maskWarpped, homography, frame.size());
Mat tmp = new Mat();
Imgproc.warpPerspective(frame, tmp, homography, frame.size(), Imgproc.INTER_LINEAR, Core.BORDER_REPLICATE, Scalar.all(255));
tmp.copyTo(dePerspectived, maskWarpped);
lines.draw(dePerspectived, new Scalar(0, 255, 0));
deskiewedView.setImage(Tools.mat2jfxImage(dePerspectived));
} else
System.out.println("Not enough lines : " + lines.size());
} catch (Throwable e) {
e.printStackTrace();
}
}, 33, 250, TimeUnit.MILLISECONDS);
}
public void print(Mat m) {
for (int row = 0; row < m.rows(); row++) {
System.out.print("(");
for (int col = 0; col < m.cols() - 1; col++) {
System.out.print(m.get(row, col)[0] + ",");
}
System.out.println(m.get(row, m.cols() - 1)[0] + ")");
}
System.out.println("
}
public Point[] rotate(Point bary, double alpha, Point... p) {
Mat matrix = Imgproc.getRotationMatrix2D(bary, alpha / Math.PI * 180, 1);
MatOfPoint2f results = new MatOfPoint2f();
Core.transform(new MatOfPoint2f(p), results, matrix);
return results.toArray();
}
public Point center(Point a, Point b) {
return new Point((a.x + b.x) / 2, (a.y + b.y) / 2);
}
private Mat findHomography(Point vp, Point bary, double width, double height) {
double alpha_ = Math.atan2((vp.y - bary.y), (vp.x - bary.x));
if (alpha_ < -Math.PI / 2 && alpha_ > -Math.PI)
alpha_ = alpha_ + Math.PI;
if (alpha_ < Math.PI && alpha_ > Math.PI / 2)
alpha_ = alpha_ - Math.PI;
double alpha = alpha_;
Point rotatedVp = rotate(bary, alpha, vp)[0];
Point A = new Point(0, 0);
Point B = new Point(width, 0);
Point C = new Point(width, height);
Point D = new Point(0, height);
Point AB2 = new Point(width / 2, 0);
Point CD2 = new Point(width / 2, height);
Point A_, B_, C_, D_;
if (Math.abs(rotatedVp.x - width / 2) > 1000) {
A_ = A;
B_ = B;
C_ = C;
D_ = D;
System.out.println("
} else if (rotatedVp.x >= width / 2) {
A_ = new Line(AB2, rotatedVp).intersection(0);
D_ = new Line(CD2, rotatedVp).intersection(0);
C_ = new Line(A_, bary).intersection(new Line(CD2, rotatedVp));
B_ = new Line(D_, bary).intersection(new Line(AB2, rotatedVp));
} else {
B_ = new Line(AB2, rotatedVp).intersection(width);
C_ = new Line(CD2, rotatedVp).intersection(width);
A_ = new Line(C_, bary).intersection(new Line(AB2, rotatedVp));
D_ = new Line(B_, bary).intersection(new Line(CD2, rotatedVp));
}
//System.out.println("vp : " + vp);
System.out.println("rotated vp : " + rotatedVp);
System.out.println("Alpha : " + alpha * 180 / Math.PI);
// System.out.println("A : " + A + " " + A_);
// System.out.println("B : " + B + " " + B_);
// System.out.println("C : " + C + " " + C_);
// System.out.println("D : " + D + " " + D_);
return Imgproc.getPerspectiveTransform(new MatOfPoint2f(rotate(bary, -alpha, A_, B_, C_, D_)), new MatOfPoint2f(A, B, C, D));
}
// private Mat findHomography(Point vp, Point bary, double width, double height) {
// System.out.println("vpx : " + vp.x);
// System.out.println("vpy : " + vp.y);
// double alpha_ = Math.atan2((vp.y - bary.y), (vp.x - bary.x));
// if (alpha_ < -Math.PI / 2 && alpha_ > -Math.PI)
// alpha_ = alpha_ + Math.PI;
// if (alpha_ < Math.PI && alpha_ > Math.PI / 2)
// alpha_ = alpha_ - Math.PI;
// double alpha = alpha_;
// Point A = new Point(width / 2, height / 2);
// Point B = new Point(width, height / 2);
// Point C = new Point(width, height);
// Point D = new Point(width / 2, height);
// Point A_ = A;
// Point B_ = new Point(bary.x + Math.cos(alpha) * width / 2, bary.y + Math.sin(alpha) * width / 2);
// Point D_ = new Point(bary.x - Math.sin(alpha) * height / 2, bary.y + Math.cos(alpha) * height / 2);
// double a_1 = -1 / ((vp.y - bary.y) / (vp.x - bary.x));
// double b_1 = B_.y - a_1 * B_.x;
// double a_2 = (vp.y - D_.y) / (vp.x - D_.x);
// double b_2 = vp.y - a_2 * vp.x;
// double tmpx = (b_2 - b_1) / (a_1 - a_2);
// Point C_ = new Point(tmpx, a_2 * tmpx + b_2);
// System.out.println("Alpha : " + alpha * 180 / Math.PI);
// System.out.println("A : " + A + " " + A_);
// System.out.println("B : " + B + " " + B_);
// System.out.println("C : " + C + " " + C_);
// System.out.println("D : " + D + " " + D_);
// Mat homography = Imgproc.getPerspectiveTransform(new MatOfPoint2f(A_, B_, C_, D_), new MatOfPoint2f(A, B, C, D));
// MatOfPoint2f results = new MatOfPoint2f();
// Core.perspectiveTransform(new MatOfPoint2f(new Point(0, 0), bary, new Point(width, height)), results, homography);
// Point[] targets = results.toArray();
// return homography;
public static class Lines {
private final List<Line> lines = new ArrayList<>();
private final double mean;
public Lines(Mat src) {
double mean = 0;
for (int i = 0; i < src.rows(); i++) {
double[] val = src.get(i, 0);
Line line = new Line(val[0], val[1], val[2], val[3]);
lines.add(line);
mean += line.getAngle();
}
this.mean = mean / src.rows();
}
public Ransac<Line> vanishingPointRansac(int width, int height) {
Function<Collection<Line>, Model<Line>> modelProvider = datas -> {
Iterator<Line> it = datas.iterator();
Line line = it.next();
Line line2 = it.next();
Point vp = line.intersection(line2);
return new Model<Line>() {
@Override
public double computeError(Line line) {
if (!Double.isFinite(vp.y) || !Double.isFinite(vp.x))
return Double.MAX_VALUE;
// Line transformed = line.perspectivTransform(homography[0]);
// return transformed.getAngle() * line.size();
return line.distance(vp);
}
@Override
public double computeGlobalError(Collection<Line> datas) {
double error = 0;
double lineL = 0;
for (Line line : datas) {
error += Math.pow(computeError(line) * line.size(), 2);
lineL += Math.pow(line.size(), 2);
}
return Math.sqrt(error) / Math.sqrt(lineL);
}
@Override
public Object[] getParams() {
return new Object[] { vp };
}
};
};
Ransac<Line> ransac = new Ransac<>(lines, modelProvider, 2, 200, 100, Double.valueOf(Math.floor(lines.size() * 0.4)).intValue());
ransac.compute(false);
return ransac;
}
public Lines rotate(Mat matrix) {
return new Lines(lines.stream().map(line -> line.transform(matrix)).collect(Collectors.toList()));
}
public Lines perspectivTransform(Mat matrix) {
return new Lines(lines.stream().map(line -> line.perspectivTransform(matrix)).collect(Collectors.toList()));
}
public void draw(Mat frame, Scalar color) {
lines.forEach(line -> line.draw(frame, color));
}
public Lines(Collection<Line> lines) {
double mean = 0;
for (Line line : lines) {
this.lines.add(line);
mean += line.getAngle();
}
this.mean = mean / lines.size();
}
public int size() {
return lines.size();
}
public double getMean() {
return mean;
}
}
public static class Line {
private final double x1, y1, x2, y2, angle;
public Line(Point p1, Point p2) {
this(p1.x, p1.y, p2.x, p2.y);
}
public Line(double x1, double y1, double x2, double y2) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
this.angle = Math.atan2(y2 - y1, x2 - x1);
}
public double size() {
return Math.sqrt(Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2));
}
public Line transform(Mat rotationMatrix) {
MatOfPoint2f results = new MatOfPoint2f();
Core.transform(Converters.vector_Point2f_to_Mat(Arrays.asList(new Point(x1, y1), new Point(x2, y2))), results, rotationMatrix);
Point[] targets = results.toArray();
return new Line(targets[0].x, targets[0].y, targets[1].x, targets[1].y);
}
public Line perspectivTransform(Mat homography) {
MatOfPoint2f results = new MatOfPoint2f();
Core.perspectiveTransform(Converters.vector_Point2f_to_Mat(Arrays.asList(new Point(x1, y1), new Point(x2, y2))), results, homography);
Point[] targets = results.toArray();
return new Line(targets[0].x, targets[0].y, targets[1].x, targets[1].y);
}
public void draw(Mat frame, Scalar color) {
Imgproc.line(frame, new Point(x1, y1), new Point(x2, y2), color, 1);
}
@Override
public String toString() {
return "Line : " + angle;
}
public double getAngle() {
return angle;
}
public double geta() {
return (y2 - y1) / (x2 - x1);
}
public double getOrthoa() {
return (x2 - x1) / (y1 - y2);
}
public double getOrthob(Point p) {
return p.y - getOrthoa() * p.x;
}
public double getb() {
return y1 - geta() * x1;
}
public double distance(Point p) {
return Math.abs(geta() * p.x - p.y + getb()) / Math.sqrt(1 + Math.pow(geta(), 2));
}
public Point intersection(double a, double b) {
double x = (b - getb()) / (geta() - a);
double y = a * x + b;
return new Point(x, y);
}
public Point intersection(Line line) {
double x = (line.getb() - getb()) / (geta() - line.geta());
double y = geta() * x + getb();
return new Point(x, y);
}
public Point intersection(double verticalLinex) {
double x = verticalLinex;
double y = geta() * x + getb();
return new Point(x, y);
}
}
@Override
public void stop() throws Exception {
super.stop();
timer.shutdown();
timer.awaitTermination(5000, TimeUnit.MILLISECONDS);
capture.release();
}
}
|
package org.zeroxlab.momodict.reader;
import android.content.Context;
import android.support.annotation.NonNull;
import org.zeroxlab.momodict.archive.FileSet;
import org.zeroxlab.momodict.archive.Info;
import org.zeroxlab.momodict.archive.Word;
import org.zeroxlab.momodict.db.realm.RealmStore;
import org.zeroxlab.momodict.model.Book;
import org.zeroxlab.momodict.model.Entry;
import org.zeroxlab.momodict.model.Store;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* A class to extract compressed file, to parse and to save into Database.
*/
public class Reader {
private final String mCacheDir;
private final String mFilePath;
/**
* Constructor
*
* @param cacheDirPath A string as path of cache directory. Extracted files will be placed here.
* @param compressedFilePath A string as path of a compressed file which will be parsed.
*/
public Reader(@NonNull String cacheDirPath, @NonNull String compressedFilePath) {
mCacheDir = cacheDirPath;
mFilePath = compressedFilePath;
}
/**
* To parse file and save into database.
*
* @param ctx Context instance
*/
public void parse(@NonNull Context ctx) {
// extract file
final FileSet archive = CompressedFileReader.readBzip2File(mCacheDir, mFilePath);
try {
final Store store = new RealmStore(ctx);
final File ifoFile = new File(archive.get(FileSet.Type.IFO));
final File idxFile = new File(archive.get(FileSet.Type.IDX));
// To parse ifo file
final IfoReader ifoReader = new IfoReader(ifoFile);
final Info info = ifoReader.parse();
if (!IfoReader.isSanity(info)) {
throw new RuntimeException("Insanity .ifo file");
}
// To parse idx file
IdxReader idxReader = new IdxReader(idxFile);
idxReader.parse();
// To save ifo to database
Book dict = new Book();
dict.bookName = info.bookName;
dict.author = info.author;
dict.wordCount = info.wordCount;
dict.date = info.date;
store.addBook(dict);
// To save each words to database
if (idxReader.size() != 0) {
List<Word> words = DictReader.parse(idxReader.getEntries(),
archive.get(FileSet.Type.DICT));
List<Entry> entries = new ArrayList<>();
for (Word word : words) {
Entry entry = new Entry();
entry.source = info.bookName;
entry.wordStr = word.entry.wordStr;
entry.data = word.data;
entries.add(entry);
}
store.addEntries(entries);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (archive != null) {
archive.clean();
}
}
}
}
|
package org.noear.weed.xml;
import org.noear.weed.utils.IOUtils;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class XmlSqlLoader {
public static XmlSqlLoader _g = new XmlSqlLoader();
private static String _lock = "";
private boolean is_loaed = false;
private List<URL> xmlFiles = new ArrayList<>();
public static void load() throws Exception {
if (_g.is_loaed == false) {
synchronized (_lock) {
if (_g.is_loaed == false) {
_g.is_loaed = true;
_g.load0();
}
}
}
}
public static void tryLoad() {
try {
load();
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
private void load0() throws Exception {
XmlFileScaner.scan("weed3", ".xml")
.stream()
.map(k -> IOUtils.getResource(k))
.forEach(url -> _g.xmlFiles.add(url));
if (_g.xmlFiles.size() == 0) {
return;
}
List<String> codes = new ArrayList<>();
for (URL file : _g.xmlFiles) {
String code = XmlSqlCompiler.parse(file);
if (code != null) {
codes.add(code);
}
}
if (codes.size() == 0) {
return;
}
boolean is_ok = JavaStringCompiler.instance().compiler(codes);
if (is_ok) {
JavaStringCompiler.instance().loadClassAll(true);
} else {
String error = JavaStringCompiler.instance().getCompilerMessage();
System.out.println(error);
throw new RuntimeException(error);
}
}
private XmlSqlLoader() {
}
}
|
package com.opengamma.analytics.financial.model.volatility.smile.fitting.interpolation;
import com.opengamma.analytics.math.differentiation.ScalarFirstOrderDifferentiator;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.interpolation.DoubleQuadraticInterpolator1D;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.analytics.math.interpolation.data.Interpolator1DDataBundle;
import com.opengamma.util.ArgumentChecker;
import org.apache.commons.lang.ObjectUtils;
/**
* Fits a set of implied volatilities at given strikes by interpolating log-moneyness (ln(strike/forward)) against implied volatility using the supplied interpolator (the default
* is double quadratic). While this will fit any input data, there is no guarantee that the smile is arbitrage free, or indeed always positive, and should therefore be used with
* care, and only when other smile interpolators fail. The smile is extrapolated in both directions using shifted log-normals set to match the level and slope of the smile at
* the end point.
*/
public class SmileInterpolatorSpline implements GeneralSmileInterpolator {
private static final Interpolator1D DEFAULT_INTERPOLATOR = new DoubleQuadraticInterpolator1D();
private static final ScalarFirstOrderDifferentiator DIFFERENTIATOR = new ScalarFirstOrderDifferentiator();
private static final ShiftedLogNormalTailExtrapolationFitter TAIL_FITTER = new ShiftedLogNormalTailExtrapolationFitter();
private final Interpolator1D _interpolator;
public SmileInterpolatorSpline() {
this(DEFAULT_INTERPOLATOR);
}
public SmileInterpolatorSpline(final Interpolator1D interpolator) {
ArgumentChecker.notNull(interpolator, "null interpolator");
_interpolator = interpolator;
}
@Override
public Function1D<Double, Double> getVolatilityFunction(final double forward, final double[] strikes, final double expiry, final double[] impliedVols) {
ArgumentChecker.notNull(strikes, "strikes");
ArgumentChecker.notNull(impliedVols, "implied vols");
final int n = strikes.length;
ArgumentChecker.isTrue(impliedVols.length == n, "#strikes {} does not match #vols {}", n, impliedVols.length);
final double kL = strikes[0];
final double kH = strikes[n - 1];
ArgumentChecker.isTrue(kL <= forward, "Cannot do left tail extrapolation when the lowest strike ({}) is greater than the forward ({})", kL, forward);
ArgumentChecker.isTrue(kH >= forward, "Cannot do right tail extrapolation when the highest strike ({}) is less than the forward ({})", kH, forward);
final double volL = impliedVols[0];
final double volH = impliedVols[n - 1];
final double[] x = new double[n];
for (int i = 0; i < n; i++) {
x[i] = Math.log(strikes[i] / forward);
}
final Interpolator1DDataBundle data = _interpolator.getDataBundle(x, impliedVols);
final Function1D<Double, Double> interpFunc = new Function1D<Double, Double>() {
@SuppressWarnings("synthetic-access")
@Override
public Double evaluate(final Double k) {
final double m = Math.log(k / forward);
return _interpolator.interpolate(data, m);
}
};
final Function1D<Double, Boolean> domain = new Function1D<Double, Boolean>() {
@Override
public Boolean evaluate(final Double k) {
return k >= kL && k <= kH;
}
};
final Function1D<Double, Double> dSigmaDx = DIFFERENTIATOR.differentiate(interpFunc, domain);
double gradL = dSigmaDx.evaluate(kL);
double gradH = dSigmaDx.evaluate(kH);
final double[] res1 = TAIL_FITTER.fitVolatilityAndGrad(forward, kL, volL, gradL, expiry);
final double[] res2 = TAIL_FITTER.fitVolatilityAndGrad(forward, kH, volH, gradH, expiry);
return new Function1D<Double, Double>() {
@Override
public Double evaluate(final Double k) {
if (k < kL) {
return ShiftedLogNormalTailExtrapolation.impliedVolatility(forward, k, expiry, res1[0], res1[1]);
} else if (k > kH) {
return ShiftedLogNormalTailExtrapolation.impliedVolatility(forward, k, expiry, res2[0], res2[1]);
} else {
return interpFunc.evaluate(k);
}
}
};
}
public Interpolator1D getInterpolator() {
return _interpolator;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + _interpolator.hashCode();
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final SmileInterpolatorSpline other = (SmileInterpolatorSpline) obj;
return ObjectUtils.equals(_interpolator, other._interpolator);
}
}
|
package com.metaweb.gridworks.exporters;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import au.com.bytecode.opencsv.CSVWriter;
import com.metaweb.gridworks.browsing.Engine;
import com.metaweb.gridworks.browsing.FilteredRows;
import com.metaweb.gridworks.browsing.RowVisitor;
import com.metaweb.gridworks.model.Column;
import com.metaweb.gridworks.model.Project;
import com.metaweb.gridworks.model.Row;
public class CsvExporter implements Exporter{
final static Logger logger = LoggerFactory.getLogger("CsvExporter");
char separator;
public CsvExporter(){
separator = ','; //Comma separated-value is default
}
public CsvExporter(char separator){
this.separator = separator;
}
@Override
public void export(Project project, Properties options, Engine engine, OutputStream outputStream)
throws IOException {
throw new RuntimeException("Not implemented");
}
@Override
public void export(Project project, Properties options, Engine engine, Writer writer) throws IOException {
boolean printColumnHeader = true;
if (options != null && options.getProperty("printColumnHeader") != null) {
printColumnHeader = Boolean.parseBoolean(options.getProperty("printColumnHeader"));
}
RowVisitor visitor = new RowVisitor() {
CSVWriter csvWriter;
boolean printColumnHeader = true;
boolean isFirstRow = true; //the first row should also add the column headers
public RowVisitor init(CSVWriter writer, boolean printColumnHeader){
this.csvWriter = writer;
this.printColumnHeader = printColumnHeader;
return this;
}
public boolean visit(Project project, int rowIndex, Row row) {
String[] cols = new String[project.columnModel.columns.size()];
String[] vals = new String[row.cells.size()];
int i = 0;
for(Column col : project.columnModel.columns){
int cellIndex = col.getCellIndex();
cols[i] = col.getName();
Object value = row.getCellValue(cellIndex);
if(value != null){
vals[i] = value instanceof String ? (String) value : value.toString();
}
i++;
}
if( printColumnHeader && isFirstRow ){
csvWriter.writeNext(cols,false);
isFirstRow = false; //switch off flag
}
csvWriter.writeNext(vals,false);
return false;
}
@Override
public void start(Project project) {
// nothing to do
}
@Override
public void end(Project project) {
try {
csvWriter.close();
} catch (IOException e) {
logger.error("CsvExporter could not close writer : " + e.getMessage());
}
}
}.init(new CSVWriter(writer, separator), printColumnHeader);
FilteredRows filteredRows = engine.getAllFilteredRows();
filteredRows.accept(project, visitor);
}
@Override
public String getContentType() {
return "application/x-unknown";
}
@Override
public boolean takeWriter() {
return true;
}
}
|
package org.commcare.android.tasks;
import android.content.SharedPreferences;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.entity.mime.MIME;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.commcare.android.database.SqlStorage;
import org.commcare.android.database.UserStorageClosedException;
import org.commcare.android.logging.AndroidLogger;
import org.commcare.android.logging.DeviceReportRecord;
import org.commcare.android.logging.ForceCloseLogEntry;
import org.commcare.android.logging.ForceCloseLogSerializer;
import org.commcare.android.util.SessionUnavailableException;
import org.commcare.dalvik.preferences.CommCarePreferences;
import org.javarosa.core.model.User;
import org.commcare.android.logging.AndroidLogEntry;
import org.commcare.android.logging.AndroidLogSerializer;
import org.commcare.android.logging.DeviceReportWriter;
import org.commcare.android.net.HttpRequestGenerator;
import org.commcare.dalvik.R;
import org.commcare.dalvik.application.CommCareApplication;
import org.javarosa.core.services.Logger;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Date;
/**
* Catch exceptions that are going to crash the phone, grab the stack trace,
* and upload to developers.
*
* @author csims@dimagi.com
**/
public class ExceptionReporting {
private static final String TAG = ExceptionReporting.class.getSimpleName();
public static void reportExceptionInBg(final Throwable exception) {
new Thread(new Runnable() {
public void run() {
sendExceptionToServer(exception);
}
}).start();
}
private static void sendExceptionToServer(Throwable exception) {
DeviceReportRecord record = null;
ByteArrayOutputStream baos = null;
try {
// We had a session and were able to create a DeviceReportRecord, so will send the error
// using that. This is preferable when possible, because it means that if the send
// fails, we have still written the DeviceReportRecord to storage, and will attempt
// to send it again later
record = DeviceReportRecord.generateRecordStubForForceCloses();
} catch (SessionUnavailableException e) {
// The forceclose occurred when a user was not logged in, so we don't have a session
// to store the record to; just use a temp output stream instead
baos = new ByteArrayOutputStream();
}
String exceptionText = getStackTrace(exception);
String submissionUri = getSubmissionUri();
DeviceReportWriter reportWriter;
try {
reportWriter = new DeviceReportWriter(record != null ? record.openOutputStream() : baos);
reportWriter.addReportElement(new ForceCloseLogSerializer(
new ForceCloseLogEntry(exception, exceptionText)));
reportWriter.write();
if (record == null) {
sendWithoutWriting(baos.toByteArray(), submissionUri);
} else {
if (!LogSubmissionTask.submitDeviceReportRecord(record, submissionUri, null, -1)) {
// If submission failed, write this record to storage so we can send it later
try {
SqlStorage<DeviceReportRecord> storage =
CommCareApplication._().getUserStorage(DeviceReportRecord.class);
storage.write(record);
} catch (UserStorageClosedException e) {
}
}
}
} catch (IOException e) {
// Couldn't create a report writer, so just manually create the data we want to send
e.printStackTrace();
String fsDate = new Date().toString();
byte[] data = ("<?xml version='1.0' ?><n0:device_report xmlns:n0=\"http://code.javarosa.org/devicereport\"><device_id>FAILSAFE</device_id><report_date>" + fsDate + "</report_date><log_subreport><log_entry date=\"" + fsDate + "\"><entry_type>forceclose</entry_type><entry_message>" + exceptionText + "</entry_message></log_entry></log_subreport></device_report>").getBytes();
sendWithoutWriting(data, submissionUri);
}
}
private static void sendWithoutWriting(byte[] dataToSend, String submissionUri) {
//TODO: Send this with the standard logging subsystem
String payload = new String(dataToSend);
Log.d(TAG, "Outgoing payload: " + payload);
MultipartEntity entity = new MultipartEntity();
try {
//Apparently if you don't have a filename in the multipart wrapper, some receivers
//don't properly receive this post.
StringBody body = new StringBody(payload, "text/xml", MIME.DEFAULT_CHARSET) {
@Override
public String getFilename() {
return "exceptionreport.xml";
}
};
entity.addPart("xml_submission_file", body);
} catch (IllegalCharsetNameException | UnsupportedEncodingException
| UnsupportedCharsetException e1) {
e1.printStackTrace();
}
HttpRequestGenerator generator;
try {
User user = CommCareApplication._().getSession().getLoggedInUser();
if (user.getUserType().equals(User.TYPE_DEMO)) {
generator = new HttpRequestGenerator();
} else {
generator = new HttpRequestGenerator(user);
}
} catch (Exception e) {
generator = new HttpRequestGenerator();
}
try {
HttpResponse response = generator.postData(submissionUri, entity);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
response.getEntity().writeTo(bos);
Log.d(TAG, "Response: " + new String(bos.toByteArray()));
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getSubmissionUri() {
try {
SharedPreferences settings = CommCareApplication._().getCurrentApp().getAppPreferences();
return settings.getString(CommCarePreferences.PREFS_SUBMISSION_URL_KEY,
CommCareApplication._().getString(R.string.PostURL));
} catch (Exception e) {
return CommCareApplication._().getString(R.string.PostURL);
}
}
public static String getStackTrace(Throwable e) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bos));
return new String(bos.toByteArray());
}
public static String getStackTraceWithContext(Throwable e) {
String stackTrace = getStackTrace(e);
if (e.getCause() != null) {
stackTrace += "Sub Context: \n" + getStackTrace(e.getCause());
}
return stackTrace;
}
}
|
package org.commcare.views.widgets;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import org.commcare.dalvik.R;
import org.commcare.utils.StringUtils;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectMultiData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryPrompt;
import java.util.Vector;
public class SpinnerMultiWidget extends QuestionWidget {
private final Vector<SelectChoice> mItems;
// The possible select answers
private final CharSequence[] answerItems;
// The button to push to display the answers to choose from
private final Button button;
// Defines which answers are selected
private final boolean[] selections;
// The alert box that contains the answer selection view
private final AlertDialog.Builder alert_builder;
// Displays the current selections below the button
private final TextView selectionText;
@SuppressWarnings("unchecked")
public SpinnerMultiWidget(final Context context, FormEntryPrompt prompt) {
super(context, prompt);
mItems = getSelectChoices();
selections = new boolean[mItems.size()];
answerItems = new CharSequence[mItems.size()];
alert_builder = new AlertDialog.Builder(context);
button = new Button(context);
selectionText = new TextView(getContext());
// Build View
for (int i = 0; i < mItems.size(); i++) {
answerItems[i] = mPrompt.getSelectChoiceText(mItems.get(i));
}
selectionText.setText(StringUtils.getStringSpannableRobust(context, R.string.selected));
selectionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontSize);
selectionText.setVisibility(View.GONE);
button.setText(StringUtils.getStringSpannableRobust(context, R.string.select_answer));
button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontSize);
button.setPadding(0, 0, 0, 7);
// Give the button a click listener. This defines the alert as well. All the
// click and selection behavior is defined here.
button.setOnClickListener(v -> {
alert_builder.setTitle(mPrompt.getQuestionText());
if (mPrompt.isReadOnly()) {
alert_builder.setNegativeButton(R.string.cancel,
(dialog, id) -> {
dialog.dismiss();
});
} else {
alert_builder.setPositiveButton(R.string.ok,
(dialog, id) -> {
boolean first = true;
selectionText.setText("");
for (int i = 0; i < selections.length; i++) {
if (selections[i]) {
if (first) {
first = false;
selectionText.setText(StringUtils.getStringSpannableRobust(context, R.string.selected)
+ answerItems[i].toString());
selectionText.setVisibility(View.VISIBLE);
} else {
selectionText.setText(selectionText.getText() + ", "
+ answerItems[i].toString());
}
}
}
widgetEntryChanged();
});
}
alert_builder.setMultiChoiceItems(answerItems, selections,
(dialog, which, isChecked) -> {
selections[which] = isChecked;
widgetEntryChanged();
});
AlertDialog alert = alert_builder.create();
alert.show();
widgetEntryChanged();
});
// Fill in previous answers
Vector<Selection> ve = new Vector<>();
if (mPrompt.getAnswerValue() != null) {
ve = (Vector<Selection>)mPrompt.getAnswerValue().getValue();
}
if (ve != null) {
boolean first = true;
for (int i = 0; i < selections.length; ++i) {
String value = mItems.get(i).getValue();
boolean found = false;
for (Selection s : ve) {
if (value.equals(s.getValue())) {
found = true;
break;
}
}
selections[i] = found;
if (found) {
if (first) {
first = false;
selectionText.setText(StringUtils.getStringSpannableRobust(context, R.string.selected)
+ answerItems[i].toString());
selectionText.setVisibility(View.VISIBLE);
} else {
selectionText.setText(selectionText.getText() + ", "
+ answerItems[i].toString());
}
}
}
}
addView(button);
addView(selectionText);
}
@Override
public IAnswerData getAnswer() {
Vector<Selection> vc = new Vector<>();
for (int i = 0; i < mItems.size(); i++) {
if (selections[i]) {
SelectChoice sc = mItems.get(i);
vc.add(new Selection(sc));
}
}
if (vc.size() == 0) {
return null;
} else {
return new SelectMultiData(vc);
}
}
@Override
public void clearAnswer() {
selectionText.setText(R.string.selected);
selectionText.setVisibility(View.GONE);
for (int i = 0; i < selections.length; i++) {
selections[i] = false;
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
button.setOnLongClickListener(l);
}
@Override
public void unsetListeners() {
super.unsetListeners();
button.setOnLongClickListener(null);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
button.cancelLongPress();
}
}
|
package bropals.lib.simplegame.gui;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.regex.Pattern;
/**
* A GUI element that displays some text. When word wrap is enabled, the
* GuiText will attempt to draw all text inside of its box. If there is not
* enough space, then it will continue drawing at the width of the GuiText.
*
* @author Jonathon
*/
public class GuiText extends GuiElement {
private String text;
private Font font;
private Color textColor;
private boolean wordWrap;
private String[] lines;
/**
* Creates a GuiText object to display text. Word wrap mode is on
* by default; default color is Color.BLACK.
* @param text the text to display
* @param x the top-left corner's X position of the GuiText's box
* @param y the top-left corner's Y position of the GuiText's box
* @param w the width of the GuiText box
* @param h the height of the GuiText
*/
public GuiText(String text, int x, int y, int w, int h) {
super(x, y, w, h);
setText(text);
font = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
wordWrap = true;
textColor = Color.BLACK;
}
/**
* Sets the color of this GuiText's text.
* @param color the color of this GuiText's text.
*/
public void setTextColor(Color color) {
this.textColor=color;
}
/**
* Gets the color of this GuiText's text.
* @return the color of this GuiText's text.
*/
public Color getTextColor() {
return textColor;
}
/**
* Gets the word wrap preference of this GuiText. Returns true if it
* is wrapping its text, false if it is not.
* @return the word wrap preference.
*/
public boolean isWordWrapping() {
return wordWrap;
}
/**
* Sets the word wrap state of this GuiText.
* @param wordWrap the word wrap state.
*/
public void setWordWrap(boolean wordWrap) {
this.wordWrap = wordWrap;
lines = null;
}
private void splitIntoLines(FontMetrics metrics) {
if (this.wordWrap) {
ArrayList<String> l = new ArrayList();
String[] splitText = this.text.split(Pattern.quote(" "));
/* Split into multiple lines */
int lineWidth = 0;
int wordLength;
int spaceWidth = metrics.charWidth(' ');
String currentLine = "";
for (int word = 0; word < splitText.length; word++) {
wordLength = metrics.stringWidth(splitText[word]);
if ( wordLength + lineWidth > getWidth() ) {
l.add(currentLine);
lineWidth = (spaceWidth + wordLength);
currentLine = (splitText[word] + ' ');
} else {
lineWidth += (spaceWidth + wordLength);
currentLine += (splitText[word] + ' ');
}
}
lines = (String[])l.toArray(new String[0]);
}
}
/**
* Sets the text for this GuiText to display.
* @param text the text to display.
*/
public void setText(String text) {
this.text=text;
lines = null;
}
/**
* Gets the text that this GuiText is displaying.
* @return the text that this GuiText is displaying.
*/
public String getText() {
return text;
}
/**
* Gets the Font that this GuiText is using
* @return the font that this GuiText is using
*/
public Font getFont() {
return font;
}
/**
* Sets the Font that this GuiText uses.
* @param font the font that this GuiText uses.
*/
public void setFont(Font font) {
this.font=font;
lines = null;
}
@Override
public void render(Object graphicsObject) {
Graphics g = (Graphics)graphicsObject;
g.setFont(font);
g.setColor(textColor);
FontMetrics fm = g.getFontMetrics();
int xLoc = getX();
int yLoc = getY() + fm.getHeight();
if (wordWrap) {
if (lines == null) {
splitIntoLines(fm);
}
for (String line : lines) {
g.drawString(line, xLoc, yLoc);
yLoc += fm.getHeight();
}
} else {
g.drawString(getText(), xLoc, yLoc);
}
}
}
|
package gameAuthoring.scenes.pathBuilding;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javafx.geometry.Point2D;
public class Path {
private static final double CONNECT_THRESHOLD = 40;
private static final double INSIDE_STARTING_LOC_THRESHOLD = 50;
private static final double MIN_DISTANCE_BTW_LOCS = 150;
private static final int MAX_NUM_STARTING_LOCS = 2;
private static final int MAX_NUM_ENDING_LOCS = 2;
private List<StartingLocation> myStartingLocations;
private List<EndingLocation> myEndingLocations;
private List<LinkedList<PathComponent>> myPath;
private PathComponent mySelectedComponent;
public Path() {
myPath = new ArrayList<LinkedList<PathComponent>>();
myStartingLocations = new ArrayList<StartingLocation>();
myEndingLocations = new ArrayList<EndingLocation>();
}
public void addPathComponentToPath(PathComponent componentToAdd) {
if(!componentSuccessfullyAddedToStartingLocation(componentToAdd) &&
!componentSuccessfullyAddedToEndOfAConnectedComponent(componentToAdd)) {
createNewConnectedComponent(componentToAdd);
}
}
private boolean componentSuccessfullyAddedToStartingLocation (PathComponent componentToAdd) {
for(StartingLocation startingLoc:myStartingLocations){
Point2D centerCircle = new Point2D(startingLoc.getCenterX(), startingLoc.getCenterY());
if(addedComponentIsWithinCircle(componentToAdd, centerCircle)) {
componentToAdd.setStartingPoint(centerCircle);
createNewConnectedComponent(componentToAdd);
return true;
}
}
return false;
}
private boolean addedComponentIsWithinCircle (PathComponent componentToAdd, Point2D centerCircle) {
System.out.println(componentToAdd.getStartingPoint().distance(centerCircle));
return componentToAdd.getStartingPoint().distance(centerCircle) < INSIDE_STARTING_LOC_THRESHOLD;
}
private boolean componentSuccessfullyAddedToEndOfAConnectedComponent (PathComponent componentToAdd) {
for(LinkedList<PathComponent> connectedComponent:myPath){
PathComponent lastComponentInConnectedComponent = connectedComponent.getLast();
if(closeEnoughToConnect(lastComponentInConnectedComponent, componentToAdd)){
componentToAdd.setStartingPoint(lastComponentInConnectedComponent.getEndingPoint());
connectedComponent.add(componentToAdd);
return true;
}
}
return false;
}
private void createNewConnectedComponent (PathComponent componentToAdd) {
LinkedList<PathComponent> newConnectedComponent = new LinkedList<PathComponent>();
newConnectedComponent.add(componentToAdd);
myPath.add(newConnectedComponent);
}
private boolean closeEnoughToConnect (PathComponent last, PathComponent componentToAdd) {
return last.getEndingPoint().distance(componentToAdd.getStartingPoint()) < CONNECT_THRESHOLD;
}
public void moveConnectedComponent (PathComponent draggedComponent, double deltaX, double deltaY) {
LinkedList<PathComponent> connectedComponent =
getConnectedComponentContaining(draggedComponent);
for(PathComponent component:connectedComponent) {
component.translate(deltaX, deltaY);
}
}
private LinkedList<PathComponent> getConnectedComponentContaining (PathComponent draggedComponent) {
for(LinkedList<PathComponent> connectedComponent:myPath){
for(PathComponent component:connectedComponent) {
if(draggedComponent.equals(component)) {
return connectedComponent;
}
}
}
return null;
}
public void tryToConnectComponents (PathComponent componentDragged) {
LinkedList<PathComponent> draggedConnectedComponent =
getConnectedComponentContaining(componentDragged);
for(LinkedList<PathComponent> connectedComponent:myPath){
PathComponent lastComponentInConnectedComponent = connectedComponent.getLast();
if(closeEnoughToConnect(lastComponentInConnectedComponent, draggedConnectedComponent.getFirst())){
draggedConnectedComponent.getFirst().setStartingPoint(lastComponentInConnectedComponent.getEndingPoint());
connectedComponent.addAll(draggedConnectedComponent);
myPath.remove(draggedConnectedComponent);
return;
}
}
}
public StartingLocation addStartingLocation(double x, double y) {
if(canCreateStartingLocationAt(x, y)){
StartingLocation loc = new StartingLocation(x, y);
myStartingLocations.add(loc);
return loc;
}
return null;
}
private boolean canCreateStartingLocationAt (double x, double y) {
Point2D newLocation = new Point2D(x, y);
for(StartingLocation loc:myStartingLocations){
Point2D centerOfStartingLoc = new Point2D(loc.getCenterX(), loc.getCenterY());
if(centerOfStartingLoc.distance(newLocation) < MIN_DISTANCE_BTW_LOCS){
return false;
}
}
return myStartingLocations.size() < MAX_NUM_STARTING_LOCS;
}
public EndingLocation addEndingLocation(double x, double y) {
if(canCreateEndingLocationAt(x, y)){
EndingLocation loc = new EndingLocation(x, y);
myEndingLocations.add(loc);
return loc;
}
return null;
}
private boolean canCreateEndingLocationAt (double x, double y) {
Point2D newLocation = new Point2D(x, y);
for(EndingLocation loc:myEndingLocations){
Point2D centerOfStartingLoc = new Point2D(loc.getCenterX(), loc.getCenterY());
if(centerOfStartingLoc.distance(newLocation) < MIN_DISTANCE_BTW_LOCS){
return false;
}
}
return myEndingLocations.size() < MAX_NUM_ENDING_LOCS;
}
public void addEndingLocation(EndingLocation loc) {
myEndingLocations.add(loc);
}
public boolean startingLocationsConfiguredCorrectly () {
return !myStartingLocations.isEmpty();
}
public boolean endingLocationsConfiguredCorrectly () {
return !myEndingLocations.isEmpty();
}
public void setSelectedComponent (PathLine tempLine) {
if(mySelectedComponent != null && componentIsInSelectedComponent(tempLine)) {
deselectSelectedConnectedComponent();
return;
}
deselectSelectedConnectedComponent();
mySelectedComponent = tempLine;
LinkedList<PathComponent> selectedConnectedComponent = getConnectedComponentContaining(mySelectedComponent);
if(selectedConnectedComponent != null){
for(PathComponent comp:selectedConnectedComponent) {
comp.select();
}
}
}
private boolean componentIsInSelectedComponent (PathLine componentClickedOn) {
LinkedList<PathComponent> selectedConnectedComponent = getConnectedComponentContaining(mySelectedComponent);
for(PathComponent comp:selectedConnectedComponent){
if(comp.equals(componentClickedOn)){
return true;
}
}
return false;
}
private void deselectSelectedConnectedComponent () {
if(mySelectedComponent == null){
return;
}
LinkedList<PathComponent> selectedConnectedComponent = getConnectedComponentContaining(mySelectedComponent);
if(selectedConnectedComponent != null){
for(PathComponent comp:selectedConnectedComponent) {
comp.deselect();
}
}
mySelectedComponent = null;
}
public LinkedList<PathComponent> deleteSelectedComponent () {
if(mySelectedComponent == null){
return null;
}
LinkedList<PathComponent> connectedComponentToDelete = getConnectedComponentContaining(mySelectedComponent);
if(connectedComponentToDelete != null){
myPath.remove(connectedComponentToDelete);
}
mySelectedComponent = null;
return connectedComponentToDelete;
}
}
|
package com.fsck.k9.activity;
import java.util.Collection;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.Account.SortType;
import com.fsck.k9.DI;
import com.fsck.k9.K9;
import com.fsck.k9.K9.SplitViewMode;
import com.fsck.k9.Preferences;
import com.fsck.k9.activity.compose.MessageActions;
import com.fsck.k9.activity.misc.SwipeGestureDetector.OnSwipeGestureListener;
import com.fsck.k9.controller.MessageReference;
import com.fsck.k9.fragment.MessageListFragment;
import com.fsck.k9.fragment.MessageListFragment.MessageListFragmentListener;
import com.fsck.k9.helper.Contacts;
import com.fsck.k9.helper.ParcelableUtil;
import com.fsck.k9.mailstore.SearchStatusManager;
import com.fsck.k9.mailstore.StorageManager;
import com.fsck.k9.notification.NotificationChannelManager;
import com.fsck.k9.preferences.StorageEditor;
import com.fsck.k9.search.LocalSearch;
import com.fsck.k9.search.SearchAccount;
import com.fsck.k9.search.SearchSpecification;
import com.fsck.k9.search.SearchSpecification.Attribute;
import com.fsck.k9.search.SearchSpecification.SearchCondition;
import com.fsck.k9.search.SearchSpecification.SearchField;
import com.fsck.k9.ui.K9Drawer;
import com.fsck.k9.ui.R;
import com.fsck.k9.ui.messageview.MessageViewFragment;
import com.fsck.k9.ui.messageview.MessageViewFragment.MessageViewFragmentListener;
import com.fsck.k9.ui.settings.SettingsActivity;
import com.fsck.k9.view.ViewSwitcher;
import com.fsck.k9.view.ViewSwitcher.OnSwitchCompleteListener;
import com.mikepenz.materialdrawer.Drawer.OnDrawerListener;
import de.cketti.library.changelog.ChangeLog;
import timber.log.Timber;
/**
* MessageList is the primary user interface for the program. This Activity
* shows a list of messages.
* From this Activity the user can perform all standard message operations.
*/
public class MessageList extends K9Activity implements MessageListFragmentListener,
MessageViewFragmentListener, OnBackStackChangedListener, OnSwipeGestureListener,
OnSwitchCompleteListener {
private static final String EXTRA_SEARCH = "search_bytes";
private static final String EXTRA_NO_THREADING = "no_threading";
private static final String ACTION_SHORTCUT = "shortcut";
private static final String EXTRA_SPECIAL_FOLDER = "special_folder";
private static final String EXTRA_MESSAGE_REFERENCE = "message_reference";
// used for remote search
public static final String EXTRA_SEARCH_ACCOUNT = "com.fsck.k9.search_account";
private static final String EXTRA_SEARCH_FOLDER = "com.fsck.k9.search_folder";
private static final String STATE_DISPLAY_MODE = "displayMode";
private static final String STATE_MESSAGE_LIST_WAS_DISPLAYED = "messageListWasDisplayed";
private static final String STATE_FIRST_BACK_STACK_ID = "firstBackstackId";
// Used for navigating to next/previous message
private static final int PREVIOUS = 1;
private static final int NEXT = 2;
public static final int REQUEST_MASK_PENDING_INTENT = 1 << 15;
public static void actionDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask) {
actionDisplaySearch(context, search, noThreading, newTask, true);
}
public static void actionDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask, boolean clearTop) {
context.startActivity(
intentDisplaySearch(context, search, noThreading, newTask, clearTop));
}
public static Intent intentDisplaySearch(Context context, SearchSpecification search,
boolean noThreading, boolean newTask, boolean clearTop) {
Intent intent = new Intent(context, MessageList.class);
intent.putExtra(EXTRA_SEARCH, ParcelableUtil.marshall(search));
intent.putExtra(EXTRA_NO_THREADING, noThreading);
if (clearTop) {
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
if (newTask) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
return intent;
}
public static Intent shortcutIntent(Context context, String specialFolder) {
Intent intent = new Intent(context, MessageList.class);
intent.setAction(ACTION_SHORTCUT);
intent.putExtra(EXTRA_SPECIAL_FOLDER, specialFolder);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
public static Intent actionDisplayMessageIntent(Context context,
MessageReference messageReference) {
Intent intent = new Intent(context, MessageList.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(EXTRA_MESSAGE_REFERENCE, messageReference.toIdentityString());
return intent;
}
private enum DisplayMode {
MESSAGE_LIST,
MESSAGE_VIEW,
SPLIT_VIEW
}
protected final SearchStatusManager searchStatusManager = DI.get(SearchStatusManager.class);
private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation();
private final Preferences preferences = DI.get(Preferences.class);
private final NotificationChannelManager channelUtils = DI.get(NotificationChannelManager.class);
private ActionBar actionBar;
private ActionBarDrawerToggle drawerToggle;
private K9Drawer drawer;
private FragmentTransaction openFolderTransaction;
private View actionBarMessageList;
private TextView actionBarTitle;
private TextView actionBarSubTitle;
private Menu menu;
private ViewGroup messageViewContainer;
private View messageViewPlaceHolder;
private MessageListFragment messageListFragment;
private MessageViewFragment messageViewFragment;
private int firstBackStackId = -1;
private Account account;
private LocalSearch search;
private boolean singleFolderMode;
private ProgressBar actionBarProgress;
private MenuItem menuButtonCheckMail;
private View actionButtonIndeterminateProgress;
private int lastDirection = (K9.messageViewShowNext()) ? NEXT : PREVIOUS;
/**
* {@code true} if the message list should be displayed as flat list (i.e. no threading)
* regardless whether or not message threading was enabled in the settings. This is used for
* filtered views, e.g. when only displaying the unread messages in a folder.
*/
private boolean noThreading;
private DisplayMode displayMode;
private MessageReference messageReference;
/**
* {@code true} when the message list was displayed once. This is used in
* {@link #onBackPressed()} to decide whether to go from the message view to the message list or
* finish the activity.
*/
private boolean messageListWasDisplayed = false;
private ViewSwitcher viewSwitcher;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (UpgradeDatabases.actionUpgradeDatabases(this, getIntent())) {
finish();
return;
}
if (useSplitView()) {
setContentView(R.layout.split_message_list);
} else {
setContentView(R.layout.message_list);
viewSwitcher = findViewById(R.id.container);
viewSwitcher.setFirstInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_left));
viewSwitcher.setFirstOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_right));
viewSwitcher.setSecondInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_right));
viewSwitcher.setSecondOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_left));
viewSwitcher.setOnSwitchCompleteListener(this);
}
initializeActionBar();
initializeDrawer(savedInstanceState);
// Enable gesture detection for MessageLists
setupGestureDetector(this);
if (!decodeExtras(getIntent())) {
return;
}
if (isDrawerEnabled()) {
drawer.updateUserAccountsAndFolders(account);
}
findFragments();
initializeDisplayMode(savedInstanceState);
initializeLayout();
initializeFragments();
displayViews();
channelUtils.updateChannels();
ChangeLog cl = new ChangeLog(this);
if (cl.isFirstRun()) {
cl.getLogDialog().show();
}
if (savedInstanceState == null) {
checkAndRequestPermissions();
}
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (isFinishing()) {
return;
}
setIntent(intent);
if (firstBackStackId >= 0) {
getFragmentManager().popBackStackImmediate(firstBackStackId,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
firstBackStackId = -1;
}
removeMessageListFragment();
removeMessageViewFragment();
messageReference = null;
search = null;
if (!decodeExtras(intent)) {
return;
}
if(isDrawerEnabled()) {
drawer.updateUserAccountsAndFolders(account);
}
initializeDisplayMode(null);
initializeFragments();
displayViews();
}
/**
* Get references to existing fragments if the activity was restarted.
*/
private void findFragments() {
FragmentManager fragmentManager = getSupportFragmentManager();
messageListFragment = (MessageListFragment) fragmentManager.findFragmentById(R.id.message_list_container);
messageViewFragment = (MessageViewFragment) fragmentManager.findFragmentById(R.id.message_view_container);
if (messageListFragment != null) {
initializeFromLocalSearch(messageListFragment.getLocalSearch());
}
}
/**
* Create fragment instances if necessary.
*
* @see #findFragments()
*/
private void initializeFragments() {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.addOnBackStackChangedListener(this);
boolean hasMessageListFragment = (messageListFragment != null);
if (!hasMessageListFragment) {
FragmentTransaction ft = fragmentManager.beginTransaction();
messageListFragment = MessageListFragment.newInstance(search, false,
(K9.isThreadedViewEnabled() && !noThreading));
ft.add(R.id.message_list_container, messageListFragment);
ft.commit();
}
// Check if the fragment wasn't restarted and has a MessageReference in the arguments. If
// so, open the referenced message.
if (!hasMessageListFragment && messageViewFragment == null &&
messageReference != null) {
openMessage(messageReference);
}
}
/**
* Set the initial display mode (message list, message view, or split view).
*
* <p><strong>Note:</strong>
* This method has to be called after {@link #findFragments()} because the result depends on
* the availability of a {@link MessageViewFragment} instance.
* </p>
*
* @param savedInstanceState
* The saved instance state that was passed to the activity as argument to
* {@link #onCreate(Bundle)}. May be {@code null}.
*/
private void initializeDisplayMode(Bundle savedInstanceState) {
if (useSplitView()) {
displayMode = DisplayMode.SPLIT_VIEW;
return;
}
if (savedInstanceState != null) {
DisplayMode savedDisplayMode =
(DisplayMode) savedInstanceState.getSerializable(STATE_DISPLAY_MODE);
if (savedDisplayMode != DisplayMode.SPLIT_VIEW) {
displayMode = savedDisplayMode;
return;
}
}
if (messageViewFragment != null || messageReference != null) {
displayMode = DisplayMode.MESSAGE_VIEW;
} else {
displayMode = DisplayMode.MESSAGE_LIST;
}
}
private boolean useSplitView() {
SplitViewMode splitViewMode = K9.getSplitViewMode();
int orientation = getResources().getConfiguration().orientation;
return (splitViewMode == SplitViewMode.ALWAYS ||
(splitViewMode == SplitViewMode.WHEN_IN_LANDSCAPE &&
orientation == Configuration.ORIENTATION_LANDSCAPE));
}
private void initializeLayout() {
messageViewContainer = findViewById(R.id.message_view_container);
LayoutInflater layoutInflater = getLayoutInflater();
messageViewPlaceHolder = layoutInflater.inflate(R.layout.empty_message_view, messageViewContainer, false);
}
private void displayViews() {
switch (displayMode) {
case MESSAGE_LIST: {
showMessageList();
break;
}
case MESSAGE_VIEW: {
showMessageView();
break;
}
case SPLIT_VIEW: {
messageListWasDisplayed = true;
if (messageViewFragment == null) {
showMessageViewPlaceHolder();
} else {
MessageReference activeMessage = messageViewFragment.getMessageReference();
if (activeMessage != null) {
messageListFragment.setActiveMessage(activeMessage);
}
}
break;
}
}
}
private boolean decodeExtras(Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_VIEW.equals(action) && intent.getData() != null) {
Uri uri = intent.getData();
List<String> segmentList = uri.getPathSegments();
String accountId = segmentList.get(0);
Collection<Account> accounts = preferences.getAvailableAccounts();
for (Account account : accounts) {
if (String.valueOf(account.getAccountNumber()).equals(accountId)) {
String folderServerId = segmentList.get(1);
String messageUid = segmentList.get(2);
messageReference = new MessageReference(account.getUuid(), folderServerId, messageUid, null);
break;
}
}
} else if (ACTION_SHORTCUT.equals(action)) {
// Handle shortcut intents
String specialFolder = intent.getStringExtra(EXTRA_SPECIAL_FOLDER);
if (SearchAccount.UNIFIED_INBOX.equals(specialFolder)) {
search = SearchAccount.createUnifiedInboxAccount().getRelatedSearch();
} else if (SearchAccount.ALL_MESSAGES.equals(specialFolder)) {
search = SearchAccount.createAllMessagesAccount().getRelatedSearch();
}
} else if (intent.getStringExtra(SearchManager.QUERY) != null) {
// check if this intent comes from the system search ( remote )
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
//Query was received from Search Dialog
String query = intent.getStringExtra(SearchManager.QUERY).trim();
search = new LocalSearch(getString(R.string.search_results));
search.setManualSearch(true);
noThreading = true;
search.or(new SearchCondition(SearchField.SENDER, Attribute.CONTAINS, query));
search.or(new SearchCondition(SearchField.SUBJECT, Attribute.CONTAINS, query));
search.or(new SearchCondition(SearchField.MESSAGE_CONTENTS, Attribute.CONTAINS, query));
Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
if (appData != null) {
search.addAccountUuid(appData.getString(EXTRA_SEARCH_ACCOUNT));
// searches started from a folder list activity will provide an account, but no folder
if (appData.getString(EXTRA_SEARCH_FOLDER) != null) {
search.addAllowedFolder(appData.getString(EXTRA_SEARCH_FOLDER));
}
} else {
search.addAccountUuid(LocalSearch.ALL_ACCOUNTS);
}
}
} else {
// regular LocalSearch object was passed
search = intent.hasExtra(EXTRA_SEARCH) ?
ParcelableUtil.unmarshall(intent.getByteArrayExtra(EXTRA_SEARCH), LocalSearch.CREATOR) : null;
noThreading = intent.getBooleanExtra(EXTRA_NO_THREADING, false);
}
if (messageReference == null) {
String messageReferenceString = intent.getStringExtra(EXTRA_MESSAGE_REFERENCE);
messageReference = MessageReference.parse(messageReferenceString);
}
if (messageReference != null) {
search = new LocalSearch();
search.addAccountUuid(messageReference.getAccountUuid());
String folderServerId = messageReference.getFolderServerId();
search.addAllowedFolder(folderServerId);
}
if (search == null) {
// We've most likely been started by an old unread widget
String accountUuid = intent.getStringExtra("account");
String folderServerId = intent.getStringExtra("folder");
search = new LocalSearch(folderServerId);
search.addAccountUuid((accountUuid == null) ? "invalid" : accountUuid);
if (folderServerId != null) {
search.addAllowedFolder(folderServerId);
}
}
initializeFromLocalSearch(search);
if (account != null && !account.isAvailable(this)) {
Timber.i("not opening MessageList of unavailable account");
onAccountUnavailable();
return false;
}
return true;
}
private void checkAndRequestPermissions() {
if (!hasPermission(Permission.READ_CONTACTS)) {
requestPermissionOrShowRationale(Permission.READ_CONTACTS);
}
}
@Override
public void onPause() {
super.onPause();
StorageManager.getInstance(getApplication()).removeListener(mStorageListener);
}
@Override
public void onResume() {
super.onResume();
if (!(this instanceof Search)) {
//necessary b/c no guarantee Search.onStop will be called before MessageList.onResume
//when returning from search results
searchStatusManager.setActive(false);
}
if (account != null && !account.isAvailable(this)) {
onAccountUnavailable();
return;
}
StorageManager.getInstance(getApplication()).addListener(mStorageListener);
}
@Override
protected void onStart() {
super.onStart();
Contacts.clearCache();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(STATE_DISPLAY_MODE, displayMode);
outState.putBoolean(STATE_MESSAGE_LIST_WAS_DISPLAYED, messageListWasDisplayed);
outState.putInt(STATE_FIRST_BACK_STACK_ID, firstBackStackId);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
messageListWasDisplayed = savedInstanceState.getBoolean(STATE_MESSAGE_LIST_WAS_DISPLAYED);
firstBackStackId = savedInstanceState.getInt(STATE_FIRST_BACK_STACK_ID);
}
private void initializeActionBar() {
actionBar = getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(R.layout.actionbar_custom);
View customView = actionBar.getCustomView();
actionBarMessageList = customView.findViewById(R.id.actionbar_message_list);
actionBarTitle = customView.findViewById(R.id.actionbar_title_first);
actionBarSubTitle = customView.findViewById(R.id.actionbar_title_sub);
actionBarProgress = customView.findViewById(R.id.actionbar_progress);
actionButtonIndeterminateProgress = getActionButtonIndeterminateProgress();
actionBar.setDisplayHomeAsUpEnabled(true);
}
private void initializeDrawer(Bundle savedInstanceState) {
if (!isDrawerEnabled()) {
return;
}
drawer = new K9Drawer(this, savedInstanceState);
DrawerLayout drawerLayout = drawer.getLayout();
drawerToggle = new ActionBarDrawerToggle(
this, drawerLayout, null,
R.string.navigation_drawer_open, R.string.navigation_drawer_close
);
drawerLayout.addDrawerListener(drawerToggle);
drawerToggle.syncState();
}
public OnDrawerListener createOnDrawerListener() {
return new OnDrawerListener() {
@Override
public void onDrawerClosed(View drawerView) {
if (openFolderTransaction != null) {
openFolderTransaction.commit();
openFolderTransaction = null;
}
}
@Override
public void onDrawerOpened(View drawerView) {
// Do nothing
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
// Do nothing
}
};
}
public void openFolder(String folderName) {
LocalSearch search = new LocalSearch(folderName);
search.addAccountUuid(account.getUuid());
search.addAllowedFolder(folderName);
performSearch(search);
}
public void openUnifiedInbox() {
account = null;
drawer.selectUnifiedInbox();
actionDisplaySearch(this, SearchAccount.createUnifiedInboxAccount().getRelatedSearch(), false, false);
}
public void openRealAccount(Account realAccount) {
if (realAccount.getAutoExpandFolder() == null) {
FolderList.actionHandleAccount(this, realAccount);
} else {
LocalSearch search = new LocalSearch(realAccount.getAutoExpandFolder());
search.addAllowedFolder(realAccount.getAutoExpandFolder());
search.addAccountUuid(realAccount.getUuid());
actionDisplaySearch(this, search, false, false);
}
}
private void performSearch(LocalSearch search) {
initializeFromLocalSearch(search);
FragmentManager fragmentManager = getSupportFragmentManager();
openFolderTransaction = fragmentManager.beginTransaction();
messageListFragment = MessageListFragment.newInstance(search, false, K9.isThreadedViewEnabled());
openFolderTransaction.replace(R.id.message_list_container, messageListFragment);
}
protected boolean isDrawerEnabled() {
return true;
}
@SuppressLint("InflateParams")
private View getActionButtonIndeterminateProgress() {
return getLayoutInflater().inflate(R.layout.actionbar_indeterminate_progress_actionview, null);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean ret = false;
if (KeyEvent.ACTION_DOWN == event.getAction()) {
ret = onCustomKeyDown(event.getKeyCode(), event);
}
if (!ret) {
ret = super.dispatchKeyEvent(event);
}
return ret;
}
@Override
public void onBackPressed() {
if (displayMode == DisplayMode.MESSAGE_VIEW && messageListWasDisplayed) {
showMessageList();
} else {
super.onBackPressed();
}
}
/**
* Handle hotkeys
*
* <p>
* This method is called by {@link #dispatchKeyEvent(KeyEvent)} before any view had the chance
* to consume this key event.
* </p>
*
* @param keyCode
* The value in {@code event.getKeyCode()}.
* @param event
* Description of the key event.
*
* @return {@code true} if this event was consumed.
*/
public boolean onCustomKeyDown(final int keyCode, final KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP: {
if (messageViewFragment != null && displayMode != DisplayMode.MESSAGE_LIST &&
K9.useVolumeKeysForNavigationEnabled()) {
showPreviousMessage();
return true;
} else if (displayMode != DisplayMode.MESSAGE_VIEW &&
K9.useVolumeKeysForListNavigationEnabled()) {
messageListFragment.onMoveUp();
return true;
}
break;
}
case KeyEvent.KEYCODE_VOLUME_DOWN: {
if (messageViewFragment != null && displayMode != DisplayMode.MESSAGE_LIST &&
K9.useVolumeKeysForNavigationEnabled()) {
showNextMessage();
return true;
} else if (displayMode != DisplayMode.MESSAGE_VIEW &&
K9.useVolumeKeysForListNavigationEnabled()) {
messageListFragment.onMoveDown();
return true;
}
break;
}
case KeyEvent.KEYCODE_C: {
messageListFragment.onCompose();
return true;
}
case KeyEvent.KEYCODE_Q: {
if (messageListFragment != null && messageListFragment.isSingleAccountMode()) {
onShowFolderList();
}
return true;
}
case KeyEvent.KEYCODE_O: {
messageListFragment.onCycleSort();
return true;
}
case KeyEvent.KEYCODE_I: {
messageListFragment.onReverseSort();
return true;
}
case KeyEvent.KEYCODE_DEL:
case KeyEvent.KEYCODE_D: {
if (displayMode == DisplayMode.MESSAGE_LIST) {
messageListFragment.onDelete();
} else if (messageViewFragment != null) {
messageViewFragment.onDelete();
}
return true;
}
case KeyEvent.KEYCODE_S: {
messageListFragment.toggleMessageSelect();
return true;
}
case KeyEvent.KEYCODE_G: {
if (displayMode == DisplayMode.MESSAGE_LIST) {
messageListFragment.onToggleFlagged();
} else if (messageViewFragment != null) {
messageViewFragment.onToggleFlagged();
}
return true;
}
case KeyEvent.KEYCODE_M: {
if (displayMode == DisplayMode.MESSAGE_LIST) {
messageListFragment.onMove();
} else if (messageViewFragment != null) {
messageViewFragment.onMove();
}
return true;
}
case KeyEvent.KEYCODE_V: {
if (displayMode == DisplayMode.MESSAGE_LIST) {
messageListFragment.onArchive();
} else if (messageViewFragment != null) {
messageViewFragment.onArchive();
}
return true;
}
case KeyEvent.KEYCODE_Y: {
if (displayMode == DisplayMode.MESSAGE_LIST) {
messageListFragment.onCopy();
} else if (messageViewFragment != null) {
messageViewFragment.onCopy();
}
return true;
}
case KeyEvent.KEYCODE_Z: {
if (displayMode == DisplayMode.MESSAGE_LIST) {
messageListFragment.onToggleRead();
} else if (messageViewFragment != null) {
messageViewFragment.onToggleRead();
}
return true;
}
case KeyEvent.KEYCODE_F: {
if (messageViewFragment != null) {
messageViewFragment.onForward();
}
return true;
}
case KeyEvent.KEYCODE_A: {
if (messageViewFragment != null) {
messageViewFragment.onReplyAll();
}
return true;
}
case KeyEvent.KEYCODE_R: {
if (messageViewFragment != null) {
messageViewFragment.onReply();
}
return true;
}
case KeyEvent.KEYCODE_J:
case KeyEvent.KEYCODE_P: {
if (messageViewFragment != null) {
showPreviousMessage();
}
return true;
}
case KeyEvent.KEYCODE_N:
case KeyEvent.KEYCODE_K: {
if (messageViewFragment != null) {
showNextMessage();
}
return true;
}
/* FIXME
case KeyEvent.KEYCODE_Z: {
messageViewFragment.zoom(event);
return true;
}*/
case KeyEvent.KEYCODE_H: {
Toast toast;
if (displayMode == DisplayMode.MESSAGE_LIST) {
toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG);
} else {
toast = Toast.makeText(this, R.string.message_view_help_key, Toast.LENGTH_LONG);
}
toast.show();
return true;
}
case KeyEvent.KEYCODE_DPAD_LEFT: {
if (messageViewFragment != null && displayMode == DisplayMode.MESSAGE_VIEW) {
return showPreviousMessage();
}
return false;
}
case KeyEvent.KEYCODE_DPAD_RIGHT: {
if (messageViewFragment != null && displayMode == DisplayMode.MESSAGE_VIEW) {
return showNextMessage();
}
return false;
}
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// Swallow these events too to avoid the audible notification of a volume change
if (K9.useVolumeKeysForListNavigationEnabled()) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
Timber.v("Swallowed key up.");
return true;
}
}
return super.onKeyUp(keyCode, event);
}
private void onAccounts() {
Accounts.listAccounts(this);
finish();
}
private void onShowFolderList() {
FolderList.actionHandleAccount(this, account);
finish();
}
private void onEditSettings() {
SettingsActivity.launch(this);
}
@Override
public boolean onSearchRequested() {
return messageListFragment.onSearchRequested();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (displayMode != DisplayMode.MESSAGE_VIEW && !isAdditionalMessageListDisplayed()) {
if (isDrawerEnabled()) {
if (drawer.isOpen()) {
drawer.close();
} else {
drawer.open();
}
} else {
finish();
}
} else {
goBack();
}
return true;
} else if (id == R.id.compose) {
messageListFragment.onCompose();
return true;
} else if (id == R.id.toggle_message_view_theme) {
onToggleTheme();
return true;
} else if (id == R.id.check_mail) { // MessageList
messageListFragment.checkMail();
return true;
} else if (id == R.id.set_sort_date) {
messageListFragment.changeSort(SortType.SORT_DATE);
return true;
} else if (id == R.id.set_sort_arrival) {
messageListFragment.changeSort(SortType.SORT_ARRIVAL);
return true;
} else if (id == R.id.set_sort_subject) {
messageListFragment.changeSort(SortType.SORT_SUBJECT);
return true;
} else if (id == R.id.set_sort_sender) {
messageListFragment.changeSort(SortType.SORT_SENDER);
return true;
} else if (id == R.id.set_sort_flag) {
messageListFragment.changeSort(SortType.SORT_FLAGGED);
return true;
} else if (id == R.id.set_sort_unread) {
messageListFragment.changeSort(SortType.SORT_UNREAD);
return true;
} else if (id == R.id.set_sort_attach) {
messageListFragment.changeSort(SortType.SORT_ATTACHMENT);
return true;
} else if (id == R.id.select_all) {
messageListFragment.selectAll();
return true;
} else if (id == R.id.settings) {
onEditSettings();
return true;
} else if (id == R.id.search) {
messageListFragment.onSearchRequested();
return true;
} else if (id == R.id.search_remote) {
messageListFragment.onRemoteSearch();
return true;
} else if (id == R.id.mark_all_as_read) {
messageListFragment.confirmMarkAllAsRead();
return true;
} else if (id == R.id.show_folder_list) {
onShowFolderList();
return true;
} else if (id == R.id.next_message) { // MessageView
showNextMessage();
return true;
} else if (id == R.id.previous_message) {
showPreviousMessage();
return true;
} else if (id == R.id.delete) {
messageViewFragment.onDelete();
return true;
} else if (id == R.id.reply) {
messageViewFragment.onReply();
return true;
} else if (id == R.id.reply_all) {
messageViewFragment.onReplyAll();
return true;
} else if (id == R.id.forward) {
messageViewFragment.onForward();
return true;
} else if (id == R.id.forward_as_attachment) {
messageViewFragment.onForwardAsAttachment();
return true;
} else if (id == R.id.share) {
messageViewFragment.onSendAlternate();
return true;
} else if (id == R.id.toggle_unread) {
messageViewFragment.onToggleRead();
return true;
} else if (id == R.id.archive || id == R.id.refile_archive) {
messageViewFragment.onArchive();
return true;
} else if (id == R.id.spam || id == R.id.refile_spam) {
messageViewFragment.onSpam();
return true;
} else if (id == R.id.move || id == R.id.refile_move) {
messageViewFragment.onMove();
return true;
} else if (id == R.id.copy || id == R.id.refile_copy) {
messageViewFragment.onCopy();
return true;
} else if (id == R.id.select_text) {
messageViewFragment.onSelectText();
return true;
} else if (id == R.id.show_headers || id == R.id.hide_headers) {
messageViewFragment.onToggleAllHeadersView();
updateMenu();
return true;
}
if (!singleFolderMode) {
// None of the options after this point are "safe" for search results
//TODO: This is not true for "unread" and "starred" searches in regular folders
return false;
}
if (id == R.id.send_messages) {
messageListFragment.onSendPendingMessages();
return true;
} else if (id == R.id.expunge) {
messageListFragment.onExpunge();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.message_list_option, menu);
this.menu = menu;
menuButtonCheckMail = menu.findItem(R.id.check_mail);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
configureMenu(menu);
return true;
}
/**
* Hide menu items not appropriate for the current context.
*
* <p><strong>Note:</strong>
* Please adjust the comments in {@code res/menu/message_list_option.xml} if you change the
* visibility of a menu item in this method.
* </p>
*
* @param menu
* The {@link Menu} instance that should be modified. May be {@code null}; in that case
* the method does nothing and immediately returns.
*/
private void configureMenu(Menu menu) {
if (menu == null) {
return;
}
/*
* Set visibility of menu items related to the message view
*/
if (displayMode == DisplayMode.MESSAGE_LIST
|| messageViewFragment == null
|| !messageViewFragment.isInitialized()) {
menu.findItem(R.id.next_message).setVisible(false);
menu.findItem(R.id.previous_message).setVisible(false);
menu.findItem(R.id.single_message_options).setVisible(false);
menu.findItem(R.id.delete).setVisible(false);
menu.findItem(R.id.compose).setVisible(false);
menu.findItem(R.id.archive).setVisible(false);
menu.findItem(R.id.move).setVisible(false);
menu.findItem(R.id.copy).setVisible(false);
menu.findItem(R.id.spam).setVisible(false);
menu.findItem(R.id.refile).setVisible(false);
menu.findItem(R.id.toggle_unread).setVisible(false);
menu.findItem(R.id.select_text).setVisible(false);
menu.findItem(R.id.toggle_message_view_theme).setVisible(false);
menu.findItem(R.id.show_headers).setVisible(false);
menu.findItem(R.id.hide_headers).setVisible(false);
} else {
// hide prev/next buttons in split mode
if (displayMode != DisplayMode.MESSAGE_VIEW) {
menu.findItem(R.id.next_message).setVisible(false);
menu.findItem(R.id.previous_message).setVisible(false);
} else {
MessageReference ref = messageViewFragment.getMessageReference();
boolean initialized = (messageListFragment != null &&
messageListFragment.isLoadFinished());
boolean canDoPrev = (initialized && !messageListFragment.isFirst(ref));
boolean canDoNext = (initialized && !messageListFragment.isLast(ref));
MenuItem prev = menu.findItem(R.id.previous_message);
prev.setEnabled(canDoPrev);
prev.getIcon().setAlpha(canDoPrev ? 255 : 127);
MenuItem next = menu.findItem(R.id.next_message);
next.setEnabled(canDoNext);
next.getIcon().setAlpha(canDoNext ? 255 : 127);
}
MenuItem toggleTheme = menu.findItem(R.id.toggle_message_view_theme);
if (K9.useFixedMessageViewTheme()) {
toggleTheme.setVisible(false);
} else {
// Set title of menu item to switch to dark/light theme
if (K9.getK9MessageViewTheme() == K9.Theme.DARK) {
toggleTheme.setTitle(R.string.message_view_theme_action_light);
} else {
toggleTheme.setTitle(R.string.message_view_theme_action_dark);
}
toggleTheme.setVisible(true);
}
// Set title of menu item to toggle the read state of the currently displayed message
int[] drawableAttr;
if (messageViewFragment.isMessageRead()) {
menu.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_unread_action);
drawableAttr = new int[] { R.attr.iconActionMarkAsUnread };
} else {
menu.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_read_action);
drawableAttr = new int[] { R.attr.iconActionMarkAsRead };
}
TypedArray ta = obtainStyledAttributes(drawableAttr);
menu.findItem(R.id.toggle_unread).setIcon(ta.getDrawable(0));
ta.recycle();
// Jellybean has built-in long press selection support
menu.findItem(R.id.select_text).setVisible(Build.VERSION.SDK_INT < 16);
menu.findItem(R.id.delete).setVisible(K9.isMessageViewDeleteActionVisible());
/*
* Set visibility of copy, move, archive, spam in action bar and refile submenu
*/
if (messageViewFragment.isCopyCapable()) {
menu.findItem(R.id.copy).setVisible(K9.isMessageViewCopyActionVisible());
menu.findItem(R.id.refile_copy).setVisible(true);
} else {
menu.findItem(R.id.copy).setVisible(false);
menu.findItem(R.id.refile_copy).setVisible(false);
}
if (messageViewFragment.isMoveCapable()) {
boolean canMessageBeArchived = messageViewFragment.canMessageBeArchived();
boolean canMessageBeMovedToSpam = messageViewFragment.canMessageBeMovedToSpam();
menu.findItem(R.id.move).setVisible(K9.isMessageViewMoveActionVisible());
menu.findItem(R.id.archive).setVisible(canMessageBeArchived &&
K9.isMessageViewArchiveActionVisible());
menu.findItem(R.id.spam).setVisible(canMessageBeMovedToSpam &&
K9.isMessageViewSpamActionVisible());
menu.findItem(R.id.refile_move).setVisible(true);
menu.findItem(R.id.refile_archive).setVisible(canMessageBeArchived);
menu.findItem(R.id.refile_spam).setVisible(canMessageBeMovedToSpam);
} else {
menu.findItem(R.id.move).setVisible(false);
menu.findItem(R.id.archive).setVisible(false);
menu.findItem(R.id.spam).setVisible(false);
menu.findItem(R.id.refile).setVisible(false);
}
if (messageViewFragment.allHeadersVisible()) {
menu.findItem(R.id.show_headers).setVisible(false);
} else {
menu.findItem(R.id.hide_headers).setVisible(false);
}
}
/*
* Set visibility of menu items related to the message list
*/
// Hide both search menu items by default and enable one when appropriate
menu.findItem(R.id.search).setVisible(false);
menu.findItem(R.id.search_remote).setVisible(false);
if (displayMode == DisplayMode.MESSAGE_VIEW || messageListFragment == null ||
!messageListFragment.isInitialized()) {
menu.findItem(R.id.check_mail).setVisible(false);
menu.findItem(R.id.set_sort).setVisible(false);
menu.findItem(R.id.select_all).setVisible(false);
menu.findItem(R.id.send_messages).setVisible(false);
menu.findItem(R.id.expunge).setVisible(false);
menu.findItem(R.id.mark_all_as_read).setVisible(false);
menu.findItem(R.id.show_folder_list).setVisible(false);
} else {
menu.findItem(R.id.set_sort).setVisible(true);
menu.findItem(R.id.select_all).setVisible(true);
menu.findItem(R.id.compose).setVisible(true);
menu.findItem(R.id.mark_all_as_read).setVisible(
messageListFragment.isMarkAllAsReadSupported());
if (!messageListFragment.isSingleAccountMode()) {
menu.findItem(R.id.expunge).setVisible(false);
menu.findItem(R.id.send_messages).setVisible(false);
menu.findItem(R.id.show_folder_list).setVisible(false);
} else {
menu.findItem(R.id.send_messages).setVisible(messageListFragment.isOutbox());
menu.findItem(R.id.expunge).setVisible(messageListFragment.isRemoteFolder() &&
messageListFragment.isAccountExpungeCapable());
menu.findItem(R.id.show_folder_list).setVisible(true);
}
menu.findItem(R.id.check_mail).setVisible(messageListFragment.isCheckMailSupported());
// If this is an explicit local search, show the option to search on the server
if (!messageListFragment.isRemoteSearch() &&
messageListFragment.isRemoteSearchAllowed()) {
menu.findItem(R.id.search_remote).setVisible(true);
} else if (!messageListFragment.isManualSearch()) {
menu.findItem(R.id.search).setVisible(true);
}
}
}
protected void onAccountUnavailable() {
finish();
// TODO inform user about account unavailability using Toast
Accounts.listAccounts(this);
}
public void setActionBarTitle(String title) {
actionBarTitle.setText(title);
}
public void setActionBarSubTitle(String subTitle) {
actionBarSubTitle.setText(subTitle);
}
@Override
public void setMessageListTitle(String title) {
setActionBarTitle(title);
}
@Override
public void setMessageListSubTitle(String subTitle) {
setActionBarSubTitle(subTitle);
}
@Override
public void setMessageListProgress(int progress) {
setProgress(progress);
}
@Override
public void openMessage(MessageReference messageReference) {
Account account = preferences.getAccount(messageReference.getAccountUuid());
String folderServerId = messageReference.getFolderServerId();
if (folderServerId.equals(account.getDraftsFolder())) {
MessageActions.actionEditDraft(this, messageReference);
} else {
messageViewContainer.removeView(messageViewPlaceHolder);
if (messageListFragment != null) {
messageListFragment.setActiveMessage(messageReference);
}
MessageViewFragment fragment = MessageViewFragment.newInstance(messageReference);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.message_view_container, fragment);
messageViewFragment = fragment;
ft.commit();
if (displayMode != DisplayMode.SPLIT_VIEW) {
showMessageView();
}
}
}
@Override
public void onResendMessage(MessageReference messageReference) {
MessageActions.actionEditDraft(this, messageReference);
}
@Override
public void onForward(MessageReference messageReference) {
onForward(messageReference, null);
}
@Override
public void onForward(MessageReference messageReference, Parcelable decryptionResultForReply) {
MessageActions.actionForward(this, messageReference, decryptionResultForReply);
}
@Override
public void onForwardAsAttachment(MessageReference messageReference) {
onForwardAsAttachment(messageReference, null);
}
@Override
public void onForwardAsAttachment(MessageReference messageReference, Parcelable decryptionResultForReply) {
MessageActions.actionForwardAsAttachment(this, messageReference, decryptionResultForReply);
}
@Override
public void onReply(MessageReference messageReference) {
onReply(messageReference, null);
}
@Override
public void onReply(MessageReference messageReference, Parcelable decryptionResultForReply) {
MessageActions.actionReply(this, messageReference, false, decryptionResultForReply);
}
@Override
public void onReplyAll(MessageReference messageReference) {
onReplyAll(messageReference, null);
}
@Override
public void onReplyAll(MessageReference messageReference, Parcelable decryptionResultForReply) {
MessageActions.actionReply(this, messageReference, true, decryptionResultForReply);
}
@Override
public void onCompose(Account account) {
MessageActions.actionCompose(this, account);
}
@Override
public void showMoreFromSameSender(String senderAddress) {
LocalSearch tmpSearch = new LocalSearch(getString(R.string.search_from_format, senderAddress));
tmpSearch.addAccountUuids(search.getAccountUuids());
tmpSearch.and(SearchField.SENDER, senderAddress, Attribute.CONTAINS);
initializeFromLocalSearch(tmpSearch);
MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, false, false);
addMessageListFragment(fragment, true);
}
@Override
public void onBackStackChanged() {
findFragments();
if (isDrawerEnabled() && !isAdditionalMessageListDisplayed()) {
unlockDrawer();
}
if (displayMode == DisplayMode.SPLIT_VIEW) {
showMessageViewPlaceHolder();
}
configureMenu(menu);
}
@Override
public void onSwipeRightToLeft(MotionEvent e1, MotionEvent e2) {
// Disabled because it interferes with the bezel swipe for the drawer
// if (messageListFragment != null && displayMode != DisplayMode.MESSAGE_VIEW) {
// messageListFragment.onSwipeRightToLeft(e1, e2);
}
@Override
public void onSwipeLeftToRight(MotionEvent e1, MotionEvent e2) {
// Disabled because it interferes with the bezel swipe for the drawer
// if (messageListFragment != null && displayMode != DisplayMode.MESSAGE_VIEW) {
// messageListFragment.onSwipeLeftToRight(e1, e2);
}
private final class StorageListenerImplementation implements StorageManager.StorageListener {
@Override
public void onUnmount(String providerId) {
if (account != null && providerId.equals(account.getLocalStorageProviderId())) {
runOnUiThread(new Runnable() {
@Override
public void run() {
onAccountUnavailable();
}
});
}
}
@Override
public void onMount(String providerId) {
// no-op
}
}
private void addMessageListFragment(MessageListFragment fragment, boolean addToBackStack) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.message_list_container, fragment);
if (addToBackStack)
ft.addToBackStack(null);
messageListFragment = fragment;
if (isDrawerEnabled()) {
lockDrawer();
}
int transactionId = ft.commit();
if (transactionId >= 0 && firstBackStackId < 0) {
firstBackStackId = transactionId;
}
}
@Override
public boolean startSearch(Account account, String folderServerId) {
// If this search was started from a MessageList of a single folder, pass along that folder info
// so that we can enable remote search.
if (account != null && folderServerId != null) {
final Bundle appData = new Bundle();
appData.putString(EXTRA_SEARCH_ACCOUNT, account.getUuid());
appData.putString(EXTRA_SEARCH_FOLDER, folderServerId);
startSearch(null, false, appData, false);
} else {
// TODO Handle the case where we're searching from within a search result.
startSearch(null, false, null, false);
}
return true;
}
@Override
public void showThread(Account account, String folderServerId, long threadRootId) {
showMessageViewPlaceHolder();
LocalSearch tmpSearch = new LocalSearch();
tmpSearch.addAccountUuid(account.getUuid());
tmpSearch.and(SearchField.THREAD_ID, String.valueOf(threadRootId), Attribute.EQUALS);
initializeFromLocalSearch(tmpSearch);
MessageListFragment fragment = MessageListFragment.newInstance(tmpSearch, true, false);
addMessageListFragment(fragment, true);
}
private void showMessageViewPlaceHolder() {
removeMessageViewFragment();
// Add placeholder view if necessary
if (messageViewPlaceHolder.getParent() == null) {
messageViewContainer.addView(messageViewPlaceHolder);
}
messageListFragment.setActiveMessage(null);
}
/**
* Remove MessageViewFragment if necessary.
*/
private void removeMessageViewFragment() {
if (messageViewFragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.remove(messageViewFragment);
messageViewFragment = null;
ft.commit();
showDefaultTitleView();
}
}
private void removeMessageListFragment() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.remove(messageListFragment);
messageListFragment = null;
ft.commit();
}
@Override
public void remoteSearchStarted() {
// Remove action button for remote search
configureMenu(menu);
}
@Override
public void goBack() {
FragmentManager fragmentManager = getSupportFragmentManager();
if (displayMode == DisplayMode.MESSAGE_VIEW) {
showMessageList();
} else if (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStack();
} else if (messageListFragment.isManualSearch()) {
finish();
} else if (!singleFolderMode) {
onAccounts();
} else {
onShowFolderList();
}
}
@Override
public void enableActionBarProgress(boolean enable) {
if (menuButtonCheckMail != null && menuButtonCheckMail.isVisible()) {
actionBarProgress.setVisibility(ProgressBar.GONE);
if (enable) {
menuButtonCheckMail
.setActionView(actionButtonIndeterminateProgress);
} else {
menuButtonCheckMail.setActionView(null);
}
} else {
if (menuButtonCheckMail != null)
menuButtonCheckMail.setActionView(null);
if (enable) {
actionBarProgress.setVisibility(ProgressBar.VISIBLE);
} else {
actionBarProgress.setVisibility(ProgressBar.GONE);
}
}
}
@Override
public void showNextMessageOrReturn() {
if (K9.messageViewReturnToList() || !showLogicalNextMessage()) {
if (displayMode == DisplayMode.SPLIT_VIEW) {
showMessageViewPlaceHolder();
} else {
showMessageList();
}
}
}
/**
* Shows the next message in the direction the user was displaying messages.
*
* @return {@code true}
*/
private boolean showLogicalNextMessage() {
boolean result = false;
if (lastDirection == NEXT) {
result = showNextMessage();
} else if (lastDirection == PREVIOUS) {
result = showPreviousMessage();
}
if (!result) {
result = showNextMessage() || showPreviousMessage();
}
return result;
}
@Override
public void setProgress(boolean enable) {
setProgressBarIndeterminateVisibility(enable);
}
private boolean showNextMessage() {
MessageReference ref = messageViewFragment.getMessageReference();
if (ref != null) {
if (messageListFragment.openNext(ref)) {
lastDirection = NEXT;
return true;
}
}
return false;
}
private boolean showPreviousMessage() {
MessageReference ref = messageViewFragment.getMessageReference();
if (ref != null) {
if (messageListFragment.openPrevious(ref)) {
lastDirection = PREVIOUS;
return true;
}
}
return false;
}
private void showMessageList() {
messageListWasDisplayed = true;
displayMode = DisplayMode.MESSAGE_LIST;
viewSwitcher.showFirstView();
messageListFragment.setActiveMessage(null);
if (isDrawerEnabled()) {
if (isAdditionalMessageListDisplayed()) {
lockDrawer();
} else {
unlockDrawer();
}
}
showDefaultTitleView();
configureMenu(menu);
}
private void showMessageView() {
displayMode = DisplayMode.MESSAGE_VIEW;
if (!messageListWasDisplayed) {
viewSwitcher.setAnimateFirstView(false);
}
viewSwitcher.showSecondView();
if (isDrawerEnabled()) {
lockDrawer();
}
showMessageTitleView();
configureMenu(menu);
}
@Override
public void updateMenu() {
invalidateOptionsMenu();
}
@Override
public void disableDeleteAction() {
menu.findItem(R.id.delete).setEnabled(false);
}
private void onToggleTheme() {
if (K9.getK9MessageViewTheme() == K9.Theme.DARK) {
K9.setK9MessageViewThemeSetting(K9.Theme.LIGHT);
} else {
K9.setK9MessageViewThemeSetting(K9.Theme.DARK);
}
new Thread(new Runnable() {
@Override
public void run() {
StorageEditor editor = preferences.getStorage().edit();
K9.save(editor);
editor.commit();
}
}).start();
recreate();
}
private void showDefaultTitleView() {
actionBarMessageList.setVisibility(View.VISIBLE);
if (messageListFragment != null) {
messageListFragment.updateTitle();
}
}
private void showMessageTitleView() {
actionBarMessageList.setVisibility(View.GONE);
}
@Override
public void onSwitchComplete(int displayedChild) {
if (displayedChild == 0) {
removeMessageViewFragment();
}
}
@Override
public void startIntentSenderForResult(IntentSender intent, int requestCode, Intent fillInIntent,
int flagsMask, int flagsValues, int extraFlags) throws SendIntentException {
requestCode |= REQUEST_MASK_PENDING_INTENT;
super.startIntentSenderForResult(intent, requestCode, fillInIntent, flagsMask, flagsValues, extraFlags);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode & REQUEST_MASK_PENDING_INTENT) == REQUEST_MASK_PENDING_INTENT) {
requestCode ^= REQUEST_MASK_PENDING_INTENT;
if (messageViewFragment != null) {
messageViewFragment.onPendingIntentResult(requestCode, resultCode, data);
}
}
}
private boolean isAdditionalMessageListDisplayed() {
FragmentManager fragmentManager = getSupportFragmentManager();
return fragmentManager.getBackStackEntryCount() > 0;
}
private void lockDrawer() {
drawer.lock();
drawerToggle.setDrawerIndicatorEnabled(false);
}
private void unlockDrawer() {
drawer.unlock();
drawerToggle.setDrawerIndicatorEnabled(true);
}
private void initializeFromLocalSearch(LocalSearch search) {
this.search = search;
singleFolderMode = false;
if (search.searchAllAccounts()) {
account = null;
} else {
String[] accountUuids = search.getAccountUuids();
if (accountUuids.length == 1) {
account = preferences.getAccount(accountUuids[0]);
List<String> folderServerIds = search.getFolderServerIds();
singleFolderMode = folderServerIds.size() == 1;
} else {
account = null;
}
}
configureDrawer();
// now we know if we are in single account mode and need a subtitle
actionBarSubTitle.setVisibility((!singleFolderMode) ? View.GONE : View.VISIBLE);
}
private void configureDrawer() {
if (drawer == null)
return;
if (singleFolderMode) {
drawer.selectFolder(search.getFolderServerIds().get(0));
} else if (search.getId().equals(SearchAccount.UNIFIED_INBOX)) {
drawer.selectUnifiedInbox();
} else {
drawer.selectFolder(null);
}
}
}
|
package org.wisdom.api.http;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.wisdom.api.bodies.NoHttpBody;
import org.wisdom.api.bodies.RenderableJson;
import org.wisdom.api.bodies.RenderableObject;
import org.wisdom.api.bodies.RenderableString;
import org.wisdom.api.cookies.Cookie;
import org.wisdom.api.utils.DateUtil;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
/**
* A result is an object returned by a controller action.
* It will be merge with the response.
*/
public class Result implements Status {
/**
* The status code.
*/
private int statusCode;
/**
* The content.
*/
private Renderable<?> content;
/**
* Something like: "utf-8" => will be appended to the content-type. eg
* "text/html; charset=utf-8"
*/
private Charset charset;
/**
* The headers.
*/
private Map<String, String> headers;
/**
* The cookies.
*/
private List<Cookie> cookies;
/**
* A result. Sets utf-8 as charset and status code by default.
* Refer to {@link Status#OK}, {@link Status#NO_CONTENT} and so on
* for some short cuts to predefined results.
*
* @param statusCode The status code to set for the result. Shortcuts to the code at: {@link Status#OK}
*/
public Result(int statusCode) {
this();
this.statusCode = statusCode;
}
/**
* A result. Sets utf-8 as charset and status code by default.
* Refer to {@link Status#OK}, {@link Status#NO_CONTENT} and so on
* for some short cuts to predefined results.
*/
public Result() {
this.headers = Maps.newHashMap();
this.cookies = Lists.newArrayList();
}
public Renderable<?> getRenderable() {
return content;
}
/**
* Sets this renderable as object to render. Usually this renderable
* does rendering itself and will not call any templating engine.
*
* @param renderable The renderable that will handle everything after returning the result.
* @return This result for chaining.
*/
public Result render(Renderable<?> renderable) {
this.content = renderable;
return this;
}
public Result render(Object object) {
if (object instanceof Renderable) {
this.content = (Renderable<?>) object;
} else {
this.content = new RenderableObject(object);
}
return this;
}
public Result render(Exception e) {
this.content = new RenderableObject(e);
return this;
}
public Result render(ObjectNode node) {
this.content = new RenderableJson(node);
return this;
}
public Result render(String content) {
this.content = new RenderableString(content);
return this;
}
public Result render(CharSequence content) {
this.content = new RenderableString(content);
return this;
}
public Result render(StringBuilder content) {
this.content = new RenderableString(content);
return this;
}
public Result render(StringBuffer content) {
this.content = new RenderableString(content);
return this;
}
public String getContentType() {
return headers.get(HeaderNames.CONTENT_TYPE);
}
private void setContentType(String contentType){
headers.put(HeaderNames.CONTENT_TYPE, contentType);
}
/**
* @return Charset of the current result that will be used. Will be "utf-8"
* by default.
*/
public Charset getCharset() {
return charset;
}
/**
* @return Set the charset of the result. Is "utf-8" by default.
*/
public Result with(Charset charset) {
this.charset = charset;
return this;
}
/**
* @return the full content-type containing the mime type and the charset if set.
*/
public String getFullContentType() {
if (getContentType() == null) {
// Will use the renderable content type.
return null;
}
Charset localCharset = getCharset();
if (localCharset == null) {
return getContentType();
} else {
return getContentType() + "; " + localCharset.displayName();
}
}
/**
* Sets the content type. Must not contain any charset WRONG:
* "text/html; charset=utf8".
* <p/>
* If you want to set the charset use method {@link Result#with(Charset)};
*
* @param contentType (without encoding) something like "text/html" or
* "application/json"
*/
public Result as(String contentType) {
setContentType(contentType);
return this;
}
public Map<String, String> getHeaders() {
return headers;
}
public Result with(String headerName, String headerContent) {
headers.put(headerName, headerContent);
return this;
}
/**
* Returns cookie with that name or null.
*
* @param cookieName Name of the cookie
* @return The cookie or null if not found.
*/
public Cookie getCookie(String cookieName) {
for (Cookie cookie : getCookies()) {
if (cookie.name().equals(cookieName)) {
return cookie;
}
}
return null;
}
public List<Cookie> getCookies() {
return cookies;
}
public Result with(Cookie cookie) {
cookies.add(cookie);
return this;
}
public Result without(String name) {
String v = headers.remove(name);
if (v == null && getCookie(name) != null) {
// It may be a cookie
discard(name);
}
return this;
}
public Result discard(String name) {
cookies.add(Cookie.builder(name, "").setMaxAge(0).build());
return this;
}
public int getStatusCode() {
return statusCode;
}
/**
* Set the status of this result.
* Refer to {@link Status#OK}, {@link Status#NO_CONTENT} and so on
* for some short cuts to predefined results.
*
* @param statusCode The status code. Result ({@link Status#OK}) provides some helpers.
* @return The result you executed the method on for method chaining.
*/
public Result status(int statusCode) {
this.statusCode = statusCode;
return this;
}
/**
* A redirect that uses 303 see other.
*
* @param url The url used as redirect target.
* @return A nicely configured result with status code 303 and the url set
* as Location header.
*/
public Result redirect(String url) {
status(Status.SEE_OTHER);
with(Response.LOCATION, url);
return this;
}
/**
* A redirect that uses 307 see other.
*
* @param url The url used as redirect target.
* @return A nicely configured result with status code 307 and the url set
* as Location header.
*/
public Result redirectTemporary(String url) {
status(Status.TEMPORARY_REDIRECT);
with(Response.LOCATION, url);
return this;
}
/**
* Set the content type of this result to {@link MimeTypes#HTML}.
*
* @return the same result where you executed this method on. But the content type is now {@link MimeTypes#HTML}.
*/
public Result html() {
setContentType(MimeTypes.HTML);
charset = Charsets.UTF_8;
return this;
}
/**
* Set the content type of this result to {@link MimeTypes#JSON}.
*
* @return the same result where you executed this method on. But the content type is now {@link MimeTypes#JSON}.
*/
public Result json() {
setContentType(MimeTypes.JSON);
charset = Charsets.UTF_8;
return this;
}
/**
* Set the content type of this result to {@link MimeTypes#XML}.
*
* @return the same result where you executed this method on. But the content type is now {@link MimeTypes#XML}.
*/
public Result xml() {
setContentType(MimeTypes.XML);
charset = Charsets.UTF_8;
return this;
}
public Result noCache() {
with(Response.CACHE_CONTROL, Response.NOCACHE_VALUE);
with(Response.DATE, DateUtil.formatForHttpHeader(System.currentTimeMillis()));
with(Response.EXPIRES, DateUtil.formatForHttpHeader(0L));
return this;
}
public void addCookie(Cookie cookie) {
cookies.add(cookie);
}
public Result noContentIfNone() {
if (content == null) {
content = new NoHttpBody();
}
return this;
}
}
|
package org.eclipse.birt.report.designer.ui.cubebuilder.dialog;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.IHelpContextIds;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.internal.ui.util.WidgetUtil;
import org.eclipse.birt.report.designer.ui.cubebuilder.nls.Messages;
import org.eclipse.birt.report.designer.ui.cubebuilder.provider.CubeExpressionProvider;
import org.eclipse.birt.report.designer.ui.cubebuilder.util.OlapUtil;
import org.eclipse.birt.report.designer.ui.dialogs.ExpressionBuilder;
import org.eclipse.birt.report.designer.ui.dialogs.ExpressionProvider;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.birt.report.designer.ui.widget.ExpressionCellEditor;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.LevelAttributeHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.RuleHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.birt.report.model.api.elements.structures.LevelAttribute;
import org.eclipse.birt.report.model.api.elements.structures.Rule;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.metadata.PropertyValueException;
import org.eclipse.birt.report.model.api.olap.TabularHierarchyHandle;
import org.eclipse.birt.report.model.api.olap.TabularLevelHandle;
import org.eclipse.birt.report.model.elements.interfaces.ILevelModel;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
public class LevelPropertyDialog extends TitleAreaDialog
{
// private Text intervalRange;
// private Button intervalBaseButton;
// private Text intervalBaseText;
private Composite dynamicArea;
private DataSetHandle dataset;
private IChoice[] getAvailableDataTypeChoices( )
{
IChoice[] dataTypes = DEUtil.getMetaDataDictionary( )
.getElement( ReportDesignConstants.LEVEL_ELEMENT )
.getProperty( ILevelModel.DATA_TYPE_PROP )
.getAllowedChoices( )
.getChoices( );
List choiceList = new ArrayList( );
for ( int i = 0; i < dataTypes.length; i++ )
{
// String name = dataTypes[i].getName( );
// if ( name.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME
// || name.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_DATE )
// || name.equals( DesignChoiceConstants.COLUMN_DATA_TYPE_TIME ) )
// continue;
choiceList.add( dataTypes[i] );
}
return (IChoice[]) choiceList.toArray( new IChoice[0] );
}
public String[] getDataTypeNames( )
{
IChoice[] choices = getAvailableDataTypeChoices( );
if ( choices == null )
return new String[0];
String[] names = new String[choices.length];
for ( int i = 0; i < choices.length; i++ )
{
names[i] = choices[i].getName( );
}
return names;
}
public String getDataTypeDisplayName( String name )
{
return ChoiceSetFactory.getDisplayNameFromChoiceSet( name,
DEUtil.getMetaDataDictionary( )
.getElement( ReportDesignConstants.LEVEL_ELEMENT )
.getProperty( ILevelModel.DATA_TYPE_PROP )
.getAllowedChoices( ) );
}
private String[] getDataTypeDisplayNames( )
{
IChoice[] choices = getAvailableDataTypeChoices( );
if ( choices == null )
return new String[0];
String[] displayNames = new String[choices.length];
for ( int i = 0; i < choices.length; i++ )
{
displayNames[i] = choices[i].getDisplayName( );
}
return displayNames;
}
private boolean isNew;
public LevelPropertyDialog( boolean isNew )
{
super( UIUtil.getDefaultShell( ) );
setShellStyle( getShellStyle( ) | SWT.RESIZE | SWT.MAX );
this.isNew = isNew;
}
protected Control createDialogArea( Composite parent )
{
// createTitleArea( parent );
UIUtil.bindHelp( parent, IHelpContextIds.LEVEL_PROPERTY_DIALOG ); //$NON-NLS-1$
getShell( ).setText( Messages.getString( "LevelPropertyDialog.Shell.Title" ) ); //$NON-NLS-1$
if ( isNew )
this.setTitle( Messages.getString( "LevelPropertyDialog.Title.Add" ) );
else
this.setTitle( Messages.getString( "LevelPropertyDialog.Title.Edit" ) );
this.setMessage( Messages.getString( "LevelPropertyDialog.Message" ) ); //$NON-NLS-1$
Composite area = (Composite) super.createDialogArea( parent );
Composite contents = new Composite( area, SWT.NONE );
GridLayout layout = new GridLayout( );
// layout.verticalSpacing = 10;
layout.marginWidth = 20;
contents.setLayout( layout );
GridData data = new GridData( GridData.FILL_BOTH );
data.widthHint = convertWidthInCharsToPixels( 80 );
data.heightHint = 400;
contents.setLayoutData( data );
// createInfoArea( contents );
createChoiceArea( contents );
dynamicArea = createDynamicArea( contents );
staticArea = createStaticArea( contents );
WidgetUtil.createGridPlaceholder( contents, 1, true );
initLevelDialog( );
parent.layout( );
return contents;
}
private void initLevelDialog( )
{
if ( input != null )
{
expressionEditor.setExpressionProvider( new CubeExpressionProvider( input ) );
}
if ( input.getLevelType( ) == null )
{
try
{
input.setLevelType( DesignChoiceConstants.LEVEL_TYPE_DYNAMIC );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
if ( input.getLevelType( )
.equals( DesignChoiceConstants.LEVEL_TYPE_DYNAMIC ) )
{
refreshDynamicViewer( );
dataset = ( (TabularHierarchyHandle) input.getContainer( ) ).getDataSet( );
if ( dataset != null )
attributeItems = OlapUtil.getDataFieldNames( dataset );
resetEditorItems( );
dynamicButton.setSelection( true );
if ( input.getName( ) != null )
nameText.setText( input.getName( ) );
dynamicDataTypeCombo.setItems( getDataTypeDisplayNames( ) );
dynamicDataTypeCombo.setText( getDataTypeDisplayName( input.getDataType( ) ) );
fieldCombo.setItems( OlapUtil.getDataFieldNames( dataset ) );
if ( input.getColumnName( ) != null )
fieldCombo.setText( input.getColumnName( ) );
else
fieldCombo.select( 0 );
displayKeyCombo.setItems( OlapUtil.getDataFieldNames( dataset ) );
displayKeyCombo.setItem( 0,
Messages.getString( "LevelPropertyDialog.None" ) ); //$NON-NLS-1$
displayKeyCombo.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
if ( displayKeyCombo.getSelectionIndex( ) > 0 )
{
displayKeyCombo.setText( DEUtil.getResultSetColumnExpression( displayKeyCombo.getText( ) ) );
}
}
} );
if ( input.getDisplayColumnName( ) != null )
{
displayKeyCombo.setText( input.getDisplayColumnName( ) );
}
else if ( displayKeyCombo.getItemCount( ) > 0 )
displayKeyCombo.select( 0 );
/*
* PropertyHandle property = input.getPropertyHandle(
* GroupElement.INTERVAL_RANGE_PROP ); String range = property ==
* null ? null : property.getStringValue( ); intervalRange.setText(
* range == null ? "" : range ); //$NON-NLS-1$ int width =
* intervalRange.computeSize( SWT.DEFAULT, SWT.DEFAULT ).x; (
* (GridData) intervalRange.getLayoutData( ) ).widthHint = width <
* 60 ? 60 : width; String interval = input.getInterval( ); if (
* interval == null || interval.equals(
* DesignChoiceConstants.INTERVAL_TYPE_NONE ) ) {
* updateRadioButtonStatus( noneIntervalButton ); } else if (
* interval.equals( DesignChoiceConstants.INTERVAL_TYPE_INTERVAL ) )
* updateRadioButtonStatus( intervalButton ); else if (
* interval.equals( DesignChoiceConstants.INTERVAL_TYPE_PREFIX ) )
* updateRadioButtonStatus( prefixButton ); if (
* !noneIntervalButton.getSelection( ) ) { intervalRange.setEnabled(
* true ); intervalBaseButton.setEnabled( true );
* intervalBaseButton.setSelection( input.getIntervalBase( ) != null );
* intervalBaseText.setEnabled( intervalBaseButton.getSelection( ) );
* if ( input.getIntervalBase( ) != null ) {
* intervalBaseText.setText( input.getIntervalBase( ) ); } }
*/
updateButtonStatus( dynamicButton );
}
else
{
staticDataTypeCombo.setItems( getDataTypeDisplayNames( ) );
staticNameText.setText( input.getName( ) );
staticDataTypeCombo.setText( getDataTypeDisplayName( input.getDataType( ) ) );
refreshStaticViewer( );
// dynamicViewer.setInput( dynamicAttributes );
staticButton.setSelection( true );
updateButtonStatus( staticButton );
}
}
private void refreshDynamicViewer( )
{
Iterator attrIter = input.attributesIterator( );
List attrList = new LinkedList( );
while ( attrIter.hasNext( ) )
{
attrList.add( attrIter.next( ) );
}
dynamicViewer.setInput( attrList );
}
private void refreshStaticViewer( )
{
Iterator valuesIter = input.staticValuesIterator( );
List valuesList = new LinkedList( );
while ( valuesIter.hasNext( ) )
{
valuesList.add( valuesIter.next( ) );
}
staticViewer.setInput( valuesList );
}
// private int getIntervalTypeIndex( String interval )
// int index = 0;
// for ( int i = 0; i < intervalChoices.length; i++ )
// if ( intervalChoices[i].getName( ).equals( interval ) )
// index = i;
// break;
// return index;
protected void okPressed( )
{
if ( dynamicButton.getSelection( ) )
{
try
{
input.setLevelType( DesignChoiceConstants.LEVEL_TYPE_DYNAMIC );
if ( nameText.getText( ) != null
&& !nameText.getText( ).trim( ).equals( "" ) ) //$NON-NLS-1$
{
input.setName( nameText.getText( ) );
}
if ( fieldCombo.getText( ) != null )
{
input.setColumnName( fieldCombo.getText( ) );
}
if ( displayKeyCombo.getText( ).trim( ).length( )>0 && !displayKeyCombo.getText( )
.equals( Messages.getString( "LevelPropertyDialog.None" ) ) )
{
input.setDisplayColumnName( displayKeyCombo.getText( ) );
}
else
input.setDisplayColumnName( null );
if ( dynamicDataTypeCombo.getText( ) != null )
{
input.setDataType( getDataTypeNames( )[dynamicDataTypeCombo.getSelectionIndex( )] );
}
/*
* if ( noneIntervalButton.getSelection( ) ) input.setInterval(
* DesignChoiceConstants.INTERVAL_TYPE_NONE ); else if (
* intervalButton.getSelection( ) ) input.setInterval(
* DesignChoiceConstants.INTERVAL_TYPE_INTERVAL ); else if (
* prefixButton.getSelection( ) ) input.setInterval(
* DesignChoiceConstants.INTERVAL_TYPE_PREFIX );
*
* if ( !noneIntervalButton.getSelection( ) ) {
* input.setIntervalRange( intervalRange.getText( ) ); } else {
* input.setProperty( GroupHandle.INTERVAL_RANGE_PROP, null ); }
* if ( intervalBaseText.getEnabled( ) ) {
* input.setIntervalBase( UIUtil.convertToModelString(
* intervalBaseText.getText( ), false ) ); } else {
* input.setIntervalBase( null ); }
*/
input.getPropertyHandle( ILevelModel.STATIC_VALUES_PROP )
.clearValue( );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
else if ( staticButton.getSelection( ) )
{
try
{
input.setLevelType( DesignChoiceConstants.LEVEL_TYPE_MIRRORED );
if ( staticNameText.getText( ) != null
&& !staticNameText.getText( ).trim( ).equals( "" ) ) //$NON-NLS-1$
{
input.setName( staticNameText.getText( ) );
}
if ( staticDataTypeCombo.getText( ) != null )
{
input.setDataType( getDataTypeNames( )[staticDataTypeCombo.getSelectionIndex( )] );
}
/*
* input.setInterval( null ); input.setIntervalRange( null );
* input.setProperty( GroupHandle.INTERVAL_RANGE_PROP, null );
* input.setIntervalBase( UIUtil.convertToModelString(
* intervalBaseText.getText( ), false ) );
* input.setIntervalBase( null );
*/
input.getPropertyHandle( ILevelModel.ATTRIBUTES_PROP )
.clearValue( );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
super.okPressed( );
}
private static final String dummyChoice = "dummy"; //$NON-NLS-1$
private IStructuredContentProvider contentProvider = new IStructuredContentProvider( ) {
public void dispose( )
{
}
public void inputChanged( Viewer viewer, Object oldInput,
Object newInput )
{
}
public Object[] getElements( Object input )
{
if ( input instanceof List )
{
List list = (List) input;
if ( !list.contains( dummyChoice ) )
list.add( dummyChoice );
// Object[] items = new Object[list.size( )+1];
// list.toArray( items );
// String[] elements = new String[items.length + 1];
// System.arraycopy( items, 0, elements, 0, items.length );
// Object[] elements = new Object[list.size( ) + 1];
// elements[elements.length - 1] = dummyChoice;
return list.toArray( );
}
// else if ( input instanceof Map )
// Map map = (Map) input;
// String[] items = new String[map.size( )];
// map.keySet( ).toArray( items );
// String[] elements = new String[items.length + 1];
// System.arraycopy( items, 0, elements, 0, items.length );
// elements[elements.length - 1] = dummyChoice;
// return elements;
return new Object[0];
}
};
private ITableLabelProvider staticLabelProvider = new ITableLabelProvider( ) {
public Image getColumnImage( Object element, int columnIndex )
{
return null;
}
public String getColumnText( Object element, int columnIndex )
{
if ( columnIndex == 1 )
{
if ( element == dummyChoice )
return Messages.getString( "LevelPropertyDialog.MSG.Static.CreateNew" ); //$NON-NLS-1$
else
{
if ( element instanceof RuleHandle )
{
return ( (RuleHandle) element ).getDisplayExpression( );
}
return ""; //$NON-NLS-1$
}
}
else if ( columnIndex == 2 )
{
if ( element == dummyChoice )
return ""; //$NON-NLS-1$
else
{
if ( element instanceof RuleHandle )
{
return ( (RuleHandle) element ).getRuleExpression( );
}
return ""; //$NON-NLS-1$
}
}
else
return ""; //$NON-NLS-1$
}
public void addListener( ILabelProviderListener listener )
{
}
public void dispose( )
{
}
public boolean isLabelProperty( Object element, String property )
{
return false;
}
public void removeListener( ILabelProviderListener listener )
{
}
};
private ITableLabelProvider dynamicLabelProvider = new ITableLabelProvider( ) {
public Image getColumnImage( Object element, int columnIndex )
{
return null;
}
public String getColumnText( Object element, int columnIndex )
{
if ( columnIndex == 1 )
{
if ( element == dummyChoice )
return Messages.getString( "LevelPropertyDialog.MSG.Dynamic.CreateNew" ); //$NON-NLS-1$
else
{
if ( element instanceof LevelAttributeHandle )
{
return ( (LevelAttributeHandle) element ).getName( );
}
}
}
return ""; //$NON-NLS-1$
}
public void addListener( ILabelProviderListener listener )
{
}
public void dispose( )
{
}
public boolean isLabelProperty( Object element, String property )
{
return false;
}
public void removeListener( ILabelProviderListener listener )
{
}
};
private ICellModifier dynamicCellModifier = new ICellModifier( ) {
public boolean canModify( Object element, String property )
{
return true;
}
public Object getValue( Object element, String property )
{
if ( element instanceof LevelAttributeHandle )
{
LevelAttributeHandle handle = (LevelAttributeHandle) element;
resetEditorItems( handle.getName( ) );
for ( int i = 0; i < editor.getItems( ).length; i++ )
if ( handle.getName( ).equals( editor.getItems( )[i] ) )
return new Integer( i );
}
if ( element instanceof String )
{
resetEditorItems( );
}
return new Integer( -1 );
}
public void modify( Object element, String property, Object value )
{
if ( element instanceof Item )
element = ( (Item) element ).getData( );
if ( ( (Integer) value ).intValue( ) > -1
&& ( (Integer) value ).intValue( ) < editor.getItems( ).length )
{
if ( element instanceof LevelAttributeHandle )
{
LevelAttributeHandle handle = (LevelAttributeHandle) element;
try
{
handle.setName( editor.getItems( )[( (Integer) value ).intValue( )] );
if ( dataset != null )
{
ResultSetColumnHandle dataField = OlapUtil.getDataField( dataset,
handle.getName( ) );
handle.setDataType( dataField.getDataType( ) );
}
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
else
{
LevelAttribute attribute = StructureFactory.createLevelAttribute( );
attribute.setName( editor.getItems( )[( (Integer) value ).intValue( )] );
if ( dataset != null )
{
ResultSetColumnHandle dataField = OlapUtil.getDataField( dataset,
attribute.getName( ) );
attribute.setDataType( dataField.getDataType( ) );
}
try
{
input.getPropertyHandle( ILevelModel.ATTRIBUTES_PROP )
.addItem( attribute );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
refreshDynamicViewer( );
}
}
};
private ICellModifier staticCellModifier = new ICellModifier( ) {
public boolean canModify( Object element, String property )
{
if ( property.equals( Prop_Name ) )
{
return true;
}
else
{
if ( element != dummyChoice )
return true;
else
return false;
}
}
public Object getValue( Object element, String property )
{
if ( property.equals( Prop_Name ) )
{
if ( element != dummyChoice )
{
if ( element instanceof RuleHandle )
return ( (RuleHandle) element ).getDisplayExpression( );
}
return ""; //$NON-NLS-1$
}
else
{
if ( element != dummyChoice )
{
if ( element instanceof RuleHandle )
{
String result = ( (RuleHandle) element ).getRuleExpression( );
return result == null ? "" : result; //$NON-NLS-1$
}
}
return ""; //$NON-NLS-1$
}
}
public void modify( Object element, String property, Object value )
{
if ( element instanceof Item )
{
element = ( (Item) element ).getData( );
}
if ( property.equals( Prop_Name )
&& !( value.toString( ).trim( ).equals( "" ) || value.equals( dummyChoice ) ) ) //$NON-NLS-1$
{
if ( element instanceof RuleHandle )
{
( (RuleHandle) element ).setDisplayExpression( value.toString( ) );
}
else
{
Rule rule = StructureFactory.createRule( );
rule.setProperty( Rule.DISPLAY_EXPRE_MEMBER,
value.toString( ) );
rule.setProperty( Rule.RULE_EXPRE_MEMBER, "" ); //$NON-NLS-1$
try
{
input.getPropertyHandle( ILevelModel.STATIC_VALUES_PROP )
.addItem( rule );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
refreshStaticViewer( );
}
else if ( property.equals( prop_Expression ) )
{
if ( element != dummyChoice
&& !( value.toString( ).trim( ).equals( "" ) ) ) //$NON-NLS-1$
{
if ( element instanceof RuleHandle )
{
( (RuleHandle) element ).setRuleExpression( value.toString( ) );
}
refreshStaticViewer( );
}
}
}
};
private int dynamicSelectIndex;
protected Composite createDynamicArea( Composite parent )
{
Composite contents = new Composite( parent, SWT.NONE );
GridLayout layout = new GridLayout( );
layout.marginWidth = 0;
layout.marginHeight = 0;
contents.setLayout( layout );
GridData data = new GridData( GridData.FILL_HORIZONTAL );
contents.setLayoutData( data );
Group groupGroup = new Group( contents, SWT.NONE );
layout = new GridLayout( );
layout.numColumns = 4;
groupGroup.setLayout( layout );
groupGroup.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
Label nameLabel = new Label( groupGroup, SWT.NONE );
nameLabel.setText( Messages.getString( "LevelDialog.Label.Name" ) ); //$NON-NLS-1$
nameText = new Text( groupGroup, SWT.BORDER );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 3;
nameText.setLayoutData( gd );
nameText.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
checkOkButtonStatus( );
}
} );
Label fieldLabel = new Label( groupGroup, SWT.NONE );
fieldLabel.setText( Messages.getString( "LevelPropertyDialog.KeyField" ) ); //$NON-NLS-1$
fieldCombo = new Combo( groupGroup, SWT.BORDER | SWT.READ_ONLY );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 3;
fieldCombo.setLayoutData( gd );
fieldCombo.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
checkOkButtonStatus( );
}
} );
Label displayKeyLabel = new Label( groupGroup, SWT.NONE );
displayKeyLabel.setText( Messages.getString( "LevelPropertyDialog.DisplayField" ) ); //$NON-NLS-1$
displayKeyCombo = new Combo( groupGroup, SWT.BORDER );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 2;
displayKeyCombo.setLayoutData( gd );
Button expressionButton = new Button( groupGroup, SWT.PUSH );
UIUtil.setExpressionButtonImage( expressionButton );
expressionButton.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent event )
{
openExpression( );
}
private void openExpression( )
{
ExpressionBuilder expressionBuilder = new ExpressionBuilder( displayKeyCombo.getText( ).trim( ).equals( Messages.getString( "LevelPropertyDialog.None" ) )?"":displayKeyCombo.getText( ).trim( ) );
ExpressionProvider provider = new CubeExpressionProvider( input );
expressionBuilder.setExpressionProvier( provider );
if ( expressionBuilder.open( ) == Window.OK )
{
displayKeyCombo.setText( expressionBuilder.getResult( ) );
}
}
} );
new Label( groupGroup, SWT.NONE ).setText( Messages.getString( "LevelPropertyDialog.DataType" ) ); //$NON-NLS-1$
dynamicDataTypeCombo = new Combo( groupGroup, SWT.BORDER
| SWT.READ_ONLY );
dynamicDataTypeCombo.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
dynamicDataTypeCombo.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
checkOkButtonStatus( );
}
} );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 3;
dynamicDataTypeCombo.setLayoutData( gd );
/*
* // Creates intervalRange labels new Label( groupGroup, SWT.NONE
* ).setText( Messages.getString( "LevelPropertyDialog.GroupBy" ) );
* //$NON-NLS-1$
*
* noneIntervalButton = new Button( groupGroup, SWT.RADIO );
* noneIntervalButton.setText( Messages.getString(
* "LevelPropertyDialog.Button.None" ) ); //$NON-NLS-1$
* noneIntervalButton.addSelectionListener( new SelectionAdapter( ) {
*
* public void widgetSelected( SelectionEvent e ) {
* updateRadioButtonStatus( noneIntervalButton ); } } ); intervalButton =
* new Button( groupGroup, SWT.RADIO ); intervalButton.setText(
* Messages.getString( "LevelPropertyDialog.Button.Interval" ) );
* //$NON-NLS-1$ intervalButton.addSelectionListener( new
* SelectionAdapter( ) {
*
* public void widgetSelected( SelectionEvent e ) {
* updateRadioButtonStatus( intervalButton ); } } ); prefixButton = new
* Button( groupGroup, SWT.RADIO ); prefixButton.setText(
* Messages.getString( "LevelPropertyDialog.Button.Prefix" ) );
* //$NON-NLS-1$ prefixButton.addSelectionListener( new
* SelectionAdapter( ) {
*
* public void widgetSelected( SelectionEvent e ) {
* updateRadioButtonStatus( prefixButton ); } } ); new Label(
* groupGroup, SWT.NONE ).setText( Messages.getString(
* "LevelPropertyDialog.Label.Range" ) ); //$NON-NLS-1$
*
* intervalRange = new Text( groupGroup, SWT.SINGLE | SWT.BORDER );
* intervalRange.setLayoutData( new GridData( ) );
* intervalRange.addVerifyListener( new VerifyListener( ) {
*
*
* public void verifyText( VerifyEvent event ) { if ( event.text.length( ) <=
* 0 ) { return; }
*
* int beginIndex = Math.min( event.start, event.end ); int endIndex =
* Math.max( event.start, event.end ); String inputtedText =
* intervalRange.getText( ); String newString = inputtedText.substring(
* 0, beginIndex );
*
* newString += event.text; newString += inputtedText.substring(
* endIndex );
*
* event.doit = false;
*
* try { double value = Double.parseDouble( newString );
*
* if ( value >= 0 ) { event.doit = true; } } catch (
* NumberFormatException e ) { return; } } } ); gd = new GridData(
* GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 3;
* intervalRange.setLayoutData( gd );
*
* intervalBaseButton = new Button( groupGroup, SWT.CHECK );
* intervalBaseButton.setText( Messages.getString(
* "LevelPropertyDialog.Interval.Base" ) ); //$NON-NLS-1$ gd = new
* GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 4;
* intervalBaseButton.setLayoutData( gd );
* intervalBaseButton.addSelectionListener( new SelectionAdapter( ) {
*
* public void widgetSelected( SelectionEvent e ) {
* intervalBaseText.setEnabled( intervalBaseButton.getSelection( ) ); } } );
*
* intervalBaseText = new Text( groupGroup, SWT.SINGLE | SWT.BORDER );
* gd = new GridData( GridData.FILL_HORIZONTAL ); gd.horizontalSpan = 4;
* intervalBaseText.setLayoutData( gd );
*/
dynamicTable = new Table( contents, SWT.SINGLE
| SWT.FULL_SELECTION
| SWT.BORDER
| SWT.VERTICAL
| SWT.HORIZONTAL );
gd = new GridData( GridData.FILL_BOTH );
gd.heightHint = 150;
dynamicTable.setLayoutData( gd );
dynamicTable.setLinesVisible( true );
dynamicTable.setHeaderVisible( true );
dynamicTable.addKeyListener( new KeyAdapter( ) {
public void keyPressed( KeyEvent e )
{
if ( e.keyCode == SWT.DEL )
{
int itemCount = dynamicTable.getItemCount( );
if ( dynamicSelectIndex == itemCount )
{
return;
}
if ( dynamicSelectIndex == itemCount - 1 )
{
dynamicSelectIndex
}
try
{
handleDynamicDelEvent( );
}
catch ( Exception e1 )
{
WidgetUtil.processError( getShell( ), e1 );
}
refreshDynamicViewer( );
}
}
} );
dynamicViewer = new TableViewer( dynamicTable );
String[] columns = new String[]{
" ", Messages.getString( "LevelPropertyDialog.Label.Attribute" ) //$NON-NLS-1$ //$NON-NLS-2$
};
TableColumn column = new TableColumn( dynamicTable, SWT.LEFT );
column.setText( columns[0] );
column.setWidth( 15 );
TableColumn column1 = new TableColumn( dynamicTable, SWT.LEFT );
column1.setResizable( columns[1] != null );
if ( columns[1] != null )
{
column1.setText( columns[1] );
}
column1.setWidth( 200 );
dynamicViewer.setColumnProperties( new String[]{
"", prop_Attribute
} );
editor = new ComboBoxCellEditor( dynamicViewer.getTable( ),
attributeItems,
SWT.READ_ONLY );
CellEditor[] cellEditors = new CellEditor[]{
null, editor
};
dynamicViewer.setCellEditors( cellEditors );
dynamicViewer.setContentProvider( contentProvider );
dynamicViewer.setLabelProvider( dynamicLabelProvider );
dynamicViewer.setCellModifier( dynamicCellModifier );
return contents;
}
/*
* protected void updateRadioButtonStatus( Button button ) { if ( button ==
* noneIntervalButton ) { noneIntervalButton.setSelection( true );
* intervalButton.setSelection( false ); prefixButton.setSelection( false ); }
* else if ( button == intervalButton ) { noneIntervalButton.setSelection(
* false ); intervalButton.setSelection( true ); prefixButton.setSelection(
* false ); } else if ( button == prefixButton ) {
* noneIntervalButton.setSelection( false ); intervalButton.setSelection(
* false ); prefixButton.setSelection( true ); } intervalRange.setEnabled(
* !noneIntervalButton.getSelection( ) ); intervalBaseButton.setEnabled(
* !noneIntervalButton.getSelection( ) ); intervalBaseText.setEnabled(
* intervalBaseButton.getEnabled( ) && intervalBaseButton.getSelection( ) ); }
*/
String[] attributeItems = new String[0];
private void resetEditorItems( )
{
resetEditorItems( null );
}
private void resetEditorItems( String name )
{
List list = new ArrayList( );
list.addAll( Arrays.asList( attributeItems ) );
Iterator attrIter = input.attributesIterator( );
while ( attrIter.hasNext( ) )
{
LevelAttributeHandle handle = (LevelAttributeHandle) attrIter.next( );
list.remove( handle.getName( ) );
}
list.remove( input.getColumnName( ) );
if ( name != null && !list.contains( name ) )
{
list.add( 0, name );
}
String[] temps = new String[list.size( )];
list.toArray( temps );
editor.setItems( temps );
}
protected void handleDynamicDelEvent( )
{
if ( dynamicViewer.getSelection( ) != null
&& dynamicViewer.getSelection( ) instanceof StructuredSelection )
{
Object element = ( (StructuredSelection) dynamicViewer.getSelection( ) ).getFirstElement( );
if ( element instanceof LevelAttributeHandle )
{
try
{
( (LevelAttributeHandle) element ).drop( );
}
catch ( PropertyValueException e )
{
ExceptionHandler.handle( e );
}
}
}
}
protected void handleStaticDelEvent( )
{
if ( staticViewer.getSelection( ) != null
&& staticViewer.getSelection( ) instanceof StructuredSelection )
{
Object element = ( (StructuredSelection) staticViewer.getSelection( ) ).getFirstElement( );
if ( element instanceof RuleHandle )
{
try
{
( (RuleHandle) element ).drop( );
}
catch ( PropertyValueException e )
{
ExceptionHandler.handle( e );
}
}
}
}
private void createChoiceArea( Composite parent )
{
Composite contents = new Composite( parent, SWT.NONE );
GridLayout layout = new GridLayout( );
layout.marginWidth = 0;
layout.marginHeight = 0;
layout.numColumns = 2;
contents.setLayout( layout );
GridData data = new GridData( GridData.FILL_HORIZONTAL );
contents.setLayoutData( data );
dynamicButton = new Button( contents, SWT.RADIO );
dynamicButton.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
try
{
input.setLevelType( DesignChoiceConstants.LEVEL_TYPE_DYNAMIC );
}
catch ( SemanticException e1 )
{
ExceptionHandler.handle( e1 );
}
initLevelDialog( );
refreshDynamicViewer( );
updateButtonStatus( dynamicButton );
}
} );
staticButton = new Button( contents, SWT.RADIO );
staticButton.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
try
{
input.setLevelType( DesignChoiceConstants.LEVEL_TYPE_MIRRORED );
}
catch ( SemanticException e1 )
{
ExceptionHandler.handle( e1 );
}
initLevelDialog( );
refreshStaticViewer( );
updateButtonStatus( staticButton );
}
} );
dynamicButton.setText( Messages.getString( "LevelPropertyDialog.Button.Dynamic" ) ); //$NON-NLS-1$
staticButton.setText( Messages.getString( "LevelPropertyDialog.Button.Static" ) ); //$NON-NLS-1$
}
protected void updateButtonStatus( Button button )
{
if ( button == dynamicButton )
{
staticButton.setSelection( false );
dynamicButton.setSelection( true );
setExcludeGridData( staticArea, true );
setExcludeGridData( dynamicArea, false );
try
{
input.setLevelType( DesignChoiceConstants.LEVEL_TYPE_DYNAMIC );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
else if ( button == staticButton )
{
dynamicButton.setSelection( false );;
staticButton.setSelection( true );
setExcludeGridData( dynamicArea, true );
setExcludeGridData( staticArea, false );
try
{
input.setLevelType( DesignChoiceConstants.LEVEL_TYPE_MIRRORED );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
this.getShell( ).layout( );
checkOkButtonStatus( );
}
private TabularLevelHandle input;
private TableViewer dynamicViewer;
private Text nameText;
private ComboBoxCellEditor editor;
private TableViewer staticViewer;
private Composite staticArea;
private Button dynamicButton;
private Button staticButton;
protected int staticSelectIndex;
private static final String Prop_Name = "Name"; //$NON-NLS-1$
private static final String prop_Expression = "Expression"; //$NON-NLS-1$
private static final String prop_Attribute = "Attribute";
private Table dynamicTable;
private ExpressionCellEditor expressionEditor;
private Combo staticDataTypeCombo;
private Text staticNameText;
private Combo fieldCombo;
private Combo dynamicDataTypeCombo;
private Combo displayKeyCombo;
// private Button noneIntervalButton;
// private Button intervalButton;
// private Button prefixButton;
protected Composite createStaticArea( Composite parent )
{
Composite container = new Composite( parent, SWT.NONE );
GridLayout layout = new GridLayout( );
layout.marginWidth = layout.marginHeight = 0;
container.setLayout( layout );
container.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Group properties = new Group( container, SWT.NONE );
layout = new GridLayout( );
layout.numColumns = 2;
properties.setLayout( layout );
properties.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
new Label( properties, SWT.NONE ).setText( Messages.getString( "LevelPropertyDialog.Name" ) ); //$NON-NLS-1$
staticNameText = new Text( properties, SWT.BORDER );
staticNameText.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
staticNameText.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
checkOkButtonStatus( );
}
} );
new Label( properties, SWT.NONE ).setText( Messages.getString( "LevelPropertyDialog.DataType" ) ); //$NON-NLS-1$
staticDataTypeCombo = new Combo( properties, SWT.BORDER | SWT.READ_ONLY );
staticDataTypeCombo.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
staticDataTypeCombo.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
checkOkButtonStatus( );
}
} );
Group contents = new Group( container, SWT.NONE );
layout = new GridLayout( );
contents.setLayout( layout );
contents.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
final Table staticTable = new Table( contents, SWT.SINGLE
| SWT.FULL_SELECTION
| SWT.BORDER
| SWT.VERTICAL
| SWT.HORIZONTAL );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.heightHint = 150;
staticTable.setLayoutData( gd );
staticTable.setLinesVisible( true );
staticTable.setHeaderVisible( true );
staticTable.addKeyListener( new KeyAdapter( ) {
public void keyPressed( KeyEvent e )
{
if ( e.keyCode == SWT.DEL )
{
int itemCount = staticTable.getItemCount( );
if ( staticSelectIndex == itemCount )
{
return;
}
if ( staticSelectIndex == itemCount - 1 )
{
staticSelectIndex
}
try
{
handleStaticDelEvent( );
}
catch ( Exception e1 )
{
WidgetUtil.processError( getShell( ), e1 );
}
refreshStaticViewer( );
}
}
} );
staticViewer = new TableViewer( staticTable );
String[] columns = new String[]{
"", //$NON-NLS-1$
Messages.getString( "LevelPropertyDialog.Label.Name" ), //$NON-NLS-1$
Messages.getString( "LevelPropertyDialog.Label.Expression" ) //$NON-NLS-1$
};
int[] widths = new int[]{
15, 150, 150
};
for ( int i = 0; i < columns.length; i++ )
{
TableColumn column = new TableColumn( staticTable, SWT.LEFT );
column.setResizable( columns[i] != null );
if ( columns[i] != null )
{
column.setText( columns[i] );
}
column.setWidth( widths[i] );
}
staticViewer.setColumnProperties( new String[]{
"",
LevelPropertyDialog.Prop_Name,
LevelPropertyDialog.prop_Expression
} );
expressionEditor = new ExpressionCellEditor( staticTable );
CellEditor[] cellEditors = new CellEditor[]{
null, new TextCellEditor( staticTable ), expressionEditor
};
staticViewer.setCellEditors( cellEditors );
staticViewer.setContentProvider( contentProvider );
staticViewer.setLabelProvider( staticLabelProvider );
staticViewer.setCellModifier( staticCellModifier );
return container;
}
public void setInput( TabularLevelHandle level )
{
this.input = level;
}
public static void setExcludeGridData( Control control, boolean exclude )
{
Object obj = control.getLayoutData( );
if ( obj == null )
control.setLayoutData( new GridData( ) );
else if ( !( obj instanceof GridData ) )
return;
GridData data = (GridData) control.getLayoutData( );
if ( exclude )
{
data.heightHint = 0;
}
else
{
data.heightHint = -1;
}
control.setLayoutData( data );
control.getParent( ).layout( );
control.setVisible( !exclude );
}
protected void checkOkButtonStatus( )
{
if ( dynamicButton.getSelection( ) )
{
if ( nameText.getText( ) == null
|| nameText.getText( ).trim( ).equals( "" ) //$NON-NLS-1$
|| fieldCombo.getSelectionIndex( ) == -1
|| dynamicDataTypeCombo.getSelectionIndex( ) == -1 )
{
if ( getButton( IDialogConstants.OK_ID ) != null )
getButton( IDialogConstants.OK_ID ).setEnabled( false );
}
else
{
if ( getButton( IDialogConstants.OK_ID ) != null )
getButton( IDialogConstants.OK_ID ).setEnabled( true );
}
}
else
{
if ( staticNameText.getText( ) == null
|| staticNameText.getText( ).trim( ).equals( "" ) //$NON-NLS-1$
|| staticDataTypeCombo.getSelectionIndex( ) == -1 )
{
if ( getButton( IDialogConstants.OK_ID ) != null )
getButton( IDialogConstants.OK_ID ).setEnabled( false );
}
else
{
if ( getButton( IDialogConstants.OK_ID ) != null )
getButton( IDialogConstants.OK_ID ).setEnabled( true );
}
}
}
protected void createButtonsForButtonBar( Composite parent )
{
super.createButtonsForButtonBar( parent );
checkOkButtonStatus( );
if ( input != null && input.getLevelType( ) != null )
{
if ( input.getLevelType( )
.equals( DesignChoiceConstants.LEVEL_TYPE_DYNAMIC ) )
{
dynamicButton.setSelection( true );
staticButton.setSelection( false );
}
else
{
dynamicButton.setSelection( false );
staticButton.setSelection( true );
}
}
}
}
|
package org.zstack.header.other;
import org.zstack.header.message.APIEvent;
import org.zstack.header.message.APIMessage;
public interface APIAuditor {
class Result {
public String resourceUuid;
public Class resourceType;
public String getResourceUuid() {
return resourceUuid;
}
public void setResourceUuid(String resourceUuid) {
this.resourceUuid = resourceUuid;
}
public Class getResourceType() {
return resourceType;
}
public void setResourceType(Class resourceType) {
this.resourceType = resourceType;
}
public Result(String resourceUuid, Class resourceType) {
this.resourceUuid = resourceUuid;
if (this.resourceUuid == null) {
this.resourceUuid = "";
}
this.resourceType = resourceType;
}
}
Result audit(APIMessage msg, APIEvent rsp);
}
|
package org.phenotips.data.permissions.rest.internal.utils;
import org.phenotips.data.PatientRepository;
import org.phenotips.data.permissions.AccessLevel;
import org.phenotips.data.permissions.PermissionsManager;
import org.xwiki.component.annotation.Component;
import org.xwiki.users.UserManager;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.WebApplicationException;
import org.slf4j.Logger;
/**
* Default implementation of {@link SecureContextFactory}. The purpose is to reduce the number of common injections
* between default implementations of the REST resources.
*
* @version $Id$
* @since 1.3M2
*/
@Component
@Singleton
public class DefaultSecureContextFactory implements SecureContextFactory
{
@Inject
private Logger logger;
@Inject
private PatientRepository repository;
@Inject
private UserManager users;
@Inject
private PermissionsManager manager;
@Override
public PatientAccessContext getContext(String patientId, String minimumAccessLevel) throws WebApplicationException
{
AccessLevel level = this.manager.resolveAccessLevel(minimumAccessLevel);
return new PatientAccessContext(patientId, level, this.repository, this.users, this.manager, this.logger);
}
}
|
package lecho.lib.hellocharts;
import java.util.List;
import java.util.Locale;
import lecho.lib.hellocharts.anim.ChartAnimator;
import lecho.lib.hellocharts.anim.ChartAnimatorV11;
import lecho.lib.hellocharts.anim.ChartAnimatorV8;
import lecho.lib.hellocharts.model.AnimatedValue;
import lecho.lib.hellocharts.model.ChartData;
import lecho.lib.hellocharts.model.InternalLineChartData;
import lecho.lib.hellocharts.model.InternalSeries;
import lecho.lib.hellocharts.utils.Config;
import lecho.lib.hellocharts.utils.Utils;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Cap;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class LineChart extends View {
private static final String TAG = "LineChart";
private static final float LINE_SMOOTHNES = 0.16f;
private static final int DEFAULT_LINE_WIDTH_DP = 2;
private static final int DEFAULT_POINT_RADIUS_DP = 6;
private static final int DEFAULT_POINT_TOUCH_RADIUS_DP = 12;
private static final int DEFAULT_TEXT_SIZE_DP = 14;
private static final int DEFAULT_TEXT_COLOR = Color.WHITE;
private static final int DEFAULT_AXIS_COLOR = Color.LTGRAY;
private float mCommonMargin = 0;
private Path mLinePath = new Path();
private Paint mLinePaint = new Paint();
private Paint mTextPaint = new Paint();
private InternalLineChartData mData;
private float mLineWidth;
private float mPointRadius;
private float mPointPressedRadius;
private float mTouchRadius;
private float mXMultiplier;
private float mYMultiplier;
private float mAvailableWidth;
private float mAvailableHeight;
private float mYAxisMargin = 0;
private float mXAxisMargin = 0;
private boolean mLinesOn = true;
private boolean mInterpolationOn = false;
private boolean mPointsOn = true;
private boolean mPopupsOn = false;
private boolean mAxesOn = true;
private ChartAnimator mAnimator;
private int mSelectedSeriesIndex = Integer.MIN_VALUE;
private int mSelectedValueIndex = Integer.MIN_VALUE;
private OnPointClickListener mOnPointClickListener = new DummyOnPointListener();
public LineChart(Context context) {
super(context);
initAttributes();
initPaints();
initAnimatiors();
}
public LineChart(Context context, AttributeSet attrs) {
super(context, attrs);
initAttributes();
initPaints();
initAnimatiors();
}
public LineChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initAttributes();
initPaints();
initAnimatiors();
}
private void initAttributes() {
mLineWidth = Utils.dp2px(getContext(), DEFAULT_LINE_WIDTH_DP);
mPointRadius = Utils.dp2px(getContext(), DEFAULT_POINT_RADIUS_DP);
mPointPressedRadius = mPointRadius + Utils.dp2px(getContext(), 4);
mTouchRadius = Utils.dp2px(getContext(), DEFAULT_POINT_TOUCH_RADIUS_DP);
mCommonMargin = (float) Utils.dp2px(getContext(), 4);
}
private void initPaints() {
mLinePaint.setAntiAlias(true);
mLinePaint.setStyle(Paint.Style.STROKE);
mLinePaint.setStrokeCap(Cap.ROUND);
mTextPaint.setAntiAlias(true);
mTextPaint.setStyle(Paint.Style.FILL);
mTextPaint.setStrokeWidth(1);
mTextPaint.setTextSize(Utils.dp2px(getContext(), DEFAULT_TEXT_SIZE_DP));
}
private void initAnimatiors() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
mAnimator = new ChartAnimatorV8(this, Config.DEFAULT_ANIMATION_DURATION);
} else {
mAnimator = new ChartAnimatorV11(this, Config.DEFAULT_ANIMATION_DURATION);
}
}
@Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
long time = System.nanoTime();
super.onSizeChanged(width, height, oldWidth, oldHeight);
// TODO mPointRadus can change, recalculate in setter
calculateAvailableDimensions();
// TODO max-min can chage - recalculate in setter
calculateMultipliers();
Log.v(TAG, "onSizeChanged [ms]: " + (System.nanoTime() - time) / 1000000f);
}
/**
* Calculates available width and height. Should be called when chart dimensions or chart data change.
*/
private void calculateAvailableDimensions() {
final float additionalPadding = 2 * mPointPressedRadius;
mAvailableWidth = getWidth() - getPaddingLeft() - getPaddingRight() - additionalPadding - mYAxisMargin;
mAvailableHeight = getHeight() - getPaddingTop() - getPaddingBottom() - additionalPadding - mXAxisMargin;
}
/**
* Calculates multipliers used to translate values into pixels. Should be called when chart dimensions or chart data
* change.
*/
private void calculateMultipliers() {
mXMultiplier = mAvailableWidth / (mData.getMaxXValue() - mData.getMinXValue());
mYMultiplier = mAvailableHeight / (mData.getMaxYValue() - mData.getMinYValue());
}
private void calculateYAxisMargin() {
if (mAxesOn) {
final Rect textBounds = new Rect();
final String text;
if (Math.abs(mData.mYAxis.get(0)) > Math.abs(mData.mYAxis.get(mData.mYAxis.size()-1))) {
text = String.format(Locale.ENGLISH, Config.DEFAULT_AXES_FORMAT, mData.mYAxis.get(0));
} else {
text = String.format(Locale.ENGLISH, Config.DEFAULT_AXES_FORMAT, mData.mYAxis.get(mData.mYAxis.size()-1));
}
mTextPaint.getTextBounds(text, 0, text.length(), textBounds);
mYAxisMargin = textBounds.width() + mCommonMargin;
} else {
mYAxisMargin = 0;
}
}
private void calculateXAxisMargin() {
if (mAxesOn) {
final Rect textBounds = new Rect();
// Hard coded only for text height calculation.
mTextPaint.getTextBounds("X", 0, 1, textBounds);
mXAxisMargin = textBounds.height() + mCommonMargin;
} else {
mYAxisMargin = 0;
}
}
@Override
protected void onDraw(Canvas canvas) {
long time = System.nanoTime();
if (mAxesOn) {
drawYAxis(canvas);
drawXAxis(canvas);
}
if (mLinesOn) {
drawLines(canvas);
}
if (mPointsOn) {
drawPoints(canvas);
}
Log.v(TAG, "onDraw [ms]: " + (System.nanoTime() - time) / 1000000f);
}
private void drawXAxis(Canvas canvas) {
mLinePaint.setStrokeWidth(1);
mLinePaint.setColor(DEFAULT_AXIS_COLOR);
mTextPaint.setColor(DEFAULT_AXIS_COLOR);
mTextPaint.setTextAlign(Align.CENTER);
final float rawX1 = getPaddingLeft();
final float rawX2 = getWidth() - getPaddingRight();
final float rawY1 = getHeight() - getPaddingBottom();
final float rawY2 = calculateY(mData.getMinYValue());
canvas.drawLine(rawX1 + mYAxisMargin, rawY2, rawX2, rawY2, mLinePaint);
for (float x : mData.mXAxis) {
final String text = String.format(Locale.ENGLISH, Config.DEFAULT_AXES_FORMAT, x);
canvas.drawText(text, calculateX(x), rawY1, mTextPaint);
}
}
private void drawYAxis(Canvas canvas) {
mLinePaint.setStrokeWidth(1);
mLinePaint.setColor(DEFAULT_AXIS_COLOR);
mTextPaint.setColor(DEFAULT_AXIS_COLOR);
mTextPaint.setTextAlign(Align.LEFT);
final float rawX1 = getPaddingLeft();
final float rawX2 = getWidth() - getPaddingRight();
for (float y : mData.mYAxis) {
float rawY = calculateY(y);
final String text = String.format(Locale.ENGLISH, Config.DEFAULT_AXES_FORMAT, y);
canvas.drawLine(rawX1 + mYAxisMargin, rawY, rawX2, rawY, mLinePaint);
canvas.drawText(text, rawX1, rawY, mTextPaint);
}
}
private void drawLines(Canvas canvas) {
mLinePaint.setStrokeWidth(mLineWidth);
for (InternalSeries internalSeries : mData.getInternalsSeries()) {
if (mInterpolationOn) {
drawSmoothPath(canvas, internalSeries);
} else {
drawPath(canvas, internalSeries);
}
mLinePath.reset();
}
}
// TODO Drawing points can be done in the same loop as drawing lines but it may cause problems in the future. Reuse
// calculated X/Y;
private void drawPoints(Canvas canvas) {
for (InternalSeries internalSeries : mData.getInternalsSeries()) {
mTextPaint.setColor(internalSeries.getColor());
int valueIndex = 0;
for (float valueX : mData.getDomain()) {
final float rawValueX = calculateX(valueX);
final float valueY = internalSeries.getValues().get(valueIndex).getPosition();
final float rawValueY = calculateY(valueY);
canvas.drawCircle(rawValueX, rawValueY, mPointRadius, mTextPaint);
if (mPopupsOn) {
drawValuePopup(canvas, mPointRadius, valueY, rawValueX, rawValueY);
}
++valueIndex;
}
}
if (mSelectedSeriesIndex >= 0 && mSelectedValueIndex >= 0) {
final float valueX = mData.getDomain().get(mSelectedValueIndex);
final float rawValueX = calculateX(valueX);
final float valueY = mData.getInternalsSeries().get(mSelectedSeriesIndex).getValues()
.get(mSelectedValueIndex).getPosition();
final float rawValueY = calculateY(valueY);
mTextPaint.setColor(mData.getInternalsSeries().get(mSelectedSeriesIndex).getColor());
canvas.drawCircle(rawValueX, rawValueY, mPointPressedRadius, mTextPaint);
if (mPopupsOn) {
drawValuePopup(canvas, mPointRadius, valueY, rawValueX, rawValueY);
}
}
}
private void drawValuePopup(Canvas canvas, float offset, float valueY, float rawValueX, float rawValueY) {
mTextPaint.setTextAlign(Align.LEFT);
final String text = String.format(Locale.ENGLISH, Config.DEFAULT_VALUE_FORMAT, valueY);
final Rect textBounds = new Rect();
mTextPaint.getTextBounds(text, 0, text.length(), textBounds);
float left = rawValueX + offset;
float right = rawValueX + offset + textBounds.width() + mCommonMargin * 2;
float top = rawValueY - offset - textBounds.height() - mCommonMargin * 2;
float bottom = rawValueY - offset;
if (top < getPaddingTop() + mPointPressedRadius) {
top = rawValueY + offset;
bottom = rawValueY + offset + textBounds.height() + mCommonMargin * 2;
}
if (right > getWidth() - getPaddingRight() - mPointPressedRadius) {
left = rawValueX - offset - textBounds.width() - mCommonMargin * 2;
right = rawValueX - offset;
}
final RectF popup = new RectF(left, top, right, bottom);
canvas.drawRoundRect(popup, mCommonMargin, mCommonMargin, mTextPaint);
final int color = mTextPaint.getColor();
mTextPaint.setColor(DEFAULT_TEXT_COLOR);
canvas.drawText(text, left + mCommonMargin, bottom - mCommonMargin, mTextPaint);
mTextPaint.setColor(color);
}
private void drawPath(Canvas canvas, final InternalSeries internalSeries) {
int valueIndex = 0;
for (float valueX : mData.getDomain()) {
final float rawValueX = calculateX(valueX);
final float rawValueY = calculateY(internalSeries.getValues().get(valueIndex).getPosition());
if (valueIndex == 0) {
mLinePath.moveTo(rawValueX, rawValueY);
} else {
mLinePath.lineTo(rawValueX, rawValueY);
}
++valueIndex;
}
mLinePaint.setColor(internalSeries.getColor());
canvas.drawPath(mLinePath, mLinePaint);
}
private void drawSmoothPath(Canvas canvas, final InternalSeries internalSeries) {
final int domainSize = mData.getDomain().size();
float previousPointX = Float.NaN;
float previousPointY = Float.NaN;
float currentPointX = Float.NaN;
float currentPointY = Float.NaN;
float nextPointX = Float.NaN;
float nextPointY = Float.NaN;
for (int valueIndex = 0; valueIndex < domainSize - 1; ++valueIndex) {
if (Float.isNaN(currentPointX)) {
currentPointX = calculateX(mData.getDomain().get(valueIndex));
currentPointY = calculateY(internalSeries.getValues().get(valueIndex).getPosition());
}
if (Float.isNaN(previousPointX)) {
if (valueIndex > 0) {
previousPointX = calculateX(mData.getDomain().get(valueIndex - 1));
previousPointY = calculateY(internalSeries.getValues().get(valueIndex - 1).getPosition());
} else {
previousPointX = currentPointX;
previousPointY = currentPointY;
}
}
if (Float.isNaN(nextPointX)) {
nextPointX = calculateX(mData.getDomain().get(valueIndex + 1));
nextPointY = calculateY(internalSeries.getValues().get(valueIndex + 1).getPosition());
}
// afterNextPoint is always new one or it is equal nextPoint.
final float afterNextPointX;
final float afterNextPointY;
if (valueIndex < domainSize - 2) {
afterNextPointX = calculateX(mData.getDomain().get(valueIndex + 2));
afterNextPointY = calculateY(internalSeries.getValues().get(valueIndex + 2).getPosition());
} else {
afterNextPointX = nextPointX;
afterNextPointY = nextPointY;
}
// Calculate control points.
final float firstDiffX = (nextPointX - previousPointX);
final float firstDiffY = (nextPointY - previousPointY);
final float secondDiffX = (afterNextPointX - currentPointX);
final float secondDiffY = (afterNextPointY - currentPointY);
final float firstControlPointX = currentPointX + (LINE_SMOOTHNES * firstDiffX);
final float firstControlPointY = currentPointY + (LINE_SMOOTHNES * firstDiffY);
final float secondControlPointX = nextPointX - (LINE_SMOOTHNES * secondDiffX);
final float secondControlPointY = nextPointY - (LINE_SMOOTHNES * secondDiffY);
mLinePath.moveTo(currentPointX, currentPointY);
mLinePath.cubicTo(firstControlPointX, firstControlPointY, secondControlPointX, secondControlPointY,
nextPointX, nextPointY);
// Shift values to prevent recalculation of values that where already calculated.
previousPointX = currentPointX;
previousPointY = currentPointY;
currentPointX = nextPointX;
currentPointY = nextPointY;
nextPointX = afterNextPointX;
nextPointY = afterNextPointY;
}
mLinePaint.setColor(internalSeries.getColor());
canvas.drawPath(mLinePath, mLinePaint);
}
private float calculateX(float valueX) {
final float additionalPadding = getPaddingLeft() + mPointPressedRadius + mYAxisMargin;
final float valueDistance = (valueX - mData.getMinXValue()) * mXMultiplier;
return valueDistance + additionalPadding;
}
private float calculateY(float valueY) {
final float additionalPadding = getPaddingBottom() + mPointPressedRadius + mXAxisMargin;
final float valueDistance = (valueY - mData.getMinYValue()) * mYMultiplier;
// Subtracting from height because on android top left corner is 0,0 and bottom right is maxX,maxY.
return getHeight() - valueDistance - additionalPadding;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!mPointsOn) {
// No point - no touch events.
return true;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Select only the first value within touched area.
// Reverse loop to starts with the line drawn on top.
for (int seriesIndex = mData.getInternalsSeries().size() - 1; seriesIndex >= 0; --seriesIndex) {
int valueIndex = 0;
for (AnimatedValue value : mData.getInternalsSeries().get(seriesIndex).getValues()) {
final float rawX = calculateX(mData.getDomain().get(valueIndex));
final float rawY = calculateY(value.getPosition());
if (Utils.isInArea(rawX, rawY, event.getX(), event.getY(), mTouchRadius)) {
mSelectedSeriesIndex = seriesIndex;
mSelectedValueIndex = valueIndex;
invalidate();
return true;
}
++valueIndex;
}
}
break;
case MotionEvent.ACTION_UP:
// If value was selected call click listener and clear selection.
if (mSelectedValueIndex >= 0) {
final float x = mData.getDomain().get(mSelectedValueIndex);
final float y = mData.getInternalsSeries().get(mSelectedSeriesIndex).getValues()
.get(mSelectedValueIndex).getPosition();
mOnPointClickListener.onPointClick(mSelectedSeriesIndex, mSelectedValueIndex, x, y);
mSelectedSeriesIndex = Integer.MIN_VALUE;
mSelectedValueIndex = Integer.MIN_VALUE;
invalidate();
}
break;
case MotionEvent.ACTION_MOVE:
// Clear selection if user is now touching outside touch area.
if (mSelectedValueIndex >= 0) {
final float x = mData.getDomain().get(mSelectedValueIndex);
final float y = mData.getInternalsSeries().get(mSelectedSeriesIndex).getValues()
.get(mSelectedValueIndex).getPosition();
final float rawX = calculateX(x);
final float rawY = calculateY(y);
if (!Utils.isInArea(rawX, rawY, event.getX(), event.getY(), mTouchRadius)) {
mSelectedSeriesIndex = Integer.MIN_VALUE;
mSelectedValueIndex = Integer.MIN_VALUE;
invalidate();
}
}
break;
case MotionEvent.ACTION_CANCEL:
// Clear selection
if (mSelectedValueIndex >= 0) {
mSelectedSeriesIndex = Integer.MIN_VALUE;
mSelectedValueIndex = Integer.MIN_VALUE;
invalidate();
}
break;
default:
break;
}
return true;
}
public void setData(final ChartData rawData) {
mData = InternalLineChartData.createFromRawData(rawData);
mData.calculateRanges();
calculateYAxisMargin();
calculateXAxisMargin();
calculateAvailableDimensions();
calculateMultipliers();
postInvalidate();
}
public ChartData getData() {
return mData.getRawData();
}
public void animationUpdate(float scale) {
for (AnimatedValue value : mData.getInternalsSeries().get(0).getValues()) {
value.update(scale);
}
mData.calculateYRanges();
calculateYAxisMargin();
calculateXAxisMargin();
calculateAvailableDimensions();
calculateMultipliers();
invalidate();
}
public void animateSeries(int index, List<Float> values) {
mAnimator.cancelAnimation();
mData.updateSeriesTargetPositions(index, values);
mAnimator.startAnimation();
}
public void updateSeries(int index, List<Float> values) {
mData.updateSeries(index, values);
postInvalidate();
}
public void setOnPointClickListener(OnPointClickListener listener) {
if (null == listener) {
mOnPointClickListener = new DummyOnPointListener();
} else {
mOnPointClickListener = listener;
}
}
// Just empty listener to avoid NPE checks.
private static class DummyOnPointListener implements OnPointClickListener {
@Override
public void onPointClick(int selectedSeriesIndex, int selectedValueIndex, float x, float y) {
// Do nothing.
}
}
}
|
package org.jetel.data;
import java.io.UnsupportedEncodingException;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Arrays;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.util.bytes.ByteBufferUtils;
import org.jetel.util.file.ZipUtils;
import org.jetel.util.string.Compare;
public class CompressedByteDataField extends ByteDataField {
private static final long serialVersionUID = 1L;
/** lenght of data represented by the field. */
private int dataLen;
/**
* @param _metadata
*/
public CompressedByteDataField(DataFieldMetadata _metadata) {
super(_metadata);
dataLen = 0;
}
/**
* @param _metadata
* @param plain
*/
public CompressedByteDataField(DataFieldMetadata _metadata, boolean plain) {
super(_metadata, plain);
dataLen = 0;
}
/**
* @param _metadata
* @param value
*/
public CompressedByteDataField(DataFieldMetadata _metadata, byte[] value) {
super(_metadata, value);
dataLen = value == null ? 0 : value.length;
}
public DataField duplicate(){
CompressedByteDataField compressedByteDataField = new CompressedByteDataField(metadata, value);
compressedByteDataField.value = (value != null) ? Arrays.copyOf(value, value.length) : null;
compressedByteDataField.dataLen = dataLen;
return compressedByteDataField;
}
/**
* @see org.jetel.data.DataField#copyField(org.jetel.data.DataField)
* @deprecated use setValue(DataField) instead
*/
public void copyFrom(DataField fromField){
if (fromField instanceof CompressedByteDataField){
if (!fromField.isNull){
int length = ((CompressedByteDataField) fromField).value.length;
if (this.value == null || this.value.length != length){
this.value = new byte[length];
}
System.arraycopy(((CompressedByteDataField) fromField).value, 0, this.value, 0, length);
}
setNull(fromField.isNull);
dataLen = ((CompressedByteDataField) fromField).dataLen;
} else {
super.copyFrom(fromField);
}
}
public void setValue(byte[] value) {
dataLen = value == null ? 0 : value.length;
super.setValue(ZipUtils.compress(value));
}
public void setValue(byte value) {
dataLen = metadata.getSize();
if (dataLen <= 0) {
dataLen = INITIAL_BYTE_ARRAY_CAPACITY;
}
byte[] buf = new byte[dataLen];
Arrays.fill(buf, value);
setValue(buf);
setNull(false);
}
@Override
public void setValue(DataField fromField) {
if (fromField instanceof CompressedByteDataField){
if (!fromField.isNull){
int length = ((CompressedByteDataField) fromField).value.length;
if (this.value == null || this.value.length != length){
this.value = new byte[length];
}
System.arraycopy(((CompressedByteDataField) fromField).value, 0, this.value, 0, length);
}
setNull(fromField.isNull);
dataLen = ((CompressedByteDataField) fromField).dataLen;
} else {
super.setValue(fromField);
}
}
public char getType() {
return DataFieldMetadata.BYTE_FIELD_COMPRESSED;
}
public Object getValueDuplicate() {
return getValue();
}
public byte getByte(int position) {
if(isNull) {
return 0;
}
return getByteArray()[position];
}
public byte[] getByteArray() {
return ZipUtils.decompress(super.value, dataLen);
}
public void fromString(CharSequence seq) {
fromString(seq, Defaults.DataFormatter.DEFAULT_CHARSET_ENCODER);
}
public void fromString(CharSequence seq, String charset) {
if (seq == null || Compare.equals(seq, metadata.getNullValue())) {
setNull(true);
return;
}
try {
byte[] bytes = seq.toString().getBytes(charset);
setValue(bytes);
dataLen = bytes.length;
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex.toString() + " when calling fromString() on field \""
+ this.metadata.getName() + "\"", ex);
}
setNull(false);
}
public void fromByteBuffer(ByteBuffer dataBuffer, CharsetDecoder decoder) {
dataLen = metadata.getSize();
if (dataLen <= 0) {
dataLen = INITIAL_BYTE_ARRAY_CAPACITY;
}
byte[] buf = new byte[dataLen];
dataBuffer.get(buf);
setValue(buf);
setNull(false);
}
public void toByteBuffer(ByteBuffer dataBuffer, CharsetEncoder encoder) {
if(!isNull) {
try {
dataBuffer.put(getByteArray());
} catch (BufferOverflowException e) {
throw new RuntimeException("The size of data buffer is only " + dataBuffer.limit() + ". Set appropriate parameter in defautProperties file.", e);
}
}
}
public void toByteBuffer(ByteBuffer dataBuffer) {
if(!isNull) {
try {
dataBuffer.put(getByteArray());
} catch (BufferOverflowException e) {
throw new RuntimeException("The size of data buffer is only " + dataBuffer.limit() + ". Set appropriate parameter in defautProperties file.", e);
}
}
}
public void serialize(ByteBuffer buffer) {
try {
if(isNull) {
// encode nulls as zero
ByteBufferUtils.encodeLength(buffer, 0);
} else {
// increment length of non-null values by one
ByteBufferUtils.encodeLength(buffer, dataLen + 1);
ByteBufferUtils.encodeLength(buffer, value.length);
buffer.put(value);
}
} catch (BufferOverflowException e) {
throw new RuntimeException("The size of data buffer is only " + buffer.limit() + ". Set appropriate parameter in defautProperties file.", e);
}
}
public void deserialize(ByteBuffer buffer) {
dataLen = ByteBufferUtils.decodeLength(buffer);
if (dataLen == 0) {
setNull(true);
return;
}
// encoded length is incremented by one, decrement it back to normal
dataLen
int bufLen = ByteBufferUtils.decodeLength(buffer);
if (value == null || bufLen != value.length) {
value = new byte[bufLen];
}
buffer.get(value);
setNull(false);
}
public boolean equals(Object obj) {
if (isNull || obj==null) return false;
if (obj instanceof CompressedByteDataField){
return this.dataLen == ((CompressedByteDataField) obj).dataLen
&& Arrays.equals(this.value, ((CompressedByteDataField) obj).value);
}else if (obj instanceof byte[]){
return Arrays.equals(getByteArray(), (byte[])obj);
}else {
return false;
}
}
public int compareTo(Object obj) {
if (isNull) return -1;
byte[] left;
byte[] right;
if (obj instanceof CompressedByteDataField){
left = value;
right = ((CompressedByteDataField)obj).value;
}else if (obj instanceof byte[]){
left = getByteArray();
right = (byte[])obj;
}else {
throw new ClassCastException("Can't compare CompressedByteDataField and "+obj.getClass().getName());
}
int compLength = left.length >= right.length ? left.length : right.length;
for (int i = 0; i < compLength; i++) {
if (left[i] > right[i]) {
return 1;
} else if (left[i] < right[i]) {
return -1;
}
}
// arrays seem to be the same (so far), decide according to the length
if (left.length == right.length) {
return 0;
} else if (left.length > right.length) {
return 1;
} else {
return -1;
}
}
public int getSizeSerialized() {
if(isNull) {
return ByteBufferUtils.lengthEncoded(0);
} else {
return ByteBufferUtils.lengthEncoded(dataLen) + ByteBufferUtils.lengthEncoded(value.length) + value.length;
}
}
public int getDataLength() {
return dataLen;
}
}
|
package org.jetel.data.parser;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFReader.SheetIterator;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.parser.AbstractSpreadsheetParser.CellValueFormatter;
import org.jetel.data.parser.SpreadsheetStreamParser.CellBuffers;
import org.jetel.data.parser.SpreadsheetStreamParser.RecordFieldValueSetter;
import org.jetel.data.parser.XSSFSheetXMLHandler.SheetContentsHandler;
import org.jetel.exception.BadDataFormatException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.JetelException;
import org.jetel.exception.JetelRuntimeException;
import org.jetel.exception.SpreadsheetException;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.util.SpreadsheetUtils;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
public class XLSXStreamParser implements SpreadsheetStreamHandler {
private final static Log LOGGER = LogFactory.getLog(XLSXStreamParser.class);
private SpreadsheetStreamParser parent;
private String fileName;
private String sheetName;
private OPCPackage opcPackage;
private XSSFReader reader;
private StylesTable stylesTable;
private ReadOnlySharedStringsTable sharedStringsTable;
private XMLStreamReader staxParser;
private XMLInputFactory xmlInputFactory;
private RecordFillingContentHandler sheetContentHandler;
private XSSFSheetXMLHandler xssfContentHandler;
private SheetIterator sheetIterator;
private InputStream currentSheetInputStream;
private CellBuffers<CellValue> cellBuffers;
// private CellValue[][] cellBuffers;
// private int nextPartial = -1;
private int currentSheetIndex;
private int nextRecordStartRow;
/** the data formatter used to format cell values as strings */
private final CellValueFormatter dataFormatter = new CellValueFormatter();
private boolean endOfSheet;
public XLSXStreamParser(SpreadsheetStreamParser parent) {
this.parent = parent;
}
@Override
public void init() throws ComponentNotReadyException {
xmlInputFactory = XMLInputFactory.newInstance();
cellBuffers = parent.new CellBuffers<CellValue>();
}
@Override
public DataRecord parseNext(DataRecord record) throws JetelException {
sheetContentHandler.setRecordStartRow(nextRecordStartRow);
sheetContentHandler.setRecord(record);
try {
while (staxParser.hasNext() && !sheetContentHandler.isRecordFinished()) {
processParserEvent(staxParser, xssfContentHandler);
}
if (!staxParser.hasNext()) {
endOfSheet = true;
if (!sheetContentHandler.isRecordFinished()) {
if (!sheetContentHandler.isRecordStarted() && cellBuffers.isEmpty()) {
return null;
}
sheetContentHandler.finishRecord();
}
}
} catch (XMLStreamException e) {
throw new JetelException("Error occurred while reading XML of sheet " + currentSheetIndex, e);
} catch (SAXException e) {
throw new JetelException("Error occurred while reading XML of sheet " + currentSheetIndex, e);
}
nextRecordStartRow += parent.mappingInfo.getStep();
return record;
}
@Override
public int skip(int nRec) throws JetelException {
if (nRec <= 0) {
return 0;
}
sheetContentHandler.skipRecords(nRec);
try {
while (staxParser.hasNext() && sheetContentHandler.isSkipRecords()) {
processParserEvent(staxParser, xssfContentHandler);
}
int skippedRecords = sheetContentHandler.getNumberOfSkippedRecords();
nextRecordStartRow += skippedRecords * parent.mappingInfo.getStep();
return skippedRecords;
} catch (XMLStreamException e) {
throw new JetelException("Error occurred while reading XML of sheet " + currentSheetIndex, e);
} catch (SAXException e) {
throw new JetelException("Error occurred while reading XML of sheet " + currentSheetIndex, e);
}
}
@Override
public List<String> getSheetNames() {
try {
SheetIterator iterator = (SheetIterator) reader.getSheetsData();
List<String> toReturn = new ArrayList<String>();
while (iterator.hasNext()) {
InputStream stream = iterator.next();
toReturn.add(iterator.getSheetName());
stream.close();
}
return toReturn;
} catch (InvalidFormatException e) {
throw new JetelRuntimeException(e);
} catch (IOException e) {
throw new JetelRuntimeException(e);
}
}
@Override
public int getCurrentRecordStartRow() {
return nextRecordStartRow;
}
@Override
public boolean setCurrentSheet(int sheetNumber) {
endOfSheet = false;
if (currentSheetIndex >= sheetNumber) {
closeCurrentInputStream();
initializeSheetIterator();
}
while (currentSheetIndex < sheetNumber && sheetIterator.hasNext()) {
closeCurrentInputStream();
currentSheetInputStream = sheetIterator.next();
currentSheetIndex++;
}
if (currentSheetIndex == sheetNumber) {
try {
staxParser = xmlInputFactory.createXMLStreamReader(currentSheetInputStream);
xssfContentHandler = new XSSFSheetXMLHandler(sharedStringsTable, sheetContentHandler);
sheetContentHandler.setRecordStartRow(parent.startLine);
sheetContentHandler.prepareForNextSheet();
} catch (Exception e) {
throw new JetelRuntimeException("Failed to create XML parser for sheet " + sheetIterator.getSheetName(), e);
}
this.nextRecordStartRow = parent.startLine;
cellBuffers.clear();
sheetName = getSheetNames().get(sheetNumber);
return true;
}
return false;
}
@Override
public String[][] getHeader(int startRow, int startColumn, int endRow, int endColumn) {
if (opcPackage == null) {
return null;
}
try {
List<List<CellValue>> rows = readRows(startRow, startColumn, endRow, endColumn);
String[][] result = new String[rows.size()][];
int i = 0;
for (List<CellValue> row : rows) {
if (row != null && !row.isEmpty()) {
result[i] = new String[row.get(row.size() - 1).columnIndex - startColumn + 1];
for (CellValue cellValue : row) {
result[i][cellValue.columnIndex - startColumn] = cellValue.value;
}
} else {
result[i] = new String[0];
}
i++;
}
return result;
} catch (ComponentNotReadyException e) {
throw new JetelRuntimeException("Failed to provide preview", e);
}
}
@Override
public void prepareInput(Object inputSource) throws IOException, ComponentNotReadyException {
try {
if (inputSource instanceof InputStream) {
opcPackage = OPCPackage.open((InputStream) inputSource);
} else {
File inputFile = (File) inputSource;
fileName = inputFile.getAbsolutePath();
opcPackage = OPCPackage.open(inputFile.getAbsolutePath());
}
reader = new XSSFReader(opcPackage);
stylesTable = reader.getStylesTable();
sharedStringsTable = new ReadOnlySharedStringsTable(opcPackage);
sheetContentHandler = new RecordFillingContentHandler(stylesTable, dataFormatter);
cellBuffers.init(CellValue.class, sheetContentHandler, sheetContentHandler.getFieldValueToFormatSetter());
} catch (InvalidFormatException e) {
throw new ComponentNotReadyException("Error opening the XLSX workbook!", e);
} catch (OpenXML4JException e) {
throw new ComponentNotReadyException("Error opening the XLSX workbook!", e);
} catch (SAXException e) {
throw new ComponentNotReadyException("Error opening the XLSX workbook!", e);
}
initializeSheetIterator();
}
@Override
public void close() throws IOException {
try {
staxParser.close();
} catch (XMLStreamException e) {
LOGGER.warn("Closing parser threw exception", e);
}
closeCurrentInputStream();
}
private static void processParserEvent(XMLStreamReader staxParser, XSSFSheetXMLHandler contentHandler)
throws XMLStreamException, SAXException {
staxParser.next();
switch (staxParser.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
AttributesImpl attrs = new AttributesImpl();
for (int i = 0; i < staxParser.getAttributeCount(); i++) {
attrs.addAttribute(staxParser.getAttributeNamespace(i), staxParser.getAttributeLocalName(i),
qNameToStr(staxParser.getAttributeName(i)), staxParser.getAttributeType(i), staxParser.getAttributeValue(i));
}
contentHandler.startElement(staxParser.getNamespaceURI(), staxParser.getLocalName(), qNameToStr(staxParser.getName()), attrs);
break;
case XMLStreamConstants.CHARACTERS:
contentHandler.characters(staxParser.getTextCharacters(), staxParser.getTextStart(), staxParser.getTextLength());
break;
case XMLStreamConstants.END_ELEMENT:
contentHandler.endElement(staxParser.getNamespaceURI(), staxParser.getLocalName(), qNameToStr(staxParser.getName()));
break;
}
}
private static String qNameToStr(QName qName) {
String prefix = qName.getPrefix();
return prefix.isEmpty() ? qName.getLocalPart() : prefix + ":" + qName.getLocalPart();
}
private void closeCurrentInputStream() {
if (currentSheetInputStream != null) {
try {
currentSheetInputStream.close();
currentSheetInputStream = null;
} catch (IOException e) {
LOGGER.warn("Failed to close input stream", e);
}
}
}
private void initializeSheetIterator() {
try {
sheetIterator = (SheetIterator) reader.getSheetsData();
currentSheetIndex = -1;
} catch (Exception e) {
throw new JetelRuntimeException(e);
}
}
private List<List<CellValue>> readRows(int startRow, int startColumn, int endRow, int endColumn)
throws ComponentNotReadyException {
List<List<CellValue>> rows = new LinkedList<List<CellValue>>();
XMLStreamReader parser = null;
try {
parser = xmlInputFactory.createXMLStreamReader(currentSheetInputStream);
RawRowContentHandler rowContentHandler = new RawRowContentHandler(stylesTable, dataFormatter, startColumn, endColumn);
XSSFSheetXMLHandler xssfContentHandler = new XSSFSheetXMLHandler(sharedStringsTable, rowContentHandler);
int currentRow = startRow;
while (currentRow < endRow) {
rowContentHandler.setRecordStartRow(currentRow);
while (parser.hasNext() && !rowContentHandler.isRecordFinished()) {
processParserEvent(parser, xssfContentHandler);
}
if (!parser.hasNext() && !rowContentHandler.isRecordFinished()) {
return rows;
}
rows.add(rowContentHandler.getCellValues());
currentRow++;
}
} catch (XMLStreamException e) {
throw new ComponentNotReadyException("Error occurred while reading XML of sheet " + currentSheetIndex, e);
} catch (SAXException e) {
throw new ComponentNotReadyException("Error occurred while reading XML of sheet " + currentSheetIndex, e);
} finally {
closeCurrentInputStream();
if (parser != null) {
try {
parser.close();
} catch (XMLStreamException e) {
LOGGER.warn("Closing parser threw an exception", e);
}
}
}
setCurrentSheet(currentSheetIndex);
return rows;
}
// based on org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(Cell)
// public boolean isCellDateFormatted(CellValue cell) {
// boolean bDate = false;
// double d = Double.parseDouble(cell.value);
// if (DateUtil.isValidExcelDate(d) ) {
// CellStyle style = stylesTable.getStyleAt(cell.styleIndex);
// if (style == null) return false;
// int i = style.getDataFormat();
// String f = style.getDataFormatString();
// if (f == null) {
// f = BuiltinFormats.getBuiltinFormat(i);
// bDate = DateUtil.isADateFormat(i, f);
// return bDate;
private abstract class SheetRowContentHandler implements SheetContentsHandler {
/* row on which starts currently read record */
protected int recordStartRow;
/* row where current record finishes */
protected int recordEndRow;
/* actual row which is being parsed */
protected int currentParseRow;
/* flag indicating whether row where current record finishes was read */
protected boolean recordStarted;
protected boolean recordFinished;
protected CellValueFormatter formatter;
protected StylesTable stylesTable;
public SheetRowContentHandler(StylesTable stylesTable, CellValueFormatter formatter) {
this.stylesTable = stylesTable;
this.formatter = formatter;
}
public void prepareForNextSheet() {
recordStartRow = parent.startLine;
recordEndRow = 0;
currentParseRow = -1;
}
public void setRecordStartRow(int startRow) {
recordStartRow = startRow;
recordEndRow = startRow + parent.mapping.length - 1;
recordStarted = false;
recordFinished = recordEndRow < currentParseRow;
}
public boolean isRecordFinished() {
return recordFinished;
}
public boolean isRecordStarted() {
return recordStarted;
}
@Override
public void startRow(int rowNum) {
currentParseRow = rowNum;
if (currentParseRow > recordEndRow) {
recordFinished = true;
}
}
@Override
public void endRow() {
if (currentParseRow >= recordEndRow) {
recordFinished = true;
}
}
@Override
public void headerFooter(String text, boolean isHeader, String tagName) {
// Do nothing, not interested
}
protected String getFormatString(int styleIndex) {
XSSFCellStyle style = stylesTable.getStyleAt(styleIndex);
String formatString = style.getDataFormatString();
if (formatString == null) {
formatString = BuiltinFormats.getBuiltinFormat(style.getDataFormat());
}
return formatString;
}
protected String formatNumericToString(String value, int styleIndex, String locale) {
XSSFCellStyle style = stylesTable.getStyleAt(styleIndex);
String formatString = getFormatString(styleIndex);
return formatter.formatRawCellContents(Double.parseDouble(value), style.getDataFormat(), formatString, null);
}
}
private class RawRowContentHandler extends SheetRowContentHandler {
private List<CellValue> cellValues = new ArrayList<CellValue>();
private final int firstColumn;
private final int lastColumn;
public RawRowContentHandler(StylesTable stylesTable, CellValueFormatter formatter, int firstColumn, int lastColumn) {
super(stylesTable, formatter);
this.firstColumn = firstColumn;
this.lastColumn = lastColumn;
}
public List<CellValue> getCellValues() {
return new ArrayList<XLSXStreamParser.CellValue>(cellValues);
}
@Override
public void setRecordStartRow(int startRow) {
recordStartRow = startRow;
recordEndRow = startRow;
recordStarted = false;
recordFinished = false;
cellValues.clear();
}
@Override
public void cell(String cellReference, int cellType, int formulaType, String value, int styleIndex) {
if (currentParseRow == recordStartRow) {
int columnIndex = SpreadsheetUtils.getColumnIndex(cellReference);
if (columnIndex < firstColumn || columnIndex >= lastColumn) {
return;
}
String formattedValue = value;
if (cellType == Cell.CELL_TYPE_NUMERIC || (cellType == Cell.CELL_TYPE_FORMULA && formulaType == Cell.CELL_TYPE_NUMERIC)) {
formattedValue = formatNumericToString(value, styleIndex, null);
}
if (cellType != Cell.CELL_TYPE_BLANK) {
cellValues.add(new CellValue(columnIndex, formattedValue, cellType, formulaType, styleIndex));
}
}
}
}
private class RecordFillingContentHandler extends SheetRowContentHandler implements RecordFieldValueSetter<CellValue> {
private DataRecord record;
private int lastColumn = -1;
private int skipStartRow;
private boolean skipRecords = false;
private final RecordFieldValueSetter<CellValue> fieldValueToFormatSetter = new FieldValueToFormatSetter();
public RecordFillingContentHandler(StylesTable stylesTable, CellValueFormatter formatter) {
super(stylesTable, formatter);
}
public void finishRecord() {
for (int i = currentParseRow + 1; i <= recordEndRow; i++) {
handleMissingCells(i - recordStartRow, lastColumn, parent.mapping[0].length);
}
}
public void setRecord(DataRecord record) {
this.record = record;
cellBuffers.fillRecordFromBuffer(record);
}
public boolean isSkipRecords() {
return skipRecords;
}
public int getNumberOfSkippedRecords() {
int result = currentParseRow - skipStartRow;
return result > 0 ? result / parent.mappingInfo.getStep() : 0;
}
public void skipRecords(int nRec) {
if (nRec > 0) {
skipStartRow = recordStartRow;
record = null;
int numberOfRows = nRec * parent.mappingInfo.getStep();
setRecordStartRow(recordStartRow + numberOfRows);
skipRecords = true;
}
}
@Override
public void cell(String cellReference, int cellType, int formulaType, String value, int styleIndex) {
if (currentParseRow < recordStartRow) {
// not interested yet, skip
return;
}
int columnIndex = SpreadsheetUtils.getColumnIndex(cellReference);
if (columnIndex < parent.mappingMinColumn || columnIndex >= parent.mapping[0].length + parent.mappingMinColumn) {
// not interested, skip
return;
}
int shiftedColumnIndex = columnIndex - parent.mappingMinColumn;
int mappingRow = currentParseRow - recordStartRow;
handleMissingCells(mappingRow, lastColumn, shiftedColumnIndex);
lastColumn = shiftedColumnIndex;
CellValue cellValue = new CellValue(-1, value, cellType, formulaType, styleIndex);
cellBuffers.setCellBufferValue(mappingRow, shiftedColumnIndex, cellValue);
if (record != null) {
if (parent.mapping[mappingRow][shiftedColumnIndex] != XLSMapping.UNDEFINED) {
setFieldValue(parent.mapping[mappingRow][shiftedColumnIndex], cellValue);
}
if (parent.formatMapping != null) {
if (parent.formatMapping[mappingRow][shiftedColumnIndex] != XLSMapping.UNDEFINED) {
fieldValueToFormatSetter.setFieldValue(parent.formatMapping[mappingRow][shiftedColumnIndex], cellValue);
}
}
}
}
@Override
public void startRow(int rowNum) {
super.startRow(rowNum);
if (currentParseRow >= recordStartRow) {
skipRecords = false;
}
}
@Override
public void endRow() {
super.endRow();
if (!skipRecords && currentParseRow >= recordStartRow) {
handleMissingCells(currentParseRow - recordStartRow, lastColumn, parent.mapping[0].length);
}
lastColumn = -1;
}
private void handleMissingCells(int mappingRow, int firstColumn, int lastColumn) {
handleMissingCells(parent.mapping[mappingRow], mappingRow, firstColumn, lastColumn);
if (parent.formatMapping != null) {
handleMissingCells(parent.formatMapping[mappingRow], mappingRow, firstColumn, lastColumn);
}
}
private void handleMissingCells(int[] mappingPart, int mappingRow, int firstColumn, int lastColumn) {
for (int i = firstColumn + 1; i < lastColumn; i++) {
int cloverFieldIndex = mappingPart[i];
if (cloverFieldIndex != XLSMapping.UNDEFINED) {
try {
record.getField(cloverFieldIndex).setNull(true);
if (endOfSheet) {
parent.handleException(new SpreadsheetException("Unexpected end of sheet - expected one more data row for field " + record.getField(cloverFieldIndex).getMetadata().getName() +
". Occurred"), record, cloverFieldIndex, fileName, sheetName, null, null, null, null);
}
} catch (BadDataFormatException e) {
parent.handleException(new SpreadsheetException("Cell is empty, but cannot set default value or null into field " + record.getField(cloverFieldIndex).getMetadata().getName(), e), record, cloverFieldIndex, fileName, sheetName, null, null, null, null);
}
}
}
}
@Override
public void setFieldValue(int fieldIndex, CellValue cell) {
setFieldValue(fieldIndex, cell.type, cell.formulaType, cell.value, cell.styleIndex);
}
private void setFieldValue(int cloverFieldIndex, int cellType, int formulaType, String value, int styleIndex) {
if (!recordStarted) {
recordStarted = true;
}
DataField field = record.getField(cloverFieldIndex);
String cellFormat = null;
try {
switch (field.getType()) {
case DataFieldMetadata.DATE_FIELD:
case DataFieldMetadata.DATETIME_FIELD:
if (cellType == Cell.CELL_TYPE_NUMERIC) {
field.setValue(DateUtil.getJavaDate(Double.parseDouble(value), AbstractSpreadsheetParser.USE_DATE1904));
} else {
throw new IllegalStateException("Cannot get Date value from cell of type " + cellTypeToString(cellType));
}
break;
case DataFieldMetadata.BYTE_FIELD:
case DataFieldMetadata.STRING_FIELD:
if (cellType == Cell.CELL_TYPE_NUMERIC || (cellType == Cell.CELL_TYPE_FORMULA && formulaType == Cell.CELL_TYPE_NUMERIC)) {
field.fromString(formatNumericToString(value, styleIndex, field.getMetadata().getLocaleStr()));
} else {
field.fromString(value);
}
break;
case DataFieldMetadata.DECIMAL_FIELD:
case DataFieldMetadata.INTEGER_FIELD:
case DataFieldMetadata.LONG_FIELD:
case DataFieldMetadata.NUMERIC_FIELD:
if (cellType == Cell.CELL_TYPE_NUMERIC || cellType == Cell.CELL_TYPE_FORMULA) {
field.setValue(Double.parseDouble(value));
} else {
throw new IllegalStateException("Cannot get Numeric value from cell of type " + cellTypeToString(cellType));
}
break;
case DataFieldMetadata.BOOLEAN_FIELD:
if (cellType == Cell.CELL_TYPE_BOOLEAN) {
field.setValue(XSSFSheetXMLHandler.CELL_VALUE_TRUE.equals(value));
} else {
throw new IllegalStateException("Cannot get Boolean value from cell of type " + cellTypeToString(cellType));
}
break;
}
} catch (RuntimeException ex1) { // exception when trying get date or number from a different cell type
try {
// field.fromString(value);
field.setNull(true);
} catch (Exception ex2) {
}
String cellCoordinates = SpreadsheetUtils.getColumnReference(lastColumn + parent.mappingMinColumn) + String.valueOf(currentParseRow);
// parent.handleException(new BadDataFormatException("All attempts to set value \""+ value +"\" into field \"" + field.getMetadata().getName() + "\" (" + field.getMetadata().getTypeAsString() + ") failed:\n1st try error: " + ex1 + "\n"),
// record, cloverFieldIndex, cellCoordinates, value);
parent.handleException(new SpreadsheetException(ex1.getMessage() + " in " + cellCoordinates), record, cloverFieldIndex,
fileName, sheetName, cellCoordinates, value, cellTypeToString(cellType), cellFormat);
}
}
private String cellTypeToString(int cellType) {
switch (cellType) {
case Cell.CELL_TYPE_BOOLEAN:
return "Boolean";
case Cell.CELL_TYPE_STRING:
return "String";
case Cell.CELL_TYPE_NUMERIC:
return "Numeric";
case Cell.CELL_TYPE_FORMULA:
return "Formula";
case Cell.CELL_TYPE_BLANK:
return "Blank";
default:
return "Unknown";
}
}
protected RecordFieldValueSetter<CellValue> getFieldValueToFormatSetter() {
return fieldValueToFormatSetter;
}
private class FieldValueToFormatSetter implements RecordFieldValueSetter<CellValue> {
@Override
public void setFieldValue(int cloverFieldIndex, CellValue cellValue) {
DataField field = record.getField(cloverFieldIndex);
String format = getFormatString(cellValue.styleIndex);
field.fromString(format);
}
}
}
private static class CellValue {
public final int columnIndex;
public final String value;
public final int type;
public final int formulaType;
public final int styleIndex;
CellValue(int columnIndex, String value, int type, int formulaType, int styleIndex) {
this.columnIndex = columnIndex;
this.value = value;
this.type = type;
this.formulaType = formulaType;
this.styleIndex = styleIndex;
}
}
}
|
package org.ovirt.engine.ui.uicommonweb.models.datacenters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.comparators.NameableComparator;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.help.HelpTag;
import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel;
import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
@SuppressWarnings("unused")
public class DataCenterNetworkListModel extends SearchableListModel
{
private UICommand privateNewCommand;
public UICommand getNewCommand()
{
return privateNewCommand;
}
private void setNewCommand(UICommand value)
{
privateNewCommand = value;
}
private UICommand privateEditCommand;
public UICommand getEditCommand()
{
return privateEditCommand;
}
private void setEditCommand(UICommand value)
{
privateEditCommand = value;
}
private UICommand privateRemoveCommand;
public UICommand getRemoveCommand()
{
return privateRemoveCommand;
}
private void setRemoveCommand(UICommand value)
{
privateRemoveCommand = value;
}
@Override
public StoragePool getEntity()
{
return (StoragePool) super.getEntity();
}
public void setEntity(StoragePool value)
{
super.setEntity(value);
}
public DataCenterNetworkListModel()
{
setTitle(ConstantsManager.getInstance().getConstants().logicalNetworksTitle());
setHelpTag(HelpTag.logical_networks);
setHashName("logical_networks"); //$NON-NLS-1$
setNewCommand(new UICommand("New", this)); //$NON-NLS-1$
setEditCommand(new UICommand("Edit", this)); //$NON-NLS-1$
setRemoveCommand(new UICommand("Remove", this)); //$NON-NLS-1$
updateActionAvailability();
}
@Override
protected void onEntityChanged()
{
super.onEntityChanged();
getSearchCommand().execute();
}
@Override
public void search()
{
if (getEntity() != null)
{
super.search();
}
}
@Override
protected void syncSearch()
{
if (getEntity() == null)
{
return;
}
super.syncSearch();
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object ReturnValue)
{
ArrayList<Network> newItems = ((VdcQueryReturnValue) ReturnValue).getReturnValue();
Collections.sort(newItems, new NameableComparator());
SearchableListModel searchableListModel = (SearchableListModel) model;
searchableListModel.setItems(newItems);
}
};
IdQueryParameters tempVar = new IdQueryParameters(getEntity().getId());
tempVar.setRefresh(getIsQueryFirstTime());
Frontend.getInstance().runQuery(VdcQueryType.GetAllNetworks, tempVar, _asyncQuery);
}
public void remove()
{
if (getConfirmWindow() != null)
{
return;
}
ConfirmationModel model = new RemoveNetworksModel(this);
setConfirmWindow(model);
}
public void edit()
{
final Network network = (Network) getSelectedItem();
if (getWindow() != null)
{
return;
}
final NetworkModel networkModel = new EditNetworkModel(network, this);
setWindow(networkModel);
networkModel.getDataCenters().setItems(Arrays.asList(getEntity()));
networkModel.getDataCenters().setSelectedItem(getEntity());
}
public void newNetwork()
{
if (getWindow() != null)
{
return;
}
final NetworkModel networkModel = new NewNetworkModel(this);
setWindow(networkModel);
networkModel.getDataCenters().setItems(Arrays.asList(getEntity()));
networkModel.getDataCenters().setSelectedItem(getEntity());
}
@Override
protected void onSelectedItemChanged()
{
super.onSelectedItemChanged();
updateActionAvailability();
}
@Override
protected void selectedItemsChanged()
{
super.selectedItemsChanged();
updateActionAvailability();
}
private void updateActionAvailability()
{
List tempVar = getSelectedItems();
ArrayList selectedItems =
(ArrayList) ((tempVar != null) ? tempVar : new ArrayList());
getEditCommand().setIsExecutionAllowed(selectedItems.size() == 1);
getRemoveCommand().setIsExecutionAllowed(selectedItems.size() > 0);
}
@Override
public void executeCommand(UICommand command)
{
super.executeCommand(command);
if (command == getNewCommand())
{
newNetwork();
}
else if (command == getEditCommand())
{
edit();
}
else if (command == getRemoveCommand())
{
remove();
}
}
@Override
protected String getListName() {
return "DataCenterNetworkListModel"; //$NON-NLS-1$
}
}
|
package org.jetel.util.compile;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject.Kind;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Java compiler for dynamic compilation of Java source code.
*
* @author Martin Janik, Javlin a.s. <martin.janik@javlin.eu>
*
* @version 2nd June 2010
* @created 14th May 2010
*
* @see JavaCompiler
*/
public final class DynamicCompiler {
private static final Log logger = LogFactory.getLog(DynamicCompiler.class);
/** The class loader to be used during compilation and class loading. */
private final ClassLoader classLoader;
/** Additional class path URLs to be used during compilation and class loading. */
private final URL[] classPathUrls;
/**
* Constructs a <code>DynamicCompiler</code> instance for a given class loader to be used during compilation.
* Additional class path URLs may be provided if any external Java classes are required.
*
* @param classLoader the class loader to be used, may be <code>null</code>
* @param classPathUrls the array of additional class path URLs, may be <code>null</code>
*/
public DynamicCompiler(ClassLoader classLoader, URL... classPathUrls) {
this.classLoader = classLoader;
this.classPathUrls = classPathUrls; // <- potential encapsulation problem, defensive copying would solve that
}
/**
* Compiles a given piece of Java source code and then loads a desired class. This method may be called repeatedly.
*
* @param sourceCode the Java source code to be compiled, may not be <code>null</code>
* @param className the name of a Java class (present in the source) code to be loaded, may not be <code>null</code>
*
* @return the class instance loaded from the compiled source code
*
* @throws NullPointerException if either the argument is <code>null</code>
* @throws CompilationException if the compilation failed
*/
public Class<?> compile(String sourceCode, String className) throws CompilationException {
if (sourceCode == null) {
throw new NullPointerException("sourceCode");
}
if (className == null) {
throw new NullPointerException("className");
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaClassFileManager fileManager = new JavaClassFileManager(compiler, classLoader, classPathUrls);
logger.debug("Java compile time classpath (-cp) for class '" + className + "': " + fileManager.getClassPath());
StringWriter compilerOutput = new StringWriter();
CompilationTask task = compiler.getTask(compilerOutput, fileManager, null,
Arrays.asList("-cp", fileManager.getClassPath()), null,
Arrays.asList(new JavaSourceFileObject(className, sourceCode)));
if (!task.call()) {
throw new CompilationException("Compilation failed! See compiler output for more details.",
compilerOutput.toString());
}
try {
return fileManager.loadClass(className);
} catch (ClassNotFoundException exception) {
throw new CompilationException("Loading of class " + className + " failed!", exception);
}
}
/**
* Java source code wrapper used by {@link JavaCompiler}.
*
* @author Martin Janik, Javlin a.s. <martin.janik@javlin.eu>
*
* @version 28th May 2010
* @created 14th May 2010
*/
private static final class JavaSourceFileObject extends SimpleJavaFileObject {
/** The Java source code. */
private final String sourceCode;
public JavaSourceFileObject(String name, String sourceCode) {
super(URI.create(name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.sourceCode = sourceCode;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return sourceCode;
}
}
/**
* Java class file wrapper used by {@link JavaCompiler}.
*
* @author Martin Janik, Javlin a.s. <martin.janik@javlin.eu>
*
* @version 28th May 2010
* @created 14th May 2010
*/
private static final class JavaClassFileObject extends SimpleJavaFileObject {
/** The class data in a form of Java byte code. */
private final ByteArrayOutputStream classData = new ByteArrayOutputStream();
public JavaClassFileObject(String name) {
super(URI.create(name.replace('.', '/') + Kind.CLASS.extension), Kind.CLASS);
}
@Override
public OutputStream openOutputStream() throws IOException {
return classData;
}
public byte[] getData() {
return classData.toByteArray();
}
}
/**
* Java class file manager used by {@link JavaCompiler}.
*
* @author Martin Janik, Javlin a.s. <martin.janik@javlin.eu>
*
* @version 2nd June 2010
* @created 14th May 2010
*/
private static final class JavaClassFileManager extends ForwardingJavaFileManager<JavaFileManager> {
/** The class loader used to load classes directly from Java byte code. */
private final ByteCodeClassLoader classLoader;
public JavaClassFileManager(JavaCompiler compiler, ClassLoader classLoader, URL[] classPathUrls) {
super(compiler.getStandardFileManager(null, null, null));
this.classLoader = new ByteCodeClassLoader(classLoader, classPathUrls);
}
public String getClassPath() {
return ClassLoaderUtils.getClasspath(classLoader.getParent(), classLoader.getURLs());
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling)
throws IOException {
JavaClassFileObject javaClass = new JavaClassFileObject(className);
classLoader.registerClass(className, javaClass);
return javaClass;
}
public Class<?> loadClass(String name) throws ClassNotFoundException {
return classLoader.loadClass(name);
}
}
/**
* Class loader used to load classes directly from Java byte code.
*
* @author Martin Janik, Javlin a.s. <martin.janik@javlin.eu>
*
* @version 2nd June 2010
* @created 14th May 2010
*/
private static final class ByteCodeClassLoader extends URLClassLoader {
/** The map of compiled Java classes that can be loaded by this class loader. */
private final Map<String, JavaClassFileObject> javaClasses = new HashMap<String, JavaClassFileObject>();
public ByteCodeClassLoader(ClassLoader parent, URL[] classPathUrls) {
super((classPathUrls != null) ? classPathUrls : new URL[0], parent);
}
public void registerClass(String name, JavaClassFileObject byteCode) {
javaClasses.put(name, byteCode);
}
@Override
protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class<?> clazz = findLoadedClass(name);
if (clazz == null) {
JavaClassFileObject javaClass = javaClasses.get(name);
if (javaClass != null) {
try {
byte[] classData = javaClass.getData();
clazz = defineClass(name, classData, 0, classData.length);
} catch(ClassFormatError error) {
throw new ClassNotFoundException(name, error);
}
} else {
clazz = super.loadClass(name, false);
}
}
if (resolve) {
resolveClass(clazz);
}
return clazz;
}
}
}
|
package org.jetel.interpreter;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Properties;
import junit.framework.TestCase;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.data.SetVal;
import org.jetel.data.primitive.CloverDouble;
import org.jetel.data.primitive.CloverInteger;
import org.jetel.data.primitive.CloverLong;
import org.jetel.data.primitive.Decimal;
import org.jetel.data.primitive.DecimalFactory;
import org.jetel.data.primitive.Numeric;
import org.jetel.interpreter.node.CLVFStart;
import org.jetel.interpreter.node.CLVFStartExpression;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataRecordMetadata;
/**
* @author dpavlis
* @since 10.8.2004
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class TestInterpreter extends TestCase {
DataRecordMetadata metadata;
DataRecord record,out;
protected void setUp() {
Defaults.init();
metadata=new DataRecordMetadata("TestInput",DataRecordMetadata.DELIMITED_RECORD);
metadata.addField(new DataFieldMetadata("Name",DataFieldMetadata.STRING_FIELD, ";"));
metadata.addField(new DataFieldMetadata("Age",DataFieldMetadata.NUMERIC_FIELD, "|"));
metadata.addField(new DataFieldMetadata("City",DataFieldMetadata.STRING_FIELD, "\n"));
metadata.addField(new DataFieldMetadata("Born",DataFieldMetadata.DATE_FIELD, "\n"));
metadata.addField(new DataFieldMetadata("Value",DataFieldMetadata.INTEGER_FIELD, "\n"));
record = new DataRecord(metadata);
record.init();
out = new DataRecord(metadata);
out.init();
SetVal.setString(record,0," HELLO ");
SetVal.setInt(record,1,135);
SetVal.setString(record,2,"Some silly longer string.");
SetVal.setValue(record,3,Calendar.getInstance().getTime());
record.getField("Born").setNull(true);
SetVal.setInt(record,4,-999);
}
protected void tearDown() {
metadata= null;
record=null;
out=null;
}
public void test_int(){
System.out.println("int test:");
String expStr = "int i; i=0; print_err(i); \n"+
"int j; j=-1; print_err(j);\n"+
"int minInt; minInt="+Integer.MIN_VALUE+"; print_err(minInt);\n"+
"int maxInt; maxInt="+Integer.MAX_VALUE+"; print_err(maxInt)"+
"int field; field=$Value; print_err(field)";
try {
print_code(expStr);
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(0,((CloverInteger)result[0]).intValue());
assertEquals(-1,((CloverInteger)result[1]).intValue());
assertEquals(Integer.MIN_VALUE,((CloverInteger)result[2]).intValue());
assertEquals(Integer.MAX_VALUE,((CloverInteger)result[3]).intValue());
assertEquals(((Integer)record.getField("Value").getValue()).intValue(),((CloverInteger)result[4]).intValue());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_long(){
System.out.println("\nlong test:");
String expStr = "long i; i=0; print_err(i); \n"+
"long j; j=-1; print_err(j);\n"+
"long minLong; minLong="+(Long.MIN_VALUE+1)+"; print_err(minLong);\n"+
"long maxLong; maxLong="+(Long.MAX_VALUE)+"; print_err(maxLong);\n"+
"long field; field=$Value; print_err(field);\n"+
"long wrong;wrong="+Long.MAX_VALUE+"; print_err(wrong);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(0,((CloverLong)result[0]).longValue());
assertEquals(-1,((CloverLong)result[1]).longValue());
assertEquals(Long.MIN_VALUE+1,((CloverLong)result[2]).longValue());
assertEquals(Long.MAX_VALUE,((CloverLong)result[3]).longValue());
assertEquals(((Integer)record.getField("Value").getValue()).longValue(),((CloverLong)result[4]).longValue());
// assertEquals(Integer.MAX_VALUE,((CloverInteger)result[5]).intValue());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_decimal(){
System.out.println("\ndecimal test:");
String expStr = "decimal i; i=0; print_err(i); \n"+
"decimal j; j=-1.0; print_err(j);\n"+
"decimal(18,3) minLong; minLong=999999.999; print_err(minLong);\n"+
"decimal maxLong; maxLong=0000000.0000000; print_err(maxLong);\n"+
"decimal fieldValue; fieldValue=$Value; print_err(fieldValue);\n"+
"decimal fieldAge; fieldAge=$Age; print_err(fieldAge);\n"+
"decimal(400,350) minDouble; minDouble="+Double.MIN_VALUE+"; print_err(minDouble);\n" +
"decimal def;print_err(def);\n" +
"print_err('the end');\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(DecimalFactory.getDecimal(0),((Decimal)result[0]));
assertEquals(DecimalFactory.getDecimal(-1),((Decimal)result[1]));
assertEquals(DecimalFactory.getDecimal(999999.999),((Decimal)result[2]));
assertEquals(DecimalFactory.getDecimal(0),((Decimal)result[3]));
assertEquals(((Integer)record.getField("Value").getValue()).intValue(),((Decimal)result[4]).getInt());
assertEquals((Double)record.getField("Age").getValue(),new Double(((Decimal)result[5]).getDouble()));
assertEquals(new Double(Double.MIN_VALUE),new Double(((Decimal)result[6]).getDouble()));
// assertEquals(DecimalFactory.getDecimal(),(Decimal)result[7]);
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_number(){
System.out.println("\nnumber test:");
String expStr = "number i; i=0; print_err(i); \n"+
"number j; j=-1.0; print_err(j);\n"+
"number minLong; minLong=999999.99911; print_err(minLong); \n"+
"number fieldValue; fieldValue=$Value; print_err(fieldValue);\n"+
"number fieldAge; fieldAge=$Age; print_err(fieldAge);\n"+
"number minDouble; minDouble="+Double.MIN_VALUE+"; print_err(minDouble)" +
"number def;print_err(def);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(new CloverDouble(0),((CloverDouble)result[0]));
assertEquals(new CloverDouble(-1),((CloverDouble)result[1]));
assertEquals(new CloverDouble(999999.99911),((CloverDouble)result[2]));
assertEquals(new CloverDouble(((Integer)record.getField("Value").getValue())),((CloverDouble)result[3]));
assertEquals(new CloverDouble((Double)record.getField("Age").getValue()),((CloverDouble)result[4]));
assertEquals(new CloverDouble(Double.MIN_VALUE),((CloverDouble)result[5]));
assertEquals(new CloverDouble(0),((CloverDouble)result[6]));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_string(){
System.out.println("\nstring test:");
int lenght=1000;
StringBuffer tmp = new StringBuffer(lenght);
for (int i=0;i<lenght;i++){
tmp.append(i%10);
}
String expStr = "string i; i=\"0\"; print_err(i); \n"+
"string hello; hello='hello'; print_err(hello);\n"+
"string fieldName; fieldName=$Name; print_err(fieldName);\n"+
"string fieldCity; fieldCity=$City; print_err(fieldCity);\n"+
"string longString; longString=\""+tmp+"\"; print_err(longString);\n"+
"string specialChars; specialChars='a\u0101\u0102A'; print_err(specialChars);";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes("UTF-8")));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals("0",((StringBuffer)result[0]).toString());
assertEquals("hello",((StringBuffer)result[1]).toString());
assertEquals(record.getField("Name").getValue().toString(),((StringBuffer)result[2]).toString());
assertEquals(record.getField("City").getValue().toString(),((StringBuffer)result[3]).toString());
assertEquals(tmp.toString(),((StringBuffer)result[4]).toString());
assertEquals("a\u0101\u0102A",((StringBuffer)result[5]).toString());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
} catch (UnsupportedEncodingException ex){
ex.printStackTrace();
}
}
public void test_date(){
System.out.println("\ndate test:");
String expStr = "date d3; d3=2006-08-01; print_err(d3);\n"+
"date d2; d2=2006-08-02 15:15:00 ; print_err(d2);\n"+
"date d1; d1=2006-1-1 1:2:3; print_err(d1);\n"+
"date born; born=$0.Born; print_err(born);";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(new GregorianCalendar(2006,7,01).getTime(),((Date)result[0]));
assertEquals(new GregorianCalendar(2006,7,02,15,15).getTime(),((Date)result[1]));
assertEquals(new GregorianCalendar(2006,0,01,01,02,03).getTime(),((Date)result[2]));
assertEquals((Date)record.getField("Born").getValue(),((Date)result[3]));
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_boolean(){
System.out.println("\nboolean test:");
String expStr = "boolean b1; b1=true; print_err(b1);\n"+
"boolean b2; b2=false ; print_err(b2);\n"+
"boolean b4; print_err(b4);";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(true,((Boolean)result[0]).booleanValue());
assertEquals(false,((Boolean)result[1]).booleanValue());
assertEquals(false,((Boolean)result[2]).booleanValue());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_variables(){
System.out.println("\nvariable test:");
String expStr = "boolean b1; boolean b2; b1=true; print_err(b1);\n"+
"b2=false ; print_err(b2);\n"+
"string b4; b4=\"hello\"; print_err(b4);\n"+
"b2 = true; print_err(b2);\n" +
"if b2 {int in;in=2;print_err('in')}\n"+
"print_err(b2)";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(true,((Boolean)result[0]).booleanValue());
assertEquals(true,((Boolean)result[1]).booleanValue());
assertEquals("hello",((StringBuffer)result[2]).toString());
// assertEquals(2,((CloverInteger)result[3]).getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_plus(){
System.out.println("\nplus test:");
String expStr = "int i; i=10;\n"+
"int j; j=100;\n" +
"int iplusj;iplusj=i+j; print_err(\"plus int:\"+iplusj);\n" +
"long l;l="+Integer.MAX_VALUE/10+"l;print_err(l);\n" +
"long m;m="+(Integer.MAX_VALUE)+"l;print_err(m)\n" +
"long lplusm;lplusm=l+m;print_err(\"plus long:\"+lplusm);\n" +
"number n; n=0;print_err(n);\n" +
"number m1; m1=0.001;print_err(m1);\n" +
"number nplusm1; nplusm1=n+m1;print_err(\"plus number:\"+nplusm1);\n" +
"number nplusj;nplusj=n+j;print_err(\"number plus int:\"+nplusj);\n"+
"decimal d; d=0.1;print_err(d);\n" +
"decimal(10,4) d1; d1=0.0001;print_err(d1);\n" +
"decimal(10,4) dplusd1; dplusd1=d+d1;print_err(\"plus decimal:\"+dplusd1);\n" +
"decimal dplusj;dplusj=d+j;print_err(\"decimal plus int:\"+dplusj);\n" +
"decimal(10,4) dplusn;dplusn=d+m1;print_err(\"decimal plus number:\"+dplusn);\n" +
"dplusn=dplusn+10;\n" +
"string s; s=\"hello\"; print_err(s);\n" +
"string s1;s1=\" world\";print_err(s1);\n " +
"string spluss1;spluss1=s+s1;print_err(\"adding strings:\"+spluss1);\n" +
"string splusm1;splusm1=s+m1;print_err(\"string plus decimal:\"+splusm1);\n" +
"date mydate; mydate=2004-01-30 15:00:30;print_err(mydate);\n" +
"date dateplus;dateplus=mydate+i;print_err(dateplus);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals("iplusj",110,((CloverInteger)result[2]).getInt());
assertEquals("lplusm",(long)Integer.MAX_VALUE+(long)Integer.MAX_VALUE/10,((CloverLong)result[5]).getLong());
assertEquals("nplusm1",new CloverDouble(0.001),(CloverDouble)result[8]);
assertEquals("nplusj",new CloverDouble(100),(CloverDouble)result[9]);
assertEquals("dplusd1",new Double(0.1000),new Double(((Decimal)result[12]).getDouble()));
assertEquals("dplusj",new Double(100.1),new Double(((Decimal)result[13]).getDouble()));
assertEquals("dplusn",new Double(10.1),new Double(((Decimal)result[14]).getDouble()));
assertEquals("spluss1","hello world",(((StringBuffer)result[17]).toString()));
assertEquals("splusm1","hello0.0010",(((StringBuffer)result[18]).toString()));
assertEquals("dateplus",new GregorianCalendar(2004,01,9,15,00,30).getTime(),(Date)result[20]);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_minus(){
System.out.println("\nminus test:");
String expStr = "int i; i=10;\n"+
"int j; j=100;\n" +
"int iplusj;iplusj=i-j; print_err(\"minus int:\"+iplusj);\n" +
"long l;l="+((long)Integer.MAX_VALUE+10)+";print_err(l);\n" +
"long m;m=1;print_err(m)\n" +
"long lplusm;lplusm=l-m;print_err(\"minus long:\"+lplusm);\n" +
"number n; n=0;print_err(n);\n" +
"number m1; m1=0.001;print_err(m1);\n" +
"number nplusm1; nplusm1=n-m1;print_err(\"minus number:\"+nplusm1);\n" +
"number nplusj;nplusj=n-j;print_err(\"number minus int:\"+nplusj);\n"+
"decimal d; d=0.1;print_err(d);\n" +
"decimal(10,4) d1; d1=0.0001;print_err(d1);\n" +
"decimal(10,4) dplusd1; dplusd1=d-d1;print_err(\"minus decimal:\"+dplusd1);\n" +
"decimal dplusj;dplusj=d-j;print_err(\"decimal minus int:\"+dplusj);\n" +
"decimal(10,4) dplusn;dplusn=d-m1;print_err(\"decimal minus number:\"+dplusn);\n" +
"number d1minusm1;d1minusm1=d1-m1;print_err('decimal minus number = number:'+d1minusm1);\n" +
"date mydate; mydate=2004-01-30 15:00:30;print_err(mydate);\n" +
"date dateplus;dateplus=mydate-i;print_err(dateplus);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals("iplusj",-90,((CloverInteger)result[2]).getInt());
assertEquals("lplusm",(long)Integer.MAX_VALUE+9,((CloverLong)result[5]).getLong());
assertEquals("nplusm1",new CloverDouble(-0.001),(CloverDouble)result[8]);
assertEquals("nplusj",new CloverDouble(-100),(CloverDouble)result[9]);
assertEquals("dplusd1",new Double(0.0900),new Double(((Decimal)result[12]).getDouble()));
assertEquals("dplusj",new Double(-99.9),new Double(((Decimal)result[13]).getDouble()));
assertEquals("dplusn",new Double(0.0900),new Double(((Decimal)result[14]).getDouble()));
assertEquals("d1minusm1",new CloverDouble(-0.0009),(CloverDouble)result[15]);
assertEquals("dateplus",new GregorianCalendar(2004,0,20,15,00,30).getTime(),(Date)result[17]);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_multiply(){
System.out.println("\nmultiply test:");
String expStr = "int i; i=10;\n"+
"int j; j=100;\n" +
"int iplusj;iplusj=i*j; print_err(\"multiply int:\"+iplusj);\n" +
"long l;l="+((long)Integer.MAX_VALUE+10)+";print_err(l);\n" +
"long m;m=1;print_err(m)\n" +
"long lplusm;lplusm=l*m;print_err(\"multiply long:\"+lplusm);\n" +
"number n; n=0.1;print_err(n);\n" +
"number m1; m1=-0.01;print_err(m1);\n" +
"number nplusm1; nplusm1=n*m1;print_err(\"multiply number:\"+nplusm1);\n" +
"number m1plusj;m1plusj=m1*j;print_err(\"number multiply int:\"+m1plusj);\n"+
"decimal d; d=-0.1;print_err(d);\n" +
"decimal(10,4) d1; d1=10.01;print_err(d1);\n" +
"decimal(10,4) dplusd1; dplusd1=d*d1;print_err(\"multiply decimal:\"+dplusd1);\n" +
"decimal(10,4) dplusj;dplusj=d*j;print_err(\"decimal multiply int:\"+dplusj);\n"+
"decimal(10,4) dplusn;dplusn=d*n;print_err(\"decimal multiply number:\"+dplusn);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals("i*j",1000,((CloverInteger)result[2]).getInt());
assertEquals("l*m",(long)Integer.MAX_VALUE+10,((CloverLong)result[5]).getLong());
assertEquals("n*m1",new CloverDouble(-0.001),(CloverDouble)result[8]);
assertEquals("m1*j",new CloverDouble(-1),(CloverDouble)result[9]);
assertEquals("d*d1",DecimalFactory.getDecimal(-1.0000),(Decimal)result[12]);
assertEquals("d*j",DecimalFactory.getDecimal(-10),(Decimal)result[13]);
assertEquals("d*n",DecimalFactory.getDecimal(-0.0100),(Decimal)result[14]);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_division(){
System.out.println("\ndivision test:");
String expStr = "int i; i=10;\n"+
"int j; j=100;\n" +
"int iplusj;iplusj=i/j; print_err(\"div int:\"+iplusj);\n" +
"int jdivi;jdivi=j/i; print_err(\"div int:\"+jdivi);\n" +
"long l;l="+((long)Integer.MAX_VALUE+10)+";print_err(l);\n" +
"long m;m=1;print_err(m)\n" +
"long lplusm;lplusm=l/m;print_err(\"div long:\"+lplusm);\n" +
"number n; n=0;print_err(n);\n" +
"number m1; m1=0.01;print_err(m1);\n" +
"number n1; n1=10;print_err(n1);\n" +
"number nplusm1; nplusm1=n/m1;print_err(\"0/0.01:\"+nplusm1);\n" +
"number m1divn; m1divn=m1/n;print_err(\"deleni nulou:\"+m1divn);\n" +
"number m1divn1; m1divn1=m1/n1;print_err(\"deleni numbers:\"+m1divn1);\n" +
"number m1plusj;m1plusj=j/n1;print_err(\"number division int:\"+m1plusj);\n"+
"decimal d; d=0.1;print_err(d);\n" +
"decimal(10,4) d1; d1=0.01;print_err(d1);\n" +
"decimal(10,4) dplusd1; dplusd1=d/d1;print_err(\"div decimal:\"+dplusd1);\n" +
"decimal(10,4) dplusj;dplusj=d/j;print_err(\"decimal div int:\"+dplusj);\n"+
"decimal(10,4) dplusn;dplusn=n1/d;print_err(\"decimal div number:\"+dplusn);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals("i/j",0,((CloverInteger)result[2]).getInt());
assertEquals("j/i",10,((CloverInteger)result[3]).getInt());
assertEquals("l/m",(long)Integer.MAX_VALUE+10,((CloverLong)result[6]).getLong());
assertEquals("n/m1",new CloverDouble(0),(CloverDouble)result[10]);
assertEquals("m1/n",new CloverDouble(Double.POSITIVE_INFINITY),(CloverDouble)result[11]);
assertEquals("m1/n1",new CloverDouble(0.001),(CloverDouble)result[12]);
assertEquals("j/n1",new CloverDouble(10),(CloverDouble)result[13]);
assertEquals("d/d1",DecimalFactory.getDecimal(0.1/0.01),(Decimal)result[16]);
assertEquals("d/j",DecimalFactory.getDecimal(0.0000),(Decimal)result[17]);
assertEquals("n1/d",DecimalFactory.getDecimal(100.0000),(Decimal)result[18]);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_modulus(){
System.out.println("\nmodulus test:");
String expStr = "int i; i=10;\n"+
"int j; j=103;\n" +
"int iplusj;iplusj=j%i; print_err(\"mod int:\"+iplusj);\n" +
"long l;l="+((long)Integer.MAX_VALUE+10)+";print_err(l);\n" +
"long m;m=2;print_err(m)\n" +
"long lplusm;lplusm=l%m;print_err(\"mod long:\"+lplusm);\n" +
"number n; n=10.2;print_err(n);\n" +
"number m1; m1=2;print_err(m1);\n" +
"number nplusm1; nplusm1=n%m1;print_err(\"mod number:\"+nplusm1);\n" +
"number m1plusj;m1plusj=n%i;print_err(\"number mod int:\"+m1plusj);\n"+
"decimal d; d=10.1;print_err(d);\n" +
"decimal(10,4) d1; d1=10;print_err(d1);\n" +
"decimal dplusd1; dplusd1=d%d1;print_err(\"mod decimal:\"+dplusd1);\n" +
"decimal(10,4) dplusj;dplusj=d1%j;print_err(\"decimal mod int:\"+dplusj);\n"+
"decimal dplusn;dplusn=d%m1;print_err(\"decimal mod number:\"+dplusn);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(3,((CloverInteger)result[2]).getInt());
assertEquals(((long)Integer.MAX_VALUE+10)%2,((CloverLong)result[5]).getLong());
assertEquals(new CloverDouble(10.2%2),(CloverDouble)result[8]);
assertEquals(new CloverDouble(10.2%10),(CloverDouble)result[9]);
assertEquals(DecimalFactory.getDecimal(0.1),(Decimal)result[12]);
assertEquals(DecimalFactory.getDecimal(10),(Decimal)result[13]);
assertEquals(DecimalFactory.getDecimal(0.1),(Decimal)result[14]);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_increment_decrement(){
System.out.println("\nincrement-decrement test:");
String expStr = "int i; i=10;print_err(++i);\n" +
"--i;" +
"print_err(--i);\n"+
"long j;j="+(Long.MAX_VALUE-10)+";print_err(++j);\n" +
"print_err(--j);\n"+
"decimal d;d=2;++d;\n" +
"print_err(--d);\n;" +
"number n;n=3.5;print_err(++n);\n" +
"--n;\n" +
"{print_err(++n);}\n" +
"print_err(++n);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
Object[] result = executor.stack.globalVarSlot;
assertEquals(9,((CloverInteger)result[0]).getInt());
assertEquals(new CloverLong(Long.MAX_VALUE-10),((CloverLong)result[1]));
assertEquals(DecimalFactory.getDecimal(2),(Decimal)result[2]);
assertEquals(new CloverDouble(5.5),(CloverDouble)result[3]);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_equal(){
System.out.println("\nequal test:");
String expStr = "int i; i=10;print_err(\"i=\"+i);\n" +
"int j;j=9;print_err(\"j=\"+j);\n" +
"boolean eq1; eq1=(i==j+1);print_err(\"eq1=\"+eq1);\n" +
"boolean eq1;eq1=(i.eq.(j+1));print_err(\"eq1=\"+eq1);\n" +
"long l;l=10;print_err(\"l=\"+l);\n" +
"boolean eq2;eq2=(l==j);print_err(\"eq2=\"+eq2);\n" +
"eq2=(l.eq.i);print_err(\"eq2=\");print_err(eq2);\n" +
"decimal d;d=10;print_err(\"d=\"+d);\n" +
"boolean eq3;eq3=d==i;print_err(\"eq3=\"+eq3);\n" +
"number n;n=10;print_err(\"n=\"+n);\n" +
"boolean eq4;eq4=n.eq.l;print_err(\"eq4=\"+eq4);\n" +
"boolean eq5;eq5=n==d;print_err(\"eq5=\"+eq5);\n" +
"string s;s='hello';print_err(\"s=\"+s);\n" +
"string s1;s1=\"hello \";print_err(\"s1=\"+s1);\n" +
"boolean eq6;eq6=s.eq.s1;print_err(\"eq6=\"+eq6);\n" +
"boolean eq7;eq7=s==trim(s1);print_err(\"eq7=\"+eq7);\n" +
"date mydate;mydate=2006-01-01;print_err(\"mydate=\"+mydate)\n" +
"date anothermydate;print_err(\"anothermydate=\"+anothermydate);\n" +
"boolean eq8;eq8=mydate.eq.anothermydate;print_err(\"eq8=\"+eq8);\n" +
"anothermydate=2006-1-1 0:0:0;print_err(\"anothermydate=\"+anothermydate);\n" +
"boolean eq9;eq9=mydate==anothermydate;print_err(\"eq9=\"+eq9);\n" +
"boolean eq10;eq10=eq9.eq.eq8;print_err(\"eq10=\"+eq10);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(false,((Boolean)result[2]).booleanValue());
assertEquals(true,((Boolean)result[4]).booleanValue());
assertEquals(true,((Boolean)result[6]).booleanValue());
assertEquals(true,((Boolean)result[8]).booleanValue());
assertEquals(true,((Boolean)result[9]).booleanValue());
assertEquals(false,((Boolean)result[12]).booleanValue());
assertEquals(true,((Boolean)result[13]).booleanValue());
assertEquals(false,((Boolean)result[16]).booleanValue());
assertEquals(true,((Boolean)result[17]).booleanValue());
assertEquals(false,((Boolean)result[18]).booleanValue());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_non_equal(){
System.out.println("\nNon equal test:");
String expStr = "int i; i=10;print_err(\"i=\"+i);\n" +
"int j;j=9;print_err(\"j=\"+j);\n" +
"boolean eq1; eq1=(i!=j);print_err(\"eq1=\");print_err(eq1);\n" +
"long l;l=10;print_err(\"l=\"+l);\n" +
"boolean eq2;eq2=(l<>j);print_err(\"eq2=\");print_err(eq2);\n" +
"decimal d;d=10;print_err(\"d=\"+d);\n" +
"boolean eq3;eq3=d.ne.i;print_err(\"eq3=\");print_err(eq3);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(true,((Boolean)result[2]).booleanValue());
assertEquals(true,((Boolean)result[4]).booleanValue());
assertEquals(false,((Boolean)result[6]).booleanValue());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_greater_less(){
System.out.println("\nGreater and less test:");
String expStr = "int i; i=10;print_err(\"i=\"+i);\n" +
"int j;j=9;print_err(\"j=\"+j);\n" +
"boolean eq1; eq1=(i>j);print_err(\"eq1=\"+eq1);\n" +
"long l;l=10;print_err(\"l=\"+l);\n" +
"boolean eq2;eq2=(l>=j);print_err(\"eq2=\"+eq2);\n" +
"decimal d;d=10;print_err(\"d=\"+d);\n" +
"boolean eq3;eq3=d=>i;print_err(\"eq3=\"+eq3);\n" +
"number n;n=10;print_err(\"n=\"+n);\n" +
"boolean eq4;eq4=n.gt.l;print_err(\"eq4=\"+eq4);\n" +
"boolean eq5;eq5=n.ge.d;print_err(\"eq5=\"+eq5);\n" +
"string s;s='hello';print_err(\"s=\"+s);\n" +
"string s1;s1=\"hello\";print_err(\"s1=\"+s1);\n" +
"boolean eq6;eq6=s<s1;print_err(\"eq6=\"+eq6);\n" +
"date mydate;mydate=2006-01-01;print_err(\"mydate=\"+mydate)\n" +
"date anothermydate;print_err(\"anothermydate=\"+anothermydate);\n" +
"boolean eq7;eq7=mydate.lt.anothermydate;print_err(\"eq7=\"+eq7);\n" +
"anothermydate=2006-1-1 0:0:0;print_err(\"anothermydate=\"+anothermydate);\n" +
"boolean eq8;eq8=mydate<=anothermydate;print_err(\"eq8=\"+eq8);\n" ;
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals("eq1",true,((Boolean)result[2]).booleanValue());
assertEquals("eq2",true,((Boolean)result[4]).booleanValue());
assertEquals("eq3",true,((Boolean)result[6]).booleanValue());
assertEquals("eq4",false,((Boolean)result[8]).booleanValue());
assertEquals("eq5",true,((Boolean)result[9]).booleanValue());
assertEquals("eq6",false,((Boolean)result[12]).booleanValue());
assertEquals("eq7",true,((Boolean)result[15]).booleanValue());
assertEquals("eq8",true,((Boolean)result[16]).booleanValue());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_regex(){
System.out.println("\nRegex test:");
String expStr = "string s;s='Hej';print_err(s);\n" +
"boolean eq2;eq2=(s~=\"[A-Za-z]{3}\");\n" +
"print_err(\"eq2=\"+eq2);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
Object[] result = executor.stack.globalVarSlot;
assertEquals(true,((Boolean)result[1]).booleanValue());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_1_expression() {
String expStr="$Age>=135 or 200>$Age and not $Age<=0 and 1==999999999999999 or $Name==\"HELLO\"";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStartExpression parseTree = parser.StartExpression();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(true, ((Boolean)executor.getResult()).booleanValue() );
parseTree.dump("");
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_2_expression() {
String expStr="datediff(nvl($Born,2005-2-1),2005-1-1,month)";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStartExpression parseTree = parser.StartExpression();
System.out.println("Initializing parse tree..");
parseTree.init();
parseTree.dump("");
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(1,((CloverInteger)executor.getResult()).intValue());
parseTree.dump("");
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_3_expression() {
String expStr="not (trim($Name) .ne. \"HELLO\") || replace($Name,\".\" ,\"a\")=='aaaaaaa'";
print_code(expStr);
try {
System.out.println("in Test3expression");
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStartExpression parseTree = parser.StartExpression();
parseTree.dump("ccc");
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.err.println(it.next());
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
assertEquals(true,((Boolean)executor.getResult()).booleanValue());
parseTree.dump("");
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_if(){
System.out.println("\nIf statement test:");
String expStr = "int i; i=10;print_err(\"i=\"+i);\n" +
"int j;j=9;print_err(\"j=\"+j);\n" +
"long l;" +
"if (i>j) l=1; else l=0;\n" +
"print_err(l);\n" +
"decimal d;" +
"if (i.gt.j and l.eq.1) {d=0;print_err('d rovne 0');}\n" +
"else d=0.1;\n" +
"number n;\n" +
"if (d==0.1) n=0;\n" +
"if (d==0.1 || l<=1) n=0;\n" +
"else {n=-1;print_err('n rovne -1')}\n" +
"date date1; date1=2006-01-01;print_err(date1);\n" +
"date date2; date2=2006-02-01;print_err(date2);\n" +
"boolean result;result=false;\n" +
"boolean compareDates;compareDates=date1<=date2;print_err(compareDates);\n" +
"if (date11<=date2) \n" +
"{ print_err('before if (i<jj)');\n" +
" if (i<j) print_err('date1<today and i<j') else print_err('date1<date2 only')\n" +
" result=true;}\n" +
"result=false;" +
"if (i<j) result=true;\n" +
"else if (not result) result=true;\n" +
"else print_err('last else');\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
Object[] result = executor.stack.globalVarSlot;
assertEquals(1,((CloverLong)result[2]).getLong());
assertEquals(DecimalFactory.getDecimal(0),(Decimal)result[3]);
assertEquals(new CloverDouble(0),(CloverDouble)result[4]);
assertEquals(true,((Boolean)result[7]).booleanValue());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_switch(){
System.out.println("\nSwitch test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"int n;n=datediff(born,1900-01-01,month)%12;print_err(n);\n" +
"string mont;\n" +
"decimal april;april=4;\n" +
"switch (n) {\n" +
" case 0.0:mont='january';\n" +
" case 1.0:mont='february';\n" +
" case 2.0:mont='march';\n" +
" case 3:mont='april';\n" +
" case april:mont='may';\n" +
" case 5.0:mont='june';\n" +
" case 6.0:mont='july';\n" +
" case 7.0:mont='august';\n" +
" case 3:print_err('a kuku')\n" +
" case 8.0:mont='september';\n" +
" case 9.0:mont='october';\n" +
" case 10.0:mont='november';\n" +
" case 11.0:mont='december';\n" +
" default: mont='unknown';};\n"+
"print_err('month:'+mont);\n" +
"boolean ok;ok=(n.ge.0)and(n.lt.12);\n" +
"switch (ok) {\n" +
" case true:print_err('OK')\n" +
" case false:print_err('WRONG')};\n" +
"switch (born) {\n" +
" case 2006-01-01:{mont='January';print_err('january);}\n" +
" case 1973-04-23:{mont='April';print_err('april');}\n" +
" default:print_err('other')};\n"+
"switch (born<1996-08-01) {\n" +
" case true:{print_err('older then ten');}\n" +
" default:print_err('younger then ten')};\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(3,((CloverInteger)result[1]).getInt());
assertEquals("April",((StringBuffer)result[2]).toString());
assertEquals(true,((Boolean)result[4]).booleanValue());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_while(){
System.out.println("\nWhile test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"while (born<now) {\n" +
" born=dateadd(born,1,year);\n " +
" while (yer<5) yer=yer+1;\n" +
" yer=yer+1;}\n" +
"print_err('years:'+yer);\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(39,((CloverInteger)result[2]).getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_do_while(){
System.out.println("\nDo-while test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"do {\n" +
" born=dateadd(born,1,year);\n " +
" print_err('years:'+yer);\n" +
" print_err(born);\n" +
" do yer=yer+1; while (yer<5);\n" +
" print_err('years:'+yer);\n" +
" print_err(born);\n" +
" yer=yer+1;}\n" +
"while (born<now)\n" +
"print_err('years on the end:'+yer);\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(72,((CloverInteger)result[2]).getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_for(){
System.out.println("\nFor test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"for (born;born<now;born=dateadd(born,1,year)) yer=yer+1;\n" +
"print_err('years on the end:'+yer);\n" +
"boolean b;\n" +
"for (born;!b;++yer) \n" +
" if (yer==100) b=true;\n" +
"print_err(born);\n" +
"print_err('years on the end:'+yer);\n" +
"print_err('norn:'+born);\n"+
"int i;\n" +
"for (i=0;i.le.10;++i) ;\n" +
"print_err('on the end i='+i);\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
int iVarSlot=parser.getGlobalVariableSlot("i");
int yerVarSlot=parser.getGlobalVariableSlot("yer");
Object[] result = executor.stack.globalVarSlot;
assertEquals(101,((CloverInteger)result[yerVarSlot]).getInt());
assertEquals(11,((CloverInteger)result[iVarSlot]).getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_break(){
System.out.println("\nBreak test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"int i;" +
"while (born<now) {\n" +
" ++yer;\n" +
" born=dateadd(born,1,year);\n" +
" for (i=0;i<20;++i) \n" +
" if (i==10) break\n" +
"}\n" +
"print_err('years on the end:'+yer);\n"+
"print_err('i after while:'+i);\n" ;
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(34,((CloverInteger)result[2]).getInt());
assertEquals(10,((CloverInteger)result[3]).getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_continue(){
System.out.println("\nContinue test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"date now;now=today();\n" +
"int yer;yer=0;\n" +
"int i;\n" +
"for (i=0;i<10;i=i+1) {\n" +
" print_err('i='+i);\n" +
" if (i>5) continue\n" +
" print_err('After if')" +
"}\n" +
"print_err('new loop starting');\n" +
"while (born<now) {\n" +
" print_err('i='+i);i=0;\n" +
" yer=yer+1;\n" +
" born=dateadd(born,1,year);\n" +
" if (yer>30) continue\n" +
" for (i=0;i<20;++i) \n" +
" if (i==10) break\n" +
"}\n" +
"print_err('years on the end:'+yer);\n"+
"print_err('i after while:'+i);\n" ;
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals(34,((CloverInteger)result[2]).getInt());
assertEquals(0,((CloverInteger)result[3]).getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_return(){
System.out.println("\nReturn test:");
String expStr = "date born; born=$Born;print_err(born);\n" +
"function year_before(now) {\n" +
" return dateadd(now,-1,year)" +
"}\n" +
"function age(born){\n" +
" date now;int yer;\n" +
" now=today();yer=0;\n" +
" for (born;born<now;born=dateadd(born,1,year)) ++yer;\n" +
" if (yer>0) return yer else return -1" +
"}\n" +
"print_err('years born'+age(born));\n" +
"print_err(\"years on the end:\"+age(born));\n"+
"print_err(\"year before:\"+year_before(born));\n" +
" while (true) {print_err('pred return');" +
"return;" +
"print_err('po return')}" +
"print_err('za blokem');\n";
GregorianCalendar born = new GregorianCalendar(1973,03,23);
record.getField("Born").setValue(born.getTime());
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
parseTree.dump("");
for(Iterator iter=parser.getParseExceptions().iterator();iter.hasNext();){
System.err.println(iter.next());
}
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_buildInFunctions(){
System.out.println("\nBuild-in functions test:");
String expStr = "string s;s='hello world';\n" +
"number lenght;lenght=5.5;\n" +
"string subs;subs=substring(s,1,lenght);\n" +
"print_err('original string:'+s );\n" +
"print_err('substring:'+subs );\n" +
"string upper;upper=uppercase(subs);\n" +
"print_err('to upper case:'+upper );\n"+
"string lower;lower=lowercase(subs+'hI ');\n" +
"print_err('to lower case:'+lower );\n"+
"string t;t=trim('\t im '+lower);\n" +
"print_err('after trim:'+t );\n" +
"breakpoint();\n"+
"decimal l;l=length(upper);\n" +
"print_err('length of '+upper+':'+l );\n"+
"string c;c=concat(lower,upper,2,',today is ',today());\n" +
"print_err('concatenation \"'+lower+'\"+\"'+upper+'\"+2+\",today is \"+today():'+c );\n"+
"date datum; date born;born=nvl($Born,today()-400);\n" +
"datum=dateadd(born,100,millisec);\n" +
"print_err(datum );\n"+
"long ddiff;date otherdate;otherdate=today();\n" +
"ddiff=datediff(born,otherdate,year);\n" +
"print_err('date diffrence:'+ddiff );\n" +
"boolean isn;isn=isnull(ddiff);\n" +
"print_err(isn );\n" +
"number s1;s1=nvl(l+1,1);\n" +
"print_err(s1 );\n" +
"string rep;rep=replace(c,'[lL]','t');\n" +
"print_err(rep );\n" +
"decimal stn;stn=str2num('2.5e-1');\n" +
"print_err(stn );\n" +
"string nts;nts=num2str(1);\n" +
"print_err(nts );\n" +
"date newdate;newdate=2001-12-20 16:30:04;\n" +
"decimal dtn;dtn=date2num(newdate,month);\n" +
"print_err(dtn );\n" +
"int ii;ii=iif(newdate<2000-01-01,20,21);\n" +
"print_err('ii:'+ii);\n" +
"print_stack();\n" +
"date ndate;ndate=2002-12-24;\n" +
"string dts;dts=date2str(ndate,'yy.MM.dd');\n" +
"print_err('date to string:'+dts);\n" +
"print_err(str2date(dts,'yy.MM.dd'));\n" ;
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals("subs","ello ",((StringBuffer)result[2]).toString());
assertEquals("upper","ELLO ",((StringBuffer)result[3]).toString());
assertEquals("lower","ello hi ",((StringBuffer)result[4]).toString());
assertEquals("t(=trim)","im ello hi",((StringBuffer)result[5]).toString());
assertEquals("l(=length)",5,((Decimal)result[6]).getInt());
assertEquals("c(=concat)","ello hi ELLO 2,today is "+new Date(),((StringBuffer)result[7]).toString());
// assertEquals("datum",record.getField("Born").getValue(),(Date)result[8]);
assertEquals("ddiff",-1,((CloverLong)result[10]).getLong());
assertEquals("isn",false,((Boolean)result[12]).booleanValue());
assertEquals("s1",new CloverDouble(6),(CloverDouble)result[13]);
assertEquals("rep","etto hi EttO 2,today is "+new Date(),((StringBuffer)result[14]).toString());
assertEquals("stn",0.25,((Decimal)result[15]).getDouble());
assertEquals("nts","1",((StringBuffer)result[16]).toString());
assertEquals("dtn",11.0,((Decimal)result[18]).getDouble());
assertEquals("ii",21,((CloverInteger)result[19]).getInt());
assertEquals("dts","02.12.24",((StringBuffer)result[21]).toString());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_math_functions(){
System.out.println("\nMath functions test:");
String expStr = "number original;original=pi();\n" +
"print_err('pi='+original);\n" +
"number result;result=sqrt(original);\n" +
"print_err('sqrt='+result);\n" +
"int i;i=9;\n" +
"number p9;p9=sqrt(i);\n" +
"number ln;ln=log(p9);\n" +
"print_err('sqrt(-1)='+sqrt(-1));\n" +
"decimal d;d=0;"+
"print_err('log(0)='+log(d));\n" +
"number l10;l10=log10(p9);\n" +
"number ex;ex =exp(l10);\n" +
"number po;po=pow(p9,1.2);\n" +
"number p;p=pow(-10,-0.3);\n" +
"print_err('power(-10,-0.3)='+p);\n" +
"int r;r=round(-po);\n" +
"print_err('round of '+(-po)+'='+r);"+
"int t;t=trunc(-po);\n" +
"print_err('truncation of '+(-po)+'='+t);\n" +
"date date1;date1=2004-01-02 17:13:20;\n" +
"/*date tdate1; tdate1=trunc(date1);\n*/" +
"print_err('truncation of '+date1+'='+tdate1)\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
if (parser.getParseExceptions().size()>0){
//report error
for(Iterator it=parser.getParseExceptions().iterator();it.hasNext();){
System.out.println(it.next());
}
throw new RuntimeException("Parse exception");
}
Object[] result = executor.stack.globalVarSlot;
assertEquals("pi",new CloverDouble(Math.PI),(CloverDouble)result[0]);
assertEquals("sqrt",new CloverDouble(Math.sqrt(Math.PI)),(CloverDouble)result[1]);
assertEquals("sqrt(9)",new CloverDouble(3),(CloverDouble)result[3]);
assertEquals("ln",new CloverDouble(Math.log(3)),(CloverDouble)result[4]);
assertEquals("log10",new CloverDouble(Math.log10(3)),(CloverDouble)result[6]);
assertEquals("exp",new CloverDouble(Math.exp(Math.log10(3))),(CloverDouble)result[7]);
assertEquals("power",new CloverDouble(Math.pow(3,1.2)),(CloverDouble)result[8]);
assertEquals("power--",new CloverDouble(Math.pow(-10,-0.3)),(CloverDouble)result[9]);
assertEquals("round",new CloverInteger(-4),(CloverInteger)result[10]);
assertEquals("truncation",new CloverInteger(-3),(CloverInteger)result[11]);
assertEquals("date truncation",new GregorianCalendar(2004,00,02).getTime(),(Date)result[13]);
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_global_parameters(){
System.out.println("\nGlobal parameters test:");
String expStr = "string original;original=${G1};\n" +
"int num; num=str2num(original); \n"+
"print_err(original);\n"+
"print_err(num);\n";
print_code(expStr);
try {
TransformLangParser parser = new TransformLangParser(record.getMetadata(),
new ByteArrayInputStream(expStr.getBytes()));
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
Properties globalParameters = new Properties();
globalParameters.setProperty("G1","10");
executor.setGlobalParameters(globalParameters);
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals("num",10,((Numeric)result[1]).getInt());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void test_mapping(){
System.out.println("\nMapping test:");
String expStr = "function test(){\n" +
" string result;\n" +
" print_err('function');\n" +
" result='result';\n" +
" return result;\n" +
" $Name:=result;\n" +
" }\n" +
"test();\n" +
"print_err('out of function');\n" +
"$City:=test();\n";
print_code(expStr);
try {
DataRecordMetadata[] recordMetadata=new DataRecordMetadata[] {metadata};
TransformLangParser parser = new TransformLangParser(recordMetadata,
recordMetadata,new ByteArrayInputStream(expStr.getBytes()),"UTF-8");
CLVFStart parseTree = parser.Start();
System.out.println("Initializing parse tree..");
parseTree.init();
System.out.println("Interpreting parse tree..");
TransformLangExecutor executor=new TransformLangExecutor();
executor.setInputRecords(new DataRecord[] {record});
executor.setOutputRecords(new DataRecord[]{out});
executor.visit(parseTree,null);
System.out.println("Finished interpreting.");
parseTree.dump("");
Object[] result = executor.stack.globalVarSlot;
assertEquals("result",out.getField("City").getValue().toString());
// assertEquals("result",out.getField("Name").getValue().toString());
} catch (ParseException e) {
System.err.println(e.getMessage());
e.printStackTrace();
throw new RuntimeException("Parse exception",e);
}
}
public void print_code(String text){
String[] lines=text.split("\n");
for(int i=0;i<lines.length;i++){
System.out.println((i+1)+"\t:"+lines[i]);
}
}
}
|
package org.jetel.sequence;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import org.jetel.data.sequence.Sequence;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.ConfigurationStatus.Priority;
import org.jetel.exception.ConfigurationStatus.Severity;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.GraphElement;
import org.jetel.graph.TransformationGraph;
import org.jetel.util.file.FileUtils;
import org.jetel.util.primitive.TypedProperties;
import org.jetel.util.property.ComponentXMLAttributes;
import org.w3c.dom.Element;
public class PrimitiveSequence extends GraphElement implements Sequence {
public final static String SEQUENCE_TYPE = "PRIMITIVE_SEQUENCE";
private static final String XML_NAME_ATTRIBUTE = "name";
private static final String XML_START_ATTRIBUTE = "start";
private static final String XML_STEP_ATTRIBUTE = "step";
private static final String XML_SEQCONFIG_ATTRIBUTE = "seqConfig";
private static Exception initFromConfigFileException;
private long value = 0;
private long start = 0;
private long step = 1;
boolean alreadyIncremented = false;
public PrimitiveSequence(String id, TransformationGraph graph, String name) {
super(id, graph, name);
}
/**
* @see org.jetel.graph.GraphElement#checkConfig()
*/
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
if (initFromConfigFileException != null) {
status.add("Failed to initialize sequence from definition file; " + initFromConfigFileException, Severity.ERROR, this, Priority.NORMAL);
return status;
}
//TODO
return status;
}
/**
* @see org.jetel.graph.GraphElement#init()
*/
@Override
synchronized public void init() throws ComponentNotReadyException {
if(isInitialized()) return;
super.init();
alreadyIncremented = false;
}
@Override
public synchronized void preExecute() throws ComponentNotReadyException {
super.preExecute();
if (firstRun()) {//a phase-dependent part of initialization
//all necessary elements have been initialized in init()
} else {
logger.debug("Primitive sequence '" + getId() + "' reset.");
resetValue();
}
}
@Override
public synchronized void reset() throws ComponentNotReadyException {
super.reset();
}
/**
* @see org.jetel.graph.GraphElement#free()
*/
@Override
synchronized public void free() {
if(!isInitialized()) return;
super.free();
//no op
}
/**
* @see org.jetel.data.sequence.Sequence#currentValueInt()
*/
@Override
public int currentValueInt() {
return (int) currentValueLong();
}
/**
* @see org.jetel.data.sequence.Sequence#nextValueInt()
*/
@Override
public int nextValueInt() {
return (int) nextValueLong();
}
/**
* @see org.jetel.data.sequence.Sequence#currentValueLong()
*/
@Override
public synchronized long currentValueLong() {
return alreadyIncremented ? value - step : value;
}
/**
* @see org.jetel.data.sequence.Sequence#nextValueLong()
*/
@Override
public synchronized long nextValueLong() {
long tmpVal=value;
value += step;
alreadyIncremented = true;
return tmpVal;
}
/**
* @see org.jetel.data.sequence.Sequence#currentValueString()
*/
@Override
public String currentValueString() {
return Long.toString(currentValueLong());
}
/**
* @see org.jetel.data.sequence.Sequence#nextValueString()
*/
@Override
public String nextValueString() {
return Long.toString(nextValueLong());
}
/**
* @see org.jetel.data.sequence.Sequence#resetValue()
*/
@Override
public synchronized void resetValue() {
alreadyIncremented = false;
value = start;
}
/**
* @see org.jetel.data.sequence.Sequence#isPersistent()
*/
@Override
public boolean isPersistent() {
return false;
}
public long getStart() {
return start;
}
/**
* Sets start value and resets this sequencer.
* @param start
*/
public synchronized void setStart(long start) {
this.start = start;
resetValue();
}
public long getStep() {
return step;
}
/**
* Sets step value and resets this sequencer.
* @param step
*/
public synchronized void setStep(long step) {
this.step = step;
}
static public PrimitiveSequence fromXML(TransformationGraph graph, Element nodeXML) throws XMLConfigurationException {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph);
try {
String configAttr = xattribs.getString(XML_SEQCONFIG_ATTRIBUTE, "");
if (configAttr.isEmpty()) {
PrimitiveSequence seq = new PrimitiveSequence(
xattribs.getString(XML_ID_ATTRIBUTE),
graph,
xattribs.getString(XML_NAME_ATTRIBUTE, ""));
if(xattribs.exists(XML_START_ATTRIBUTE)) {
seq.setStart(xattribs.getLong(XML_START_ATTRIBUTE));
}
if(xattribs.exists(XML_STEP_ATTRIBUTE)) {
seq.setStep(xattribs.getLong(XML_STEP_ATTRIBUTE));
}
return seq;
}
else {
PrimitiveSequence seq = new PrimitiveSequence(
xattribs.getString(XML_ID_ATTRIBUTE),
graph,
xattribs.getString(XML_NAME_ATTRIBUTE, ""));
try {
URL projectURL = graph != null ? graph.getRuntimeContext().getContextURL() : null;
InputStream stream = FileUtils.getFileURL(projectURL, configAttr).openStream();
Properties tempProperties = new Properties();
tempProperties.load(stream);
TypedProperties typedProperties = new TypedProperties(tempProperties, graph);
seq.setName(typedProperties.getStringProperty(XML_NAME_ATTRIBUTE));
seq.start = typedProperties.getLongProperty(XML_START_ATTRIBUTE, 0);
seq.step = typedProperties.getLongProperty(XML_STEP_ATTRIBUTE, 0);
stream.close();
} catch (Exception ex) {
initFromConfigFileException = ex;
}
return seq;
}
} catch(Exception ex) {
throw new XMLConfigurationException(SEQUENCE_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(), ex);
}
}
@Override
public boolean isShared() {
return false;
}
}
|
package gluewine.rest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import gluewine.entities.User;
import org.gluewine.core.Glue;
import org.gluewine.persistence_jpa.Filter;
import org.gluewine.persistence_jpa.FilterLine;
import org.gluewine.persistence_jpa.FilterOperator;
import org.gluewine.persistence_jpa_hibernate.HibernateSessionProvider;
import org.gluewine.persistence.Transactional;
import org.gluewine.jetty.GluewineServlet;
public class login extends GluewineServlet {
@Override
public String getContextPath() {
return "login";
}
@Glue
private HibernateSessionProvider provider;
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
final long now = new Date().getTime();
resp.setDateHeader("Date", now);
resp.setDateHeader("Expires", now);
resp.setContentType("text/html");
StringBuilder b = new StringBuilder("<HTML><HEAD>");
b.append("<TITLE>Login</TITLE>");
b.append("</HEAD>");
b.append("<H1>Login</H1>");
b.append("<form action='login' method='POST'>");
b.append("<label for='username'>Username:</label>");
b.append("<input type='text' name='username'/>");
b.append("</br><label for='password'>Password:</label>");
b.append("<input type='password' name='password'/>");
b.append("</br><input type='submit' value='submit' name='submit'/>");
b.append("</form>");
b.append("</HEAD>");
resp.setContentLength(b.length());
try
{
resp.getWriter().println(b.toString());
}
catch (IOException e)
{
e.printStackTrace();
try
{
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server Error");
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
//resp.setContentType("text/html");
//resp.getWriter().write("<html>"
//+ "<body>"
//+ "<h1>login</h1>"
//+ "<form action='login' method='POST'>"
//+ "<label for='username'>Username:</label>"
//+ "<input type='text' name='username'/>"
//+ "</br><label for='password'>Password:</label>"
//+ "<input type='password' name='password'/>"
//+ "</br><input type='submit' value='submit' name='submit'/>"
//+ "</form>"
//+ "</body>"
//+ "</html>");
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
String username = req.getParameter("username");
String password = req.getParameter("password");
List<User> users = provider.getSession().getAll(User.class);
for(User user : users)
{
if( user.getUsername() == username)
{
if (user.getPassword() == password)
{
resp.setContentType("text/html");
StringBuilder b = new StringBuilder("<HTML><HEAD>");
b.append("<TITLE>Gluewine framework</TITLE>");
b.append("</HEAD>");
b.append("Welcome " + username);
b.append("</HEAD>");
resp.setContentLength(b.length());
try
{
resp.getWriter().println(b.toString());
}
catch (IOException e)
{
e.printStackTrace();
try
{
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server Error");
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
} else resp.sendError(HttpServletResponse.SC_CONFLICT, "wrong username of password");
}
}
}
|
package org.safehaus.subutai.core.peer.impl.entity;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.safehaus.subutai.common.command.CommandException;
import org.safehaus.subutai.common.command.CommandResult;
import org.safehaus.subutai.common.command.CommandUtil;
import org.safehaus.subutai.common.command.RequestBuilder;
import org.safehaus.subutai.common.host.HostInfo;
import org.safehaus.subutai.common.metric.ResourceHostMetric;
import org.safehaus.subutai.common.peer.ContainerHost;
import org.safehaus.subutai.common.protocol.Template;
import org.safehaus.subutai.common.util.CollectionUtil;
import org.safehaus.subutai.core.hostregistry.api.HostRegistry;
import org.safehaus.subutai.core.metric.api.Monitor;
import org.safehaus.subutai.core.metric.api.MonitorException;
import org.safehaus.subutai.core.peer.api.ContainerState;
import org.safehaus.subutai.core.peer.api.HostNotFoundException;
import org.safehaus.subutai.core.peer.api.ResourceHost;
import org.safehaus.subutai.core.peer.api.ResourceHostException;
import org.safehaus.subutai.core.peer.impl.container.CreateContainerTask;
import org.safehaus.subutai.core.peer.impl.container.DestroyContainerTask;
import org.safehaus.subutai.core.registry.api.TemplateRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* Resource host implementation.
*/
@Entity
@Table( name = "resource_host" )
@Access( AccessType.FIELD )
public class ResourceHostEntity extends AbstractSubutaiHost implements ResourceHost
{
private static final int CONNECT_TIMEOUT = 300;
protected static final Logger LOG = LoggerFactory.getLogger( ResourceHostEntity.class );
private static final Pattern LXC_STATE_PATTERN = Pattern.compile( "State:(\\s*)(.*)" );
@OneToMany( mappedBy = "parent", fetch = FetchType.EAGER,
targetEntity = ContainerHostEntity.class )
Set<ContainerHost> containersHosts = Sets.newHashSet();
@Transient
private ExecutorService singleThreadExecutorService = Executors.newSingleThreadExecutor();
@Transient
private Monitor monitor;
@Transient
CommandUtil commandUtil = new CommandUtil();
@Transient
TemplateRegistry registry;
@Transient
HostRegistry hostRegistry;
public ResourceHostEntity()
{
}
public ResourceHostEntity( final String peerId, final HostInfo resourceHostInfo )
{
super( peerId, resourceHostInfo );
}
public <T> Future<T> queueSequentialTask( Callable<T> callable )
{
return singleThreadExecutorService.submit( callable );
}
@Override
public ContainerState getContainerHostState( final ContainerHost containerHost ) throws ResourceHostException
{
Preconditions.checkNotNull( containerHost, "Container host is null" );
try
{
getContainerHostById( containerHost.getId() );
}
catch ( HostNotFoundException e )
{
throw new ResourceHostException(
String.format( "Container with name %s does not exist", containerHost.getHostname() ) );
}
RequestBuilder requestBuilder =
new RequestBuilder( String.format( "/usr/bin/lxc-info -n %s", containerHost.getHostname() ) )
.withTimeout( 30 );
CommandResult result;
try
{
result = commandUtil.execute( requestBuilder, this );
}
catch ( CommandException e )
{
throw new ResourceHostException( "Error fetching container state", e );
}
String stdOut = result.getStdOut();
Matcher m = LXC_STATE_PATTERN.matcher( stdOut );
if ( m.find() )
{
return ContainerState.valueOf( m.group( 2 ) );
}
else
{
return ContainerState.UNKNOWN;
}
}
@Override
public ResourceHostMetric getHostMetric() throws ResourceHostException
{
try
{
return monitor.getResourceHostMetric( this );
}
catch ( MonitorException e )
{
throw new ResourceHostException( "Error obtaining host metric", e );
}
}
public Set<ContainerHost> getContainerHosts()
{
synchronized ( containersHosts )
{
return Sets.newConcurrentHashSet( containersHosts );
}
}
public void startContainerHost( final ContainerHost containerHost ) throws ResourceHostException
{
Preconditions.checkNotNull( containerHost, "Container host is null" );
try
{
getContainerHostById( containerHost.getId() );
}
catch ( HostNotFoundException e )
{
throw new ResourceHostException(
String.format( "Container with name %s does not exist", containerHost.getHostname() ) );
}
RequestBuilder requestBuilder =
new RequestBuilder( String.format( "/usr/bin/lxc-start -n %s -d", containerHost.getHostname() ) )
.withTimeout( 1 ).daemon();
try
{
commandUtil.execute( requestBuilder, this );
}
catch ( CommandException e )
{
throw new ResourceHostException( "Error on starting container", e );
}
//wait container connection
long ts = System.currentTimeMillis();
while ( System.currentTimeMillis() - ts < CONNECT_TIMEOUT * 1000 && !ContainerState.RUNNING
.equals( getContainerHostState( containerHost ) ) )
{
try
{
Thread.sleep( 100 );
}
catch ( InterruptedException e )
{
throw new ResourceHostException( e );
}
}
if ( !ContainerState.RUNNING.equals( getContainerHostState( containerHost ) ) )
{
throw new ResourceHostException(
String.format( "Error starting container %s", containerHost.getHostname() ) );
}
}
public void stopContainerHost( final ContainerHost containerHost ) throws ResourceHostException
{
Preconditions.checkNotNull( containerHost, "Container host is null" );
try
{
getContainerHostById( containerHost.getId() );
}
catch ( HostNotFoundException e )
{
throw new ResourceHostException(
String.format( "Container with name %s does not exist", containerHost.getHostname() ) );
}
RequestBuilder requestBuilder =
new RequestBuilder( String.format( "/usr/bin/lxc-stop -n %s", containerHost.getHostname() ) )
.withTimeout( 120 );
try
{
commandUtil.execute( requestBuilder, this );
}
catch ( CommandException e )
{
throw new ResourceHostException( "Error stopping container", e );
}
}
@Override
public void destroyContainerHost( final ContainerHost containerHost ) throws ResourceHostException
{
Preconditions.checkNotNull( containerHost, "Container host is null" );
try
{
getContainerHostById( containerHost.getId() );
}
catch ( HostNotFoundException e )
{
throw new ResourceHostException(
String.format( "Container with name %s does not exist", containerHost.getHostname() ) );
}
Future future = queueSequentialTask( new DestroyContainerTask( this, containerHost.getHostname() ) );
try
{
future.get();
}
catch ( ExecutionException | InterruptedException e )
{
throw new ResourceHostException( "Error destroying container", e );
}
}
@Override
public ContainerHost getContainerHostByName( final String hostname ) throws HostNotFoundException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( hostname ), "Invalid hostname" );
for ( ContainerHost containerHost : getContainerHosts() )
{
if ( containerHost.getHostname().equalsIgnoreCase( hostname ) )
{
return containerHost;
}
}
throw new HostNotFoundException( String.format( "Container host not found by hostname %s", hostname ) );
}
public void removeContainerHost( final ContainerHost containerHost )
{
Preconditions.checkNotNull( containerHost, "Container host is null" );
if ( getContainerHosts().contains( containerHost ) )
{
synchronized ( containersHosts )
{
containersHosts.remove( containerHost );
}
}
}
public ContainerHost getContainerHostById( final UUID id ) throws HostNotFoundException
{
Preconditions.checkNotNull( id, "Invalid container id" );
for ( ContainerHost containerHost : getContainerHosts() )
{
if ( containerHost.getId().equals( id ) )
{
return containerHost;
}
}
throw new HostNotFoundException( String.format( "Container host not found by id %s", id ) );
}
@Override
public ContainerHost createContainer( final String templateName, final String hostname, final int timeout )
throws ResourceHostException
{
Preconditions.checkArgument( !Strings.isNullOrEmpty( templateName ), "Invalid template name" );
Preconditions.checkArgument( !Strings.isNullOrEmpty( hostname ), "Invalid hostname" );
Preconditions.checkArgument( timeout > 0, "Invalid timeout" );
if ( registry.getTemplate( templateName ) == null )
{
throw new ResourceHostException( String.format( "Template %s is not registered", templateName ) );
}
try
{
getContainerHostByName( hostname );
throw new ResourceHostException( String.format( "Container with name %s already exists", hostname ) );
}
catch ( HostNotFoundException e )
{
//ignore
}
Future<ContainerHost> containerHostFuture =
queueSequentialTask( new CreateContainerTask( this, templateName, hostname, timeout ) );
try
{
return containerHostFuture.get();
}
catch ( ExecutionException | InterruptedException e )
{
throw new ResourceHostException( "Error creating container", e );
}
}
@Override
public void prepareTemplates( List<Template> templates ) throws ResourceHostException
{
Preconditions.checkArgument( !CollectionUtil.isCollectionEmpty( templates ), "Invalid template set" );
LOG.debug( String.format( "Preparing templates on %s...", hostname ) );
for ( Template p : templates )
{
prepareTemplate( p );
}
LOG.debug( "Template successfully prepared." );
}
@Override
public void prepareTemplate( final Template template ) throws ResourceHostException
{
Preconditions.checkNotNull( template, "Invalid template" );
if ( templateExists( template ) )
{
return;
}
importTemplate( template );
if ( templateExists( template ) )
{
return;
}
// trying add repository
updateRepository( template );
importTemplate( template );
if ( !templateExists( template ) )
{
LOG.debug( String.format( "Could not prepare template %s on %s.", template.getTemplateName(), hostname ) );
throw new ResourceHostException(
String.format( "Could not prepare template %s on %s", template.getTemplateName(), hostname ) );
}
}
@Override
public boolean templateExists( final Template template ) throws ResourceHostException
{
Preconditions.checkNotNull( template, "Invalid template" );
try
{
CommandResult commandresult = execute( new RequestBuilder( "subutai list -t" )
.withCmdArgs( Lists.newArrayList( template.getTemplateName() ) ) );
if ( commandresult.hasSucceeded() )
{
LOG.debug( String.format( "Template %s exists on %s.", template.getTemplateName(), hostname ) );
return true;
}
else
{
LOG.warn( String.format( "Template %s does not exists on %s.", template.getTemplateName(), hostname ) );
return false;
}
}
catch ( CommandException ce )
{
LOG.error( "Command exception.", ce );
throw new ResourceHostException( "General command exception on checking container existence.", ce );
}
}
@Override
public void importTemplate( Template template ) throws ResourceHostException
{
Preconditions.checkNotNull( template, "Invalid template" );
try
{
commandUtil.execute( new RequestBuilder( "subutai import" )
.withCmdArgs( Lists.newArrayList( template.getTemplateName() ) ), this );
}
catch ( CommandException ce )
{
LOG.error( "Template import failed", ce );
throw new ResourceHostException( "Template import failed", ce );
}
}
@Override
public void updateRepository( Template template ) throws ResourceHostException
{
Preconditions.checkNotNull( template, "Invalid template" );
if ( template.isRemote() )
{
try
{
LOG.debug( String.format( "Adding remote repository %s to %s...", template.getPeerId(), hostname ) );
CommandResult commandResult = execute( new RequestBuilder( String.format(
"echo \"deb http://gw.intra.lan:9999/%1$s trusty main\" > /etc/apt/sources.list.d/%1$s.list ",
template.getPeerId().toString() ) ) );
if ( !commandResult.hasSucceeded() )
{
LOG.warn( String.format( "Could not add repository %s to %s.", template.getPeerId(), hostname ),
commandResult );
}
LOG.debug( String.format( "Updating repository index on %s...", hostname ) );
commandResult = execute( new RequestBuilder( "apt-get update" ).withTimeout( 300 ) );
if ( !commandResult.hasSucceeded() )
{
LOG.warn( String.format( "Could not update repository %s on %s.", template.getPeerId(), hostname ),
commandResult );
}
}
catch ( CommandException ce )
{
LOG.error( "Command exception.", ce );
throw new ResourceHostException( "General command exception on updating repository.", ce );
}
}
}
public void setRegistry( final TemplateRegistry registry )
{
this.registry = registry;
}
public void setHostRegistry( final HostRegistry hostRegistry )
{
this.hostRegistry = hostRegistry;
}
public void setMonitor( final Monitor monitor )
{
this.monitor = monitor;
}
public void addContainerHost( ContainerHost host )
{
Preconditions.checkNotNull( host, "Invalid container host" );
( ( ContainerHostEntity ) host ).setParent( this );
synchronized ( containersHosts )
{
containersHosts.add( host );
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.